{"version":3,"file":"runtime-C6AOQRt7.mjs","names":["dshToPiContent","#carried","#host","#handle","#thinkingLevel","#session","#tools","#subscribers","#disposers","#activeToolNames","#liveStreamAttempt","#project","#streamingText","#state","#model","#assignTranscript","#streaming","#pendingToolCalls","#seed","#aborted","#cancelChild","#toolCallNames","#messageProjection","#turns","#queueMessage","#sessionName","#scopeTools","#restrictionDispose","#extensionFailures","#byParent","#commandRunners","#surfaces","#factoryComponents","#entrySources","#draftRequests","#liveDrafts","#completionSources","#imageToolNames","#view","#mountFactory","#llm","#models","#resolved","#refreshing","#refreshOnce","#resolveExact","AdapterBase","service","pathResolve","record"],"sources":["../src/session-events.ts","../src/pi-cli-bridge.ts","../src/dsh-content.ts","../src/session-bridge.ts","../src/subagent-bridge.ts","../src/compat/vendor/pi-open-browser.ts","../src/browser-surfaces.ts","../src/compat/vendor/pi-tool-validation.ts","../src/model-bridge.ts","../src/provider-adapter.ts","../src/tui-surfaces.ts","../src/pi-component-relay.ts","../src/pi-tui-extension-surface.ts","../src/runtime.ts"],"sourcesContent":["// Public session-log access across DSH generations. Newer hosts expose an\n// immutable snapshot instead of the old events property; never treat that\n// API change as an empty conversation.\nexport function readSessionEvents(session: unknown): readonly Record<string, unknown>[] {\n  if (typeof session !== 'object' || session === null) return []\n  const value = session as { snapshotEvents?: unknown; events?: unknown }\n  const events = typeof value.snapshotEvents === 'function'\n    ? value.snapshotEvents.call(session)\n    : typeof value.events === 'function' ? value.events.call(session) : value.events\n  if (!Array.isArray(events)) throw new Error('pi2dsh: the DSH session exposes no supported synchronous history reader')\n  return events as readonly Record<string, unknown>[]\n}\n\n/** Host-authored context is not a human turn; relay messages intentionally are. */\nexport function isPiUserMessage(data: Record<string, unknown>): boolean {\n  const source = data.source as { kind?: string; form?: string } | undefined\n  return source?.kind === undefined || source.kind === 'user' || source.form === 'relay'\n}\n\n/** The existing native descriptor convention for Pi in-memory side sessions. */\nexport function isPiEphemeralSession(session: unknown): boolean {\n  return readSessionEvents(session).some(event => {\n    const data = event.data as { provider?: string; label?: string } | undefined\n    return event.type === 'subagent/descriptor' && data?.provider === 'pi2dsh' && data.label?.startsWith('Side: ') === true\n  })\n}\n","// A local, per-exec CLI protocol adapter. The OS process carries arguments and\n// stdout only; all model/tool work runs in the existing native DSH child seam.\nimport { createServer, type Socket } from 'node:net'\nimport { randomBytes, timingSafeEqual } from 'node:crypto'\nimport { chmod, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\n\nexport interface PiPrintRequest {\n  cwd: string\n  prompt: string\n  model?: string\n  provider?: string\n  thinking?: string\n  extensions: string[]\n  noExtensions: boolean\n  noSession: boolean\n  tools?: string[]\n  systemPrompt?: string\n  appendSystemPrompt?: string\n}\n\nexport async function parsePiPrintArgs(args: string[], cwd: string): Promise<PiPrintRequest> {\n  const parsed: PiPrintRequest = { cwd, prompt: '', extensions: [], noExtensions: false, noSession: false }\n  let print = false\n  const prompts: string[] = []\n  const value = (index: number): string => {\n    const found = args[index + 1]\n    if (found === undefined) throw new Error(`pi2dsh CLI: ${args[index]} needs a value`)\n    return found\n  }\n  for (let i = 0; i < args.length; i++) {\n    const arg = args[i]!\n    if (arg === '-p' || arg === '--print') print = true\n    else if (arg === '--no-session') parsed.noSession = true\n    else if (arg === '--no-extensions') parsed.noExtensions = true\n    else if (arg === '--no-tools') parsed.tools = []\n    else if (arg === '-e' || arg === '--extension') parsed.extensions.push(await realpath(resolve(cwd, value(i++))))\n    else if (arg === '--model') parsed.model = value(i++)\n    else if (arg === '--provider') parsed.provider = value(i++)\n    else if (arg === '--thinking') parsed.thinking = value(i++)\n    else if (arg === '--tools') parsed.tools = value(i++).split(',').filter(Boolean)\n    else if (arg === '--system-prompt') parsed.systemPrompt = value(i++)\n    else if (arg === '--append-system-prompt') parsed.appendSystemPrompt = value(i++)\n    else if (arg === '--mode') {\n      if (value(i++) !== 'text') throw new Error('pi2dsh CLI: only non-interactive text output is supported')\n    } else if (arg.startsWith('-')) throw new Error(`pi2dsh CLI: unsupported option ${arg}`)\n    else if (arg.startsWith('@')) {\n      const path = resolve(cwd, arg.slice(1))\n      prompts.push(`<file name=${JSON.stringify(path)}>\\n${await readFile(path, 'utf8')}\\n</file>`)\n    } else prompts.push(arg)\n  }\n  if (!print) throw new Error('pi2dsh CLI: only pi -p/--print is supported; use the DSH surface for interactive work')\n  if (prompts.length === 0) throw new Error('pi2dsh CLI: a prompt or @file is required')\n  parsed.prompt = prompts.join('\\n\\n')\n  return parsed\n}\n\nexport async function withPiPrintTransport<T>(\n  invoke: (request: PiPrintRequest, signal: AbortSignal) => Promise<{ stdout: string; code: number }>,\n  execute: (env: Record<string, string>) => Promise<T>,\n): Promise<T> {\n  // This seat is a local POSIX process adapter, not a replacement Windows CLI.\n  if (process.platform === 'win32') return execute({})\n  const directory = await mkdtemp(join(tmpdir(), 'p2cli-'))\n  await chmod(directory, 0o700)\n  const socketPath = join(directory, 's')\n  const token = randomBytes(32).toString('hex')\n  const sockets = new Set<Socket>()\n  const work = new Set<Promise<void>>()\n  const controllers = new Set<AbortController>()\n  const server = createServer(socket => {\n    sockets.add(socket)\n    const controller = new AbortController()\n    controllers.add(controller)\n    let input = ''\n    let claimed = false\n    let finished = false\n    socket.setEncoding('utf8')\n    socket.on('error', () => controller.abort())\n    socket.on('close', () => {\n      sockets.delete(socket)\n      controllers.delete(controller)\n      if (!finished) controller.abort(new Error('Pi print subprocess disconnected'))\n    })\n    socket.on('data', chunk => {\n      if (claimed) return\n      input += chunk\n      if (input.length > 4 * 1024 * 1024) { socket.destroy(); return }\n      if (!input.includes('\\n')) return\n      claimed = true\n      const task = (async () => {\n        try {\n          const request = JSON.parse(input.slice(0, input.indexOf('\\n'))) as { token?: unknown; args?: unknown; cwd?: unknown }\n          const supplied = typeof request.token === 'string' ? Buffer.from(request.token) : Buffer.alloc(0)\n          const expected = Buffer.from(token)\n          if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) throw new Error('pi2dsh CLI: invalid execution capability')\n          if (!Array.isArray(request.args) || request.args.some(arg => typeof arg !== 'string') || typeof request.cwd !== 'string') throw new Error('pi2dsh CLI: invalid request')\n          const parsed = await parsePiPrintArgs(request.args as string[], request.cwd)\n          controller.signal.throwIfAborted()\n          const result = await invoke(parsed, controller.signal)\n          finished = true\n          socket.end(`${JSON.stringify(result)}\\n`)\n        } catch (error) {\n          finished = true\n          console.warn('[pi2dsh CLI]', error instanceof Error ? error.message : String(error))\n          socket.end(`${JSON.stringify({ code: 1, stdout: '', stderr: error instanceof Error ? error.message : String(error) })}\\n`)\n        }\n      })()\n      work.add(task)\n      void task.finally(() => work.delete(task))\n    })\n  })\n  try {\n    await new Promise<void>((resolveListen, reject) => { server.once('error', reject); server.listen(socketPath, resolveListen) })\n    await chmod(socketPath, 0o600)\n    const quote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`\n    const client = fileURLToPath(new URL('./pi-cli-client.mjs', import.meta.url))\n    await writeFile(join(directory, 'pi'), `#!/bin/sh\\nexec ${quote(process.execPath)} ${quote(client)} \"$@\"\\n`, { mode: 0o700 })\n    return await execute({ PATH: `${directory}:${process.env.PATH ?? ''}`, PI2DSH_CLI_SOCKET: socketPath, PI2DSH_CLI_TOKEN: token })\n  } finally {\n    for (const controller of controllers) controller.abort(new Error('Pi exec completed'))\n    for (const socket of sockets) socket.destroy()\n    await Promise.allSettled(work)\n    await new Promise<void>(resolveClose => server.close(() => resolveClose()))\n    await rm(directory, { recursive: true, force: true })\n  }\n}\n","import * as llm from '@deepseek-ai/dsh-llm'\n\n/** A file is text on the Pi side, using the host's own execution-world locator. */\nexport function fileContentForPi(attachment: unknown, ctx?: { get(name: string): unknown }): { type: 'text', text: string } {\n  const format = (llm as unknown as { fileHandleText?: (ref: unknown, path: string | undefined) => string }).fileHandleText\n  if (format === undefined) throw new Error('pi2dsh: this DSH host cannot project file attachments')\n  let path: string | undefined\n  try {\n    const store = ctx?.get('attachments') as { fileHostPath?(ref: unknown): string | undefined } | undefined\n    const hostPath = store?.fileHostPath?.(attachment)\n    const fs = ctx?.get('fs') as { processPathFromHostPath(path: string): string | undefined } | undefined\n    if (hostPath !== undefined) path = fs?.processPathFromHostPath(hostPath)\n  } catch {\n    // The host's formatter explicitly reports an inaccessible attachment.\n  }\n  return { type: 'text', text: format(attachment, path) }\n}\n","// Pi session semantics over a DSH durable session.\n//\n// Single authority, live projection: DSH's append-only event log is the ONLY\n// authority for conversation content. API reads project from it at call time.\n// File-only Pi consumers additionally receive a disposable Pi JSONL export:\n// it is never read back as DSH state or used as a resume authority. This disk\n// adapter is a materialized compatibility view, not native storage.\n//\n// Pi-only facts (custom entries, labels, branch summaries) remain in their\n// original per-session archive. Derived full transcripts live separately in\n// Pi's standard sessions/<cwd>/ layout so file scanners and source anchors\n// can consume them. Editing a derived transcript never edits DSH or the\n// Pi-only facts; exports are rebuilt from those authorities. Resume uses the\n// export's native identity and the official DSH resume seam, never its body.\n// A positive native deletion verdict retires an export. An unavailable\n// persistence service or a failed listing never deletes evidence.\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { isPiEphemeralSession, isPiUserMessage, readSessionEvents } from './session-events.js'\nimport { foldSurface } from '@deepseek-ai/dsh-session'\nimport { getAgentDir } from './compat/vendor/pi-config-shim.js'\nimport { fileContentForPi } from './dsh-content.js'\nimport { getDefaultSessionDir } from './compat/vendor/pi-session-manager.js'\n\n/** The durable seq behind a projected entry id (`dsh-<seq>`), when it has one. */\nfunction entrySeq(id: string): number | undefined {\n  const match = /^dsh-(\\d+)$/.exec(id)\n  return match === null ? undefined : Number(match[1])\n}\n\ntype UnknownRecord = Record<string, unknown>\n\ninterface DshSessionLike {\n  id: string\n  events?: readonly UnknownRecord[] | (() => readonly UnknownRecord[])\n  snapshotEvents?(): readonly UnknownRecord[]\n  append?(type: string, data: unknown, opts?: unknown): unknown\n  header?: UnknownRecord\n}\n\ninterface SidecarRecord {\n  kind: 'custom' | 'label' | 'name' | 'branch_summary'\n  id: string\n  timestamp: string\n  customType?: string\n  data?: unknown\n  targetId?: string\n  label?: string\n  name?: string\n  summary?: string\n  fromId?: string\n}\n\n/** One Pi-only record as the Pi session-file entry line it is stored as. */\nfunction piEntryLineOf(record: SidecarRecord): string {\n  const base = { id: record.id, parentId: null, timestamp: record.timestamp }\n  switch (record.kind) {\n    case 'custom':\n      return JSON.stringify({\n        type: 'custom', ...base, customType: record.customType,\n        ...(record.data === undefined ? {} : { data: record.data }),\n      })\n    case 'label':\n      return JSON.stringify({\n        type: 'label', ...base, targetId: record.targetId,\n        ...(record.label === undefined ? {} : { label: record.label }),\n      })\n    case 'branch_summary':\n      return JSON.stringify({ type: 'branch_summary', ...base, fromId: record.fromId, summary: record.summary })\n    case 'name':\n      return JSON.stringify({ type: 'session_info', ...base, name: record.name })\n  }\n}\n\n/**\n * Normalize one parsed session-file line back into a record. Understands the\n * Pi entry shapes this bridge writes today AND the pre-0.18 private\n * `{kind: …}` lines, so archives written by older engines keep loading. A Pi\n * header line and anything unrecognized return undefined.\n */\nfunction recordOfParsedLine(parsed: UnknownRecord): SidecarRecord | undefined {\n  if (typeof parsed.kind === 'string') return parsed as unknown as SidecarRecord\n  const id = typeof parsed.id === 'string' ? parsed.id : undefined\n  const timestamp = typeof parsed.timestamp === 'string' ? parsed.timestamp : undefined\n  if (id === undefined || timestamp === undefined) return undefined\n  switch (parsed.type) {\n    case 'custom':\n      return {\n        kind: 'custom', id, timestamp, customType: String(parsed.customType ?? ''),\n        ...(parsed.data === undefined ? {} : { data: parsed.data }),\n      }\n    case 'label':\n      return {\n        kind: 'label', id, timestamp,\n        ...(typeof parsed.targetId === 'string' ? { targetId: parsed.targetId } : {}),\n        ...(typeof parsed.label === 'string' ? { label: parsed.label } : {}),\n      }\n    case 'branch_summary':\n      return {\n        kind: 'branch_summary', id, timestamp,\n        ...(typeof parsed.summary === 'string' ? { summary: parsed.summary } : {}),\n        ...(typeof parsed.fromId === 'string' ? { fromId: parsed.fromId } : {}),\n      }\n    case 'session_info':\n      return { kind: 'name', id, timestamp, ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}) }\n    default:\n      return undefined\n  }\n}\n\nexport interface PiProjectedEntry {\n  type: string\n  id: string\n  parentId: string | null\n  timestamp: string\n  [key: string]: unknown\n}\n\n/** Only public persistence reads; never resume or load-with-recovery for indexing. */\nexport interface SessionExportPersistence {\n  list(): Promise<readonly UnknownRecord[]>\n  inspect?(id: string): Promise<{ meta: UnknownRecord; events: readonly UnknownRecord[] }>\n  open?(id: string, access: 'read'): Promise<{\n    header: UnknownRecord\n    read(): Promise<{ events: readonly UnknownRecord[] }>\n    close(): Promise<void>\n  }>\n}\n\nfunction sidecarDir(): string {\n  return join(getAgentDir(), 'session-entries')\n}\n\nfunction sessionEvents(session: DshSessionLike): readonly UnknownRecord[] {\n  return readSessionEvents(session)\n}\n\nfunction dshToPiContent(content: unknown, fileContent: (ref: unknown) => unknown = fileContentForPi): unknown[] {\n  if (!Array.isArray(content)) return [{ type: 'text', text: String(content ?? '') }]\n  return content.map(block => {\n    if (typeof block !== 'object' || block === null) return { type: 'text', text: String(block) }\n    const record = block as UnknownRecord\n    if (record.type === 'file') return fileContent(record.attachment)\n    if (record.type === 'text') return { type: 'text', text: String(record.text ?? '') }\n    if (record.type === 'reasoning') return { type: 'thinking', thinking: String(record.text ?? '') }\n    if (record.type === 'tool-call') {\n      return { type: 'toolCall', id: record.id, name: record.name, arguments: record.arguments }\n    }\n    return { type: record.type }\n  })\n}\n\nexport class PiSessionBridge {\n  constructor(private readonly fileContent: (ref: unknown) => unknown = fileContentForPi) {}\n  private readonly records = new Map<string, SidecarRecord[]>()\n  private readonly loaded = new Set<string>()\n  private readonly exportedSessions = new Map<string, { session: DshSessionLike; cwd: string }>()\n\n  async exportStoredSessions(persistence: SessionExportPersistence): Promise<void> {\n    const priorExports: Array<{ path: string; id: string }> = []\n    const root = join(getAgentDir(), 'sessions')\n    if (existsSync(root)) {\n      for (const directory of readdirSync(root, { withFileTypes: true })) {\n        if (!directory.isDirectory()) continue\n        for (const entry of readdirSync(join(root, directory.name), { withFileTypes: true })) {\n          if (!entry.isFile() || !entry.name.startsWith('dsh-')) continue\n          const path = join(root, directory.name, entry.name)\n          const id = this.sessionIdOfArchiveFile(path)\n          if (id !== undefined) priorExports.push({ path, id })\n        }\n      }\n    }\n    const snapshots = await persistence.list()\n    const present = new Set<string>()\n    const hidden = new Set<string>()\n    for (const snapshot of snapshots) {\n      const header = (snapshot.header ?? snapshot) as UnknownRecord\n      if (typeof header.id !== 'string') continue\n      present.add(header.id)\n      if (typeof header.cwd !== 'string') continue\n      if (typeof persistence.open === 'function') {\n        const handle = await persistence.open(header.id, 'read')\n        try {\n          const { events } = await handle.read()\n          const session = { id: header.id, header: handle.header, events }\n          if (isPiEphemeralSession(session)) hidden.add(header.id)\n          else this.exportSessionFile(session, header.cwd)\n        } finally { await handle.close() }\n      } else if (typeof persistence.inspect === 'function') {\n        const { meta, events } = await persistence.inspect(header.id)\n        const session = { id: header.id, header: meta, events }\n        if (isPiEphemeralSession(session)) hidden.add(header.id)\n        else this.exportSessionFile(session, header.cwd)\n      }\n      // Stored snapshots are not live objects and must not later overwrite a live export.\n      this.exportedSessions.delete(header.id)\n    }\n    // A successful complete native listing is the authority. Never let a\n    // deleted native session live on solely in a derived search export.\n    for (const exported of priorExports) {\n      if ((!present.has(exported.id) || hidden.has(exported.id)) && existsSync(exported.path)) unlinkSync(exported.path)\n    }\n  }\n\n  /** Materialize the public Pi file contract from the native session, never vice versa. */\n  exportSessionFile(session: DshSessionLike, cwd: string): string {\n    this.exportedSessions.set(session.id, { session, cwd })\n    const safe = session.id.replace(/[^a-zA-Z0-9._-]+/gu, '_')\n    const path = join(getDefaultSessionDir(cwd, getAgentDir()), `dsh-${safe}.jsonl`)\n    const header = {\n      type: 'session', version: 3, id: session.id, cwd,\n      timestamp: new Date(Number(session.header?.createdAt ?? sessionEvents(session)[0]?.time ?? Date.now())).toISOString(),\n      pi2dshExport: { nativeSessionId: session.id },\n    }\n    const text = `${[header, ...this.projectEntries(session)].map(value => JSON.stringify(value)).join('\\n')}\\n`\n    // Preserve mtime when unchanged so incremental file consumers can skip it.\n    if (existsSync(path) && readFileSync(path, 'utf8') === text) return path\n    const temporary = `${path}.${randomUUID()}.tmp`\n    try {\n      writeFileSync(temporary, text, { mode: 0o600 })\n      renameSync(temporary, path)\n    } finally {\n      if (existsSync(temporary)) unlinkSync(temporary)\n    }\n    return path\n  }\n\n  private sidecarPath(sessionId: string): string {\n    const safe = sessionId.replace(/[^a-zA-Z0-9._-]+/gu, '_')\n    return join(sidecarDir(), `${safe}.jsonl`)\n  }\n\n  /**\n   * The Pi-visible archive file for one DSH session — the established\n   * `<id>.jsonl` convention (getSessionFile/switchSession use the same one).\n   * Guaranteed to EXIST on return, and to start with a genuine Pi\n   * `{type:\"session\"}` header line: Pi consumers treat the session file as\n   * the durable identity a conversation can be reopened by (pi-subagents\n   * guards its tombstone resurrect with existsSync), and real Pi parsing\n   * (`SessionManager.open` reads the header for id/cwd) must see a Pi file,\n   * not a bare inode. An empty pre-existing file is upgraded in place.\n   */\n  archiveFileFor(sessionId: string, cwd?: string): string {\n    const path = this.sidecarPath(sessionId)\n    const needsHeader = !existsSync(path) || readFileSync(path, 'utf8').trim().length === 0\n    if (needsHeader) {\n      mkdirSync(sidecarDir(), { recursive: true })\n      appendFileSync(path, `${JSON.stringify({\n        type: 'session', version: 3, id: sessionId,\n        timestamp: new Date().toISOString(), cwd: cwd ?? process.cwd(),\n      })}\\n`)\n    }\n    return path\n  }\n\n  /**\n   * The DSH session id an archive-file path names, or undefined for any path\n   * this bridge did not mint (a genuine Pi session file, an in-memory\n   * manager's undefined). The reverse of {@link archiveFileFor} — ids that\n   * survive its sanitization round-trip exactly, which every id this bridge\n   * mints does.\n   */\n  sessionIdOfArchiveFile(path: unknown): string | undefined {\n    if (typeof path !== 'string' || path.length === 0) return undefined\n    const resolved = resolve(path)\n    const base = basename(resolved)\n    if (resolve(dirname(resolved)) === resolve(sidecarDir())) {\n      return base.endsWith('.jsonl') ? base.slice(0, -'.jsonl'.length) : undefined\n    }\n    const within = relative(join(getAgentDir(), 'sessions'), resolved)\n    if (within.startsWith('..') || !base.startsWith('dsh-') || !base.endsWith('.jsonl')) return undefined\n    try {\n      const header = JSON.parse(readFileSync(resolved, 'utf8').split('\\n')[0]!) as UnknownRecord\n      const marker = header.pi2dshExport as UnknownRecord | undefined\n      return typeof marker?.nativeSessionId === 'string' && marker.nativeSessionId === header.id\n        ? marker.nativeSessionId : undefined\n    } catch { return undefined }\n  }\n\n  /**\n   * Retire one archive this bridge minted: the file whose existence tells Pi\n   * consumers \"this conversation can be reopened\". Called ONLY on a positive\n   * persistence-layer verdict that the DSH session is gone, so existsSync\n   * answers honestly again.\n   */\n  discardArchive(sessionId: string): void {\n    try {\n      unlinkSync(this.sidecarPath(sessionId))\n    } catch {\n      // Already gone — retiring an absent identity is a no-op, not a failure.\n    }\n    this.records.delete(sessionId)\n    this.loaded.delete(sessionId)\n    this.exportedSessions.delete(sessionId)\n    const root = join(getAgentDir(), 'sessions')\n    if (existsSync(root)) {\n      for (const directory of readdirSync(root, { withFileTypes: true })) {\n        if (!directory.isDirectory()) continue\n        const file = join(root, directory.name, `dsh-${sessionId.replace(/[^a-zA-Z0-9._-]+/gu, '_')}.jsonl`)\n        if (this.sessionIdOfArchiveFile(file) === sessionId) unlinkSync(file)\n      }\n    }\n  }\n\n  load(sessionId: string): void {\n    if (this.loaded.has(sessionId)) return\n    this.loaded.add(sessionId)\n    const path = this.sidecarPath(sessionId)\n    if (!existsSync(path)) {\n      this.records.set(sessionId, this.records.get(sessionId) ?? [])\n      return\n    }\n    const parsed: SidecarRecord[] = []\n    for (const line of readFileSync(path, 'utf8').split('\\n')) {\n      if (line.trim().length === 0) continue\n      try {\n        const record = recordOfParsedLine(JSON.parse(line) as UnknownRecord)\n        if (record !== undefined) parsed.push(record)\n      } catch {\n        // A torn tail line from a crashed process is dropped, like DSH's own\n        // never-finished trailing fragments.\n      }\n    }\n    this.records.set(sessionId, parsed)\n  }\n\n  private persist(sessionId: string, record: SidecarRecord): void {\n    this.load(sessionId)\n    const list = this.records.get(sessionId) ?? []\n    list.push(record)\n    this.records.set(sessionId, list)\n    // The archive must open with its Pi header before any entry follows it.\n    this.archiveFileFor(sessionId)\n    appendFileSync(this.sidecarPath(sessionId), `${piEntryLineOf(record)}\\n`)\n    const exported = this.exportedSessions.get(sessionId)\n    if (exported !== undefined) this.exportSessionFile(exported.session, exported.cwd)\n  }\n\n  appendCustomEntry(sessionId: string, customType: string, data: unknown): string {\n    const id = randomUUID()\n    this.persist(sessionId, {\n      kind: 'custom', id, timestamp: new Date().toISOString(), customType,\n      ...(data === undefined ? {} : { data }),\n    })\n    return id\n  }\n\n  /**\n   * The custom entries a package appended to one session, oldest first.\n   *\n   * Addressed by id alone: the browser half asks for a session it is showing,\n   * and has no DSH session object to hand over.\n   * @param sessionId - session whose sidecar to read.\n   * @returns each custom entry with its type, data and id.\n   */\n  customEntries(sessionId: string): Array<{ id: string, customType: string, data: unknown, timestamp: string }> {\n    this.load(sessionId)\n    const out: Array<{ id: string, customType: string, data: unknown, timestamp: string }> = []\n    for (const record of this.records.get(sessionId) ?? []) {\n      if (record.kind !== 'custom') continue\n      const entry = record as unknown as { id: string, customType: string, data?: unknown, timestamp: string }\n      out.push({ id: entry.id, customType: entry.customType, data: entry.data, timestamp: entry.timestamp })\n    }\n    return out\n  }\n\n  appendBranchSummary(sessionId: string, summary: string, fromId: string): string {\n    const id = randomUUID()\n    this.persist(sessionId, {\n      kind: 'branch_summary', id, timestamp: new Date().toISOString(), summary, fromId,\n    })\n    return id\n  }\n\n  appendLabel(sessionId: string, targetId: string, label: string | undefined): void {\n    this.persist(sessionId, {\n      kind: 'label', id: randomUUID(), timestamp: new Date().toISOString(), targetId,\n      ...(label === undefined ? {} : { label }),\n    })\n  }\n\n  setName(sessionId: string, name: string): void {\n    const sanitized = name.replace(/[\\r\\n]+/gu, ' ').trim()\n    this.persist(sessionId, { kind: 'name', id: randomUUID(), timestamp: new Date().toISOString(), name: sanitized })\n  }\n\n  getName(sessionId: string): string | undefined {\n    this.load(sessionId)\n    const list = this.records.get(sessionId) ?? []\n    for (let i = list.length - 1; i >= 0; i -= 1) {\n      if (list[i]!.kind === 'name') return list[i]!.name\n    }\n    return undefined\n  }\n\n  labels(sessionId: string): Map<string, string> {\n    this.load(sessionId)\n    const labels = new Map<string, string>()\n    for (const record of this.records.get(sessionId) ?? []) {\n      if (record.kind !== 'label' || record.targetId === undefined) continue\n      if (record.label === undefined) labels.delete(record.targetId)\n      else labels.set(record.targetId, record.label)\n    }\n    return labels\n  }\n\n  /**\n   * Project the DSH durable log plus sidecar records into Pi's entry-chain\n   * shape. DSH history is linear, so the projection is a single-branch tree:\n   * every entry's parent is its predecessor.\n   */\n  /**\n   * The seqs still on the model-visible surface, via DSH's own canonical fold.\n   * @param session - the session to project.\n   * @returns the visible seqs, or undefined when the fold cannot run (a\n   *   projection built from a partial event list, e.g. in a test double) — in\n   *   which case nothing is filtered out rather than everything.\n   */\n  visibleSeqs(session: DshSessionLike): Set<number> | undefined {\n    try {\n      return new Set(foldSurface(sessionEvents(session) as never).nodes)\n    } catch {\n      return undefined\n    }\n  }\n\n  projectEntries(session: DshSessionLike): PiProjectedEntry[] {\n    this.load(session.id)\n    const merged: Array<{ time: number; entry: Omit<PiProjectedEntry, 'parentId'> }> = []\n    for (const event of sessionEvents(session)) {\n      const seq = Number(event.seq ?? 0)\n      const time = Number(event.time ?? 0)\n      const data = (event.data ?? {}) as UnknownRecord\n      const type = event.type\n      if (type === 'user/message') {\n        merged.push({\n          time,\n          entry: {\n            id: `dsh-${seq}`, timestamp: new Date(time).toISOString(),\n            ...(isPiUserMessage(data)\n              ? { type: 'message', message: { role: 'user', content: dshToPiContent(data.content, this.fileContent) } }\n              : { type: 'custom_message', customType: String((data.source as UnknownRecord | undefined)?.piCustomType ?? (data.source as UnknownRecord | undefined)?.kind ?? 'context'), content: dshToPiContent(data.content, this.fileContent), display: false }),\n          },\n        })\n      } else if (type === 'assistant/message') {\n        const message = (data.message ?? {}) as UnknownRecord\n        merged.push({\n          time,\n          entry: {\n            type: 'message', id: `dsh-${seq}`, timestamp: new Date(time).toISOString(),\n            message: { role: 'assistant', content: dshToPiContent(message.content, this.fileContent) },\n          },\n        })\n      } else if (type === 'tool/result') {\n        const message = (data.message ?? {}) as UnknownRecord\n        const blocks = Array.isArray(message.content) ? message.content as UnknownRecord[] : []\n        const tool = blocks.find(block => block.type === 'tool-result')\n        merged.push({\n          time,\n          entry: {\n            type: 'message', id: `dsh-${seq}`, timestamp: new Date(time).toISOString(),\n            message: {\n              role: 'toolResult',\n              toolCallId: tool?.toolCallId,\n              content: dshToPiContent(tool?.content ?? []),\n              isError: tool?.isError === true,\n            },\n          },\n        })\n      }\n    }\n    for (const record of this.records.get(session.id) ?? []) {\n      const time = Date.parse(record.timestamp)\n      if (record.kind === 'custom') {\n        merged.push({\n          time,\n          entry: {\n            type: 'custom', id: record.id, timestamp: record.timestamp,\n            customType: record.customType,\n            ...(record.data === undefined ? {} : { data: record.data }),\n          },\n        })\n      } else if (record.kind === 'branch_summary') {\n        merged.push({\n          time,\n          entry: {\n            type: 'branch_summary', id: record.id, timestamp: record.timestamp,\n            summary: record.summary, fromId: record.fromId,\n          },\n        })\n      } else if (record.kind === 'label') {\n        merged.push({\n          time,\n          entry: {\n            type: 'label', id: record.id, timestamp: record.timestamp,\n            targetId: record.targetId, label: record.label,\n          },\n        })\n      } else {\n        merged.push({\n          time,\n          entry: { type: 'session_info', id: record.id, timestamp: record.timestamp, name: record.name },\n        })\n      }\n    }\n    merged.sort((left, right) => left.time - right.time)\n    const entries: PiProjectedEntry[] = []\n    let parentId: string | null = null\n    for (const item of merged) {\n      const entry = { ...item.entry, parentId } as PiProjectedEntry\n      entries.push(entry)\n      parentId = entry.id\n    }\n    return entries\n  }\n\n  /** The exact 14-method surface Pi exposes as ctx.sessionManager. */\n  readonlySessionManager(session: DshSessionLike, cwd: string): UnknownRecord {\n    const entriesOf = (): PiProjectedEntry[] => this.projectEntries(session)\n    const leafOf = (): PiProjectedEntry | undefined => entriesOf().at(-1)\n    return {\n      getCwd: () => cwd,\n      getSessionDir: () => getDefaultSessionDir(cwd, getAgentDir()),\n      getSessionId: () => session.id,\n      // The archive path is a REOPENABLE identity to Pi consumers (existsSync\n      // guards, SessionManager.open) — materialized on read, not virtual.\n      getSessionFile: () => isPiEphemeralSession(session) ? undefined : this.exportSessionFile(session, cwd),\n      getLeafId: () => leafOf()?.id ?? null,\n      getLeafEntry: () => leafOf(),\n      getEntry: (id: string) => entriesOf().find(entry => entry.id === id),\n      getLabel: (id: string) => this.labels(session.id).get(id),\n      getBranch: (fromId?: string) => {\n        const entries = entriesOf()\n        if (fromId === undefined) return entries\n        const index = entries.findIndex(entry => entry.id === fromId)\n        return index === -1 ? [] : entries.slice(0, index + 1)\n      },\n      // Pi's buildContextEntries is the COMPACTION-AWARE list — what actually\n      // goes to the model. Two rules, both of them Pi's:\n      //\n      //  - by type: message/compaction/branch_summary/custom_message enter the\n      //    context; custom entries and labels are state-only;\n      //  - by compaction: entries the latest compaction summarized are gone,\n      //    replaced by the summary. Returning them anyway (what this did) let\n      //    a package build context out of history the model can no longer see\n      //    — and the longer the session, the further apart the two drift.\n      //\n      // Which entries survive is not re-derived here: DSH's own `foldSurface`\n      // is the authority on the model-visible surface, and its node list is\n      // seqs, which is exactly what these entry ids are made of.\n      buildContextEntries: () => {\n        const visible = this.visibleSeqs(session)\n        return entriesOf().filter(entry => {\n          if (entry.type !== 'message' && entry.type !== 'compaction'\n            && entry.type !== 'branch_summary' && entry.type !== 'custom_message') return false\n          // A sidecar entry has no seq of its own and is never shadowed.\n          const seq = entrySeq(entry.id)\n          return seq === undefined || visible === undefined || visible.has(seq)\n        })\n      },\n      getHeader: () => ({\n        type: 'session',\n        version: 3,\n        id: session.id,\n        timestamp: new Date(Number(sessionEvents(session)[0]?.time ?? Date.now())).toISOString(),\n        cwd,\n      }),\n      getEntries: () => entriesOf(),\n      getTree: () => {\n        const entries = entriesOf()\n        const labels = this.labels(session.id)\n        type Node = { entry: PiProjectedEntry; children: Node[]; label?: string | undefined }\n        let root: Node | undefined\n        let cursor: Node | undefined\n        for (const entry of entries) {\n          const node: Node = {\n            entry,\n            children: [],\n            ...(labels.has(entry.id) ? { label: labels.get(entry.id) } : {}),\n          }\n          if (cursor === undefined) root = node\n          else cursor.children.push(node)\n          cursor = node\n        }\n        return root === undefined ? [] : [root]\n      },\n      getSessionName: () => this.getName(session.id),\n    }\n  }\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm'\n\ntype UnknownRecord = Record<string, unknown>\ntype PiSessionEventHandler = (event: UnknownRecord) => void\n\n// Pi's public AgentSession surface, driven by a REAL DSH agent created\n// through ctx.agents — the host loop's registered factory builds the child\n// session and drives its turns. The bridge owns no model loop of its own:\n// in a composition without the loop/model runtime (e.g. the credential-less\n// black-box probe), creation fails with an explicit message instead of\n// pretending a subagent ran.\n//\n// Surface covered is the set the ecosystem's subagent packages actually\n// consume (verified against @tintinweb/pi-subagents): prompt, steer, abort,\n// subscribe, messages, setSessionName, getSessionStats, bindExtensions,\n// getAllTools/getActiveToolNames/setActiveToolsByName, and the\n// agent.beforeToolCall hook slot (wired to DSH's tools/pre-execute seam).\n\nexport interface SubagentHost {\n  cordis: Context\n  cwd(): string\n  parentSessionId(): string | undefined\n  /** The delegating parent's delegation depth (DSH's recursion budget); 0 for a top-level parent. */\n  parentDelegationDepth(): number\n  piContentToDsh(content: unknown): Promise<ContentBlock[]>\n  deliver(agent: UnknownRecord, message: unknown, mode: 'inject' | 'steer' | 'followup'): void\n  messageFromSessionEvent(event: UnknownRecord): Promise<UnknownRecord | undefined>\n  messageSource: string\n  /** The Pi package that asked for the child, used to label it in DSH's catalog. */\n  packageName?: string\n  /** The delegating parent Agent's own ctx (undefined outside an agent scope). */\n  parentAgentContext(): unknown\n  /** The live parent identity required by newer DSH agent ownership. */\n  parentAgent?(): UnknownRecord | undefined\n  /**\n   * Translate the child's Pi custom tools into DSH tool definitions and\n   * register them THROUGH the unpublished child ctx, so they land in the\n   * child Agent's scope and unwind with it.\n   */\n  registerChildTools(childCtx: unknown, tools: readonly unknown[]): void\n  /**\n   * DSH's official delegation policy capture (dsh-subagent semantics): the\n   * parent session's explicit sandbox override, and the approval policy\n   * pinned to 'never' when an approval service exists.\n   */\n  delegatedPolicyOverrides(): { sandboxMode?: unknown, approvalPolicy?: string }\n  /**\n   * Pi-shaped readonly sessionManager projection over one DSH session. Its\n   * getSessionFile() returns the durable archive path (`<id>.jsonl`\n   * convention) Pi consumers treat as the conversation's reopenable identity\n   * — pi-subagents records it per child and resurrects `@handle` mentions by\n   * reopening exactly that file.\n   */\n  sessionManagerFor?(session: unknown): UnknownRecord\n  /**\n   * The DSH session id an archive path names, or undefined for any path the\n   * bridge did not mint (a genuine Pi session file, an in-memory manager).\n   */\n  resumeSessionIdFor?(file: unknown): string | undefined\n  /**\n   * Serve the child the extension set a real Pi createAgentSession loads:\n   * the host's installed Pi packages, filtered by the creator's resource\n   * loader (its own getExtensions applies noExtensions/extensionsOverride —\n   * the creator's code decides, not this bridge). No loader means Pi's\n   * default: everything discovered. Resolves with per-extension failures\n   * (Pi's per-extension error isolation — a failed extension never takes\n   * the child down).\n   */\n  mountChildExtensions?(childAgent: UnknownRecord, loader: unknown): Promise<Array<{ name: string, error: string }>>\n  /**\n   * Whether the host's session persistence POSITIVELY lacks this session —\n   * DSH's own post-resume-failure verdict shape (`persistence.list()` in\n   * agent-loop's restoreOrCreateConfigured). undefined = cannot tell (no\n   * persistence service or list failed), and nothing may be retired on it.\n   */\n  sessionGoneFromPersistence?(sessionId: string): Promise<boolean | undefined>\n  /** Retire a stale archive identity this bridge minted, so existsSync answers honestly again. */\n  discardStaleArchive?(sessionId: string): void\n  /**\n   * The delegating parent's own model route. Pi's default for a child session\n   * is the caller's current model; without it the child agent has no model\n   * option and prompt sections keyed on {{model}} fail the first assembly.\n   */\n  parentModelRoute?(): { provider?: string, model?: string } | undefined\n  /**\n   * Claim a freshly created child agent for this instance: its requests join\n   * the instance's agent/request waterfall (which is what carries a per-child\n   * thinking level), and only the creating instance claims it.\n   */\n  adoptChildAgent?(child: unknown, thinkingLevel?: string): void\n}\n\nexport interface CreateAgentSessionOptions {\n  cwd?: string\n  tools?: unknown[]\n  customTools?: unknown[]\n  model?: unknown\n  thinkingLevel?: unknown\n  signal?: AbortSignal\n  [key: string]: unknown\n}\n\ninterface BeforeToolCallDecision {\n  block?: boolean\n  reason?: string\n}\n\ninterface PiSubagentFacade {\n  beforeToolCall?: (\n    context: { toolCall: { name: string, id: string, arguments: unknown } },\n    signal: AbortSignal | undefined,\n  ) => Promise<BeforeToolCallDecision | undefined> | BeforeToolCallDecision | undefined\n  /** Pi's AgentState — the same object `session.state` returns. */\n  state?: UnknownRecord\n}\n\nlet subagentSerial = 0\n\n/**\n * Pi built-in tool name → the DSH native tool that serves it. The two\n * vocabularies coincide (read/bash/edit/write/grep); Pi's find and ls are\n * both served by the host's glob.\n */\nfunction nativeToolNameOf(name: string): string {\n  return name === 'find' || name === 'ls' ? 'glob' : name\n}\n\n/**\n * The tool schemas a CHILD agent actually resolves — its scoped view when the\n * service answers for the agent being built, else the global layer. On\n * roster-owned surfaces the preset tools live above the global layer, so the\n * scoped read is the one that sees them.\n */\nfunction childSchemas(\n  toolsService: { schemas(scope?: unknown): ReadonlyArray<{ name: string }> },\n  childAgent: unknown,\n): ReadonlyArray<{ name: string }> {\n  try {\n    if (childAgent !== undefined) return toolsService.schemas(childAgent)\n  } catch {\n    // fall through to the global read below\n  }\n  return toolsService.schemas()\n}\n\n/**\n * Cross-scope subscription base. Session events dispatch under the OWNING\n * session's scope; a package instance mounted per Agent registers listeners\n * inside its own Agent's scope and would never see a child session's events.\n * The bridge's callbacks filter by exact session/agent identity, so they\n * subscribe unscoped at the root context — the same posture the old\n * host-level mount had.\n */\nfunction unscopedEventContext(cordis: unknown): { on(name: string, callback: (...args: any[]) => unknown): () => void } {\n  const host = cordis as { root?: unknown, on(name: string, callback: (...args: any[]) => unknown): () => void }\n  return (host.root ?? host) as { on(name: string, callback: (...args: any[]) => unknown): () => void }\n}\n\n/** Flatten a Pi message's content to text for transcript seeding. */\nfunction piMessageText(message: UnknownRecord): string {\n  const content = message.content\n  if (typeof content === 'string') return content\n  if (!Array.isArray(content)) return ''\n  return content\n    .map(block => {\n      const record = block as UnknownRecord | undefined\n      if (record?.type === 'text' && typeof record.text === 'string') return record.text\n      if (record?.type === 'toolCall' && typeof record.name === 'string') {\n        return `(tool ${record.name})`\n      }\n      return ''\n    })\n    .filter(text => text.length > 0)\n    .join('\\n')\n}\n\nexport class PiBridgedAgentSession {\n  readonly agent: PiSubagentFacade = {}\n  readonly messages: UnknownRecord[] = []\n  /**\n   * Pi's AgentSession.sessionManager surface, projected over the child's DSH\n   * session. getSessionFile() names the durable archive — what pi-subagents\n   * stores as the conversation's reopenable identity (tombstone resurrect).\n   */\n  readonly sessionManager: UnknownRecord | undefined\n  // Transcript assigned through Pi's public `state.messages` setter and not\n  // yet carried into the child's durable log (see #state).\n  #seed: UnknownRecord[] = []\n  // Entries that are CONTEXT rather than exchange: a package seeding the\n  // parent's transcript, and the host's own runtime-context snapshots. A reader\n  // showing the conversation to a person has to tell the two apart, and order\n  // cannot — a package may seed again later, and snapshots arrive mid-thread.\n  readonly #carried = new WeakSet<UnknownRecord>()\n\n  readonly #host: SubagentHost\n  readonly #handle: { agent: UnknownRecord, dispose(): Promise<void> }\n  readonly #thinkingLevel: string\n  readonly #session: UnknownRecord\n  readonly #tools: unknown[]\n  readonly #subscribers = new Set<PiSessionEventHandler>()\n  readonly #disposers: Array<() => void> = []\n  #activeToolNames: string[]\n  #state!: UnknownRecord\n  #model: unknown\n  #streaming = false\n  #pendingToolCalls = new Set<string>()\n  /** callId → tool name, so tool_execution_end can name the tool its result belongs to. */\n  #toolCallNames = new Map<string, string>()\n  #sessionName = ''\n  #turns = 0\n  #restrictionDispose: (() => void) | undefined\n  /** Keeps message projections (which await attachment reads) in log order. */\n  #messageProjection: Promise<unknown> = Promise.resolve()\n  #aborted = false\n  #liveStreamAttempt: { id: unknown, index: number, ended: boolean } | undefined\n  #streamingText = ''\n\n  constructor(\n    host: SubagentHost,\n    handle: { agent: UnknownRecord, dispose(): Promise<void> },\n    tools: unknown[],\n    thinkingLevel?: string,\n  ) {\n    this.#thinkingLevel = typeof thinkingLevel === 'string' && thinkingLevel.length > 0 ? thinkingLevel : 'off'\n    this.#host = host\n    this.#handle = handle\n    this.#session = (handle.agent as { session?: UnknownRecord }).session ?? {}\n    this.sessionManager = host.sessionManagerFor?.(this.#session)\n    this.#tools = tools\n    this.#activeToolNames = tools\n      .map(tool => (tool as { name?: unknown } | undefined)?.name)\n      .filter((name): name is string => typeof name === 'string')\n\n    // Subscribe UNSCOPED, at the root: the child's events dispatch under the\n    // CHILD's scope, and this bridge lives inside the PARENT instance's agent\n    // scope — a scoped listener would be filtered out and the wait below\n    // would never resolve (the /btw hang). The callbacks filter by exact\n    // session/agent identity themselves, so root subscription is precise.\n    const cordis = unscopedEventContext(host.cordis)\n    // Project this child session's durable events into Pi AgentSessionEvents.\n    const offEvents = cordis.on('session/event', (session: UnknownRecord, event: UnknownRecord) => {\n      if (session !== this.#session) return\n      if (event.type === 'assistant/chunk' && this.#liveStreamAttempt !== undefined) return\n      this.#project(event)\n    })\n    const offStream = cordis.on('agent/assistant-stream', (payload: UnknownRecord) => {\n      if (payload.agent !== this.#handle.agent) return\n      const frame = payload.frame as UnknownRecord\n      if (frame.type === 'start') {\n        this.#liveStreamAttempt = { id: frame.attemptId, index: -1, ended: false }\n        this.#streamingText = ''\n      } else {\n        const active = this.#liveStreamAttempt\n        if (active === undefined || active.ended || active.id !== frame.attemptId) return\n        if (frame.type === 'end') active.ended = true\n        if (frame.type === 'chunk' && Number(frame.index) > active.index) {\n          active.index = Number(frame.index)\n          this.#project({ type: 'assistant/chunk', data: { chunk: frame.chunk } })\n        }\n      }\n    })\n    // Pi packages assign session.agent.beforeToolCall to gate the subagent's\n    // tool calls; DSH's pre-execute seam is the same decision point.\n    const offPre = cordis.on('tools/pre-execute', async (\n      exec: { agent?: unknown, name: string, callId: string, arguments: unknown },\n      next: () => Promise<UnknownRecord>,\n    ): Promise<UnknownRecord> => {\n      if (exec.agent !== this.#handle.agent || this.agent.beforeToolCall === undefined) return next()\n      const decision = await this.agent.beforeToolCall(\n        { toolCall: { name: exec.name, id: exec.callId, arguments: exec.arguments } },\n        undefined,\n      )\n      if (decision?.block === true) {\n        return { kind: 'deny', reason: decision.reason ?? `Tool \"${exec.name}\" is not available to this subagent.` }\n      }\n      return next()\n    })\n    this.#disposers.push(offEvents, offStream, offPre)\n    // Pi's AgentSession exposes ONE AgentState object as both `session.state`\n    // and `session.agent.state` (agent-session.ts: `get state() { return\n    // this.agent.state }`). `messages` is a PUBLIC settable member of\n    // AgentState, and packages seed a child transcript by assigning it\n    // (pi-btw builds its side thread that way). DSH history is an append-only\n    // durable log, so an assignment cannot rewrite history: the assigned\n    // transcript is carried into the child with the next prompt instead\n    // (documented in compatibility.ts).\n    const session = this\n    this.#state = {\n      get systemPrompt(): string { return '' },\n      get model(): unknown { return session.#model },\n      get thinkingLevel(): string { return session.#thinkingLevel },\n      get tools(): unknown[] { return [...session.#tools] },\n      set tools(_next: unknown[]) { /* DSH owns the child's tool scope */ },\n      get messages(): UnknownRecord[] { return [...session.messages] },\n      set messages(next: UnknownRecord[]) { session.#assignTranscript(next) },\n      get isStreaming(): boolean { return session.#streaming },\n      get pendingToolCalls(): ReadonlySet<string> { return new Set(session.#pendingToolCalls) },\n    } as unknown as UnknownRecord\n    this.agent.state = this.#state\n  }\n\n  /** Pi's AgentState projection, shared by `session.state` and `session.agent.state`. */\n  get state(): UnknownRecord {\n    return this.#state\n  }\n\n  /**\n   * Pi's `state.messages = …` assignment. Messages already present in this\n   * child's projection stay as they are (they are durable); anything new is\n   * queued and delivered with the next prompt so the child model really sees\n   * the transcript the package seeded.\n   */\n  #assignTranscript(next: readonly UnknownRecord[]): void {\n    const identity = (message: UnknownRecord): string => JSON.stringify([message.role, message.content])\n    const known = new Set(this.messages.map(identity))\n    this.#seed = next.filter(message => !known.has(identity(message)))\n    for (const message of this.#seed) {\n      this.#carried.add(message)\n      this.messages.push(message)\n    }\n  }\n\n  /**\n   * Whether one transcript entry is carried context rather than part of the\n   * exchange in this child session.\n   * @param message - an entry of {@link messages}.\n   * @returns true for a seeded transcript entry or a host runtime snapshot.\n   */\n  isCarriedContext(message: UnknownRecord): boolean {\n    return this.#carried.has(message)\n  }\n\n  #project(event: UnknownRecord): void {\n    const type = event.type\n    const emit = (piEvent: UnknownRecord): void => {\n      for (const handler of [...this.#subscribers]) {\n        try {\n          handler(piEvent)\n        } catch {\n          // A broken subscriber must not sever the projection for the rest.\n        }\n      }\n    }\n    // Pi's abort() contract: the run stops and STAYS stopped until the next\n    // explicit prompt(). DSH's cancel only aborts the active turn — a tool\n    // result reaching quiescence after the abort is waking input that opens\n    // a fresh turn (\"runs when the aborted activity converges to idle\"), and\n    // the stopped child would finish its task anyway. Keep the child quiet by\n    // cancelling while aborted — and on EVERY opening event, not just\n    // turn/start: a cancel issued the instant the durable turn/start lands can\n    // race the driver claiming its activity (\"with no active activity,\n    // cancellation is a no-op\"), so the guard fires again at step/start and\n    // request/header until one lands on live activity. prompt() lifts it.\n    if (this.#aborted && (type === 'turn/start' || type === 'step/start' || type === 'request/header')) {\n      this.#cancelChild()\n      return\n    }\n    if (type === 'turn/start') {\n      this.#streaming = true\n      emit({ type: 'turn_start', turnIndex: Number((event.data as UnknownRecord).turn ?? 1) - 1 })\n    }\n    if (type === 'request/header') {\n      // The route this child is actually calling, in Pi Model shape.\n      const config = ((event.data as UnknownRecord).config ?? {}) as UnknownRecord\n      if (typeof config.model === 'string') {\n        this.#model = { id: config.model, provider: String(config.provider ?? '') }\n      }\n    }\n    if (type === 'tools/result' || type === 'tool/result') {\n      const data = event.data as UnknownRecord\n      // DSH records the result as a user-role message whose content blocks are\n      // 'tool-result' entries. Pi's contract is a tool_execution_end event per\n      // finished call ({toolCallId, toolName, result, isError}) — pi-subagents\n      // counts its \"tool uses\" on exactly this event, so missing it read as\n      // \"0 tool uses\" while the child was really running tools.\n      const message = data.message as UnknownRecord | undefined\n      const blocks = Array.isArray(message?.content) ? message.content : []\n      for (const block of blocks) {\n        const record = block as UnknownRecord | undefined\n        if (record?.type !== 'tool-result') continue\n        const callId = String(record.toolCallId ?? (message?.source as UnknownRecord | undefined)?.callId ?? data.callId ?? '')\n        this.#pendingToolCalls.delete(callId)\n        const isError = record.isError === true\n        emit({\n          type: 'tool_execution_end',\n          toolCallId: callId,\n          toolName: this.#toolCallNames.get(callId) ?? '',\n          result: { content: record.content ?? [], isError },\n          isError,\n        })\n        this.#toolCallNames.delete(callId)\n      }\n      if (blocks.length === 0) this.#pendingToolCalls.delete(String(data.callId ?? ''))\n    }\n    if (type === 'tool/call') {\n      const data = event.data as UnknownRecord\n      this.#pendingToolCalls.add(String(data.callId ?? ''))\n      this.#toolCallNames.set(String(data.callId ?? ''), String(data.name ?? ''))\n      let args: unknown = {}\n      try {\n        args = JSON.parse(String(data.arguments ?? '{}'))\n      } catch {\n        args = {}\n      }\n      emit({ type: 'tool_execution_start', toolCallId: data.callId, toolName: data.name, args })\n    }\n    if (type === 'assistant/message') this.#streamingText = ''\n    if (type === 'assistant/chunk') {\n      const chunk = ((event.data as UnknownRecord).chunk ?? {}) as UnknownRecord\n      if (chunk.type !== undefined && chunk.type !== 'text-delta') return\n      const delta = typeof chunk.text === 'string' ? chunk.text : typeof chunk.delta === 'string' ? chunk.delta : ''\n      const message = { role: 'assistant', content: [{ type: 'text', text: this.#streamingText += delta }] }\n      emit({\n        type: 'message_update',\n        message,\n        assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta, partial: message },\n      })\n    }\n    // Projecting content now awaits the attachment service, so the chain keeps\n    // this child's messages in the order its log produced them.\n    this.#messageProjection = this.#messageProjection.then(async () => {\n      const message = await this.#host.messageFromSessionEvent(event)\n      if (message === undefined) return\n      // The host injects its own runtime-context snapshots as user messages\n      // (source.form === 'snapshot'). They belong to the model's context, not\n      // to the conversation, so they are marked the same as a seeded\n      // transcript: still in `messages` (the model really saw them), skipped by\n      // anything showing the exchange to a person.\n      if (((event.data as UnknownRecord | undefined)?.source as UnknownRecord | undefined)?.form === 'snapshot') {\n        this.#carried.add(message)\n      }\n      this.messages.push(message)\n      emit({ type: 'message_start', message })\n      emit({ type: 'message_end', message })\n    })\n    if (type === 'turn/end') {\n      this.#turns += 1\n      this.#streaming = false\n      this.#pendingToolCalls.clear()\n      // Behind the same chain as the message projections, so a turn never ends\n      // before the messages it produced have been delivered — Pi's contract is\n      // that a completed prompt has already emitted its message events.\n      this.#messageProjection = this.#messageProjection.then(() => {\n        emit({ type: 'turn_end', turnIndex: Number((event.data as UnknownRecord).turn ?? 1) - 1, message: { role: 'assistant', content: [] }, toolResults: [] })\n      })\n    }\n  }\n\n  subscribe(handler: PiSessionEventHandler): () => void {\n    this.#subscribers.add(handler)\n    return () => this.#subscribers.delete(handler)\n  }\n\n  async prompt(text: string): Promise<void> {\n    // Pi's contract: prompting an aborted session runs it again — the abort\n    // suppression above must not outlive the next explicit prompt.\n    this.#aborted = false\n    // Carry a seeded transcript (Pi's `state.messages = …`) into the child's\n    // durable log before the prompt it is meant to precede.\n    if (this.#seed.length > 0) {\n      const seeded = this.#seed\n      this.#seed = []\n      const rendered = seeded\n        .map(message => {\n          const role = String(message.role ?? 'user')\n          const content = piMessageText(message)\n          return content.length === 0 ? undefined : `[${role}]: ${content}`\n        })\n        .filter((line): line is string => line !== undefined)\n      if (rendered.length > 0) {\n        const seedBlocks = await this.#host.piContentToDsh([{\n          type: 'text',\n          text: `<${SEED_CARRIER_TAG}>\\n${rendered.join('\\n\\n')}\\n</${SEED_CARRIER_TAG}>`,\n        }])\n        this.#host.deliver(this.#handle.agent, createUserMessage({\n          content: seedBlocks,\n          source: { kind: 'plugin', plugin: this.#host.messageSource },\n        }), 'inject')\n      }\n    }\n    const blocks = await this.#host.piContentToDsh([{ type: 'text', text: String(text) }])\n    // Root subscription for the same reason as the constructor: the child's\n    // turn/end dispatches under the child's scope.\n    const cordis = unscopedEventContext(this.#host.cordis)\n    const completed = new Promise<void>(resolve => {\n      const off = cordis.on('session/event', (session: UnknownRecord, event: UnknownRecord) => {\n        if (session !== this.#session) return\n        if (event.type === 'turn/end') {\n          off()\n          resolve()\n        }\n      })\n      this.#disposers.push(off)\n    })\n    this.#host.deliver(this.#handle.agent, createUserMessage({\n      content: blocks,\n      source: { kind: 'plugin', plugin: this.#host.messageSource, form: 'relay' },\n    }), 'followup')\n    await completed\n    // The turn's own event resolves `completed`, but message projection awaits\n    // the attachment service, so draining that chain here is what makes\n    // \"prompt() resolved\" mean \"every message event for this turn has been\n    // delivered\" — the order a Pi caller reading `session.messages` expects.\n    await this.#messageProjection\n  }\n\n  // Pi's AgentSession contract (coding-agent agent-session.ts): steer and\n  // followUp are BOTH async and resolve once the message is queued —\n  // pi-subagents chains `session.steer(msg).catch(...)` directly, so a void\n  // return is a synchronous crash in the caller, not a style choice.\n  async steer(text: string, images?: readonly UnknownRecord[]): Promise<void> {\n    await this.#queueMessage(text, images, 'steer')\n  }\n\n  async followUp(text: string, images?: readonly UnknownRecord[]): Promise<void> {\n    await this.#queueMessage(text, images, 'followup')\n  }\n\n  async #queueMessage(text: string, images: readonly UnknownRecord[] | undefined, mode: 'steer' | 'followup'): Promise<void> {\n    const content: UnknownRecord[] = [{ type: 'text', text: String(text) }]\n    for (const image of images ?? []) content.push(image)\n    const blocks = await this.#host.piContentToDsh(content)\n    this.#host.deliver(this.#handle.agent, createUserMessage({\n      content: blocks,\n      source: { kind: 'plugin', plugin: this.#host.messageSource },\n    }), mode)\n  }\n\n  abort(): void {\n    this.#aborted = true\n    this.#cancelChild()\n  }\n\n  /** One official Agent.cancel, contained but LOUD: a swallowed cancel is a\n   * child that keeps running after its parent was interrupted. */\n  #cancelChild(): void {\n    const cancel = (this.#handle.agent as { cancel?: (reason: UnknownRecord) => void }).cancel\n    if (cancel === undefined) {\n      // Console AND logger, same rule as the engine's mount line: a profile's\n      // logger level must never be able to hide a child that cannot be stopped.\n      const message = '[pi2dsh] subagent abort(): the child agent handle has no cancel — the child cannot be stopped'\n      console.warn(message)\n      this.#host.cordis.logger?.warn?.(message)\n      return\n    }\n    try {\n      cancel.call(this.#handle.agent, { kind: 'hook', reason: 'pi2dsh subagent abort()' })\n    } catch (error) {\n      const message = `[pi2dsh] subagent abort(): Agent.cancel failed (${error instanceof Error ? error.message : String(error)}) — already disposed, or the child kept running`\n      console.warn(message)\n      this.#host.cordis.logger?.warn?.(message)\n    }\n  }\n\n  setSessionName(name: string): void {\n    this.#sessionName = String(name)\n  }\n\n  getSessionName(): string {\n    return this.#sessionName\n  }\n\n  getSessionStats(): UnknownRecord {\n    return { turns: this.#turns, messages: this.messages.length, aborted: this.#aborted }\n  }\n\n  /** The child scope's REAL tool schemas (native + scoped custom), in Pi tool shape. */\n  #scopeTools(): Array<{ name: string, description?: unknown, parameters?: unknown }> {\n    const agentCtx = (this.#handle.agent as { ctx?: { get?(name: string): unknown } }).ctx\n    const toolsService = (typeof agentCtx?.get === 'function' ? agentCtx.get('tools') : undefined) as\n      | { schemas?(agent: unknown): ReadonlyArray<{ name: string, description?: unknown, parameters?: unknown }> }\n      | undefined\n    try {\n      return [...(toolsService?.schemas?.(this.#handle.agent) ?? [])]\n    } catch {\n      return []\n    }\n  }\n\n  getAllTools(): unknown[] {\n    // The child's real toolset: the visibility-resolved schemas of its own\n    // scope (native tools granted by the preset composition plus the scoped\n    // custom registrations). Custom tool OBJECTS are answered as given —\n    // that is the object the package registered.\n    const custom = new Map(this.#tools\n      .filter((tool): tool is UnknownRecord => typeof (tool as UnknownRecord | undefined)?.name === 'string')\n      .map(tool => [String(tool.name), tool]))\n    return this.#scopeTools().map(schema => custom.get(schema.name) ?? schema)\n  }\n\n  getActiveToolNames(): string[] {\n    const fromScope = this.#scopeTools().map(schema => schema.name)\n    return fromScope.length > 0 ? fromScope : [...this.#activeToolNames]\n  }\n\n  /** Hand over the creation-time restriction so a later setActiveToolsByName\n   * retires it instead of intersecting with it. */\n  adoptRestriction(dispose: (() => void) | undefined): void {\n    this.#restrictionDispose = dispose\n  }\n\n  setActiveToolsByName(names: string[]): void {\n    this.#activeToolNames = names.filter(name => typeof name === 'string')\n    // Drive the child scope's REAL restriction: dispose the previous one and\n    // allow exactly the requested set (mapped onto native names). Scoped\n    // custom registrations are outside restriction reach, matching Pi.\n    const agentCtx = (this.#handle.agent as { ctx?: { get?(name: string): unknown } }).ctx\n    const toolsService = (typeof agentCtx?.get === 'function' ? agentCtx.get('tools') : undefined) as\n      | {\n        restrict(filter: { allow?: readonly string[] }): () => void\n        schemas(scope?: unknown): ReadonlyArray<{ name: string }>\n      }\n      | undefined\n    if (toolsService === undefined) return\n    try {\n      this.#restrictionDispose?.()\n      // Same unknown-name tolerance as creation: a name this host does not\n      // carry names nothing (restrict() itself would refuse it). Known names\n      // come from this child's OWN resolved view, so preset-scoped tools on\n      // roster-owned surfaces stay reachable.\n      let known: Set<string>\n      try {\n        known = new Set(toolsService.schemas(this.#handle.agent).map(schema => schema.name))\n      } catch {\n        known = new Set(toolsService.schemas().map(schema => schema.name))\n      }\n      this.#restrictionDispose = toolsService.restrict({\n        allow: this.#activeToolNames.map(nativeToolNameOf).filter(name => known.has(name)),\n      })\n    } catch {\n      // The scope may already be disposing; the façade list above still answers.\n    }\n  }\n\n  /** Per-extension mount failures recorded at creation, for bindExtensions' onError. */\n  #extensionFailures: ReadonlyArray<{ name: string, error: string }> = []\n\n  adoptExtensionFailures(failures: ReadonlyArray<{ name: string, error: string }>): void {\n    this.#extensionFailures = failures\n  }\n\n  async bindExtensions(bindings: UnknownRecord = {}): Promise<void> {\n    // Real Pi loads extensions at createAgentSession and bindExtensions wires\n    // bindings + fires session_start. Here the creator-filtered installed\n    // packages were mounted at creation (same load timing as Pi's sdk), and\n    // each per-child instance dispatches its own session lifecycle — so this\n    // face's remaining job is Pi's per-extension error isolation: report the\n    // recorded mount failures to the binding's onError, the exact shape\n    // pi-subagents surfaces as extension-error tool activity. One timing\n    // nuance is documented in compatibility.ts: session_start reaches the\n    // child-bound packages at creation rather than at this call.\n    const onError = (bindings as { onError?: (failure: { extensionPath: string, error: string }) => void }).onError\n    if (typeof onError !== 'function') return\n    for (const failure of this.#extensionFailures) {\n      try {\n        onError({ extensionPath: failure.name, error: failure.error })\n      } catch {\n        // The binding's own throw is the binder's bug; Pi does not let it\n        // cascade into the session either.\n      }\n    }\n  }\n\n  async dispose(): Promise<void> {\n    for (const dispose of this.#disposers.splice(0)) {\n      try {\n        dispose()\n      } catch {\n        // Disposal is best-effort teardown; the handle dispose below decides.\n      }\n    }\n    this.#subscribers.clear()\n    await this.#handle.dispose()\n  }\n}\n\n/**\n * The name DSH's own child catalog shows for a side thread. Pi packages rarely\n * label a child, so the package that started it is the honest fallback: with\n * several Pi packages installed, their threads stay apart in one list.\n * @param requested - a label the calling package supplied, if any.\n * @param packageName - the Pi package the call came from.\n */\n/**\n * Envelope the bridge wraps a seeded transcript in before handing it to the\n * child as one durable message.\n *\n * Exported because it is a CONTRACT, not a formatting detail: a reader of the\n * child session (the side panel) has to recognise the carrier to tell carried\n * context apart from the exchange, and matching on a copied string would drift.\n */\nexport const SEED_CARRIER_TAG = 'prior-conversation'\n\nexport function childLabel(requested: unknown, packageName: string | undefined): string {\n  if (typeof requested === 'string' && requested.trim().length > 0) return requested.trim().slice(0, 80)\n  const owner = packageName?.trim()\n  return owner === undefined || owner.length === 0 ? 'Pi side conversation' : `${owner} side conversation`\n}\n\nexport async function createBridgedAgentSession(\n  host: SubagentHost,\n  options: CreateAgentSessionOptions,\n): Promise<{ session: PiBridgedAgentSession }> {\n  // ctx.get() resolves the service without an inject declaration — the bridge\n  // is constructed from arbitrary extension call sites, not a fiber of its own.\n  const agents = (host.cordis as unknown as { get(name: string): unknown }).get('agents') as\n    | {\n      create?: (options: UnknownRecord) => Promise<{ agent: UnknownRecord, dispose(): Promise<void> }>\n      resume?: (options: UnknownRecord) => Promise<{ agent: UnknownRecord, dispose(): Promise<void> }>\n      get?(id: string): unknown\n    }\n    | undefined\n  if (agents?.create === undefined) {\n    throw new Error('pi2dsh: createAgentSession() needs the DSH agent registry in the host composition')\n  }\n  // Pi's reopen contract: the caller hands a SessionManager opened FROM a\n  // session file (pi-subagents resurrects an evicted `@handle` this way —\n  // SessionManager.open(tombstone.sessionFile) → createAgentSession). When\n  // that file is an archive this bridge minted, the durable identity it names\n  // is a DSH session — the continuation must bind back to THAT session\n  // through the official persisted-resume seam, not start a lookalike.\n  const providedManager = options.sessionManager as { getSessionFile?(): string | undefined } | undefined\n  const archiveFile = typeof providedManager?.getSessionFile === 'function' ? providedManager.getSessionFile() : undefined\n  const resumeSessionId = host.resumeSessionIdFor?.(archiveFile)\n  // Pi's `SessionManager.inMemory()` marks an EPHEMERAL side thread: no\n  // session file, scratch by design (pi-btw's side conversations — keeping\n  // is explicit through the package's own save/inject flows). A structural\n  // judgement, never a package name. The host has no ephemeral-session seam\n  // yet, so the durable record still exists; the ecosystem's side-thread\n  // label convention below keeps these threads out of task/subagent product\n  // surfaces (better-sidebar and dsh-sidechain both filter on the prefix).\n  const sideline = providedManager !== undefined && archiveFile === undefined\n  const parentId = host.parentSessionId()\n  const parentAgent = host.parentAgent?.() ?? (parentId === undefined ? undefined : agents.get?.(parentId))\n  const parentOwnership = parentAgent === undefined ? {} : { parentAgent }\n  subagentSerial += 1\n  const sessionId = `pi2dsh-sub-${Date.now().toString(36)}-${subagentSerial}`\n  let handle\n  let initialRestrictionDispose: (() => void) | undefined\n  try {\n    // A Pi model object on the options routes the child agent: DSH's\n    // agentOptions carry the provider route and model id the child's loop\n    // will call (reviewer sessions, model division of labor).\n    const requestedModel = options.model as { provider?: unknown, id?: unknown } | undefined\n    // Pi's createAgentSession carries the caller's behavior contract on two\n    // public surfaces: a plain systemPrompt option, or a ResourceLoader whose\n    // getSystemPrompt() yields the override (guardian builds its reviewer\n    // this way: DefaultResourceLoader with systemPromptOverride). An override\n    // REPLACES the host's default prompt in Pi, and appendSystemPrompt\n    // entries follow it.\n    const loader = options.resourceLoader as {\n      getSystemPrompt?(): string | undefined\n      getAppendSystemPrompt?(): string[]\n    } | undefined\n    const overrideText = typeof options.systemPrompt === 'string' && options.systemPrompt.length > 0\n      ? options.systemPrompt\n      : (typeof loader?.getSystemPrompt === 'function' ? loader.getSystemPrompt() : undefined)\n    const appendTexts = (typeof loader?.getAppendSystemPrompt === 'function' ? loader.getAppendSystemPrompt() : [])\n      .filter((text): text is string => typeof text === 'string' && text.length > 0)\n    const systemPrompt = overrideText !== undefined && overrideText.length > 0\n      ? [overrideText, ...appendTexts].join('\\n\\n')\n      : undefined\n    // Pi's tool contract for a child session (core/sdk.ts): `tools` is an\n    // allowlist of NAMES over built-in + extension tools (default: the\n    // built-in coding set), `customTools` are tool OBJECTS registered in\n    // addition, and `noTools` empties the built-in half. On DSH the built-in\n    // half is the host's NATIVE toolset — granted the official way, by\n    // composing the parent's agent preset into the child scope — so a child\n    // bash call runs the host's sandboxed, approval-guarded native tool, not\n    // a bridge copy. The allowlist becomes an official scoped restriction;\n    // scoped registrations (the custom tools) are outside restriction reach,\n    // which is exactly Pi's \"custom tools stay enabled\" semantics.\n    const customTools = Array.isArray(options.customTools) ? [...options.customTools] : []\n    const requestedNames = Array.isArray(options.tools)\n      ? options.tools.filter((name): name is string => typeof name === 'string')\n      : undefined\n    const parentCtx = host.parentAgentContext() as { get?(name: string): unknown } | undefined\n    // The agent-presets roster, when the composition carries one. Reachable\n    // through the parent agent's ctx OR the root ctx — on surfaces that move\n    // every model-facing tool into the roster (dsh-tui disables the host-layer\n    // tool rows), a child that joins no preset resolves its tools against the\n    // EMPTY global layer and runs toolless. So joining is not optional there.\n    const roster = ((typeof parentCtx?.get === 'function' ? parentCtx.get('agentPresets') : undefined)\n      ?? (host.cordis as unknown as { get?(name: string): unknown }).get?.('agentPresets')) as\n      | {\n        composedPreset?(ctx: unknown): string | undefined\n        composeFrom?(child: unknown, parent: unknown): string | undefined\n        resolve?(id?: string): Promise<{ id: string }>\n        mount?(ctx: unknown, id: string): Promise<unknown>\n      }\n      | undefined\n    // The preset recorded on the child's durable header: the parent's standing\n    // preset when it has one, else the roster default — resolved BEFORE create\n    // because the session boundary snapshots `meta` (same rule the official\n    // hosts follow in their composeAgent).\n    let composedPreset = roster?.composedPreset?.(parentCtx)\n    if (roster !== undefined && composedPreset === undefined && typeof roster.resolve === 'function') {\n      composedPreset = await roster.resolve(undefined).then(preset => preset?.id).catch(() => undefined)\n    }\n    const delegated = host.delegatedPolicyOverrides()\n    // Pi's model default for a child session is the CALLER's current model —\n    // an explicit Pi model on the options wins, else the parent's own route\n    // travels. A child agent without any model option fails its first prompt\n    // assembly on {{model}}-keyed sections before a request is even made.\n    const route = typeof requestedModel?.id === 'string' && requestedModel.id.length > 0\n      ? {\n          model: requestedModel.id,\n          ...(typeof requestedModel.provider === 'string' && requestedModel.provider.length > 0\n            ? { provider: requestedModel.provider }\n            : {}),\n        }\n      : host.parentModelRoute?.()\n    const agentOptionsFragment = typeof route?.model === 'string' && route.model.length > 0\n      ? { agentOptions: route }\n      : {}\n    // The creator-exclusive setup runs on the UNPUBLISHED child scope:\n    // everything contributed here is in place before the first assembly\n    // and unwinds with the child. This is the same shape DSH's own\n    // dsh-subagent delegation uses (policy seed → preset composition →\n    // scope contributions). A persisted resume takes the SAME setup — the\n    // reconstructed session keeps its durable header, but the live scoped\n    // world (preset join, restrictions, custom tools, prompt) is fresh.\n    const setup = async (childCtx: { get?(name: string): unknown, agent?: UnknownRecord } & UnknownRecord, agent?: UnknownRecord): Promise<void> => {\n        const childAgent = agent ?? childCtx.agent\n        // 1. Delegation policy, official semantics: the parent's explicit\n        //    sandbox override travels with the child; approval is pinned so\n        //    a headless child never blocks on a dialog nobody is watching.\n        const childSession = childAgent?.session as { append?(type: string, data: unknown): void } | undefined\n        if (typeof childSession?.append === 'function') {\n          if (delegated.sandboxMode !== undefined) {\n            childSession.append('sandbox/mode', { mode: delegated.sandboxMode, source: 'delegation' })\n          }\n          if (delegated.approvalPolicy !== undefined) {\n            childSession.append('approval/policy', { policy: delegated.approvalPolicy, source: 'delegation' })\n          }\n        }\n        // 2. Join the child to a preset composition, in the roster's official\n        //    preference order: inherit the parent's STANDING composition\n        //    (composeFrom — same generation, same tool registrations; how\n        //    DSH's own subagent drivers compose children), else mount the\n        //    roster default (what the official hosts do for a fresh session).\n        //    Only a rosterless deployment composes nothing — there the\n        //    model-facing rows sit in the host composition and the child sees\n        //    them through the global layer. On roster-owned surfaces\n        //    (dsh-tui) skipping this join means a TOOLLESS child, so falling\n        //    through both branches with a roster present is warned loud.\n        if (roster !== undefined) {\n          let joined: string | undefined\n          try {\n            joined = roster.composeFrom?.(childCtx, parentCtx)\n          } catch {\n            joined = undefined\n          }\n          if (joined === undefined && composedPreset !== undefined && typeof roster.mount === 'function') {\n            try {\n              await roster.mount(childCtx, composedPreset)\n              joined = composedPreset\n            } catch {\n              joined = undefined\n            }\n          }\n          if (joined === undefined) {\n            host.cordis.logger?.warn?.(\n              '[pi2dsh] child agent joined no preset composition; on roster-owned surfaces its tools resolve against the empty global layer',\n            )\n          }\n        }\n        // 3. Pi's allowlist / noTools, as the official scoped restriction.\n        //    Pi built-in names map onto the host's native tools (same names,\n        //    with Pi's find/ls served by the host's glob).\n        const restriction = requestedNames !== undefined\n          ? requestedNames.map(nativeToolNameOf)\n          : (options.noTools === 'all' || options.noTools === true || options.noTools === 'builtin' ? [] : undefined)\n        if (restriction !== undefined) {\n          const toolsService = (typeof childCtx.get === 'function' ? childCtx.get('tools') : undefined) as\n            | {\n              restrict(filter: { allow?: readonly string[] }): () => void\n              schemas(scope?: unknown): ReadonlyArray<{ name: string }>\n            }\n            | undefined\n          if (toolsService !== undefined) {\n            // restrict() REFUSES unknown names; a Pi allowlist naming a tool\n            // this host does not carry simply means that tool does not exist\n            // here (Pi's own semantics for a name that matches nothing). The\n            // known set is the CHILD's resolved view — preset-scoped tools\n            // live above the global layer, so the bare schemas() would miss\n            // them on roster-owned surfaces.\n            const known = new Set(childSchemas(toolsService, childAgent).map(schema => schema.name))\n            // Keep the disposer: DSH restrictions INTERSECT, so a later\n            // setActiveToolsByName must retire this one, not stack on it.\n            initialRestrictionDispose = toolsService.restrict({ allow: restriction.filter(name => known.has(name)) })\n          }\n        }\n        // Pi's excludeTools denylist applies AFTER the allowlist. A separate\n        // restriction (they intersect) carries it; the child cannot re-open a\n        // denied name through setActiveToolsByName, matching Pi's ordering.\n        const excluded = Array.isArray(options.excludeTools)\n          ? options.excludeTools.filter((name): name is string => typeof name === 'string')\n          : []\n        if (excluded.length > 0) {\n          const toolsService = (typeof childCtx.get === 'function' ? childCtx.get('tools') : undefined) as\n            | {\n              restrict(filter: { deny?: readonly string[] }): () => void\n              schemas(scope?: unknown): ReadonlyArray<{ name: string }>\n            }\n            | undefined\n          if (toolsService !== undefined) {\n            const known = new Set(childSchemas(toolsService, childAgent).map(schema => schema.name))\n            toolsService.restrict({ deny: excluded.map(nativeToolNameOf).filter(name => known.has(name)) })\n          }\n        }\n        // 4. The custom tools, translated and registered in the child scope.\n        //    `noTools: 'all'` starts with nothing enabled, so they are not\n        //    registered there (Pi's setActiveToolsByName can re-enable the\n        //    built-in half; custom tools under noTools:'all' stay off).\n        if (customTools.length > 0 && options.noTools !== 'all') {\n          host.registerChildTools(childCtx, customTools)\n        }\n        // 5. The caller's system prompt, in place before the first assembly.\n        //    `complete: true` is DSH's sole-prompt-section semantics,\n        //    matching Pi's systemPromptOverride replacing the default.\n        if (systemPrompt !== undefined) {\n          const prompt = (typeof childCtx.get === 'function' ? childCtx.get('systemPrompt') : undefined) as\n            | { section(input: { name: string, order: number, text: string, complete?: boolean }): unknown }\n            | undefined\n          if (prompt === undefined) {\n            throw new Error('pi2dsh: createAgentSession() got a system prompt but the DSH composition has no systemPrompt service to carry it')\n          }\n          prompt.section({ name: 'pi2dsh:subagent-system-prompt', order: -1_000_000, text: systemPrompt, complete: true })\n        }\n      }\n    if (resumeSessionId !== undefined) {\n      if (typeof agents.resume !== 'function') {\n        throw new Error(\n          'pi2dsh: reopening a child conversation needs the DSH agent registry\\'s persisted-resume seam, which this composition does not provide',\n        )\n      }\n      // The durable header (cwd, lineage, preset) is the persisted session's\n      // own; only the live identity and the fresh scoped world are supplied.\n      handle = await agents.resume({ resumeSessionId, ...parentOwnership, ...agentOptionsFragment, setup, ...(options.signal === undefined ? {} : { signal: options.signal }) })\n    } else {\n      handle = await agents.create({\n        sessionId,\n        ...parentOwnership,\n        meta: {\n          cwd: typeof options.cwd === 'string' ? options.cwd : host.cwd(),\n          origin: 'subagent',\n          // DSH's durable recursion budget (childSessionMeta semantics): the\n          // child persists parent depth + 1 so resumed children cannot delegate\n          // as if they were top-level.\n          delegationDepth: host.parentDelegationDepth() + 1,\n          ...(host.parentSessionId() !== undefined ? { parentSession: host.parentSessionId() } : {}),\n          ...(typeof composedPreset === 'string' && composedPreset.length > 0 ? { agentPreset: composedPreset } : {}),\n        },\n        ...agentOptionsFragment,\n        setup,\n        ...(options.signal === undefined ? {} : { signal: options.signal }),\n      })\n    }\n  } catch (error) {\n    if (resumeSessionId !== undefined) {\n      // Distinguish \"the conversation is gone\" from \"this composition cannot\n      // resume\" by DSH's own verdict: after a failed resume, the persistence\n      // list() decides whether the session still exists (the exact check\n      // agent-loop's restoreOrCreateConfigured performs). Only a POSITIVE\n      // \"gone\" retires the archive identity — an absent persistence service\n      // proves nothing and must not destroy a valid token.\n      if (await host.sessionGoneFromPersistence?.(resumeSessionId) === true) {\n        host.discardStaleArchive?.(resumeSessionId)\n        throw new Error(\n          `pi2dsh: child session ${JSON.stringify(resumeSessionId)} no longer exists in the host's session persistence — `\n          + `the conversation is gone and its archive identity has been retired (${error instanceof Error ? error.message : String(error)})`,\n        )\n      }\n      throw new Error(\n        `pi2dsh: reopening child session ${JSON.stringify(resumeSessionId)} failed — this composition may lack session persistence (${error instanceof Error ? error.message : String(error)})`,\n      )\n    }\n    throw new Error(\n      `pi2dsh: native subagent creation failed (${error instanceof Error ? error.message : String(error)})`,\n      { cause: error },\n    )\n  }\n  const tools = [\n    ...(Array.isArray(options.tools) ? options.tools : []),\n    ...(Array.isArray(options.customTools) ? options.customTools : []),\n  ]\n  // DSH identifies session-backed children by ONE durable event appended\n  // inside the child's own log: `subagent/descriptor` (dsh-subagent). Without\n  // it the host's child catalog reports the session as a `diagnostic` row\n  // (\"corrupt\") instead of a child, so nothing can list or reopen it. The\n  // event type is DSH's own — this is the official identity channel, not a\n  // vocabulary of ours.\n  const childSession = (handle.agent as { session?: { append?(type: string, data: unknown): unknown } }).session\n  // A resumed session already carries its descriptor from the original\n  // creation; appending another would duplicate the identity event.\n  if (resumeSessionId === undefined && typeof childSession?.append === 'function') {\n    try {\n      childSession.append('subagent/descriptor', {\n        version: 2,\n        mode: 'continuable',\n        provider: 'pi2dsh',\n        // 'Side: ' is the ecosystem's side-thread marker (better-sidebar's\n        // SIDE_LABEL_PREFIX): a user-initiated side chat is not a delegated\n        // task, and task surfaces filter it out by this prefix.\n        label: `${sideline ? 'Side: ' : ''}${childLabel(options.label, host.packageName)}`,\n      })\n    } catch (error) {\n      // A host without the subagent vocabulary rejects the type; the child\n      // still runs, it just will not be enumerable. Never fatal, never silent.\n      host.cordis.logger?.warn?.(\n        `[pi2dsh] child session could not record its subagent identity: ${error instanceof Error ? error.message : String(error)}`,\n      )\n    }\n  }\n  // Pi's thinkingLevel option is per-child request config; DSH carries it on\n  // the instance's agent/request waterfall, which the adoption below joins the\n  // child to. An explicit 'off' must survive adoption: current DSH adapters\n  // can otherwise apply their own enabled-thinking default.\n  const thinkingLevel = typeof options.thinkingLevel === 'string' ? options.thinkingLevel : undefined\n  host.adoptChildAgent?.(handle.agent, thinkingLevel)\n  // Real Pi loads the child's extension set inside createAgentSession (the\n  // sdk builds a default loader when none is passed and loads everything the\n  // creator's loader admits). The same timing here: the creator-filtered\n  // installed packages mount onto the child agent's own ctx before this call\n  // returns, so their tools exist before the first prompt, and they unwind\n  // with the agent. Per-extension failures never take the child down (Pi's\n  // isolation); bindExtensions reports them to the binding's onError.\n  let extensionFailures: Array<{ name: string, error: string }> = []\n  try {\n    extensionFailures = await host.mountChildExtensions?.(handle.agent, options.resourceLoader) ?? []\n  } catch (error) {\n    extensionFailures = [{ name: 'pi2dsh:child-extensions', error: error instanceof Error ? error.message : String(error) }]\n  }\n  for (const failure of extensionFailures) {\n    const message = `[pi2dsh] child extension ${JSON.stringify(failure.name)} did not mount: ${failure.error}`\n    host.cordis.logger?.warn?.(message)\n    console.warn(message)\n  }\n  const session = new PiBridgedAgentSession(host, handle, tools, thinkingLevel)\n  session.adoptRestriction(initialRestrictionDispose)\n  session.adoptExtensionFailures(extensionFailures)\n  return { session }\n}\n","// Vendored from Pi: packages/coding-agent/src/utils/open-browser.ts\n// (upstream commit 6f707eb36064e82af9c1320a7634f4dfad21049b), logic unchanged.\n//\n// Pi's own login dialog calls this when a flow announces an authorization URL,\n// which is why \"A browser window should open\" is in the text those flows print.\n// The bridge does not run Pi's terminal dialog, so without this the sentence was\n// a lie and the user was left with an unclickable wrapped URL and no way in.\nimport { spawn } from 'node:child_process'\n\n/**\n * Open a URL or file in the platform browser/default handler.\n *\n * This intentionally never invokes a shell. On Windows, do not use\n * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before\n * `start` runs, which would make attacker-controlled URLs injectable.\n * @param target - the URL or file to hand to the platform handler.\n */\nexport function openBrowser(target: string): void {\n  const [cmd, args]: [string, string[]] =\n    process.platform === 'darwin'\n      ? ['open', [target]]\n      : process.platform === 'win32'\n        ? ['rundll32', ['url.dll,FileProtocolHandler', target]]\n        : ['xdg-open', [target]]\n\n  // spawn reports launcher failures (for example, missing xdg-open) via an\n  // error event. Browser launch is best-effort: callers still present the target\n  // to the user, so keep the launcher failure from becoming a process crash.\n  spawn(cmd, args, { stdio: 'ignore', detached: true })\n    .on('error', () => {})\n    .unref()\n}\n","// The browser half's server side: everything pi2dsh puts on DSH's web surface.\n//\n// Pi packages that open a side conversation (pi-btw's `/btw`, and anything\n// else built on `createAgentSession`) get a real DSH child session — visible in\n// the host's own subagent catalog, resumable, continuable. What DSH has no seat\n// for is the SHAPE those packages present in Pi: a focused panel floating over\n// the main conversation, so the side thread is readable without leaving the\n// thread you were in.\n//\n// DSH's browser half does have a seat for exactly that (`shell.overlay`), so\n// the panel is drawn by this package's own client half. Its data does NOT ride\n// DSH's typed Remote system — that is a first-party, code-generated contract —\n// but this package's own route, which is the honest way for an out-of-tree\n// plugin to talk to its own UI.\n//\n// Two kinds of state live here, both keyed by the session they belong to:\n//\n//   threads   — side conversations a Pi package opened (the floating panel)\n//   surfaces  — Pi's presentation calls (status, widget, header, footer, title,\n//               working/thinking chrome). Pi hands these a string or one of its\n//               own components; a component renders to plain text lines through\n//               the bridge's headless pi-tui shims, which is what a browser can\n//               actually show.\n//\n// Nothing here knows about any particular package. A thread is tracked because\n// a Pi package opened a child session; a surface is recorded because a package\n// called a Pi UI method — whatever the package.\nimport type { Context } from '@deepseek-ai/cordis'\nimport { SEED_CARRIER_TAG, type PiBridgedAgentSession } from './subagent-bridge.js'\n\ntype UnknownRecord = Record<string, unknown>\n\n/** One side thread as the panel renders it. */\nexport interface PanelThreadView {\n  /** The child session's id, stable for the life of the thread. */\n  id: string\n  /** Human label, already the one DSH's catalog shows. */\n  label: string\n  /** Pi package that opened it, when known. */\n  package?: string\n  /** Whether the child is mid-turn. */\n  running: boolean\n  messages: Array<{ role: string, text: string }>\n}\n\ninterface TrackedThread {\n  id: string\n  label: string\n  package: string | undefined\n  session: PiBridgedAgentSession\n}\n\n/** Executes one Pi command by its Pi-side name; resolves the notices text. */\nexport type PiCommandRunner = (command: string, args: string) => Promise<string | undefined>\n\n/** Flatten one Pi message's content to the text a panel row shows. */\nfunction messageText(message: UnknownRecord): string {\n  const content = message.content\n  if (typeof content === 'string') return content\n  if (!Array.isArray(content)) return ''\n  const parts: string[] = []\n  for (const block of content as UnknownRecord[]) {\n    // Thinking stays out: the panel is the conversation, not the reasoning\n    // trace, and Pi's own side-conversation UI shows the same.\n    if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)\n    else if (block.type === 'toolCall' && typeof block.name === 'string') parts.push(`[tool: ${block.name}]`)\n  }\n  return parts.join('\\n')\n}\n\n/**\n * Live side threads, keyed by the parent session they belong to.\n *\n * Host-level (one per engine instance, like the provider directory): the panel\n * is one surface, however many Pi packages contribute threads to it.\n */\nexport class BrowserSurfaces {\n  /** Last time a browser client touched the /pi2dsh route (ms epoch). */\n  lastClientContactMs?: number\n\n  readonly #byParent = new Map<string, Map<string, TrackedThread>>()\n  readonly #commandRunners = new Map<string, Map<string, PiCommandRunner>>()\n  // session -> package -> what that package put on screen\n  readonly #surfaces = new Map<string, Map<string, SurfaceView>>()\n  /**\n   * Retained components from `(tui, theme) => Component` factories, keyed by\n   * their slot (session + package + widget key). Retained because the driver\n   * handed to the factory must stay LIVE: requestRender re-renders this\n   * component into its slot for as long as the package holds the handle.\n   * Replacing or clearing the slot disposes the previous component.\n   */\n  readonly #factoryComponents = new Map<string, { render?: (width: number) => unknown, dispose?: () => void }>()\n  // package -> its custom-entry renderer, pulled per request\n  readonly #entrySources = new Map<string, EntrySource>()\n  // session -> the composer text a package asked for, and the live text the\n  // browser last reported. Pi's editor calls are two-way: setEditorText writes,\n  // getEditorText reads what the user actually has.\n  readonly #draftRequests = new Map<string, DraftRequest>()\n  readonly #liveDrafts = new Map<string, string>()\n  readonly #completionSources = new Map<string, CompletionSource>()\n  // A keyed DSH tool view has to be registered under the exact wire name.\n  // The runtime adds only tools from explicitly supported image packages at\n  // package mount, before any call executes; every other tool keeps DSH's own\n  // row unchanged.\n  readonly #imageToolNames = new Set<string>()\n\n  /** Register one known image tool's exact DSH wire name. */\n  registerImageTool(name: string): void {\n    if (name.length > 0) this.#imageToolNames.add(name)\n  }\n\n  /** Exact wire names needing the generic Pi image-result browser view. */\n  imageToolNames(): string[] {\n    return [...this.#imageToolNames]\n  }\n\n  /**\n   * Track one child session under its parent.\n   * @param parentSessionId - the session the panel floats over.\n   * @param thread - the child's identity and live session object.\n   * @returns a disposer that removes the thread from the panel.\n   */\n  track(parentSessionId: string, thread: TrackedThread): () => void {\n    const threads = this.#byParent.get(parentSessionId) ?? new Map<string, TrackedThread>()\n    threads.set(thread.id, thread)\n    this.#byParent.set(parentSessionId, threads)\n    return () => {\n      const live = this.#byParent.get(parentSessionId)\n      if (live === undefined) return\n      live.delete(thread.id)\n      if (live.size === 0) this.#byParent.delete(parentSessionId)\n    }\n  }\n\n  /**\n   * Register the executor for one package's Pi commands on one session, so\n   * product UI (a side-chat window's input, its action buttons) can run the\n   * package's OWN command handlers — the same code path the composer takes.\n   * Generic by construction: the runner closure carries the package runtime;\n   * this registry only routes (session, package) to it.\n   * @param sessionId - the root session the package is mounted for.\n   * @param packageName - the Pi package owning the commands.\n   * @param runner - executes one registered Pi command by its Pi name.\n   * @returns a disposer that unregisters the runner.\n   */\n  registerCommandRunner(sessionId: string, packageName: string, runner: PiCommandRunner): () => void {\n    const runners = this.#commandRunners.get(sessionId) ?? new Map<string, PiCommandRunner>()\n    runners.set(packageName, runner)\n    this.#commandRunners.set(sessionId, runners)\n    return () => {\n      const live = this.#commandRunners.get(sessionId)\n      if (live === undefined) return\n      if (live.get(packageName) === runner) live.delete(packageName)\n      if (live.size === 0) this.#commandRunners.delete(sessionId)\n    }\n  }\n\n  /**\n   * The registered runner for (session, package), when one is mounted.\n   *\n   * An empty sessionId means \"any session where the package is mounted\":\n   * session-free product UI (a Settings page) invoking a package command\n   * whose effect is global state — the handler itself is the package's own\n   * either way, and every mounted copy routes to the same package storage.\n   */\n  commandRunner(sessionId: string, packageName: string): PiCommandRunner | undefined {\n    if (sessionId !== '') return this.#commandRunners.get(sessionId)?.get(packageName)\n    for (const runners of this.#commandRunners.values()) {\n      const runner = runners.get(packageName)\n      if (runner !== undefined) return runner\n    }\n    return undefined\n  }\n\n  /**\n   * The panel's view of one parent session.\n   * @param parentSessionId - session the browser is currently showing.\n   * @returns every side thread opened under it, oldest first.\n   */\n  snapshot(parentSessionId: string): PanelThreadView[] {\n    const threads = this.#byParent.get(parentSessionId)\n    if (threads === undefined) return []\n    return [...threads.values()].map(thread => ({\n      id: thread.id,\n      label: thread.label,\n      ...(thread.package === undefined ? {} : { package: thread.package }),\n      running: (thread.session as unknown as { isStreaming?: boolean }).isStreaming === true,\n      // Seeded entries are the context the package handed the child (pi-btw\n      // starts its thread with the main conversation), not the side exchange.\n      // Showing them would make the panel a copy of the main thread.\n      messages: thread.session.messages\n        .filter(message => !thread.session.isCarriedContext(message as UnknownRecord))\n        // Host instructions and other non-presentational custom messages\n        // remain model context, but their Pi display flag forbids UI rows.\n        .filter(message => (message as UnknownRecord).display !== false)\n        .map(message => ({ role: String((message as UnknownRecord).role ?? ''), text: messageText(message as UnknownRecord) }))\n        // The bridge also re-materializes the seed as ONE durable carrier\n        // message before the first prompt, so it is a real entry the WeakSet\n        // cannot know about — recognised here by the envelope the bridge owns.\n        .filter(entry => !entry.text.startsWith(`<${SEED_CARRIER_TAG}>`))\n        .filter(entry => entry.text.length > 0),\n    }))\n  }\n\n  /**\n   * Pi's `setStatus(key, text)`: one keyed status entry in the status bar.\n   * The key is the entry's identity; passing undefined removes that entry,\n   * exactly like Pi clears one status.\n   * @param sessionId - session the calling agent belongs to.\n   * @param packageName - Pi package making the call, when known.\n   * @param key - the status entry's key.\n   * @param text - the text to show, or undefined to remove the entry.\n   */\n  setStatus(sessionId: string, packageName: string | undefined, key: string, text: unknown): void {\n    if (sessionId.length === 0) return\n    const view = this.#view(sessionId, packageName)\n    const rendered = text === undefined || text === null ? undefined : String(text)\n    if (rendered === undefined || rendered.length === 0) delete view.statuses[key]\n    else view.statuses[key] = rendered\n  }\n\n  /**\n   * Pi's `setWidget(key, content)`: one keyed widget. Only string arrays are\n   * recorded — anything else is ignored exactly like Pi's own rpc mode, where\n   * widgets are transmitted to a host as lines and factory content needs TUI\n   * access the host never provides.\n   * @param sessionId - session the calling agent belongs to.\n   * @param packageName - Pi package making the call, when known.\n   * @param key - the widget's key.\n   * @param content - the widget's lines, or undefined to remove the widget.\n   */\n  setWidget(sessionId: string, packageName: string | undefined, key: string, content: unknown, theme?: unknown): void {\n    if (sessionId.length === 0) return\n    const view = this.#view(sessionId, packageName)\n    // Pi's setWidget is overloaded: lines, or a `(tui, theme) => Component`\n    // factory. Both are rendered here, through the same projection the header\n    // and footer use — a component's contract is `render(width): string[]`, so\n    // there is text to show and nothing has to be invented.\n    //\n    // Pi's own rpc mode drops the factory form, but that host also drops\n    // setFooter and setHeader entirely, and this bridge renders those; matching\n    // rpc mode HERE and exceeding it THERE was the inconsistency. Worse, the\n    // old rule deleted on any non-array: a package that set lines and later\n    // updated with a factory had its widget silently disappear.\n    const slot = `${sessionId}\u0000${packageName ?? 'pi'}\u0000${key}`\n    this.#factoryComponents.get(slot)?.dispose?.()\n    this.#factoryComponents.delete(slot)\n    if (typeof content === 'function') {\n      // The factory receives a REAL tui handle whose requestRender re-renders\n      // the retained component into this widget slot — Pi's own contract.\n      // Passing undefined and relying on the call-site try/catch was NOT a\n      // safe degradation: a factory retains the handle in a closure and calls\n      // it later, far outside any catch, taking that turn's tool call down\n      // with it (pi-lens's lsp_diagnostics on the web surface, 2026-08-27).\n      this.#mountFactory(slot, content as (tui: unknown, theme: unknown) => unknown, theme, text => {\n        const live = this.#view(sessionId, packageName)\n        if (text === undefined) delete live.widgets[key]\n        else live.widgets[key] = text\n      })\n      return\n    }\n    const text = surfaceText(content, theme)\n    if (text === undefined) delete view.widgets[key]\n    else view.widgets[key] = text\n  }\n\n  /**\n   * Mount one `(tui, theme) => Component` factory: run it with a live driver,\n   * render the retained component now, and re-render it into the same slot on\n   * every requestRender. A factory or render that throws leaves the slot\n   * empty — the package's own bug stays its own — but a RETAINED handle keeps\n   * working for the component's lifetime.\n   * @param slot - identity for the retained component (dispose-on-replace).\n   * @param factory - the package's factory, exactly as passed to setWidget.\n   * @param theme - the bridge's headless theme.\n   * @param store - writes rendered text (or undefined to clear) into the slot.\n   */\n  #mountFactory(slot: string, factory: (tui: unknown, theme: unknown) => unknown, theme: unknown, store: (text: string | undefined) => void): void {\n    let component: { render?: (width: number) => unknown, dispose?: () => void } | undefined\n    const render = (): void => {\n      if (component === undefined) return\n      // A handle outlives its component: a package can keep calling\n      // requestRender after its widget was replaced or cleared. A stale\n      // handle must be inert, not resurrect the disposed component's output.\n      if (this.#factoryComponents.get(slot) !== component) return\n      store(surfaceText(component, theme))\n    }\n    const driver = { requestRender: () => { render() } }\n    try {\n      component = factory(driver, theme) as typeof component\n    } catch {\n      store(undefined)\n      return\n    }\n    if (component === null || typeof component?.render !== 'function') {\n      store(undefined)\n      return\n    }\n    this.#factoryComponents.set(slot, component)\n    render()\n  }\n\n  /**\n   * Record one simple presentation call (working chrome, title, header,\n   * footer). The value is a string, a Pi component, a working-indicator\n   * options object, or a header/footer factory; each renders to text here so\n   * the browser half never runs Pi code.\n   * @param sessionId - session the calling agent belongs to.\n   * @param packageName - Pi package making the call, when known.\n   * @param key - which surface.\n   * @param value - the value the package passed; undefined clears it.\n   * @param theme - the bridge's headless theme, for factories that style with it.\n   */\n  setSurface(\n    sessionId: string,\n    packageName: string | undefined,\n    key: SurfaceKey,\n    value: unknown,\n    theme?: unknown,\n  ): void {\n    if (sessionId.length === 0) return\n    const view = this.#view(sessionId, packageName)\n    const text = surfaceText(value, theme)\n    if (text === undefined) delete view.values[key]\n    else view.values[key] = text\n  }\n\n  /**\n   * Pi's `setWorkingVisible`: hide the working chrome without forgetting it.\n   * @param sessionId - session the calling agent belongs to.\n   * @param packageName - Pi package making the call, when known.\n   * @param visible - whether the working chrome should show.\n   */\n  setWorkingVisible(sessionId: string, packageName: string | undefined, visible: boolean): void {\n    if (sessionId.length === 0) return\n    this.#view(sessionId, packageName).workingVisible = visible\n  }\n\n  /**\n   * Register one package's custom-entry renderer.\n   *\n   * Pulled rather than pushed: a renderer's output depends on the session being\n   * looked at, and the package registers once at mount for every session it\n   * will ever be asked about.\n   * @param packageName - owning Pi package.\n   * @param source - called with the session id the browser is showing.\n   * @returns a disposer that unregisters the source.\n   */\n  trackEntries(packageName: string, source: EntrySource): () => void {\n    this.#entrySources.set(packageName, source)\n    return () => { this.#entrySources.delete(packageName) }\n  }\n\n  /**\n   * Custom entries every package renders for one session, in package order.\n   * @param sessionId - session the browser is showing.\n   * @returns rendered entries; a renderer that throws contributes nothing.\n   */\n  entries(sessionId: string): RenderedEntry[] {\n    const out: RenderedEntry[] = []\n    for (const [packageName, source] of this.#entrySources) {\n      try {\n        for (const entry of source(sessionId)) out.push({ ...entry, package: packageName })\n      } catch {\n        // A renderer is the package's own code; one that throws leaves the\n        // conversation intact instead of taking the request down.\n      }\n    }\n    return out\n  }\n\n  /**\n   * Ask the browser to put text in the composer.\n   *\n   * A revision rather than a flag: the seat applies a request once, and the\n   * next call — even with identical text — is a new request rather than a\n   * no-op, which is what a package retrying a paste means.\n   * @param sessionId - session whose composer to write.\n   * @param text - the full next draft.\n   */\n  requestDraft(sessionId: string, text: string): void {\n    if (sessionId.length === 0) return\n    const current = this.#draftRequests.get(sessionId)\n    this.#draftRequests.set(sessionId, { text, rev: (current?.rev ?? 0) + 1 })\n    // Optimistic: a package that writes and immediately reads sees its own\n    // write, exactly as it would in Pi, without waiting for a browser round\n    // trip that may never come (a CLI session has no browser at all).\n    this.#liveDrafts.set(sessionId, text)\n  }\n\n  /**\n   * The pending composer write for one session, if any.\n   * @param sessionId - session the browser is showing.\n   * @returns the request, or undefined when nothing is pending.\n   */\n  draftRequest(sessionId: string): DraftRequest | undefined {\n    return this.#draftRequests.get(sessionId)\n  }\n\n  /**\n   * Record what the composer actually holds, as reported by the browser.\n   * @param sessionId - session the report is about.\n   * @param text - the live draft.\n   */\n  reportDraft(sessionId: string, text: string): void {\n    if (sessionId.length === 0) return\n    this.#liveDrafts.set(sessionId, text)\n  }\n\n  /**\n   * The composer text for one session.\n   * @param sessionId - session to read.\n   * @returns the browser's last report, or the last requested text.\n   */\n  liveDraft(sessionId: string): string {\n    return this.#liveDrafts.get(sessionId) ?? ''\n  }\n\n  /**\n   * Register one package's completion provider.\n   * @param packageName - owning Pi package.\n   * @param source - asked with the trigger character and the typed query.\n   * @returns a disposer that unregisters the source.\n   */\n  trackCompletions(packageName: string, source: CompletionSource): () => void {\n    this.#completionSources.set(packageName, source)\n    return () => { this.#completionSources.delete(packageName) }\n  }\n\n  /**\n   * Completions every package offers for one trigger token.\n   * @param trigger - the trigger character the menu opened on.\n   * @param query - what the user has typed after it.\n   * @returns candidates in package order; a provider that throws contributes none.\n   */\n  async completions(trigger: string, query: string): Promise<CompletionItem[]> {\n    const out: CompletionItem[] = []\n    for (const source of this.#completionSources.values()) {\n      try {\n        out.push(...await source(trigger, query))\n      } catch {\n        // A provider is the package's own code; its failure must not empty the\n        // menu for every other package.\n      }\n    }\n    return out\n  }\n\n  /**\n   * What packages have put on screen for one session.\n   * @param sessionId - session the browser is showing.\n   * @returns one entry per package that has driven a surface, empties dropped.\n   */\n  surfaces(sessionId: string): SurfaceView[] {\n    const bySession = this.#surfaces.get(sessionId)\n    if (bySession === undefined) return []\n    return [...bySession.values()].filter(view => viewHasContent(view))\n  }\n\n  /** Get-or-create one package's view for a session. */\n  #view(sessionId: string, packageName: string | undefined): SurfaceView {\n    const owner = packageName ?? 'pi'\n    const bySession = this.#surfaces.get(sessionId) ?? new Map<string, SurfaceView>()\n    let view = bySession.get(owner)\n    if (view === undefined) {\n      view = {\n        ...(packageName === undefined ? {} : { package: packageName }),\n        values: {},\n        statuses: {},\n        widgets: {},\n        workingVisible: true,\n      }\n      bySession.set(owner, view)\n      this.#surfaces.set(sessionId, bySession)\n    }\n    return view\n  }\n}\n\n/** Whether a view still carries something to show. */\nfunction viewHasContent(view: SurfaceView): boolean {\n  return Object.keys(view.values).length > 0\n    || Object.keys(view.statuses).length > 0\n    || Object.keys(view.widgets).length > 0\n}\n\n/**\n * Presentation slots a Pi package can drive, in DSH's browser shell. The\n * keyed surfaces (status, widget) live on {@link SurfaceView.statuses} and\n * {@link SurfaceView.widgets}; the simple ones live in `values`.\n */\nexport type SurfaceKey =\n  | 'workingMessage' | 'workingIndicator' | 'hiddenThinkingLabel'\n  | 'title' | 'header' | 'footer'\n\n/** One package's presentation state for one session. */\nexport interface SurfaceView {\n  package?: string\n  /** Simple string surfaces: working chrome, transient title, header, footer. */\n  values: Partial<Record<SurfaceKey, string>>\n  /** Pi's `setStatus` entries, keyed by the entry key. */\n  statuses: Record<string, string>\n  /** Pi's `setWidget` entries, keyed by the widget key. */\n  widgets: Record<string, string>\n  /** Pi's setWorkingVisible: false hides the working chrome without clearing it. */\n  workingVisible: boolean\n}\n\n/**\n * Render whatever Pi handed a presentation call into displayable text.\n *\n * Pi's UI methods accept a string, a string array (widget lines), one of its\n * components (`render(width): string[]`), a working-indicator options object\n * (`{ frames?: string[] }`), or a header/footer factory\n * (`(tui, theme) => Component`). Every shape is projected to text here — the\n * pi-tui shims honour `render(width)` headlessly, and a factory is called with\n * the bridge's headless theme (and no TUI, which Pi's own rpc mode never\n * provides either); anything that cannot render leaves the surface empty\n * rather than faking output.\n * @param value - the value the package passed.\n * @param theme - the bridge's headless theme, for factories that style with it.\n * @returns the text to show, or undefined to clear the surface.\n */\nexport function surfaceText(value: unknown, theme?: unknown): string | undefined {\n  if (value === undefined || value === null) return undefined\n  if (typeof value === 'string') return value.length === 0 ? undefined : value\n  if (Array.isArray(value)) {\n    // A widget's lines: the exact shape Pi's rpc mode transmits to a host.\n    const text = value.map(String).join('\\n').trimEnd()\n    return text.length === 0 ? undefined : text\n  }\n  const record = value as { render?: (width: number) => unknown; frames?: unknown }\n  if (typeof record.render === 'function') {\n    try {\n      const lines = record.render(80)\n      const text = (Array.isArray(lines) ? lines : [lines]).map(line => String(line)).join('\\n').trimEnd()\n      return text.length === 0 ? undefined : text\n    } catch {\n      // A component that throws while rendering is the package's own bug; the\n      // surface simply stays empty rather than taking the turn down with it.\n      return undefined\n    }\n  }\n  if (Array.isArray(record.frames)) {\n    // WorkingIndicatorOptions: frames animate in Pi; a browser shows the\n    // honest static projection of the package's own frames. An empty array\n    // hides the indicator, exactly as Pi defines it.\n    const text = record.frames.map(String).join('').trimEnd()\n    return text.length === 0 ? undefined : text\n  }\n  if (typeof value === 'function') {\n    // A header/footer factory: `(tui, theme) => Component`. Called without a\n    // TUI — factories that need one degrade to an empty surface, matching\n    // Pi's rpc mode, where no factory runs at all.\n    try {\n      return surfaceText((value as (tui: unknown, theme: unknown) => unknown)(undefined, theme), theme)\n    } catch {\n      return undefined\n    }\n  }\n  const text = String(value)\n  return text.length === 0 || text === '[object Object]' ? undefined : text\n}\n\n/** One custom entry a package rendered for the conversation. */\nexport interface RenderedEntry {\n  id: string\n  customType: string\n  package?: string\n  text: string\n}\n\n/** One pending composer write, with the revision the browser acknowledges. */\nexport interface DraftRequest {\n  text: string\n  rev: number\n}\n\n/** One completion a Pi provider offered for a trigger token. */\nexport interface CompletionItem {\n  value: string\n  label: string\n  description?: string\n}\n\n/** A package's completion provider, asked with the token the user is typing. */\nexport type CompletionSource = (trigger: string, query: string) => Promise<CompletionItem[]>\n\n/** A package's renderer, pulled at snapshot time for the session on screen. */\nexport type EntrySource = (sessionId: string) => RenderedEntry[]\n\ninterface WebServerLike {\n  register(route: { kind: string, path: string, handler: (req: UnknownRecord, res: UnknownRecord) => Promise<void> }): () => void\n}\n\n/**\n * Serve the browser half's own read route on the host's web server.\n *\n * One prefix, one GET, one payload: the client half polls it for the session\n * it is showing and gets every surface at once.\n * A composition with no web server (the CLI profile) simply has no panel, which\n * is the correct outcome rather than an error — the side conversation itself\n * still runs, and the host's subagent catalog still lists it.\n * @param ctx - the mounting context.\n * @param registry - live thread registry to read from.\n * @returns whether the route was registered.\n */\n/**\n * Short, clickable stand-ins for the authorization URLs a login flow announces.\n *\n * An OAuth authorize URL is 400 characters of query string. Putting it in a\n * dialog produces six wrapped lines with the question buried under them, and a\n * link that long is unusable even when the surface makes it clickable. These\n * are the short links shown instead; hitting one redirects to the real address.\n */\nconst pendingAuthorizations = new Map<string, string>()\n\n/**\n * Publish a short link for one authorization URL.\n * @param url - the address the flow wants the user to open.\n * @returns the path to show, or undefined when the URL is not http(s).\n */\nexport function publishAuthorization(url: string): string | undefined {\n  if (!/^https?:\\/\\//u.test(url)) return undefined\n  const token = Math.random().toString(36).slice(2, 10)\n  pendingAuthorizations.set(token, url)\n  // One login at a time in practice; keep the map from growing without bound.\n  if (pendingAuthorizations.size > 8) {\n    const oldest = pendingAuthorizations.keys().next().value\n    if (oldest !== undefined) pendingAuthorizations.delete(oldest)\n  }\n  return `/pi2dsh/authorize/${token}`\n}\n\n/**\n * Retire a published link when its flow is over.\n *\n * A finished (or superseded) flow's address still resolves at the provider, and\n * following it produces a callback the flow that is now listening cannot match\n * — the provider answers \"State mismatch\", which reads like a bug in the login\n * rather than a link that has expired. Saying so is the honest answer.\n * @param path - what {@link publishAuthorization} returned.\n */\nexport function revokeAuthorization(path: string): void {\n  pendingAuthorizations.delete(path.slice('/pi2dsh/authorize/'.length))\n}\n\n/**\n * Structured data the runtime can serve to product-layer UI (dsh-x's MCP tab).\n * The registry stays generic: these are injected by the runtime, which owns\n * the semantics (session cwd, the MCP config layers, the write discipline).\n */\nexport interface BrowserSurfaceHooks {\n  mcpState?(session: string): Promise<unknown>\n  mcpAction?(session: string, server: string, disabled: boolean, scope: 'project' | 'global'): Promise<unknown>\n  /** The Models-page login card's read face: OAuth providers + the one in-flight flow. */\n  loginState?(): Promise<unknown>\n  /** The card's writes: begin/answer/cancel/dismiss/signout, all host-level. */\n  loginAction?(action: string, provider: string, value: string): Promise<unknown>\n}\n\nexport function registerBrowserSurfaceRoute(ctx: Context, registry: BrowserSurfaces, hooks?: BrowserSurfaceHooks): boolean {\n  const web = (ctx as unknown as { get(name: string): unknown }).get('webServer') as WebServerLike | undefined\n  if (web === undefined || typeof web.register !== 'function') return false\n  ctx.effect(() => web.register({\n    kind: 'prefix',\n    path: '/pi2dsh',\n    handler: async (req: UnknownRecord, res: UnknownRecord) => {\n      const response = res as unknown as {\n        writeHead(status: number, headers?: Record<string, string>): void\n        end(body?: string): void\n      }\n      const method = String(req.method ?? 'GET')\n      const url = new URL(String(req.url ?? '/'), 'http://pi2dsh.invalid')\n      // Any request through this prefix is a live browser client talking to\n      // the presentation layer. hasUI's 0.1.2-line answer reads this stamp:\n      // question answerers there are per-connected-client waterfall relays,\n      // so \"a browser is polling us\" is the signal we actually own.\n      registry.lastClientContactMs = Date.now()\n      // The one write the browser half performs: reporting what the user has\n      // actually typed, so a package's getEditorText reads the composer rather\n      // than only its own last write.\n      if (method === 'POST' && url.pathname === '/pi2dsh/editor-draft') {\n        const chunks: Buffer[] = []\n        const body = await new Promise<string>((settle) => {\n          const stream = req as unknown as { on(event: string, handler: (chunk?: unknown) => void): void }\n          stream.on('data', chunk => chunks.push(Buffer.from(chunk as Uint8Array)))\n          stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))\n        })\n        try {\n          const payload = JSON.parse(body || '{}') as { session?: unknown, draft?: unknown }\n          if (typeof payload.session === 'string' && typeof payload.draft === 'string') {\n            registry.reportDraft(payload.session, payload.draft)\n          }\n        } catch {\n          // A malformed report changes nothing; the composer is still the\n          // browser's, and the next report supersedes this one.\n        }\n        response.writeHead(204)\n        response.end()\n        return\n      }\n      // The MCP tab's structured faces, when the runtime provided them: the\n      // configured-server view and the disable/enable toggle.\n      if (url.pathname === '/pi2dsh/mcp-state' && (method === 'GET' || method === 'HEAD')) {\n        if (hooks?.mcpState === undefined) {\n          response.writeHead(404)\n          response.end()\n          return\n        }\n        const body = JSON.stringify(await hooks.mcpState(url.searchParams.get('session') ?? ''))\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })\n        response.end(method === 'HEAD' ? undefined : body)\n        return\n      }\n      if (url.pathname === '/pi2dsh/mcp-action' && method === 'POST') {\n        if (hooks?.mcpAction === undefined) {\n          response.writeHead(404)\n          response.end()\n          return\n        }\n        const chunks: Buffer[] = []\n        const raw = await new Promise<string>((settle) => {\n          const stream = req as unknown as { on(event: string, handler: (chunk?: unknown) => void): void }\n          stream.on('data', chunk => chunks.push(Buffer.from(chunk as Uint8Array)))\n          stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))\n        })\n        let outcome: unknown\n        try {\n          const payload = JSON.parse(raw || '{}') as { session?: unknown, server?: unknown, disabled?: unknown, scope?: unknown }\n          if (typeof payload.session !== 'string' || typeof payload.server !== 'string' || typeof payload.disabled !== 'boolean') {\n            throw new TypeError('mcp-action needs { session, server, disabled }')\n          }\n          const scope = payload.scope === 'global' ? 'global' : 'project'\n          outcome = await hooks.mcpAction(payload.session, payload.server, payload.disabled, scope)\n        } catch (error) {\n          response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })\n          response.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))\n          return\n        }\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })\n        response.end(JSON.stringify(outcome ?? { ok: true }))\n        return\n      }\n      // The Models-page login card's faces (alpha `settings.models.provider-card`\n      // seat): same hook pattern as the MCP tab — the runtime owns login\n      // semantics (the /login spine), this layer only carries bytes.\n      if (url.pathname === '/pi2dsh/login-state' && (method === 'GET' || method === 'HEAD')) {\n        if (hooks?.loginState === undefined) {\n          response.writeHead(404)\n          response.end()\n          return\n        }\n        const body = JSON.stringify(await hooks.loginState())\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })\n        response.end(method === 'HEAD' ? undefined : body)\n        return\n      }\n      if (url.pathname === '/pi2dsh/login-action' && method === 'POST') {\n        if (hooks?.loginAction === undefined) {\n          response.writeHead(404)\n          response.end()\n          return\n        }\n        const chunks: Buffer[] = []\n        const raw = await new Promise<string>((settle) => {\n          const stream = req as unknown as { on(event: string, handler: (chunk?: unknown) => void): void }\n          stream.on('data', chunk => chunks.push(Buffer.from(chunk as Uint8Array)))\n          stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))\n        })\n        let outcome: unknown\n        try {\n          const payload = JSON.parse(raw || '{}') as { action?: unknown, provider?: unknown, value?: unknown }\n          if (typeof payload.action !== 'string') throw new TypeError('login-action needs { action }')\n          outcome = await hooks.loginAction(\n            payload.action,\n            typeof payload.provider === 'string' ? payload.provider : '',\n            typeof payload.value === 'string' ? payload.value : '',\n          )\n        } catch (error) {\n          response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })\n          response.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))\n          return\n        }\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })\n        response.end(JSON.stringify(outcome ?? { ok: true }))\n        return\n      }\n      // Product UI running a Pi package's own command (a side-chat window's\n      // input is \"/btw <text>\" by other means): routed to the runner the\n      // package's runtime registered for this session, so the exact handler\n      // the composer would call runs — flags, session reuse, model fallback\n      // and all. No handler is reimplemented here.\n      if (url.pathname === '/pi2dsh/pi-command' && method === 'POST') {\n        const chunks: Buffer[] = []\n        const raw = await new Promise<string>((settle) => {\n          const stream = req as unknown as { on(event: string, handler: (chunk?: unknown) => void): void }\n          stream.on('data', chunk => chunks.push(Buffer.from(chunk as Uint8Array)))\n          stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))\n        })\n        try {\n          const payload = JSON.parse(raw || '{}') as { session?: unknown, package?: unknown, command?: unknown, args?: unknown }\n          if (typeof payload.session !== 'string' || typeof payload.package !== 'string' || typeof payload.command !== 'string') {\n            throw new TypeError('pi-command needs { session, package, command }')\n          }\n          const runner = registry.commandRunner(payload.session, payload.package)\n          if (runner === undefined) {\n            response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' })\n            response.end(JSON.stringify({ error: `no ${payload.package} command runner mounted for this session` }))\n            return\n          }\n          const notice = await runner(payload.command, typeof payload.args === 'string' ? payload.args : '')\n          response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })\n          response.end(JSON.stringify({ ok: true, ...(notice === undefined ? {} : { notice }) }))\n        } catch (error) {\n          response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })\n          response.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))\n        }\n        return\n      }\n      if (method !== 'GET' && method !== 'HEAD') {\n        response.writeHead(405)\n        response.end()\n        return\n      }\n      if (url.pathname.startsWith('/pi2dsh/authorize/')) {\n        const target = pendingAuthorizations.get(url.pathname.slice('/pi2dsh/authorize/'.length))\n        if (target === undefined) {\n          response.writeHead(404)\n          response.end('this login link has expired')\n          return\n        }\n        response.writeHead(302, { location: target, 'cache-control': 'no-store' })\n        response.end()\n        return\n      }\n      if (url.pathname === '/pi2dsh/completions') {\n        const items = await registry.completions(\n          url.searchParams.get('trigger') ?? '@',\n          url.searchParams.get('query') ?? '',\n        )\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })\n        response.end(JSON.stringify({ items }))\n        return\n      }\n      if (url.pathname === '/pi2dsh/image-tool-names') {\n        response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })\n        response.end(method === 'HEAD' ? undefined : JSON.stringify({ names: registry.imageToolNames() }))\n        return\n      }\n      if (url.pathname !== '/pi2dsh/browser-state') {\n        response.writeHead(404)\n        response.end()\n        return\n      }\n      const session = url.searchParams.get('session') ?? ''\n      const body = JSON.stringify(session === ''\n        ? { threads: [], surfaces: [], entries: [] }\n        : {\n          threads: registry.snapshot(session),\n          surfaces: registry.surfaces(session),\n          entries: registry.entries(session),\n          ...(registry.draftRequest(session) === undefined ? {} : { draft: registry.draftRequest(session) }),\n        })\n      response.writeHead(200, {\n        'content-type': 'application/json; charset=utf-8',\n        // The panel polls; a cached answer would freeze the thread mid-turn.\n        'cache-control': 'no-store',\n      })\n      response.end(method === 'HEAD' ? undefined : body)\n    },\n  }), 'pi2dsh: browser-state route')\n  return true\n}\n","// @ts-nocheck — vendored Pi source; checked upstream under Pi's own tsconfig.\n//\n// Vendored byte-identical from Pi (`packages/ai/src/utils/validation.ts`),\n// the argument gate Pi's own agent loop runs before every tool execution\n// (`packages/agent/src/agent-loop.ts`). It COERCES first — a model that emits\n// \"3\" for a number parameter, or an explicit null on an optional property,\n// is met the way Pi meets it — then checks, and throws Pi's own formatted\n// violation text, which is what the model reads and retries against.\n//\n// DSH validates too, but only checks: it never coerces. So neither side's\n// behavior is Pi's for a Pi tool, and running neither (what this bridge did)\n// is worse than either — the tool's own code silently received a string where\n// its schema says number.\n//\n// The `Tool`/`ToolCall` types are restated locally; upstream imports them from\n// pi-ai's types module.\nimport { Compile } from \"typebox/compile\";\nimport type { TLocalizedValidationError } from \"typebox/error\";\nimport { Value } from \"typebox/value\";\ninterface Tool {\n\tname: string;\n\tparameters: unknown;\n}\n\ninterface ToolCall {\n\tname: string;\n\targuments: unknown;\n}\n\nconst validatorCache = new WeakMap<object, ReturnType<typeof Compile>>();\nconst TYPEBOX_KIND = Symbol.for(\"TypeBox.Kind\");\n\ninterface JsonSchemaObject {\n\ttype?: string | string[];\n\tproperties?: Record<string, JsonSchemaObject>;\n\trequired?: string[];\n\titems?: JsonSchemaObject | JsonSchemaObject[];\n\tadditionalProperties?: boolean | JsonSchemaObject;\n\tallOf?: JsonSchemaObject[];\n\tanyOf?: JsonSchemaObject[];\n\toneOf?: JsonSchemaObject[];\n}\n\nfunction getSchemaTypes(schema: JsonSchemaObject): string[] {\n\tif (typeof schema.type === \"string\") {\n\t\treturn [schema.type];\n\t}\n\tif (Array.isArray(schema.type)) {\n\t\treturn schema.type.filter((type): type is string => typeof type === \"string\");\n\t}\n\treturn [];\n}\n\nfunction matchesJsonType(value: unknown, type: string): boolean {\n\tswitch (type) {\n\t\tcase \"number\":\n\t\t\treturn typeof value === \"number\";\n\t\tcase \"integer\":\n\t\t\treturn typeof value === \"number\" && Number.isInteger(value);\n\t\tcase \"boolean\":\n\t\t\treturn typeof value === \"boolean\";\n\t\tcase \"string\":\n\t\t\treturn typeof value === \"string\";\n\t\tcase \"null\":\n\t\t\treturn value === null;\n\t\tcase \"array\":\n\t\t\treturn Array.isArray(value);\n\t\tcase \"object\":\n\t\t\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getSubSchemaValidator(schema: JsonSchemaObject): ReturnType<typeof Compile> | undefined {\n\ttry {\n\t\treturn getValidator(schema as Tool[\"parameters\"]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction coercePrimitiveByType(value: unknown, type: string): unknown {\n\tswitch (type) {\n\t\tcase \"number\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isFinite(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"integer\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isInteger(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"boolean\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof value === \"string\") {\n\t\t\t\tif (value === \"true\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === \"false\") {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"number\") {\n\t\t\t\tif (value === 1) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"string\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tif (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\t\t\treturn String(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"null\": {\n\t\t\tif (value === \"\" || value === 0 || value === false) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tdefault:\n\t\t\treturn value;\n\t}\n}\n\nfunction applySchemaObjectCoercion(value: Record<string, unknown>, schema: JsonSchemaObject): void {\n\tconst properties = schema.properties;\n\tconst definedKeys = new Set<string>(properties ? Object.keys(properties) : []);\n\n\tif (properties) {\n\t\tfor (const [key, propertySchema] of Object.entries(properties)) {\n\t\t\tif (!(key in value)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(value[key], propertySchema);\n\t\t}\n\t}\n\n\tif (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n\t\tfor (const [key, propertyValue] of Object.entries(value)) {\n\t\t\tif (definedKeys.has(key)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);\n\t\t}\n\t}\n}\n\nfunction applySchemaArrayCoercion(value: unknown[], schema: JsonSchemaObject): void {\n\tif (Array.isArray(schema.items)) {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tconst itemSchema = schema.items[index];\n\t\t\tif (!itemSchema) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], itemSchema);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (schema.items && typeof schema.items === \"object\") {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], schema.items);\n\t\t}\n\t}\n}\n\nfunction coerceWithUnionSchema(value: unknown, schemas: JsonSchemaObject[]): unknown {\n\tfor (const schema of schemas) {\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(value)) {\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tfor (const schema of schemas) {\n\t\tconst candidate = structuredClone(value);\n\t\tconst coerced = coerceWithJsonSchema(candidate, schema);\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(coerced)) {\n\t\t\treturn coerced;\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction coerceWithJsonSchema(value: unknown, schema: JsonSchemaObject): unknown {\n\tlet nextValue = value;\n\n\tif (Array.isArray(schema.allOf)) {\n\t\tfor (const nested of schema.allOf) {\n\t\t\tnextValue = coerceWithJsonSchema(nextValue, nested);\n\t\t}\n\t}\n\n\tif (Array.isArray(schema.anyOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.anyOf);\n\t}\n\n\tif (Array.isArray(schema.oneOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.oneOf);\n\t}\n\n\tconst schemaTypes = getSchemaTypes(schema);\n\tconst matchesUnionMember =\n\t\tschemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));\n\tif (schemaTypes.length > 0 && !matchesUnionMember) {\n\t\tfor (const schemaType of schemaTypes) {\n\t\t\tconst candidate = coercePrimitiveByType(nextValue, schemaType);\n\t\t\tif (candidate !== nextValue) {\n\t\t\t\tnextValue = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\n\t\tschemaTypes.includes(\"object\") &&\n\t\ttypeof nextValue === \"object\" &&\n\t\tnextValue !== null &&\n\t\t!Array.isArray(nextValue)\n\t) {\n\t\tapplySchemaObjectCoercion(nextValue as Record<string, unknown>, schema);\n\t}\n\n\tif (schemaTypes.includes(\"array\") && Array.isArray(nextValue)) {\n\t\tapplySchemaArrayCoercion(nextValue, schema);\n\t}\n\n\treturn nextValue;\n}\n\nfunction normalizeOptionalNulls(value: unknown, schema: JsonSchemaObject): void {\n\tif (Array.isArray(value)) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst itemSchema = schema.items[index];\n\t\t\t\tif (itemSchema) normalizeOptionalNulls(value[index], itemSchema);\n\t\t\t}\n\t\t} else if (schema.items) {\n\t\t\tfor (const item of value) normalizeOptionalNulls(item, schema.items);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null || !schema.properties) return;\n\n\tconst object = value as Record<string, unknown>;\n\tconst required = new Set(schema.required ?? []);\n\tfor (const [key, propertySchema] of Object.entries(schema.properties)) {\n\t\tif (!(key in object)) continue;\n\t\tif (\n\t\t\tobject[key] === null &&\n\t\t\t!required.has(key) &&\n\t\t\ttypeof (propertySchema as { $ref?: unknown }).$ref !== \"string\" &&\n\t\t\tgetSubSchemaValidator(propertySchema)?.Check(null) === false\n\t\t) {\n\t\t\tdelete object[key];\n\t\t} else {\n\t\t\tnormalizeOptionalNulls(object[key], propertySchema);\n\t\t}\n\t}\n}\n\nfunction getValidator(schema: Tool[\"parameters\"]): ReturnType<typeof Compile> {\n\tconst key = schema as object;\n\tconst cached = validatorCache.get(key);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\tconst validator = Compile(schema);\n\tvalidatorCache.set(key, validator);\n\treturn validator;\n}\n\nfunction formatValidationPath(error: TLocalizedValidationError): string {\n\tif (error.keyword === \"required\") {\n\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\tconst requiredProperty = requiredProperties?.[0];\n\t\tif (requiredProperty) {\n\t\t\tconst basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\t\t\treturn basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n\t\t}\n\t}\n\tconst path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\treturn path || \"root\";\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n * @param tools Array of tool definitions\n * @param toolCall The tool call from the LLM\n * @returns The validated arguments\n * @throws Error if tool is not found or validation fails\n */\nexport function validateToolCall(tools: Tool[], toolCall: ToolCall): any {\n\tconst tool = tools.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolCall.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolCall);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n * @param tool The tool definition with TypeBox schema\n * @param toolCall The tool call from the LLM\n * @returns The validated (and potentially coerced) arguments\n * @throws Error with formatted message if validation fails\n */\nexport function validateToolArguments(tool: Tool, toolCall: ToolCall): any {\n\tconst args = structuredClone(toolCall.arguments);\n\tnormalizeOptionalNulls(args, tool.parameters as JsonSchemaObject);\n\tValue.Convert(tool.parameters, args);\n\n\tconst validator = getValidator(tool.parameters);\n\tif (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {\n\t\tconst coerced = coerceWithJsonSchema(args, tool.parameters as JsonSchemaObject);\n\t\tif (coerced !== args) {\n\t\t\tif (typeof args === \"object\" && args !== null && typeof coerced === \"object\" && coerced !== null) {\n\t\t\t\tfor (const key of Object.keys(args)) {\n\t\t\t\t\tdelete args[key];\n\t\t\t\t}\n\t\t\t\tObject.assign(args, coerced);\n\t\t\t} else {\n\t\t\t\treturn validator.Check(coerced) ? coerced : args;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (validator.Check(args)) {\n\t\treturn args;\n\t}\n\n\tconst errors =\n\t\tvalidator\n\t\t\t.Errors(args)\n\t\t\t.map((error) => `  - ${formatValidationPath(error)}: ${error.message}`)\n\t\t\t.join(\"\\n\") || \"Unknown validation error\";\n\n\tconst errorMessage = `Validation failed for tool \"${toolCall.name}\":\\n${errors}\\n\\nReceived arguments:\\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n\n\tthrow new Error(errorMessage);\n}\n","// Model Runtime Bridge: Pi's model surface projected onto DSH's llm service.\n//\n//  - catalog: llm.listProviders() × listModels() cached as Pi Model objects,\n//    refreshed on the `llm/adapters-updated` registry notification\n//  - designated-model calls: pi-ai complete()/stream() run on ctx.llm.stream()\n//    with two-way message conversion (both vocabularies are pi-ai lineage —\n//    DSH's official adapter package is dsh-llm-pi-ai)\n//  - per-agent model/thinking switches stay on the `agent/request` waterfall\n//    (wired in runtime.ts); this module owns catalog + call translation\n//\n// Compositions without a mounted llm service keep the empty-catalog semantics:\n// every entry point degrades to the previous explicit behavior.\n\nimport {\n  CONTEXT_WINDOW_EXCEEDED_CODE,\n  EMPTY_RESPONSE_CODE,\n  isContextWindowExceededError,\n  isQuotaExceededError,\n  LlmError,\n  QUOTA_EXCEEDED_CODE,\n} from '@deepseek-ai/dsh-llm'\nimport { AssistantMessageEventStream } from './compat/vendor/pi-ai-event-stream.js'\nimport { isContextOverflow } from './compat/vendor/pi-ai-overflow.js'\n\ntype UnknownRecord = Record<string, unknown>\n\nexport interface DshLlmLike {\n  listProviders(): Array<{ id: string, name: string }>\n  listModels(provider: string): Promise<UnknownRecord[]>\n  resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<UnknownRecord>\n  stream(options: UnknownRecord): AsyncIterable<UnknownRecord>\n}\n\nexport function llmOf(ctx: unknown): DshLlmLike | undefined {\n  try {\n    const service = (ctx as { get(name: string): unknown }).get('llm')\n    if (typeof (service as DshLlmLike | undefined)?.stream !== 'function') return undefined\n    return service as DshLlmLike\n  } catch {\n    return undefined\n  }\n}\n\n// ---- catalog ---------------------------------------------------------------\n\n/** A DSH catalog entry in Pi's Model shape. */\nexport interface PiModelShape {\n  id: string\n  name: string\n  provider: string\n  api: string\n  input: Array<'text' | 'image'>\n  reasoning: boolean\n  contextWindow?: number\n  maxTokens?: number\n  [key: string]: unknown\n}\n\n// Pi Model fields a Pi-native route's directory entry may carry through the\n// DSH directory. Restoring them keeps the projection an EXACT Pi Model —\n// packages that read baseUrl or branch on api never see that a DSH\n// directory sat in between.\nconst PI_MODEL_PASSTHROUGH_FIELDS = [\n  'baseUrl', 'cost', 'contextWindow', 'maxTokens', 'samplingParams', 'thinkingLevelMap', 'compat', 'headers',\n] as const\n\nfunction piModelFromInfo(info: UnknownRecord): PiModelShape {\n  const modalities = Array.isArray(info.inputModalities) ? info.inputModalities as string[] : undefined\n  const carried: UnknownRecord = {}\n  for (const field of PI_MODEL_PASSTHROUGH_FIELDS) {\n    if (info[field] !== undefined) carried[field] = info[field]\n  }\n  return {\n    ...carried,\n    id: String(info.id ?? ''),\n    name: String(info.name ?? info.id ?? ''),\n    provider: String(info.provider ?? ''),\n    // A Pi-native route's entry names its real wire protocol; a DSH-owned\n    // adapter's does not, and its transport stays behind the route.\n    api: typeof info.api === 'string' ? info.api : 'faux',\n    input: modalities === undefined\n      ? ['text']\n      : modalities.filter((m): m is 'text' | 'image' => m === 'text' || m === 'image'),\n    reasoning: typeof info.reasoning === 'boolean'\n      ? info.reasoning\n      : (info as { reasoning?: unknown }).reasoning !== undefined,\n  }\n}\n\n/**\n * Cached projection of DSH's advisory model catalog as Pi Model objects.\n * `refresh()` re-reads providers and models; the runtime subscribes it to\n * `llm/adapters-updated`. Reads are synchronous (Pi's getAll contract).\n */\nexport class ModelCatalog {\n  #llm: DshLlmLike | undefined\n  #models: PiModelShape[] = []\n  #resolved = new Map<string, PiModelShape>()\n  #refreshing: Promise<void> | undefined\n\n  constructor(llm: DshLlmLike | undefined) {\n    this.#llm = llm\n  }\n\n  get present(): boolean {\n    return this.#llm !== undefined\n  }\n\n  all(): PiModelShape[] {\n    return [...this.#models]\n  }\n\n  find(provider: string, modelId: string): PiModelShape | undefined {\n    return this.#resolved.get(`${provider}\u0000${modelId}`)\n      ?? this.#models.find(model => model.provider === provider && model.id === modelId)\n  }\n\n  refresh(): Promise<void> {\n    if (this.#llm === undefined) return Promise.resolve()\n    this.#refreshing ??= this.#refreshOnce().finally(() => { this.#refreshing = undefined })\n    return this.#refreshing\n  }\n\n  async #refreshOnce(): Promise<void> {\n    const llm = this.#llm\n    if (llm === undefined) return\n    const next: PiModelShape[] = []\n    for (const provider of llm.listProviders()) {\n      try {\n        for (const info of await llm.listModels(provider.id)) {\n          next.push(piModelFromInfo({ ...info, provider: provider.id }))\n        }\n      } catch {\n        // A provider whose adapter fails to list keeps its previous entries out;\n        // the catalog is advisory and absence must not break registration.\n      }\n    }\n    // DSH splits one model's description across two seams: the listing carries\n    // directory membership, while capacity for an exact provider/model route\n    // (context window, output cap, reasoning) comes from resolveModelInfo. Pi\n    // has no such split — every plugin reads ONE Model object and sizes its own\n    // work off `contextWindow`. So the projection joins them here: without it a\n    // host-configured route reaches packages with the field simply missing, and\n    // Pi-side code that reads it falls back to a guessed default (Pi's own\n    // compaction: `model.contextWindow || 128000`) against a window that can be\n    // an order of magnitude off in either direction.\n    const resolved = new Map<string, PiModelShape>()\n    await Promise.all(next.map(async (model) => {\n      const exact = await this.#resolveExact(model.provider, model.id)\n      if (exact === undefined) return\n      if (exact.contextWindow !== undefined) model.contextWindow = exact.contextWindow\n      if (exact.maxTokens !== undefined) model.maxTokens = exact.maxTokens\n      model.reasoning = exact.reasoning\n      if (exact.thinkingLevelMap !== undefined) model.thinkingLevelMap = exact.thinkingLevelMap\n      resolved.set(`${model.provider}\u0000${model.id}`, model)\n    }))\n    this.#models = next\n    // Capacity is configuration, and configuration is what just changed: the\n    // per-route cache is rebuilt with the listing rather than outliving it.\n    this.#resolved = resolved\n  }\n\n  /** Exact-route metadata (context window, reasoning efforts), cached per route. */\n  async resolve(provider: string, modelId: string): Promise<PiModelShape | undefined> {\n    const key = `${provider}\u0000${modelId}`\n    const cached = this.#resolved.get(key)\n    if (cached !== undefined) return cached\n    const model = await this.#resolveExact(provider, modelId)\n    if (model !== undefined) this.#resolved.set(key, model)\n    return model\n  }\n\n  /** One exact resolve, uncached: the two callers own their own caching. */\n  async #resolveExact(provider: string, modelId: string): Promise<PiModelShape | undefined> {\n    if (this.#llm === undefined) return undefined\n    try {\n      const info = await this.#llm.resolveModelInfo(provider, modelId)\n      const model = piModelFromInfo(info)\n      const context = (info as { context?: { contextWindow?: unknown } }).context\n      if (typeof context?.contextWindow === 'number') model.contextWindow = context.contextWindow\n      const defaultMaxTokens = (info as { defaultMaxTokens?: unknown }).defaultMaxTokens\n      if (typeof defaultMaxTokens === 'number') model.maxTokens = defaultMaxTokens\n      const reasoning = (info as { reasoning?: { efforts?: unknown[] } }).reasoning\n      const efforts = new Set((reasoning?.efforts ?? []).map(effort => String((effort as { id?: unknown })?.id ?? '')))\n      model.reasoning = [...efforts].some(effort => effort !== '' && effort !== 'off')\n      if (efforts.size > 0) {\n        model.thinkingLevelMap = Object.fromEntries(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']\n          .map(level => [level, efforts.has(level) ? level : null]))\n      }\n      return model\n    } catch {\n      return undefined\n    }\n  }\n}\n\n// ---- message conversion ----------------------------------------------------\n\ninterface PiContentBlock { type: string, [key: string]: unknown }\n\nfunction dshBlocksFromPiContent(content: unknown): UnknownRecord[] {\n  if (typeof content === 'string') return content.length > 0 ? [{ type: 'text', text: content }] : []\n  if (!Array.isArray(content)) return []\n  const blocks: UnknownRecord[] = []\n  for (const block of content as PiContentBlock[]) {\n    if (block.type === 'text' && typeof block.text === 'string') {\n      blocks.push({ type: 'text', text: block.text })\n    } else if (block.type === 'thinking' && typeof block.thinking === 'string') {\n      blocks.push({ type: 'reasoning', text: block.thinking })\n    } else if (block.type === 'toolCall') {\n      blocks.push({\n        type: 'tool-call',\n        id: String(block.id ?? ''),\n        name: String(block.name ?? ''),\n        arguments: typeof block.arguments === 'string' ? block.arguments : JSON.stringify(block.arguments ?? {}),\n      })\n    } else if (block.type === 'image') {\n      // DSH image blocks require attachment refs owned by the attachment\n      // service; a hand-built pi-ai call has none, so the reference is\n      // preserved textually instead of being silently dropped.\n      blocks.push({ type: 'text', text: `[image omitted by pi2dsh: ${String(block.mimeType ?? 'unknown media type')}]` })\n    }\n  }\n  return blocks\n}\n\n/**\n * Pi request context → DSH GenerateOptions parts. System prompt moves to the\n * dedicated slot; toolResult messages become DSH tool-result user messages.\n */\nexport function piRequestToDshMessages(context: UnknownRecord): { system?: string, messages: UnknownRecord[] } {\n  const messages: UnknownRecord[] = []\n  const source = Array.isArray(context.messages) ? context.messages as UnknownRecord[] : []\n  for (const message of source) {\n    if (message.role === 'user') {\n      messages.push({ role: 'user', content: dshBlocksFromPiContent(message.content), source: { kind: 'user' } })\n    } else if (message.role === 'assistant') {\n      messages.push({\n        role: 'assistant',\n        content: dshBlocksFromPiContent(message.content),\n        source: {\n          kind: 'model',\n          provider: String(message.provider ?? context.provider ?? 'pi2dsh'),\n          model: String(message.model ?? context.model ?? 'unknown'),\n        },\n      })\n    } else if (message.role === 'toolResult') {\n      messages.push({\n        role: 'user',\n        content: [{\n          type: 'tool-result',\n          toolCallId: String(message.toolCallId ?? ''),\n          content: dshBlocksFromPiContent(message.content),\n          isError: message.isError === true,\n        }],\n        source: { kind: 'tool', callId: String(message.toolCallId ?? '') },\n      })\n    }\n  }\n  const system = typeof context.systemPrompt === 'string' && context.systemPrompt.length > 0\n    ? context.systemPrompt\n    : undefined\n  return { ...(system === undefined ? {} : { system }), messages }\n}\n\nfunction piUsageFromDsh(usage: UnknownRecord | undefined): UnknownRecord {\n  const input = Number((usage as { inputTokens?: unknown } | undefined)?.inputTokens ?? 0)\n  const output = Number((usage as { outputTokens?: unknown } | undefined)?.outputTokens ?? 0)\n  const cacheRead = Number((usage as { cacheReadTokens?: unknown } | undefined)?.cacheReadTokens ?? 0)\n  const cacheWrite = Number((usage as { cacheWriteTokens?: unknown } | undefined)?.cacheWriteTokens ?? 0)\n  return {\n    input, output, cacheRead, cacheWrite,\n    totalTokens: input + output + cacheRead + cacheWrite,\n    cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n  }\n}\n\nfunction piStopReason(finish: UnknownRecord | undefined): string {\n  switch ((finish as { kind?: unknown } | undefined)?.kind) {\n    case 'stop': return 'stop'\n    case 'max-tokens': return 'length'\n    case 'tool-calls': return 'toolUse'\n    case 'aborted': return 'aborted'\n    default: return 'error'\n  }\n}\n\n// ---- designated-model call bridge ------------------------------------------\n\nexport interface PiStreamRequest {\n  model: UnknownRecord\n  context: UnknownRecord\n  options?: UnknownRecord | undefined\n}\n\n/**\n * Run one hand-built pi-ai model call on DSH's native llm service, translating\n * the chunk stream into Pi's AssistantMessageEventStream vocabulary.\n */\nexport function streamViaDshLlm(llm: DshLlmLike, request: PiStreamRequest): AssistantMessageEventStream {\n  const stream = new AssistantMessageEventStream() as AssistantMessageEventStream & {\n    push(event: UnknownRecord): void\n  }\n  const provider = String(request.model.provider ?? '')\n  const modelId = String(request.model.id ?? '')\n  const { system, messages } = piRequestToDshMessages({ ...request.context, provider, model: modelId })\n  const options = request.options ?? {}\n  const generate: UnknownRecord = {\n    provider,\n    model: modelId,\n    messages,\n    ...(system === undefined ? {} : { system }),\n    ...(Array.isArray(request.context.tools) ? { tools: normalizeToolSchemas(request.context.tools as UnknownRecord[]) } : {}),\n    ...(typeof options.maxTokens === 'number' ? { maxTokens: options.maxTokens } : {}),\n    ...(typeof options.temperature === 'number' ? { temperature: options.temperature } : {}),\n    ...(typeof options.reasoning === 'string' ? { reasoningEffort: options.reasoning } : {}),\n    ...(options.signal instanceof AbortSignal ? { signal: options.signal } : {}),\n  }\n\n  void (async () => {\n    const partial: UnknownRecord = { role: 'assistant', content: [], provider, model: modelId, api: 'faux' }\n    const content = partial.content as PiContentBlock[]\n    let usage: UnknownRecord | undefined\n    stream.push({ type: 'start', partial })\n    try {\n      for await (const chunk of llm.stream(generate)) {\n        const type = String(chunk.type ?? '')\n        const index = Number(chunk.index ?? 0)\n        if (type === 'block-start') {\n          const blockType = String(chunk.blockType ?? '')\n          if (blockType === 'text') {\n            content[index] = { type: 'text', text: '' }\n            stream.push({ type: 'text_start', contentIndex: index, partial })\n          } else if (blockType === 'reasoning') {\n            content[index] = { type: 'thinking', thinking: '' }\n            stream.push({ type: 'thinking_start', contentIndex: index, partial })\n          } else if (blockType === 'tool-call') {\n            content[index] = { type: 'toolCall', id: '', name: '', arguments: undefined, partialJson: '' }\n            stream.push({ type: 'toolcall_start', contentIndex: index, partial })\n          }\n        } else if (type === 'text-delta') {\n          const block = content[index] ??= { type: 'text', text: '' }\n          block.text = String(block.text ?? '') + String(chunk.text ?? '')\n          stream.push({ type: 'text_delta', contentIndex: index, delta: String(chunk.text ?? ''), partial })\n        } else if (type === 'reasoning-delta') {\n          const block = content[index] ??= { type: 'thinking', thinking: '' }\n          block.thinking = String(block.thinking ?? '') + String(chunk.text ?? '')\n          stream.push({ type: 'thinking_delta', contentIndex: index, delta: String(chunk.text ?? ''), partial })\n        } else if (type === 'tool-call-delta') {\n          const block = content[index] ??= { type: 'toolCall', id: '', name: '', arguments: undefined, partialJson: '' }\n          if (chunk.id !== undefined) block.id = String(chunk.id)\n          if (chunk.name !== undefined) block.name = String(chunk.name)\n          block.partialJson = String(block.partialJson ?? '') + String(chunk.argumentsDelta ?? '')\n          stream.push({ type: 'toolcall_delta', contentIndex: index, delta: String(chunk.argumentsDelta ?? ''), partial })\n        } else if (type === 'block-end') {\n          const block = chunk.block as UnknownRecord | undefined\n          const blockType = String(block?.type ?? '')\n          if (blockType === 'text') {\n            content[index] = { type: 'text', text: String(block?.text ?? '') }\n            stream.push({ type: 'text_end', contentIndex: index, content: String(block?.text ?? ''), partial })\n          } else if (blockType === 'reasoning') {\n            content[index] = { type: 'thinking', thinking: String(block?.text ?? '') }\n            stream.push({ type: 'thinking_end', contentIndex: index, content: String(block?.text ?? ''), partial })\n          } else if (blockType === 'tool-call') {\n            let parsed: unknown\n            try { parsed = JSON.parse(String(block?.arguments ?? '{}')) } catch { parsed = {} }\n            content[index] = { type: 'toolCall', id: String(block?.id ?? ''), name: String(block?.name ?? ''), arguments: parsed }\n            stream.push({ type: 'toolcall_end', contentIndex: index, toolCall: content[index], partial })\n          }\n        } else if (type === 'usage') {\n          usage = piUsageFromDsh(chunk.usage as UnknownRecord | undefined)\n        } else if (type === 'finish') {\n          const finish = chunk.reason as UnknownRecord | undefined\n          const stopReason = piStopReason(finish)\n          if (stopReason === 'error' || stopReason === 'aborted') {\n            const failure = (finish as { failure?: { message?: unknown } } | undefined)?.failure\n            const error = {\n              type: 'error' as const,\n              reason: stopReason === 'aborted' ? 'aborted' : 'error',\n              error: new Error(String(failure?.message ?? `model call failed (${stopReason})`)),\n            }\n            stream.push({ ...error, partial })\n            return\n          }\n          const message: UnknownRecord = {\n            role: 'assistant',\n            content: content.filter(block => block !== undefined),\n            provider, model: modelId, api: 'faux',\n            ...(usage === undefined ? {} : { usage }),\n            stopReason,\n            timestamp: Date.now(),\n          }\n          stream.push({ type: 'done', reason: stopReason, message })\n          return\n        }\n      }\n      // Stream ended without a finish chunk — surface it as an error, never a\n      // fabricated completion.\n      stream.push({ type: 'error', reason: 'error', error: new Error('pi2dsh: DSH llm stream ended without a finish chunk'), partial })\n    } catch (error) {\n      stream.push({ type: 'error', reason: 'error', error: error instanceof Error ? error : new Error(String(error)), partial })\n    }\n  })()\n\n  return stream\n}\n\nfunction normalizeToolSchemas(tools: UnknownRecord[]): UnknownRecord[] {\n  return tools.map(tool => ({\n    name: String(tool.name ?? ''),\n    description: String(tool.description ?? ''),\n    parameters: (tool.parameters ?? tool.inputSchema ?? { type: 'object', properties: {} }) as UnknownRecord,\n  }))\n}\n\n// ---- reverse conversion (DSH request → Pi request, Pi events → DSH chunks) --\n// Used by the provider adapter: a Pi package's own transport serves a DSH\n// llm route, so the DSH loop's vocabulary must arrive in Pi shapes and the\n// package's event stream must leave as DSH chunks.\n\n/** DSH GenerateOptions parts → the Pi request context a provider.stream expects. */\nexport async function dshRequestToPiContext(\n  options: UnknownRecord,\n  attachments?: DshAttachmentsLike,\n): Promise<UnknownRecord> {\n  const piMessages: UnknownRecord[] = []\n  // DSH loop requests carry their system prompt as the leading message;\n  // one-shot and older hosts use options.system. Match the host's pi-ai\n  // adapter: the explicit slot wins, including an intentionally empty slot.\n  const messages = Array.isArray(options.messages) ? options.messages as UnknownRecord[] : []\n  const first = messages[0]\n  const hasExplicitSystem = typeof options.system === 'string'\n  const systemPrompt = hasExplicitSystem\n    ? options.system as string\n    : first?.role === 'system'\n      ? (Array.isArray(first.content) ? first.content as UnknownRecord[] : [])\n        .filter(block => block.type === 'text')\n        .map(block => String(block.text ?? '')).join('\\n')\n      : undefined\n  const history = !hasExplicitSystem && first?.role === 'system' ? messages.slice(1) : messages\n  // Pi's toolResult carries the tool's NAME as well as the call id, but DSH\n  // states the name only once, on the assistant tool-call block that opened\n  // the call. Collect it on the way past so results can name their tool.\n  const toolNamesById = new Map<string, string>()\n  for (const message of history) {\n    if (message.role !== 'assistant') continue\n    for (const block of Array.isArray(message.content) ? message.content as UnknownRecord[] : []) {\n      if (block.type === 'tool-call' && typeof block.id === 'string' && typeof block.name === 'string') {\n        toolNamesById.set(block.id, block.name)\n      }\n    }\n  }\n  for (const message of history) {\n    const content = Array.isArray(message.content) ? message.content as UnknownRecord[] : []\n    const source = message.source as { kind?: unknown } | undefined\n    if (message.role === 'system') {\n      throw new Error('pi2dsh: this Pi provider cannot represent an in-history system prompt update')\n    } else if (message.role === 'user' && source?.kind === 'tool') {\n      const result = content[0] as UnknownRecord | undefined\n      const toolCallId = String(result?.toolCallId ?? '')\n      const toolName = toolNamesById.get(toolCallId)\n      piMessages.push({\n        role: 'toolResult',\n        toolCallId,\n        ...(toolName === undefined ? {} : { toolName }),\n        content: await piContentFromDshBlocks(Array.isArray(result?.content) ? result.content as UnknownRecord[] : [], attachments),\n        isError: result?.isError === true,\n      })\n    } else if (message.role === 'user') {\n      piMessages.push({ role: 'user', content: await piContentFromDshBlocks(content, attachments) })\n    } else if (message.role === 'assistant') {\n      piMessages.push({ role: 'assistant', content: await piContentFromDshBlocks(content, attachments) })\n    }\n  }\n  return {\n    ...(systemPrompt !== undefined && systemPrompt.length > 0 ? { systemPrompt } : {}),\n    messages: piMessages,\n    ...(Array.isArray(options.tools) ? { tools: options.tools } : {}),\n  }\n}\n\n/**\n * An attachment store, as much of it as this bridge uses. Mirrors DSH's\n * `StoredImageAttachment` — `data` is the bytes, `ref` restates the verified\n * media type.\n */\nexport interface DshAttachmentsLike {\n  readImage(ref: unknown): Promise<{ data: Uint8Array, ref?: { mediaType?: unknown } }>\n}\n\n/** Whether any block in this content — including inside a tool result — is an image. */\nexport function blocksContainImage(blocks: unknown): boolean {\n  if (!Array.isArray(blocks)) return false\n  return (blocks as UnknownRecord[]).some(block =>\n    block?.type === 'image' || (block?.type === 'tool-result' && blocksContainImage(block.content)))\n}\n\nasync function piContentFromDshBlocks(\n  blocks: UnknownRecord[],\n  attachments: DshAttachmentsLike | undefined,\n): Promise<UnknownRecord[]> {\n  const out: UnknownRecord[] = []\n  for (const block of blocks) {\n    if (block.type === 'text') out.push({ type: 'text', text: String(block.text ?? '') })\n    else if (block.type === 'reasoning') out.push({ type: 'thinking', thinking: String(block.text ?? '') })\n    else if (block.type === 'tool-call') {\n      let parsed: unknown\n      try { parsed = JSON.parse(String(block.arguments ?? '{}')) } catch { parsed = {} }\n      out.push({ type: 'toolCall', id: String(block.id ?? ''), name: String(block.name ?? ''), arguments: parsed })\n    }\n    else if (block.type === 'image') {\n      // Reached only after the caller confirmed the attachment store; the\n      // guard is here so a future caller cannot silently drop an image.\n      if (attachments === undefined) {\n        throw new LlmError('pi2dsh: image input requires the durable attachment service', 'UNSUPPORTED_CONTENT')\n      }\n      const stored = await attachments.readImage(block.attachment)\n      out.push({\n        type: 'image',\n        data: Buffer.from(stored.data).toString('base64'),\n        mimeType: String(stored.ref?.mediaType ?? (block.attachment as UnknownRecord | undefined)?.mediaType ?? 'image/png'),\n      })\n    }\n  }\n  return out\n}\n\n/**\n * Classify a failure into the code DSH keys retries and error surfaces off.\n *\n * Mirrored from `classifyPiAiError` in DSH's own pi-ai adapter\n * (`packages/llm/llm-pi-ai/src/stream.ts`). That symbol is private to a\n * package whose published tarball ships only `lib/`, so it cannot be imported\n * — but it must not be diverged from either. `RATE_LIMIT`, `SERVER`,\n * `TIMEOUT` and `TRANSPORT` are four of the five codes in DSH's default\n * retryable set, so a code invented here would make every rate limit, every\n * dropped socket and every timeout a Pi provider ever reports permanently\n * non-retryable — dsh-llm-retry would simply not recognize it. The quota and\n * context-window predicates it defers to are DSH's own, imported above.\n * @param message - the provider's failure text.\n * @returns the harness failure code.\n */\nfunction classifyPiFailure(message: string): string {\n  if (/\\b(?:401|403)\\b/.test(message)) return 'AUTH'\n  if (isQuotaExceededError(message)) return QUOTA_EXCEEDED_CODE\n  if (/\\b429\\b|rate.?limit/i.test(message)) return 'RATE_LIMIT'\n  if (/\\b400\\b|invalid.?request/i.test(message)) return 'INVALID_REQUEST'\n  if (/\\b5\\d\\d\\b/.test(message)) return 'SERVER'\n  if (/\\btime(?:d)?\\s*out\\b|timeout/i.test(message)) return 'TIMEOUT'\n  if (/stream ended (?:before|without)\\b/i.test(message)) return 'TRANSPORT'\n  if (/\\b(?:network|connection|socket|fetch)\\b|\\bECONN[A-Z]+\\b/i.test(message)\n    || /\\b(?:other side closed|HTTP2 request did not get a response|WebSocket closed unexpectedly)\\b/i.test(message)\n    || /\\bterminated\\b|premature close/i.test(message)) {\n    return 'TRANSPORT'\n  }\n  return 'PI_AI_ERROR'\n}\n\n/**\n * Pi usage counts → DSH's TokenUsage, mirroring the official adapter's\n * `mapUsage`: Pi reports zeros rather than absence, so the cache fields appear\n * only when non-zero.\n * @param usage - the usage record on a terminal Pi event, if the package sent one.\n * @returns the harness counts.\n */\nfunction piUsageToDsh(usage: UnknownRecord | undefined): UnknownRecord {\n  const cacheRead = Number(usage?.cacheRead ?? 0)\n  const cacheWrite = Number(usage?.cacheWrite ?? 0)\n  return {\n    inputTokens: Number(usage?.input ?? 0),\n    outputTokens: Number(usage?.output ?? 0),\n    ...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),\n    ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),\n  }\n}\n\n/**\n * The assistant message Pi's terminal `error` event carries.\n *\n * Pi delivers failures in-stream as `{ type: 'error', reason, error }` where\n * `error` is an **AssistantMessage**, not an Error — its text lives on\n * `errorMessage`. A package that hands back a bare Error instead is met\n * halfway rather than stringified into \"[object Object]\".\n * @param error - the event's payload.\n * @param fallbackStopReason - the event's own `reason`, used when the payload states none.\n * @returns a message shape the finish-reason mapping can read.\n */\nfunction piErrorPayload(error: unknown, fallbackStopReason: string): UnknownRecord {\n  if (error instanceof Error) return { stopReason: fallbackStopReason, errorMessage: error.message }\n  if (typeof error === 'object' && error !== null) {\n    const record = error as UnknownRecord\n    if (typeof record.stopReason === 'string' || typeof record.errorMessage === 'string') {\n      return { stopReason: fallbackStopReason, ...record }\n    }\n    return { stopReason: fallbackStopReason, errorMessage: JSON.stringify(error) }\n  }\n  return {\n    stopReason: fallbackStopReason,\n    errorMessage: String(error ?? 'pi2dsh: the package reported a stream failure with no detail'),\n  }\n}\n\n/**\n * A terminal Pi assistant message → DSH's finish reason, mirroring the\n * official adapter's `mapStopReason`, including its context-overflow and\n * empty-response detection (the overflow predicate is Pi's own, vendored).\n *\n * One documented deviation: DSH's adapter can trust pi-ai to populate\n * `content`, and reads an empty array as a degenerate empty completion. This\n * bridge takes its events from an arbitrary third-party package, so it also\n * accepts the blocks it actually saw stream past as proof of content. That\n * only ever narrows the error — a stream that produced output is never\n * mislabelled EMPTY_RESPONSE because its terminal event omitted a field.\n * @param message - the assistant message on the `done` or `error` event.\n * @param contextWindow - the model's resolved capacity, for usage-based overflow detection.\n * @param sawContent - whether any content block streamed before the terminal event.\n * @returns the harness finish reason.\n */\nfunction piFinishReason(\n  message: UnknownRecord | undefined,\n  contextWindow: number | undefined,\n  sawContent: boolean,\n): UnknownRecord {\n  const stopReason = String(message?.stopReason ?? 'stop')\n  const errorMessage = typeof message?.errorMessage === 'string' ? message.errorMessage : undefined\n  const model = String(message?.model ?? 'unknown')\n  const usage = message?.usage as UnknownRecord | undefined\n  // Normalized before the predicate reads it: Pi's own check dereferences\n  // `usage.input` unguarded, and a package's terminal event may carry none.\n  const probe = {\n    stopReason,\n    errorMessage,\n    usage: {\n      input: Number(usage?.input ?? 0),\n      output: Number(usage?.output ?? 0),\n      cacheRead: Number(usage?.cacheRead ?? 0),\n      cacheWrite: Number(usage?.cacheWrite ?? 0),\n    },\n  }\n  const overflow = isContextOverflow(probe as never, contextWindow)\n    || (stopReason === 'error' && errorMessage !== undefined && isContextWindowExceededError(errorMessage))\n  if (overflow) {\n    return {\n      kind: 'error',\n      failure: {\n        message: errorMessage ?? `pi2dsh: the package's provider reported context overflow for model \"${model}\"`,\n        code: CONTEXT_WINDOW_EXCEEDED_CODE,\n      },\n    }\n  }\n  switch (stopReason) {\n    case 'length': return { kind: 'max-tokens' }\n    case 'toolUse': return { kind: 'tool-calls' }\n    case 'aborted': return {\n      kind: 'aborted',\n      failure: { message: errorMessage ?? 'pi2dsh: the package aborted the stream', code: 'ABORTED' },\n    }\n    case 'error': {\n      const text = errorMessage ?? 'pi2dsh: the package reported a stream failure'\n      return { kind: 'error', failure: { message: text, code: classifyPiFailure(text) } }\n    }\n    default: {\n      const content = Array.isArray(message?.content) ? message.content : []\n      if (content.length === 0 && !sawContent) {\n        return {\n          kind: 'error',\n          failure: { message: `model \"${model}\" returned a completed response with no content`, code: EMPTY_RESPONSE_CODE },\n        }\n      }\n      return { kind: 'stop' }\n    }\n  }\n}\n\n/**\n * The id and name of the tool call an event is opening or extending. Pi states\n * them on the partial message's content at the event's index, never on the\n * event itself.\n * @param event - a `toolcall_start` or `toolcall_delta` event.\n * @param index - the event's content index.\n * @returns the call's identity, or undefined when the partial states none.\n */\nfunction partialToolCall(event: UnknownRecord, index: number): { id: string, name?: string } | undefined {\n  const partial = event.partial as UnknownRecord | undefined\n  const content = Array.isArray(partial?.content) ? partial.content as UnknownRecord[] : []\n  const block = content[index]\n  if (block === undefined || block.type !== 'toolCall') return undefined\n  const name = typeof block.name === 'string' && block.name.length > 0 ? block.name : undefined\n  return { id: typeof block.id === 'string' ? block.id : '', ...(name === undefined ? {} : { name }) }\n}\n\n/** A Pi AssistantMessageEventStream → DSH StreamChunk sequence. */\nexport async function* piEventsToDshChunks(\n  events: AsyncIterable<UnknownRecord>,\n  contextWindow?: number,\n): AsyncIterable<UnknownRecord> {\n  const openToolCalls = new Map<number, { id: string, name?: string }>()\n  let sawContent = false\n  for await (const event of events) {\n    const type = String(event.type ?? '')\n    const index = Number(event.contentIndex ?? 0)\n    if (type === 'text_start' || type === 'thinking_start' || type === 'toolcall_start') sawContent = true\n    if (type === 'text_start') yield { type: 'block-start', index, blockType: 'text' }\n    else if (type === 'text_delta') yield { type: 'text-delta', index, text: String(event.delta ?? '') }\n    else if (type === 'text_end') yield { type: 'block-end', index, block: { type: 'text', text: String(event.content ?? '') } }\n    else if (type === 'thinking_start') yield { type: 'block-start', index, blockType: 'reasoning' }\n    else if (type === 'thinking_delta') yield { type: 'reasoning-delta', index, text: String(event.delta ?? '') }\n    else if (type === 'thinking_end') yield { type: 'block-end', index, block: { type: 'reasoning', text: String(event.content ?? '') } }\n    else if (type === 'toolcall_start') {\n      // Pi names the call inside the partial message, not on the event, so\n      // read it there and remember it: DSH's deltas must each identify their\n      // call, and an empty id makes a delta unattributable.\n      const opened = partialToolCall(event, index)\n      if (opened !== undefined) openToolCalls.set(index, opened)\n      yield { type: 'block-start', index, blockType: 'tool-call' }\n    }\n    else if (type === 'toolcall_delta') {\n      const open = openToolCalls.get(index) ?? partialToolCall(event, index)\n      yield {\n        type: 'tool-call-delta',\n        index,\n        id: open?.id ?? '',\n        ...(open?.name === undefined ? {} : { name: open.name }),\n        argumentsDelta: String(event.delta ?? ''),\n      }\n    }\n    else if (type === 'toolcall_end') {\n      const call = event.toolCall as UnknownRecord | undefined\n      yield {\n        type: 'block-end', index,\n        block: {\n          type: 'tool-call',\n          id: String(call?.id ?? ''),\n          name: String(call?.name ?? ''),\n          arguments: typeof call?.arguments === 'string' ? call.arguments : JSON.stringify(call?.arguments ?? {}),\n        },\n      }\n    } else if (type === 'done') {\n      const message = event.message as UnknownRecord | undefined\n      yield { type: 'usage', usage: piUsageToDsh(message?.usage as UnknownRecord | undefined) }\n      yield { type: 'finish', reason: piFinishReason(message, contextWindow, sawContent) }\n      return\n    } else if (type === 'error') {\n      // Pi reports failures in-stream rather than by throwing, and the payload\n      // is an assistant message: its text is `errorMessage`, and its stop\n      // reason decides aborted-vs-error. Classifying it is what lets DSH's\n      // retry policy see a rate limit as a rate limit.\n      const message = piErrorPayload(event.error, String(event.reason ?? 'error'))\n      yield { type: 'usage', usage: piUsageToDsh(message.usage as UnknownRecord | undefined) }\n      yield { type: 'finish', reason: piFinishReason(message, contextWindow, sawContent) }\n      return\n    }\n  }\n  // The package's stream ended without a terminal event — the same refusal\n  // DSH's own pi-ai adapter makes, under the same code, rather than inventing\n  // a finish the provider never sent.\n  throw new LlmError(\n    'pi2dsh: the package\\'s provider stream ended without a done or error event',\n    'STREAM_CLOSED',\n  )\n}\n","// Pi provider → DSH llm route. A package-registered Pi provider carrying\n// its own transport (pi-ai createProvider's stream) becomes a real DSH\n// adapter through the public `llm.registerAdapter` seam, so the DSH llm\n// directory is the ONE model directory both worlds read: DSH routes to\n// these models natively (loop, child agents, hand-built calls), and the Pi\n// registry is a projection of that same directory. Credentials resolve per\n// request through Pi's own chain; the key rides the provider's stream\n// options and never enters logs. A provider that only declares a catalog\n// (no stream of its own) is translated into the official llm-pi-ai profile\n// schema, so its protocol, model capabilities and offered compat switches\n// still run through DSH's own transport.\n\nimport { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'\nimport type { PiAiCompatProfile } from '@deepseek-ai/dsh-llm-pi-ai'\nimport { blocksContainImage, dshRequestToPiContext, piEventsToDshChunks, type DshAttachmentsLike, type DshLlmLike } from './model-bridge.js'\nimport { getSupportedThinkingLevels } from './compat/pi-ai.js'\n\ntype UnknownRecord = Record<string, unknown>\n\ninterface PiTransportProvider {\n  // `streamSimple` is the portable half of Pi's Provider contract — required\n  // by the interface, and the only entry point that translates a reasoning\n  // level into each API's own dialect. `stream` takes per-API concrete options\n  // instead, so it is the fallback for a package that hand-rolls a provider\n  // object rather than building one through Pi's factory.\n  streamSimple?(model: UnknownRecord, context: UnknownRecord, options: UnknownRecord): AsyncIterable<UnknownRecord>\n  stream?(model: UnknownRecord, context: UnknownRecord, options: UnknownRecord): AsyncIterable<UnknownRecord>\n  getModels?(): UnknownRecord[]\n  name?: unknown\n  [key: string]: unknown\n}\n\nexport interface ProviderAdapterHost {\n  /** Pi's full credential chain for this provider (stored OAuth → stored key → ambient env). */\n  resolveAuth(): Promise<{ auth?: UnknownRecord } | undefined>\n  /** Wait for an on-demand dynamic catalog refresh when first use names an unseen model. */\n  ensureModel?(modelId: string): Promise<void>\n  warn(message: string): void\n  /**\n   * Pi's payload waterfall for a PACKAGE-OWNED transport. DSH-native adapters\n   * do not expose their body builder and therefore never call this seam.\n   */\n  beforeProviderRequest?(\n    payload: UnknownRecord,\n    request: { provider: string, model: UnknownRecord, sessionId?: string, signal?: AbortSignal },\n  ): Promise<UnknownRecord>\n  /** The durable attachment store, when the composition mounts one. */\n  resolveAttachments?(): DshAttachmentsLike | undefined\n}\n\nexport function providerCarriesTransport(value: UnknownRecord | undefined): value is PiTransportProvider & UnknownRecord {\n  return typeof value?.streamSimple === 'function' || typeof value?.stream === 'function'\n}\n\nfunction providerModels(provider: PiTransportProvider): UnknownRecord[] {\n  try {\n    // Pi accepts BOTH shapes and so must this: pi-ai's createProvider() builds\n    // an object with getModels(), while an extension's own\n    // `pi.registerProvider(id, {...})` config carries a plain `models` array —\n    // which is what the vendor packages do (moonshot, baseten, bailian, …).\n    // Reading only the function form made every one of those declare an empty\n    // catalog, and a route with no models is refused by the host adapter.\n    const models = typeof provider.getModels === 'function' ? provider.getModels() : provider.models\n    return Array.isArray(models) ? models : []\n  } catch {\n    return []\n  }\n}\n\n/**\n * The environment variable a Pi config value names, when that is all it names.\n *\n * Pi's config values (`resolve-config-value.ts`) are `$VAR` / `${VAR}`\n * interpolation, `!command` execution, or a literal. Only a value that is\n * exactly one reference can become a DSH credential reference; a command, a\n * template, or a literal secret must not be copied into settings, which carry\n * references and never values.\n * @param value - the package's declared config value, if it declared one.\n */\nfunction envReferenceOf(value: unknown): string | undefined {\n  if (typeof value !== 'string') return undefined\n  const match = /^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}$|^\\$([A-Za-z_][A-Za-z0-9_]*)$/u.exec(value.trim())\n  return match?.[1] ?? match?.[2]\n}\n\n// Pi Model fields a directory entry may carry (mirrored by the projection's\n// exit restore). A whitelist, never a spread: DSH assigns its own meanings to\n// names like reasoning/context/description, and a Pi-shaped value under those\n// names corrupts the directory contract.\nconst PI_CARRIED_FIELDS = [\n  'api', 'baseUrl', 'cost', 'contextWindow', 'maxTokens', 'samplingParams', 'thinkingLevelMap', 'compat', 'headers',\n] as const\n\n/**\n * Model capabilities DSH asks about by its own names. Shared by the catalog\n * listing and the exact-route resolve deliberately: a capability present in\n * one and absent from the other is how a model silently loses an ability —\n * the host consults the resolve before a request, so a modality declared only\n * in the listing reads as \"text only\" at the moment it matters.\n * @param model - the Pi model descriptor as its package declared it.\n */\nfunction capabilityProjection(model: UnknownRecord): UnknownRecord {\n  if (!Array.isArray(model.input)) return {}\n  const modalities = (model.input as unknown[])\n    .filter((entry): entry is string => entry === 'text' || entry === 'image')\n  return modalities.length === 0 ? {} : { inputModalities: modalities }\n}\n\n/**\n * Pi's reasoning capability, in DSH's shape.\n *\n * The two sides say the same thing differently: Pi carries a `reasoning`\n * boolean plus a `thinkingLevelMap` whose `null` entries mark unsupported\n * levels, while DSH asks an adapter for the selectable efforts directly.\n * Translating is this layer's job — carrying Pi's boolean through under the\n * name `reasoning` would collide with DSH's `{efforts}` object, and carrying\n * nothing (what this bridge did before) leaves every package-registered route\n * with no selectable effort at all, so any reasoning request is rejected.\n *\n * The mapping is DSH's own: its native pi-ai adapter derives efforts from\n * `getSupportedThinkingLevels` and names them the same way, so a route a Pi\n * package registers offers exactly the efforts it would through the host's\n * own adapter. It belongs to the exact-route resolve, not the catalog listing\n * — `reasoning` is a resolved-model field in DSH's contract.\n * @param model - the Pi model descriptor as its package declared it.\n */\nfunction reasoningProjection(model: UnknownRecord): UnknownRecord {\n  if (model.reasoning !== true) return {}\n  const levels = getSupportedThinkingLevels(model as never)\n  if (levels.length === 0) return {}\n  return {\n    reasoning: {\n      efforts: levels.map(level => ({\n        id: level,\n        name: `${level.charAt(0).toUpperCase()}${level.slice(1)}`,\n      })),\n    },\n  }\n}\n\nfunction piCarriedFields(model: UnknownRecord): UnknownRecord {\n  const carried: UnknownRecord = {}\n  for (const field of PI_CARRIED_FIELDS) {\n    if (model[field] !== undefined) carried[field] = model[field]\n  }\n  return carried\n}\n\n/**\n * Wrap one Pi provider object as a DSH LlmAdapter-shaped route handler.\n * Structural typing carries it through `llm.registerAdapter`.\n */\n/** Build the route handler ON the host's own LlmAdapter base class. The\n * 0.1.0-rc.8 dispatch reads adapter methods structurally, so a plain object\n * worked; 0.1.1's dispatch calls `adapter.prepareCall` — a method the BASE\n * CLASS provides (it binds resolveModel + stream into a one-shot prepared\n * call). Because `@deepseek-ai/dsh-llm` is a peer, `LlmAdapter` here is\n * whichever generation the host installed: own-property methods carry the\n * bridge behavior on both, and everything the base contributes on newer\n * generations (prepareCall, retry-policy defaults) is inherited instead of\n * re-implemented. */\nfunction llmAdapterInstance(methods: UnknownRecord): UnknownRecord {\n  const AdapterBase = LlmAdapter as unknown as new () => UnknownRecord\n  return Object.assign(new AdapterBase(), methods)\n}\n\nexport function piProviderDshAdapter(providerId: string, provider: PiTransportProvider, host: ProviderAdapterHost): UnknownRecord {\n  let warnedStop = false\n  const warnStopUnsupported = (): void => {\n    if (warnedStop) return\n    warnedStop = true\n    host.warn(\n      `[pi2dsh] a request to Pi provider ${JSON.stringify(providerId)} carries stop sequences, which Pi models at`\n      + ' no layer — they cannot be forwarded, so the model will not halt on them',\n    )\n  }\n  return llmAdapterInstance({\n    providerInfo: (id: string) => ({ id, name: typeof provider.name === 'string' ? provider.name : id }),\n    providerRetryPolicy: () => undefined,\n    // The directory entry carries the Pi model's OWN fields (api, baseUrl,\n    // cost, sampling params, …) alongside the DSH directory fields, so the\n    // Pi registry projection restores an exact Pi Model and packages never\n    // see that a DSH directory sat in between. Carriage is a whitelist:\n    // names DSH gives its own meaning (reasoning is Pi's boolean but DSH's\n    // {efforts} object) must never ride through with the Pi shape.\n    listModels: async (id: string) => providerModels(provider).map(model => ({\n      ...piCarriedFields(model),\n      ...capabilityProjection(model),\n      provider: id,\n      id: String(model.id ?? ''),\n      name: String(model.name ?? model.id ?? ''),\n    })),\n    resolveModel: async (id: string, modelId: string) => {\n      const known = providerModels(provider).find(model => model.id === modelId)\n      return {\n        ...(known === undefined ? {} : piCarriedFields(known)),\n        ...(known === undefined ? {} : capabilityProjection(known)),\n        ...(known === undefined ? {} : reasoningProjection(known)),\n        provider: id,\n        id: modelId,\n        name: String(known?.name ?? modelId),\n        ...(typeof known?.contextWindow === 'number' ? { context: { contextWindow: known.contextWindow } } : {}),\n        ...(typeof known?.maxTokens === 'number' ? { defaultMaxTokens: known.maxTokens } : {}),\n      }\n    },\n    async *stream(options: UnknownRecord): AsyncIterable<UnknownRecord> {\n      const resolved = await host.resolveAuth()\n      const auth = resolved?.auth as UnknownRecord | undefined\n      const modelId = String(options.model ?? '')\n      // The provider's own model entry keeps its api/thinking metadata; an\n      // unlisted id passes through as pi-ai's advisory-catalog contract allows.\n      let model = providerModels(provider).find(entry => entry.id === modelId)\n      if (model === undefined && host.ensureModel !== undefined) {\n        await host.ensureModel(modelId)\n        model = providerModels(provider).find(entry => entry.id === modelId)\n      }\n      model ??= { id: modelId, provider: providerId }\n      // Images are read through the attachment service, exactly as DSH's own\n      // pi-ai adapter reads them — and refused under DSH's own code when they\n      // cannot be. Dropping them silently (what this bridge did) sends the\n      // model a request about an image it was never given, and the answer\n      // reads as a model failure rather than a missing capability.\n      const messages = Array.isArray(options.messages) ? options.messages as UnknownRecord[] : []\n      const carriesImage = messages.some(message => blocksContainImage(message.content))\n      if (carriesImage) {\n        const declared = Array.isArray(model.input) ? model.input as unknown[] : []\n        if (!declared.includes('image')) {\n          throw new LlmError(`pi2dsh: model \"${modelId}\" does not declare image input`, 'UNSUPPORTED_CONTENT')\n        }\n      }\n      const attachments = carriesImage ? host.resolveAttachments?.() : undefined\n      if (carriesImage && attachments === undefined) {\n        throw new LlmError('pi2dsh: image input requires the durable attachment service', 'UNSUPPORTED_CONTENT')\n      }\n      const piContext = await dshRequestToPiContext(options, attachments)\n      const effort = typeof options.reasoningEffort === 'string' ? options.reasoningEffort : undefined\n      const piOptions: UnknownRecord = {\n        ...(auth?.apiKey === undefined ? {} : { apiKey: auth.apiKey }),\n        ...(auth?.baseUrl === undefined ? {} : { baseUrl: auth.baseUrl }),\n        ...(auth?.headers === undefined ? {} : { headers: auth.headers }),\n        ...(options.signal instanceof AbortSignal ? { signal: options.signal } : {}),\n        ...(typeof options.maxTokens === 'number' ? { maxTokens: options.maxTokens } : {}),\n        ...(typeof options.temperature === 'number' ? { temperature: options.temperature } : {}),\n        // DSH stamps the session so an adapter can map it to model-hidden\n        // transport metadata; Pi spells the same field the same way, and its\n        // providers use it for prompt-cache affinity and request routing.\n        ...(typeof options.sessionId === 'string' ? { sessionId: options.sessionId } : {}),\n        // Pi's standard transports invoke onPayload after constructing the\n        // exact HTTP body and before fetch(). That is the only honest place to\n        // implement before_provider_request. It is available here because\n        // THIS adapter is wrapping a Pi package's own transport; a native DSH\n        // adapter still has no equivalent public hook and remains unsupported.\n        ...(host.beforeProviderRequest === undefined ? {} : {\n          onPayload: (payload: UnknownRecord) => host.beforeProviderRequest!(payload, {\n            provider: providerId,\n            model,\n            ...(typeof options.sessionId === 'string' ? { sessionId: options.sessionId } : {}),\n            ...(options.signal instanceof AbortSignal ? { signal: options.signal } : {}),\n          }),\n        }),\n        // The effort the user picked, under the name Pi's PORTABLE entry point\n        // reads. Two reasons it is not the per-API `reasoningEffort`:\n        //\n        //  - `reasoningEffort` exists only on the two OpenAI-family APIs, so\n        //    on an anthropic or google route the chosen effort would be an\n        //    unrecognized option — selected, yet silently inert.\n        //  - `off` is a level Pi lists for every reasoning model, so it is a\n        //    level the user can pick. It has to be sent as ABSENCE: the string\n        //    reads as truthy on the OpenAI-compatible path, which would turn\n        //    thinking on for the one choice that means turn it off. Omitting\n        //    the field is exactly what Pi's own streamSimple does with it.\n        ...(effort === undefined || effort === 'off' ? {} : { reasoning: effort }),\n      }\n      // The capacity travels with the stream because two of the three\n      // context-overflow signals are usage-based: the providers that accept an\n      // oversized request and answer normally, or truncate it and stop on\n      // `length`, say nothing an error string could be matched against.\n      const contextWindow = typeof model.contextWindow === 'number' ? model.contextWindow : undefined\n      // Pi models no stop sequences at any layer, so a request carrying them\n      // cannot be served faithfully — and dropping them silently changes what\n      // the model returns. Said once per route, not once per request.\n      if (Array.isArray(options.stop) && options.stop.length > 0) warnStopUnsupported()\n      if (typeof provider.streamSimple === 'function') {\n        yield* piEventsToDshChunks(provider.streamSimple(model, piContext, piOptions), contextWindow)\n        return\n      }\n      // A hand-rolled provider object carrying only `stream`: that entry point\n      // takes per-API options, so the level is spelled the way the\n      // OpenAI-family APIs read it. `off` stays absent for the same reason.\n      const { reasoning, ...rest } = piOptions\n      yield* piEventsToDshChunks(\n        provider.stream!(model, piContext, reasoning === undefined ? rest : { ...rest, reasoningEffort: reasoning }),\n        contextWindow,\n      )\n    },\n  })\n}\n\n// ---- image-admission companion route ---------------------------------------\n\nconst IMAGE_OMITTED_TEXT = '[image attachment omitted: the selected model reads text only]'\n\nconst imageNoticeText = (path: string | undefined): string => path === undefined\n  ? IMAGE_OMITTED_TEXT\n  : `[image attached at ${path} — the selected model reads text only; use an image-capable tool to view it]`\n\n// Replace image blocks with an explicit text notice, recursing into\n// tool-result content the way DSH's contentHasImage does. The original\n// route's adapter rejects image content loudly (llm-deepseek throws\n// UNSUPPORTED_CONTENT), so the companion must hand it text-only — and a\n// visible notice, never a silent drop, keeps the model aware something was\n// there. When the attachment can be materialized to a file, the notice\n// carries its path (Pi's own image vocabulary is inline-or-path, and a path\n// lets the model reach the image through any path-taking tool); in the\n// vision-bridge composition the image's ANALYSIS additionally arrives\n// through the turn's entering messages.\nasync function textOnlyBlocks(\n  blocks: UnknownRecord[],\n  materialize: (attachment: UnknownRecord) => Promise<string | undefined>,\n): Promise<UnknownRecord[]> {\n  const out: UnknownRecord[] = []\n  for (const block of blocks) {\n    if (block.type === 'image') {\n      const attachment = block.attachment\n      const path = typeof attachment === 'object' && attachment !== null\n        ? await materialize(attachment as UnknownRecord)\n        : undefined\n      out.push({ type: 'text', text: imageNoticeText(path) })\n    } else if (block.type === 'tool-result' && Array.isArray(block.content)) {\n      out.push({ ...block, content: await textOnlyBlocks(block.content as UnknownRecord[], materialize) })\n    } else {\n      out.push(block)\n    }\n  }\n  return out\n}\n\nasync function textOnlyMessages(\n  messages: UnknownRecord[],\n  materialize: (attachment: UnknownRecord) => Promise<string | undefined>,\n): Promise<UnknownRecord[]> {\n  return Promise.all(messages.map(async message => Array.isArray(message.content)\n    ? { ...message, content: await textOnlyBlocks(message.content as UnknownRecord[], materialize) }\n    : message))\n}\n\nexport interface CompanionRouteOptions {\n  /** The existing DSH route this companion forwards to. */\n  originalId: string\n  /** Model ids to admit images for; absent = every model of the route. */\n  imageModels?: Set<string>\n  llm: DshLlmLike\n  /**\n   * Give a stored image attachment a filesystem path (cached per attachment).\n   * Absent or failing, the text notice simply omits the path.\n   */\n  materializeImage?: (attachment: UnknownRecord) => Promise<string | undefined>\n}\n\n/**\n * A DSH route that admits images on behalf of a text-only route — the\n * single-directory answer to host configuration declaring\n * `input: [\"text\", \"image\"]` for models of a route this bridge does not own.\n * The companion honestly declares image input (so the host's admission and\n * model-switch checks pass), replaces image blocks with an explicit notice,\n * and forwards every call to the original route. It never carries a wire\n * transport of its own; the images themselves are served by whatever vision\n * extension handles the turn's entering messages.\n */\nexport function imageAdmissionCompanionAdapter(options: CompanionRouteOptions): UnknownRecord {\n  const { originalId, llm } = options\n  const admits = (modelId: string): boolean => options.imageModels === undefined || options.imageModels.has(modelId)\n  const materialize = options.materializeImage ?? (async () => undefined)\n  const admitImage = (info: UnknownRecord, id: string): UnknownRecord => {\n    const modalities = Array.isArray(info.inputModalities) ? (info.inputModalities as string[]).slice() : ['text']\n    if (!modalities.includes('image')) modalities.push('image')\n    return { ...info, provider: id, inputModalities: modalities }\n  }\n  return llmAdapterInstance({\n    providerInfo: (id: string) => {\n      const origin = llm.listProviders().find(provider => provider.id === originalId)\n      return { id, name: `${origin?.name ?? originalId} + Vision Bridge` }\n    },\n    providerRetryPolicy: () => undefined,\n    // The directory face mirrors the original route's own entries — the\n    // service layer has already normalized them, so this is a DSH→DSH\n    // carriage, not a cross-vocabulary one. Only the models the user\n    // declared image input for are listed; others stay on the original.\n    listModels: async (id: string) => (await llm.listModels(originalId))\n      .filter(model => admits(String(model.id)))\n      .map(model => admitImage(model, id)),\n    resolveModel: async (id: string, modelId: string) => {\n      const info = await llm.resolveModelInfo(originalId, modelId)\n      return admits(modelId) ? admitImage(info, id) : { ...info, provider: id }\n    },\n    async *stream(streamOptions: UnknownRecord): AsyncIterable<UnknownRecord> {\n      yield* llm.stream({\n        ...streamOptions,\n        provider: originalId,\n        ...(Array.isArray(streamOptions.messages)\n          ? { messages: await textOnlyMessages(streamOptions.messages as UnknownRecord[], materialize) }\n          : {}),\n      })\n    },\n  })\n}\n\nexport interface RegisterPiProviderRouteOptions {\n  llm: {\n    /** DSH returns a disposer carrying `replace`; older fakes return the bare disposer. */\n    registerAdapter(providers: string[], adapter: unknown): (() => void) & { replace?(providers: string[]): void }\n  } | undefined\n  providerId: string\n  provider: UnknownRecord\n  host: ProviderAdapterHost\n  /** The bridge's own context: the settings seam first, a plugin mount as fallback. */\n  ctx?: { plugin(plugin: unknown, config?: unknown): unknown, get?(name: string): unknown }\n}\n\n/**\n * A registered route's disposer, plus the ability to announce it again.\n *\n * A package's model list is not always known when the route is registered:\n * gateway discovery needs a credential, and a credential may only arrive later\n * (a `/login` mid-session). DSH publishes `llm/adapters-updated` when a route\n * set is committed, and every directory observer — the browser's model picker\n * included — refreshes on exactly that event. So a later discovery needs the\n * route ANNOUNCED again, or the models exist and nobody looks.\n */\nexport interface PiRouteHandle {\n  (): void\n  /** Re-commit this route so directory observers re-read its models. */\n  reannounce?(): void\n}\n\n\n/** A wire protocol DSH's official adapter can serve, or undefined. */\nfunction protocolOf(value: unknown): string | undefined {\n  return typeof value === 'string' && DSH_PROTOCOLS.has(value) ? value : undefined\n}\n\n// What a route profile may name. A protocol outside this set is not a\n// translation failure — it is a route the official adapter cannot serve, and\n// omitting it lets the adapter say so about the route rather than rejecting\n// the whole settings section over one key.\nconst DSH_PROTOCOLS = new Set(['openai-completions', 'openai-responses', 'anthropic-messages'])\n// The modalities and thinking-format spellings the profile schema accepts.\n// A Pi model may carry others; a value outside the set is dropped rather than\n// forwarded, because one unknown spelling rejects the entire section.\nconst DSH_MODALITIES = new Set(['text', 'image'])\nconst DSH_THINKING_FORMATS = new Set([\n  'openai', 'deepseek', 'openrouter', 'together', 'zai', 'qwen',\n  'chat-template', 'qwen-chat-template', 'string-thinking', 'ant-ling',\n])\nconst DSH_MAX_TOKENS_FIELDS = new Set(['max_completion_tokens', 'max_tokens'])\nconst DSH_CACHE_CONTROL_FORMATS = new Set(['anthropic'])\nconst DSH_CHAT_TEMPLATE_VARS = new Set(['thinking.enabled', 'thinking.effort'])\n\nconst COMPLETIONS = new Set(['openai-completions'])\nconst RESPONSES = new Set(['openai-responses'])\nconst ANTHROPIC = new Set(['anthropic-messages'])\nconst COMPLETIONS_AND_RESPONSES = new Set(['openai-completions', 'openai-responses'])\nconst ALL_DSH_PROTOCOLS = new Set(DSH_PROTOCOLS)\n\n// `satisfies Record<keyof ...>` is the drift gate. A later DSH release that\n// offers another profile field makes this build fail until the field is\n// deliberately assigned to the protocols that may consume it.\nconst DSH_COMPAT_FIELD_PROTOCOLS = {\n  supportsStore: COMPLETIONS,\n  supportsDeveloperRole: COMPLETIONS_AND_RESPONSES,\n  supportsReasoningEffort: COMPLETIONS,\n  supportsUsageInStreaming: COMPLETIONS,\n  // 0.1.2 line additions — all three live in Pi's openai-completions API\n  // (pi-ai types.ts + api/openai-completions.ts), so completions-only here.\n  supportsFinishReason: COMPLETIONS,\n  chatTemplateArgs: COMPLETIONS,\n  supportsThinkingTokenBudget: COMPLETIONS,\n  maxTokensField: COMPLETIONS,\n  requiresToolResultName: COMPLETIONS,\n  requiresAssistantAfterToolResult: COMPLETIONS,\n  requiresThinkingAsText: COMPLETIONS,\n  requiresReasoningContentOnAssistantMessages: COMPLETIONS,\n  thinkingFormat: COMPLETIONS,\n  chatTemplateKwargs: COMPLETIONS,\n  supportsStrictMode: COMPLETIONS_AND_RESPONSES,\n  cacheControlFormat: COMPLETIONS,\n  supportsLongCacheRetention: ALL_DSH_PROTOCOLS,\n  supportsEagerToolInputStreaming: ANTHROPIC,\n  supportsCacheControlOnTools: ANTHROPIC,\n  supportsTemperature: ANTHROPIC,\n  forceAdaptiveThinking: ANTHROPIC,\n  allowEmptySignature: ANTHROPIC,\n  supportsStrictTools: ANTHROPIC,\n} satisfies Record<keyof PiAiCompatProfile, ReadonlySet<string>> & Record<string, ReadonlySet<string>>\n// The intersection keeps the drift gate DUAL-GENERATION: the first member\n// still fails the build when the installed line ADDS a profile field we have\n// not deliberately assigned, while the index-signature member admits keys a\n// NEWER line defines that the installed (older) line's keyof does not.\n\nfunction recordOf(value: unknown): UnknownRecord | undefined {\n  return value !== null && typeof value === 'object' && !Array.isArray(value)\n    ? value as UnknownRecord\n    : undefined\n}\n\nfunction chatTemplateKwargsOf(value: unknown): UnknownRecord | undefined {\n  const input = recordOf(value)\n  if (input === undefined) return undefined\n  const output: UnknownRecord = {}\n  for (const [key, candidate] of Object.entries(input)) {\n    if (candidate === null || typeof candidate === 'string' || typeof candidate === 'boolean'\n      || (typeof candidate === 'number' && Number.isFinite(candidate))) {\n      output[key] = candidate\n      continue\n    }\n    const placeholder = recordOf(candidate)\n    if (placeholder === undefined || typeof placeholder.$var !== 'string'\n      || !DSH_CHAT_TEMPLATE_VARS.has(placeholder.$var)\n      || (placeholder.omitWhenOff !== undefined && typeof placeholder.omitWhenOff !== 'boolean')) continue\n    output[key] = {\n      $var: placeholder.$var,\n      ...(typeof placeholder.omitWhenOff === 'boolean' ? { omitWhenOff: placeholder.omitWhenOff } : {}),\n    }\n  }\n  return Object.keys(output).length === 0 ? undefined : output\n}\n\n/**\n * The part of Pi's model compat that rc.8's official adapter deliberately\n * offers for this protocol. Vendor-owned catalog switches remain withheld:\n * forwarding one unknown key rejects the entire settings section, so this is\n * an explicit field gate rather than a spread.\n */\nfunction compatProfileOf(value: unknown, api: string | undefined): UnknownRecord {\n  const compat = recordOf(value)\n  if (compat === undefined || api === undefined) return {}\n  const output: UnknownRecord = {}\n  const fields = Object.entries(DSH_COMPAT_FIELD_PROTOCOLS) as Array<[\n    keyof PiAiCompatProfile,\n    ReadonlySet<string>,\n  ]>\n  for (const [field, protocols] of fields) {\n    if (!protocols.has(api)) continue\n    const candidate = compat[field]\n    if (field === 'maxTokensField') {\n      if (typeof candidate === 'string' && DSH_MAX_TOKENS_FIELDS.has(candidate)) output[field] = candidate\n    } else if (field === 'thinkingFormat') {\n      if (typeof candidate === 'string' && DSH_THINKING_FORMATS.has(candidate)) output[field] = candidate\n    } else if (field === 'chatTemplateKwargs') {\n      const kwargs = chatTemplateKwargsOf(candidate)\n      if (kwargs !== undefined) output[field] = kwargs\n    } else if (field === 'cacheControlFormat') {\n      if (typeof candidate === 'string' && DSH_CACHE_CONTROL_FORMATS.has(candidate)) output[field] = candidate\n    } else if (typeof candidate === 'boolean') {\n      output[field] = candidate\n    }\n  }\n  return output\n}\n\nfunction reasoningEffortsOf(model: UnknownRecord): false | UnknownRecord | undefined {\n  if (model.reasoning === false) return false\n  if (model.reasoning !== true) return undefined\n  const levelMap = recordOf(model.thinkingLevelMap)\n  const efforts: UnknownRecord = {}\n  for (const level of getSupportedThinkingLevels(model as never)) {\n    const wire = levelMap?.[level]\n    efforts[level] = level === 'off' && wire === undefined ? null : (wire ?? level)\n  }\n  return Object.keys(efforts).some(level => level !== 'off') ? efforts : undefined\n}\n\n/** A positive whole number, or undefined — the profile schema rejects 0 and fractions. */\nfunction wholeAbove(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? value : undefined\n}\n\n/**\n * One Pi model as a DSH model profile.\n *\n * Field by field on purpose. The two vocabularies overlap but do not match:\n * Pi's `maxTokens` is routinely 0 for \"unstated\" while DSH requires at least 1,\n * and Pi's `reasoning` is a boolean where DSH's `reasoningEfforts` is a map of\n * offered levels. rc.8 gives compat a real profile slot, but only for a gated\n * protocol-specific subset. Forwarding these objects verbatim still rejects\n * the whole settings section — one bad key takes down every route in it.\n * @param model - the Pi model descriptor as its package declared it.\n * @param api - the wire protocol this route resolved to, which decides which\n *   compat fields are legal to state.\n */\nfunction modelProfileOf(model: UnknownRecord, api: string | undefined): UnknownRecord {\n  const carriedCompat = compatProfileOf(model.compat, api)\n  const reasoningEfforts = reasoningEffortsOf(model)\n  const input = Array.isArray(model.input)\n    ? (model.input as unknown[]).filter(entry => typeof entry === 'string' && DSH_MODALITIES.has(entry))\n    : []\n  const contextWindow = wholeAbove(model.contextWindow)\n  const maxTokens = wholeAbove(model.maxTokens)\n  return {\n    id: String(model.id ?? ''),\n    ...(typeof model.name === 'string' ? { name: model.name } : {}),\n    ...(contextWindow === undefined ? {} : { contextWindow }),\n    ...(maxTokens === undefined ? {} : { maxTokens }),\n    ...(input.length === 0 ? {} : { input }),\n    ...(reasoningEfforts === undefined ? {} : { reasoningEfforts }),\n    ...(Object.keys(carriedCompat).length === 0 ? {} : { compat: carriedCompat }),\n  }\n}\n\n/**\n * Serve a catalog-only Pi provider through DSH's OWN llm adapter.\n *\n * A Pi package may declare a gateway without shipping any code to call it —\n * on Pi that is complete, because pi-ai supplies the transport for the wire\n * protocol the models name. The bridge used to refuse those and tell the user\n * to configure the gateway by hand in DSH settings, which is the translation\n * this package exists to do for them.\n *\n * The translation is configuration, not transport: the declaration becomes an\n * `llm-pi-ai` provider profile — the official adapter's own shape, which\n * carries `api`, `baseURL` and per-model `compat` — and that official plugin\n * is mounted with it. Nothing here speaks HTTP.\n * @returns a disposer for the mounted route, or undefined when it cannot be built.\n */\nfunction registerCatalogOnlyRoute(options: RegisterPiProviderRouteOptions): PiRouteHandle | undefined {\n  const { ctx, providerId, provider, host } = options\n  if (ctx === undefined) return undefined\n  return mountOfficialAdapter(ctx, providerId, host, () => {\n    // Read the models AT MOUNT TIME, not once at registration: a catalog-only\n    // profile is a snapshot, so a re-announce after a login has to rebuild it\n    // from whatever the package discovered in the meantime.\n    const models = providerModels(provider as PiTransportProvider)\n    // An empty list at mount is normal, not a defect: a package may discover\n    // its models from the gateway later, or rely on pi-ai's installed catalog\n    // for a known provider name. The official profile's `models` is optional\n    // and omitting it serves that installed catalog, so a route is still built\n    // — refusing here would drop a provider that works the moment it is used.\n    const first = (models[0] ?? {}) as UnknownRecord\n    // Pi's own way of saying \"the key is in this environment variable\" is the\n    // same thing DSH's `apiKeyEnv` says, so the declaration carries across as\n    // configuration. Anything else the package may have written there (a\n    // command, a literal) stays where it is.\n    const apiKeyEnv = envReferenceOf(provider.apiKey)\n    // The wire protocol is a ROUTE-level fact in DSH and may be declared at\n    // either level in Pi (extensions put it on the provider, pi-ai's factory on\n    // each model). The provider's own answer leads; a model's is the fallback.\n    const api = protocolOf(provider.api) ?? protocolOf(first.api)\n    const baseURL = typeof provider.baseUrl === 'string' ? provider.baseUrl\n      : typeof first.baseUrl === 'string' ? first.baseUrl : undefined\n    const providerCompat = compatProfileOf(provider.compat, api)\n    return {\n      displayName: typeof provider.name === 'string' ? provider.name : providerId,\n      ...(apiKeyEnv === undefined ? {} : { apiKeyEnv }),\n      ...(api === undefined ? {} : { api }),\n      ...(baseURL === undefined ? {} : { baseURL }),\n      ...(Object.keys(providerCompat).length === 0\n        ? {}\n        : { compat: providerCompat }),\n      ...(models.length === 0\n        ? {}\n        : { models: models.map(model => modelProfileOf(model, api ?? protocolOf(model.api))) }),\n    }\n  }, `[pi2dsh] Pi provider ${JSON.stringify(providerId)} declares a catalog only; DSH's official llm-pi-ai adapter now serves it as a native route`)\n}\n\n/**\n * Mount DSH's official llm-pi-ai adapter for one route, rebuildable on demand.\n * @param buildProfile - called per mount, so a re-announce picks up new facts.\n * @param announcement - what to tell the user once the route is up.\n */\nfunction mountOfficialAdapter(\n  ctx: { plugin(plugin: unknown, config?: unknown): unknown, get?(name: string): unknown },\n  providerId: string,\n  host: ProviderAdapterHost,\n  buildProfile: () => UnknownRecord,\n  announcement: string,\n): PiRouteHandle {\n  let mounted: { dispose?: () => void } | undefined\n  let disposed = false\n  // Each mount attempt claims a number; a later one makes an in-flight mount\n  // stale, so a re-announce that overtakes the first mount cannot leave two\n  // fibers holding the same provider name.\n  let generation = 0\n  const mount = (): void => {\n    const profile = buildProfile()\n    const mine = ++generation\n    void (async () => {\n      try {\n        // The route is CONFIGURATION for an adapter the composition normally\n        // already mounts, so it goes into that adapter's settings section.\n        // Mounting a second copy of the plugin instead collides on the\n        // provider directory it declares — the real failure was\n        // `configurable provider \"amazon-bedrock\" is already declared`, which\n        // names an unrelated route and tells the user nothing.\n        if (await declareInSettings(ctx, providerId, profile)) {\n          if (!disposed && mine === generation) mounted = undefined\n          host.warn(announcement)\n          return\n        }\n        const official = await import('@deepseek-ai/dsh-llm-pi-ai')\n        const fiber = await ctx.plugin(\n          (official as UnknownRecord).default ?? official,\n          { providers: { [providerId]: profile } },\n        ) as { dispose?: () => void }\n        if (disposed || mine !== generation) fiber?.dispose?.()\n        else mounted = fiber\n        host.warn(announcement)\n      } catch (error) {\n        host.warn(`[pi2dsh] Pi provider ${JSON.stringify(providerId)} could not be served by the official adapter (${error instanceof Error ? error.message : String(error)}); configure the gateway in the host's llm settings instead`)\n      }\n    })()\n  }\n  mount()\n  const route = (() => {\n    disposed = true\n    mounted?.dispose?.()\n  }) as PiRouteHandle\n  // This route's models are a snapshot baked into the official adapter's\n  // config, so re-announcing means re-mounting it. The old fiber releases the\n  // provider name first — llm refuses a second adapter for a name already\n  // held.\n  route.reannounce = () => {\n    if (disposed) return\n    mounted?.dispose?.()\n    mounted = undefined\n    mount()\n  }\n  return route\n}\n\n/**\n * Hand one provider profile to the official adapter through DSH's settings.\n *\n * `ctx.settings.update` merges into the user layer of a namespace its OWNER\n * registered, so this only works where that adapter is mounted — which is the\n * normal composition, and exactly where mounting a second copy would collide.\n * A composition without it (a bare test host, an embedded runtime) rejects and\n * the caller falls back to mounting the plugin itself.\n * @returns whether the profile was stored.\n */\nasync function declareInSettings(\n  ctx: { get?(name: string): unknown },\n  providerId: string,\n  profile: UnknownRecord,\n): Promise<boolean> {\n  const settings = ctx.get?.('settings') as { update?(ns: string, patch: object): Promise<void> } | undefined\n  if (typeof settings?.update !== 'function') return false\n  try {\n    await settings.update('llm-pi-ai', { providers: { [providerId]: profile } })\n    return true\n  } catch {\n    // Not registered here (no official adapter in this composition), or the\n    // profile is one it refuses. Either way the mount below reports honestly.\n    return false\n  }\n}\n\n/**\n * Register the provider as a live DSH route when an llm service is mounted.\n * A provider carrying its own transport streams through it; a config-only\n * provider gets Pi's synthesized per-api transport. A route conflict (an\n * adapter already owns the name — e.g. a deployment-configured `deepseek`)\n * keeps the existing route and reports the skip.\n * @returns the route disposer, or undefined when nothing was registered.\n */\nexport function registerPiProviderRoute(options: RegisterPiProviderRouteOptions): PiRouteHandle | undefined {\n  const { llm, providerId, provider, host } = options\n  if (llm === undefined) return undefined\n  // A catalog-only declaration is complete on Pi (pi-ai supplies the transport\n  // for the declared protocol), so it must be complete here too — served by\n  // DSH's own adapter rather than refused back to the user as configuration\n  // homework.\n  if (!providerCarriesTransport(provider)) {\n    // An OAuth-only provider (Pi's built-in logins, and packages shaped like\n    // them) declares no models and no transport: there is nothing to route\n    // with until a login stores a credential, and declaring it now only\n    // produces \"resolves no models\". The login path declares it.\n    if (providerModels(provider as PiTransportProvider).length === 0 && provider.oauth !== undefined) return undefined\n    return registerCatalogOnlyRoute(options)\n  }\n  try {\n    const registration = llm.registerAdapter([providerId], piProviderDshAdapter(providerId, provider, host))\n    const route = (() => { registration() }) as PiRouteHandle\n    // This adapter's listModels reads the provider LIVE, so a later discovery\n    // is already visible to anyone who asks — what is missing is the asking.\n    // Re-committing the same route set is DSH's documented atomic\n    // announcement (no observer sees a gap), and it is what makes the model\n    // picker re-read.\n    if (typeof registration.replace === 'function') {\n      route.reannounce = () => registration.replace?.([providerId])\n    }\n    return route\n  } catch (error) {\n    host.warn(`[pi2dsh] Pi provider ${JSON.stringify(providerId)} was not added as a DSH llm route (${error instanceof Error ? error.message : String(error)}); the existing route keeps the name`)\n    return undefined\n  }\n}\n","// Pi terminal components -> dsh-TUI's public plugin surfaces.\n//\n// This module deliberately knows neither MCP nor any Pi package name. A Pi\n// custom component is already a small terminal protocol (`render(width)`,\n// `handleInput(raw)`, `dispose()`); dsh-TUI's public `tuiScenes` seam supplies\n// the missing screen ownership and raw-key lifecycle. The package keeps its\n// own state and behavior while the bridge translates only the host surface.\n\nimport { createRequire } from 'node:module'\n\ntype UnknownRecord = Record<string, unknown>\n\nexport interface PiCustomComponent {\n  render(width: number): string[]\n  invalidate?(): void\n  handleInput?(data: string): void\n  dispose?(): void\n}\n\nexport interface PiTuiDriver {\n  requestRender(): void\n}\n\nexport interface PiCustomOptions {\n  overlay?: boolean\n  overlayOptions?: UnknownRecord | (() => UnknownRecord)\n}\n\nexport type PiCustomFactory<T> = (\n  tui: PiTuiDriver,\n  theme: unknown,\n  keybindings: unknown,\n  done: (result: T) => void,\n) => PiCustomComponent | Promise<PiCustomComponent>\n\ninterface TuiScenePropsLike {\n  React: {\n    createElement(type: unknown, props?: UnknownRecord | null, ...children: unknown[]): unknown\n    useEffect(effect: () => void | (() => void), dependencies: readonly unknown[]): void\n    useSyncExternalStore(\n      subscribe: (listener: () => void) => () => void,\n      getSnapshot: () => number,\n      getServerSnapshot?: () => number,\n    ): number\n  }\n  ui: {\n    Box: unknown\n    Text: unknown\n    Ansi?: unknown\n    useInput(handler: (input: string, key: UnknownRecord, event?: UnknownRecord) => void): void\n    useTerminalSize(): { columns: number; rows: number }\n  }\n  close(): void\n}\n\ninterface TuiSceneService {\n  register(descriptor: {\n    id: string\n    title?: string\n    component: (props: TuiScenePropsLike) => unknown\n  }): () => void\n  open(id: string): boolean\n  close(): void\n}\n\ninterface TuiStatusService {\n  set(key: string, text: string | undefined): (() => void) | void\n}\n\nexport interface TuiSurfaceContext {\n  get(name: string, required?: boolean): unknown\n  effect?(callback: () => (() => void)): unknown\n  inject?(services: string[], callback: (ctx: TuiSurfaceContext) => void): unknown\n  logger?: { warn(message: string): void }\n}\n\n/** One optional terminal front door behind the public Pi UI contract. */\nexport interface TerminalSurfaceAdapter {\n  readonly kind: string\n  readonly available: boolean\n  /** Commands the active terminal owns natively; incoming Pi commands alias. */\n  readonly nativeCommands: ReadonlySet<string>\n  setStatus(key: string, text: unknown): void\n  custom<T>(\n    factory: PiCustomFactory<T>,\n    theme: unknown,\n    keybindings: unknown,\n    options?: PiCustomOptions,\n  ): Promise<T | undefined>\n  dispose(): void\n}\n\ninterface ActiveCustom<T = unknown> {\n  component?: PiCustomComponent\n  options: PiCustomOptions | undefined\n  resolve(value: T | undefined): void\n  reject(error: unknown): void\n}\n\nfunction service<T>(ctx: TuiSurfaceContext, name: string): T | undefined {\n  try {\n    return ctx.get(name, false) as T | undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction surfaceToken(value: string): string {\n  const normalized = value.toLowerCase().replace(/[^a-z0-9_-]+/gu, '-').replace(/^-+|-+$/gu, '')\n  if (normalized.length === 0) return 'entry'\n  return /^[a-z]/u.test(normalized) ? normalized : `k-${normalized}`\n}\n\nfunction sceneIdFor(packageName: string): string {\n  return `pi2dsh-${surfaceToken(packageName)}-custom`\n}\n\nfunction statusKeyFor(packageName: string, key: string): string {\n  return `pi2dsh:${surfaceToken(packageName)}:${surfaceToken(key)}`\n}\n\nfunction rawTerminalInput(input: string, key: UnknownRecord, event?: UnknownRecord): string {\n  const keypress = event?.keypress as UnknownRecord | undefined\n  if (typeof keypress?.sequence === 'string' && keypress.sequence.length > 0) return keypress.sequence\n  if (key.return === true) return '\\r'\n  if (key.escape === true) return '\\x1b'\n  if (key.tab === true) return '\\t'\n  if (key.backspace === true) return '\\x7f'\n  if (key.upArrow === true) return '\\x1b[A'\n  if (key.downArrow === true) return '\\x1b[B'\n  if (key.rightArrow === true) return '\\x1b[C'\n  if (key.leftArrow === true) return '\\x1b[D'\n  if (key.ctrl === true && input.length === 1) {\n    const code = input.toLowerCase().charCodeAt(0)\n    if (code >= 97 && code <= 122) return String.fromCharCode(code - 96)\n  }\n  return input\n}\n\nfunction preferredWidth(options: PiCustomOptions | undefined): number | undefined {\n  const raw = typeof options?.overlayOptions === 'function'\n    ? options.overlayOptions()\n    : options?.overlayOptions\n  const width = raw?.width\n  return typeof width === 'number' && Number.isFinite(width) && width > 0 ? Math.floor(width) : undefined\n}\n\n/**\n * One package-scoped Pi custom-surface host backed by one dsh-TUI scene.\n * The MCP adapter is a consumer, not a special case: every component using\n * the public Pi component protocol follows the same path.\n */\nexport class TuiSurfaceAdapter implements TerminalSurfaceAdapter {\n  readonly kind = 'tuiScenes'\n  readonly nativeCommands = dshTuiLocalCommands()\n  readonly sceneId: string\n\n  private readonly scenes: TuiSceneService\n  private readonly status: TuiStatusService | undefined\n  private readonly statusDisposers = new Map<string, () => void>()\n  private readonly listeners = new Set<() => void>()\n  private readonly unregisterScene: () => void\n  private revision = 0\n  private active: ActiveCustom | undefined\n  private disposed = false\n\n  constructor(\n    ctx: TuiSurfaceContext,\n    private readonly packageName: string,\n    private readonly instanceKey?: string,\n  ) {\n    const scenes = service<TuiSceneService>(ctx, 'tuiScenes')\n    if (scenes === undefined) throw new Error('pi2dsh: dsh-TUI scene service is unavailable')\n    this.scenes = scenes\n    this.status = service<TuiStatusService>(ctx, 'tuiStatus')\n    this.sceneId = sceneIdFor(instanceKey === undefined ? packageName : `${packageName}-${instanceKey}`)\n    this.unregisterScene = scenes.register({\n      id: this.sceneId,\n      title: `${packageName} custom panel`,\n      component: props => this.scene(props),\n    })\n  }\n\n  get available(): boolean {\n    return !this.disposed\n  }\n\n  subscribe(listener: () => void): () => void {\n    this.listeners.add(listener)\n    return () => this.listeners.delete(listener)\n  }\n\n  snapshot(): number {\n    return this.revision\n  }\n\n  setStatus(key: string, text: unknown): void {\n    if (this.disposed || this.status === undefined) return\n    const dshKey = statusKeyFor(\n      this.instanceKey === undefined ? this.packageName : `${this.packageName}-${this.instanceKey}`,\n      key,\n    )\n    this.statusDisposers.get(dshKey)?.()\n    this.statusDisposers.delete(dshKey)\n    if (text === undefined) return\n    const dispose = this.status.set(dshKey, String(text))\n    if (typeof dispose === 'function') this.statusDisposers.set(dshKey, dispose)\n  }\n\n  custom<T>(\n    factory: PiCustomFactory<T>,\n    theme: unknown,\n    keybindings: unknown,\n    options?: PiCustomOptions,\n  ): Promise<T | undefined> {\n    if (this.disposed) return Promise.resolve(undefined)\n    this.finish(undefined)\n    return new Promise<T | undefined>((resolve, reject) => {\n      const run: ActiveCustom<T> = { options, resolve, reject }\n      this.active = run as ActiveCustom\n      const driver: PiTuiDriver = { requestRender: () => this.invalidate() }\n      const done = (value: T): void => this.finishFor(run, value)\n      void Promise.resolve()\n        .then(() => factory(driver, theme, keybindings, done))\n        .then(component => {\n          if (this.active !== run) {\n            component.dispose?.()\n            return\n          }\n          if (typeof component?.render !== 'function') {\n            this.failFor(run, new TypeError('Pi custom component must implement render(width)'))\n            return\n          }\n          run.component = component\n          this.invalidate()\n          if (!this.scenes.open(this.sceneId)) this.finishFor(run, undefined)\n        }, error => this.failFor(run, error))\n    })\n  }\n\n  render(width: number): string[] {\n    const active = this.active\n    if (active?.component === undefined) return []\n    const available = Math.max(12, Math.floor(width) - 2)\n    const requested = preferredWidth(active.options)\n    return active.component.render(requested === undefined ? available : Math.min(available, requested))\n  }\n\n  handleInput(data: string): void {\n    const component = this.active?.component\n    if (component === undefined) return\n    component.handleInput?.(data)\n    component.invalidate?.()\n    this.invalidate()\n  }\n\n  dispose(): void {\n    if (this.disposed) return\n    this.disposed = true\n    this.finish(undefined)\n    for (const dispose of this.statusDisposers.values()) dispose()\n    this.statusDisposers.clear()\n    this.unregisterScene()\n    this.listeners.clear()\n  }\n\n  private invalidate(): void {\n    this.revision += 1\n    for (const listener of this.listeners) listener()\n  }\n\n  private finish(value: unknown): void {\n    const active = this.active\n    if (active !== undefined) this.finishFor(active, value)\n  }\n\n  private finishFor<T>(run: ActiveCustom<T>, value: T | undefined, closeScene = true): void {\n    if (this.active !== run) return\n    this.active = undefined\n    run.component?.dispose?.()\n    if (closeScene) this.scenes.close()\n    this.invalidate()\n    run.resolve(value)\n  }\n\n  private failFor<T>(run: ActiveCustom<T>, error: unknown): void {\n    if (this.active !== run) return\n    this.active = undefined\n    run.component?.dispose?.()\n    this.scenes.close()\n    this.invalidate()\n    run.reject(error)\n  }\n\n  private scene(props: TuiScenePropsLike): unknown {\n    const { React, ui } = props\n    React.useSyncExternalStore(\n      listener => this.subscribe(listener),\n      () => this.snapshot(),\n      () => this.snapshot(),\n    )\n    React.useEffect(() => () => {\n      const active = this.active\n      if (active !== undefined) this.finishFor(active, undefined, false)\n    }, [])\n    ui.useInput((input, key, event) => this.handleInput(rawTerminalInput(input, key, event)))\n    const { columns } = ui.useTerminalSize()\n    const lines = this.render(columns)\n    const Line = ui.Ansi ?? ui.Text\n    return React.createElement(\n      ui.Box,\n      { flexDirection: 'column', width: '100%', paddingX: 1 },\n      ...lines.map((line, index) => React.createElement(Line, { key: index }, line)),\n    )\n  }\n}\n\n/**\n * Attach lazily to dsh-TUI. Cordis reloads this child fiber whenever the\n * service implementation changes, so a TUI update cannot leave a stale scene\n * proxy in the bridge.\n */\nexport function mountTuiSurfaceAdapter(\n  ctx: TuiSurfaceContext,\n  packageName: string,\n  publish: (adapter: TuiSurfaceAdapter | undefined) => void,\n  instanceKey?: string,\n): void {\n  const attach = (surfaceCtx: TuiSurfaceContext): void => {\n    const adapter = new TuiSurfaceAdapter(surfaceCtx, packageName, instanceKey)\n    publish(adapter)\n    surfaceCtx.effect?.(() => () => {\n      adapter.dispose()\n      publish(undefined)\n    })\n  }\n  // Agent setup runs after the Loader tree is settled, so the service is\n  // already present. Register on the Agent's own activation: dsh-TUI binds a\n  // scene's authority to the activation that registered it, and the command\n  // opening the scene is registered by that same activation. Creating an\n  // extra ctx.inject child here gives registration and open different owners.\n  if (service<TuiSceneService>(ctx, 'tuiScenes') !== undefined) {\n    attach(ctx)\n    return\n  }\n  // Legacy root mounts may start before dsh-TUI. Track the optional service\n  // there so it can attach when the surface appears later.\n  if (typeof ctx.inject === 'function') {\n    ctx.inject(['tuiScenes'], attach)\n    return\n  }\n}\n\n/**\n * dsh-TUI dispatches its LOCAL commands before it asks DSH's command\n * registry (\"locals win on name collisions\" — its own commands.ts contract),\n * so a registry command sharing a local name is unreachable from that\n * surface. The host command keeps its name; the incoming command gets a\n * `pi-` source prefix — and ONLY on a composition where dsh-TUI is present;\n * everywhere else the original name stands.\n *\n * The reserved-name list is dsh-TUI's `LOCAL_COMMANDS`, which it exports in\n * code but not through its package exports map (upstream ask filed). Until\n * that lands, the list is pinned per generation from the published sources:\n * 0.8.x reserved only /mcp; 0.9.0 reserves the full set below. Generation is\n * read off the installed package's public ./package.json subpath.\n */\nconst DSH_TUI_LOCAL_COMMANDS_0_9 = new Set([\n  'new', 'clear', 'compact', 'resume', 'rename', 'rewind', 'export', 'btw',\n  'trace', 'context', 'status', 'cost', 'config', 'settings', 'doctor',\n  'init', 'agents', 'activity', 'preset', 'theme', 'lang', 'model', 'effort',\n  'thinking', 'tokens', 'provider', 'login', 'logout', 'add-dir', 'hooks',\n  'mcp', 'skills', 'plugins', 'update', 'audit', 'bug', 'practice', 'review',\n  'release-notes', 'vuln-check', 'vim', 'terminal-setup', 'connect',\n  'workspace', 'help', 'tips', 'exit', 'quit', 'q', 'deepseek',\n])\nconst DSH_TUI_LOCAL_COMMANDS_LEGACY = new Set(['mcp'])\n\n/** The reserved set for one installed dsh-tui version (undefined = unknown,\n * assume the current generation). */\nexport function tuiLocalCommandsForVersion(version: string | undefined): ReadonlySet<string> {\n  if (version === undefined) return DSH_TUI_LOCAL_COMMANDS_0_9\n  const [major = 0, minor = 0] = version.split('.').map(part => Number.parseInt(part, 10))\n  return major > 0 || minor >= 9 ? DSH_TUI_LOCAL_COMMANDS_0_9 : DSH_TUI_LOCAL_COMMANDS_LEGACY\n}\n\nlet cachedTuiLocalCommands: ReadonlySet<string> | undefined\nexport function dshTuiLocalCommands(): ReadonlySet<string> {\n  if (cachedTuiLocalCommands !== undefined) return cachedTuiLocalCommands\n  let version: string | undefined\n  try {\n    const require = createRequire(import.meta.url)\n    version = (require('@deepseek-harness-tui/dsh-tui/package.json') as { version?: string }).version\n  } catch {\n    // No resolvable dsh-tui package: the composition-level tuiAvailable gate\n    // already answered true, so assume the current generation's list.\n  }\n  cachedTuiLocalCommands = tuiLocalCommandsForVersion(version)\n  return cachedTuiLocalCommands\n}\n\nexport function commandNameForDshTui(name: string, tuiAvailable: boolean): string {\n  return tuiAvailable && dshTuiLocalCommands().has(name) ? `pi-${name}` : name\n}\n\n/** Host-native command ownership, independent of the concrete TUI package. */\nexport function commandNameForTerminal(name: string, nativeCommands: ReadonlySet<string> | undefined): string {\n  return nativeCommands?.has(name) === true ? `pi-${name}` : name\n}\n\n/** Bridge fallback commands disappear when the active Host already owns one. */\nexport function shouldRegisterCompatibilityCommand(name: string, nativeCommands: ReadonlySet<string> | undefined): boolean {\n  return nativeCommands?.has(name) !== true\n}\n\nexport const tuiSurfaceInternals = {\n  rawTerminalInput,\n  sceneIdFor,\n  statusKeyFor,\n}\n","// Transport-neutral relay for Pi custom terminal components.\n//\n// The Pi component object stays on the Host side. A presentation seat only\n// exchanges serializable render/input/lifecycle messages. Today the\n// dsh-pi-tui adapter calls this relay in-process; the same contract can later\n// travel over DSH's client wire without moving callbacks or component objects\n// across the Server/Client boundary.\n\nimport type {\n  PiCustomComponent,\n  PiCustomFactory,\n  PiCustomOptions,\n  PiTuiDriver,\n} from './tui-surfaces.js'\n\nexport interface PiComponentFrameRequest {\n  sessionId: string\n  width: number\n}\n\nexport interface PiComponentFrame {\n  sessionId: string\n  revision: number\n  width: number\n  lines: string[]\n}\n\nexport interface PiComponentInput {\n  sessionId: string\n  data: string\n}\n\nlet relaySerial = 0\n\nfunction relayId(): string {\n  relaySerial += 1\n  return `pi2dsh-custom-${relaySerial}`\n}\n\n/**\n * One Host-owned Pi component session expressed as data messages.\n *\n * The result value never crosses the presentation boundary: Pi's own `done`\n * callback completes it on the Host. Frames and input are deliberately plain\n * data so the presentation transport can change independently.\n */\nexport class PiComponentRelay<T = unknown> {\n  readonly sessionId = relayId()\n  readonly options: PiCustomOptions | undefined\n  readonly ready: Promise<boolean>\n  readonly result: Promise<T | undefined>\n\n  private component: PiCustomComponent | undefined\n  private readonly invalidations = new Set<(revision: number) => void>()\n  private resolveResult!: (value: T | undefined) => void\n  private rejectResult!: (error: unknown) => void\n  private revision = 0\n  private closed = false\n\n  constructor(\n    factory: PiCustomFactory<T>,\n    theme: unknown,\n    keybindings: unknown,\n    options?: PiCustomOptions,\n  ) {\n    this.options = options\n    this.result = new Promise<T | undefined>((resolve, reject) => {\n      this.resolveResult = resolve\n      this.rejectResult = reject\n    })\n    const driver: PiTuiDriver = { requestRender: () => this.invalidate() }\n    const done = (value: T): void => this.close(value)\n    this.ready = Promise.resolve()\n      .then(() => factory(driver, theme, keybindings, done))\n      .then(component => {\n        if (this.closed) {\n          component.dispose?.()\n          return false\n        }\n        if (typeof component?.render !== 'function') {\n          throw new TypeError('Pi custom component must implement render(width)')\n        }\n        this.component = component\n        this.invalidate()\n        return true\n      })\n      .catch(error => {\n        this.fail(error)\n        return false\n      })\n  }\n\n  get active(): boolean {\n    return !this.closed\n  }\n\n  onInvalidate(listener: (revision: number) => void): () => void {\n    this.invalidations.add(listener)\n    return () => this.invalidations.delete(listener)\n  }\n\n  frame(request: PiComponentFrameRequest): PiComponentFrame {\n    if (request.sessionId !== this.sessionId) throw new Error('stale Pi component render session')\n    const width = Math.max(1, Math.floor(request.width))\n    return {\n      sessionId: this.sessionId,\n      revision: this.revision,\n      width,\n      lines: this.component?.render(width) ?? [],\n    }\n  }\n\n  input(message: PiComponentInput): void {\n    if (message.sessionId !== this.sessionId || this.closed) return\n    this.component?.handleInput?.(message.data)\n  }\n\n  invalidate(): void {\n    if (this.closed) return\n    this.revision += 1\n    for (const listener of this.invalidations) listener(this.revision)\n  }\n\n  close(value?: T): void {\n    if (this.closed) return\n    this.closed = true\n    const component = this.component\n    this.component = undefined\n    component?.dispose?.()\n    this.invalidations.clear()\n    this.resolveResult(value)\n  }\n\n  fail(error: unknown): void {\n    if (this.closed) return\n    this.closed = true\n    const component = this.component\n    this.component = undefined\n    component?.dispose?.()\n    this.invalidations.clear()\n    this.rejectResult(error)\n  }\n}\n\n","// Optional dsh-pi-tui presentation backend.\n//\n// This module consumes only the package's public extension entry points. It\n// knows no Pi consumer package names: MCP managers, subagent managers and any\n// other `ctx.ui.custom` consumer all travel through the same component relay.\n\nimport { PiComponentRelay } from './pi-component-relay.js'\nimport type {\n  PiCustomFactory,\n  PiCustomOptions,\n  TerminalSurfaceAdapter,\n  TuiSurfaceContext,\n} from './tui-surfaces.js'\n\ninterface FooterSegment {\n  spans: Array<{ text: string, tone?: string }>\n  minWidth?: number\n  importance?: number\n}\n\ninterface RegistrationHandleLike<T> {\n  replace(value: T): void\n  dispose(): void\n}\n\nexport interface PiTuiExtensionServiceLike {\n  api(): {\n    apiVersion: number\n    capabilities: ReadonlySet<string>\n  }\n  register<T>(slot: string, spec: {\n    id: string\n    order?: number\n    description?: string\n  }, contribution: T): RegistrationHandleLike<T>\n}\n\ninterface UnstableMountLeaseLike {\n  readonly active: boolean\n  focus(): void\n  invalidate(): void\n  close(): void\n}\n\nexport interface PiTuiUnstableFacadeLike {\n  surface: {\n    readonly handle: {\n      mountComponent(component: {\n        render(width: number): string[]\n        handleInput?(data: string): void\n        dispose?(): void\n      }, options?: Record<string, unknown>): UnstableMountLeaseLike\n    }\n  }\n}\n\ninterface PiTuiPublicModule {\n  LOCAL_COMMANDS: ReadonlySet<string>\n}\n\ninterface PiTuiUnstableModule {\n  UNSTABLE_API_LEVEL: number\n  unstable(service: PiTuiExtensionServiceLike): PiTuiUnstableFacadeLike\n}\n\nfunction service(ctx: TuiSurfaceContext): PiTuiExtensionServiceLike | undefined {\n  try {\n    return ctx.get('piTuiExtensions', false) as PiTuiExtensionServiceLike | undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction statusId(packageName: string, instanceKey: string | undefined, key: string): string {\n  const token = `${packageName}${instanceKey === undefined ? '' : `-${instanceKey}`}-${key}`\n    .toLowerCase()\n    .replace(/[^a-z0-9_-]+/gu, '-')\n    .replace(/^-+|-+$/gu, '')\n  return `pi2dsh-status-${token || 'entry'}`\n}\n\nfunction overlayOptions(options: PiCustomOptions | undefined): Record<string, unknown> | undefined {\n  const raw = typeof options?.overlayOptions === 'function'\n    ? options.overlayOptions()\n    : options?.overlayOptions\n  return raw === undefined ? undefined : { ...raw }\n}\n\n/** dsh-pi-tui backend over the public `piTuiExtensions` service. */\nexport class PiTuiExtensionSurfaceAdapter implements TerminalSurfaceAdapter {\n  readonly kind = 'piTuiExtensions'\n  readonly nativeCommands: ReadonlySet<string>\n\n  private readonly statusHandles = new Map<string, RegistrationHandleLike<FooterSegment>>()\n  private readonly mounts = new Set<{ relay: PiComponentRelay, lease?: UnstableMountLeaseLike }>()\n  private disposed = false\n\n  constructor(\n    private readonly extensionService: PiTuiExtensionServiceLike,\n    private readonly unstableFacade: PiTuiUnstableFacadeLike,\n    nativeCommands: ReadonlySet<string>,\n    private readonly packageName: string,\n    private readonly instanceKey?: string,\n  ) {\n    this.nativeCommands = new Set(nativeCommands)\n  }\n\n  get available(): boolean {\n    if (this.disposed) return false\n    try {\n      return this.extensionService.api().capabilities.has('unstable.surface.handle')\n    } catch {\n      return false\n    }\n  }\n\n  setStatus(key: string, text: unknown): void {\n    if (this.disposed) return\n    const id = statusId(this.packageName, this.instanceKey, key)\n    const previous = this.statusHandles.get(id)\n    if (text === undefined) {\n      previous?.dispose()\n      this.statusHandles.delete(id)\n      return\n    }\n    const value: FooterSegment = {\n      spans: [{ text: String(text), tone: 'textDim' }],\n      minWidth: 4,\n      importance: 50,\n    }\n    if (previous !== undefined) {\n      previous.replace(value)\n      return\n    }\n    if (!this.extensionService.api().capabilities.has('slot.chrome.footer.status')) return\n    this.statusHandles.set(id, this.extensionService.register<FooterSegment>(\n      'chrome.footer.status',\n      { id, order: 500, description: `Pi status ${key} from ${this.packageName}` },\n      value,\n    ))\n  }\n\n  async custom<T>(\n    factory: PiCustomFactory<T>,\n    theme: unknown,\n    keybindings: unknown,\n    options?: PiCustomOptions,\n  ): Promise<T | undefined> {\n    if (!this.available) return undefined\n    for (const active of [...this.mounts]) active.relay.close(undefined)\n\n    const relay = new PiComponentRelay(factory, theme, keybindings, options)\n    const record: { relay: PiComponentRelay<T>, lease?: UnstableMountLeaseLike } = { relay }\n    this.mounts.add(record as { relay: PiComponentRelay, lease?: UnstableMountLeaseLike })\n    try {\n      if (!await relay.ready || !relay.active) return await relay.result\n      if (this.disposed) {\n        relay.close(undefined)\n        return await relay.result\n      }\n      // Read the CURRENT handle at mount time. The public facade follows the\n      // active surface generation; retaining an earlier handle would mount on\n      // a stale terminal after fullscreen/restart transitions.\n      const handle = this.unstableFacade.surface.handle\n      const lease = handle.mountComponent({\n        render: width => relay.frame({ sessionId: relay.sessionId, width }).lines,\n        handleInput: data => relay.input({ sessionId: relay.sessionId, data }),\n        dispose: () => relay.close(undefined),\n      }, overlayOptions(options))\n      record.lease = lease\n      const offInvalidate = relay.onInvalidate(() => lease.invalidate())\n      const release = (): void => {\n        offInvalidate()\n        lease.close()\n      }\n      void relay.result.then(release, release)\n      if (!lease.active) relay.close(undefined)\n      lease.focus()\n      return await relay.result\n    } catch (error) {\n      relay.fail(error)\n      throw error\n    } finally {\n      this.mounts.delete(record as { relay: PiComponentRelay, lease?: UnstableMountLeaseLike })\n    }\n  }\n\n  dispose(): void {\n    if (this.disposed) return\n    this.disposed = true\n    for (const handle of this.statusHandles.values()) handle.dispose()\n    this.statusHandles.clear()\n    for (const active of this.mounts) {\n      active.relay.close(undefined)\n      active.lease?.close()\n    }\n    this.mounts.clear()\n  }\n}\n\n/**\n * Build the optional backend from published public entry points.\n * Returns undefined when the service is absent or cannot provide the exact\n * raw-component capability; callers then keep the existing dsh-TUI/Web path.\n */\nexport async function createPiTuiExtensionSurfaceAdapter(\n  ctx: TuiSurfaceContext,\n  packageName: string,\n  instanceKey?: string,\n): Promise<PiTuiExtensionSurfaceAdapter | undefined> {\n  const extensionService = service(ctx)\n  if (extensionService === undefined) return undefined\n  const api = extensionService.api()\n  if (api.apiVersion !== 1 || !api.capabilities.has('unstable.surface.handle')) {\n    ctx.logger?.warn(`pi2dsh: piTuiExtensions cannot host Pi components (api=${api.apiVersion}, raw surface=${api.capabilities.has('unstable.surface.handle')})`)\n    return undefined\n  }\n  try {\n    // Variable specifiers keep the optional peer out of the engine's static\n    // import graph. Both are documented package exports; no repository or\n    // private implementation path is consumed.\n    const hostEntry = '@xmoon76/dsh-pi-tui'\n    const unstableEntry = '@xmoon76/dsh-pi-tui/extensions/unstable'\n    const [hostModule, unstableModule] = await Promise.all([\n      import(hostEntry) as Promise<PiTuiPublicModule>,\n      import(unstableEntry) as Promise<PiTuiUnstableModule>,\n    ])\n    if (unstableModule.UNSTABLE_API_LEVEL !== 1) {\n      ctx.logger?.warn(`pi2dsh: unsupported dsh-pi-tui unstable API level ${unstableModule.UNSTABLE_API_LEVEL}`)\n      return undefined\n    }\n    return new PiTuiExtensionSurfaceAdapter(\n      extensionService,\n      unstableModule.unstable(extensionService),\n      hostModule.LOCAL_COMMANDS,\n      packageName,\n      instanceKey,\n    )\n  } catch (error) {\n    ctx.logger?.warn(`pi2dsh: could not attach the public piTuiExtensions backend: ${error instanceof Error ? error.message : String(error)}`)\n    return undefined\n  }\n}\n","// TODO: 拆解本文件（2026-08-20 用户拍板，待做）。~3.9k 行承载了包挂载、\n// SharedHostState、模型目录投影、/login 与凭证恢复、伴生路由、命令/工具/\n// 事件桥等多个职责。拆法必须跟着架构走：按 CLAUDE.md 三层结构与 host 级/\n// 包级资源边界切模块，纯搬家不改逻辑；动手前先给出切分方案对齐再执行。\nimport { isPiUserMessage, readSessionEvents } from './session-events.js'\nimport { withPiPrintTransport, type PiPrintRequest } from './pi-cli-bridge.js'\nimport { access, mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { EventEmitter } from 'node:events'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join, resolve as pathResolve } from 'node:path'\nimport { createJiti } from 'jiti'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm'\nimport { scopeOf } from '@deepseek-ai/dsh-scope'\nimport { fileContentForPi } from './dsh-content.js'\nimport { renderPrompt } from '@deepseek-ai/dsh-system-prompt'\nimport type {\n  PostToolDecision,\n  PreToolDecision,\n  ToolDefinition,\n  ToolExecution,\n  ToolExecutionResult,\n} from '@deepseek-ai/dsh-tools'\nimport type { GeneratedRuntimeManifest } from './types.js'\nimport { CapabilityLedger, PiCapabilityError } from './capability.js'\nimport { PiSessionBridge } from './session-bridge.js'\nimport {\n  ExtensionRunner,\n  Theme,\n  __runWithSubagentSessionFactory,\n  generateBranchSummary,\n  getAgentDir,\n} from './compat/pi-coding-agent.js'\nimport { getKeybindings, stripTerminalSequences } from './compat/pi-tui.js'\nimport { childLabel, createBridgedAgentSession, type SubagentHost } from './subagent-bridge.js'\nimport { openBrowser } from './compat/vendor/pi-open-browser.js'\nimport { BrowserSurfaces, publishAuthorization, registerBrowserSurfaceRoute, revokeAuthorization, surfaceText, type SurfaceKey } from './browser-surfaces.js'\nimport { collectPiMcpServers, piMcpConfigPaths } from './mcp-config.js'\n\n/** Fallback thread ids when a child session reports none. */\nlet sidePanelSerial = 0\nimport {\n  FileCredentialStore,\n  joinSignals,\n  loginPiProvider,\n  providerSupportsOAuth,\n  resolveOAuthApiKey,\n  resolvePiProviderAuth,\n  storedOAuthCredential,\n} from './oauth-bridge.js'\nimport { __createPiAiRuntimeRegistry, __runWithPiAiRuntime, builtinProviders } from './compat/pi-ai.js'\nimport { validateToolArguments } from './compat/vendor/pi-tool-validation.js'\nimport { ModelCatalog, llmOf, streamViaDshLlm, type DshAttachmentsLike } from './model-bridge.js'\nimport { imageAdmissionCompanionAdapter, providerCarriesTransport, registerPiProviderRoute, type PiRouteHandle } from './provider-adapter.js'\nimport { oauthCredentialRef } from './oauth-bridge.js'\nimport {\n  commandNameForTerminal,\n  mountTuiSurfaceAdapter,\n  shouldRegisterCompatibilityCommand,\n  type PiCustomFactory,\n  type PiCustomOptions,\n  type TerminalSurfaceAdapter,\n  type TuiSurfaceContext,\n} from './tui-surfaces.js'\nimport { createPiTuiExtensionSurfaceAdapter } from './pi-tui-extension-surface.js'\n\ntype UnknownRecord = Record<string, unknown>\ntype PiHandler = (event: UnknownRecord, context: UnknownRecord) => unknown | Promise<unknown>\n\n// DSH's browser tool-view slot is keyed by exact wire tool name. Pi has no\n// output-schema flag for image results, so support only packages whose image\n// tool contract we have verified. This is intentionally small and explicit:\n// mounting an unrelated Pi package must never replace its existing DSH card.\nconst KNOWN_IMAGE_TOOLS_BY_PACKAGE: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n  ['@crazygit/pi-codex-image-gen', new Set(['codex_generate_image'])],\n])\n\nfunction isKnownImageTool(packageName: string, toolName: string): boolean {\n  return KNOWN_IMAGE_TOOLS_BY_PACKAGE.get(packageName)?.has(toolName) === true\n}\n\ninterface RuntimeOptions {\n  rootUrl: URL\n  manifest: GeneratedRuntimeManifest\n  config?: UnknownRecord\n  /** Exact Agent owner supplied by the pre-publication setup host. */\n  ownerAgent?: UnknownRecord\n  /**\n   * Host-anchor mount: the once-per-host instance that carries a package's\n   * HOST-level contributions — provider routes, OAuth accounts, `/login`\n   * availability, credential recovery, companion routes, skills — so they\n   * exist from engine apply with zero live Agents and survive Agent churn\n   * (SharedHostState keeps them single-instance and refcounted alongside the\n   * per-Agent instances). The anchor serves no Agent: it never bridges\n   * session lifecycles and its agent-facing surfaces (DSH tools, commands,\n   * prompt sections) are not projected — those belong to the per-Agent\n   * instances that own real sessions.\n   */\n  hostAnchor?: boolean\n}\n\ninterface PiTool {\n  name: string\n  label?: string\n  description: string\n  parameters: unknown\n  /** Pi: one line for the system prompt's \"Available tools\" list. */\n  promptSnippet?: string\n  /** Pi: guideline bullets that apply while this tool is active. */\n  promptGuidelines?: string[]\n  executionMode?: 'parallel' | 'sequential'\n  prepareArguments?: (args: unknown) => unknown\n  execute(\n    toolCallId: string,\n    args: unknown,\n    signal: AbortSignal | undefined,\n    onUpdate: ((result: unknown) => void) | undefined,\n    context: UnknownRecord,\n  ): Promise<unknown>\n}\n\ninterface PiCommand {\n  name: string\n  description: string\n  argumentHint?: string\n  handler(args: string, context: UnknownRecord): unknown | Promise<unknown>\n}\n\ninterface RuntimeState {\n  packageName: string\n  /** Exact DSH Agent that owns this runtime; absent only for legacy root mounts. */\n  ownerAgent: UnknownRecord | undefined\n  /** Host-anchor mount: host-level contributions only, serves no Agent (see RuntimeOptions.hostAnchor). */\n  hostAnchor: boolean\n  /** The session-event projector, exposed for the mount-time backlog replay. */\n  projectSessionEvent?: (session: UnknownRecord, event: UnknownRecord) => void\n  /** Owned mounts: live session-event delivery starts after the backlog replay. */\n  sessionEventsLive?: boolean\n  handlers: Map<string, PiHandler[]>\n  tools: Map<string, PiTool>\n  // The Pi runner facade tool-catalog packages (pi-fabric) hook by patching\n  // ExtensionRunner.prototype.getAllRegisteredTools; enumeration of Pi tools\n  // goes through it so a patched prototype really filters the catalog.\n  runner: ExtensionRunner\n  toolDisposers: Map<string, () => void>\n  toolRestrictions: WeakMap<object, () => void>\n  pendingActiveTools?: string[]\n  commands: Map<string, PiCommand>\n  nativeSkillCommands: UnknownRecord[]\n  // DSH-side disposers for registered commands, so Pi's same-name\n  // registerCommand replacement (Map.set semantics) can release the old one.\n  commandDisposers: Map<string, () => void>\n  /** DSH command name -> Pi command that currently owns that public name. */\n  dshCommandOwners: Map<string, string>\n  flags: Map<string, boolean | string | undefined>\n  notifications: string[]\n  activeAgents: Set<UnknownRecord>\n  /** Latest non-child Agent whose Pi session owns this package instance. */\n  hostAgent: UnknownRecord | undefined\n  /** Agents whose linear Pi session_shutdown has already been projected. */\n  piShutdownAgents: WeakSet<object>\n  shutdownTasks: WeakMap<object, Promise<void>>\n  pendingShutdowns: Set<Promise<void>>\n  disposedAgents: WeakSet<object>\n  /** Durable sessions that have already received Pi's session_start event. */\n  startedSessions: Set<string>\n  /** In-flight session_start handlers, so an immediate command can await initialization. */\n  sessionStartTasks: Map<string, Promise<void>>\n  /** Fallback dedupe for command agents whose composition has no durable session. */\n  startedSessionlessAgents: WeakSet<object>\n  /** In-flight session_start handlers for agents without a durable session id. */\n  sessionlessStartTasks: WeakMap<object, Promise<void>>\n  /** Extension entries are async imports; lifecycle events wait until handlers exist. */\n  extensionsReady: boolean\n  /** Agent starts observed while extension entries are still loading. */\n  pendingSessionStarts: Map<UnknownRecord, string>\n  /** Skill roots already handed to DSH's skills service through resources_discover. */\n  discoveredSkillRoots: Set<string>\n  /** Count of discovered-root provider mounts, for unique provider names. */\n  discoveredSkillProviders: number\n  currentSystemPrompt: string\n  messageSource: string\n  /** Pi's cross-extension bus: shared by every package instance of one agent\n   * (host/anchor instances share the host bus), matching Pi's one-bus-per-\n   * session contract. NEVER removeAllListeners on it — that would strip the\n   * other packages' subscriptions; unwind through eventBusOffs instead. */\n  eventBus: EventEmitter\n  /** This instance's own bus subscriptions, for scoped unwind on dispose/reload. */\n  eventBusOffs: Array<() => void>\n  agentScope: AsyncLocalStorage<UnknownRecord | undefined>\n  /** Per-Agent bridge used by Pi's designated-model calls. */\n  llmBridge: PiAiLlmBridge | undefined\n  /** Per-Agent copy of Pi's compat and API-provider registries. */\n  piAiRegistry: ReturnType<typeof __createPiAiRuntimeRegistry>\n  /** Per-Agent factory used by Pi's createAgentSession(). */\n  subagentSessionFactory: SubagentSessionFactory | undefined\n  bridge: PiSessionBridge\n  theme: Theme\n  // Registered-but-headless surfaces: accepted so packages load and can\n  // introspect their own registrations; DSH owns actual presentation.\n  shortcuts: Map<string, UnknownRecord>\n  messageRenderers: Map<string, unknown>\n  entryRenderers: Map<string, unknown>\n  markdownTransformer?: unknown\n  providers: Map<string, UnknownRecord>\n  /** Ids in `providers` registered as pi-ai native Provider objects (Pi's second ledger). */\n  nativeProviders: Set<string>\n  // Pi-format auth.json store, created on first OAuth use; per-provider\n  // serialized writes, atomic 0600 persistence (see oauth-bridge).\n  autocompleteProviders: unknown[]\n  editorComponentFactory?: unknown\n  editorBuffers: WeakMap<object, string>\n  toolsExpanded: boolean\n  // Per-agent model/thinking overrides applied through the agent/request waterfall.\n  modelOverrides: WeakMap<object, { provider?: string; model?: string }>\n  thinkingLevels: WeakMap<object, string>\n  // Child agents THIS instance created through createAgentSession: the\n  // agent/request waterfall covers them (their thinking level rides it), and\n  // nobody else's instance claims them.\n  childAgents: WeakSet<object>\n  // Per-agent, per-turn system-prompt override returned by before_agent_start\n  // (Pi resets to the base prompt when a turn's handlers return none).\n  turnSystemPromptOverrides: WeakMap<object, string>\n  /**\n   * The single ordered stream for projections that must keep durable-log\n   * order. Several of them now await the attachment service (Pi's content\n   * blocks carry image bytes inline), and the subscribers that feed them are\n   * synchronous — without one shared chain a tool result with an image can be\n   * announced after the turn that produced it has already ended.\n   */\n  projection: Promise<unknown>\n  /**\n   * Pi's `terminate` hint, accumulated across the current tool batch. Pi stops\n   * the loop only when EVERY finalized call in the batch asked for it, and a\n   * single call cannot know that — so the calls record here and the next step\n   * boundary reads the verdict.\n   */\n  terminateBatch: WeakMap<object, { calls: number, terminating: number }>\n  /** Pi's turnIndex: reset when a DSH turn opens, incremented after each step. */\n  piTurnIndex: WeakMap<object, number>\n  /** Messages DSH claimed for the step that is about to be assembled. */\n  claimedForStep: WeakMap<object, UnknownRecord[]>\n  /** The turn each agent's before_agent_start has already fired for. */\n  promptedTurn: WeakMap<object, number>\n  /** Custom messages a before_agent_start handler returned, awaiting the step. */\n  pendingInjections: WeakMap<object, UnknownRecord[]>\n  globalThinkingLevel: string\n  // Pi tool_call handlers mutate event.input in place; mutations apply to\n  // pi2dsh-owned tools through this channel (DSH core deliberately forbids\n  // rewriting exec.arguments for native tools).\n  argMutations: WeakMap<object, unknown>\n  // Streaming accumulation for message_update projection from assistant/chunk.\n  streamingTexts: Map<string, string>\n  // Last model id seen in a request/header event, for model_select projection.\n  lastLoggedModels: WeakMap<object, string>\n  // Pi Model catalog projected from the DSH llm service (empty without one).\n  modelCatalog?: ModelCatalog\n  // HOST-level slices (same instances across every package in this host —\n  // see SharedHostState): companion mapping, live route disposers, and the\n  // provider directory.\n  // Image-admission companion routes (companion id → original route id).\n  // Pi's ctx.model reports the ORIGINAL route for a companion selection: the\n  // model actually generating is the original text-only one, and extensions\n  // branching on input modalities (a vision bridge deciding whether to act)\n  // need that truth, not the admission face.\n  companionRoutes: Map<string, string>\n  // Live DSH llm routes registered for transport-carrying Pi providers.\n  providerRouteDisposers: Map<string, PiRouteHandle>\n  /** Host-shared provider routes this Agent runtime owns one reference to. */\n  ownedProviderRoutes: Set<string>\n  // Last key handed to the host credential store per provider, so a request\n  // that did not rotate anything writes nothing.\n  publishedOAuthKeys: Map<string, string>\n  // The host-shared slice this package state was built over.\n  shared: SharedHostState\n  // Package-scoped terminal surface selected by public capabilities. Today\n  // this can be dsh-TUI (`tuiScenes`) or dsh-pi-tui (`piTuiExtensions`);\n  // Pi packages see one unchanged ctx.ui contract either way.\n  tuiSurfaces: TerminalSurfaceAdapter | undefined\n}\n\ntype PiAiLlmBridge = (\n  model: UnknownRecord,\n  context: UnknownRecord,\n  options: UnknownRecord | undefined,\n) => ReturnType<typeof streamViaDshLlm>\n\ntype SubagentSessionFactory = (\n  options: Record<string, unknown>,\n) => Promise<{ session: unknown }>\n\ninterface PiExecOptions {\n  signal?: AbortSignal\n  timeout?: number\n  cwd?: string\n}\n\ninterface DshSubprocessHandle {\n  collected: {\n    stdout?: { readFrom(offset: number): { text: string; lossy: boolean } }\n    stderr?: { readFrom(offset: number): { text: string; lossy: boolean } }\n  }\n  done: Promise<{ exitCode: number | null; signal: string | null }>\n}\n\ninterface DshSubprocessService {\n  resolveExecutable(command: string, env?: Readonly<Record<string, string>>, signal?: AbortSignal): Promise<string>\n  spawn(spec: UnknownRecord): DshSubprocessHandle\n}\n\ninterface DshAgent extends UnknownRecord {\n  steer(message: unknown): void\n  followup(message: unknown): void\n  inject(message: unknown): void\n}\n\nfunction logger(ctx: Context): { warn(message: string): void; info(message: string): void; debug(message: string): void } {\n  const candidate = (ctx as unknown as { logger?: Partial<ReturnType<typeof logger>> }).logger\n  return {\n    warn: message => candidate?.warn?.(message) ?? console.warn(message),\n    info: message => candidate?.info?.(message) ?? console.info(message),\n    debug: message => candidate?.debug?.(message) ?? undefined,\n  }\n}\n\nfunction cloneJson<T>(value: T): T {\n  return structuredClone(value)\n}\n\nfunction jsonEqual(left: unknown, right: unknown): boolean {\n  try {\n    return JSON.stringify(left) === JSON.stringify(right)\n  } catch {\n    return false\n  }\n}\n\nfunction jsonValue(value: unknown): unknown {\n  if (value === undefined) return null\n  try {\n    return JSON.parse(JSON.stringify(value)) as unknown\n  } catch {\n    return String(value)\n  }\n}\n\nfunction textBlocks(content: unknown): Array<{ type: 'text'; text: string }> {\n  if (!Array.isArray(content)) return [{ type: 'text', text: String(content ?? '') }]\n  return content.map((block): { type: 'text'; text: string } => {\n    if (typeof block === 'object' && block !== null && (block as UnknownRecord).type === 'text') {\n      return { type: 'text', text: String((block as UnknownRecord).text ?? '') }\n    }\n    if (typeof block === 'object' && block !== null && (block as UnknownRecord).type === 'image') {\n      const mime = String((block as UnknownRecord).mimeType ?? 'image')\n      return { type: 'text', text: `[Pi tool returned ${mime}; binary image output requires a native DSH attachment adapter]` }\n    }\n    return { type: 'text', text: String(block) }\n  })\n}\n\nfunction normalizeToolResult(result: unknown): UnknownRecord {\n  if (typeof result !== 'object' || result === null || Array.isArray(result)) {\n    return { content: [{ type: 'text', text: String(result ?? '') }], details: null }\n  }\n  const record = result as UnknownRecord\n  return {\n    content: textBlocks(record.content),\n    details: jsonValue(record.details),\n    ...(record.isError === true ? { isError: true } : {}),\n    ...(record.usage !== undefined ? { usage: jsonValue(record.usage) } : {}),\n    ...(record.terminate === true ? { terminate: true } : {}),\n  }\n}\n\nasync function piToDshContent(ctx: Context, content: unknown): Promise<ContentBlock[]> {\n  const values = Array.isArray(content) ? content : [{ type: 'text', text: String(content ?? '') }]\n  const blocks: ContentBlock[] = []\n  for (const value of values) {\n    if (typeof value !== 'object' || value === null) {\n      blocks.push({ type: 'text', text: String(value) })\n      continue\n    }\n    const block = value as UnknownRecord\n    if (block.type === 'text') {\n      blocks.push({ type: 'text', text: String(block.text ?? '') })\n      continue\n    }\n    if (block.type !== 'image') {\n      blocks.push({ type: 'text', text: String(value) })\n      continue\n    }\n    const attachments = optionalService<{\n      saveImage(input: { data: Uint8Array; mediaType: string; name?: string }): Promise<UnknownRecord>\n    }>(ctx, 'attachments')\n    if (attachments === undefined) {\n      throw new Error('pi2dsh: Pi image content requires the DSH attachments service')\n    }\n    if (typeof block.data !== 'string' || typeof block.mimeType !== 'string') {\n      throw new TypeError('pi2dsh: Pi image content requires base64 data and mimeType')\n    }\n    const attachment = await attachments.saveImage({\n      data: Buffer.from(block.data, 'base64'),\n      mediaType: block.mimeType,\n      ...(typeof block.name === 'string' ? { name: block.name } : {}),\n    })\n    blocks.push({ type: 'image', attachment } as unknown as ContentBlock)\n  }\n  return blocks\n}\n\nasync function normalizeToolResultForDsh(ctx: Context, result: unknown): Promise<UnknownRecord> {\n  if (typeof result !== 'object' || result === null || Array.isArray(result)) {\n    return { content: [{ type: 'text', text: String(result ?? '') }], details: null }\n  }\n  const record = result as UnknownRecord\n  return {\n    content: await piToDshContent(ctx, record.content),\n    details: jsonValue(record.details),\n    ...(record.isError === true ? { isError: true } : {}),\n    ...(record.usage !== undefined ? { usage: jsonValue(record.usage) } : {}),\n    ...(record.terminate === true ? { terminate: true } : {}),\n  }\n}\n\nconst SUPPORTED_SCHEMA_KEYS = new Set([\n  'type', 'oneOf', 'anyOf', 'properties', 'required', 'additionalProperties',\n  'items', 'enum', 'const', 'description', 'title', 'default', 'examples',\n])\n\nfunction normalizeSchemaNode(value: unknown, path: string, warnings: string[]): UnknownRecord {\n  if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n    warnings.push(`${path}: non-object schema replaced with unconstrained JSON`)\n    return {}\n  }\n  const source = value as UnknownRecord\n  const output: UnknownRecord = {}\n  for (const key of Object.keys(source)) {\n    if (!SUPPORTED_SCHEMA_KEYS.has(key)) warnings.push(`${path}.${key}: constraint is not enforced by DSH and was dropped`)\n  }\n  const type = source.type\n  if (typeof type === 'string' && ['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(type)) {\n    output.type = type\n  } else if (type !== undefined) {\n    warnings.push(`${path}.type: unsupported type was dropped`)\n  }\n  const union = Array.isArray(source.oneOf) ? source.oneOf : Array.isArray(source.anyOf) ? source.anyOf : undefined\n  if (union !== undefined) {\n    if (source.anyOf !== undefined) warnings.push(`${path}.anyOf: converted to DSH exact-one oneOf semantics`)\n    output.oneOf = union.map((entry, index) => normalizeSchemaNode(entry, `${path}.oneOf[${index}]`, warnings))\n    delete output.type\n  }\n  if (output.type === 'object') {\n    const properties = typeof source.properties === 'object' && source.properties !== null && !Array.isArray(source.properties)\n      ? source.properties as UnknownRecord\n      : {}\n    output.properties = Object.fromEntries(\n      Object.entries(properties).map(([key, entry]) => [key, normalizeSchemaNode(entry, `${path}.properties.${key}`, warnings)]),\n    )\n    if (Array.isArray(source.required)) output.required = source.required.filter(item => typeof item === 'string')\n    if (typeof source.additionalProperties === 'boolean') output.additionalProperties = source.additionalProperties\n    else if (source.additionalProperties !== undefined) {\n      output.additionalProperties = true\n      warnings.push(`${path}.additionalProperties: schema-valued form widened to true`)\n    }\n  }\n  if (output.type === 'array' && source.items !== undefined) {\n    output.items = normalizeSchemaNode(source.items, `${path}.items`, warnings)\n  }\n  if (Array.isArray(source.enum)) output.enum = source.enum.filter(item => item === null || ['string', 'number', 'boolean'].includes(typeof item))\n  if (source.const === null || ['string', 'number', 'boolean'].includes(typeof source.const)) output.const = source.const\n  for (const annotation of ['description', 'title'] as const) {\n    if (typeof source[annotation] === 'string') output[annotation] = source[annotation]\n  }\n  for (const annotation of ['default', 'examples'] as const) {\n    if (source[annotation] !== undefined) output[annotation] = jsonValue(source[annotation])\n  }\n  return output\n}\n\nexport function normalizeToolSchema(schema: unknown): { schema: UnknownRecord; warnings: string[] } {\n  const warnings: string[] = []\n  const normalized = normalizeSchemaNode(schema, '$', warnings)\n  if (normalized.type !== 'object') {\n    throw new TypeError('Pi tool parameters must use an object-root TypeBox schema')\n  }\n  return { schema: normalized, warnings }\n}\n\nfunction cwdOf(agent: UnknownRecord | undefined): string {\n  const session = agent?.session\n  if (typeof session === 'object' && session !== null) {\n    const header = (session as UnknownRecord).header\n    if (typeof header === 'object' && header !== null && typeof (header as UnknownRecord).cwd === 'string') {\n      return (header as UnknownRecord).cwd as string\n    }\n  }\n  return process.cwd()\n}\n\nfunction unsupported(name: string): never {\n  throw new Error(`pi2dsh: Pi API ${name} requires a native DSH port; inspect the compatibility report`)\n}\n\n// One capability ledger per host: capability-gap hits are package facts with a\n// host-level user-facing report channel (once per package+capability).\nfunction capabilityLedgerOf(ctx: Context, state: RuntimeState): CapabilityLedger {\n  const shared = state.shared\n  if (shared.capabilityLedger === undefined) {\n    shared.capabilityLedger = new CapabilityLedger(message => logger(ctx).warn(message))\n  }\n  return shared.capabilityLedger\n}\n\nfunction optionalService<T>(ctx: Context, name: string): T | undefined {\n  return (ctx as unknown as { get(name: string): unknown }).get(name) as T | undefined\n}\n\nfunction requireAgent(state: RuntimeState, operation: string): DshAgent {\n  const agent = currentAgent(state)\n  if (agent === undefined) {\n    throw new Error(`pi2dsh: ${operation} requires one active DSH agent context`)\n  }\n  return agent as DshAgent\n}\n\nfunction answerText(answer: UnknownRecord | undefined): string | undefined {\n  if (answer === undefined) return undefined\n  if (typeof answer.custom === 'string' && answer.custom.length > 0) return answer.custom\n  const selected = answer.selected\n  return Array.isArray(selected) && typeof selected[0] === 'string' ? selected[0] : undefined\n}\n\nasync function askOne(\n  ctx: Context,\n  agent: UnknownRecord | undefined,\n  signal: AbortSignal | undefined,\n  question: UnknownRecord,\n): Promise<string | undefined> {\n  const service = optionalService<{\n    ask(request: UnknownRecord): Promise<{ answers: UnknownRecord[] }>\n  }>(ctx, 'userQuestions')\n  if (service === undefined) unsupported('ctx.ui AskUser')\n  try {\n    const result = await service.ask({ questions: [question], ...(agent !== undefined ? { agent } : {}), signal })\n    return answerText(result.answers.find(answer => answer.id === question.id))\n  } catch (error) {\n    // Pi's ExtensionUIDialogOptions.signal means \"programmatically dismiss\n    // the dialog\": a dismissed dialog resolves undefined, same as the user\n    // cancelling — it is not an error the package must handle.\n    if (signal?.aborted === true) return undefined\n    throw error\n  }\n}\n\nfunction agentSession(agent: UnknownRecord | undefined): { id: string; events: unknown } | undefined {\n  const session = agent?.session\n  if (typeof session !== 'object' || session === null) return undefined\n  const record = session as UnknownRecord\n  if (typeof record.id !== 'string') return undefined\n  return record as unknown as { id: string; events: unknown }\n}\n\n// A child agent's session (subagent origin: reviewer sessions, tool workers)\n// is not a Pi host session; its lifecycle and event stream must never project\n// into the Pi extensions mounted on the parent.\nfunction isSubagentOrigin(subject: UnknownRecord | undefined): boolean {\n  const session = (subject?.session ?? subject) as UnknownRecord | undefined\n  const header = session?.header as UnknownRecord | undefined\n  // The durable header carries creation meta FLATTENED (origin sits beside\n  // id/cwd/parentSession); older/mock shapes may nest it under meta.\n  return header?.origin === 'subagent'\n    || (header?.meta as UnknownRecord | undefined)?.origin === 'subagent'\n    || (session?.meta as UnknownRecord | undefined)?.origin === 'subagent'\n}\n\n// Pi ctx.model: a setModel() override wins; otherwise the live DSH agent's\n// own route (Agent.options.provider/model), enriched from the catalog.\n// An image-admission companion selection reports its ORIGINAL route: the\n// generating model is the original text-only one, and that truth is what\n// extensions branching on input modalities need.\nfunction currentPiModel(state: RuntimeState, agent: UnknownRecord): UnknownRecord | undefined {\n  const override = state.modelOverrides.get(agent)\n  const options = agent.options as { provider?: unknown, model?: unknown } | undefined\n  const durable = lastRequestRouteOf(agentSession(agent))\n  const selectedProvider = String(override?.provider ?? durable?.provider ?? options?.provider ?? '')\n  const provider = state.companionRoutes.get(selectedProvider) ?? selectedProvider\n  const id = String(override?.model ?? durable?.model ?? options?.model ?? '')\n  if (id.length === 0) return override\n  const known = provider.length > 0 ? state.modelCatalog?.find(provider, id) : undefined\n  return known ?? { id, name: id, provider, api: 'faux', input: ['text'], reasoning: false }\n}\n\n/**\n * The provider/model of a session's LAST model request, read off the durable\n * log's request/header — the authority on what the caller is ACTUALLY running.\n * A UI/`/model` switch never touches the creation-time AgentOptions snapshot,\n * so a child inheriting the snapshot runs on a stale route (the exact\n * inheritance bug DSH's own subagent line reports); the durable header is\n * where the live truth lands, in either of its two observed nestings.\n */\nfunction lastRequestRouteOf(session: UnknownRecord | undefined): { provider?: string, model?: string } | undefined {\n  if (session === undefined) return undefined\n  const events = eventsOf(session)\n  for (let i = events.length - 1; i >= 0; i -= 1) {\n    const event = events[i] as UnknownRecord\n    if (event.type !== 'request/header') continue\n    const data = (event.data ?? {}) as UnknownRecord\n    const header = (data.header ?? {}) as UnknownRecord\n    for (const shape of [data.config, header.config, header, data] as Array<UnknownRecord | undefined>) {\n      if (typeof shape?.model === 'string' && shape.model.length > 0) {\n        return {\n          model: shape.model,\n          ...(typeof shape.provider === 'string' && shape.provider.length > 0 ? { provider: shape.provider } : {}),\n        }\n      }\n    }\n    return undefined\n  }\n  return undefined\n}\n\n/**\n * The route a spawned child inherits, by authority: an explicit Pi\n * ctx.setModel() override wins, then the caller's last durable request\n * (UI/`/model` switches land there), then the creation-time snapshot.\n */\nfunction resolveCallerRoute(\n  override: { provider?: string, model?: string } | undefined,\n  durable: { provider?: string, model?: string } | undefined,\n  snapshot: { provider?: string, model?: string } | undefined,\n): { provider?: string, model?: string } | undefined {\n  const pick = override ?? durable ?? snapshot\n  if (typeof pick?.model !== 'string' || pick.model.length === 0) return undefined\n  return pick\n}\n\n/** A session's durable events, whether the store exposes them as value or method. */\nfunction eventsOf(session: UnknownRecord): readonly UnknownRecord[] {\n  return readSessionEvents(session)\n}\n\n/** The session id a presentation call belongs to, or '' outside a session. */\nfunction sessionIdOf(state: RuntimeState, agent: UnknownRecord | undefined): string {\n  const session = agentSession(agent ?? currentAgent(state))\n  return session === undefined ? '' : String(session.id ?? '')\n}\n\n/**\n * Record one Pi presentation call against the session that made it.\n * @param ctx - context, for the logger on an unmounted host.\n * @param state - runtime state carrying the shared surface registry.\n * @param agent - the agent whose context the call came through.\n * @param key - which surface.\n * @param value - a string or Pi component; undefined clears it.\n */\nfunction putSurface(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  key: SurfaceKey,\n  value: unknown,\n): void {\n  const surfaces = state.shared.browserSurfaces\n  if (surfaces === undefined) return\n  // The headless theme styles factory-built chrome with identity functions,\n  // which is exactly what a text projection needs.\n  surfaces.setSurface(sessionIdOf(state, agent), state.packageName, key, value, state.theme)\n}\n\nfunction thinkingLevelOf(state: RuntimeState, agent: UnknownRecord | undefined): string {\n  if (agent !== undefined) {\n    const scoped = state.thinkingLevels.get(agent)\n    if (scoped !== undefined) return scoped\n  }\n  return state.globalThinkingLevel\n}\n\n// Durable-log projection entries carry their source seq in the id (\"dsh-<seq>\").\n// Sidecar entries (package-appended) have generated ids and are NOT part of the\n// durable log, so they cannot anchor a fork.\nfunction durableSeqOf(entryId: string): number | undefined {\n  const match = /^dsh-(\\d+)$/.exec(entryId)\n  return match === null ? undefined : Number(match[1])\n}\n\ninterface DshSessionsService {\n  create(id?: unknown, options?: UnknownRecord): UnknownRecord\n  fork(source: unknown, boundary?: number, childSessionId?: unknown): UnknownRecord\n  get(id: unknown): UnknownRecord | undefined\n  list(): UnknownRecord[]\n}\n\n// DSH's official fork constraint: the seed must not end inside an open turn.\n// Pi allows forking at any entry, so the requested boundary shrinks to the\n// nearest safe position at or before it (documented in compatibility.ts).\nfunction shrinkToTurnBoundary(events: readonly UnknownRecord[], boundary: number): number {\n  const slice = events.slice(0, boundary + 1)\n  for (let i = slice.length - 1; i >= 0; i--) {\n    const type = slice[i]?.type\n    if (type === 'turn/end') return boundary\n    if (type === 'turn/start') return Number(slice[i]!.seq) - 1\n  }\n  return boundary\n}\n\n// Summarize the durable slice abandoned by navigateTree, with Pi's own\n// vendored summarizer; the model call runs on the DSH llm bridge. Returns\n// undefined (navigation proceeds unsummarized) when no model route or no\n// abandoned content exists.\nasync function summarizeAbandonedBranch(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  events: readonly UnknownRecord[],\n  boundary: number,\n  options: UnknownRecord,\n): Promise<string | undefined> {\n  const abandoned = events.slice(boundary + 1)\n  if (abandoned.length === 0) return undefined\n  const model = agent === undefined ? undefined : currentPiModel(state, agent)\n  if (model === undefined) {\n    logger(ctx).warn('[pi2dsh] ctx.navigateTree: no current model route, navigating without a branch summary')\n    return undefined\n  }\n  const projection = state.bridge.readonlySessionManager(\n    { id: 'pi2dsh-abandoned-branch', events: abandoned } as never,\n    cwdOf(agent),\n  ) as { getEntries?(): unknown[] }\n  const entries = projection.getEntries?.() ?? []\n  if (entries.length === 0) return undefined\n  const result = await generateBranchSummary(entries, {\n    model,\n    signal: new AbortController().signal,\n    ...(typeof options.customInstructions === 'string' ? { customInstructions: options.customInstructions } : {}),\n    ...(options.replaceInstructions === true ? { replaceInstructions: true } : {}),\n  }) as { summary?: string; error?: string; aborted?: boolean }\n  if (result.error !== undefined) {\n    logger(ctx).warn(`[pi2dsh] ctx.navigateTree: branch summarization failed (${result.error}), navigating without a summary`)\n    return undefined\n  }\n  return result.summary\n}\n\n/** Resolve Pi's official `ExtensionUIDialogOptions` third argument\n * (`{ signal?, timeout? }`, types.ts:96 at the pinned upstream) into one\n * abort signal. A bare AbortSignal is also accepted — pi-ai's OAuth prompt\n * callbacks hand the signal directly. Anything else resolves to undefined.\n * The `timeout` field is realized with AbortSignal.timeout, so a dialog the\n * package wants auto-dismissed really leaves the screen. Silently ignoring\n * the options object is what left the OAuth paste box on screen after the\n * browser callback had already won (pi-mcp-adapter passes\n * `ui.input(title, undefined, { signal })` and cancels it in its\n * waitForAuthorizationResponse finally block). */\nfunction dialogAbortSignal(opts: unknown): AbortSignal | undefined {\n  if (opts instanceof AbortSignal) return opts\n  if (typeof opts !== 'object' || opts === null) return undefined\n  const record = opts as { signal?: unknown; timeout?: unknown }\n  const signals: AbortSignal[] = []\n  if (record.signal instanceof AbortSignal) signals.push(record.signal)\n  if (typeof record.timeout === 'number' && Number.isFinite(record.timeout) && record.timeout > 0) {\n    signals.push(AbortSignal.timeout(record.timeout))\n  }\n  if (signals.length === 0) return undefined\n  return signals.length === 1 ? signals[0] : AbortSignal.any(signals)\n}\n\nconst OSC8_HYPERLINK = /\\u001b\\]8;[^;]*;([^\\u0007\\u001b]*)(?:\\u0007|\\u001b\\\\)([\\s\\S]*?)\\u001b\\]8;;(?:\\u0007|\\u001b\\\\)/gu\nconst MARKDOWN_LINK = /\\[([^\\]]+)\\]\\(([^)]+)\\)/gu\n\ninterface DialogPromptProjection {\n  question: string\n  detail?: string\n}\n\ntype DialogLinkMode = 'markdown' | 'terminal'\n\n/**\n * Translate terminal-oriented Pi dialog copy into DSH's native question\n * shape. Pi packages legitimately put OSC 8 links and a multi-line body in\n * the dialog title because Pi's TUI owns that whole text block. DSH separates\n * a plain-text heading from a Markdown detail block, and its Web client renders\n * terminal control bytes literally. Keep the plugin's words and destination,\n * but move them onto the host's real presentation contract.\n */\nfunction projectDialogPrompt(\n  title: unknown,\n  supplementalDetail: unknown,\n  linkMode: DialogLinkMode,\n): DialogPromptProjection {\n  const linkedUrls = new Set<string>()\n  const normalize = (value: unknown): string => {\n    const formatted = String(value).replace(\n    OSC8_HYPERLINK,\n    (whole, url: string, label: string) => {\n      linkedUrls.add(url)\n      if (linkMode === 'terminal') return whole\n      const safeLabel = stripTerminalSequences(label).replace(/([\\\\\\[\\]])/gu, '\\\\$1')\n      return `[${safeLabel}](${url})`\n    },\n    )\n    return (linkMode === 'terminal' ? formatted : stripTerminalSequences(formatted)).replace(/\\r\\n?/gu, '\\n')\n  }\n\n  const titleLines = normalize(title).split('\\n')\n  while (titleLines[0]?.trim() === '') titleLines.shift()\n  while (titleLines.at(-1)?.trim() === '') titleLines.pop()\n\n  const headingLine = titleLines.shift()?.trim() || 'Input required'\n  const headingHasLink = linkMode === 'terminal'\n    ? headingLine.includes('\\u001b]8;')\n    : [...headingLine.matchAll(MARKDOWN_LINK)].length > 0\n  const question = linkMode === 'terminal'\n    ? stripTerminalSequences(headingLine)\n    : headingLine.replace(MARKDOWN_LINK, '$1')\n  if (headingHasLink) titleLines.unshift('', headingLine)\n\n  const detailLines = [...titleLines]\n  if (supplementalDetail !== undefined) {\n    if (detailLines.length > 0 && detailLines.at(-1)?.trim() !== '') detailLines.push('')\n    detailLines.push(...normalize(supplementalDetail).split('\\n'))\n  }\n\n  const deduplicated: string[] = []\n  for (const line of detailLines) {\n    if (linkedUrls.has(line.trim())) continue\n    if (line.trim() === '' && deduplicated.at(-1)?.trim() === '') continue\n    deduplicated.push(line.replace(/[ \\t]+$/gu, ''))\n  }\n  while (deduplicated[0]?.trim() === '') deduplicated.shift()\n  while (deduplicated.at(-1)?.trim() === '') deduplicated.pop()\n\n  const detail = deduplicated.join('\\n')\n  return { question, ...(detail.length === 0 ? {} : { detail }) }\n}\n\nfunction contextFor(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  signal: AbortSignal | undefined,\n  command = false,\n  sessionOverride?: UnknownRecord,\n  headlessUi = false,\n): UnknownRecord {\n  const notices: string[] = []\n  const userQuestions = optionalService(ctx, 'userQuestions')\n  // The same native DSH question seam has two renderers: Web consumes\n  // Markdown detail, while dsh-TUI consumes terminal text and preserves OSC 8.\n  // Keep one dialog lifecycle/answer path, choosing only the link encoding the\n  // active public surface actually renders.\n  const dialogLinkMode: DialogLinkMode = optionalService(ctx, 'tuiScenes') === undefined ? 'markdown' : 'terminal'\n  const ui = {\n    // Pi: `notify(message, type?: 'info' | 'warning' | 'error')`. The severity\n    // is the whole point of the second argument — dropping it filed a\n    // package's error notification at info, where an operator scanning for\n    // problems never sees it.\n    notify(message: unknown, type?: unknown) {\n      const text = String(message)\n      notices.push(text)\n      state.notifications.push(text)\n      const level = type === 'warning' || type === 'error' ? 'warn' : 'info'\n      logger(ctx)[level](`[pi2dsh] ${text}`)\n    },\n    // Pi's contract is that select() returns ONE OF THE OPTIONS. DSH's dialog\n    // renders them as numbered rows and also offers a free-text box, so a user\n    // who types what they read on screen (\"1\", or a differently-cased name)\n    // sends text that is not an option — and the package then rejects its own\n    // answer (\"Unknown OpenAI Codex login method: 1\"). Resolve back to the\n    // option here, once, for every package rather than in each caller.\n    select: async (title: unknown, options: unknown[], opts?: unknown) => {\n      const labels = options.map(option => String(option))\n      const answered = await askOne(ctx, agent, joinSignals(signal, dialogAbortSignal(opts)), {\n        id: 'pi2dsh-select',\n        ...projectDialogPrompt(title, undefined, dialogLinkMode),\n        options: labels.map(label => ({ label })),\n      })\n      return answered === undefined ? undefined : resolveOfferedChoice(answered, labels)\n    },\n    async confirm(title: unknown, message: unknown, opts?: unknown) {\n      return await askOne(ctx, agent, joinSignals(signal, dialogAbortSignal(opts)), {\n        id: 'pi2dsh-confirm',\n        ...projectDialogPrompt(title, message, dialogLinkMode),\n        options: [{ label: 'Yes' }, { label: 'No' }],\n      }) === 'Yes'\n    },\n    // Pi's dialog surfaces take ExtensionUIDialogOptions as their trailing\n    // argument; dialogAbortSignal resolves it (and the bare-signal shape\n    // pi-ai's OAuth prompt callbacks use) so a package cancelling one prompt\n    // path really dismisses the DSH question — the browser callback beating\n    // the paste box must take the paste box off the screen.\n    input: (title: unknown, placeholder?: unknown, opts?: unknown) => askOne(\n      ctx, agent, joinSignals(signal, dialogAbortSignal(opts)), {\n        id: 'pi2dsh-input',\n        ...projectDialogPrompt(title, placeholder, dialogLinkMode),\n      }),\n    // Device-code OAuth does not ask for text after announcing the code; the\n    // provider simply polls. Keep that expiring code in DSH's live question\n    // surface until the flow finishes. Any user dismissal is a cancellation,\n    // which oauthInteraction turns into an abort of the package-owned flow.\n    deviceCode: async (title: unknown, detail: unknown, opts?: unknown) => {\n      await askOne(ctx, agent, joinSignals(signal, dialogAbortSignal(opts)), {\n        id: 'pi2dsh-device-code',\n        ...projectDialogPrompt(title, detail, dialogLinkMode),\n        options: [{ label: 'Cancel login' }],\n      })\n    },\n    editor: (title: unknown, prefill?: unknown) => askOne(ctx, agent, signal, {\n      id: 'pi2dsh-editor',\n      ...projectDialogPrompt(title, prefill === undefined ? undefined : `Current text:\\n${String(prefill)}`, dialogLinkMode),\n    }),\n    // Pi's presentation calls, on DSH's browser surface. Each records what the\n    // package put on screen for THIS session; the bridge's own browser half\n    // draws it in the host's matching slot. Signatures are Pi's exact ones\n    // (types.ts): setStatus/setWidget are keyed, setFooter/setHeader take\n    // factories, setWorkingIndicator takes {frames}. In a composition with no\n    // web server (the CLI profile) the recording is simply never read — the\n    // same shape as Pi's own non-TUI modes, where these are accepted and\n    // nothing draws.\n    setStatus: (key: unknown, text: unknown) => {\n      const surfaces = state.shared.browserSurfaces\n      surfaces?.setStatus(sessionIdOf(state, agent), state.packageName, String(key), text)\n      state.tuiSurfaces?.setStatus(String(key), text)\n    },\n    setWidget: (key: unknown, content: unknown) => {\n      const surfaces = state.shared.browserSurfaces\n      if (surfaces === undefined) return\n      // Lines or a component factory, both rendered by the server half with\n      // the same headless theme the header and footer use.\n      surfaces.setWidget(sessionIdOf(state, agent), state.packageName, String(key), content, state.theme)\n    },\n    onTerminalInput: () => () => undefined,\n    setWorkingMessage: (message?: unknown) => putSurface(ctx, state, agent, 'workingMessage', message),\n    setWorkingVisible: (visible: unknown) => {\n      const surfaces = state.shared.browserSurfaces\n      if (surfaces === undefined) return\n      surfaces.setWorkingVisible(sessionIdOf(state, agent), state.packageName, visible !== false)\n    },\n    setWorkingIndicator: (options?: unknown) => putSurface(ctx, state, agent, 'workingIndicator', options),\n    setHiddenThinkingLabel: (label?: unknown) => putSurface(ctx, state, agent, 'hiddenThinkingLabel', label),\n    setFooter: (factory?: unknown) => putSurface(ctx, state, agent, 'footer', factory),\n    setHeader: (factory?: unknown) => putSurface(ctx, state, agent, 'header', factory),\n    // Pi's setTitle is transient window chrome. It deliberately does NOT rename\n    // the DSH session: a session title is durable, user-owned and shown in the\n    // session list, and quietly rewriting it would outlive the turn that asked.\n    setTitle: (title: unknown) => putSurface(ctx, state, agent, 'title', title),\n    // A terminal composition gets the package's real Pi component through\n    // dsh-TUI's public full-screen scene seam. Everything else — web included\n    // — resolves undefined, Pi's own rpc-mode behavior. The web used to\n    // project the component's terminal frames into a modal; that standard was\n    // killed (2026-08-29, user decision): a browser surface renders product\n    // UI (side-chat window, MCP tab, pills), never a projected TUI, and every\n    // scene consumer verified on web already had a product face carrying the\n    // same content (pi-btw → side-chat window, /pi-mcp → the MCP tab).\n    custom: async (factory: unknown, options?: unknown) => {\n      if (typeof factory !== 'function') return undefined\n      // A product-UI invocation (the side-chat window running a package\n      // command) presents the results itself; the package's own full-screen\n      // component would DOUBLE that presentation over it. Resolving undefined\n      // is Pi's own rpc-mode behavior — an official degradation, not a lie.\n      if (headlessUi) return undefined\n      const surfaces = state.tuiSurfaces\n      if (surfaces !== undefined) {\n        return surfaces.custom(\n          factory as PiCustomFactory<unknown>,\n          state.theme,\n          getKeybindings(),\n          options as PiCustomOptions | undefined,\n        )\n      }\n      // A declared browser product surface owns presentation (side threads,\n      // MCP pages, etc.). Keep its established RPC degradation; native\n      // question dialogs alone must not turn that into a command failure.\n      if (state.shared.browserSurfacesRouted === true) return undefined\n      if (humanAnswererAvailable(userQuestions, agent, state.shared)) {\n        const gap = {\n          capability: 'ui.custom',\n          reason: 'native dialogs are available, but this surface has no terminal-component renderer.',\n          guidance: 'Use the package\\'s non-terminal fallback or a DSH terminal surface.',\n          packageName: state.packageName,\n        }\n        capabilityLedgerOf(ctx, state).reportDegraded(gap)\n        throw new PiCapabilityError(gap)\n      }\n      return undefined\n    },\n    // Pi's editor calls, on DSH's real composer. `inputActions.setDraft` is\n    // part of the session standard kit every session-scoped slot component\n    // receives, so the bridge's own browser half can perform the write; the\n    // per-agent buffer stays as the answer for a composition with no browser\n    // (the CLI profile), where Pi's own non-interactive modes behave the same.\n    pasteToEditor(text: unknown) {\n      const surfaces = state.shared.browserSurfaces\n      const sessionId = sessionIdOf(state, agent)\n      const current = surfaces?.liveDraft(sessionId) ?? (agent === undefined ? '' : state.editorBuffers.get(agent) ?? '')\n      const next = current + String(text)\n      if (agent !== undefined) state.editorBuffers.set(agent, next)\n      surfaces?.requestDraft(sessionId, next)\n    },\n    setEditorText(text: unknown) {\n      if (agent !== undefined) state.editorBuffers.set(agent, String(text))\n      state.shared.browserSurfaces?.requestDraft(sessionIdOf(state, agent), String(text))\n    },\n    // The composer's real contents when a browser is showing this session (the\n    // browser half reports them back), falling back to what this package last\n    // wrote when nothing is watching.\n    getEditorText: () => {\n      const live = state.shared.browserSurfaces?.liveDraft(sessionIdOf(state, agent)) ?? ''\n      if (live.length > 0) return live\n      return agent === undefined ? '' : state.editorBuffers.get(agent) ?? ''\n    },\n    addAutocompleteProvider(factory: unknown) {\n      state.autocompleteProviders.push(factory)\n    },\n    setEditorComponent(factory: unknown) {\n      state.editorComponentFactory = factory\n    },\n    getEditorComponent: () => state.editorComponentFactory,\n    get theme() {\n      return state.theme\n    },\n    getAllThemes: () => [{ name: state.theme.name, path: undefined }],\n    getTheme: (name: string) => (name === state.theme.name ? state.theme : undefined),\n    setTheme: (target: unknown) => (\n      typeof target === 'object' || target === state.theme.name\n        ? { success: true }\n        : { success: false, error: `pi2dsh headless mode ships a single theme (${state.theme.name})` }\n    ),\n    getToolsExpanded: () => state.toolsExpanded,\n    setToolsExpanded(expanded: unknown) {\n      state.toolsExpanded = expanded === true\n    },\n  }\n  // A replaced-session context (Pi's withSession callback) binds to the\n  // replacement session while the live agent — and everything that needs\n  // one — stays with the turn that initiated the operation.\n  const session = sessionOverride ?? agentSession(agent)\n  // Pi's ModelRegistry surface over the ONE model directory — the DSH llm\n  // directory — projected faithfully into Pi vocabulary (package-registered\n  // route entries carry their full Pi Model fields through it). Neither\n  // side sees the other: packages read exact Pi Models, DSH routes to\n  // ordinary adapters. The provider-auth half resolves package-registered\n  // providers through Pi's full credential chain (vendored\n  // double-checked-lock refresh) and DSH routes through the host's public\n  // configurable-provider and credentials seams.\n  const providerConfig = (name: string): UnknownRecord | undefined => state.providers.get(name)\n  const catalog = state.modelCatalog\n  // Directory membership comes from the DSH llm directory alone. The DSH\n  // catalog channel detaches entries to its own metadata contract, so the\n  // projection restores each Pi-native route's entry from the registration\n  // source at the exit — packages read the EXACT Pi Model (api, baseUrl,\n  // cost, …) they configured, and never see that a DSH directory sat in\n  // between. DSH-owned routes project as-is.\n  const piNativeEntry = (provider: string, id: string): UnknownRecord | undefined => {\n    // Restore only entries OUR route registration put in the directory\n    // (package providers restore only while they own their route). A\n    // foreign adapter's models never wear a Pi-native configuration's\n    // fields.\n    const source = (state.providerRouteDisposers.has(provider) ? state.providers.get(provider) : undefined) as\n      | { getModels?(): unknown; models?: unknown }\n      | undefined\n    if (source === undefined) return undefined\n    let models: unknown\n    try {\n      models = typeof source.getModels === 'function' ? source.getModels() : source.models\n    } catch {\n      return undefined\n    }\n    if (!Array.isArray(models)) return undefined\n    return (models as UnknownRecord[]).find(model => model.id === id)\n  }\n  const restorePiShape = (entry: UnknownRecord): UnknownRecord => {\n    const native = piNativeEntry(String(entry.provider ?? ''), String(entry.id ?? ''))\n    return native === undefined ? entry : { ...entry, ...native, provider: entry.provider }\n  }\n  const allModels = () => (catalog?.all() ?? []).map(restorePiShape)\n  // THE one call path for every standard Pi model call: package → bridge →\n  // DSH llm route → adapter. No provider surface hands a package a direct\n  // wire transport; the wire clients live inside route adapters only.\n  const dshRoutedStream = (model: UnknownRecord, context: UnknownRecord, options?: UnknownRecord) => {\n    const llm = llmOf(ctx)\n    if (llm === undefined) {\n      throw new Error('pi2dsh: model calls need a DSH llm service; this composition mounts none')\n    }\n    return streamViaDshLlm(llm, { model, context, options: options as never })\n  }\n  const dshRoutedPiProvider = (base: UnknownRecord, providerId: string): UnknownRecord => ({\n    ...base,\n    id: providerId,\n    getModels: () => allModels().filter(model => model.provider === providerId),\n    stream: dshRoutedStream,\n    streamSimple: dshRoutedStream,\n  })\n  const modelRegistry = {\n    getAll: () => allModels(),\n    getAvailable: () => allModels(),\n    find: (provider: string, modelId: string) => {\n      const entry = catalog?.find(provider, modelId)\n      return entry === undefined ? undefined : restorePiShape(entry)\n    },\n    getError: () => undefined,\n    hasConfiguredAuth: (model: unknown) => {\n      // Configuration check, not key liveness (Pi's is also a config check):\n      // the route resolves iff its provider is in the live llm directory or\n      // registered by a package.\n      const provider = String((model as UnknownRecord | undefined)?.provider ?? '')\n      if (provider.length === 0) return false\n      return state.providers.has(provider)\n        || (catalog?.all() ?? []).some(entry => entry.provider === provider)\n    },\n    // Pi's per-model credential read, two families with one resolver:\n    // package-registered providers use their own declared chain; DSH routes\n    // resolve through the host's public configurable-provider directory and\n    // credentials service. Neither family fabricates a key: no resolution →\n    // not ok.\n    getApiKeyAndHeaders: async (model: unknown) => {\n      const provider = String((model as UnknownRecord | undefined)?.provider ?? '')\n      const config = providerConfig(provider)\n      if (config !== undefined) {\n        const resolved = await resolvePiProviderAuth({\n          providerId: provider, providerConfig: config, store: oauthStoreOf(state),\n        })\n        const auth = resolved?.auth as UnknownRecord | undefined\n        if (auth?.apiKey === undefined) return { ok: false }\n        return {\n          ok: true,\n          apiKey: auth.apiKey,\n          ...(auth.headers === undefined ? {} : { headers: auth.headers as Record<string, string> }),\n          ...(auth.baseUrl === undefined && config.baseUrl === undefined ? {} : { baseUrl: auth.baseUrl ?? config.baseUrl }),\n        }\n      }\n      // A DSH adapter route: its credential reference lives in the public\n      // configurable-provider directory (settingsNs/settingsPath), the\n      // profile's apiKeyEnv, and the credentials service — three public\n      // seams, no name guessing. Any missing step answers not-ok honestly.\n      try {\n        const llm = llmOf(ctx) as unknown as { listConfigurableProviders?(): Array<{ provider: string, settingsNs: string, settingsPath: readonly string[] }> } | undefined\n        const entry = llm?.listConfigurableProviders?.()?.find(candidate => candidate.provider === provider)\n        if (entry === undefined) return { ok: false }\n        const settings = (ctx as unknown as { get(name: string): unknown }).get('settings') as { get(ns: string): unknown } | undefined\n        const section = settings?.get(entry.settingsNs)\n        const profile = entry.settingsPath.reduce<unknown>(\n          (node, key) => (typeof node === 'object' && node !== null ? (node as UnknownRecord)[key] : undefined),\n          section,\n        ) as UnknownRecord | undefined\n        const ref = profile?.apiKeyEnv\n        if (typeof ref !== 'string' || ref.length === 0) return { ok: false }\n        const credentials = (ctx as unknown as { get(name: string): unknown }).get('credentials') as { resolve(ref: string): Promise<{ value?: string } | undefined> } | undefined\n        const resolved = await credentials?.resolve(ref)\n        if (typeof resolved?.value !== 'string' || resolved.value.length === 0) return { ok: false }\n        return { ok: true, apiKey: resolved.value }\n      } catch {\n        return { ok: false }\n      }\n    },\n    getProviderAuthStatus: (provider: string) =>\n      providerSupportsOAuth(providerConfig(provider)) ? 'oauth' : 'none',\n    // Every provider the directory carries answers as a Pi Provider whose\n    // stream surface runs through the DSH llm route — packages never hold a\n    // wire transport. A package-registered provider keeps its fields (Pi's\n    // read-back contract) with its stream rerouted while its route is live;\n    // a DSH-owned route answers a synthesized Pi Provider over its\n    // directory models.\n    getProvider: (provider: string) => {\n      const base = providerConfig(provider)\n      if (base !== undefined) {\n        const routed = state.providerRouteDisposers.has(provider)\n        // A package provider that never became a route keeps its own object:\n        // that transport is the package's own asset, not a bridge surface.\n        return routed ? dshRoutedPiProvider(base, provider) : base\n      }\n      if ((catalog?.all() ?? []).some(entry => entry.provider === provider)) {\n        return dshRoutedPiProvider({ id: provider, name: provider }, provider)\n      }\n      return undefined\n    },\n    // Pi's registry.complete: one designated-model call through the same\n    // single path (the DSH llm route), collected to an AssistantMessage.\n    complete: async (model: unknown, context: unknown, options?: unknown) => {\n      const stream = dshRoutedStream(\n        model as UnknownRecord,\n        (context ?? {}) as UnknownRecord,\n        options as UnknownRecord | undefined,\n      ) as unknown as { result(): Promise<unknown> }\n      const result = await stream.result()\n      if (result instanceof Error) throw result\n      return result\n    },\n    // Pi's ModelRegistry registration surface (model-registry.ts): the same\n    // runtime as pi.registerProvider, so it is the same path here. The string\n    // form requires a config, exactly like Pi.\n    registerProvider: (providerOrName: unknown, config?: UnknownRecord) => {\n      if (typeof providerOrName === 'string' && config === undefined) {\n        throw new Error('Provider config is required when registering by name')\n      }\n      registerPiProvider(ctx, state, providerOrName, config)\n    },\n    unregisterProvider: (provider: string) => unregisterPiProvider(ctx, state, provider),\n    // Pi reads the legacy and native ledgers separately; ids are their union.\n    getRegisteredProviderConfig: (provider: string) =>\n      state.nativeProviders.has(provider) ? undefined : providerConfig(provider),\n    getRegisteredNativeProvider: (provider: string) =>\n      state.nativeProviders.has(provider) ? providerConfig(provider) : undefined,\n    getRegisteredProviderIds: () => [...state.providers.keys()],\n    getProviderDisplayName: (provider: string) => {\n      const config = providerConfig(provider)\n      return typeof config?.name === 'string' ? config.name : provider\n    },\n    getProviderAuth: async (provider: string) => {\n      const config = providerConfig(provider)\n      if (config === undefined) return undefined\n      const resolved = await resolvePiProviderAuth({\n        providerId: provider, providerConfig: config, store: oauthStoreOf(state),\n      })\n      if (resolved?.auth === undefined) return resolved\n      // Pi fills the provider's declared baseUrl when the credential itself\n      // carries none (OAuth toAuth often returns just the key).\n      return resolved.auth.baseUrl === undefined && config.baseUrl !== undefined\n        ? { ...resolved, auth: { ...resolved.auth, baseUrl: config.baseUrl } }\n        : resolved\n    },\n    getApiKeyForProvider: async (provider: string) => {\n      const config = providerConfig(provider)\n      if (config === undefined) return undefined\n      const resolved = await resolvePiProviderAuth({\n        providerId: provider, providerConfig: config, store: oauthStoreOf(state),\n      })\n      return (resolved?.auth as UnknownRecord | undefined)?.apiKey as string | undefined\n    },\n    isUsingOAuth: (model: unknown) => {\n      const provider = String((model as UnknownRecord | undefined)?.provider ?? '')\n      return provider.length > 0 && providerSupportsOAuth(providerConfig(provider))\n    },\n    refresh: async () => {\n      // Pi's refresh() re-reads the model directory projection.\n      await catalog?.refresh()\n      return { models: allModels(), errors: [] }\n    },\n  }\n  const contextCwd = typeof (sessionOverride?.header as UnknownRecord | undefined)?.cwd === 'string'\n    ? (sessionOverride!.header as { cwd: string }).cwd\n    : cwdOf(agent)\n  // Pi's ReplacedSessionContext adds these three on top of the command\n  // context, and they belong to the REPLACEMENT session. Routing them through\n  // the live agent (which still belongs to the turn that started the\n  // operation) wrote into the old session — worse than not implementing them.\n  const replacedSessionActions: UnknownRecord = sessionOverride === undefined ? {} : {\n    sendMessage: (message: UnknownRecord, options: UnknownRecord = {}) => sendPiMessage(\n      ctx, state, message.content, deliveryMode(options), sessionOverride,\n      typeof message.customType === 'string' ? message.customType : undefined,\n    ),\n    sendUserMessage: (content: unknown) => reportUnawaitedDelivery(ctx, state, 'sendUserMessage', sendPiMessage(ctx, state, content, 'followup', sessionOverride)),\n    appendEntry: (customType: string, data?: unknown) => {\n      state.bridge.appendCustomEntry(String(sessionOverride.id ?? ''), customType, data)\n    },\n  }\n  const base: UnknownRecord = {\n    ...replacedSessionActions,\n    ui,\n    // Pi's mode answers ONE question for packages: \"can I show interactive\n    // full-screen UI here?\" (pi-mcp-adapter opens its manager only in tui\n    // mode). Only a real terminal seat answers yes. The web deliberately\n    // reports rpc (2026-08-29): it renders product UI, never a projected\n    // TUI, so claiming tui would send packages' full-screen components into\n    // a seat that no longer exists.\n    get mode(): 'tui' | 'rpc' {\n      return state.tuiSurfaces?.available === true ? 'tui' : 'rpc'\n    },\n    // A getter, not a value: this context is rebuilt for every dispatched\n    // event, and the probe below costs a register/dispose. Packages read\n    // `hasUI` rarely, and reading it lazily also makes the answer current at\n    // the moment it is asked rather than at the moment the context was built.\n    get hasUI(): boolean {\n      return state.tuiSurfaces?.available === true || humanAnswererAvailable(userQuestions, agent, state.shared)\n    },\n    cwd: contextCwd,\n    sessionManager: session === undefined\n      ? state.bridge.readonlySessionManager({ id: 'pi2dsh-detached', events: [] }, contextCwd)\n      : state.bridge.readonlySessionManager(session as never, contextCwd),\n    modelRegistry,\n    // Current effective model: a setModel() override wins; otherwise the DSH\n    // agent's own provider/model route (Agent.options), enriched from the\n    // catalog when the entry is known there.\n    model: agent === undefined ? undefined : currentPiModel(state, agent),\n    // Pi: \"Models scoped to this session … Empty when no scoping is configured\n    // (all available models are usable).\" DSH has no model-scope concept, so\n    // empty is the accurate answer and carries exactly Pi's meaning. Handing\n    // back the whole catalog said the opposite — that the session is RESTRICTED\n    // to every model — and in the wrong shape besides (Pi wants\n    // `{model, thinkingLevel?}` wrappers around Pi Models, not DSH entries).\n    scopedModels: [],\n    thinkingLevel: thinkingLevelOf(state, agent),\n    isIdle: () => command,\n    // Pi's isProjectTrusted() reports the HOST's trust decision for the\n    // directory the session runs in. On DSH that decision is observable, not\n    // absent: the user chose the session's working directory (launched dsh in\n    // it, or added it as a workspace), and the host already runs its own\n    // bash/edit/write there without any further trust prompt — DSH's model is\n    // \"opening a workspace is the trust act\". The old hardcoded `false`\n    // claimed the host ACTIVELY distrusts every project, a stronger statement\n    // than DSH ever makes, and Pi packages honor it literally: pi-lens gates\n    // toolchain spawns on `trustState !== \"untrusted\"`, so a host with no\n    // accessor (unknown) keeps LSP alive while our `false` shut every\n    // language server off (2026-08-27, caught by the code-navigation E2E).\n    // No agent — the host anchor and detached contexts — stays fail-closed:\n    // there is no user-chosen directory to point at.\n    isProjectTrusted: () => agent !== undefined && contextCwd.length > 0,\n    signal,\n    abort: () => {\n      const target = agent as { cancel?(cause: unknown): void } | undefined\n      if (typeof target?.cancel !== 'function') unsupported('ctx.abort without a live DSH agent')\n      target.cancel({ kind: 'hook', reason: 'pi2dsh: aborted by migrated Pi extension' })\n    },\n    // Pi: \"Whether there are queued messages waiting\" — steering plus follow-up.\n    // DSH keeps exactly that on the agent's durable inbox (next-step plus\n    // next-turn); a hardcoded false told every package the queue is always\n    // empty, so anything that waits for the queue to drain never waited.\n    hasPendingMessages: () => {\n      const inbox = agent?.inbox as { nextStep?: readonly unknown[], nextTurn?: readonly unknown[], hasPending?: boolean } | undefined\n      return inbox?.nextStep !== undefined || inbox?.nextTurn !== undefined\n        ? (inbox.nextStep?.length ?? 0) + (inbox.nextTurn?.length ?? 0) > 0\n        : inbox?.hasPending === true\n    },\n    // Pi defines shutdown() as \"request a graceful shutdown; the actual\n    // behavior is provided by the host\" (runner.ts bindExtensions). This\n    // host's behavior: on DSH the user owns process exit, so the request is\n    // absorbed — reported to the user once, and the package keeps running.\n    shutdown: () => {\n      capabilityLedgerOf(ctx, state).reportHostDecision({\n        capability: 'ctx.shutdown',\n        reason: 'Pi delegates shutdown behavior to the host, and on DSH the user owns process exit.',\n        guidance: 'The shutdown request was recorded and ignored.',\n        packageName: state.packageName,\n      })\n    },\n    getContextUsage: () => undefined,\n    // Pi's compact() is a fire-and-forget trigger (void; completion flows\n    // through the options callbacks). Translated to the official DSH manual\n    // compaction surface: ctx.compaction.compactNow() on the live agent.\n    compact: (options?: UnknownRecord) => {\n      const ledger = capabilityLedgerOf(ctx, state)\n      const compaction = optionalService<{\n        compactNow(agent: unknown, signal: AbortSignal): Promise<unknown>\n      }>(ctx, 'compaction')\n      const target = agent as {\n        runMaintenance?: <T>(job: (signal: AbortSignal) => Promise<T>) => Promise<T>\n      } | undefined\n      const onError = (options?.onError as ((error: Error) => void) | undefined)\n      if (compaction === undefined || typeof target?.runMaintenance !== 'function') {\n        const gap = new PiCapabilityError({\n          capability: 'ctx.compact',\n          reason: compaction === undefined\n            ? 'this DSH composition mounts no compaction service.'\n            : 'compaction needs a live DSH agent for this turn.',\n          guidance: 'Compaction runs through the host compaction plugin when one is composed.',\n          packageName: state.packageName,\n        })\n        ledger.reportDegraded({\n          capability: 'ctx.compact',\n          reason: gap.message,\n          guidance: '',\n          packageName: state.packageName,\n        })\n        // Pi's own error channel for compact() is the onError callback, not a\n        // synchronous throw from a void trigger.\n        onError?.(gap)\n        return\n      }\n      void compaction.compactNow(target, new AbortController().signal)\n        .then(result => {\n          if (result === null || result === undefined) return\n          const dsh = result as { summary?: unknown; shadowedTokenCount?: number }\n          const summaryBlocks = Array.isArray(dsh.summary) ? dsh.summary : []\n          const summaryText = summaryBlocks\n            .filter((block): block is { type: string; text: string } =>\n              typeof block === 'object' && block !== null\n              && (block as UnknownRecord).type === 'text'\n              && typeof (block as UnknownRecord).text === 'string')\n            .map(block => block.text)\n            .join('\\n')\n          const onComplete = options?.onComplete as ((result: UnknownRecord) => void) | undefined\n          // Honest projection: summary text and the shadowed-content token\n          // estimate are real; the DSH log has no Pi entry ids, so\n          // firstKeptEntryId is empty (documented in compatibility.ts).\n          onComplete?.({\n            summary: summaryText,\n            firstKeptEntryId: '',\n            tokensBefore: dsh.shadowedTokenCount ?? 0,\n          })\n        })\n        .catch((error: unknown) => {\n          const failure = error instanceof Error ? error : new Error(String(error))\n          if (onError !== undefined) {\n            onError(failure)\n            return\n          }\n          logger(ctx).warn(`[pi2dsh] plugin \"${state.packageName}\": ctx.compact failed: ${failure.message}`)\n        })\n    },\n    getSystemPrompt: () => state.currentSystemPrompt,\n    __agent: agent,\n    __notices: notices,\n  }\n  if (command) {\n    Object.assign(base, {\n      getSystemPromptOptions: () => ({}),\n      waitForIdle: async () => {\n        const wait = agent?.whenIdle\n        if (typeof wait === 'function') await wait.call(agent)\n      },\n      // Pi's session-tree operations, on DSH's OWN official surfaces:\n      // ctx.sessions.create() (new session), ctx.sessions.fork() (prefix fork\n      // with lineage + open-turn validation), and the live session store\n      // (switch). The replacement/forked session really exists — it appears in\n      // the host's session surfaces, and the withSession callback operates on\n      // it through a projection context. What DSH deliberately does NOT have\n      // is a host-level \"current session pointer\" a plugin could move: which\n      // session the user is looking at stays a host-surface choice, announced\n      // once through the ledger.\n      newSession: async (options?: UnknownRecord) => {\n        const sessions = optionalService<DshSessionsService>(ctx, 'sessions')\n        if (sessions === undefined) {\n          capabilityLedgerOf(ctx, state).reportDegraded({\n            capability: 'ctx.newSession',\n            reason: 'this DSH composition mounts no session service.',\n            guidance: '',\n            packageName: state.packageName,\n          })\n          return { cancelled: true }\n        }\n        const parent = agentSession(agent) as { id?: unknown } | undefined\n        const created = sessions.create(undefined, {\n          meta: {\n            cwd: cwdOf(agent),\n            ...(parent?.id === undefined ? {} : { parentSession: parent.id }),\n          },\n        })\n        const withSession = options?.withSession as ((replaced: unknown) => Promise<void>) | undefined\n        await withSession?.(contextFor(ctx, state, agent, signal, true, created))\n        capabilityLedgerOf(ctx, state).reportHostDecision({\n          capability: 'ctx.newSession',\n          reason: `a new DSH session was created (${String((created as { id?: unknown }).id)}).`,\n          guidance: 'Which session the surface shows stays a host choice — open it from the DSH session list.',\n          packageName: state.packageName,\n        })\n        return { cancelled: false }\n      },\n      fork: async (entryId: string, options?: UnknownRecord) => {\n        const sessions = optionalService<DshSessionsService>(ctx, 'sessions')\n        const source = agentSession(agent)\n        if (sessions === undefined || source === undefined) {\n          capabilityLedgerOf(ctx, state).reportDegraded({\n            capability: 'ctx.fork',\n            reason: sessions === undefined\n              ? 'this DSH composition mounts no session service.'\n              : 'forking needs the live session of an active agent.',\n            guidance: '',\n            packageName: state.packageName,\n          })\n          return { cancelled: true }\n        }\n        const seq = durableSeqOf(String(entryId))\n        if (seq === undefined) {\n          throw new Error(\n            `pi2dsh: ctx.fork(${JSON.stringify(String(entryId))}) — only durable-log entries (projected ids \"dsh-<seq>\") `\n            + 'can anchor a fork; package-appended sidecar entries are not part of the DSH durable log',\n          )\n        }\n        // Pi's default position is \"before\": fork the history strictly before\n        // the entry; \"at\" includes it.\n        const position = (options?.position as string | undefined) ?? 'before'\n        const events = readSessionEvents(source)\n        const requested = Math.min(position === 'at' ? seq : seq - 1, events.length - 1)\n        const boundary = requested < 0 ? -1 : shrinkToTurnBoundary(events, requested)\n        const child = boundary < 0\n          ? sessions.create(undefined, {\n              meta: { cwd: cwdOf(agent), parentSession: (source as { id?: unknown }).id },\n            })\n          : sessions.fork(source, boundary)\n        const withSession = options?.withSession as ((replaced: unknown) => Promise<void>) | undefined\n        await withSession?.(contextFor(ctx, state, agent, signal, true, child))\n        capabilityLedgerOf(ctx, state).reportHostDecision({\n          capability: 'ctx.fork',\n          reason: `the session was forked on DSH's official prefix-fork surface (child ${String((child as { id?: unknown }).id)}; DSH forks land on completed-turn boundaries).`,\n          guidance: 'Open the forked session from the DSH session list.',\n          packageName: state.packageName,\n        })\n        return { cancelled: false }\n      },\n      navigateTree: async (targetId: string, options?: UnknownRecord) => {\n        const sessions = optionalService<DshSessionsService>(ctx, 'sessions')\n        const source = agentSession(agent)\n        if (sessions === undefined || source === undefined) {\n          capabilityLedgerOf(ctx, state).reportDegraded({\n            capability: 'ctx.navigateTree',\n            reason: sessions === undefined\n              ? 'this DSH composition mounts no session service.'\n              : 'tree navigation needs the live session of an active agent.',\n            guidance: '',\n            packageName: state.packageName,\n          })\n          return { cancelled: true }\n        }\n        const seq = durableSeqOf(String(targetId))\n        if (seq === undefined) {\n          throw new Error(\n            `pi2dsh: ctx.navigateTree(${JSON.stringify(String(targetId))}) — only durable-log entries (projected ids \"dsh-<seq>\") `\n            + 'can be navigation targets; package-appended sidecar entries are not part of the DSH durable log',\n          )\n        }\n        const events = readSessionEvents(source)\n        const capped = Math.min(seq, events.length - 1)\n        const boundary = capped < 0 ? -1 : shrinkToTurnBoundary(events, capped)\n        const child = boundary < 0\n          ? sessions.create(undefined, {\n              meta: { cwd: cwdOf(agent), parentSession: (source as { id?: unknown }).id },\n            })\n          : sessions.fork(source, boundary)\n        // Pi's navigateTree can summarize the branch being left. The vendored\n        // Pi summarizer runs it over the abandoned durable slice, with the\n        // model call on the DSH llm bridge; without a current model route the\n        // navigation still happens, just unsummarized.\n        if (options?.summarize === true) {\n          const summary = await summarizeAbandonedBranch(ctx, state, agent, events, boundary, options)\n          if (summary !== undefined) {\n            state.bridge.appendBranchSummary(String((child as { id?: unknown }).id), summary, String(targetId))\n          }\n        }\n        if (typeof options?.label === 'string') {\n          state.bridge.appendLabel(String((child as { id?: unknown }).id), String(targetId), options.label)\n        }\n        capabilityLedgerOf(ctx, state).reportHostDecision({\n          capability: 'ctx.navigateTree',\n          reason: `navigation forked the session at the target on DSH's official surface (child ${String((child as { id?: unknown }).id)}; the DSH tree lives BETWEEN sessions via fork lineage, not inside one log).`,\n          guidance: 'Open the navigated session from the DSH session list.',\n          packageName: state.packageName,\n        })\n        return { cancelled: false }\n      },\n      switchSession: async (sessionPath: string, options?: UnknownRecord) => {\n        const sessions = optionalService<DshSessionsService>(ctx, 'sessions')\n        if (sessions === undefined) {\n          capabilityLedgerOf(ctx, state).reportDegraded({\n            capability: 'ctx.switchSession',\n            reason: 'this DSH composition mounts no session service.',\n            guidance: '',\n            packageName: state.packageName,\n          })\n          return { cancelled: true }\n        }\n        // Pi passes a session FILE path; the DSH identity is the session id.\n        // Accept either the bare id or a path whose basename is \"<id>.jsonl\".\n        const raw = String(sessionPath)\n        const base = raw.replace(/\\\\/g, '/').split('/').pop() ?? raw\n        const candidate = state.bridge.sessionIdOfArchiveFile(raw)\n          ?? (base.endsWith('.jsonl') ? base.slice(0, -'.jsonl'.length) : base)\n        const target = sessions.get(candidate) ?? sessions.list().find(entry => String((entry as { id?: unknown }).id) === candidate)\n        if (target === undefined) {\n          throw new Error(\n            `pi2dsh: ctx.switchSession(${JSON.stringify(raw)}) — no live DSH session ${JSON.stringify(candidate)}; `\n            + 'switching to persisted sessions is host-owned (resume them from the DSH surface first)',\n          )\n        }\n        const withSession = options?.withSession as ((replaced: unknown) => Promise<void>) | undefined\n        await withSession?.(contextFor(ctx, state, agent, signal, true, target))\n        capabilityLedgerOf(ctx, state).reportHostDecision({\n          capability: 'ctx.switchSession',\n          reason: `the live DSH session ${JSON.stringify(candidate)} was targeted.`,\n          guidance: 'Which session the surface shows stays a host choice — open it from the DSH session list.',\n          packageName: state.packageName,\n        })\n        return { cancelled: false }\n      },\n      // Pi's reload() re-runs extensions: every mounted package disposes its\n      // registrations and its entries run again through a fresh loader, so\n      // edited plugin code takes effect. Skills/prompts/themes stay\n      // host-managed (they reload with dsh itself) — documented in\n      // compatibility.ts.\n      reload: async () => {\n        const remounts = packageRemountsOf(ctx, state.shared)\n        if (remounts.size === 0) return\n        for (const [name, remount] of remounts) {\n          try {\n            await remount()\n          } catch (error) {\n            logger(ctx).warn(`[pi2dsh] ctx.reload: remounting \"${name}\" failed: ${error instanceof Error ? error.message : String(error)}`)\n          }\n        }\n        capabilityLedgerOf(ctx, state).reportHostDecision({\n          capability: 'ctx.reload',\n          reason: 'extension entries were disposed and remounted through a fresh loader.',\n          guidance: 'Skills, prompts, and themes are host-managed and reload when dsh restarts.',\n          packageName: state.packageName,\n        })\n      },\n    })\n  }\n  return base\n}\n\nasync function dispatch(\n  state: RuntimeState,\n  eventName: string,\n  event: UnknownRecord,\n  eventContext: UnknownRecord,\n): Promise<unknown[]> {\n  const results: unknown[] = []\n  const agent = eventContext.__agent as UnknownRecord | undefined\n  for (const handler of state.handlers.get(eventName) ?? []) {\n    results.push(await runInPiRuntime(state, agent, () => handler(event, eventContext)))\n  }\n  return results\n}\n\nfunction shutdownPiSession(ctx: Context, state: RuntimeState, agent: UnknownRecord, reason: string, signal?: AbortSignal): Promise<void> {\n  const existing = state.shutdownTasks.get(agent)\n  if (existing !== undefined) return existing\n  if (state.piShutdownAgents.has(agent)) return Promise.resolve()\n  state.piShutdownAgents.add(agent)\n  const task = dispatch(state, 'session_shutdown', { type: 'session_shutdown', reason }, contextFor(ctx, state, agent, signal)).then(() => {})\n  state.shutdownTasks.set(agent, task)\n  state.pendingShutdowns.add(task)\n  void task.then(() => state.pendingShutdowns.delete(task), () => state.pendingShutdowns.delete(task))\n  return task\n}\n\n/**\n * Bind every compatibility singleton to this exact Agent runtime for the\n * duration of extension-owned work. AsyncLocalStorage follows promises and\n * detached work spawned inside the callback, so two live Agents cannot\n * overwrite each other's model bridge or child-session factory.\n */\nfunction runInPiRuntime<T>(\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  callback: () => T,\n): T {\n  return state.agentScope.run(agent, () => __runWithSubagentSessionFactory(\n    state.subagentSessionFactory,\n    () => __runWithPiAiRuntime(state.llmBridge, state.piAiRegistry, callback),\n  ))\n}\n\n/**\n * Pi's request-body event is a waterfall over the body the provider transport\n * will actually send. Only package-registered Pi transports expose that body\n * through SimpleStreamOptions.onPayload; native DSH adapters build it behind\n * their own boundary and never call this function.\n */\nasync function dispatchBeforeProviderRequest(\n  ctx: Context,\n  state: RuntimeState,\n  payload: UnknownRecord,\n  request: { provider: string, model: UnknownRecord, sessionId?: string, signal?: AbortSignal },\n): Promise<UnknownRecord> {\n  let current = payload\n  const agent = currentAgent(state)\n  const eventContext = contextFor(ctx, state, agent, request.signal)\n  // A direct ctx.llm.stream() call may have no live agent, but the adapter\n  // still knows the exact selected model. Pi handlers are entitled to it.\n  eventContext.model = { ...request.model, provider: request.provider }\n  for (const handler of state.handlers.get('before_provider_request') ?? []) {\n    try {\n      const result = await runInPiRuntime(state, agent, () => handler({\n        type: 'before_provider_request',\n        payload: current,\n      }, eventContext))\n      if (result !== undefined && typeof result === 'object' && result !== null) {\n        current = result as UnknownRecord\n      }\n    } catch (error) {\n      // Pi isolates extension hook failures: one bad observer must not take\n      // down the provider or prevent later waterfall handlers from running.\n      logger(ctx).warn(`[pi2dsh] before_provider_request handler failed: ${error instanceof Error ? error.message : String(error)}`)\n    }\n  }\n  return current\n}\n\n/** Run Pi's provider-body waterfall through every package runtime of one Agent. */\nasync function dispatchHostProviderRequest(\n  ctx: Context,\n  shared: SharedHostState,\n  fallback: RuntimeState,\n  payload: UnknownRecord,\n  request: { provider: string, model: UnknownRecord, sessionId?: string, signal?: AbortSignal },\n): Promise<UnknownRecord> {\n  const scoped = request.sessionId === undefined\n    ? undefined\n    : shared.runtimeStatesBySession.get(request.sessionId)\n  const states = scoped === undefined || scoped.size === 0 ? [fallback] : [...scoped]\n  let current = payload\n  for (const state of states) {\n    current = await dispatchBeforeProviderRequest(ctx, state, current, request)\n  }\n  return current\n}\n\n/**\n * What triggered a compaction, in Pi's vocabulary.\n *\n * DSH's durable lifecycle events say two things about the trigger: a manual\n * compaction runs with no open turn (`turn: null`), and one a command drove\n * cites that command. Both are Pi's \"manual\".\n *\n * The limit, stated rather than papered over: DSH's automatic trigger is\n * `'pressure' | 'context-overflow'` at the call site but is NOT written to the\n * log, so Pi's `threshold` and `overflow` cannot be told apart after the fact.\n * Automatic compactions report `threshold`, the far more common of the two —\n * and `willRetry` stays false for the same reason. A package keying behavior\n * on `overflow` specifically will not see it.\n * @param data - the `compaction/start` or `compaction/summary` event data.\n */\nfunction compactionReason(data: UnknownRecord): 'manual' | 'threshold' | 'overflow' {\n  if (data.sourceCommandId !== undefined) return 'manual'\n  return data.turn === null ? 'manual' : 'threshold'\n}\n\n/**\n * DSH content → the Pi content blocks packages read.\n *\n * Asynchronous because Pi's image block carries the bytes inline while DSH's\n * carries only an attachment reference, and the bytes come from the attachment\n * service. The sync version this replaced projected an image as a bare\n * `{type:'image'}` — a block that announces an image and contains none, which\n * is the exact shape a package cannot tell from a real one.\n * @param ctx - context used to reach the attachment service.\n * @param content - the DSH blocks to project.\n */\nasync function dshToPiContent(ctx: Context, content: readonly ContentBlock[]): Promise<Array<UnknownRecord>> {\n  const out: UnknownRecord[] = []\n  for (const block of content) {\n    if (block.type === 'text') out.push({ type: 'text', text: block.text })\n    else if (block.type === 'reasoning') out.push({ type: 'thinking', thinking: block.text })\n    else if (block.type === 'tool-call') out.push({ type: 'toolCall', id: block.id, name: block.name, arguments: block.arguments })\n    else if (block.type === 'image') {\n      const image = await piImageBlock(ctx, (block as unknown as UnknownRecord).attachment)\n      // An unreadable attachment contributes nothing rather than an empty\n      // image: Pi passes what exists.\n      if (image !== undefined) out.push(image)\n    }\n    else if ((block as { type: string }).type === 'file') {\n      out.push(fileContentForPi((block as unknown as UnknownRecord).attachment, ctx as never))\n    }\n    else out.push({ type: block.type })\n  }\n  return out\n}\n\n/**\n * One DSH image attachment as Pi's inline image block.\n * @param ctx - context used to reach the attachment service.\n * @param attachment - the durable reference on an image block.\n * @returns the Pi block, or undefined when the bytes cannot be read.\n */\nasync function piImageBlock(ctx: Context, attachment: unknown): Promise<UnknownRecord | undefined> {\n  if (attachment === undefined || attachment === null) return undefined\n  const attachments = optionalService<DshAttachmentsLike>(ctx, 'attachments')\n  if (attachments === undefined) return undefined\n  try {\n    const stored = await attachments.readImage(attachment)\n    return {\n      type: 'image',\n      data: Buffer.from(stored.data).toString('base64'),\n      mimeType: String((attachment as UnknownRecord).mediaType ?? 'image/png'),\n    }\n  } catch {\n    return undefined\n  }\n}\n\nasync function messageFromSessionEvent(ctx: Context, event: UnknownRecord): Promise<UnknownRecord | undefined> {\n  const type = event.type\n  const data = event.data\n  if (typeof data !== 'object' || data === null) return undefined\n  const record = data as UnknownRecord\n  if (type === 'user/message') return {\n    role: isPiUserMessage(record) ? 'user' : 'custom',\n    ...(!isPiUserMessage(record) ? { customType: String((record.source as UnknownRecord | undefined)?.piCustomType ?? (record.source as UnknownRecord | undefined)?.kind ?? 'context'), display: false } : {}),\n    content: await dshToPiContent(ctx, (record.content ?? []) as ContentBlock[]),\n  }\n  if (type === 'assistant/message') {\n    const message = record.message as UnknownRecord | undefined\n    return { role: 'assistant', content: await dshToPiContent(ctx, (message?.content ?? []) as ContentBlock[]) }\n  }\n  if (type === 'tool/result') {\n    const message = record.message as UnknownRecord | undefined\n    const blocks = (message?.content ?? []) as Array<UnknownRecord>\n    const tool = blocks.find(block => block.type === 'tool-result')\n    return {\n      role: 'toolResult',\n      toolCallId: tool?.toolCallId,\n      content: await dshToPiContent(ctx, (tool?.content ?? []) as ContentBlock[]),\n      isError: tool?.isError === true,\n    }\n  }\n  return undefined\n}\n\nfunction sourceReason(value: unknown): string {\n  return value === 'resume' ? 'resume' : value === 'fork' ? 'fork' : 'startup'\n}\n\n/**\n * Claim Pi's once-per-session `session_start` event.\n *\n * dsh-TUI can execute a slash command before DSH starts the first model turn,\n * so `agent/session-start` has not necessarily been announced yet. Pi, by\n * contrast, announces `session_start` before the user can execute a command.\n * The command bridge uses this same claim before invoking a Pi command; when\n * DSH later announces the real agent lifecycle, the durable session id keeps\n * the second path from restarting the extension.\n */\nfunction claimPiSessionStart(state: RuntimeState, agent: UnknownRecord | undefined): boolean {\n  const id = agentSession(agent)?.id\n  if (typeof id === 'string') {\n    if (state.startedSessions.has(id)) return false\n    state.startedSessions.add(id)\n    return true\n  }\n  if (typeof agent === 'object' && agent !== null) {\n    if (state.startedSessionlessAgents.has(agent)) return false\n    state.startedSessionlessAgents.add(agent)\n    return true\n  }\n  return false\n}\n\nasync function ensurePiSessionStarted(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  signal: AbortSignal | undefined,\n): Promise<void> {\n  await startPiSession(ctx, state, agent, 'startup', signal)\n}\n\nfunction inFlightPiSessionStart(state: RuntimeState, agent: UnknownRecord | undefined): Promise<void> | undefined {\n  const id = agentSession(agent)?.id\n  if (typeof id === 'string') return state.sessionStartTasks.get(id)\n  if (typeof agent === 'object' && agent !== null) return state.sessionlessStartTasks.get(agent)\n  return undefined\n}\n\nfunction rememberPiSessionStart(state: RuntimeState, agent: UnknownRecord | undefined, task: Promise<void>): void {\n  const id = agentSession(agent)?.id\n  if (typeof id === 'string') state.sessionStartTasks.set(id, task)\n  else if (typeof agent === 'object' && agent !== null) state.sessionlessStartTasks.set(agent, task)\n}\n\nfunction forgetPiSessionStart(state: RuntimeState, agent: UnknownRecord | undefined, task: Promise<void>): void {\n  const id = agentSession(agent)?.id\n  if (typeof id === 'string') {\n    if (state.sessionStartTasks.get(id) === task) state.sessionStartTasks.delete(id)\n  } else if (typeof agent === 'object' && agent !== null && state.sessionlessStartTasks.get(agent) === task) {\n    state.sessionlessStartTasks.delete(agent)\n  }\n}\n\nfunction releasePiSessionClaim(state: RuntimeState, agent: UnknownRecord | undefined): void {\n  const id = agentSession(agent)?.id\n  if (typeof id === 'string') {\n    state.startedSessions.delete(id)\n    state.sessionStartTasks.delete(id)\n  } else if (typeof agent === 'object' && agent !== null) {\n    state.startedSessionlessAgents.delete(agent)\n    state.sessionlessStartTasks.delete(agent)\n  }\n}\n\nfunction replacementReason(reason: string): 'new' | 'resume' | 'fork' {\n  if (reason === 'resume') return 'resume'\n  if (reason === 'fork') return 'fork'\n  return 'new'\n}\n\nfunction trackRuntimeSession(state: RuntimeState, agent: UnknownRecord | undefined): void {\n  const id = agentSession(agent)?.id\n  if (typeof id !== 'string') return\n  let states = state.shared.runtimeStatesBySession.get(id)\n  if (states === undefined) {\n    states = new Set()\n    state.shared.runtimeStatesBySession.set(id, states)\n  }\n  states.add(state)\n}\n\nfunction untrackRuntimeSession(state: RuntimeState, agent: UnknownRecord | undefined): void {\n  const id = agentSession(agent)?.id\n  if (typeof id !== 'string') return\n  const states = state.shared.runtimeStatesBySession.get(id)\n  states?.delete(state)\n  if (states?.size === 0) state.shared.runtimeStatesBySession.delete(id)\n}\n\nconst sessionExportTasks = new WeakMap<object, Promise<void>>()\n\nasync function prepareSessionFileExports(ctx: Context, state: RuntimeState): Promise<void> {\n  const persistence = optionalService<import('./session-bridge.js').SessionExportPersistence>(ctx, 'sessionPersistence')\n  if (typeof persistence?.list !== 'function'\n    || (typeof persistence.open !== 'function' && typeof persistence.inspect !== 'function')) return\n  let task = sessionExportTasks.get(ctx.root)\n  if (task === undefined) {\n    task = state.bridge.exportStoredSessions(persistence)\n    sessionExportTasks.set(ctx.root, task)\n    task.catch(() => { sessionExportTasks.delete(ctx.root) })\n  }\n  await task\n}\n\n/** Dispatch or join the one in-flight Pi session_start for this session. */\nasync function startPiSession(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  reason: string,\n  signal: AbortSignal | undefined,\n): Promise<void> {\n  if (!acceptsAgent(state, agent)) return\n  const existing = inFlightPiSessionStart(state, agent)\n  if (existing !== undefined) {\n    await existing\n    return\n  }\n  const task = runInPiRuntime(state, agent, async () => {\n    const previous = state.hostAgent\n    const replacing = typeof previous === 'object' && previous !== null && previous !== agent\n    const transitionReason = replacing ? replacementReason(reason) : reason\n\n    // DSH deliberately overlaps physical Agents during an atomic switch:\n    // B is fully created (and announces agent/session-start) before A is\n    // disposed. Pi deliberately exposes one linear extension runtime:\n    // session_shutdown(A) must settle before session_start(B). Serialize that\n    // semantic handoff here; the later physical disposal of A is then only a\n    // DSH-resource event and must not emit a second Pi shutdown.\n    if (replacing) {\n      releasePiSessionClaim(state, previous)\n      await shutdownPiSession(ctx, state, previous, replacementReason(reason), signal)\n    }\n\n    if (typeof agent === 'object' && agent !== null) {\n      state.hostAgent = agent\n      state.piShutdownAgents.delete(agent)\n      state.shutdownTasks.delete(agent)\n    }\n    if (!claimPiSessionStart(state, agent)) return\n    try {\n      await prepareSessionFileExports(ctx, state)\n      await dispatch(\n        state,\n        'session_start',\n        { type: 'session_start', reason: transitionReason },\n        contextFor(ctx, state, agent, signal),\n      )\n      await discoverPiResources(ctx, state, agent, transitionReason, signal)\n      await refreshNativeSkillCommands(ctx, state, agent, signal)\n    } catch (error) {\n      releasePiSessionClaim(state, agent)\n      throw error\n    }\n  })\n  rememberPiSessionStart(state, agent, task)\n  try {\n    await task\n  } finally {\n    forgetPiSessionStart(state, agent, task)\n  }\n}\n\nfunction subscribeLifecycle(ctx: Context, state: RuntimeState): void {\n  const cordis = ctx as unknown as {\n    on(name: string, callback: (...args: any[]) => unknown, options?: unknown): () => void\n    effect(callback: () => unknown, label?: string): unknown\n  }\n  const warn = (event: string, error: unknown) => logger(ctx).warn(`[pi2dsh] ${event} handler failed: ${String(error)}`)\n\n  cordis.on('agent/session-start', (payload: UnknownRecord) => {\n    const agent = payload.agent as UnknownRecord\n    if (!acceptsAgent(state, agent)) return\n    state.activeAgents.add(agent)\n    trackRuntimeSession(state, agent)\n    const session = agentSession(agent)\n    if (session !== undefined) state.bridge.load(session.id)\n    if (state.pendingActiveTools !== undefined) {\n      runInPiRuntime(state, agent, () => setActiveTools(ctx, state, state.pendingActiveTools!))\n    }\n    // dsh-TUI creates its initial Agent while plugin entries are still being\n    // imported. Marking the session as started at that instant would dispatch\n    // into an empty handler ledger, then suppress the real delivery once the\n    // extension is ready. Buffer the fact, not the event execution.\n    if (!state.extensionsReady) {\n      state.pendingSessionStarts.set(agent, sourceReason(payload.source))\n      return\n    }\n    void startPiSession(ctx, state, agent, sourceReason(payload.source), undefined)\n      .catch(error => warn('session_start', error))\n  })\n  cordis.on('agent/disposed', (payload: UnknownRecord) => {\n    const agent = payload.agent as UnknownRecord\n    if (!acceptsAgent(state, agent)) return\n    const ownsHostSession = state.hostAgent === agent\n    state.activeAgents.delete(agent)\n    untrackRuntimeSession(state, agent)\n    state.pendingSessionStarts.delete(agent)\n    if (typeof agent === 'object' && agent !== null) {\n      state.toolRestrictions.get(agent)?.()\n      state.toolRestrictions.delete(agent)\n    }\n    if (typeof agent === 'object' && agent !== null && !state.disposedAgents.has(agent)) {\n      state.disposedAgents.add(agent)\n      releasePiSessionClaim(state, agent)\n      // A scoped runtime owns exactly this Agent. Legacy root mounts may\n      // still replace first and dispose second; the ownership guard above\n      // prevents one Agent's late disposal from touching another runtime.\n      if (ownsHostSession && !state.piShutdownAgents.has(agent)) {\n        state.hostAgent = undefined\n        void shutdownPiSession(ctx, state, agent, 'quit')\n          .catch(error => warn('session_shutdown', error))\n      }\n    }\n  })\n\n  const liveStreams = new WeakMap<object, { attemptId: unknown, turn: unknown, step: unknown, index: number, ended: boolean }>()\n  const projectAssistantChunk = (session: UnknownRecord, data: UnknownRecord, chunk: UnknownRecord, eventContext: UnknownRecord): void => {\n    if ((state.handlers.get('message_update')?.length ?? 0) === 0) return\n    if (chunk.type !== undefined && chunk.type !== 'text-delta') return\n    const key = `${String(session.id ?? '')}:${String(data.turn ?? 0)}:${String(data.step ?? 0)}`\n    const delta = typeof chunk.text === 'string'\n      ? chunk.text\n      : typeof chunk.delta === 'string' ? chunk.delta : ''\n    const accumulated = (state.streamingTexts.get(key) ?? '') + delta\n    state.streamingTexts.set(key, accumulated)\n    const message = { role: 'assistant', content: [{ type: 'text', text: accumulated }] }\n    void dispatch(state, 'message_update', {\n      type: 'message_update', message,\n      assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta, partial: message },\n    }, eventContext).catch(error => warn('message_update', error))\n  }\n\n  // Stream frames are transient on new hosts; completed messages stay in the\n  // durable log. Keep attempt identity here so a retry cannot reuse partial\n  // text, and do not project the legacy event as well on a dual-emitting host.\n  cordis.on('agent/assistant-stream', (payload: UnknownRecord) => {\n    const agent = payload.agent as UnknownRecord | undefined\n    if (agent === undefined || state.hostAnchor || !acceptsAgent(state, agent)) return\n    const session = agentSession(agent) as UnknownRecord | undefined\n    if (session === undefined) return\n    const frame = payload.frame as UnknownRecord\n    if (frame.type === 'start') {\n      liveStreams.set(session, { attemptId: frame.attemptId, turn: frame.turn, step: frame.step, index: -1, ended: false })\n      state.streamingTexts.delete(`${String(session.id ?? '')}:${String(frame.turn ?? 0)}:${String(frame.step ?? 0)}`)\n      return\n    }\n    const active = liveStreams.get(session)\n    if (active === undefined || active.ended || active.attemptId !== frame.attemptId) return\n    if (frame.type === 'chunk' && Number(frame.index) > active.index) {\n      active.index = Number(frame.index)\n      projectAssistantChunk(session, active, frame.chunk as UnknownRecord, contextFor(ctx, state, agent, undefined))\n    }\n    if (frame.type === 'end') {\n      active.ended = true\n      state.streamingTexts.delete(`${String(session.id ?? '')}:${String(active.turn ?? 0)}:${String(active.step ?? 0)}`)\n    }\n  })\n\n  const projectSessionEvent = (session: UnknownRecord, event: UnknownRecord): void => {\n    const agent = [...state.activeAgents].find(candidate => candidate.session === session)\n    const eventContext = contextFor(ctx, state, agent, undefined)\n    const type = event.type\n    // Pi's vocabulary is one level finer than DSH's name for the same thing:\n    // Pi emits turn_start/turn_end around EVERY model call (its inner loop),\n    // and agent_start/agent_end around the whole prompt. DSH calls those a\n    // step and a turn. Mapping Pi's turn onto DSH's turn fired the per-call\n    // events once per prompt, so a package counting model calls, or reading\n    // one call's assistant message out of turn_end, saw the wrong thing.\n    if (type === 'turn/start') {\n      // Pi resets turnIndex at agent_start, so the counter is per prompt.\n      if (session !== undefined) state.piTurnIndex.set(session as unknown as object, 0)\n      void dispatch(state, 'agent_start', { type: 'agent_start' }, eventContext).catch(error => warn('agent_start', error))\n    }\n    if (type === 'step/start') {\n      const index = state.piTurnIndex.get(session as unknown as object) ?? 0\n      void dispatch(state, 'turn_start', { type: 'turn_start', turnIndex: index, timestamp: event.time ?? Date.now() }, eventContext)\n        .catch(error => warn('turn_start', error))\n    }\n    if (type === 'step/end') {\n      const data = event.data as UnknownRecord\n      const turn = Number(data.turn ?? 1)\n      const step = Number(data.step ?? 1)\n      const key = session as unknown as object\n      const index = state.piTurnIndex.get(key) ?? 0\n      state.piTurnIndex.set(key, index + 1)\n      state.projection = state.projection.then(async () => {\n        // This STEP's assistant message and this STEP's tool results — Pi's\n        // turn_end reports one model call, not a whole prompt.\n        const stepEvents = readSessionEvents(session).filter(entry => {\n          const entryData = entry.data as UnknownRecord | undefined\n          return Number(entryData?.turn ?? -1) === turn && Number(entryData?.step ?? -1) === step\n        })\n        const toolResults = (await Promise.all(stepEvents\n          .filter(entry => entry.type === 'tool/result')\n          .map(entry => messageFromSessionEvent(ctx, entry))))\n          .filter((message): message is UnknownRecord => message !== undefined)\n        const assistant = stepEvents.findLast(entry => entry.type === 'assistant/message')\n        const message = assistant === undefined\n          ? { role: 'assistant', content: [] }\n          : await messageFromSessionEvent(ctx, assistant) ?? { role: 'assistant', content: [] }\n        await dispatch(state, 'turn_end', { type: 'turn_end', turnIndex: index, message, toolResults }, eventContext)\n      }).catch(error => warn('turn_end', error))\n    }\n    if (type === 'tool/call') {\n      const data = event.data as UnknownRecord\n      let args: unknown = {}\n      try { args = JSON.parse(String(data.arguments ?? '{}')) } catch { args = {} }\n      void dispatch(state, 'tool_execution_start', {\n        type: 'tool_execution_start', toolCallId: data.callId, toolName: data.name, args: piViewOfToolArguments(state, String(data.name), args),\n      }, eventContext).catch(error => warn('tool_execution_start', error))\n    }\n    if (type === 'assistant/chunk' && !liveStreams.has(session)) {\n      const data = event.data as UnknownRecord\n      projectAssistantChunk(session, data, (data.chunk ?? {}) as UnknownRecord, eventContext)\n    }\n    if (type === 'assistant/message') {\n      const data = event.data as UnknownRecord\n      state.streamingTexts.delete(`${String(session.id ?? '')}:${String(data.turn ?? 0)}:${String(data.step ?? 0)}`)\n    }\n    if (type === 'session/title') {\n      const data = event.data as UnknownRecord\n      void dispatch(state, 'session_info_changed', {\n        type: 'session_info_changed', name: typeof data.title === 'string' ? data.title : undefined,\n      }, eventContext).catch(error => warn('session_info_changed', error))\n    }\n    // DSH compaction events are facts from the durable log: the \"before\"\n    // projection is advisory (cancel/replace cannot reach DSH's compactor),\n    // and the \"after\" projection carries the summary when one was recorded.\n    if (type === 'compaction/start') {\n      const before = dispatch(state, 'session_before_compact', {\n        type: 'session_before_compact',\n        preparation: { ...(event.data as UnknownRecord) },\n        branchEntries: [],\n        reason: compactionReason(event.data as UnknownRecord),\n        willRetry: false,\n      }, eventContext).catch(error => warn('session_before_compact', error))\n      // Preserve Pi handler ordering and join this work during teardown.\n      // The native log notification itself is still not an awaited veto gate.\n      state.projection = Promise.all([state.projection, before]).then(() => {})\n    }\n    // `compaction/summary` and ONLY it. `compaction/end` closes the bracket\n    // whether the compaction succeeded or failed (it carries `error` when it\n    // did not), so firing on both dispatched twice for every success and once,\n    // falsely, for every failure — telling packages the history was compacted\n    // when nothing had been.\n    if (type === 'compaction/summary') {\n      const data = event.data as UnknownRecord\n      const shadowed = data.shadowedRange as { start?: unknown, end?: unknown } | undefined\n      const usage = data.usage as UnknownRecord | undefined\n      state.projection = state.projection.then(() => dispatch(state, 'session_compact', {\n        type: 'session_compact',\n        compactionEntry: {\n          type: 'compaction',\n          id: `dsh-${String(event.seq ?? '')}`,\n          // Pi's CompactionEntry.summary is a STRING. DSH's is a ContentBlock\n          // array, and the old spread of the raw event data over this object\n          // put that array back under the same name — so every package doing\n          // string work on the summary got an array instead.\n          summary: textBlocks(data.summary).map(block => block.text).join('\\n'),\n          firstKeptEntryId: typeof shadowed?.end === 'number' ? `dsh-${shadowed.end + 1}` : '',\n          tokensBefore: Number(data.shadowedTokenCount ?? 0),\n          ...(usage === undefined ? {} : { usage }),\n          fromHook: false,\n        },\n        fromExtension: false,\n        reason: compactionReason(data),\n        willRetry: false,\n      }, eventContext)).then(() => {}).catch(error => warn('session_compact', error))\n    }\n    if (type === 'request/header') {\n      const header = ((event.data as UnknownRecord).header ?? {}) as UnknownRecord\n      const model = header.model ?? (header as { config?: UnknownRecord }).config?.model\n      if (model !== undefined && agent !== undefined) {\n        const previous = state.lastLoggedModels.get(agent)\n        if (previous !== undefined && previous !== String(model)) {\n          void dispatch(state, 'model_select', {\n            type: 'model_select',\n            model: { id: String(model) },\n            previousModel: { id: previous },\n            source: 'set',\n          }, eventContext).catch(error => warn('model_select', error))\n        }\n        state.lastLoggedModels.set(agent, String(model))\n      }\n    }\n    state.projection = state.projection.then(async () => {\n      const message = await messageFromSessionEvent(ctx, event)\n      if (message === undefined) return\n      await dispatch(state, 'message_start', { type: 'message_start', message }, eventContext)\n      await dispatch(state, 'message_end', { type: 'message_end', message }, eventContext)\n    }).catch(error => warn('message lifecycle', error))\n    if (type === 'turn/end') {\n      // Behind the shared stream so the prompt's own steps have announced\n      // themselves before it is declared finished.\n      state.projection = state.projection.then(async () => {\n        await dispatch(state, 'agent_end', { type: 'agent_end', messages: [] }, eventContext)\n        await dispatch(state, 'agent_settled', { type: 'agent_settled' }, eventContext)\n      }).catch(error => warn('turn end lifecycle', error))\n    }\n  }\n  // Exposed for the mount-time backlog replay (flushPendingSessionStarts):\n  // events appended between Agent publication and extension readiness are\n  // otherwise lost to a per-Agent instance.\n  state.projectSessionEvent = projectSessionEvent\n\n  cordis.on('session/event', (session: UnknownRecord, event: UnknownRecord) => {\n    // The host anchor serves no session; this listener's own session guard\n    // predates acceptsAgent and must exclude it explicitly, or the anchor's\n    // extension instance receives a second copy of every lifecycle event\n    // beside the owning per-Agent instance (step-seams caught turn_start\n    // firing twice per model call through a globalThis-shared recorder).\n    if (state.hostAnchor) return\n    const ownedSession = agentSession(state.ownerAgent)\n    if (ownedSession !== undefined ? session !== ownedSession : isSubagentOrigin(session)) return\n    // A per-Agent mount runs AFTER its Agent published: events arriving\n    // before the extension handlers exist would dispatch into an empty\n    // ledger and be lost (a one-shot run opens its turn during module\n    // loading). Drop them here — the durable log holds them, and the flush\n    // replays the still-open turn synchronously before flipping this flag,\n    // so the seam is gap- and overlap-free.\n    if (ownedSession !== undefined && state.sessionEventsLive !== true) return\n    projectSessionEvent(session, event)\n  })\n\n  // Per-agent model/thinking overrides recorded by setModel()/setThinkingLevel()\n  // are applied at the request boundary, DSH's sanctioned seam for call-config\n  // replacement.\n  cordis.on('agent/request', async (payload: UnknownRecord, next: () => Promise<UnknownRecord>) => {\n    const config = await next()\n    const agent = payload.agent as UnknownRecord | undefined\n    if (agent === undefined || !acceptsAgent(state, agent)) return config\n    const override = state.modelOverrides.get(agent)\n    const thinking = state.thinkingLevels.get(agent)\n    if (override === undefined && thinking === undefined) return config\n    return {\n      ...config,\n      ...(override?.provider === undefined ? {} : { provider: override.provider }),\n      ...(override?.model === undefined ? {} : { model: override.model }),\n      ...(thinking === undefined || (thinking === 'off' && (currentPiModel(state, agent)?.thinkingLevelMap as UnknownRecord | undefined)?.off === null)\n        ? {} : { reasoningEffort: thinking }),\n    }\n  })\n\n\n  cordis.effect(() => async () => {\n    await state.projection\n    const agent = state.hostAgent\n    if (typeof agent === 'object' && agent !== null) {\n      state.disposedAgents.add(agent)\n      await shutdownPiSession(ctx, state, agent, 'quit')\n    }\n    await Promise.all(state.pendingShutdowns)\n    state.hostAgent = undefined\n    for (const active of state.activeAgents) untrackRuntimeSession(state, active)\n    state.activeAgents.clear()\n    state.startedSessions.clear()\n    state.sessionStartTasks.clear()\n    state.pendingSessionStarts.clear()\n    for (const dispose of state.toolDisposers.values()) dispose()\n    state.toolDisposers.clear()\n    for (const provider of [...state.ownedProviderRoutes]) releaseSharedProviderRoute(state, provider)\n    // The bus is agent-shared: unwind only this instance's subscriptions.\n    for (const off of state.eventBusOffs.splice(0)) off()\n  }, 'pi2dsh session shutdown')\n}\n\nasync function flushPendingSessionStarts(ctx: Context, state: RuntimeState): Promise<void> {\n  state.extensionsReady = true\n  // A per-Agent mount happens AFTER DSH published the Agent: its\n  // agent/session-start fired before this instance existed, so no listener\n  // could even buffer it. The owner's session has started by definition —\n  // deliver the missed start now, exactly as Pi hosts run session_start\n  // before the first turn (a default-on status package draws from it; the\n  // lazy first-execution gate alone would leave it blank until the first\n  // command, and a toggle command would then flip it OFF instead of ON).\n  if (state.ownerAgent !== undefined && !state.pendingSessionStarts.has(state.ownerAgent)) {\n    const owned = state.ownerAgent\n    if (!state.activeAgents.has(owned)) {\n      state.activeAgents.add(owned)\n      trackRuntimeSession(state, owned)\n      const session = agentSession(owned)\n      if (session !== undefined) state.bridge.load(session.id)\n    }\n    state.pendingSessionStarts.set(owned, 'startup')\n  }\n  const pending = [...state.pendingSessionStarts]\n  state.pendingSessionStarts.clear()\n  for (const [agent, reason] of pending) {\n    await startPiSession(ctx, state, agent, reason, undefined)\n  }\n  // Backlog replay for a per-Agent mount: the owner's loop may have OPENED a\n  // turn before this instance's handlers existed (a one-shot headless run\n  // prompts the instant the Agent publishes; DSH appends `turn/start` while\n  // extension modules are still loading, and the assembly our engine gate\n  // holds comes later in the same turn). Live delivery is suppressed until\n  // this point (see the session/event subscription), so Pi's event stream —\n  // agent_start before the prompt's first turn_start — is reconstructed from\n  // the durable log: replay the still-open turn and flip live delivery in\n  // the same synchronous stretch, so no event is doubled and none is lost.\n  if (state.ownerAgent !== undefined && state.projectSessionEvent !== undefined) {\n    const session = agentSession(state.ownerAgent) as (UnknownRecord & { events?: UnknownRecord[] }) | undefined\n    if (session !== undefined) {\n      const events = readSessionEvents(session)\n      let from = -1\n      for (let index = events.length - 1; index >= 0; index -= 1) {\n        if (events[index]!.type === 'turn/end') break\n        if (events[index]!.type === 'turn/start') { from = index; break }\n      }\n      if (from >= 0) {\n        for (let index = from; index < events.length; index += 1) {\n          state.projectSessionEvent(session, events[index]!)\n        }\n      }\n    }\n    state.sessionEventsLive = true\n  }\n}\n\n/**\n * Start freshly reloaded extension handlers in every live Pi host session.\n *\n * `ctx.reload()` creates a new extension instance. The durable session has\n * already been claimed by the previous instance, so the ordinary once-per-\n * session guard must deliberately NOT suppress this replay: from the new\n * instance's point of view this is its first `session_start`. The command's\n * AsyncLocalStorage agent is included because a lean composition can execute\n * a Pi command without publishing DSH's optional agent/session-start event.\n */\nasync function restartReloadedPiSessions(ctx: Context, state: RuntimeState): Promise<void> {\n  state.extensionsReady = true\n  const pending = new Map(state.pendingSessionStarts)\n  state.pendingSessionStarts.clear()\n  const commandAgent = currentAgent(state)\n  const candidates = [...state.activeAgents, ...(commandAgent === undefined ? [] : [commandAgent])]\n  const seenSessions = new Set<string>()\n  const seenSessionless = new Set<UnknownRecord>()\n  for (const agent of candidates) {\n    if (!acceptsAgent(state, agent)) continue\n    const sessionId = agentSession(agent)?.id\n    if (typeof sessionId === 'string') {\n      if (seenSessions.has(sessionId)) continue\n      seenSessions.add(sessionId)\n    } else {\n      if (seenSessionless.has(agent)) continue\n      seenSessionless.add(agent)\n    }\n    await runInPiRuntime(state, agent, () => dispatch(\n      state,\n      'session_start',\n      { type: 'session_start', reason: pending.get(agent) ?? 'resume' },\n      contextFor(ctx, state, agent, undefined),\n    ))\n    await discoverPiResources(ctx, state, agent, pending.get(agent) ?? 'resume', undefined)\n    await refreshNativeSkillCommands(ctx, state, agent, undefined)\n  }\n}\n\n/**\n * Pi's `resources_discover`, fired right after session_start (Pi:\n * AgentSession.extendResourcesFromExtensions): handlers return extra\n * `skillPaths` (and prompt/theme paths) for the session's cwd, and Pi extends\n * its resource loader with them. On DSH the skills registry is the host's\n * `skills` service, so every discovered skill ROOT is handed to the official\n * filesystem provider (dsh-skill-filesystem) exactly like a package's static\n * skill directories — once per root, per package (the registry is host-level\n * and provider names must stay unique). Prompt templates and TUI themes have\n * no DSH seat and are reported, not silently dropped. A single SKILL.md file\n * path (Pi accepts those too) has no root to mount and is reported likewise.\n */\nasync function refreshNativeSkillCommands(ctx: Context, state: RuntimeState, agent: UnknownRecord | undefined, signal?: AbortSignal): Promise<void> {\n  const skills = optionalService<{\n    list(options: UnknownRecord): Promise<UnknownRecord[]>\n    get(name: string, options: UnknownRecord): Promise<UnknownRecord | undefined>\n  }>(ctx, 'skills')\n  if (skills === undefined) { state.nativeSkillCommands = []; return }\n  const options = { cwd: cwdOf(agent), scope: scopeOf(ctx), signal: signal ?? new AbortController().signal }\n  try {\n    const entries: UnknownRecord[] = []\n    for (const summary of await skills.list(options)) {\n      if ((summary.invocation as UnknownRecord | undefined)?.userInvocable === false) continue\n      const skill = await skills.get(String(summary.name), options)\n      if (typeof skill?.path !== 'string') continue\n      entries.push({ name: `skill:${String(summary.name)}`, description: String(summary.description ?? ''), source: 'skill',\n        sourceInfo: { path: skill.path, source: skill.path, scope: String(summary.source ?? '').startsWith('project') ? 'project' : 'user', origin: 'top-level', baseDir: dirname(skill.path) },\n      })\n    }\n    state.nativeSkillCommands = entries\n  } catch (error) {\n    state.nativeSkillCommands = []\n    logger(ctx).warn(`[pi2dsh] skill command metadata could not be refreshed: ${error instanceof Error ? error.message : String(error)}`)\n  }\n}\n\nasync function discoverPiResources(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord | undefined,\n  reason: string,\n  signal: AbortSignal | undefined,\n): Promise<void> {\n  if ((state.handlers.get('resources_discover')?.length ?? 0) === 0) return\n  const cwd = cwdOf(agent)\n  const results = await dispatch(\n    state,\n    'resources_discover',\n    { type: 'resources_discover', cwd, reason: reason === 'reload' ? 'reload' : 'startup' },\n    contextFor(ctx, state, agent, signal),\n  )\n  const roots: string[] = []\n  const skipped: string[] = []\n  let promptPaths = 0\n  let themePaths = 0\n  for (const result of results) {\n    if (typeof result !== 'object' || result === null) continue\n    const record = result as UnknownRecord\n    for (const entry of Array.isArray(record.skillPaths) ? record.skillPaths as unknown[] : []) {\n      if (typeof entry !== 'string' || entry.length === 0) continue\n      const absolute = pathResolve(cwd, entry)\n      let isDirectory = false\n      try {\n        isDirectory = (await stat(absolute)).isDirectory()\n      } catch {\n        continue\n      }\n      if (!isDirectory) { skipped.push(absolute); continue }\n      if (!state.discoveredSkillRoots.has(absolute) && !roots.includes(absolute)) roots.push(absolute)\n    }\n    if (Array.isArray(record.promptPaths)) promptPaths += (record.promptPaths as unknown[]).length\n    if (Array.isArray(record.themePaths)) themePaths += (record.themePaths as unknown[]).length\n  }\n  if (promptPaths > 0 || themePaths > 0 || skipped.length > 0) {\n    logger(ctx).info(`[pi2dsh] ${state.packageName}: resources_discover returned ${promptPaths} prompt path(s), ${themePaths} theme path(s) and ${skipped.length} single skill file(s) that DSH has no seat for; they were not mounted`)\n  }\n  if (roots.length === 0) return\n  const skills = (ctx as unknown as { get(name: string): unknown }).get('skills')\n  if (skills === undefined) {\n    logger(ctx).warn(`[pi2dsh] ${state.packageName}: resources_discover found ${roots.length} skill root(s) but this DSH composition has no ctx.skills`)\n    return\n  }\n  for (const root of roots) state.discoveredSkillRoots.add(root)\n  state.discoveredSkillProviders += 1\n  const { apply: applyFilesystemSkills } = await import('@deepseek-ai/dsh-skill-filesystem')\n  const config = {\n    providerName: `pi2dsh-${state.packageName.replace(/[^a-zA-Z0-9_-]+/gu, '-').replace(/^-+|-+$/gu, '')}-discovered-${state.discoveredSkillProviders}`,\n    includeDefaultRoots: false,\n    customSkillDirs: roots,\n    watch: false,\n  }\n  await ctx.plugin(Object.assign(\n    (skillCtx: Context) => applyFilesystemSkills(skillCtx, config),\n    { inject: ['skills'] },\n  ))\n  logger(ctx).info(`[pi2dsh] ${state.packageName}: resources_discover mounted ${roots.length} skill root(s) as ${config.providerName}`)\n}\n\n/**\n * The Pi view of a host tool's arguments. DSH's built-in file tools carry\n * Claude-style argument names (`file_path`, `old_string`/`new_string`,\n * grep's `include`); Pi's same-named built-ins carry `path`,\n * `oldText`/`newText`, `glob`. Extensions read `event.input` by Pi's names —\n * pi-code attaches a path-scoped rule to the read of a matching `input.path`,\n * and its hooks translate Pi shapes to Claude's `tool_input` — so a host call\n * is projected into Pi's shape for the tool_call / tool_result /\n * tool_execution_start events. Migrated Pi tools already speak Pi and pass\n * through untouched; unknown keys are kept, so nothing is lost.\n */\nconst HOST_TOOL_ARGUMENT_PROJECTION: Record<string, Record<string, string>> = {\n  read: { file_path: 'path' },\n  write: { file_path: 'path' },\n  edit: { file_path: 'path', old_string: 'oldText', new_string: 'newText' },\n  grep: { include: 'glob' },\n}\nfunction piViewOfToolArguments(state: RuntimeState, name: string, args: unknown): unknown {\n  if (state.tools.has(name)) return cloneJson(args)\n  const mapping = HOST_TOOL_ARGUMENT_PROJECTION[name]\n  if (mapping === undefined || typeof args !== 'object' || args === null || Array.isArray(args)) return cloneJson(args)\n  const projected: UnknownRecord = {}\n  for (const [key, value] of Object.entries(args as UnknownRecord)) projected[mapping[key] ?? key] = value\n  return cloneJson(projected)\n}\n\nfunction subscribeInterceptors(ctx: Context, state: RuntimeState): void {\n  const cordis = ctx as unknown as { on(name: string, callback: (...args: any[]) => unknown): () => void }\n  cordis.on('tools/pre-execute', async (exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> => {\n    // A child agent's tool traffic must not reach extensions mounted on the\n    // parent: DSH lets an untagged listener see every scope, so without this\n    // a parent's guard would silently police another session's calls, and its\n    // handlers would receive an end without ever having seen the start.\n    if (!acceptsAgent(state, exec.agent as unknown as UnknownRecord | undefined)) return next()\n    const original = piViewOfToolArguments(state, exec.name, exec.arguments)\n    const input = cloneJson(original)\n    const event: UnknownRecord = { type: 'tool_call', toolName: exec.name, toolCallId: exec.callId, input }\n    const results = await dispatch(state, 'tool_call', event, contextFor(ctx, state, exec.agent as unknown as UnknownRecord, exec.signal))\n    if (!jsonEqual(event.input, original)) {\n      if (state.tools.has(exec.name)) {\n        // Pi semantics: tool_call handlers mutate event.input in place. For\n        // pi2dsh-owned tools the mutation is applied inside our execute\n        // wrapper; DSH-native tools cannot accept it because the core logs\n        // arguments before policy on purpose.\n        state.argMutations.set(exec as unknown as object, cloneJson(event.input))\n      } else {\n        return { kind: 'deny', reason: `pi2dsh: a Pi tool_call hook mutated arguments of native DSH tool ${JSON.stringify(exec.name)}; DSH logs arguments before policy, so this mutation cannot be honored` }\n      }\n    }\n    // Pi's `terminate` is a batch verdict, not a per-call one: the loop stops\n    // after a tool batch only when EVERY finalized call in it was blocked with\n    // terminate. One call cannot see the batch, so each records its vote and\n    // the next step boundary counts them.\n    const agent = exec.agent as unknown as object | undefined\n    const tally = agent === undefined\n      ? undefined\n      : state.terminateBatch.get(agent) ?? { calls: 0, terminating: 0 }\n    if (tally !== undefined && agent !== undefined) {\n      tally.calls += 1\n      state.terminateBatch.set(agent, tally)\n    }\n    for (const result of results) {\n      if (typeof result !== 'object' || result === null) continue\n      const record = result as UnknownRecord\n      if (record.block !== true) continue\n      // Only a BLOCKED call's terminate counts — Pi documents it as a hint\n      // \"when this call is blocked\", and an executed call never carries one.\n      if (record.terminate === true && tally !== undefined) tally.terminating += 1\n      return { kind: 'deny', reason: String(record.reason ?? 'blocked by migrated Pi tool_call hook') }\n    }\n    return next()\n  })\n\n  cordis.on('tools/post-execute', async (\n    exec: ToolExecution,\n    result: ToolExecutionResult,\n    next: () => Promise<PostToolDecision>,\n  ): Promise<PostToolDecision> => {\n    // A child agent's tool traffic must not reach extensions mounted on the\n    // parent: DSH lets an untagged listener see every scope, so without this\n    // a parent's guard would silently police another session's calls, and its\n    // handlers would receive an end without ever having seen the start.\n    if (!acceptsAgent(state, exec.agent as unknown as UnknownRecord | undefined)) return next()\n    const downstream = await next()\n    // Pi emits the execution's end as part of completing it, so a handler has\n    // run before the caller sees the result. This waterfall is that moment;\n    // the `tools/result` observer it used to ride is a fire-and-forget emit,\n    // which — once projecting the content had to await the attachment service\n    // — could land after the turn that produced it had already ended.\n    await dispatch(state, 'tool_execution_end', {\n      type: 'tool_execution_end',\n      toolCallId: exec.callId,\n      toolName: exec.name,\n      result: { content: await dshToPiContent(ctx, result.content), details: result.meta ?? null },\n      isError: result.isError,\n    }, contextFor(ctx, state, exec.agent as unknown as UnknownRecord, exec.signal))\n      .catch(error => logger(ctx).warn(`[pi2dsh] tool_execution_end handler failed: ${String(error)}`))\n    if (downstream.kind === 'block') return downstream\n    const event: UnknownRecord = {\n      type: 'tool_result',\n      toolName: exec.name,\n      toolCallId: exec.callId,\n      input: piViewOfToolArguments(state, exec.name, exec.arguments),\n      content: await dshToPiContent(ctx, result.content),\n      details: result.meta ?? null,\n      isError: result.isError,\n      usage: undefined,\n    }\n    const results = await dispatch(state, 'tool_result', event, contextFor(ctx, state, exec.agent as unknown as UnknownRecord, exec.signal))\n    for (const patch of results) {\n      if (typeof patch !== 'object' || patch === null) continue\n      Object.assign(event, patch)\n    }\n    const content = textBlocks(event.content)\n    if (event.isError === true && !result.isError) return { kind: 'block', feedback: content }\n    if (event.isError === false && result.isError) {\n      logger(ctx).warn('[pi2dsh] a Pi tool_result hook attempted to recover a DSH error; error recovery was ignored')\n    }\n    if (!jsonEqual(event.content, await dshToPiContent(ctx, result.content))) return { kind: 'accept', content }\n    return downstream\n  })\n\n  // The claim that opens a step happens immediately BEFORE the assembly\n  // (agent-loop: `inbox.claim(...)` then `systemPrompt.assemble(...)`), and it\n  // publishes each claimed message. Catching them here is what lets the Pi\n  // event run during the assembly it is supposed to influence.\n  cordis.on('agent/inbox/claimed', (payload: UnknownRecord) => {\n    const agent = payload.agent as UnknownRecord | undefined\n    if (agent === undefined || !acceptsAgent(state, agent)) return\n    const claimed = state.claimedForStep.get(agent) ?? []\n    claimed.push({ message: payload.message, turn: Number(payload.turn ?? 0) })\n    state.claimedForStep.set(agent, claimed)\n  })\n\n  cordis.on('agent/pre-step', async (payload: UnknownRecord, next: () => Promise<UnknownRecord>) => {\n    const agent = payload.agent as UnknownRecord\n    if (!acceptsAgent(state, agent)) return next()\n    // The step boundary IS the end of the previous tool batch, so this is\n    // where Pi's batch verdict is read: stop only when every call in that\n    // batch was blocked asking to terminate. Rejecting the proposed step is\n    // exactly Pi's \"stop after the current tool batch\" — the results already\n    // entered the conversation; the agent simply does not take another step.\n    const tally = state.terminateBatch.get(agent as unknown as object)\n    state.terminateBatch.delete(agent as unknown as object)\n    if (tally !== undefined && tally.calls > 0 && tally.calls === tally.terminating) {\n      logger(ctx).info(\n        `[pi2dsh] a Pi tool_call hook terminated the turn: all ${tally.calls} call(s) in the batch were blocked`\n        + ' with terminate',\n      )\n      return { kind: 'reject' }\n    }\n    const decision = await next() as UnknownRecord & { kind?: string, messages?: UnknownRecord[] }\n    if (decision.kind !== 'enter') return decision\n    const signal = payload.signal as AbortSignal | undefined\n    const messages = decision.messages ?? []\n    // The custom messages a before_agent_start handler returned during this\n    // step's assembly, joining the step beside the user message as\n    // plugin-sourced context (Pi's role:\"custom\" append).\n    const injected = state.pendingInjections.get(agent) ?? []\n    state.pendingInjections.delete(agent)\n    const stepMessages = injected.length === 0 ? messages : [...messages, ...injected]\n    // Pi's context event fires before every model call with the full message\n    // array and may return a transformed copy. DSH's durable history is\n    // append-only, so the projection splits: entered history is read-only,\n    // and only this step's not-yet-entered messages accept the transform —\n    // which is exactly the slice packages rewrite (their own custom messages\n    // and the turn's user message, e.g. image placeholders → guide text).\n    const transformed = await applyPiContextTransform(ctx, state, agent, signal, stepMessages)\n    if (transformed === stepMessages && injected.length === 0) return decision\n    return { ...decision, messages: transformed }\n  })\n\n  // Pi tools contribute two things to the system prompt: a one-line\n  // `promptSnippet` for the \"Available tools\" list (without which Pi omits the\n  // tool from that list entirely) and `promptGuidelines` bullets that apply\n  // only while the tool is active. Both were being dropped on registration, so\n  // a migrated tool that documents itself through them documented nothing.\n  //\n  // They belong in a registered SECTION, not in this bridge's waterfall\n  // rewrite: DSH orders sections itself, and 100-199 is its own tool-guidance\n  // band — so a Pi tool's guidance lands exactly where DSH's does.\n  const systemPrompt = optionalService<{ section(section: UnknownRecord): () => void }>(ctx, 'systemPrompt')\n  // The anchor registers no prompt section: tool guidance describes the\n  // per-Agent instances' DSH-registered tools, which the anchor projects none of.\n  if (systemPrompt !== undefined && !state.hostAnchor) {\n    // The section name carries the package: the guidance IS per-package (it\n    // describes that package's tools), and a shared constant made the second\n    // Pi package in a profile fail to mount entirely — DSH rejects a duplicate\n    // section name, and the whole mount unwound with it. Every package\n    // contributes its own section; DSH orders them within its own band.\n    ctx.effect(() => systemPrompt.section({\n      name: `pi2dsh:tool-guidance:${state.packageName ?? 'pi'}`,\n      order: 150,\n      text: () => piToolPromptContribution(ctx, state),\n    }))\n  }\n\n  cordis.on('system-prompt/assemble', async (assembly: UnknownRecord, assembleContext: UnknownRecord, next: () => Promise<UnknownRecord>) => {\n    const downstream = await next()\n    // Recorded on EVERY assembly, before any gate: this is the value\n    // `ctx.getSystemPrompt()` reports and the one the before_agent_start event\n    // carries. Deciding whether to record it by whether some package happens\n    // to subscribe to before_agent_start left a package that only READS the\n    // prompt reading an empty string for the life of the session.\n    const original = renderPrompt(downstream as never)\n    state.currentSystemPrompt = original\n    const agent = (assembleContext.agent ?? assembleContext.scope) as UnknownRecord | undefined\n    if (agent !== undefined && !acceptsAgent(state, agent)) return downstream\n    if (agent !== undefined && acceptsAgent(state, agent)) {\n      // Pi's before_agent_start fires once per user prompt: after the user\n      // message is known, before the first model call. That is HERE — the\n      // loop claims the turn's messages and then assembles — and it has to be\n      // here, because a handler's returned systemPrompt is meant to be this\n      // turn's prompt. Running it on the later pre-step waterfall (what this\n      // bridge did) left the override one step behind: it missed the turn\n      // that produced it and then applied to the following one.\n      await runBeforeAgentStart(ctx, state, agent, assembleContext.signal as AbortSignal | undefined, original)\n      const override = state.turnSystemPromptOverrides.get(agent)\n      if (override === undefined) return downstream\n      state.currentSystemPrompt = override\n      return { ...downstream, sections: [{ name: 'pi2dsh:system-prompt', text: override }] }\n    }\n    // No live agent (diagnostics, compositions without the agent loop): keep\n    // the assembly-time dispatch so systemPrompt-replacement packages still\n    // run; Pi's prompt/images/custom-message surfaces need a real turn.\n    if ((state.handlers.get('before_agent_start')?.length ?? 0) === 0) return downstream\n    const event: UnknownRecord = {\n      type: 'before_agent_start', prompt: '', systemPrompt: original, systemPromptOptions: {},\n    }\n    const results = await dispatch(state, 'before_agent_start', event, contextFor(ctx, state, assembleContext.scope as UnknownRecord, assembleContext.signal as AbortSignal | undefined))\n    let replacement = original\n    for (const result of results) {\n      if (typeof result === 'object' && result !== null && typeof (result as UnknownRecord).systemPrompt === 'string') {\n        replacement = (result as UnknownRecord).systemPrompt as string\n        event.systemPrompt = replacement\n      }\n    }\n    state.currentSystemPrompt = replacement\n    return { ...downstream, sections: [{ name: 'pi2dsh:system-prompt', text: replacement }] }\n  })\n}\n\n/**\n * Pi's `before_agent_start`, run inside the assembly of the turn it belongs to.\n *\n * Fires once per user prompt: only when this step's claim opened a NEW turn,\n * matching Pi, where the event follows the user's message rather than every\n * model call. A handler's `systemPrompt` becomes this turn's override (reset\n * at the next turn, exactly as Pi resets to the base prompt) and a returned\n * `message` is held for the step that is about to be entered.\n * @param ctx - context used for attachments and handler dispatch.\n * @param state - runtime state holding claims, overrides, and injections.\n * @param agent - the agent whose assembly this is.\n * @param signal - the turn's control signal, when one exists.\n * @param assembled - the prompt as assembled, before any package override.\n */\nasync function runBeforeAgentStart(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord,\n  signal: AbortSignal | undefined,\n  assembled: string,\n): Promise<void> {\n  const claimed = state.claimedForStep.get(agent) ?? []\n  state.claimedForStep.delete(agent)\n  if (claimed.length === 0) return\n  // Steering claimed mid-turn carries the turn already prompted for; only a\n  // turn this bridge has not announced yet is a new user prompt.\n  const turn = Number(claimed[0]?.turn ?? 0)\n  if (state.promptedTurn.get(agent) === turn) return\n  state.promptedTurn.set(agent, turn)\n  // A new turn resets to the base prompt whether or not any handler runs.\n  state.turnSystemPromptOverrides.delete(agent)\n  if ((state.handlers.get('before_agent_start')?.length ?? 0) === 0) return\n\n  const userMessages = claimed\n    .map(entry => entry.message as UnknownRecord)\n    .filter(message => ((message.source as { kind?: string } | undefined)?.kind ?? 'user') === 'user')\n  const prompt = userMessages\n    .flatMap(message => textBlocks(message.content))\n    .map(block => block.text)\n    .join('\\n')\n  const images = await collectPiImages(ctx, userMessages)\n  const event: UnknownRecord = {\n    type: 'before_agent_start',\n    prompt,\n    ...(images.length > 0 ? { images } : {}),\n    systemPrompt: assembled,\n    systemPromptOptions: await piSystemPromptOptions(ctx, state, agent, claimed.map(entry => entry.message as UnknownRecord)),\n  }\n  // Pi chains systemPrompt returns: each handler sees the prompt as the\n  // previous handler left it (BeforeAgentStartEventResult: \"If multiple\n  // extensions return this, they are chained\"). Running every handler on the\n  // original and keeping the last return let a handler that merely echoes its\n  // input erase another's addition (pi-code: context-imports appended the\n  // expanded @imports; a later extension returned the base prompt unchanged\n  // and that became the turn's override).\n  const eventContext = contextFor(ctx, state, agent, signal)\n  const results: unknown[] = []\n  for (const handler of state.handlers.get('before_agent_start') ?? []) {\n    const result = await runInPiRuntime(state, agent, () => handler(event, eventContext))\n    results.push(result)\n    if (typeof result === 'object' && result !== null && typeof (result as UnknownRecord).systemPrompt === 'string') {\n      event.systemPrompt = (result as UnknownRecord).systemPrompt as string\n    }\n  }\n  if (event.systemPrompt !== assembled) state.turnSystemPromptOverrides.set(agent, event.systemPrompt as string)\n  const injected: UnknownRecord[] = []\n  for (const result of results) {\n    if (typeof result !== 'object' || result === null) continue\n    const record = result as UnknownRecord\n    const message = record.message as UnknownRecord | undefined\n    if (message === undefined) continue\n    const content = message.content\n    const blocks = await piToDshContent(ctx, typeof content === 'string' ? [{ type: 'text', text: content }] : content ?? [])\n    injected.push(createUserMessage({\n      content: blocks,\n      // piCustomType rides the merge-extensible source so the durable log\n      // (and every later projection) keeps Pi's role:\"custom\" identity.\n      source: {\n        kind: 'plugin', plugin: state.messageSource,\n        ...(typeof message.customType === 'string' ? { piCustomType: message.customType } : {}),\n      },\n    }) as unknown as UnknownRecord)\n  }\n  if (injected.length > 0) state.pendingInjections.set(agent, injected)\n}\n\n/**\n * Pi's `BuildSystemPromptOptions` for the before_agent_start event: the\n * structured view of \"what the host loaded\", which extensions read instead of\n * re-discovering resources. Two fields carry weight on DSH:\n *  - `cwd`: the session's working directory (pi-code's context-imports\n *    otherwise falls back to process.cwd(), the CLI's directory).\n *  - `contextFiles`: the AGENTS.md/CLAUDE.md chain the host loaded, as\n *    `{path, content}`. DSH delivers those as an `agent-instructions` user\n *    message rather than system-prompt text, so the set is recovered from the\n *    official loader itself: the baseline message records the exact\n *    discovery/budget identity DSH used, and `loadBaselineInstructionSet`\n *    from `@deepseek-ai/dsh-agent-instructions` re-runs that same walk. No\n *    parallel discovery logic lives here; without the package or a baseline\n *    the list is empty, exactly Pi's value when nothing was loaded.\n * (pi-code's CLAUDE.md `@import` expansion reads this list — with `{}` it\n * had nothing to expand and the model \"found\" the imported file with `read`.)\n */\nasync function piSystemPromptOptions(ctx: Context, state: RuntimeState, agent: UnknownRecord, claimed: readonly UnknownRecord[]): Promise<UnknownRecord> {\n  const cwd = cwdOf(agent)\n  const baselineOf = (message: unknown): UnknownRecord | undefined => {\n    const source = (message as UnknownRecord | undefined)?.source as UnknownRecord | undefined\n    return source?.kind === 'agent-instructions' && source.baseline === true ? source : undefined\n  }\n  // On the FIRST step the baseline is not in the log yet: DSH inserts it into\n  // the inbox and it is claimed into this very step (assembly runs before the\n  // step enters and writes it as user/message). So the claimed batch is\n  // searched first, then the durable log — the user/message it became on\n  // later turns, or the inbox insertion record that carried it in.\n  let baseline: UnknownRecord | undefined\n  for (const message of claimed) {\n    baseline = baselineOf(message)\n    if (baseline !== undefined) break\n  }\n  if (baseline === undefined) {\n    const events = readSessionEvents(agentSession(agent))\n    for (let index = events.length - 1; index >= 0 && baseline === undefined; index -= 1) {\n      const event = events[index]!\n      const data = event.data as UnknownRecord | undefined\n      if (event.type === 'user/message') baseline = baselineOf(data)\n      else if (event.type === 'agent/inbox/spliced' && Array.isArray(data?.inserted)) {\n        for (const inserted of data.inserted as unknown[]) {\n          baseline = baselineOf(inserted)\n          if (baseline !== undefined) break\n        }\n      }\n    }\n  }\n  // On the very first assembly the baseline may exist nowhere yet (DSH enters\n  // it with the step, after assembly): discovery then runs with the loader's\n  // own defaults — the same walk the stock profile configures — and picks up\n  // the recorded identity from the second turn on.\n  try {\n    const identity = typeof baseline?.baselineIdentity === 'string'\n      ? JSON.parse(baseline.baselineIdentity) as Record<string, unknown>\n      : {}\n    // The package's public surface is the discovery walk (paths) and the\n    // rendered budgeted text; per-file content is read here under the same\n    // source cap the loader applies (larger files are ignored, as it does).\n    const { discoverBaselineInstructionFiles } = await import('@deepseek-ai/dsh-agent-instructions') as unknown as {\n      discoverBaselineInstructionFiles(options: Record<string, unknown>): Promise<Array<{ absolutePath: string, displayPath: string }>>\n    }\n    const list = (value: unknown): string[] | undefined => Array.isArray(value) && value.every(entry => typeof entry === 'string') ? value as string[] : undefined\n    const discovered = await discoverBaselineInstructionFiles({\n      cwd,\n      ...(typeof identity.projectRoot === 'string' && identity.projectRoot.length > 0 ? { projectRoot: identity.projectRoot } : {}),\n      ...(list(identity.projectRootMarkers) !== undefined ? { projectRootMarkers: list(identity.projectRootMarkers) } : {}),\n      ...(list(identity.instructionFileCandidates) !== undefined ? { instructionFileCandidates: list(identity.instructionFileCandidates) } : {}),\n      ...(list(identity.localInstructionFileCandidates) !== undefined ? { localInstructionFileCandidates: list(identity.localInstructionFileCandidates) } : {}),\n    })\n    const maxSourceBytes = typeof identity.maxSourceBytes === 'number' ? identity.maxSourceBytes : 1048576\n    const contextFiles: Array<{ path: string, content: string }> = []\n    for (const file of discovered) {\n      try {\n        const bytes = await readFile(file.absolutePath)\n        if (bytes.byteLength > maxSourceBytes) continue\n        contextFiles.push({ path: file.absolutePath, content: bytes.toString('utf8') })\n      } catch {\n        // A candidate that vanished between discovery and read is simply absent.\n      }\n    }\n    return { cwd, contextFiles }\n  } catch (error) {\n    logger(ctx).warn(`[pi2dsh] could not recover the host's instruction files for before_agent_start (contextFiles left empty): ${error instanceof Error ? error.message : String(error)}`)\n    return { cwd, contextFiles: [] }\n  }\n}\n\n// Project one not-yet-entered DSH message as the Pi message shape context\n// handlers expect: a piCustomType source marker restores Pi's role:\"custom\"\n// identity, everything else is a user message.\nasync function piShapeOfPending(ctx: Context, message: UnknownRecord): Promise<UnknownRecord> {\n  const source = message.source as UnknownRecord | undefined\n  const content = await dshToPiContent(ctx, (message.content ?? []) as ContentBlock[])\n  return typeof source?.piCustomType === 'string'\n    ? { role: 'custom', customType: source.piCustomType, content }\n    : { role: 'user', content }\n}\n\n// Pi's context event on the DSH seam: full history (read-only projection from\n// the durable log) plus this step's pending messages (transformable). A\n// handler's returned array must keep the length; only the pending tail is\n// applied, with each message's blocks rebuilt from the returned Pi content.\nasync function applyPiContextTransform(\n  ctx: Context,\n  state: RuntimeState,\n  agent: UnknownRecord,\n  signal: AbortSignal | undefined,\n  pending: UnknownRecord[],\n): Promise<UnknownRecord[]> {\n  if ((state.handlers.get('context')?.length ?? 0) === 0) return pending\n  const session = agentSession(agent)\n  const history: UnknownRecord[] = []\n  for (const event of readSessionEvents(session)) {\n    const projected = await messageFromSessionEvent(ctx, event)\n    if (projected === undefined) continue\n    if (event.type === 'user/message') {\n      const customType = ((event.data as UnknownRecord | undefined)?.source as UnknownRecord | undefined)?.piCustomType\n      if (typeof customType === 'string') {\n        history.push({ ...projected, role: 'custom', customType })\n        continue\n      }\n    }\n    history.push(projected)\n  }\n  const projectedPending = await Promise.all(pending.map(message => piShapeOfPending(ctx, message)))\n  const event: UnknownRecord = { type: 'context', messages: [...history, ...projectedPending] }\n  const results = await dispatch(state, 'context', event, contextFor(ctx, state, agent, signal))\n  let current = event.messages as UnknownRecord[]\n  for (const result of results) {\n    if (typeof result !== 'object' || result === null) continue\n    const returned = (result as UnknownRecord).messages\n    if (!Array.isArray(returned)) continue\n    if (returned.length !== current.length) {\n      logger(ctx).warn('[pi2dsh] a Pi context handler changed the message count; DSH durable history is append-only, so the transform was ignored')\n      continue\n    }\n    current = returned as UnknownRecord[]\n  }\n  if (current === event.messages) return pending\n  for (let index = 0; index < history.length; index++) {\n    if (current[index] === history[index]) continue\n    if (JSON.stringify(current[index]) === JSON.stringify(history[index])) continue\n    logger(ctx).warn('[pi2dsh] a Pi context handler edited already-entered history; DSH durable history is append-only, so those edits were ignored (only this step\\'s not-yet-entered messages accept the transform)')\n    break\n  }\n  const tail = current.slice(history.length)\n  const rebuilt: UnknownRecord[] = []\n  for (const [index, original] of pending.entries()) {\n    const shape = tail[index]\n    if (shape === undefined) { rebuilt.push(original); continue }\n    if (JSON.stringify(shape.content) === JSON.stringify(projectedPending[index]?.content)) {\n      rebuilt.push(original)\n      continue\n    }\n    const blocks = await piToDshContent(ctx, typeof shape.content === 'string'\n      ? [{ type: 'text', text: shape.content }]\n      : shape.content ?? [])\n    // A context hook may edit the surrounding text while retaining the file\n    // handle. Restore those unchanged handles to their original durable refs\n    // so the host still owns file presentation and access checks.\n    const files = new Map<string, ContentBlock>()\n    for (const block of (original.content ?? []) as UnknownRecord[]) {\n      if (block.type === 'file') files.set(fileContentForPi(block.attachment, ctx as never).text, block as unknown as ContentBlock)\n    }\n    rebuilt.push(createUserMessage({\n      content: blocks.map(block => block.type === 'text' ? files.get(block.text) ?? block : block),\n      source: (original.source ?? { kind: 'plugin', plugin: state.messageSource }) as never,\n    }) as unknown as UnknownRecord)\n  }\n  return rebuilt\n}\n\n// Pi's before_agent_start images: the entering user messages' image\n// attachments, read back from the DSH attachment store as base64\n// ImageContent. Messages without attachments (or compositions without the\n// attachment service) simply contribute none — the path-in-prompt flow the\n// vision packages document works either way.\nasync function collectPiImages(ctx: Context, messages: UnknownRecord[]): Promise<UnknownRecord[]> {\n  const attachments = optionalService<DshAttachmentsLike>(ctx, 'attachments')\n  if (attachments === undefined) return []\n  const images: UnknownRecord[] = []\n  for (const message of messages) {\n    const content = (message as { content?: unknown }).content\n    if (!Array.isArray(content)) continue\n    for (const block of content as UnknownRecord[]) {\n      if (block?.type !== 'image' || block.attachment === undefined) continue\n      try {\n        const stored = await attachments.readImage(block.attachment)\n        images.push({\n          type: 'image',\n          data: Buffer.from(stored.data).toString('base64'),\n          mimeType: String((block.attachment as UnknownRecord).mediaType ?? 'image/png'),\n        })\n      } catch {\n        // An unreadable attachment contributes no image; Pi passes what exists.\n      }\n    }\n  }\n  return images\n}\n\nfunction oauthStoreOf(state: RuntimeState): FileCredentialStore {\n  state.shared.oauthStore ??= new FileCredentialStore(join(getAgentDir(), 'auth.json'))\n  return state.shared.oauthStore\n}\n\nconst COMPANION_ROUTE_PREFIX = 'pi2dsh-companion/'\n\n// HOST-level state, shared by every Pi package mounted into one host\n// composition (the engine and host bundles mount several packages through\n// one module graph and one Context). Pi's own semantics make these\n// singular per host: ONE provider directory, ONE /login command, ONE\n// credential store, ONE catalog projection. Package state (tools,\n// commands, events, runner) stays per-package. Separate converted bundles\n// each carry their own module graph, so this map is naturally per-bundle\n// there — existing behavior unchanged.\ninterface SharedHostState {\n  companionRoutes: Map<string, string>\n  providerRouteDisposers: Map<string, PiRouteHandle>\n  /** Coalesced dynamic-catalog refreshes, shared by startup and first use. */\n  providerModelDiscoveries: Map<string, Promise<number | undefined>>\n  /** Agent-runtime owners for each host-global provider route. */\n  providerRouteOwners: Map<string, Set<RuntimeState>>\n  /** Per-session Pi runtimes, in package mount order, for provider waterfalls. */\n  runtimeStatesBySession: Map<string, Set<RuntimeState>>\n  publishedOAuthKeys: Map<string, string>\n  /** Composed canonical provider configs — the ONLY read surface. Maintained\n   * exclusively by recomposeSharedProvider from the layered ledger below. */\n  providers: Map<string, UnknownRecord>\n  /** Base layer: the engine's built-in OAuth directory entries (Pi's\n   * `builtins` map). Survives any package overlay; restored on unregister. */\n  providerBuiltins?: Map<string, UnknownRecord>\n  /** Extension layer, one slot per package so a package's per-agent instances\n   * re-registering the same content stay idempotent instead of perturbing\n   * cross-package overlay order. Slot content follows Pi's re-registration\n   * contract: defined values merge over the previous registration. */\n  providerPackages?: Map<string, Map<string, UnknownRecord>>\n  /** Package overlay order = first-registration order, mirroring Pi where\n   * \"last registration wins\" is load order (per-session rebuilds keep it stable). */\n  providerPackageOrder?: string[]\n  /** Pi's cross-extension event bus is ONE bus per session; ours is one per\n   * agent (host/anchor instances share the host bus). */\n  agentEventBuses?: WeakMap<object, EventEmitter>\n  hostEventBus?: EventEmitter\n  /** Pi's theme is session-shared UI state, not per-extension. */\n  agentThemes?: WeakMap<object, Theme>\n  hostTheme?: Theme\n  /** Provider ids whose DSH authorization-seam projection is armed (an\n   * inject scope waiting on — or holding — the authorization service). */\n  authorizationArmedIds?: Set<string>\n  /** Provider ids whose deferred route restore is armed (an inject scope\n   * waiting for the credentials service to compose). */\n  routeRestoreArmedIds?: Set<string>\n  modelCatalog?: ModelCatalog\n  catalogSubscribed?: boolean\n  loginCommandRegistered?: boolean\n  oauthRefreshHooked?: boolean\n  companionSweepSubscribed?: boolean\n  oauthStore?: FileCredentialStore\n  capabilityLedger?: CapabilityLedger\n  // Per-package remount closures backing Pi's ctx.reload(): dispose every\n  // extension-owned registration and run the extension entries again through\n  // a fresh loader, so edited plugin code takes effect. Host-managed resources\n  // (skills, prompts) reload with dsh itself.\n  packageRemounts?: WeakMap<object, Map<string, () => Promise<void>>>\n  // The side-conversation panel is ONE surface per host, however many packages\n  // contribute threads to it — same rule as the provider directory.\n  browserSurfaces?: BrowserSurfaces\n  browserSurfacesRouted?: boolean\n  // The one login allowed to be in flight. Interactive OAuth flows own a FIXED\n  // local callback port (codex: 1455) and Pi's own flow, finding it taken,\n  // silently degrades to a server that never receives a code — so a second\n  // concurrent flow hands the user an address whose callback lands on the FIRST\n  // flow's listener, which rejects it as a state mismatch and leaves both\n  // dialogs waiting forever. Pi cannot hit this: its login dialog is modal, so\n  // a second flow cannot be started. On DSH /login is an ordinary command a\n  // user can run again, so the bridge has to enforce what Pi's shape enforced.\n  activeLogin?: ActiveLogin | undefined\n  // The Models-page login card's view of the one in-flight flow (alpha\n  // `settings.models.provider-card` seat). Host-level like activeLogin: one\n  // flow, one card driving it, whichever browser tab asked first.\n  browserLogin?: BrowserLoginFlow | undefined\n  // The engine's installed-package extension catalog for CHILD sessions —\n  // what \"default-discovered extensions\" means when a Pi creator spawns a\n  // child (real Pi loads them into every child unless the creator narrows).\n  childExtensions?: ChildExtensionCatalog\n  // Per (agent × package): the live Pi tool ledger of the instance mounted\n  // for that agent, so a creator's loader can present Pi's Extension.tools\n  // shape (pi-subagents' ext: tool scope reads it live every turn).\n  childPackageTools?: WeakMap<object, Map<string, ReadonlyMap<string, unknown>>>\n}\n\ninterface ActiveLogin {\n  providerName: string\n  controller: AbortController\n  /** Settles when the flow has released its callback port. */\n  finished: Promise<void>\n  /** Short links this flow published, retired when it ends. */\n  published: string[]\n}\n\n/**\n * What the login card polls: the flow's running transcript, one pending\n * question at most, and the outcome once the spine settles. Notices carry the\n * exact strings the /login command would print — URLs inside them are the\n * short links the spine already publishes on this same web server.\n */\ninterface BrowserLoginFlow {\n  provider: string\n  providerName: string\n  notices: Array<{ message: string, code?: string }>\n  question?: { id: number, kind: 'input' | 'select', title: string, placeholder?: string, options?: string[] }\n  /** Resolves the ui call the question belongs to; cleared with the question. */\n  answer?: ((value: string | undefined) => void) | undefined\n  done?: { ok: boolean, summary: string }\n}\n\nconst SHARED_HOST_STATE = new WeakMap<object, SharedHostState>()\n\n/**\n * The engine's installed-package extension catalog, for serving CHILD\n * sessions: real Pi's createAgentSession loads the default-discovered\n * extensions into every child unless the creator's loader narrows them.\n * The catalog is what \"default-discovered\" means on this host.\n */\nexport interface ChildExtensionCatalog {\n  /** Absolute declared-entry path → installed package name. */\n  packageByEntryPath: ReadonlyMap<string, string>\n  /**\n   * Mount the named packages onto one child agent (its own agent-local ctx —\n   * contributions unwind with the agent, DSH's documented scope semantics).\n   * @returns per-package failures, Pi's per-extension error isolation.\n   */\n  mount(childAgent: UnknownRecord, packageNames: readonly string[]): Promise<Array<{ name: string, error: string }>>\n}\n\nexport function registerChildExtensionCatalog(ctx: Context, catalog: ChildExtensionCatalog): void {\n  sharedHostStateOf(ctx).childExtensions = catalog\n}\n\n/** Read the installed-package catalog registered on shared host state, or undefined. */\nexport function getSharedChildExtensionCatalog(ctx: Context): ChildExtensionCatalog | undefined {\n  return sharedHostStateOf(ctx).childExtensions\n}\n\n/**\n * Which installed packages a creator's resource loader selects for its child\n * — the creator's OWN filter code decides (the loader's getExtensions applies\n * noExtensions and extensionsOverride), this only maps the surviving entry\n * paths back to package names. No loader at all means Pi's default: the full\n * discovered set (sdk.ts builds a default loader and loads everything).\n */\nfunction resolveChildExtensionPackages(\n  loader: unknown,\n  catalog: ChildExtensionCatalog,\n): { names: string[], failures: Array<{ name: string, error: string }> } {\n  if (loader === undefined || loader === null) {\n    return { names: [...new Set(catalog.packageByEntryPath.values())], failures: [] }\n  }\n  const getExtensions = (loader as { getExtensions?: () => { extensions?: unknown[] } }).getExtensions\n  if (typeof getExtensions !== 'function') return { names: [], failures: [] }\n  const names = new Set<string>()\n  const failures: Array<{ name: string, error: string }> = []\n  let entries: unknown[]\n  try {\n    entries = getExtensions.call(loader)?.extensions ?? []\n  } catch (error) {\n    return { names: [], failures: [{ name: 'resourceLoader.getExtensions', error: error instanceof Error ? error.message : String(error) }] }\n  }\n  for (const entry of entries) {\n    const path = (entry as { path?: unknown } | undefined)?.path\n    if (typeof path !== 'string' || path.length === 0) continue\n    const name = catalog.packageByEntryPath.get(pathResolve(path))\n    if (name !== undefined) names.add(name)\n    else {\n      failures.push({\n        name: path,\n        error: 'not an installed DSH plugin — path-loaded extensions are not supported on this host; install it with `dsh plugin add <pkg>`',\n      })\n    }\n  }\n  return { names: [...names], failures }\n}\n\n/**\n * Pi's provider ledger is layered, not flat (model-runtime.ts:742-786 at the\n * pinned upstream): a builtin base map, an extension overlay where defined\n * fields merge over the base (undefined fields expose the base — a package\n * overriding only baseUrl keeps the builtin OAuth flow), later registrations\n * overriding earlier ones, and unregistration restoring the builtin. These\n * helpers vendor that contract for the shared host ledger. One deliberate\n * adaptation: the overlay is slotted per PACKAGE and folded in package\n * first-registration order, because in Pi \"last wins\" is load order (each\n * session rebuilds the runtime so registration order is always load order),\n * while our host ledger accumulates across sessions — folding raw arrival\n * order would let a later agent's re-registration of package A overturn\n * package B for no Pi-semantic reason.\n */\nexport function mergeProviderRegistration(previous: UnknownRecord | undefined, config: UnknownRecord): UnknownRecord {\n  const effective: UnknownRecord = { ...previous }\n  for (const [key, value] of Object.entries(config)) {\n    if (value !== undefined) effective[key] = value\n  }\n  return effective\n}\n\nexport function overlayProviderConfig(base: UnknownRecord | undefined, overlay: UnknownRecord): UnknownRecord {\n  const merged: UnknownRecord = { ...base }\n  for (const [key, value] of Object.entries(overlay)) {\n    if (value !== undefined) merged[key] = value\n  }\n  // Pi's applyExtension: an overlay WITHOUT its own model list keeps the base\n  // models, rebased onto the overlay's gateway when one is given; an overlay\n  // WITH a model list replaces the base list outright (handled by the field\n  // copy above).\n  const baseModels = base?.models\n  if (overlay.models === undefined && typeof overlay.baseUrl === 'string' && Array.isArray(baseModels)) {\n    merged.models = baseModels.map(entry => (\n      typeof entry === 'object' && entry !== null ? { ...entry as UnknownRecord, baseUrl: overlay.baseUrl } : entry\n    ))\n  }\n  return merged\n}\n\n/** Structural fingerprint used to decide whether a recomposition actually\n * changed the canonical shape. Function identities differ on every factory\n * run (each agent instance registers fresh closures), so functions compare\n * by presence — behaviourally equivalent re-registrations keep the existing\n * canonical reference and the route built on it, exactly like today. */\nfunction providerFingerprint(config: UnknownRecord | undefined): string {\n  if (config === undefined) return 'absent'\n  return JSON.stringify(config, (_key, value: unknown) => (typeof value === 'function' ? '[function]' : value))\n}\n\nfunction recordPackageProviderRegistration(shared: SharedHostState, packageName: string, name: string, value: UnknownRecord): void {\n  shared.providerPackages ??= new Map()\n  shared.providerPackageOrder ??= []\n  if (!shared.providerPackageOrder.includes(packageName)) shared.providerPackageOrder.push(packageName)\n  let slots = shared.providerPackages.get(name)\n  if (slots === undefined) {\n    slots = new Map()\n    shared.providerPackages.set(name, slots)\n  }\n  slots.set(packageName, mergeProviderRegistration(slots.get(packageName), value))\n}\n\n/** Rebuild the canonical entry for one provider id from builtin + package\n * slots. Returns whether the composed shape changed (callers retire the\n * route on change so it is rebuilt from the new canonical). */\nfunction recomposeSharedProvider(shared: SharedHostState, name: string): boolean {\n  const builtin = shared.providerBuiltins?.get(name)\n  const slots = shared.providerPackages?.get(name)\n  let canonical: UnknownRecord | undefined\n  if (slots === undefined || slots.size === 0) {\n    // No overlays: expose the builtin untouched so its auth/login behavior is\n    // exact (Pi recomposeProvider takes the same shortcut).\n    canonical = builtin\n  } else {\n    canonical = { ...(builtin ?? {}) }\n    for (const packageName of shared.providerPackageOrder ?? []) {\n      const registration = slots.get(packageName)\n      if (registration !== undefined) canonical = overlayProviderConfig(canonical, registration)\n    }\n  }\n  const previous = shared.providers.get(name)\n  const changed = providerFingerprint(previous) !== providerFingerprint(canonical)\n  if (!changed) return false\n  if (canonical === undefined) shared.providers.delete(name)\n  else shared.providers.set(name, canonical)\n  return true\n}\n\n/** Force-retire a provider's route regardless of refcounts: the canonical\n * definition changed, so a route built on the old shape must not serve it. */\nfunction retireSharedProviderRoute(shared: SharedHostState, name: string): void {\n  const route = shared.providerRouteDisposers.get(name)\n  if (route === undefined) return\n  shared.providerRouteDisposers.delete(name)\n  shared.providerRouteOwners.delete(name)\n  route()\n}\n\nfunction sharedEventBusFor(shared: SharedHostState, ownerAgent: UnknownRecord | undefined): EventEmitter {\n  if (ownerAgent === undefined) {\n    if (shared.hostEventBus === undefined) {\n      shared.hostEventBus = new EventEmitter()\n      shared.hostEventBus.setMaxListeners(0)\n    }\n    return shared.hostEventBus\n  }\n  shared.agentEventBuses ??= new WeakMap()\n  let bus = shared.agentEventBuses.get(ownerAgent)\n  if (bus === undefined) {\n    bus = new EventEmitter()\n    bus.setMaxListeners(0)\n    shared.agentEventBuses.set(ownerAgent, bus)\n  }\n  return bus\n}\n\nfunction sharedThemeFor(shared: SharedHostState, ownerAgent: UnknownRecord | undefined): Theme {\n  if (ownerAgent === undefined) {\n    shared.hostTheme ??= new Theme()\n    return shared.hostTheme\n  }\n  shared.agentThemes ??= new WeakMap()\n  let theme = shared.agentThemes.get(ownerAgent)\n  if (theme === undefined) {\n    theme = new Theme()\n    shared.agentThemes.set(ownerAgent, theme)\n  }\n  return theme\n}\n\nfunction sharedHostStateOf(ctx: Context): SharedHostState {\n  const key = ((ctx as unknown as { root?: object }).root ?? ctx) as object\n  let shared = SHARED_HOST_STATE.get(key)\n  if (shared === undefined) {\n    shared = {\n      companionRoutes: new Map(),\n      providerRouteDisposers: new Map(),\n      providerModelDiscoveries: new Map(),\n      providerRouteOwners: new Map(),\n      runtimeStatesBySession: new Map(),\n      publishedOAuthKeys: new Map(),\n      providers: new Map(),\n    }\n    SHARED_HOST_STATE.set(key, shared)\n  }\n  return shared\n}\n\nfunction packageRemountsOf(ctx: Context, shared: SharedHostState): Map<string, () => Promise<void>> {\n  const scoped = scopeOf(ctx)\n  const owner = (typeof scoped === 'object' && scoped !== null ? scoped : ctx) as object\n  const byOwner = (shared.packageRemounts ??= new WeakMap())\n  let remounts = byOwner.get(owner)\n  if (remounts === undefined) {\n    remounts = new Map()\n    byOwner.set(owner, remounts)\n  }\n  return remounts\n}\n\n/** Companion configuration: default (auto), `false` (off), or an explicit narrow map. */\nexport type VisionCompanionsConfig = false | Record<string, readonly string[]> | undefined\n\n/**\n * Image-admission companion routes: for every text-only route in the DSH\n * llm directory, a `<route>-vision` route that admits images at the host's\n * admission checks, replaces image blocks with explicit path-carrying\n * notices, and forwards text-only to the original route. What happens to\n * an admitted image is decided at run time by whatever is mounted — a\n * vision extension analyzes it through the turn's entering messages, and\n * without one the notice's file path lets any image-capable tool read it —\n * so companions need no knowledge of any particular plugin and are\n * registered AUTOMATICALLY (zero configuration). `visionCompanions: false`\n * turns them off; an explicit `{ <route>: [modelIds] }` map narrows them.\n * The directory is live: adapters-updated re-sweeps, adding companions for\n * new text-only routes and disposing companions whose original vanished.\n * The companion is an ordinary directory entry (single-directory\n * contract); Pi's ctx.model reports the original route for it\n * (companionRoutes). Idempotent per host.\n */\nexport function registerVisionCompanions(ctx: Context, config: VisionCompanionsConfig): void {\n  if (config === false) return\n  const shared = sharedHostStateOf(ctx)\n  const llm = llmOf(ctx)\n  if (llm === undefined) return\n  const sweep = async (): Promise<void> => {\n    const explicit = config\n    const providers = llm.listProviders()\n    const wanted = new Map<string, { originalId: string, imageModels: Set<string> | undefined }>()\n    if (explicit !== undefined) {\n      for (const [originalId, modelIds] of Object.entries(explicit)) {\n        if (!Array.isArray(modelIds) || modelIds.length === 0) continue\n        if (!providers.some(provider => provider.id === originalId)) {\n          logger(ctx).warn(`[pi2dsh] visionCompanions names route ${JSON.stringify(originalId)}, but no such llm route exists; no companion route was registered`)\n          continue\n        }\n        wanted.set(`${originalId}-vision`, { originalId, imageModels: new Set(modelIds.map(String)) })\n      }\n    } else {\n      for (const provider of providers) {\n        if (shared.companionRoutes.has(provider.id)) continue\n        try {\n          const models = await llm.listModels(provider.id)\n          if (models.length === 0) continue\n          const textOnly = models.every(model => !(Array.isArray(model.inputModalities) && (model.inputModalities as string[]).includes('image')))\n          // undefined imageModels = every model of the route.\n          if (textOnly) wanted.set(`${provider.id}-vision`, { originalId: provider.id, imageModels: undefined })\n        } catch {\n          // A provider whose adapter fails to list contributes no companion.\n        }\n      }\n    }\n    // Dispose companions whose original route vanished from the directory.\n    for (const [key, dispose] of shared.providerRouteDisposers) {\n      if (!key.startsWith(COMPANION_ROUTE_PREFIX)) continue\n      const companionId = key.slice(COMPANION_ROUTE_PREFIX.length)\n      const originalId = shared.companionRoutes.get(companionId)\n      if (originalId !== undefined && !providers.some(provider => provider.id === originalId)) {\n        shared.providerRouteDisposers.delete(key)\n        dispose()\n        logger(ctx).info(`[pi2dsh] companion route ${JSON.stringify(companionId)} disposed (its original route ${JSON.stringify(originalId)} left the directory)`)\n      }\n    }\n    for (const [companionId, spec] of wanted) {\n      // The companion→original mapping is a CONFIGURATION fact, not a\n      // registration outcome: in a host with several bundles, one bundle\n      // wins the route name and the others' registration is refused, but\n      // every bundle's ctx.model projection must still report the original\n      // route for a companion selection.\n      shared.companionRoutes.set(companionId, spec.originalId)\n      if (shared.providerRouteDisposers.has(`${COMPANION_ROUTE_PREFIX}${companionId}`)) continue\n      try {\n        const dispose = (llm as unknown as { registerAdapter(providers: string[], adapter: unknown): () => void })\n          .registerAdapter([companionId], imageAdmissionCompanionAdapter({\n            originalId: spec.originalId,\n            ...(spec.imageModels === undefined ? {} : { imageModels: spec.imageModels }),\n            llm,\n            materializeImage: attachment => materializeAttachmentImage(ctx, attachment),\n          }))\n        shared.providerRouteDisposers.set(`${COMPANION_ROUTE_PREFIX}${companionId}`, dispose)\n        logger(ctx).info(`[pi2dsh] image-admission companion route ${JSON.stringify(companionId)} registered for ${JSON.stringify(spec.originalId)}`)\n      } catch (error) {\n        logger(ctx).warn(`[pi2dsh] companion route ${JSON.stringify(companionId)} already has a live adapter in this host (${error instanceof Error ? error.message : String(error)}); reusing it`)\n      }\n    }\n  }\n  // Our own companion registrations fire llm/adapters-updated, so the\n  // event-triggered sweep must coalesce: one in flight, at most one queued.\n  // Convergence: a re-sweep after registration finds nothing new to add.\n  let sweeping = false\n  let queued = false\n  const runSweep = (): void => {\n    if (sweeping) {\n      queued = true\n      return\n    }\n    sweeping = true\n    void sweep().finally(() => {\n      sweeping = false\n      if (queued) {\n        queued = false\n        runSweep()\n      }\n    })\n  }\n  runSweep()\n  if (shared.companionSweepSubscribed !== true) {\n    shared.companionSweepSubscribed = true\n    const cordisCtx = ctx as unknown as { on(name: string, callback: (...args: unknown[]) => unknown): () => void }\n    cordisCtx.on('llm/adapters-updated', () => { runSweep() })\n  }\n}\n\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n  'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif',\n}\n\n// Give a stored image attachment a filesystem path so path-taking tools\n// (Pi's read, vision tools) can reach it — Pi's own world has no attachment\n// store, images are inline or file paths, so a path IS the Pi-shaped answer.\n// Files are cached per attachment id under the OS temp dir.\nasync function materializeAttachmentImage(ctx: Context, attachment: UnknownRecord): Promise<string | undefined> {\n  const attachments = (ctx as unknown as { get(name: string): unknown }).get('attachments') as {\n    readImage(attachment: unknown): Promise<{ data: ArrayBufferLike }>\n  } | undefined\n  const id = typeof attachment.attachmentId === 'string' ? attachment.attachmentId : undefined\n  if (attachments === undefined || id === undefined) return undefined\n  const extension = IMAGE_EXTENSIONS[String(attachment.mediaType)] ?? 'png'\n  const dir = join(tmpdir(), 'pi2dsh-attached-images')\n  const filePath = join(dir, `${id}.${extension}`)\n  try {\n    if (!existsSync(filePath)) {\n      const stored = await attachments.readImage(attachment)\n      await mkdir(dir, { recursive: true })\n      await writeFile(filePath, Buffer.from(stored.data))\n    }\n    return filePath\n  } catch {\n    // An unreadable attachment simply keeps the plain omission notice.\n    return undefined\n  }\n}\n\n// Pi hosts ship /login <provider> as a built-in. It is host-level end to\n// end: the provider directory it reads is host-shared and a host-registered\n// command reaches every agent's palette, so exactly one registration serves\n// the whole host however many packages and agents mount.\nfunction ensureLoginCommand(ctx: Context, state: RuntimeState): void {\n  // Skip the bridge's fallback ONLY when the native /login is a real\n  // replacement: the terminal owns the name AND the composition carries the\n  // authorization service the bridge projects Pi OAuth flows into — that is\n  // what makes the native flow able to offer them (dsh-pi-tui, verified with\n  // 43 providers). A native `login` WITHOUT that service is a different\n  // feature wearing the same name (dsh-TUI 0.9's credential-status view on a\n  // stock composition), and dropping the fallback there deletes the user's\n  // only Pi OAuth entry point — the fallback then registers and the shared\n  // aliasing gives it the /pi-login seat, exactly the pre-existing reachable\n  // shape. Capability judgement, never a package-name special case.\n  if (!shouldRegisterCompatibilityCommand('login', state.tuiSurfaces?.nativeCommands)\n    && optionalService(ctx, 'authorization') !== undefined) {\n    logger(ctx).debug('[pi2dsh] native terminal owns /login and the authorization service is composed; Pi OAuth flows are available through it')\n    return\n  }\n  // ONE registration per host. /login is host-level through and through: it\n  // reads the SHARED provider directory and a host-registered command is\n  // visible from every agent's palette (verified live — the TUI probe drives\n  // /pi-login registered at the host anchor). The old idempotency key was\n  // the caller's SCOPE, and host-anchor mounts have no agent scope — each\n  // package's own activation became a distinct owner, every package\n  // registered its own copy, and DSH's collision numbering quietly mounted\n  // them as /login-2/-3/-4 instead of throwing.\n  if (state.shared.loginCommandRegistered === true) return\n  state.shared.loginCommandRegistered = true\n  try {\n    registerLoginCommand(ctx, state)\n    // The registration lives on THIS package's activation; when that package\n    // unmounts (remove, /reload remount) the command goes with it, so the\n    // host flag must clear for the next mount to re-register.\n    ctx.effect(() => () => { state.shared.loginCommandRegistered = false })\n  } catch (error) {\n    state.shared.loginCommandRegistered = false\n    logger(ctx).warn(`[pi2dsh] /login could not be registered; provider logins remain available on the host's own sign-in surface (${error instanceof Error ? error.message : String(error)})`)\n  }\n}\n\n/**\n * Turn what the user answered into one of the offered options.\n * @param answer - the label, a differently-cased label, or a 1-based position.\n * @param offered - the options as they were shown, in order.\n * @returns the matching option, or undefined when nothing matches.\n */\nfunction resolveOfferedChoice(answer: string, offered: readonly string[]): string | undefined {\n  const trimmed = answer.trim()\n  if (offered.includes(trimmed)) return trimmed\n  const insensitive = offered.find(name => name.toLowerCase() === trimmed.toLowerCase())\n  if (insensitive !== undefined) return insensitive\n  if (/^\\d+$/u.test(trimmed)) {\n    const at = Number(trimmed) - 1\n    if (at >= 0 && at < offered.length) return offered[at]\n  }\n  return undefined\n}\n\n/**\n * Cancel the login already in flight, if any, and wait for it to let go.\n *\n * Waiting matters: the next flow binds the same fixed callback port, and Pi's\n * flow answers a taken port by silently degrading to a listener that never\n * receives a code. Starting the new flow before the old one has closed\n * reproduces exactly that.\n * @param state - the mounting package's state, holding the shared host state.\n * @returns the cancelled provider's name, or undefined when nothing was running.\n */\nasync function supersedeActiveLogin(state: RuntimeState): Promise<string | undefined> {\n  const previous = state.shared.activeLogin\n  if (previous === undefined) return undefined\n  state.shared.activeLogin = undefined\n  previous.controller.abort()\n  for (const path of previous.published) revokeAuthorization(path)\n  let timer: ReturnType<typeof setTimeout> | undefined\n  const released = await Promise.race([\n    previous.finished.then(() => true),\n    new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), 5_000) }),\n  ])\n  if (timer !== undefined) clearTimeout(timer)\n  // Never start a flow that would silently lose its callback: say so instead.\n  if (!released) {\n    throw new Error(`the ${previous.providerName} login is still shutting down; try /login again in a moment`)\n  }\n  return previous.providerName\n}\n\n/**\n * Give a logged-in provider a route, if nothing else already gave it one.\n *\n * Pi's built-in OAuth providers (openai-codex, anthropic, github-copilot,\n * kimi-coding) are seeded so `/login` can offer them, but they carry no\n * transport and no catalog — so the registration path above never builds them\n * a route, and a successful login used to leave the model picker unchanged.\n * A stored credential is the whole precondition: with one, the models pi-ai's\n * installed catalog describes become selectable through DSH's own adapter.\n * @param name - the Pi provider id, which is also its DSH route name.\n * @param config - the provider config, whose oauth block made it loginable.\n * @returns whether this call put a route in place.\n */\n/**\n * Mount-time route restore that tolerates composition order.\n *\n * The credentials service (credentials-local) can compose AFTER a\n * zero-package profile's host mount — probing immediately loses that race and\n * a stored login silently produces no route: an engine-only profile with a\n * valid auth.json hit MISSING_CREDENTIAL on every turn, while installing any\n * Pi package shifted mount timing enough to mask the bug (2026-08-30,\n * community/full-audit-work/zero-package-oauth-bug.md). When the service is\n * already there the restore stays awaited — that is mount readiness, see the\n * caller's comment. Otherwise the official inject seam re-runs it the moment\n * the service composes, the same pattern maybeProjectAuthorizationFlow uses.\n */\nasync function restoreLoggedInRouteWhenReady(\n  ctx: Context,\n  state: RuntimeState,\n  name: string,\n  config: UnknownRecord,\n): Promise<void> {\n  if (optionalService(ctx, 'credentials') !== undefined) {\n    await ensureLoggedInProviderRoute(ctx, state, name, config)\n    return\n  }\n  const shared = state.shared\n  shared.routeRestoreArmedIds ??= new Set()\n  if (shared.routeRestoreArmedIds.has(name)) return\n  const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => void }).inject\n  if (typeof inject !== 'function') {\n    // No inject seam to wait on: run once so the \"no credentials service\"\n    // warning states the truth for this composition instead of staying silent.\n    await ensureLoggedInProviderRoute(ctx, state, name, config)\n    return\n  }\n  shared.routeRestoreArmedIds.add(name)\n  inject.call(ctx, ['credentials'], scope => {\n    ensureLoggedInProviderRoute(scope, state, name, config).catch(error =>\n      logger(ctx).warn(`[pi2dsh] could not restore the route for logged-in provider ${JSON.stringify(name)}: ${error instanceof Error ? error.message : String(error)}`))\n  })\n}\n\nasync function ensureLoggedInProviderRoute(\n  ctx: Context,\n  state: RuntimeState,\n  name: string,\n  config: UnknownRecord,\n): Promise<boolean> {\n  if (!providerSupportsOAuth(config)) return false\n  // A package that carries a transport or declares a catalog already has its\n  // own, better, route — this is only for a provider whose sole capability is\n  // logging in.\n  if (providerCarriesTransport(config) || state.providerRouteDisposers.has(name)) return false\n  // A route written by an earlier session may already be registered when this\n  // package mounts. That only means its SETTINGS survived; it says nothing\n  // about the credential behind apiKeyEnv (a copied profile, a cleared host\n  // store, or a rotated OAuth token can all leave it missing/stale). Publish\n  // and arm refresh first, then skip only the redundant settings write.\n  const alreadyRouted = llmOf(ctx)?.listProviders().some(provider => provider.id === name) === true\n  const credential = await storedOAuthCredential(oauthStoreOf(state), name).catch(() => undefined)\n  if (credential === undefined) return false\n  // The route is CONFIGURATION, not transport: the official llm-pi-ai adapter\n  // is already mounted and owns this namespace, so the profile goes into its\n  // settings section — mounting a second copy of that plugin collides on the\n  // provider directory it declares (\"configurable provider ... is already\n  // declared\"). The profile names the credential and nothing else: no api, no\n  // baseURL, no models, so the adapter reuses pi-ai's installed provider with\n  // its own protocol, quirks and model catalog.\n  // The profile names a credential; something has to put a value behind that\n  // name. DSH's credentials service is a SINGLE service (credentials-local\n  // holds it), so a bridge-owned provider cannot be mounted beside it without\n  // shadowing the host's own store — the value goes into the host's store\n  // instead, and stays fresh through the per-request hook below.\n  const published = await publishOAuthCredential(ctx, state, name, config)\n  if (!published.ok) return false\n  keepOAuthCredentialFresh(ctx, state)\n  if (alreadyRouted) return false\n  const settings = optionalService<{ update(ns: string, patch: object): Promise<void> }>(ctx, 'settings')\n  if (settings === undefined) {\n    logger(ctx).warn(`[pi2dsh] logged in to ${JSON.stringify(name)}, but this composition has no settings service to declare its model route in`)\n    return false\n  }\n  await settings.update('llm-pi-ai', {\n    providers: {\n      [name]: {\n        // The name the user logged in as, so the picker groups models under\n        // \"OpenAI (ChatGPT Plus/Pro)\" rather than a bare route key.\n        ...(typeof config.name === 'string' ? { displayName: config.name } : {}),\n        // An endpoint the credential itself decided (github-copilot reads its\n        // host out of the token, so an enterprise or proxied account is not on\n        // the catalog default). It is an address, not a secret, and overriding\n        // it does NOT repoint the route — only naming `api` would, and that is\n        // what would cost the catalog provider's own protocol and quirks.\n        ...(published.baseUrl === undefined ? {} : { baseURL: published.baseUrl }),\n        apiKeyEnv: oauthCredentialRef(name),\n      },\n    },\n  })\n  return true\n}\n\ninterface DshCredentialsLike {\n  set(ref: string, value: string): Promise<void>\n  describe(ref: string): Promise<{ configured: boolean, writable: boolean }>\n}\n\n/**\n * Put a logged-in provider's current key where the official adapter reads it.\n *\n * Pi keeps the OAuth credential (access + refresh + expiry) in its own store;\n * DSH's adapter reads one opaque value through the credentials seam. This is\n * the join: Pi's resolution runs — including its double-checked-lock refresh\n * when the token is inside the five-minute window — and whatever key that\n * yields is stored under the reference the profile names.\n * @returns whether a key is now behind the reference, plus any endpoint the\n *   credential itself decided (some providers read their host out of the token).\n */\nasync function publishOAuthCredential(\n  ctx: Context,\n  state: RuntimeState,\n  name: string,\n  config: UnknownRecord,\n): Promise<{ ok: boolean, baseUrl?: string }> {\n  const credentials = optionalService<DshCredentialsLike>(ctx, 'credentials')\n  if (credentials === undefined) {\n    logger(ctx).warn(`[pi2dsh] logged in to ${JSON.stringify(name)}, but this composition has no credentials service to hand the token to`)\n    return { ok: false }\n  }\n  const resolvedAuth = (await resolvePiProviderAuth({\n    providerId: name, providerConfig: config, store: oauthStoreOf(state),\n  }).catch(() => undefined))?.auth as { apiKey?: unknown, baseUrl?: unknown } | undefined\n  const key = typeof resolvedAuth?.apiKey === 'string' ? resolvedAuth.apiKey : undefined\n  if (key === undefined || key.length === 0) {\n    // Some flows hand back a header rather than a key (kimi-coding returns\n    // `{headers: {Authorization: ...}}`). DSH's profile carries a credential\n    // REFERENCE, never a secret, so a header-shaped credential has nowhere to\n    // go — and staying silent about it is how \"logged in, still no models\"\n    // happens. Say it once, plainly, instead of leaving an empty picker.\n    logger(ctx).warn(`[pi2dsh] logged in to ${JSON.stringify(name)}, but this provider authenticates with a request header rather than an api key — DSH routes name a credential reference, so no model route was added for it`)\n    return { ok: false }\n  }\n  const ref = oauthCredentialRef(name)\n  // An inherited environment value is the one layer the host cannot edit, and\n  // it WINS resolution — writing under it would be stored and never read.\n  const endpoint = typeof resolvedAuth?.baseUrl === 'string' ? { baseUrl: resolvedAuth.baseUrl } : {}\n  const described = await credentials.describe(ref).catch(() => undefined)\n  if (described?.writable === false) return { ok: true, ...endpoint }\n  if (state.publishedOAuthKeys.get(name) === key) return { ok: true, ...endpoint }\n  await credentials.set(ref, key)\n  state.publishedOAuthKeys.set(name, key)\n  return { ok: true, ...endpoint }\n}\n\n/**\n * Re-publish rotating OAuth keys at the moment a request needs them.\n *\n * An access token expires (codex's in about an hour), so a value stored once at\n * login goes stale and every later request fails on a credential the user\n * believes they supplied. DSH's own credentials contract is per-operation for\n * exactly this reason, and `llm/stream` is the per-operation seam.\n *\n * Whether the refresh is awaited depends on whether this request can still be\n * served by what is stored. Inside Pi's refresh window the stored token is\n * still VALID, so refreshing beside the request costs nothing and the rotated\n * key is there for the next one. Past expiry it is not: publishing in the\n * background there means the first request after an idle stretch goes out with\n * a dead token and fails, every time, and only the second one works. So an\n * expired credential blocks its own request until it has been renewed.\n */\nfunction keepOAuthCredentialFresh(ctx: Context, state: RuntimeState): void {\n  if (state.shared.oauthRefreshHooked === true) return\n  state.shared.oauthRefreshHooked = true\n  const cordisCtx = ctx as unknown as { on(event: string, handler: (...args: never[]) => unknown): () => void }\n  cordisCtx.on('llm/stream', ((options: UnknownRecord, next: () => AsyncIterable<unknown>) => {\n    const provider = typeof options.provider === 'string' ? options.provider : undefined\n    const config = provider === undefined ? undefined : state.shared.providers.get(provider)\n    if (provider === undefined || config === undefined || !providerSupportsOAuth(config)) return next()\n    const publish = (): Promise<unknown> => publishOAuthCredential(ctx, state, provider, config)\n      .catch(error => logger(ctx).warn(`[pi2dsh] could not refresh the stored credential for ${JSON.stringify(provider)}: ${error instanceof Error ? error.message : String(error)}`))\n    return (async function* () {\n      const stored = await storedOAuthCredential(oauthStoreOf(state), provider).catch(() => undefined)\n      const expires = typeof stored?.expires === 'number' ? stored.expires : undefined\n      // Expired (or an unstated expiry, which cannot be trusted): this request\n      // cannot go out on what is stored, so wait for the renewal.\n      if (expires === undefined || expires <= Date.now()) await publish()\n      else void publish()\n      yield* next()\n    })()\n  }) as never)\n}\n\n/**\n * Ask a provider package to discover its models, then let the host see them.\n *\n * Gateway discovery needs a credential, and a credential is not always there\n * when the provider registers: OAuth providers get theirs from a `/login` the\n * user runs later. So this is called at registration AND after a login — the\n * two moments a credential can appear — and it ends by re-announcing the\n * route, because DSH's directory observers (the model picker among them)\n * re-read on the route-set notification and nothing else.\n * @param name - the Pi provider id, which is also its DSH route name.\n * @param value - the provider config the package registered.\n * @returns how many models the route lists afterwards, or undefined when the\n *   package has no discovery of its own.\n */\nasync function discoverProviderModels(\n  ctx: Context,\n  state: RuntimeState,\n  name: string,\n  value: UnknownRecord,\n): Promise<number | undefined> {\n  const refreshModels = (value as { refreshModels?: unknown }).refreshModels\n  if (typeof refreshModels !== 'function') return undefined\n  const existing = state.shared.providerModelDiscoveries.get(name)\n  if (existing !== undefined) return await existing\n  const task = (async (): Promise<number | undefined> => {\n    try {\n      const resolved = await resolvePiProviderAuth({\n        providerId: name, providerConfig: value, store: oauthStoreOf(state),\n      }).catch(() => undefined)\n      const apiKey = (resolved?.auth as UnknownRecord | undefined)?.apiKey\n      await Promise.resolve(refreshModels.call(value, {\n        stored: undefined,\n        ...(apiKey === undefined ? {} : { credential: { type: 'api_key', key: apiKey } }),\n        store: {\n          read: async () => undefined,\n          write: async () => {},\n          delete: async () => {},\n        },\n        allowNetwork: true,\n        signal: new AbortController().signal,\n        publish: async (publication: { update?: () => void }) => {\n          publication.update?.()\n          return true\n        },\n      }))\n    } catch (error) {\n      logger(ctx).warn(`[pi2dsh] model catalog refresh for Pi provider ${JSON.stringify(name)} failed (its registry entries stay static): ${error instanceof Error ? error.message : String(error)}`)\n      return undefined\n    }\n    // The Pi-side projection, then the DSH-side announcement. Refreshing only\n    // the first is what left a post-login model list invisible until a restart:\n    // the entries existed, and no directory observer had been told to look.\n    void state.modelCatalog?.refresh()\n    state.providerRouteDisposers.get(name)?.reannounce?.()\n    return await llmOf(ctx)?.listModels(name).then(models => models.length).catch(() => undefined)\n  })()\n  state.shared.providerModelDiscoveries.set(name, task)\n  try {\n    return await task\n  } finally {\n    if (state.shared.providerModelDiscoveries.get(name) === task)\n      state.shared.providerModelDiscoveries.delete(name)\n  }\n}\n\n/** The dialog surface a login flow talks to — the /login command hands the\n * DSH command UI, the authorization-seam flow hands a session adapter. */\nexport interface ProviderLoginUi {\n  input(title: unknown, placeholder?: unknown, signal?: AbortSignal): Promise<string | undefined>\n  select(title: unknown, options: unknown[], signal?: AbortSignal): Promise<string | undefined>\n  notify(message: unknown): void\n  deviceCode?(title: unknown, detail: unknown, signal?: AbortSignal): Promise<void>\n}\n\n/**\n * Run one provider's own OAuth login end to end — the shared spine behind\n * the /login command and the DSH authorization-seam flow. Owns the\n * host-wide single-flight (the fixed callback port), the short-link\n * publication, and the post-login route + catalog refresh.\n * @returns the user-facing summary line.\n */\nasync function runProviderLogin(\n  ctx: Context,\n  state: RuntimeState,\n  providerId: string,\n  config: UnknownRecord,\n  ui: ProviderLoginUi,\n  externalSignal?: AbortSignal,\n): Promise<string> {\n  const oauthName = ((config.oauth as UnknownRecord | undefined)?.name as string | undefined) ?? providerId\n  // One login at a time, host-wide (see SharedHostState.activeLogin). A\n  // newer login is the user's current intent — nobody runs it twice\n  // wanting two — so it takes over: the previous flow is cancelled, which\n  // also closes its dialog and frees the callback port the new flow needs.\n  const superseded = await supersedeActiveLogin(state)\n  if (superseded !== undefined) ui.notify(`Cancelled the ${superseded} login that was still waiting.`)\n  const active: ActiveLogin = {\n    providerName: oauthName,\n    controller: new AbortController(),\n    finished: Promise.resolve(),\n    published: [],\n  }\n  if (externalSignal !== undefined) {\n    if (externalSignal.aborted) active.controller.abort()\n    else externalSignal.addEventListener('abort', () => active.controller.abort(), { once: true })\n  }\n  const attempt = loginPiProvider({\n    // The host action: this is the one place that opens a window on the\n    // machine dsh runs on. Nothing below this layer reaches for it.\n    open: openBrowser,\n    // A short link on this app's own origin, because a 400-character\n    // authorize URL in a dialog is not something a person can click.\n    shorten: (url: string) => {\n      const path = publishAuthorization(url)\n      const web = (ctx as unknown as { get(name: string): { port?: number, host?: string } | undefined }).get('webServer')\n      if (path === undefined || web?.port === undefined) return undefined\n      active.published.push(path)\n      const host = web.host === '0.0.0.0' || web.host === undefined ? '127.0.0.1' : web.host\n      return `http://${host}:${web.port}${path}`\n    },\n    providerId,\n    providerName: oauthName,\n    providerConfig: config,\n    store: oauthStoreOf(state),\n    ui,\n    signal: active.controller.signal,\n  })\n  // What the NEXT login waits on before binding the port: the attempt\n  // itself, however it ends.\n  active.finished = attempt.then(() => undefined, () => undefined)\n  state.shared.activeLogin = active\n  try {\n    await attempt\n  } finally {\n    for (const path of active.published) revokeAuthorization(path)\n    if (state.shared.activeLogin === active) state.shared.activeLogin = undefined\n  }\n  // The credential the user just supplied is the one gateway discovery was\n  // missing. Running it now — and re-announcing the route — is what makes\n  // this provider's models appear in the model picker without a restart;\n  // logging in and then finding nothing to select is not a login.\n  // Logging in is only half of \"I want this gateway's models\": the other\n  // half is the route. Declared first, so the discovery below (and the\n  // count reported to the user) sees it.\n  const declared = await ensureLoggedInProviderRoute(ctx, state, providerId, config)\n  const discovered = await discoverProviderModels(ctx, state, providerId, config)\n    ?? (declared ? await llmOf(ctx)?.listModels(providerId).then(list => list.length).catch(() => undefined) : undefined)\n  const models = discovered === undefined ? '' : `; ${discovered} models available`\n  ui.notify(`Logged in to ${oauthName}${models}`)\n  return `Logged in to ${oauthName}${models}`\n}\n\n/**\n * Project one provider's OAuth login onto DSH's official authorization seam\n * (`ctx.authorization`, 0.1.1 line). The flow runs the SAME login spine as\n * /login; the DSH sign-in surface supplies the interaction. On hosts without\n * the seam (rc.8 line) this is a no-op and /login stays the only entry.\n *\n * The credential itself stays in the bridge's Pi-format store — the DSH\n * credential record written at the end is the seam's commit witness (the\n * service verifies it observed a record update for the flow's key), and the\n * official sign-out (`deleteRecord`) is mirrored back into the Pi store by\n * the watcher below.\n *\n * Same id under another scope (the official llm-pi-ai catalog registers\n * sign-ins for its whole catalog) is NOT a conflict: flows are keyed by\n * scope/id exactly so registrars can coexist, and the credential spaces\n * really are separate — signing in through the official flow lands a record\n * only llm-pi-ai routes can use, while this flow authorizes the routes the\n * bridge actually serves (package transports and logged-in builtins).\n * Standing down here would leave those routes unreachable from the native\n * surface. The label carries \"(pi2dsh)\" so a future surface shows whose\n * sign-in each entry is. Only our own exact key is defended: a collision on\n * `pi2dsh/<id>` throws in registerFlow and degrades to /login-only.\n *\n * Composition order is not ours to assume: the stock 0.1.1 compositions ship\n * the authorization package without composing it, so the service may appear\n * (or bounce) at any time after this provider registers. The official\n * pattern — the one llm-pi-ai itself uses — is `ctx.inject(['authorization',\n * ...], cb)`: cordis mounts the callback when the services are present,\n * disposes everything it registered when they leave, and mounts it again if\n * they return. The scope hangs off the CALLING ctx, so a flow projected for\n * a package's provider dies with that package, and a built-in entry's flow\n * dies with the engine.\n */\nfunction maybeProjectAuthorizationFlow(ctx: Context, state: RuntimeState, providerId: string): void {\n  const shared = state.shared\n  shared.authorizationArmedIds ??= new Set()\n  if (shared.authorizationArmedIds.has(providerId)) return\n  const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => void }).inject\n  if (typeof inject !== 'function') return\n  shared.authorizationArmedIds.add(providerId)\n  inject.call(ctx, ['authorization', 'credentials'], scope => {\n    void projectAuthorizationFlow(scope, state, providerId)\n  })\n}\n\n/** The per-mount half: services are present on `scope`, register the flow and\n * this provider's sign-out mirror. Everything registered here is disposed by\n * cordis with the scope. */\nasync function projectAuthorizationFlow(scope: Context, state: RuntimeState, providerId: string): Promise<void> {\n  const shared = state.shared\n  const ctx = scope\n  const authorization = optionalService<{\n    registerFlow(flow: UnknownRecord): () => void\n  }>(ctx, 'authorization')\n  const credentials = optionalService<{\n    modifyRecord(key: unknown, mutate: (current: unknown) => Promise<unknown>): Promise<unknown>\n    readRecord(key: unknown): Promise<unknown>\n  }>(ctx, 'credentials')\n  if (authorization === undefined || credentials === undefined) return\n  try {\n    // The key helpers are 0.1.1-line exports of the credentials package;\n    // resolve them dynamically so no chunk references symbols the rc.8\n    // generation lacks. Reaching here implies ctx.authorization exists, so\n    // the peer IS the new generation — a miss still degrades to a warning.\n    const credentialsModule = await import('@deepseek-ai/dsh-credentials') as unknown as {\n      credentialKey?(scope: string, id: string): unknown\n      isCredentialKeySegment?(value: string): boolean\n    }\n    const { credentialKey, isCredentialKeySegment } = credentialsModule\n    if (credentialKey === undefined || isCredentialKeySegment === undefined) return\n    if (!isCredentialKeySegment(providerId)) {\n      logger(ctx).warn(`[pi2dsh] provider ${JSON.stringify(providerId)} cannot appear on the DSH sign-in surface (its id is outside the credential-key grammar); /login still works`)\n      return\n    }\n    const canonicalOf = (): UnknownRecord => shared.providers.get(providerId) ?? {}\n    const labelOf = (): string =>\n      ((canonicalOf().oauth as UnknownRecord | undefined)?.name as string | undefined) ?? providerId\n    const key = credentialKey('pi2dsh', providerId)\n    // registerFlow's effect is created on the calling ctx (cordis binds\n    // `this.ctx` to the caller), so the flow is withdrawn with this scope;\n    // the returned disposer would only serve early withdrawal.\n    authorization.registerFlow({\n      key,\n      label: `${labelOf()} (pi2dsh)`,\n      methods: [{ id: 'oauth', label: `Sign in to ${labelOf()}` }],\n      run: async (session: {\n        method: string\n        signal: AbortSignal\n        notify(notice: UnknownRecord): void\n        prompt(prompt: UnknownRecord): Promise<string>\n      }) => {\n        const ui: ProviderLoginUi = {\n          notify: message => { session.notify({ message: String(message) }) },\n          input: async (title, _placeholder, promptSignal) => {\n            try {\n              return await session.prompt({\n                kind: 'text',\n                message: String(title),\n                ...(promptSignal instanceof AbortSignal ? { signal: promptSignal } : {}),\n              })\n            } catch (error) {\n              // A withdrawn prompt (the browser callback won the race) is a\n              // dismissal, not a failure — same contract as ui.input.\n              if (promptSignal instanceof AbortSignal && promptSignal.aborted) return undefined\n              throw error\n            }\n          },\n          select: async (title, options, promptSignal) => {\n            try {\n              return await session.prompt({\n                kind: 'select',\n                message: String(title),\n                options: options.map(option => ({ id: String(option), label: String(option) })),\n                ...(promptSignal instanceof AbortSignal ? { signal: promptSignal } : {}),\n              })\n            } catch (error) {\n              if (promptSignal instanceof AbortSignal && promptSignal.aborted) return undefined\n              throw error\n            }\n          },\n          // A device code is exactly what AuthorizationNotice.code is for.\n          // Resolving this call means \"the user dismissed the dialog\"\n          // (oauthInteraction cancels the flow on it — the login-card contract\n          // test caught the instant-resolve variant cancelling a device-code\n          // flow the moment it started), so it settles only when the flow's\n          // own signal closes it.\n          deviceCode: (title, detail, signal) => {\n            session.notify({ message: String(title), code: String(detail) })\n            return new Promise<void>((resolve) => {\n              if (!(signal instanceof AbortSignal)) return\n              if (signal.aborted) resolve()\n              else signal.addEventListener('abort', () => resolve(), { once: true })\n            })\n          },\n        }\n        const canonical = canonicalOf()\n        if (!providerSupportsOAuth(canonical)) throw new Error(`${providerId} no longer supports OAuth login`)\n        await runProviderLogin(ctx, state, providerId, canonical, ui, session.signal)\n        await credentials.modifyRecord(key, async () => ({\n          kind: 'grant',\n          payload: { provider: providerId, managedBy: 'pi2dsh' },\n        }))\n      },\n    })\n    // The official sign-out mirror for THIS flow's key: deleting the DSH\n    // credential record removes the bridge's stored login too. Registered on\n    // the same scope, so it lives exactly as long as the flow it mirrors.\n    ;(ctx as unknown as { on(event: string, callback: (eventKey: unknown) => void): unknown }).on('credentials/record-updated', (eventKey: unknown) => {\n      void (async () => {\n        try {\n          if (String(eventKey) !== String(key)) return\n          if (await credentials.readRecord(key) !== undefined) return\n          await oauthStoreOf(state).delete(providerId)\n          // A login placeholder route exists only because of the stored\n          // credential; retire it. A package-owned transport route stays — its\n          // per-request credential resolution reports the missing login itself.\n          const canonical = shared.providers.get(providerId)\n          if (canonical !== undefined && !providerCarriesTransport(canonical)) {\n            retireSharedProviderRoute(shared, providerId)\n          }\n          logger(ctx).info(`[pi2dsh] signed out of ${providerId}: the DSH credential record was deleted, so the bridge's stored login was removed`)\n        } catch (error) {\n          logger(ctx).warn(`[pi2dsh] sign-out mirror failed: ${error instanceof Error ? error.message : String(error)}`)\n        }\n      })()\n    })\n  } catch (error) {\n    logger(ctx).warn(`[pi2dsh] could not project ${JSON.stringify(providerId)} onto the DSH sign-in surface: ${error instanceof Error ? error.message : String(error)}; /login still works`)\n  }\n}\n\nfunction registerLoginCommand(ctx: Context, state: RuntimeState): void {\n  registerCommand(ctx, state, {\n    name: 'login',\n    description: 'Log in to a Pi provider through its own OAuth flow',\n    argumentHint: '<provider>',\n    async handler(args: string, commandContext: UnknownRecord) {\n      const oauthProviders = [...state.providers.entries()]\n        .filter(([, config]) => providerSupportsOAuth(config))\n        .map(([name]) => name)\n      if (oauthProviders.length === 0) throw new Error('no registered Pi provider supports OAuth login')\n      const ui = commandContext.ui as ProviderLoginUi & {\n        select(title: unknown, options: unknown[]): Promise<string | undefined>\n      }\n      let answer = args.trim().split(/\\s+/u)[0] ?? ''\n      if (answer.length === 0) {\n        answer = oauthProviders.length === 1\n          ? oauthProviders[0] as string\n          : String(await ui.select('Log in to which provider?', oauthProviders) ?? '')\n      }\n      // The picker's answer is a LABEL by DSH's contract, but the same dialog\n      // also offers a free-text box — a user who types the row number there\n      // sends \"1\", and the row number is what a person reads off the screen\n      // anyway. Accept the name, any casing of it, or the 1-based position;\n      // anything else still fails loud with the list.\n      // Answering nothing is a cancellation, and Pi's protocol has a channel\n      // for that. Reporting it as `unknown OAuth provider \"\"` told the user\n      // their choice was wrong when they had simply not made one.\n      if (answer.length === 0) return 'Login cancelled'\n      const providerId = resolveOfferedChoice(answer, oauthProviders)\n      const config = providerId === undefined ? undefined : state.providers.get(providerId)\n      if (providerId === undefined || config === undefined || !providerSupportsOAuth(config)) {\n        throw new Error(`unknown OAuth provider ${JSON.stringify(answer)}; available: ${oauthProviders.join(', ')}`)\n      }\n      return await runProviderLogin(ctx, state, providerId, config, ui, commandContext.signal as AbortSignal | undefined)\n    },\n  })\n}\n\nfunction registerTool(ctx: Context, state: RuntimeState, tool: PiTool): void {\n  // Pi's runner stores tools in a name-keyed Map (set + refreshTools):\n  // re-registering a name replaces the previous definition. Mirror that —\n  // catalog packages (pi-fabric) re-register wrapped variants at runtime,\n  // and the reload remount re-registers every tool. The DSH-side\n  // registration STAYS on a replacement: its execute() resolves the live\n  // ledger entry, so swapping the ledger swaps the behavior. (Re-registering\n  // on the DSH side from an execution stack would attach the effect to the\n  // wrong fiber scope and hide the tool from registered agents.)\n  if (state.tools.has(tool.name)) {\n    const previous = state.tools.get(tool.name)!\n    state.tools.set(tool.name, tool)\n    if (JSON.stringify(previous.parameters ?? null) !== JSON.stringify(tool.parameters ?? null)) {\n      logger(ctx).warn(`[pi2dsh] tool ${tool.name} was re-registered with a different parameter schema; the new schema takes effect when dsh restarts (behavior is already live)`)\n    }\n    return\n  }\n  const normalized = normalizeToolSchema(tool.parameters)\n  for (const warning of normalized.warnings) logger(ctx).warn(`[pi2dsh] tool ${tool.name}: ${warning}`)\n  state.tools.set(tool.name, tool)\n  if (state.hostAnchor) {\n    // The anchor keeps the package's own Pi-side ledger (getActiveTools,\n    // re-registration and unregister semantics stay exact) but projects no\n    // DSH tool: every executable session belongs to a per-Agent instance,\n    // and a host-level twin would put duplicate names in front of the model.\n    state.toolDisposers.set(tool.name, () => {})\n    return\n  }\n  const definition: ToolDefinition = {\n    name: tool.name,\n    description: tool.description,\n    parameters: normalized.schema,\n    output: {\n      schema: {},\n      render: (_args, value) => (value as UnknownRecord).content as ContentBlock[],\n      presentationMeta: (_args, value) => jsonValue((value as UnknownRecord).details) as never,\n    },\n    isConcurrencySafe: () => tool.executionMode === 'parallel',\n    async execute(args, exec) {\n      // Live ledger resolution (see the re-registration note above).\n      const live = state.tools.get(tool.name) ?? tool\n      const agent = exec.agent as unknown as UnknownRecord | undefined\n      // A DSH surface may replace its Agent without publishing the optional\n      // agent/session-start event first (dsh-TUI /new does exactly that).\n      // Pi initializes session-owned tools such as MCP before any tool can be\n      // invoked, so the tool boundary must share the same once-per-session\n      // start gate as the slash-command boundary. Without it the first MCP\n      // call in a fresh TUI session reaches the adapter as \"not initialized\".\n      await ensurePiSessionStarted(ctx, state, agent, exec.signal)\n      const mutated = state.argMutations.get(exec as unknown as object)\n      if (mutated !== undefined) state.argMutations.delete(exec as unknown as object)\n      const effective = mutated ?? args\n      // Pi's order, unchanged: the tool's own `prepareArguments` shim first,\n      // then the argument gate its agent loop runs before EVERY execution —\n      // coerce against the schema, then check. Without it a model that emits\n      // \"3\" for a number parameter hands the tool a string (Pi hands it 3),\n      // and malformed arguments reach the tool instead of coming back to the\n      // model as the violation text it can retry against.\n      const prepared = validateToolArguments(\n        { name: live.name, parameters: live.parameters },\n        { name: live.name, arguments: live.prepareArguments?.(cloneJson(effective)) ?? effective },\n      )\n      const result = await normalizeToolResultForDsh(ctx, await runInPiRuntime(state, agent, () => live.execute(\n          String(exec.callId),\n          prepared,\n          exec.signal,\n          update => {\n            void dispatch(state, 'tool_execution_update', {\n              type: 'tool_execution_update',\n              toolCallId: String(exec.callId),\n              toolName: tool.name,\n              args: prepared,\n              partialResult: jsonValue(update),\n            }, contextFor(ctx, state, agent, exec.signal))\n              .catch(error => logger(ctx).warn(`[pi2dsh] tool_execution_update handler failed: ${String(error)}`))\n          },\n          contextFor(ctx, state, agent, exec.signal),\n        )))\n      if (result.terminate === true) exec.concludeTurn()\n      if (result.isError === true) {\n        const message = textBlocks(result.content).map(block => block.text).filter(Boolean).join('\\n')\n        throw new Error(message || `Pi tool ${tool.name} failed`)\n      }\n      return result\n    },\n  }\n  const dispose = (ctx as unknown as { tools: { register(toolDefinition: ToolDefinition): () => void } }).tools.register(definition)\n  state.toolDisposers.set(tool.name, dispose)\n  // Register the browser card at package mount, not after the first result.\n  // The package and tool name must both match the verified contract, so no\n  // unrelated tool presentation is replaced.\n  if (isKnownImageTool(state.packageName, tool.name)) {\n    state.shared.browserSurfaces?.registerImageTool(tool.name)\n  }\n}\n\n/**\n * Register ONE Pi custom tool into a child agent's scope (createAgentSession\n * customTools). Same translation as {@link registerTool}'s definition, but:\n * the registration goes through the CHILD ctx (a scoped registration that\n * unwinds with the child, invisible to the parent and siblings), and the\n * package's own Pi tool ledger is untouched — a child session's custom tools\n * belong to that session in Pi, not to the extension's registered set.\n * Partial-result updates have no Pi-side consumer on this path yet (the\n * façade projects durable events only), so the update callback is a no-op —\n * never a fake dispatch.\n */\nfunction registerChildPiTool(childCtx: Context, state: RuntimeState, tool: PiTool): void {\n  const normalized = normalizeToolSchema(tool.parameters)\n  for (const warning of normalized.warnings) logger(childCtx).warn(`[pi2dsh] subagent tool ${tool.name}: ${warning}`)\n  const definition: ToolDefinition = {\n    name: tool.name,\n    description: tool.description,\n    parameters: normalized.schema,\n    output: {\n      schema: {},\n      render: (_args, value) => (value as UnknownRecord).content as ContentBlock[],\n      presentationMeta: (_args, value) => jsonValue((value as UnknownRecord).details) as never,\n    },\n    isConcurrencySafe: () => tool.executionMode === 'parallel',\n    async execute(args, exec) {\n      const agent = exec.agent as unknown as UnknownRecord | undefined\n      // Pi's argument gate, unchanged: the tool's own prepareArguments shim,\n      // then schema coercion + check before every execution.\n      const prepared = validateToolArguments(\n        { name: tool.name, parameters: tool.parameters },\n        { name: tool.name, arguments: tool.prepareArguments?.(cloneJson(args)) ?? args },\n      )\n      const result = await normalizeToolResultForDsh(childCtx, await runInPiRuntime(state, agent, () => tool.execute(\n        String(exec.callId),\n        prepared,\n        exec.signal,\n        () => { /* no Pi-side partial-update consumer on the child path */ },\n        contextFor(childCtx, state, agent, exec.signal),\n      )))\n      if (result.terminate === true) exec.concludeTurn()\n      if (result.isError === true) {\n        const message = textBlocks(result.content).map(block => block.text).filter(Boolean).join('\\n')\n        throw new Error(message || `Pi tool ${tool.name} failed`)\n      }\n      return result\n    },\n  }\n  ;(childCtx as unknown as { tools: { register(toolDefinition: ToolDefinition): () => void } }).tools.register(definition)\n}\n\nfunction unregisterTool(state: RuntimeState, name: string): boolean {\n  const dispose = state.toolDisposers.get(name)\n  if (dispose === undefined) return false\n  dispose()\n  state.toolDisposers.delete(name)\n  state.tools.delete(name)\n  return true\n}\n\nfunction currentAgent(state: RuntimeState): UnknownRecord | undefined {\n  const scoped = state.agentScope.getStore()\n  if (scoped !== undefined) return scoped\n  if (state.activeAgents.size === 1) return state.activeAgents.values().next().value as UnknownRecord | undefined\n  return undefined\n}\n\n/** Exact-Agent ownership for scoped mounts; legacy root mounts retain their old host-session rule. */\nfunction acceptsAgent(state: RuntimeState, agent: UnknownRecord | undefined): boolean {\n  // The host anchor serves no Agent at all: every live Agent has its own\n  // instance, so anchor participation would double-run session lifecycles.\n  if (state.hostAnchor) return false\n  // A child THIS instance spawned belongs to it on the request boundary too:\n  // its per-agent thinking level rides the same agent/request waterfall. The\n  // WeakSet is instance-local, so no other package's instance claims it.\n  if (agent !== undefined && state.childAgents.has(agent)) return true\n  if (state.ownerAgent !== undefined) return agent === state.ownerAgent\n  return !isSubagentOrigin(agent)\n}\n\nfunction toolRuntime(ctx: Context, agent?: UnknownRecord): {\n  schemas(scope?: unknown): Array<{ name: string; description?: string; parameters?: unknown }>\n  restrict?(filter: { allow?: string[], deny?: string[] }): () => void\n} {\n  const scoped = agent?.ctx as { tools?: ReturnType<typeof toolRuntime> } | undefined\n  return scoped?.tools ?? (ctx as unknown as { tools: ReturnType<typeof toolRuntime> }).tools\n}\n\n/**\n * The system-prompt text a package's ACTIVE tools contribute.\n *\n * Pi renders `promptSnippet` into its \"Available tools\" list and\n * `promptGuidelines` into its \"Guidelines\" bullets. DSH assembles its prompt\n * from ordered sections, so both arrive as one section in DSH's tool-guidance\n * band, headed the way Pi heads them.\n * @param ctx - context used to read which tools are active.\n * @param state - runtime state holding the registered Pi tools.\n * @returns the section text, empty when no active Pi tool contributes any.\n */\nfunction piToolPromptContribution(ctx: Context, state: RuntimeState): string {\n  const active = new Set(getActiveTools(ctx, state))\n  const snippets: string[] = []\n  const guidelines: string[] = []\n  for (const [name, tool] of state.tools) {\n    if (!active.has(name)) continue\n    const snippet = tool.promptSnippet\n    if (typeof snippet === 'string' && snippet.trim().length > 0) snippets.push(`- ${snippet.trim()}`)\n    const bullets = tool.promptGuidelines\n    if (!Array.isArray(bullets)) continue\n    for (const bullet of bullets) {\n      if (typeof bullet === 'string' && bullet.trim().length > 0) guidelines.push(`- ${bullet.trim()}`)\n    }\n  }\n  const parts: string[] = []\n  if (snippets.length > 0) parts.push(`Available tools:\\n${snippets.join('\\n')}`)\n  if (guidelines.length > 0) parts.push(`Guidelines:\\n${guidelines.join('\\n')}`)\n  return parts.join('\\n\\n')\n}\n\nfunction getActiveTools(ctx: Context, state: RuntimeState): string[] {\n  const agent = currentAgent(state)\n  return toolRuntime(ctx, agent).schemas(agent).map(tool => tool.name)\n}\n\n/**\n * Pi's `setActiveTools`, on DSH's restriction seam.\n *\n * Pi walks the requested names and keeps the ones its registry knows —\n * **unknown names are silently skipped**. DSH's `restrict` instead FAILS the\n * whole call on a name it cannot restrict (unknown, scope-local, or a\n * reserved transport name), so passing Pi's list through verbatim turned a\n * routine Pi call into a hard error over one stale name.\n *\n * So the list is narrowed to what DSH says is restrictable before restricting.\n * The one case that cannot be both: a tool that is VISIBLE but not\n * restrictable (a scope's own registration, `run_code` outside native mode)\n * cannot be switched off at all. Silence there would leave a tool running that\n * the package believes it disabled, so it is reported once — the package's\n * call still takes effect for everything else.\n * @param ctx - context used to reach the tool runtime.\n * @param state - runtime state holding the per-agent restriction disposers.\n * @param names - the tool names the package wants active.\n */\nfunction setActiveTools(ctx: Context, state: RuntimeState, names: string[]): void {\n  const unique = [...new Set(names)]\n  const agent = currentAgent(state)\n  state.pendingActiveTools = unique\n  if (agent === undefined || typeof agent !== 'object' || agent === null) return\n  const scopedTools = agent.ctx === undefined ? undefined : toolRuntime(ctx, agent)\n  if (scopedTools === undefined || typeof scopedTools.restrict !== 'function') {\n    // No agent-scoped tool runtime (e.g. a bare test agent): remember the\n    // intent and apply it when a scoped agent starts. Restricting the global\n    // registry here would mask every agent, which DSH rightly rejects.\n    logger(ctx).warn('[pi2dsh] setActiveTools deferred: the current agent exposes no scoped tools.restrict()')\n    return\n  }\n  const restrictable = restrictableToolNames(scopedTools, agent)\n  const allow = restrictable === undefined ? unique : unique.filter(name => restrictable.has(name))\n  if (restrictable !== undefined) {\n    const visible = new Set(scopedTools.schemas(agent as never).map(schema => schema.name))\n    const unswitchable = [...visible].filter(name => !restrictable.has(name) && !unique.includes(name))\n    if (unswitchable.length > 0) {\n      logger(ctx).warn(\n        `[pi2dsh] setActiveTools could not deactivate ${unswitchable.map(name => JSON.stringify(name)).join(', ')}:`\n        + ' DSH does not allow restricting a scope-registered or reserved tool, so it stays available to the model',\n      )\n    }\n  }\n  state.toolRestrictions.get(agent)?.()\n  // An empty allow-list is refused by DSH (an empty filter fails), and it is\n  // also not what Pi means: Pi's empty list deactivates everything, which on\n  // DSH is spelled as denying every restrictable name.\n  state.toolRestrictions.set(agent, allow.length === 0\n    ? scopedTools.restrict({ deny: [...(restrictable ?? new Set<string>())] })\n    : scopedTools.restrict({ allow }))\n}\n\n/**\n * The tool names DSH will accept in a restriction for this scope.\n * @param tools - the agent-scoped tool runtime.\n * @param agent - the scope key.\n * @returns the restrictable names, or undefined when this runtime exposes no view.\n */\nfunction restrictableToolNames(tools: UnknownRecord, agent: unknown): ReadonlySet<string> | undefined {\n  const view = tools.view\n  if (typeof view !== 'function') return undefined\n  try {\n    const names = (view.call(tools, agent) as { restrictableNames?: unknown } | undefined)?.restrictableNames\n    return names instanceof Set ? names as ReadonlySet<string> : undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction deliverAgentMessage(agent: DshAgent, message: unknown, mode: 'inject' | 'steer' | 'followup'): void {\n  const deliver = agent[mode]\n  if (typeof deliver !== 'function') throw new Error(`pi2dsh: active DSH agent has no ${mode}() delivery method`)\n  deliver.call(agent, message)\n}\n\n/**\n * Pi declares sendMessage / sendUserMessage as returning void, so packages call\n * them without awaiting. A delivery that fails — typically a completion\n * notice sent while the host is already tearing the agent down — would\n * otherwise surface as an unhandled rejection, which the DSH CLI reports as a\n * fatal failure and a non-zero exit. The failure is reported once, as a\n * warning naming the package; a caller that does await still receives it.\n */\nfunction reportUnawaitedDelivery(ctx: Context, state: RuntimeState, api: string, delivery: Promise<void>): Promise<void> {\n  delivery.catch((error: unknown) => {\n    logger(ctx).warn(`[pi2dsh] ${state.packageName}: ${api} was not delivered: ${error instanceof Error ? error.message : String(error)}`)\n  })\n  return delivery\n}\n\n/**\n * Pi's `sendMessage` / `sendUserMessage`, on DSH.\n *\n * Two things this has to get right that a plain `deliverAgentMessage` does not:\n *\n *  - **Durability.** Pi's no-turn `sendMessage` appends to the session and\n *    emits its message events before it returns: on return the message IS in\n *    the conversation. DSH's inject only queues it in the agent's inbox, where\n *    it becomes a `user/message` when the next step claims it — so a turn\n *    cancelled in between dropped it, and a package that had already reported\n *    success was wrong. The no-turn mode now appends to the durable log\n *    itself, which is what Pi's contract promises.\n *  - **Which session.** Inside a `withSession` callback the context is bound to\n *    the REPLACEMENT session, but the live agent is still the one that started\n *    the operation — so routing through the agent wrote into the OLD session.\n *    An override session is written to directly.\n * @param ctx - context used for content conversion.\n * @param state - runtime state (message source, active agent).\n * @param content - the Pi content to deliver.\n * @param mode - inject (no turn), steer, or followup.\n * @param sessionOverride - the replacement session, inside a withSession callback.\n * @param customType - Pi's role:\"custom\" marker, when the caller sent one.\n */\nasync function sendPiMessage(\n  ctx: Context,\n  state: RuntimeState,\n  content: unknown,\n  mode: 'inject' | 'steer' | 'followup',\n  sessionOverride?: UnknownRecord,\n  customType?: string,\n): Promise<void> {\n  const blocks = await piToDshContent(ctx, typeof content === 'string' ? [{ type: 'text', text: content }] : content)\n  const message = createUserMessage({\n    content: blocks,\n    source: {\n      kind: 'plugin', plugin: state.messageSource,\n      ...(customType === undefined ? { form: 'relay' as const } : { piCustomType: customType }),\n    },\n  })\n  // A replacement session has no live agent of its own; the durable log IS the\n  // conversation, so every mode writes there.\n  if (sessionOverride !== undefined) {\n    appendUserMessage(sessionOverride, message as unknown as UnknownRecord)\n    return\n  }\n  if (mode === 'inject') {\n    const session = agentSession(currentAgent(state))\n    if (session === undefined) {\n      throw new Error('pi2dsh: sendMessage requires one active DSH agent with a durable session')\n    }\n    appendUserMessage(session as unknown as UnknownRecord, message as unknown as UnknownRecord)\n    return\n  }\n  const agent = requireAgent(state, 'sendUserMessage')\n  deliverAgentMessage(agent, message, mode)\n}\n\n/**\n * Pi's delivery options → this bridge's mode. No options at all means \"into\n * the conversation, no turn\", which is Pi's own default.\n * @param options - the caller's delivery options.\n */\nfunction deliveryMode(options: UnknownRecord): 'inject' | 'steer' | 'followup' {\n  if (options.deliverAs === 'steer') return 'steer'\n  if (options.deliverAs === 'followUp' || options.deliverAs === 'nextTurn' || options.triggerTurn === true) {\n    return 'followup'\n  }\n  return 'inject'\n}\n\n/**\n * Append one plugin-sourced user message to a session's durable log, which is\n * what makes it part of the conversation before the call returns.\n * @param session - the live DSH session to append to.\n * @param message - the message, already in DSH shape.\n */\nfunction appendUserMessage(session: UnknownRecord, message: UnknownRecord): void {\n  const append = session.append\n  if (typeof append !== 'function') {\n    throw new Error('pi2dsh: this session cannot be appended to, so the message could not be delivered durably')\n  }\n  // `user/message` is surface-eligible, so DSH requires the marker that says\n  // where it lands on the model-visible surface — the same `append` the agent\n  // loop uses when it enters a claimed prompt.\n  append.call(session, 'user/message', message, { surfaceOp: 'append' })\n}\n\nfunction combineExecSignal(options: PiExecOptions): {\n  signal: AbortSignal\n  killed(): boolean\n  cleanup(): void\n} {\n  const controller = new AbortController()\n  let killed = false\n  let timer: ReturnType<typeof setTimeout> | undefined\n  const abort = (reason: unknown): void => {\n    if (controller.signal.aborted) return\n    killed = true\n    controller.abort(reason)\n  }\n  const onAbort = (): void => abort(options.signal?.reason ?? new Error('Pi exec aborted'))\n  if (options.signal?.aborted) onAbort()\n  else options.signal?.addEventListener('abort', onAbort, { once: true })\n  if (typeof options.timeout === 'number' && Number.isFinite(options.timeout) && options.timeout > 0) {\n    timer = setTimeout(() => abort(new Error(`Pi exec timed out after ${options.timeout}ms`)), options.timeout)\n  }\n  return {\n    signal: controller.signal,\n    killed: () => killed,\n    cleanup() {\n      if (timer !== undefined) clearTimeout(timer)\n      options.signal?.removeEventListener('abort', onAbort)\n    },\n  }\n}\n\nasync function executePiCommand(\n  service: DshSubprocessService,\n  cwd: string,\n  command: string,\n  args: string[],\n  options: PiExecOptions,\n  environment?: Record<string, string>,\n): Promise<{ stdout: string; stderr: string; code: number; killed: boolean }> {\n  const operation = combineExecSignal(options)\n  try {\n    if (typeof command !== 'string' || command.length === 0) throw new TypeError('Pi exec command must be a non-empty string')\n    if (!Array.isArray(args) || args.some(value => typeof value !== 'string')) throw new TypeError('Pi exec args must be strings')\n    const executable = await service.resolveExecutable(command, environment, operation.signal)\n    const collect = { maxBytes: 64 * 1024 * 1024 }\n    const handle = service.spawn({\n      argv: [executable, ...args],\n      cwd: options.cwd ?? cwd,\n      ...(environment === undefined ? {} : { env: environment }),\n      stdio: { stdin: 'ignore', stdout: collect, stderr: collect },\n      graceMs: 5_000,\n      signal: operation.signal,\n    })\n    const outcome = await handle.done\n    const stdout = handle.collected.stdout?.readFrom(0)\n    const stderr = handle.collected.stderr?.readFrom(0)\n    const truncation = [stdout?.lossy ? 'stdout' : '', stderr?.lossy ? 'stderr' : ''].filter(Boolean)\n    return {\n      stdout: stdout?.text ?? '',\n      stderr: `${stderr?.text ?? ''}${truncation.length === 0 ? '' : `\\n[pi2dsh: ${truncation.join(' and ')} exceeded the 64 MiB compatibility limit]`}`,\n      code: outcome.exitCode ?? 0,\n      killed: operation.killed(),\n    }\n  } catch (error) {\n    return {\n      stdout: '',\n      stderr: error instanceof Error ? error.message : String(error),\n      code: operation.signal.aborted ? 0 : 1,\n      killed: operation.killed(),\n    }\n  } finally {\n    operation.cleanup()\n  }\n}\n\nfunction normalizedPiCommandName(piName: string): string {\n  // DSH command names are /^[a-z][a-z0-9_-]*$/; Pi allows richer names like\n  // \"btw:tangent\". Normalize instead of refusing the whole package.\n  const normalized = piName.toLowerCase().replace(/[^a-z0-9_-]+/gu, '-').replace(/^[^a-z]+/u, '')\n  return normalized.length > 0 ? normalized : 'pi-command'\n}\n\nfunction dshCommandName(ctx: Context, state: RuntimeState, piName: string): string {\n  const validName = normalizedPiCommandName(piName)\n  const name = commandNameForTerminal(validName, state.tuiSurfaces?.nativeCommands)\n  if (name !== piName) {\n    const reason = name === `pi-${validName}`\n      ? `because the active terminal reserves /${validName} for its native command (host commands win on collisions)`\n      : 'to satisfy DSH command naming'\n    logger(ctx).warn(`[pi2dsh] Pi command /${piName} registered as /${name} ${reason}`)\n  }\n  return name\n}\n\nfunction registerCommand(ctx: Context, state: RuntimeState, command: PiCommand): void {\n  // Pi's registerCommand never throws. Within one extension it is Map.set —\n  // a same-name registration replaces the earlier one (loader.ts\n  // extension.commands.set). Colliding registrations from DIFFERENT sources\n  // both survive in Pi under numbered invocation names (runner.ts\n  // resolveRegisteredCommands: /name:1, /name:2). On the shared DSH command\n  // namespace the earlier registration's name cannot be rewritten from here,\n  // so the mapped semantics are: this package's re-registration replaces its\n  // own command and keeps the base name; a collision with another package's\n  // command registers under Pi's numbered scheme (/name-2, /name-3 — DSH\n  // command naming takes '-' where Pi takes ':') while the first keeps the\n  // bare name.\n  if (state.commands.has(command.name)) {\n    // Same-name re-registration (Pi's Map.set semantics, and the reload\n    // remount path): the DSH-side registration STAYS — its handler resolves\n    // the live command from the ledger below, so replacing the ledger entry\n    // is the complete replacement. Re-registering on the DSH side from a\n    // command execution stack would attach the effect to the wrong fiber\n    // scope and make the command invisible to registered agents.\n    state.commands.set(command.name, command)\n    return\n  }\n  state.commands.set(command.name, command)\n  if (state.hostAnchor) {\n    // Anchor ledger only: the command palette entries belong to the\n    // per-Agent instances; a host-level twin would collide into the\n    // numbered-alias scheme (/name-2) against its own package.\n    return\n  }\n  const commands = (ctx as unknown as { get(name: string): unknown }).get('commands') as {\n    register(definition: UnknownRecord): () => void\n  } | undefined\n  if (commands === undefined) {\n    logger(ctx).warn(`[pi2dsh] command /${command.name} was not registered because this DSH composition has no ctx.commands`)\n    return\n  }\n  const baseName = dshCommandName(ctx, state, command.name)\n  const existingOwner = state.dshCommandOwners.get(baseName)\n  // Prefer a Pi command that NATURALLY owns this name over an earlier command\n  // the host renamed into it. pi-mcp-adapter deliberately declares both\n  // /mcp and /pi-mcp; dsh-TUI reserves /mcp, so the first declaration is\n  // temporarily projected onto /pi-mcp. When the explicit /pi-mcp arrives it\n  // should replace that temporary projection, not leak a meaningless\n  // /pi-mcp-2. The rule is generic: normalization collisions where both Pi\n  // names naturally map to the same DSH name still use numbered aliases.\n  if (existingOwner !== undefined\n    && existingOwner !== command.name\n    && normalizedPiCommandName(command.name) === baseName\n    && normalizedPiCommandName(existingOwner) !== baseName) {\n    state.commandDisposers.get(existingOwner)?.()\n    state.commandDisposers.delete(existingOwner)\n    state.dshCommandOwners.delete(baseName)\n  }\n  const definitionFor = (dshName: string): UnknownRecord => ({\n    name: dshName,\n    description: command.description || `Migrated Pi command /${command.name}`,\n    // EVERY Pi command takes a free-form argument string by contract\n    // (`handler(args, ctx)`), whether or not the package declared a hint. DSH\n    // surfaces only pass arguments to commands that declare an `input`\n    // descriptor — without one, \"/name some args\" is sent as a chat message\n    // instead of invoking the command (ui-commands' matchEnter: an argued\n    // line for an input-less command is not claimed). So the descriptor is\n    // always declared, using the package's hint when it has one.\n    input: { hint: command.argumentHint ?? 'arguments (optional)' },\n    async handler(invocation: UnknownRecord) {\n      const agent = invocation.agent as UnknownRecord\n      const commandContext = contextFor(ctx, state, agent, invocation.signal as AbortSignal, true)\n      // Resolve the LIVE command from the ledger: a same-name re-registration\n      // (including a reload remount) replaces the ledger entry while this one\n      // DSH-side registration keeps serving the name.\n      const live = state.commands.get(command.name) ?? command\n      await runInPiRuntime(state, agent, async () => {\n        await ensurePiSessionStarted(ctx, state, agent, invocation.signal as AbortSignal | undefined)\n        await refreshNativeSkillCommands(ctx, state, agent, invocation.signal as AbortSignal | undefined)\n        await live.handler(String(invocation.rawInput ?? '').trimStart(), commandContext)\n      })\n      const notices = commandContext.__notices as string[]\n      return { kind: 'success', ...(notices.length > 0 ? { text: notices.join('\\n') } : {}) }\n    },\n  })\n  let lastError: unknown\n  for (let ordinal = 1; ordinal <= 9; ordinal++) {\n    const dshName = ordinal === 1 ? baseName : `${baseName}-${ordinal}`\n    try {\n      state.commandDisposers.set(command.name, commands.register(definitionFor(dshName)))\n      state.dshCommandOwners.set(dshName, command.name)\n      if (ordinal > 1) {\n        logger(ctx).warn(`[pi2dsh] command /${command.name} collides with an earlier registration in this host; mounted as /${dshName} (Pi numbers colliding commands the same way)`)\n      }\n      return\n    } catch (error) {\n      lastError = error\n    }\n  }\n  logger(ctx).warn(`[pi2dsh] command /${command.name} was not registered: ${lastError instanceof Error ? lastError.message : String(lastError)}`)\n}\n\n/**\n * DSH's own session title service, when the profile mounts it.\n *\n * Pi's \"session name\" and DSH's \"session title\" are the same fact under two\n * names, and DSH's is the one every DSH surface displays. This bridge used to\n * keep the name only in its own sidecar, so a package could rename the session\n * and nothing the user looks at ever changed — while `getSessionName()` read\n * back a name DSH had never adopted, and DSH's own generated titles were\n * invisible to packages entirely.\n */\ninterface DshSessionTitleService {\n  get(session: unknown): { title?: unknown } | undefined\n  rename(session: unknown, title: string): unknown\n}\n\n/**\n * The session's current name: DSH's title when a title service is mounted,\n * this bridge's sidecar otherwise (and as the fallback for a session named\n * before the service was there).\n * @param ctx - the cordis context to resolve the optional service from.\n * @param state - runtime state holding the sidecar.\n * @param session - the live DSH session.\n */\nfunction sessionNameOf(ctx: Context, state: RuntimeState, session: { id: string }): string | undefined {\n  const titles = optionalService<DshSessionTitleService>(ctx, 'sessionTitle')\n  const title = titles?.get(session)?.title\n  return typeof title === 'string' && title.length > 0 ? title : state.bridge.getName(session.id)\n}\n\n/**\n * Whether a human can actually answer a question right now.\n *\n * Two facts decide it, and the old check (`the service is mounted`) saw\n * neither: a headless composition mounts the service and registers NO\n * provider, and a delegated child agent has no human answerer at all — both\n * make every `ctx.ui.select/confirm/input` throw for a package that was told\n * `hasUI: true` and skipped its non-interactive path.\n *\n * The provider is a private field, but its existence is publicly observable:\n * DSH allows exactly one provider per context and refuses a second with\n * `DUPLICATE_PROVIDER`. So registering a probe answers the question — a\n * refusal means a real provider is there, and an acceptance means there was\n * none, which the immediate disposal restores.\n * @param userQuestions - the mounted question service, if any.\n * @param agent - the agent whose turn this context belongs to.\n */\nfunction humanAnswererAvailable(\n  userQuestions: unknown,\n  agent: UnknownRecord | undefined,\n  shared?: { browserSurfaces?: { lastClientContactMs?: number } },\n): boolean {\n  if (userQuestions === undefined) return false\n  // A child agent is owned by another agent; DSH refuses its questions with\n  // DELEGATED_CALLER however the composition is wired.\n  if (isSubagentOrigin(agent)) return false\n  const service = userQuestions as { registerProvider?(provider: unknown): () => void }\n  if (typeof service.registerProvider !== 'function') {\n    // 0.1.2 line: the provider slot became agent-scoped `user-questions/request`\n    // waterfall answerers (relayed per connected client, or registered by an\n    // ACP/TUI surface). Presence is publicly observable: Lifecycle.dispatch\n    // (a typed cordis member) lists the listeners an emit would reach —\n    // non-empty means someone would answer. The browser-poll stamp stays as\n    // the OR for a client whose relay registers lazily; engine-only web has\n    // neither and stays false, matching the headless ruling.\n    const events = (service as { ctx?: { events?: { dispatch?(type: string, args: unknown[]): unknown[] } } }).ctx?.events\n    if (typeof events?.dispatch === 'function') {\n      try {\n        // dispatch's second argument BEGINS with the event name (an optional\n        // thisArg may precede it); the first argument is only a debug label.\n        if (events.dispatch('pi2dsh:hasui-probe', ['user-questions/request']).length > 0) return true\n      } catch {\n        // An introspection failure must not turn into a hasUI answer.\n      }\n    }\n    const last = shared?.browserSurfaces?.lastClientContactMs\n    return typeof last === 'number' && Date.now() - last < 15_000\n  }\n  let dispose: (() => void) | undefined\n  try {\n    dispose = service.registerProvider({ ask: async () => { throw new Error('pi2dsh probe provider') } })\n  } catch {\n    // Refused: a real provider holds the slot.\n    return true\n  }\n  dispose?.()\n  return false\n}\n\nfunction requireSession(state: RuntimeState, operation: string): { id: string; events: unknown } {\n  const agent = currentAgent(state)\n  const session = agentSession(agent)\n  if (session === undefined) {\n    throw new Error(`pi2dsh: ${operation} requires one active DSH agent with a durable session`)\n  }\n  return session\n}\n\nfunction releaseSharedProviderRoute(state: RuntimeState, name: string): void {\n  if (!state.ownedProviderRoutes.delete(name)) return\n  const owners = state.shared.providerRouteOwners.get(name)\n  owners?.delete(state)\n  if (owners !== undefined && owners.size > 0) return\n  state.shared.providerRouteOwners.delete(name)\n  const route = state.shared.providerRouteDisposers.get(name)\n  state.shared.providerRouteDisposers.delete(name)\n  route?.()\n}\n\nfunction registerSharedProviderRoute(\n  ctx: Context,\n  state: RuntimeState,\n  name: string,\n  value: UnknownRecord,\n): PiRouteHandle | undefined {\n  const shared = state.shared\n  const existing = shared.providerRouteDisposers.get(name)\n  if (existing !== undefined) {\n    let owners = shared.providerRouteOwners.get(name)\n    if (owners === undefined) {\n      owners = new Set()\n      shared.providerRouteOwners.set(name, owners)\n    }\n    owners.add(state)\n    state.ownedProviderRoutes.add(name)\n    return existing\n  }\n\n  // The canonical composed config is maintained by recomposeSharedProvider;\n  // the fallback only covers host paths (stored-login placeholder routes)\n  // that reach here before any composition happened for this id.\n  const canonical = shared.providers.get(name) ?? value\n  if (!shared.providers.has(name)) shared.providers.set(name, canonical)\n  const route = registerPiProviderRoute({\n    llm: llmOf(ctx) as never,\n    ctx: ctx as never,\n    providerId: name,\n    provider: canonical,\n    host: {\n      resolveAuth: async () => resolvePiProviderAuth({\n        providerId: name,\n        providerConfig: canonical,\n        store: oauthStoreOf(state),\n      }) as Promise<{ auth?: UnknownRecord } | undefined>,\n      ensureModel: async () => { await discoverProviderModels(ctx, state, name, canonical) },\n      warn: message => logger(ctx).warn(message),\n      beforeProviderRequest: (payload, request) => dispatchHostProviderRequest(\n        ctx,\n        shared,\n        state,\n        payload,\n        request,\n      ),\n      resolveAttachments: () => optionalService<DshAttachmentsLike>(ctx, 'attachments'),\n    },\n  })\n  if (route === undefined) return undefined\n  shared.providerRouteDisposers.set(name, route)\n  shared.providerRouteOwners.set(name, new Set([state]))\n  state.ownedProviderRoutes.add(name)\n  return route\n}\n\nasync function runPiPrintRequest(ctx: Context, state: RuntimeState, parent: UnknownRecord | undefined, request: PiPrintRequest, signal: AbortSignal): Promise<{ stdout: string; code: number }> {\n  if (parent === undefined || state.subagentSessionFactory === undefined) throw new Error('pi2dsh CLI: native print work requires an active DSH agent')\n  const catalog = state.shared.childExtensions\n  const requestedPaths: string[] = []\n  for (const requested of request.extensions) {\n    let matched: string | undefined\n    for (const path of catalog?.packageByEntryPath.keys() ?? []) {\n      if (await realpath(path).catch(() => path) === requested) { matched = path; break }\n    }\n    if (matched === undefined) throw new Error(`pi2dsh CLI: extension ${requested} is not installed in this DSH profile`)\n    requestedPaths.push(matched)\n  }\n  const paths = [...new Set([...(request.noExtensions ? [] : catalog?.packageByEntryPath.keys() ?? []), ...requestedPaths])]\n  let model: UnknownRecord | undefined\n  if (request.model !== undefined) {\n    model = state.modelCatalog?.all().find(entry => `${entry.provider}/${entry.id}` === request.model\n      || (entry.id === request.model && (request.provider === undefined || entry.provider === request.provider)))\n    if (model === undefined) throw new Error(`pi2dsh CLI: model ${request.model} is unavailable in the DSH model directory`)\n  } else if (request.provider !== undefined) {\n    const inherited = currentPiModel(state, parent)\n    if (inherited?.provider !== request.provider) throw new Error('pi2dsh CLI: --provider requires an explicit --model for a different route')\n    model = inherited\n  }\n  const created = await runInPiRuntime(state, parent, () => state.subagentSessionFactory!({\n    cwd: request.cwd,\n    signal,\n    ...(model === undefined ? {} : { model }),\n    ...(request.thinking === undefined ? {} : { thinkingLevel: request.thinking }),\n    ...(request.tools === undefined ? {} : { tools: request.tools }),\n    ...(request.noSession ? { sessionManager: { getSessionFile: () => undefined } } : {}),\n    label: 'Background task',\n    resourceLoader: {\n      getExtensions: () => ({ extensions: paths.map(path => ({ path })), errors: [] }),\n      getSystemPrompt: () => request.systemPrompt,\n      getAppendSystemPrompt: () => request.appendSystemPrompt === undefined ? [] : [request.appendSystemPrompt],\n    },\n  }))\n  if (request.noSession) capabilityLedgerOf(ctx, state).reportHostDecision({\n    capability: 'pi print --no-session',\n    reason: 'the print worker has no Pi session file; DSH retains its native child audit log.',\n    guidance: 'Native retention remains a DSH host policy.',\n    packageName: state.packageName,\n  })\n  const child = created.session as {\n    prompt(text: string): Promise<void>; abort(): void; dispose(): Promise<void>\n    messages: UnknownRecord[]; sessionManager?: { getSessionId(): string }\n    bindExtensions(options: { onError(error: unknown): void }): Promise<void>\n  }\n  let rejectCancellation!: (reason: unknown) => void\n  const cancellation = new Promise<never>((_resolve, reject) => { rejectCancellation = reject })\n  void cancellation.catch(() => {})\n  const abort = () => {\n    child.abort()\n    rejectCancellation(signal.reason ?? new Error('Pi print worker cancelled'))\n  }\n  signal.addEventListener('abort', abort, { once: true })\n  try {\n    const failures: unknown[] = []\n    await child.bindExtensions({ onError: error => { failures.push(error) } })\n    if (failures.length > 0) throw new Error(`pi2dsh CLI: child extension mount failed: ${JSON.stringify(failures)}`)\n    signal.throwIfAborted()\n    await Promise.race([child.prompt(request.prompt), cancellation])\n    signal.throwIfAborted()\n    const session = optionalService<DshSessionsService>(ctx, 'sessions')?.get(child.sessionManager?.getSessionId() ?? '')\n    const end = readSessionEvents(session).findLast(event => event.type === 'turn/end')\n    if ((end?.data as { reason?: { kind?: string } } | undefined)?.reason?.kind !== 'completed') {\n      throw new Error(`pi2dsh CLI: native child did not complete: ${JSON.stringify(end?.data ?? {})}`)\n    }\n    const last = child.messages.findLast(message => message.role === 'assistant')\n    return { code: 0, stdout: textBlocks(last?.content).map(block => block.text).join('\\n') }\n  } finally {\n    signal.removeEventListener('abort', abort)\n    if (signal.aborted) child.abort()\n    await child.dispose()\n  }\n}\n\n/**\n * The ONE provider registration path. Pi exposes it twice — `pi.registerProvider`\n * and `ctx.modelRegistry.registerProvider` (model-registry.ts) — over the same\n * runtime, so both surfaces land here. A string first argument is Pi's legacy\n * (name, config) form; an object is a pi-ai native Provider. Pi keeps the two in\n * separate ledgers that replace each other per id, which is what\n * getRegisteredProviderConfig / getRegisteredNativeProvider read back.\n */\nfunction registerPiProvider(ctx: Context, state: RuntimeState, providerOrName: unknown, config?: UnknownRecord): void {\n  // pi-ai createProvider() objects are keyed by id in Pi's registry\n  // (name is the display name); extension-generation calls pass the key\n  // explicitly as the first argument.\n  const name = typeof providerOrName === 'string'\n    ? providerOrName\n    : String((providerOrName as UnknownRecord | undefined)?.id\n      ?? (providerOrName as UnknownRecord | undefined)?.name ?? 'unnamed')\n  const value = typeof providerOrName === 'string' ? config ?? {} : providerOrName as UnknownRecord\n  state.providers.set(name, value)\n  if (typeof providerOrName === 'string') state.nativeProviders.delete(name)\n  else state.nativeProviders.add(name)\n  // Pi's layered ledger: this registration merges into the package's slot\n  // (defined fields over the previous registration), the canonical is\n  // recomposed as builtin base + package overlays in load order, and a\n  // changed shape retires the existing route so it is rebuilt from the\n  // new canonical — partial overlays keep the builtin OAuth base instead\n  // of discarding it, later packages override earlier ones, and an\n  // idempotent re-registration from another agent's instance changes\n  // nothing (same fingerprint keeps the existing canonical and route).\n  recordPackageProviderRegistration(state.shared, state.packageName, name, value)\n  if (recomposeSharedProvider(state.shared, name)) {\n    retireSharedProviderRoute(state.shared, name)\n  }\n  const canonical = state.shared.providers.get(name) ?? value\n  if (providerSupportsOAuth(canonical)) {\n    // Pi hosts expose /login <provider> for oauth-capable providers; the\n    // package's own login flow runs, credentials land in auth.json.\n    ensureLoginCommand(ctx, state)\n    // 0.1.1-line hosts additionally show it on their native sign-in\n    // surface through the official authorization seam.\n    maybeProjectAuthorizationFlow(ctx, state, name)\n    logger(ctx).info(`[pi2dsh] Pi provider ${JSON.stringify(name)} supports OAuth — log in with /login ${name}`)\n  }\n  // A provider carrying its own transport becomes a REAL DSH llm route:\n  // the loop and child agents route to it natively, with credentials\n  // resolved through Pi's own chain per request.\n  const routeDisposer = registerSharedProviderRoute(ctx, state, name, canonical)\n  if (routeDisposer !== undefined) {\n    void state.modelCatalog?.refresh()\n    // Only the transport-carrying path is registered by the time this\n    // returns. The catalog-only path mounts DSH's official adapter\n    // asynchronously and reports its OWN outcome, so announcing success\n    // here claimed a route that could still fail a moment later — which is\n    // exactly what a fake credential produced: \"registered as a native DSH\n    // llm route\" immediately followed by \"could not be served\".\n    if (providerCarriesTransport(canonical)) {\n      logger(ctx).info(`[pi2dsh] Pi provider ${JSON.stringify(name)} registered as a native DSH llm route`)\n    }\n  } else if (!providerSupportsOAuth(canonical)) {\n    logger(ctx).info(`[pi2dsh] recorded Pi provider ${JSON.stringify(name)}; model calls stay on DSH llm adapters`)\n  }\n  // Pi hosts refresh a registered provider's dynamic model catalog\n  // (fetchModels against its gateway); best-effort and non-blocking.\n  void discoverProviderModels(ctx, state, name, canonical)\n}\n\nfunction unregisterPiProvider(ctx: Context, state: RuntimeState, name: string): void {\n  state.providers.delete(name)\n  state.nativeProviders.delete(name)\n  releaseSharedProviderRoute(state, name)\n  // Pi's unregisterProvider deletes the extension layer and recomposes so\n  // the builtin base is restored. Adapted to the slotted ledger: this\n  // package's slot is removed (other packages' overlays survive — in Pi\n  // every unregister nukes the whole extension entry, but that contract\n  // exists only inside one short-lived session runtime; on a long-lived\n  // host it would let one package erase another's registration).\n  const slots = state.shared.providerPackages?.get(name)\n  if (slots?.delete(state.packageName) === true && recomposeSharedProvider(state.shared, name)) {\n    retireSharedProviderRoute(state.shared, name)\n    // Pi's recompose updates the directory entry in place; our route is an\n    // explicit registration, so the restored composition (builtin base or\n    // the remaining packages' overlays) must be re-published.\n    const restored = state.shared.providers.get(name)\n    if (restored !== undefined) registerSharedProviderRoute(ctx, state, name, restored)\n  }\n}\n\nfunction createPiApi(ctx: Context, state: RuntimeState): UnknownRecord {\n  return {\n    on(event: string, handler: PiHandler) {\n      const list = state.handlers.get(event) ?? []\n      list.push(handler)\n      state.handlers.set(event, list)\n    },\n    registerTool: (tool: PiTool) => registerTool(ctx, state, tool),\n    unregisterTool: (name: string) => unregisterTool(state, name),\n    registerCommand(name: string, options: UnknownRecord) {\n      registerCommand(ctx, state, {\n        name,\n        description: typeof options.description === 'string' ? options.description : `Migrated Pi command /${name}`,\n        ...(typeof options.argumentHint === 'string' ? { argumentHint: options.argumentHint } : {}),\n        handler: options.handler as PiCommand['handler'],\n      })\n    },\n    // Registered and introspectable; DSH surfaces have no terminal key\n    // bindings, so handlers never fire — the same as Pi's non-TUI modes.\n    registerShortcut(shortcut: string, options: UnknownRecord) {\n      state.shortcuts.set(shortcut, options)\n    },\n    registerFlag(name: string, options: UnknownRecord) {\n      state.flags.set(name, options.default as boolean | string | undefined)\n      logger(ctx).warn(`[pi2dsh] Pi flag --${name} uses its default only; DSH CLI registration is unsupported`)\n    },\n    getFlag: (name: string) => state.flags.get(name),\n    registerProvider: (providerOrName: unknown, config?: UnknownRecord) => registerPiProvider(ctx, state, providerOrName, config),\n    unregisterProvider: (name: string) => unregisterPiProvider(ctx, state, name),\n    // Renderer registrations are accepted verbatim; DSH owns presentation, so\n    // they are never invoked — matching Pi's own non-TUI surfaces.\n    registerMessageRenderer(customType: string, renderer: unknown) {\n      state.messageRenderers.set(customType, renderer)\n    },\n    registerEntryRenderer(customType: string, renderer: unknown) {\n      state.entryRenderers.set(customType, renderer)\n    },\n    registerMarkdownTransformer(transformer: unknown) {\n      state.markdownTransformer = transformer\n    },\n    sendMessage(message: UnknownRecord, options: UnknownRecord = {}) {\n      requireAgent(state, 'sendMessage')\n      return reportUnawaitedDelivery(ctx, state, 'sendMessage', sendPiMessage(ctx, state, message.content, deliveryMode(options), undefined,\n        typeof message.customType === 'string' ? message.customType : undefined))\n    },\n    sendUserMessage(content: unknown, options: UnknownRecord = {}) {\n      requireAgent(state, 'sendUserMessage')\n      return reportUnawaitedDelivery(ctx, state, 'sendUserMessage', sendPiMessage(ctx, state, content, options.deliverAs === 'steer' ? 'steer' : 'followup'))\n    },\n    appendEntry(customType: string, data?: unknown) {\n      const session = requireSession(state, 'appendEntry')\n      state.bridge.appendCustomEntry(session.id, customType, data)\n    },\n    setSessionName(name: string) {\n      const session = requireSession(state, 'setSessionName')\n      const titles = optionalService<DshSessionTitleService>(ctx, 'sessionTitle')\n      // DSH's title is durable, pins against automatic regeneration, and is\n      // what its surfaces show — so it is where the name goes. The sidecar\n      // stays the fallback for a composition that mounts no title service.\n      // A blank name is the one case that stays local: DSH refuses a title\n      // with no visible characters, while Pi accepts one.\n      if (titles !== undefined && String(name).trim().length > 0) titles.rename(session, String(name))\n      else state.bridge.setName(session.id, String(name))\n      void dispatch(state, 'session_info_changed', {\n        type: 'session_info_changed',\n        name: sessionNameOf(ctx, state, session),\n      }, contextFor(ctx, state, currentAgent(state), undefined))\n        .catch(error => logger(ctx).warn(`[pi2dsh] session_info_changed handler failed: ${String(error)}`))\n    },\n    getSessionName() {\n      const session = agentSession(currentAgent(state))\n      return session === undefined ? undefined : sessionNameOf(ctx, state, session)\n    },\n    setLabel(entryId: string, label: string | undefined) {\n      const session = requireSession(state, 'setLabel')\n      state.bridge.appendLabel(session.id, String(entryId), label)\n    },\n    async exec(command: string, args: string[] = [], options: PiExecOptions = {}) {\n      const service = optionalService<DshSubprocessService>(ctx, 'subprocess')\n      if (service === undefined) unsupported('exec')\n      const parent = currentAgent(state)\n      // A Unix socket and local launcher are not meaningful in E2B/remote\n      // execution worlds. Keep their environment and provider path untouched.\n      let local = false\n      try {\n        const { LocalSubprocessRuntime } = await import('@deepseek-ai/dsh-subprocess-local')\n        local = service instanceof LocalSubprocessRuntime\n      } catch { /* optional local provider is absent */ }\n      if (!local) return executePiCommand(service, cwdOf(parent), command, args, options)\n      return withPiPrintTransport(\n        (request, signal) => runPiPrintRequest(ctx, state, parent, request, signal),\n        environment => executePiCommand(service, cwdOf(parent), command, args, options, environment),\n      ).catch(error => ({ stdout: '', stderr: error instanceof Error ? error.message : String(error), code: 1, killed: options.signal?.aborted === true }))\n    },\n    getActiveTools: () => getActiveTools(ctx, state),\n    getAllTools: () => {\n      // Enumerate Pi-registered tools through the runner facade: a package\n      // that patched ExtensionRunner.prototype.getAllRegisteredTools\n      // (pi-fabric's catalog capture) filters what this surface reports.\n      const visiblePiTools = new Set(\n        state.runner.getAllRegisteredTools()\n          .map(record => (record.definition as PiTool | undefined)?.name)\n          .filter((name): name is string => typeof name === 'string'),\n      )\n      return toolRuntime(ctx, currentAgent(state)).schemas(currentAgent(state))\n        .filter(tool => !state.tools.has(tool.name) || visiblePiTools.has(tool.name))\n        .map(tool => ({\n          name: tool.name,\n          description: tool.description ?? '',\n          parameters: tool.parameters ?? {},\n          source: state.tools.has(tool.name) ? 'extension' : 'builtin',\n          sourceInfo: { path: '', source: state.tools.has(tool.name) ? 'pi2dsh' : 'dsh', scope: 'session', origin: 'runtime' },\n        }))\n    },\n    setActiveTools: (names: string[]) => setActiveTools(ctx, state, names),\n    getCommands: () => [...[...state.commands.values()].map(command => ({\n      name: command.name,\n      description: command.description,\n      source: 'extension',\n      sourceInfo: { path: '', source: 'pi2dsh', scope: 'user', origin: 'package' },\n    })), ...state.nativeSkillCommands],\n    async setModel(model: UnknownRecord) {\n      const agent = currentAgent(state)\n      if (agent === undefined) return false\n      const override = {\n        ...(typeof model?.provider === 'string' ? { provider: model.provider } : {}),\n        ...(typeof model?.id === 'string' ? { model: model.id } : {}),\n      }\n      if (override.model === undefined) return false\n      // Read before the write: this used to read the map back AFTER setting it,\n      // so `previousModel` was the model just selected and every handler saw\n      // \"changed from X to X\". It also has to be a Pi Model — the map holds a\n      // DSH-shaped `{provider, model}` route, which is not what Pi hands a\n      // model_select handler.\n      const previousModel = currentPiModel(state, agent)\n      state.modelOverrides.set(agent, override)\n      void dispatch(state, 'model_select', {\n        type: 'model_select', model, previousModel, source: 'set',\n      }, contextFor(ctx, state, agent, undefined))\n        .catch(error => logger(ctx).warn(`[pi2dsh] model_select handler failed: ${String(error)}`))\n      return true\n    },\n    getThinkingLevel: () => thinkingLevelOf(state, currentAgent(state)),\n    setThinkingLevel(level: string) {\n      const agent = currentAgent(state)\n      const previousLevel = thinkingLevelOf(state, agent)\n      if (agent === undefined) state.globalThinkingLevel = String(level)\n      else state.thinkingLevels.set(agent, String(level))\n      void dispatch(state, 'thinking_level_select', {\n        type: 'thinking_level_select', level: String(level), previousLevel,\n      }, contextFor(ctx, state, agent, undefined))\n        .catch(error => logger(ctx).warn(`[pi2dsh] thinking_level_select handler failed: ${String(error)}`))\n    },\n    events: {\n      emit(channel: string, data: unknown) {\n        state.eventBus.emit(channel, data)\n      },\n      on(channel: string, handler: (data: unknown) => unknown) {\n        const safeHandler = (data: unknown) => {\n          Promise.resolve(handler(data)).catch(error => logger(ctx).warn(`[pi2dsh] package event ${channel} handler failed: ${String(error)}`))\n        }\n        state.eventBus.on(channel, safeHandler)\n        const off = (): void => { state.eventBus.off(channel, safeHandler) }\n        state.eventBusOffs.push(off)\n        return off\n      },\n    },\n  }\n}\n\nfunction splitArguments(input: string): string[] {\n  const values: string[] = []\n  let current = ''\n  let quote: string | undefined\n  for (const character of input) {\n    if (quote !== undefined) {\n      if (character === quote) quote = undefined\n      else current += character\n    } else if (character === '\"' || character === \"'\") {\n      quote = character\n    } else if (/\\s/u.test(character)) {\n      if (current.length > 0) {\n        values.push(current)\n        current = ''\n      }\n    } else {\n      current += character\n    }\n  }\n  if (current.length > 0) values.push(current)\n  return values\n}\n\nfunction promptBody(text: string): string {\n  const normalized = text.replace(/\\r\\n?/gu, '\\n')\n  if (!normalized.startsWith('---')) return normalized\n  const endIndex = normalized.indexOf('\\n---', 3)\n  if (endIndex === -1) return normalized\n  return normalized.slice(endIndex + 4).trim()\n}\n\nfunction expandPrompt(text: string, rawInput: string): string {\n  const args = splitArguments(rawInput)\n  const all = args.join(' ')\n  return promptBody(text).replace(\n    /\\$\\{(\\d+|ARGUMENTS|@):-([^}]*)\\}|\\$\\{@:(\\d+)(?::(\\d+))?\\}|\\$(ARGUMENTS|@|\\d+)/gu,\n    (_match, defaultTarget: string | undefined, fallback: string | undefined, sliceStart: string | undefined, sliceLength: string | undefined, simple: string | undefined) => {\n      if (defaultTarget !== undefined) {\n        const value = defaultTarget === '@' || defaultTarget === 'ARGUMENTS'\n          ? all\n          : args[Number(defaultTarget) - 1]\n        return value || fallback || ''\n      }\n      if (sliceStart !== undefined) {\n        const offset = Math.max(0, Number(sliceStart) - 1)\n        return args.slice(offset, sliceLength === undefined ? undefined : offset + Number(sliceLength)).join(' ')\n      }\n      if (simple === '@' || simple === 'ARGUMENTS') return all\n      return args[Number(simple) - 1] ?? ''\n    },\n  )\n}\n\nasync function registerPromptCommands(ctx: Context, state: RuntimeState, rootDir: string, manifest: GeneratedRuntimeManifest): Promise<void> {\n  for (const prompt of manifest.prompts) {\n    const text = await readFile(join(rootDir, prompt.path), 'utf8')\n    registerCommand(ctx, state, {\n      name: prompt.name,\n      description: prompt.description,\n      ...(prompt.argumentHint !== undefined ? { argumentHint: prompt.argumentHint } : {}),\n      handler(rawInput, commandContext) {\n        const agent = (commandContext as UnknownRecord).__agent as UnknownRecord | undefined\n        const invocationAgent = agent ?? [...state.activeAgents][0]\n        if (invocationAgent === undefined || typeof invocationAgent.steer !== 'function') {\n          throw new Error(`pi2dsh: /${prompt.name} requires a live DSH agent`)\n        }\n        invocationAgent.steer(createUserMessage({\n          content: [{ type: 'text', text: expandPrompt(text, rawInput) }],\n          source: { kind: 'plugin', plugin: `pi2dsh:${manifest.package.name}`, form: 'relay' },\n        }))\n      },\n    })\n  }\n}\n\nasync function loadExtensions(\n  rootDir: string,\n  manifest: GeneratedRuntimeManifest,\n  api: UnknownRecord,\n  onExtensionError?: (failure: string) => void,\n  onCapabilityGap?: (error: PiCapabilityError, extension: string) => void,\n  onHostInfraReference?: (symbol: string, extension: string) => void,\n): Promise<void> {\n  const resolveShim = async (name: string): Promise<string> => {\n    const compiled = fileURLToPath(new URL(`./compat/${name}.mjs`, import.meta.url))\n    try {\n      await access(compiled)\n      return compiled\n    } catch {\n      return fileURLToPath(new URL(`./compat/${name}.ts`, import.meta.url))\n    }\n  }\n  const [codingAgentShim, tuiShim, aiShim] = await Promise.all([\n    resolveShim('pi-coding-agent'),\n    resolveShim('pi-tui'),\n    resolveShim('pi-ai'),\n  ])\n  const aliases: Record<string, string> = {}\n  const require = createRequire(import.meta.url)\n  for (const family of ['@earendil-works', '@mariozechner']) {\n    aliases[`${family}/pi-coding-agent`] = codingAgentShim\n    aliases[`${family}/pi-tui`] = tuiShim\n    // Pi publishes `./api/*` too, and a gateway package reaches for the entry\n    // that matches its protocol. Every one of them lands on the same shim.\n    for (const api of [\n      'anthropic-messages', 'openai-completions', 'openai-responses', 'openai-codex-responses',\n      'azure-openai-responses', 'google-generative-ai', 'google-vertex',\n      'mistral-conversations', 'bedrock-converse-stream', 'pi-messages',\n    ]) {\n      // The shim itself re-exports Pi's real lazy transport factories. Resolve\n      // those PUBLIC package subpaths exactly; otherwise\n      // Jiti's prefix alias rewrites e.g. `pi-ai/api/foo.lazy` underneath the\n      // shim path (`pi-ai.ts/api/foo.lazy`) when tests load the TypeScript\n      // fallback before a dist build exists.\n      try {\n        aliases[`${family}/pi-ai/api/${api}.lazy`] = fileURLToPath(\n          import.meta.resolve(`@earendil-works/pi-ai/api/${api}.lazy`),\n        )\n      } catch {\n        // The ordinary shim alias below preserves a useful missing-package\n        // failure if the bridge's declared dependency is unavailable.\n      }\n      aliases[`${family}/pi-ai/api/${api}`] = aiShim\n    }\n    // Pi resolves subpath entries of pi-ai (compat superset, oauth, provider\n    // catalogs) for extensions; all of them land on the same shim surface.\n    // Keep the broad package alias last: Jiti applies prefix aliases in\n    // insertion order, so it must not swallow the real `.lazy` subpaths above.\n    aliases[`${family}/pi-ai/compat`] = aiShim\n    aliases[`${family}/pi-ai/oauth`] = aiShim\n    aliases[`${family}/pi-ai/providers/all`] = aiShim\n    aliases[`${family}/pi-ai/bedrock-provider`] = aiShim\n    aliases[`${family}/pi-ai/bun-oauth`] = aiShim\n    aliases[`${family}/pi-ai`] = aiShim\n  }\n  // Pi's loader hands extensions the host's typebox without a declaration;\n  // mirror that by resolving every typebox entry the whitelist names to the\n  // bridge's own copy.\n  // typebox restricts its exports map (no ./package.json), so resolve each\n  // public entry directly; resolution anchors at this runtime file, which in a\n  // generated bundle sits next to the bundle's own node_modules.\n  for (const entry of ['typebox', 'typebox/value', 'typebox/compile']) {\n    try {\n      const resolved = require.resolve(entry)\n      aliases[entry] = resolved\n      aliases[entry.replace('typebox', '@sinclair/typebox')] = resolved\n    } catch {\n      // Without a resolvable typebox entry extensions fall back to normal\n      // resolution against their own dependencies.\n    }\n  }\n  const jiti = createJiti(import.meta.url, {\n    interopDefault: true,\n    alias: aliases,\n  })\n  // Pi's loader isolates per-extension failures: one broken entry reports and\n  // the rest keep loading. A package whose every entry fails still errors.\n  const failures: string[] = []\n  let mounted = 0\n  for (const extension of manifest.extensions) {\n    // Startup check, BEFORE the entry runs: an import of a host-owned symbol\n    // that cannot work on DSH is surfaced at mount time, so the user learns\n    // at startup instead of when some later code path constructs it.\n    try {\n      const source = await readFile(join(rootDir, extension), 'utf8')\n      // ModelRuntime is no longer on this list: ModelRuntime.create() is a\n      // real runtime whose model calls ride the DSH llm bridge (only its\n      // directory/credential surface is a structured capability error).\n      const infraImport = /import[^;]*?\\b(DefaultPackageManager)\\b[^;]*?from\\s*['\"]@(?:earendil-works|mariozechner)\\/pi-coding-agent['\"]/su.exec(source)\n      if (infraImport !== null) onHostInfraReference?.(infraImport[1]!, extension)\n    } catch {\n      // Unreadable entries fail below through the loader with a real error.\n    }\n    try {\n      const loaded: unknown = await jiti.import(join(rootDir, extension))\n      const candidate = typeof loaded === 'object' && loaded !== null && 'default' in loaded\n        ? (loaded as { default: unknown }).default\n        : loaded\n      if (typeof candidate !== 'function') throw new TypeError(`Pi extension ${extension} has no default factory function`)\n      await candidate(api)\n      mounted += 1\n    } catch (error) {\n      // A capability gap during entry setup means this package cannot start\n      // at all — the user gets the unusable verdict, not just a skip line.\n      // Matched by name: the shim chunk carries its own compiled copy of the\n      // class, so instanceof does not hold across that bundle boundary.\n      if (error instanceof PiCapabilityError\n        || (error instanceof Error && error.name === 'PiCapabilityError')) {\n        onCapabilityGap?.(error as PiCapabilityError, extension)\n      }\n      failures.push(`${extension}: ${error instanceof Error ? error.message : String(error)}`)\n    }\n  }\n  if (failures.length > 0 && mounted === 0 && manifest.extensions.length > 0) {\n    throw new Error(`every Pi extension entry failed to load:\\n${failures.map(item => `- ${item}`).join('\\n')}`)\n  }\n  for (const failure of failures) onExtensionError?.(failure)\n}\n\nexport async function applyPiPackage(ctx: Context, options: RuntimeOptions): Promise<void> {\n  if (options.manifest.schemaVersion !== 1) throw new Error(`unsupported pi2dsh manifest version ${String(options.manifest.schemaVersion)}`)\n  const rootDir = fileURLToPath(options.rootUrl)\n  const runtimeTools = new Map<string, PiTool>()\n  const piToolRecords = (): Array<{ definition: unknown, sourceInfo: { path: string, source: string, scope: string, origin: string } }> =>\n    [...runtimeTools.values()].map(tool => ({\n      definition: tool,\n      sourceInfo: { path: '', source: 'pi2dsh', scope: 'session', origin: 'package' },\n    }))\n  const shared = sharedHostStateOf(ctx)\n  const scopedOwner = options.ownerAgent ?? scopeOf(ctx)\n  const ownerAgent = typeof scopedOwner === 'object' && scopedOwner !== null\n    ? scopedOwner as UnknownRecord\n    : undefined\n  if (ownerAgent !== undefined && options.hostAnchor !== true) {\n    // The instance's LIVE Pi tool ledger, findable by (agent, package):\n    // pi-subagents' extension tool scope re-derives a child's active set from\n    // \"the loader's live extension maps\" every turn — this reference is that\n    // map on this host, late registrations included by construction.\n    shared.childPackageTools ??= new WeakMap()\n    const byPackage = shared.childPackageTools.get(ownerAgent) ?? new Map<string, ReadonlyMap<string, unknown>>()\n    byPackage.set(options.manifest.package.name, runtimeTools)\n    shared.childPackageTools.set(ownerAgent, byPackage)\n  }\n  const state: RuntimeState = {\n    shared,\n    packageName: options.manifest.package.name,\n    ownerAgent,\n    hostAnchor: options.hostAnchor === true,\n    handlers: new Map(),\n    tools: runtimeTools,\n    runner: new ExtensionRunner(piToolRecords),\n    toolDisposers: new Map(),\n    toolRestrictions: new WeakMap(),\n    commands: new Map(),\n    nativeSkillCommands: [],\n    commandDisposers: new Map(),\n    dshCommandOwners: new Map(),\n    companionRoutes: shared.companionRoutes,\n    flags: new Map(),\n    notifications: [],\n    activeAgents: new Set(),\n    hostAgent: undefined,\n    piShutdownAgents: new WeakSet(),\n    shutdownTasks: new WeakMap(),\n    pendingShutdowns: new Set(),\n    disposedAgents: new WeakSet(),\n    startedSessions: new Set(),\n    sessionStartTasks: new Map(),\n    startedSessionlessAgents: new WeakSet(),\n    sessionlessStartTasks: new WeakMap(),\n    extensionsReady: false,\n    pendingSessionStarts: new Map(),\n    discoveredSkillRoots: new Set(),\n    discoveredSkillProviders: 0,\n    currentSystemPrompt: '',\n    messageSource: `pi2dsh:${options.manifest.package.name}`,\n    eventBus: sharedEventBusFor(shared, ownerAgent),\n    eventBusOffs: [],\n    agentScope: new AsyncLocalStorage(),\n    llmBridge: undefined,\n    piAiRegistry: __createPiAiRuntimeRegistry(),\n    subagentSessionFactory: undefined,\n    bridge: new PiSessionBridge(ref => fileContentForPi(ref, ctx as never)),\n    theme: sharedThemeFor(shared, ownerAgent),\n    shortcuts: new Map(),\n    messageRenderers: new Map(),\n    entryRenderers: new Map(),\n    providers: new Map(),\n    nativeProviders: new Set(),\n    autocompleteProviders: [],\n    editorBuffers: new WeakMap(),\n    toolsExpanded: false,\n    modelOverrides: new WeakMap(),\n    thinkingLevels: new WeakMap(),\n    childAgents: new WeakSet(),\n    turnSystemPromptOverrides: new WeakMap(),\n    projection: Promise.resolve(),\n    terminateBatch: new WeakMap(),\n    piTurnIndex: new WeakMap(),\n    claimedForStep: new WeakMap(),\n    promptedTurn: new WeakMap(),\n    pendingInjections: new WeakMap(),\n    globalThinkingLevel: 'off',\n    argMutations: new WeakMap(),\n    streamingTexts: new Map(),\n    lastLoggedModels: new WeakMap(),\n    providerRouteDisposers: shared.providerRouteDisposers,\n    ownedProviderRoutes: new Set(),\n    publishedOAuthKeys: shared.publishedOAuthKeys,\n    tuiSurfaces: undefined,\n  }\n  // Select by PUBLIC surface capability, never by Pi consumer package. The\n  // raw piTuiExtensions seat is the closest contract and wins when present;\n  // dsh-TUI's scene service remains the fallback. A future remote client only\n  // replaces the relay transport — Pi component objects stay Host-owned.\n  const surfaceInstanceKey = typeof ownerAgent?.id === 'string' ? ownerAgent.id : undefined\n  const piTuiSurface = await createPiTuiExtensionSurfaceAdapter(\n    ctx as unknown as TuiSurfaceContext,\n    state.packageName,\n    surfaceInstanceKey,\n  )\n  if (piTuiSurface !== undefined) {\n    state.tuiSurfaces = piTuiSurface\n    ctx.effect(() => () => {\n      piTuiSurface.dispose()\n      if (state.tuiSurfaces === piTuiSurface) state.tuiSurfaces = undefined\n    })\n  } else {\n    mountTuiSurfaceAdapter(\n      ctx as unknown as TuiSurfaceContext,\n      state.packageName,\n      adapter => { state.tuiSurfaces = adapter },\n      surfaceInstanceKey,\n    )\n  }\n  subscribeLifecycle(ctx, state)\n  subscribeInterceptors(ctx, state)\n  // Pi hosts ship their built-in OAuth providers ready to log in; preload the\n  // four vendored official flows so `/login openai-codex` (etc.) works out of\n  // the box, before any package registers its own providers. They form the\n  // BUILTIN BASE LAYER of the layered ledger: a package registering the same\n  // provider id overlays it field-wise (its defined fields win, undefined\n  // fields keep the builtin — so a partial registration inherits the builtin\n  // OAuth flow), and unregistering the overlay restores the builtin.\n  shared.providerBuiltins ??= new Map()\n  for (const provider of builtinProviders()) {\n    const config = { name: provider.name, baseUrl: provider.baseUrl, oauth: provider.auth.oauth }\n    state.providers.set(provider.id, config)\n    if (!shared.providerBuiltins.has(provider.id)) {\n      shared.providerBuiltins.set(provider.id, config)\n      recomposeSharedProvider(shared, provider.id)\n    }\n    // On 0.1.1-line hosts the built-in entries also join the native sign-in\n    // surface — unless another flow (the official llm-pi-ai catalog sign-ins)\n    // already answers for the same id, in which case that one stands.\n    maybeProjectAuthorizationFlow(ctx, state, provider.id)\n  }\n  ensureLoginCommand(ctx, state)\n  // A credential stored by an EARLIER session must still produce a route:\n  // otherwise the models a user logged in for vanish on the next restart and\n  // they are told to log in again to something they are already logged in to.\n  // This is part of mount readiness, not a background convenience. A one-shot\n  // profile can start its first model call as soon as applyPiPackage returns;\n  // publishing beside that call loses the race and the host reports\n  // MISSING_CREDENTIAL even though auth.json already contains a valid login.\n  for (const [name, config] of [...state.providers]) {\n    try {\n      await restoreLoggedInRouteWhenReady(ctx, state, name, config)\n    } catch (error) {\n      logger(ctx).warn(`[pi2dsh] could not restore the route for logged-in provider ${JSON.stringify(name)}: ${error instanceof Error ? error.message : String(error)}`)\n    }\n  }\n  // Skills are static host-level content: DSH's skills registry is a host\n  // service and the filesystem provider name is per-package, so per-Agent\n  // registration would collide with itself. The anchor (or a legacy unowned\n  // mount) carries them exactly once.\n  if (options.manifest.skillDirs.length > 0 && state.ownerAgent === undefined) {\n    const skills = (ctx as unknown as { get(name: string): unknown }).get('skills')\n    if (skills === undefined) logger(ctx).warn('[pi2dsh] migrated skills were not mounted because this DSH composition has no ctx.skills')\n    else {\n      const { apply: applyFilesystemSkills } = await import('@deepseek-ai/dsh-skill-filesystem')\n      const config = {\n        providerName: `pi2dsh-${options.manifest.package.name.replace(/[^a-zA-Z0-9_-]+/gu, '-').replace(/^-+|-+$/gu, '')}`,\n        includeDefaultRoots: false,\n        customSkillDirs: options.manifest.skillDirs.map(path => join(rootDir, path)),\n        watch: false,\n      }\n      await ctx.plugin(Object.assign(\n        (skillCtx: Context) => applyFilesystemSkills(skillCtx, config),\n        { inject: ['skills'] },\n      ))\n    }\n  }\n  // Model Runtime Bridge: ONE model directory — the DSH llm directory —\n  // projected as Pi's model catalog; hand-built pi-ai complete()/stream()\n  // calls route through the native llm service. Compositions without llm\n  // keep the empty-catalog semantics.\n  const llm = llmOf(ctx)\n  // ONE catalog projection and ONE adapters-updated subscription per host;\n  // every package's registry reads the same directory view.\n  state.modelCatalog = shared.modelCatalog ??= new ModelCatalog(llm)\n  registerVisionCompanions(ctx, (options.config as { visionCompanions?: VisionCompanionsConfig } | undefined)?.visionCompanions)\n  if (llm !== undefined) {\n    if (shared.catalogSubscribed !== true) {\n      shared.catalogSubscribed = true\n      const cordisCtx = ctx as unknown as { on(name: string, callback: (...args: unknown[]) => unknown): () => void }\n      cordisCtx.on('llm/adapters-updated', () => { void shared.modelCatalog?.refresh() })\n    }\n    // Pi hosts finish loading the model directory before extensions can see\n    // the registry, so extension-visible reads (guardian reviewer probes)\n    // never race the initial catalog fill. Later refreshes stay concurrent.\n    await state.modelCatalog.refresh()\n    state.llmBridge = (model, context, callOptions) => streamViaDshLlm(llm, { model, context, options: callOptions })\n  }\n  // createAgentSession builds a real DSH child agent through ctx.agents; the\n  // factory lives for exactly the runtime's lifetime.\n  // The panel's registry and its read route: host-level, mounted once.\n  //\n  // Gated on the engine's browserPresentation config (default OFF): the\n  // engine alone ships no web renderer, so serving the route — and with it\n  // claiming `mode: 'tui'` on the web composition — would promise packages a\n  // presentation surface nobody draws. Without the gate a web session is\n  // exactly the headless composition (Pi's rpc mode, packages degrade on\n  // their own). The dsh-work-x suite sets the flag and carries the renderer.\n  const browserSurfaces = state.shared.browserSurfaces ??= new BrowserSurfaces()\n  const wantsBrowserPresentation = (options.config as { browserPresentation?: boolean } | undefined)?.browserPresentation === true\n  if (wantsBrowserPresentation && state.shared.browserSurfacesRouted !== true) {\n    // Structured MCP faces for the product-layer tab. The state face reads\n    // the MCP ecosystem's own layered config files (the exact layers the\n    // adapter reads); the action face persists ONLY the `disabled` flag into\n    // the project-local override layer — byte-for-byte the file and shape\n    // pi-mcp-adapter's own /mcp disable command writes, never touching the\n    // server's source file and never copying credentials. Secret values stay\n    // server-side: env/header VALUES are never serialized, only key names.\n    const sessionCwd = (session: string): string => {\n      const sessions = (ctx as unknown as { get(name: string): unknown }).get('sessions') as\n        { get?(id: string): { header?: { cwd?: string } } | undefined } | undefined\n      // Creation metadata lives on the session's durable header (a storage\n      // concern, deliberately outside the event log). No session (the global\n      // Settings view) means no workspace: the home directory anchors the\n      // read so only the cross-project layers can match.\n      const cwd = sessions?.get?.(session)?.header?.cwd\n      if (typeof cwd === 'string' && cwd.length > 0) return cwd\n      return session === '' ? homedir() : process.cwd()\n    }\n    // The first four config layers are cross-project (home + agent dir); the\n    // cwd-relative pair is the project layer. The split is positional in\n    // piMcpConfigPaths on purpose — one authority for the layer order.\n    const globalLayerPaths = (cwd: string): Set<string> => new Set(piMcpConfigPaths(cwd).slice(0, 4))\n    state.shared.browserSurfacesRouted = registerBrowserSurfaceRoute(ctx, browserSurfaces, {\n      async mcpState(session) {\n        const cwd = sessionCwd(session)\n        const globals = globalLayerPaths(cwd)\n        const { servers, sources } = collectPiMcpServers(cwd)\n        return {\n          cwd,\n          sources,\n          servers: [...servers.values()].map(server => ({\n            name: server.name,\n            transport: server.transport,\n            target: server.transport === 'stdio'\n              ? [server.command, ...(server.args ?? [])].filter(Boolean).join(' ')\n              : server.url ?? '',\n            disabled: server.disabled,\n            sourcePath: server.sourcePath,\n            layer: globals.has(server.sourcePath) ? 'global' : 'project',\n            envKeys: Object.keys(server.env ?? {}),\n            headerKeys: Object.keys(server.headers ?? {}),\n          })),\n        }\n      },\n      async mcpAction(session, server, disabled, scope) {\n        const cwd = sessionCwd(session)\n        const { servers } = collectPiMcpServers(cwd)\n        if (!servers.has(server)) throw new TypeError(`unknown MCP server ${JSON.stringify(server)}`)\n        // 'project' writes the workspace override (this project only, the\n        // adapter's own /mcp disable file); 'global' writes the agent-dir\n        // layer every project reads. Both persist ONLY the disabled flag.\n        const overridePath = scope === 'global'\n          ? [...globalLayerPaths(cwd)][3]!\n          : join(cwd, '.pi', 'mcp.json')\n        let current: Record<string, unknown> = {}\n        try {\n          current = JSON.parse(await readFile(overridePath, 'utf8')) as Record<string, unknown>\n        } catch { /* absent or unreadable: start a fresh override layer */ }\n        const mcpServers = (typeof current.mcpServers === 'object' && current.mcpServers !== null\n          ? current.mcpServers\n          : {}) as Record<string, unknown>\n        const entry = (typeof mcpServers[server] === 'object' && mcpServers[server] !== null\n          ? mcpServers[server]\n          : {}) as Record<string, unknown>\n        mcpServers[server] = { ...entry, disabled }\n        current.mcpServers = mcpServers\n        await mkdir(dirname(overridePath), { recursive: true })\n        await writeFile(overridePath, `${JSON.stringify(current, null, 2)}\\n`)\n        return { ok: true, note: 'run /reload (or restart the session) to apply' }\n      },\n      // The Models-page login card's faces. Same spine as /login and the\n      // authorization-seam flow (runProviderLogin); the card is only another\n      // ui surface for it — one whose dialog is a poll/answer pair over the\n      // package's own route instead of a live prompt channel.\n      async loginState() {\n        const flow = state.shared.browserLogin\n        const providers = await Promise.all(\n          [...state.providers.entries()]\n            .filter(([, config]) => providerSupportsOAuth(config))\n            .map(async ([id, config]) => ({\n              id,\n              name: ((config.oauth as UnknownRecord | undefined)?.name as string | undefined) ?? id,\n              signedIn: await storedOAuthCredential(oauthStoreOf(state), id).then(c => c !== undefined, () => false),\n            })),\n        )\n        return {\n          providers,\n          ...(flow === undefined ? {} : {\n            flow: {\n              provider: flow.provider,\n              providerName: flow.providerName,\n              notices: flow.notices,\n              ...(flow.question === undefined ? {} : {\n                question: {\n                  id: flow.question.id, kind: flow.question.kind, title: flow.question.title,\n                  ...(flow.question.placeholder === undefined ? {} : { placeholder: flow.question.placeholder }),\n                  ...(flow.question.options === undefined ? {} : { options: flow.question.options }),\n                },\n              }),\n              ...(flow.done === undefined ? {} : { done: flow.done }),\n            },\n          }),\n        }\n      },\n      async loginAction(action, provider, value) {\n        const shared = state.shared\n        if (action === 'dismiss') {\n          shared.browserLogin = undefined\n          return { ok: true }\n        }\n        if (action === 'answer') {\n          const flow = shared.browserLogin\n          if (flow?.answer === undefined) throw new TypeError('no login question is waiting for an answer')\n          const settle = flow.answer\n          flow.answer = undefined\n          delete flow.question\n          settle(value)\n          return { ok: true }\n        }\n        if (action === 'cancel') {\n          const cancelled = await supersedeActiveLogin(state)\n          const flow = shared.browserLogin\n          if (flow !== undefined && flow.done === undefined) {\n            flow.done = { ok: false, summary: 'Login cancelled' }\n          }\n          return { ok: true, ...(cancelled === undefined ? {} : { cancelled }) }\n        }\n        const config = state.providers.get(provider)\n        if (config === undefined || !providerSupportsOAuth(config)) {\n          throw new TypeError(`unknown OAuth provider ${JSON.stringify(provider)}`)\n        }\n        const providerName = ((config.oauth as UnknownRecord | undefined)?.name as string | undefined) ?? provider\n        if (action === 'signout') {\n          // The direct half of the sign-out mirror: drop the stored login and\n          // retire the placeholder route it justified. A package-owned\n          // transport route stays — its per-request credential resolution\n          // reports the missing login itself. (The DSH credential record the\n          // authorization seam writes is mirrored the other way, by the\n          // record-deleted watcher; stock compositions do not compose that\n          // service, so there is no record to clear here.)\n          await oauthStoreOf(state).delete(provider)\n          if (!providerCarriesTransport(config)) retireSharedProviderRoute(shared, provider)\n          return { ok: true, signedOut: provider }\n        }\n        if (action !== 'begin') throw new TypeError(`unknown login action ${JSON.stringify(action)}`)\n        let questionSeq = 0\n        const flow: BrowserLoginFlow = { provider, providerName, notices: [] }\n        // A pending question from a superseded flow must not wait forever:\n        // starting a new flow replaces the record wholesale, and the spine\n        // aborts the old flow's signal, which resolves its question below.\n        shared.browserLogin = flow\n        const ask = (\n          kind: 'input' | 'select',\n          title: string,\n          extras: { placeholder?: string, options?: string[] },\n          signal?: AbortSignal,\n        ): Promise<string | undefined> => new Promise((resolve) => {\n          const id = ++questionSeq\n          flow.question = { id, kind, title, ...extras }\n          flow.answer = (answered) => { resolve(answered) }\n          const withdraw = () => {\n            if (flow.question?.id !== id) return\n            delete flow.question\n            flow.answer = undefined\n            resolve(undefined)\n          }\n          if (signal !== undefined) {\n            if (signal.aborted) withdraw()\n            else signal.addEventListener('abort', withdraw, { once: true })\n          }\n        })\n        const ui: ProviderLoginUi = {\n          notify: (message) => { flow.notices.push({ message: String(message) }) },\n          input: (title, placeholder, signal) => ask('input', String(title),\n            typeof placeholder === 'string' && placeholder.length > 0 ? { placeholder } : {}, signal),\n          select: (title, options, signal) => ask('select', String(title),\n            { options: options.map(option => String(option)) }, signal),\n          // The device code stays on screen as a notice; the card keeps\n          // polling, so \"visible while the package polls\" is the default.\n          // The OAuthUiSurface contract makes RESOLVING this call mean \"the\n          // user dismissed the dialog\" (oauthInteraction cancels the flow on\n          // it) — so this settles only when the flow's own signal closes it,\n          // never on its own.\n          deviceCode: (title, detail, signal) => {\n            // The detail is the dialog-flavored markdown line; the URL in it\n            // already arrived as its own notice, so the card keeps only the\n            // code itself (the one thing the user must copy).\n            const code = /`([^`]+)`/u.exec(String(detail))?.[1]\n            flow.notices.push({ message: String(title), ...(code === undefined ? {} : { code }) })\n            return new Promise<void>((resolve) => {\n              if (!(signal instanceof AbortSignal)) return\n              if (signal.aborted) resolve()\n              else signal.addEventListener('abort', () => resolve(), { once: true })\n            })\n          },\n        }\n        void runProviderLogin(ctx, state, provider, config, ui).then(\n          (summary) => { if (shared.browserLogin === flow) flow.done = { ok: true, summary } },\n          (error: unknown) => {\n            if (shared.browserLogin === flow) {\n              flow.done = { ok: false, summary: error instanceof Error ? error.message : String(error) }\n            }\n          },\n        )\n        return { ok: true, started: provider }\n      },\n    })\n  }\n  // Pi's custom entries, drawn by the package's OWN renderer. `appendEntry`\n  // writes to the pi2dsh sidecar (DSH's log has no channel for event types\n  // declared outside the harness), so nothing in the host's conversation view\n  // would ever show them; running the registered EntryRenderer and projecting\n  // its component to text is what puts a package's own entries on screen.\n  // Pi's autocomplete providers, on DSH's trigger menu. Pi asks a provider at\n  // the cursor on every edit; DSH asks a source after `/` or `@`. The two agree\n  // exactly for a provider anchored on a trigger character — which is what an\n  // @-mention provider is, and what the ecosystem's provider actually does — so\n  // the bridge asks the Pi chain with the token the user is typing and offers\n  // whatever it returns. A provider that completes bare words mid-sentence has\n  // no DSH moment to fire in and simply returns nothing here.\n  ctx.effect(() => browserSurfaces.trackCompletions(state.packageName ?? 'pi', async (trigger, query) => {\n    if (state.autocompleteProviders.length === 0) return []\n    // Pi's chain: each factory wraps the current provider, base returns nothing.\n    let provider: UnknownRecord = { getSuggestions: async () => null }\n    for (const factory of state.autocompleteProviders) {\n      if (typeof factory !== 'function') continue\n      provider = (factory as (current: unknown) => UnknownRecord)(provider) ?? provider\n    }\n    const getSuggestions = provider.getSuggestions\n    if (typeof getSuggestions !== 'function') return []\n    // The line the provider sees is the token itself: an anchored provider\n    // reads backwards from the cursor for its trigger, and that is all there is.\n    const line = `${trigger}${query}`\n    const suggestions = await (getSuggestions as (\n      lines: string[], cursorLine: number, cursorCol: number, options: UnknownRecord,\n    ) => Promise<UnknownRecord | null>)([line], 0, line.length, { signal: new AbortController().signal })\n    const items = (suggestions?.items ?? []) as Array<{ value?: unknown, label?: unknown, description?: unknown }>\n    return items\n      .filter(item => typeof item.value === 'string')\n      .map(item => ({\n        value: String(item.value),\n        label: String(item.label ?? item.value),\n        ...(typeof item.description === 'string' ? { description: item.description } : {}),\n      }))\n  }))\n  ctx.effect(() => browserSurfaces.trackEntries(state.packageName ?? 'pi', (sessionId) => {\n    const rendered: Array<{ id: string, customType: string, text: string }> = []\n    const draw = (renderer: unknown, subject: UnknownRecord): string | undefined => (\n      typeof renderer !== 'function'\n        ? undefined\n        : surfaceText(\n          (renderer as (subject: unknown, options: unknown, theme: unknown) => unknown)(subject, {}, state.theme),\n          state.theme,\n        )\n    )\n    // Custom ENTRIES live in the sidecar, addressed by session id.\n    for (const entry of state.bridge.customEntries(sessionId)) {\n      const text = draw(state.entryRenderers.get(entry.customType), {\n        type: 'custom', id: entry.id, customType: entry.customType, data: entry.data, timestamp: entry.timestamp,\n      })\n      if (text !== undefined) rendered.push({ id: entry.id, customType: entry.customType, text })\n    }\n    // Custom MESSAGES are durable DSH log entries carrying Pi's role:\"custom\"\n    // marker, so they are read back from the session itself rather than from a\n    // cache — a renderer must still work after a restart.\n    if (state.messageRenderers.size > 0) {\n      const sessions = optionalService<{ get(id: unknown): UnknownRecord | undefined }>(ctx, 'sessions')\n      const session = sessions?.get(sessionId)\n      const events = session === undefined ? [] : eventsOf(session)\n      for (const event of events) {\n        const data = (event.data ?? {}) as UnknownRecord\n        const customType = (data.source as UnknownRecord | undefined)?.piCustomType\n        if (typeof customType !== 'string') continue\n        const text = draw(state.messageRenderers.get(customType), {\n          role: 'custom', customType, content: data.content, id: `dsh-${String(event.seq ?? '')}`,\n        })\n        if (text !== undefined) rendered.push({ id: `dsh-${String(event.seq ?? '')}`, customType, text })\n      }\n    }\n    return rendered\n  }))\n  // Product UI's path into this package's slash commands (side-chat input,\n  // its save/inject buttons): the runner executes the package's OWN handler\n  // through the same contextFor/runInPiRuntime pipeline a composer\n  // invocation takes. Registered per (root session, package) — generic, no\n  // command or package is special-cased here.\n  const runnerSessionId = ownerAgent === undefined ? '' : String(agentSession(ownerAgent)?.id ?? '')\n  if (runnerSessionId.length > 0) {\n    const disposeRunner = browserSurfaces.registerCommandRunner(runnerSessionId, state.packageName, async (name, args) => {\n      const live = state.commands.get(name)\n      if (live === undefined) throw new Error(`${state.packageName} has no command ${JSON.stringify(name)}`)\n      const commandContext = contextFor(ctx, state, ownerAgent as UnknownRecord, undefined, true, undefined, true)\n      await runInPiRuntime(state, ownerAgent, async () => {\n        await ensurePiSessionStarted(ctx, state, ownerAgent, undefined)\n        await live.handler(args, commandContext)\n      })\n      const notices = commandContext.__notices as string[]\n      return notices.length > 0 ? notices.join('\\n') : undefined\n    })\n    ctx.effect(() => disposeRunner)\n  }\n  state.subagentSessionFactory = async (subagentOptions) => {\n    const created = await createBridgedAgentSession(subagentHost(), subagentOptions)\n    // Track it against the session the panel floats over — the PARENT, not the\n    // child: the panel is a view of \"what this conversation started\".\n    const parent = agentSession(currentAgent(state))\n    const parentId = parent === undefined ? '' : String(parent.id ?? '')\n    if (parentId.length > 0) {\n      const dispose = browserSurfaces.track(parentId, {\n        id: String((created.session as unknown as { sessionId?: unknown }).sessionId ?? '')\n          || `pi2dsh-thread-${parentId}-${sidePanelSerial++}`,\n        label: childLabel(subagentOptions.label, state.packageName),\n        package: state.packageName,\n        session: created.session,\n      })\n      ctx.effect(() => dispose)\n    }\n    return created\n  }\n  // Extracted so the factory above can build one per call; the annotation\n  // carries the contract the object literal used to get from the call site.\n  const subagentHost = (): SubagentHost => ({\n    cordis: ctx,\n    cwd: () => cwdOf(currentAgent(state)),\n    parentSessionId: () => {\n      const session = agentSession(currentAgent(state))\n      return session === undefined ? undefined : String(session.id ?? '') || undefined\n    },\n    parentDelegationDepth: () => {\n      // DSH's delegationDepthOf semantics: header depth and runtime option\n      // depth may each deepen the count; absence means top-level zero.\n      const parent = currentAgent(state)\n      const header = (agentSession(parent) as { header?: { delegationDepth?: unknown } } | undefined)?.header\n      const fromHeader = typeof header?.delegationDepth === 'number' ? header.delegationDepth : 0\n      const fromOptions = typeof (parent as { options?: { subagentDepth?: unknown } } | undefined)?.options?.subagentDepth === 'number'\n        ? (parent as { options: { subagentDepth: number } }).options.subagentDepth\n        : 0\n      return Math.max(fromHeader, fromOptions)\n    },\n    piContentToDsh: content => piToDshContent(ctx, content),\n    deliver: (agent, message, mode) => deliverAgentMessage(agent as DshAgent, message, mode),\n    messageFromSessionEvent: event => messageFromSessionEvent(ctx, event),\n    messageSource: state.messageSource,\n    packageName: state.packageName,\n    parentAgentContext: () => (currentAgent(state) as { ctx?: unknown } | undefined)?.ctx,\n    parentAgent: () => currentAgent(state),\n    registerChildTools: (childCtx, tools) => {\n      for (const tool of tools) registerChildPiTool(childCtx as Context, state, tool as PiTool)\n    },\n    delegatedPolicyOverrides: () => {\n      // DSH's own delegation capture (dsh-subagent semantics), read off the\n      // parent's public services: only the parent session's EXPLICIT sandbox\n      // override travels, and approval is pinned to 'never' whenever an\n      // approval service exists — a child never blocks on a dialog.\n      const parent = currentAgent(state) as { ctx?: { get?(name: string): unknown }, session?: unknown } | undefined\n      const sandboxPolicy = (typeof parent?.ctx?.get === 'function' ? parent.ctx.get('sandboxPolicy') : undefined) as\n        | { overrideOf?(session: unknown): unknown }\n        | undefined\n      const approval = typeof parent?.ctx?.get === 'function' ? parent.ctx.get('approval') : undefined\n      const sandboxMode = sandboxPolicy?.overrideOf?.(parent?.session)\n      return {\n        ...(sandboxMode !== undefined ? { sandboxMode } : {}),\n        ...(approval !== undefined ? { approvalPolicy: 'never' } : {}),\n      }\n    },\n    sessionManagerFor: session => {\n      // The child's Pi sessionManager surface: the same readonly projection\n      // the runtime uses everywhere, with getSessionFile answering the\n      // durable archive path — the identity pi-subagents records per child\n      // and reopens `@handle` mentions by.\n      const typed = session as { id?: unknown, meta?: { cwd?: unknown } }\n      const cwd = typeof typed.meta?.cwd === 'string' ? typed.meta.cwd : cwdOf(currentAgent(state))\n      return state.bridge.readonlySessionManager(session as never, cwd) as UnknownRecord\n    },\n    resumeSessionIdFor: file => state.bridge.sessionIdOfArchiveFile(file),\n    mountChildExtensions: async (childAgent, loader) => {\n      // Real Pi loads the (creator-filtered) extension set into every child\n      // at createAgentSession. The engine's catalog is that set here; a\n      // composition without the engine has no catalog and mounts nothing —\n      // the pre-existing plain-child behavior.\n      const shared = sharedHostStateOf(ctx)\n      const catalog = shared.childExtensions\n      if (catalog === undefined) return []\n      const { names, failures } = resolveChildExtensionPackages(loader, catalog)\n      if (names.length === 0) return failures\n      const mountFailures = await catalog.mount(childAgent, names)\n      // pi-subagents' extension tool scope reads Extension.tools off the\n      // loader's entries every turn; wire the entries to the live per-child\n      // ledgers so that read answers with what really registered here.\n      const attachable = loader as { attachChildToolResolver?(fn: (path: string) => ReadonlyMap<string, unknown> | undefined): void } | null | undefined\n      if (typeof attachable?.attachChildToolResolver === 'function') {\n        // Bound call — the resolver setter writes a private field; an unbound\n        // reference loses `this` and crashed the whole mount (caught live).\n        attachable.attachChildToolResolver(path => {\n          const packageName = catalog.packageByEntryPath.get(pathResolve(path))\n          if (packageName === undefined) return undefined\n          return shared.childPackageTools?.get(childAgent as object)?.get(packageName)\n        })\n      }\n      return [...failures, ...mountFailures]\n    },\n    sessionGoneFromPersistence: async sessionId => {\n      // DSH's own verdict shape (agent-loop restoreOrCreateConfigured): the\n      // persistence list() is the authority on whether a session still\n      // exists. No service / a failed list = \"cannot tell\", never \"gone\".\n      const persistence = optionalService<{ list?(): Promise<Array<{ id?: unknown }>> }>(ctx, 'sessionPersistence')\n      if (typeof persistence?.list !== 'function') return undefined\n      try {\n        const headers = await persistence.list()\n        return !headers.some(snapshot => {\n          const header = ((snapshot as UnknownRecord).header ?? snapshot) as UnknownRecord\n          return String(header.id ?? '') === sessionId\n        })\n      } catch {\n        return undefined\n      }\n    },\n    discardStaleArchive: sessionId => state.bridge.discardArchive(sessionId),\n    parentModelRoute: () => {\n      // The caller's LIVE route, by authority: an explicit Pi ctx.setModel()\n      // override, else the last durable request/header (where a DSH UI or\n      // /model switch actually lands — the snapshot never learns of it), else\n      // the creation-time AgentOptions snapshot. Snapshot-only reading is the\n      // exact inheritance bug DSH's own subagent line reports.\n      const parent = currentAgent(state)\n      if (parent === undefined) return undefined\n      const options = parent.options as { provider?: unknown, model?: unknown } | undefined\n      return resolveCallerRoute(\n        state.modelOverrides.get(parent),\n        lastRequestRouteOf(agentSession(parent)),\n        typeof options?.model === 'string'\n          ? { model: options.model, ...(typeof options.provider === 'string' ? { provider: options.provider } : {}) }\n          : undefined,\n      )\n    },\n    adoptChildAgent: (child, thinkingLevel) => {\n      if (typeof child !== 'object' || child === null) return\n      state.childAgents.add(child)\n      if (typeof thinkingLevel === 'string' && thinkingLevel.length > 0) {\n        state.thinkingLevels.set(child, thinkingLevel)\n        // Modern DSH dispatches Agent events in that Agent's scope. A parent\n        // listener cannot configure a child merely by accepting its identity.\n        const childCtx = (child as UnknownRecord).ctx as { on?: (event: string, listener: (payload: UnknownRecord, next: () => Promise<UnknownRecord>) => Promise<UnknownRecord>) => unknown } | undefined\n        childCtx?.on?.('agent/request', async (payload, next) => {\n          const config = await next()\n          if (payload.agent !== child) return config\n          const level = state.thinkingLevels.get(child)\n          if (level === undefined || (level === 'off' && (currentPiModel(state, child as UnknownRecord)?.thinkingLevelMap as UnknownRecord | undefined)?.off === null)) return config\n          return { ...config, reasoningEffort: level }\n        })\n      }\n    },\n  })\n  await registerPromptCommands(ctx, state, rootDir, options.manifest)\n  const onExtensionError = (failure: string): void =>\n    logger(ctx).warn(`[pi2dsh] extension entry failed and was skipped (matching Pi's per-extension error isolation): ${failure}`)\n  const onCapabilityGap = (gap: PiCapabilityError): void =>\n    capabilityLedgerOf(ctx, state).reportUnusable({\n      capability: gap.capability,\n      reason: 'this package needs it during startup.',\n      guidance: gap.message,\n      packageName: state.packageName,\n    })\n  const onHostInfraReference = (symbol: string): void =>\n    capabilityLedgerOf(ctx, state).reportStartupReference({\n      capability: symbol,\n      reason: 'installing packages is owned by the DSH host and its security gates (dsh plugin add/remove).',\n      guidance: '',\n      packageName: state.packageName,\n    })\n  const mountExtensions = (): Promise<void> => runInPiRuntime(\n    state,\n    currentAgent(state),\n    () => loadExtensions(\n      rootDir,\n      options.manifest,\n      createPiApi(ctx, state),\n      onExtensionError,\n      onCapabilityGap,\n      onHostInfraReference,\n    ),\n  )\n  await mountExtensions()\n  await flushPendingSessionStarts(ctx, state)\n  // Pi's ctx.reload() remount: dispose every extension-owned registration and\n  // run the entries again through a fresh loader. Prompt commands are package\n  // registrations too (they share the command ledger), so they re-register\n  // with the entries.\n  const remounts = packageRemountsOf(ctx, shared)\n  remounts.set(state.packageName, async () => {\n    // Tool and command registrations on the DSH side stay in place — their\n    // handlers resolve the live ledger entries, and re-registering from a\n    // command execution stack would attach effects to the wrong fiber scope.\n    // The remounted entries replace ledger entries through the same-name\n    // registration path; event handlers (both Pi lifecycle handlers and the\n    // package-local event bus) start from a clean slate — without this every\n    // reload would double the subscriptions.\n    await state.projection\n    const previousAgent = state.hostAgent ?? currentAgent(state)\n    if (previousAgent !== undefined) {\n      await shutdownPiSession(ctx, state, previousAgent, 'reload')\n      state.piShutdownAgents.delete(previousAgent)\n      state.shutdownTasks.delete(previousAgent)\n    }\n    state.extensionsReady = false\n    state.handlers.clear()\n    // The bus is agent-shared: unwind only this instance's subscriptions.\n    for (const off of state.eventBusOffs.splice(0)) off()\n    try {\n      await registerPromptCommands(ctx, state, rootDir, options.manifest)\n      await mountExtensions()\n      await restartReloadedPiSessions(ctx, state)\n    } finally {\n      // A failed per-entry import is isolated by loadExtensions, but keep the\n      // lifecycle gate usable even if host-owned prompt registration itself\n      // rejects before the remount completes.\n      state.extensionsReady = true\n    }\n  })\n  ctx.effect(() => () => { remounts.delete(state.packageName) })\n  const health = state.shared.capabilityLedger?.healthOf(state.packageName)\n  const healthSuffix = health === undefined || health.status === 'ok'\n    ? ''\n    : ` — ${health.status.toUpperCase()}: missing Pi capabilities ${health.gaps.join(', ')}`\n  logger(ctx).info(`[pi2dsh] loaded ${options.manifest.package.name}: ${state.tools.size} tools, ${state.commands.size} commands, ${options.manifest.skillDirs.length} skill roots${healthSuffix}${state.hostAnchor ? ' (host anchor)' : ''}`)\n}\n\nexport const runtimeInternals = {\n  compactionReason,\n  resolveOfferedChoice,\n  currentPiModel,\n  lastRequestRouteOf,\n  resolveCallerRoute,\n  resolveChildExtensionPackages,\n  dshToPiContent,\n  expandPrompt,\n  isKnownImageTool,\n  isSubagentOrigin,\n  normalizeToolResult,\n  splitArguments,\n  supersedeActiveLogin,\n  textBlocks,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAgB,kBAAkB,SAAsD;CACtF,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM,OAAO,CAAC;CAC7D,MAAM,QAAQ;CACd,MAAM,SAAS,OAAO,MAAM,mBAAmB,aAC3C,MAAM,eAAe,KAAK,OAAO,IACjC,OAAO,MAAM,WAAW,aAAa,MAAM,OAAO,KAAK,OAAO,IAAI,MAAM;CAC5E,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,MAAM,yEAAyE;CACrH,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAwC;CACtE,MAAM,S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