pi2dsh 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +22 -19
  2. package/README.zh.md +18 -15
  3. package/dist/{analyzer-CJFwQlSG.mjs → analyzer-DBtUYKI1.mjs} +2 -2
  4. package/dist/{analyzer-CJFwQlSG.mjs.map → analyzer-DBtUYKI1.mjs.map} +1 -1
  5. package/dist/anthropic-messages-CaYTgvLF.mjs +6436 -0
  6. package/dist/anthropic-messages-CaYTgvLF.mjs.map +1 -0
  7. package/dist/azure-openai-responses-HKWkzl2m.mjs +208 -0
  8. package/dist/azure-openai-responses-HKWkzl2m.mjs.map +1 -0
  9. package/dist/cli.mjs +3 -2
  10. package/dist/cli.mjs.map +1 -1
  11. package/dist/compat/pi-ai.d.mts +3 -2636
  12. package/dist/compat/pi-ai.mjs +3 -2
  13. package/dist/compat/pi-coding-agent.d.mts +2 -2
  14. package/dist/compat/pi-coding-agent.mjs +2 -2
  15. package/dist/{mcp-config-_idn-pzI.mjs → compatibility-Bz6ZXA7F.mjs} +8 -185
  16. package/dist/compatibility-Bz6ZXA7F.mjs.map +1 -0
  17. package/dist/completionchunk-Dhk56lZl.mjs +5212 -0
  18. package/dist/completionchunk-Dhk56lZl.mjs.map +1 -0
  19. package/dist/{credentials-oauth-Txs6oew8.mjs → credentials-oauth-CAohSLcB.mjs} +3 -3
  20. package/dist/{credentials-oauth-Txs6oew8.mjs.map → credentials-oauth-CAohSLcB.mjs.map} +1 -1
  21. package/dist/credentials-oauth.mjs +1 -1
  22. package/dist/deferred-tools-BD4g5QUx.mjs +32 -0
  23. package/dist/deferred-tools-BD4g5QUx.mjs.map +1 -0
  24. package/dist/diagnostics-BqYkodgB.mjs +35 -0
  25. package/dist/diagnostics-BqYkodgB.mjs.map +1 -0
  26. package/dist/dist-QBBA-dL_.mjs +1246 -0
  27. package/dist/dist-QBBA-dL_.mjs.map +1 -0
  28. package/dist/error-body-DKA3lknR.mjs +104 -0
  29. package/dist/error-body-DKA3lknR.mjs.map +1 -0
  30. package/dist/event-stream-QxN1yvIF.mjs +64 -0
  31. package/dist/event-stream-QxN1yvIF.mjs.map +1 -0
  32. package/dist/from-BCscBQ9P.mjs +3856 -0
  33. package/dist/from-BCscBQ9P.mjs.map +1 -0
  34. package/dist/github-copilot-headers-CZo2QHrt.mjs +25 -0
  35. package/dist/github-copilot-headers-CZo2QHrt.mjs.map +1 -0
  36. package/dist/google-generative-ai-2gCFYp-t.mjs +356 -0
  37. package/dist/google-generative-ai-2gCFYp-t.mjs.map +1 -0
  38. package/dist/google-shared-75IdVyrx.mjs +29041 -0
  39. package/dist/google-shared-75IdVyrx.mjs.map +1 -0
  40. package/dist/google-vertex-Bhyo4z2i.mjs +400 -0
  41. package/dist/google-vertex-Bhyo4z2i.mjs.map +1 -0
  42. package/dist/hash-Dbggamac.mjs +19 -0
  43. package/dist/hash-Dbggamac.mjs.map +1 -0
  44. package/dist/headers-CPzZhJQn.mjs +17 -0
  45. package/dist/headers-CPzZhJQn.mjs.map +1 -0
  46. package/dist/host.d.mts +12 -2
  47. package/dist/host.d.mts.map +1 -1
  48. package/dist/host.mjs +43 -5
  49. package/dist/host.mjs.map +1 -1
  50. package/dist/index.d.mts +5 -3
  51. package/dist/index.d.mts.map +1 -1
  52. package/dist/index.mjs +40 -16
  53. package/dist/index.mjs.map +1 -1
  54. package/dist/json-parse-CZ0U0sj_.mjs +384 -0
  55. package/dist/json-parse-CZ0U0sj_.mjs.map +1 -0
  56. package/dist/mcp-config-jmzbgdHa.mjs +181 -0
  57. package/dist/mcp-config-jmzbgdHa.mjs.map +1 -0
  58. package/dist/mistral-conversations-DJyeTo8C.mjs +36921 -0
  59. package/dist/mistral-conversations-DJyeTo8C.mjs.map +1 -0
  60. package/dist/multipart-parser-SRcGkVuX.mjs +301 -0
  61. package/dist/multipart-parser-SRcGkVuX.mjs.map +1 -0
  62. package/dist/{pi-ai-D7PqVeWs.mjs → openai-DkzRh5_G.mjs} +78 -5063
  63. package/dist/openai-DkzRh5_G.mjs.map +1 -0
  64. package/dist/openai-codex-responses-DedxQjNG.mjs +1220 -0
  65. package/dist/openai-codex-responses-DedxQjNG.mjs.map +1 -0
  66. package/dist/openai-completions-DrjrWRdX.mjs +945 -0
  67. package/dist/openai-completions-DrjrWRdX.mjs.map +1 -0
  68. package/dist/openai-prompt-cache-BDWtZRKh.mjs +11 -0
  69. package/dist/openai-prompt-cache-BDWtZRKh.mjs.map +1 -0
  70. package/dist/openai-responses-BRdGpBX6.mjs +251 -0
  71. package/dist/openai-responses-BRdGpBX6.mjs.map +1 -0
  72. package/dist/openai-responses-shared-BmnSvdKL.mjs +570 -0
  73. package/dist/openai-responses-shared-BmnSvdKL.mjs.map +1 -0
  74. package/dist/otel-CBhmS-NR.mjs +24935 -0
  75. package/dist/otel-CBhmS-NR.mjs.map +1 -0
  76. package/dist/pi-ai-CfokFhIL.d.mts +2673 -0
  77. package/dist/pi-ai-CfokFhIL.d.mts.map +1 -0
  78. package/dist/pi-ai-Dh7HUxbt.mjs +3239 -0
  79. package/dist/pi-ai-Dh7HUxbt.mjs.map +1 -0
  80. package/dist/{pi-coding-agent-B0PT23gE.d.mts → pi-coding-agent-69yY0ke-.d.mts} +4 -2
  81. package/dist/{pi-coding-agent-B0PT23gE.d.mts.map → pi-coding-agent-69yY0ke-.d.mts.map} +1 -1
  82. package/dist/{pi-coding-agent-BVZu0dHG.mjs → pi-coding-agent-Cvez0jkF.mjs} +0 -0
  83. package/dist/{pi-coding-agent-BVZu0dHG.mjs.map → pi-coding-agent-Cvez0jkF.mjs.map} +1 -1
  84. package/dist/pi-messages-D61G2tgs.mjs +307 -0
  85. package/dist/pi-messages-D61G2tgs.mjs.map +1 -0
  86. package/dist/provider-env-C72pF4vP.mjs +40 -0
  87. package/dist/provider-env-C72pF4vP.mjs.map +1 -0
  88. package/dist/provider-retry-Cw6YJ4cr.mjs +80 -0
  89. package/dist/provider-retry-Cw6YJ4cr.mjs.map +1 -0
  90. package/dist/rolldown-runtime-CTfmNlz1.mjs +44 -0
  91. package/dist/{runtime-DEjs_Qlf.mjs → runtime-Dd2KhoX-.mjs} +659 -125
  92. package/dist/runtime-Dd2KhoX-.mjs.map +1 -0
  93. package/dist/runtime.d.mts +135 -26
  94. package/dist/runtime.d.mts.map +1 -1
  95. package/dist/runtime.mjs +1 -1
  96. package/dist/simple-options-B_GO8FDE.mjs +456 -0
  97. package/dist/simple-options-B_GO8FDE.mjs.map +1 -0
  98. package/dist/src-DlTagfW5.mjs +1186 -0
  99. package/dist/src-DlTagfW5.mjs.map +1 -0
  100. package/dist/{types-7IWJPPvS.d.mts → types-B9VBF8le.d.mts} +2 -9
  101. package/dist/{types-7IWJPPvS.d.mts.map → types-B9VBF8le.d.mts.map} +1 -1
  102. package/package.json +2 -2
  103. package/dist/compat/pi-ai.d.mts.map +0 -1
  104. package/dist/mcp-config-_idn-pzI.mjs.map +0 -1
  105. package/dist/pi-ai-D7PqVeWs.mjs.map +0 -1
  106. package/dist/runtime-DEjs_Qlf.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-Dd2KhoX-.mjs","names":["dshToPiContent","#carried","#host","#handle","#session","#tools","#subscribers","#disposers","#activeToolNames","#project","#state","#model","#assignTranscript","#streaming","#pendingToolCalls","#seed","#messageProjection","#turns","#aborted","#sessionName","#byParent","#surfaces","#entrySources","#draftRequests","#liveDrafts","#completionSources","#imageToolNames","#view","#llm","#models","#resolved","#refreshing","#refreshOnce","#resolveExact"],"sources":["../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/runtime.ts"],"sourcesContent":["// Pi session semantics over a DSH durable session.\n//\n// DSH's append-only event log is authoritative for messages; Pi-only state\n// (custom entries, labels, a session name fallback) persists in a pi2dsh\n// sidecar JSONL next to DSH's home. The sidecar exists because DSH currently\n// has no channel for out-of-repo plugin events: `Session.append()` cannot set\n// the envelope's `ignorable: true`, so an unknown event type appended to the\n// main log would make other builds refuse to reload the whole session. Until\n// DSH grows that registration surface, the sidecar keeps Pi entries durable\n// and replayable without touching main-log compatibility.\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { foldSurface } from '@deepseek-ai/dsh-session'\nimport { getAgentDir } from './compat/vendor/pi-config-shim.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 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\nexport interface PiProjectedEntry {\n type: string\n id: string\n parentId: string | null\n timestamp: string\n [key: string]: unknown\n}\n\nfunction sidecarDir(): string {\n return join(getAgentDir(), 'session-entries')\n}\n\nfunction sessionEvents(session: DshSessionLike): readonly UnknownRecord[] {\n const events = session.events\n return typeof events === 'function' ? events.call(session) : events ?? []\n}\n\nfunction dshToPiContent(content: unknown): 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 === '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 private readonly records = new Map<string, SidecarRecord[]>()\n private readonly loaded = new Set<string>()\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 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 parsed.push(JSON.parse(line) as SidecarRecord)\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 mkdirSync(sidecarDir(), { recursive: true })\n appendFileSync(this.sidecarPath(sessionId), `${JSON.stringify(record)}\\n`)\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 type: 'message', id: `dsh-${seq}`, timestamp: new Date(time).toISOString(),\n message: { role: 'user', content: dshToPiContent(data.content) },\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) },\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: () => sidecarDir(),\n getSessionId: () => session.id,\n getSessionFile: () => this.sidecarPath(session.id),\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}\n\nexport interface CreateAgentSessionOptions {\n cwd?: string\n tools?: unknown[]\n customTools?: unknown[]\n model?: unknown\n thinkingLevel?: unknown\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/** 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 // 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 #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 #sessionName = ''\n #turns = 0\n /** Keeps message projections (which await attachment reads) in log order. */\n #messageProjection: Promise<unknown> = Promise.resolve()\n #aborted = false\n\n constructor(\n host: SubagentHost,\n handle: { agent: UnknownRecord, dispose(): Promise<void> },\n tools: unknown[],\n ) {\n this.#host = host\n this.#handle = handle\n this.#session = (handle.agent as { session?: UnknownRecord }).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 const cordis = host.cordis as unknown as {\n on(name: string, callback: (...args: any[]) => unknown): () => void\n }\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 this.#project(event)\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, 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 'off' },\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 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 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 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/chunk') {\n const chunk = ((event.data as UnknownRecord).chunk ?? {}) as UnknownRecord\n const delta = typeof chunk.text === 'string' ? chunk.text : typeof chunk.delta === 'string' ? chunk.delta : ''\n emit({\n type: 'message_update',\n message: { role: 'assistant', content: [{ type: 'text', text: delta }] },\n assistantMessageEvent: { type: 'text_delta', delta, ...chunk },\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 // 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 const cordis = this.#host.cordis as unknown as {\n on(name: string, callback: (...args: any[]) => unknown): () => void\n }\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 },\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 steer(text: string): void {\n void this.#host.piContentToDsh([{ type: 'text', text: String(text) }]).then(blocks => {\n this.#host.deliver(this.#handle.agent, createUserMessage({\n content: blocks,\n source: { kind: 'plugin', plugin: this.#host.messageSource },\n }), 'steer')\n })\n }\n\n abort(): void {\n this.#aborted = true\n // Pi's session.abort() is idempotent and safe at any lifecycle point;\n // DSH's Agent.cancel throws once the agent is disposed, so contain it.\n try {\n const cancel = (this.#handle.agent as { cancel?: (reason: UnknownRecord) => void }).cancel\n cancel?.({ kind: 'hook', reason: 'pi2dsh subagent abort()' })\n } catch {\n // already disposed — nothing left to abort\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 getAllTools(): unknown[] {\n return [...this.#tools]\n }\n\n getActiveToolNames(): string[] {\n return [...this.#activeToolNames]\n }\n\n setActiveToolsByName(names: string[]): void {\n this.#activeToolNames = names.filter(name => typeof name === 'string')\n }\n\n async bindExtensions(_bindings: UnknownRecord = {}): Promise<void> {\n // The parent pi2dsh runtime already owns extension binding for the host\n // composition; a child session shares those registrations. Kept as an\n // accepted no-op so Pi's construction sequence proceeds unchanged.\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 | { create?: (options: UnknownRecord) => Promise<{ agent: UnknownRecord, dispose(): Promise<void> }> }\n | undefined\n if (agents?.create === undefined) {\n throw new Error('pi2dsh: createAgentSession() needs the DSH agent registry in the host composition')\n }\n subagentSerial += 1\n const sessionId = `pi2dsh-sub-${Date.now().toString(36)}-${subagentSerial}`\n let handle\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 handle = await agents.create({\n sessionId,\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 },\n ...(typeof requestedModel?.id === 'string' && requestedModel.id.length > 0\n ? {\n agentOptions: {\n model: requestedModel.id,\n ...(typeof requestedModel.provider === 'string' && requestedModel.provider.length > 0\n ? { provider: requestedModel.provider }\n : {}),\n },\n }\n : {}),\n })\n // Registered through the child's own Agent.ctx: ctx.get() returns a\n // caller-bound service view, so the section lands in this agent's scope\n // layer (dsh-scope kScope tag on Agent.ctx) and unwinds on disposal —\n // never visible to the parent or sibling sessions. `complete: true` is\n // DSH's sole-prompt-section semantics, matching Pi's systemPromptOverride\n // replacing the default prompt.\n if (systemPrompt !== undefined) {\n const agentCtx = (handle.agent as { ctx?: { get?(name: string): unknown } }).ctx\n const prompt = (typeof agentCtx?.get === 'function' ? agentCtx.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 } catch (error) {\n throw new Error(\n 'pi2dsh: subagent creation needs the DSH host loop (model runtime) to provide the agent factory; '\n + `this composition cannot run one (${error instanceof Error ? error.message : String(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 if (typeof childSession?.append === 'function') {\n try {\n childSession.append('subagent/descriptor', {\n version: 2,\n mode: 'continuable',\n provider: 'pi2dsh',\n label: 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 return { session: new PiBridgedAgentSession(host, handle, tools) }\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/** 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 readonly #byParent = new Map<string, Map<string, TrackedThread>>()\n // session -> package -> what that package put on screen\n readonly #surfaces = new Map<string, Map<string, SurfaceView>>()\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 * 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 .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 text = surfaceText(content, theme)\n if (text === undefined) delete view.widgets[key]\n else view.widgets[key] = text\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\nexport function registerBrowserSurfaceRoute(ctx: Context, registry: BrowserSurfaces): 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 // 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 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 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 model.reasoning = Array.isArray(reasoning?.efforts) && reasoning.efforts.length > 0\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 ...(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 // 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 Array.isArray(options.messages) ? options.messages as UnknownRecord[] : []) {\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 Array.isArray(options.messages) ? options.messages as UnknownRecord[] : []) {\n const content = Array.isArray(message.content) ? message.content as UnknownRecord[] : []\n const source = message.source as { kind?: unknown } | undefined\n 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 ...(typeof options.system === 'string' && options.system.length > 0 ? { systemPrompt: options.system } : {}),\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 { 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 */\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 {\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 {\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 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>>\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\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\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 {\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 handles `/mcp` locally before it asks DSH's command registry. Until\n * it exposes a reserved-command seam, keep its native status command and make\n * an installed Pi MCP manager reachable as `/pi-mcp`.\n */\nexport function commandNameForDshTui(name: string, tuiAvailable: boolean): string {\n return tuiAvailable && name === 'mcp' ? 'pi-mcp' : name\n}\n\nexport const tuiSurfaceInternals = {\n rawTerminalInput,\n sceneIdFor,\n statusKeyFor,\n}\n","// TODO: 拆解本文件(2026-08-20 用户拍板,待做)。~3.9k 行承载了包挂载、\n// SharedHostState、模型目录投影、/login 与凭证恢复、伴生路由、命令/工具/\n// 事件桥等多个职责。拆法必须跟着架构走:按 CLAUDE.md 三层结构与 host 级/\n// 包级资源边界切模块,纯搬家不改逻辑;动手前先给出切分方案对齐再执行。\nimport { access, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { 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 { join } 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 { 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 } 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'\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 './credentials-oauth.js'\nimport {\n commandNameForDshTui,\n mountTuiSurfaceAdapter,\n type PiCustomFactory,\n type PiCustomOptions,\n type TuiSurfaceAdapter,\n type TuiSurfaceContext,\n} from './tui-surfaces.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\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 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 // 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 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 currentSystemPrompt: string\n messageSource: string\n eventBus: EventEmitter\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 // 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 // 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, present only in a composition that\n // mounts dsh-TUI's public `tuiScenes` service.\n tuiSurfaces: TuiSurfaceAdapter | 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 const result = await service.ask({ questions: [question], ...(agent !== undefined ? { agent } : {}), signal })\n return answerText(result.answers.find(answer => answer.id === question.id))\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 selectedProvider = String(override?.provider ?? options?.provider ?? '')\n const provider = state.companionRoutes.get(selectedProvider) ?? selectedProvider\n const id = String(override?.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/** A session's durable events, whether the store exposes them as value or method. */\nfunction eventsOf(session: UnknownRecord): readonly UnknownRecord[] {\n const events = (session as { events?: unknown }).events\n if (typeof events === 'function') return (events as () => readonly UnknownRecord[]).call(session) ?? []\n return Array.isArray(events) ? events as readonly UnknownRecord[] : []\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\nfunction contextFor(\n ctx: Context,\n state: RuntimeState,\n agent: UnknownRecord | undefined,\n signal: AbortSignal | undefined,\n command = false,\n sessionOverride?: UnknownRecord,\n): UnknownRecord {\n const notices: string[] = []\n const userQuestions = optionalService(ctx, 'userQuestions')\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[], promptSignal?: unknown) => {\n const labels = options.map(option => String(option))\n const answered = await askOne(ctx, agent, joinSignals(signal, promptSignal), {\n id: 'pi2dsh-select',\n question: String(title),\n options: labels.map(label => ({ label })),\n })\n return answered === undefined ? undefined : resolveOfferedChoice(answered, labels)\n },\n async confirm(title: unknown, message: unknown) {\n return await askOne(ctx, agent, signal, {\n id: 'pi2dsh-confirm',\n question: String(title),\n detail: String(message),\n options: [{ label: 'Yes' }, { label: 'No' }],\n }) === 'Yes'\n },\n // The optional third argument is additive: Pi's own ui.input takes two, but\n // pi-ai's OAuth flows hand each prompt its OWN abort signal and cancel it\n // when another path wins (the browser callback beating the paste box). Not\n // honouring it left that box on screen after the login had already\n // succeeded elsewhere.\n input: (title: unknown, placeholder?: unknown, promptSignal?: unknown) => askOne(\n ctx, agent, joinSignals(signal, promptSignal), {\n id: 'pi2dsh-input',\n question: String(title),\n ...(placeholder === undefined ? {} : { detail: String(placeholder) }),\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, promptSignal?: unknown) => {\n await askOne(ctx, agent, joinSignals(signal, promptSignal), {\n id: 'pi2dsh-device-code',\n question: String(title),\n detail: String(detail),\n options: [{ label: 'Cancel login' }],\n })\n },\n editor: (title: unknown, prefill?: unknown) => askOne(ctx, agent, signal, {\n id: 'pi2dsh-editor',\n question: String(title),\n ...(prefill === undefined ? {} : { detail: `Current text:\\n${String(prefill)}` }),\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. Browser/headless compositions\n // keep Pi's own rpc-mode behavior and resolve undefined.\n custom: async (factory: unknown, options?: unknown) => {\n const surfaces = state.tuiSurfaces\n if (surfaces === undefined || typeof factory !== 'function') return undefined\n return surfaces.custom(\n factory as PiCustomFactory<unknown>,\n state.theme,\n getKeybindings(),\n options as PiCustomOptions | undefined,\n )\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 getRegisteredProviderConfig: (provider: string) => providerConfig(provider),\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) => 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 get mode(): 'tui' | 'rpc' { return state.tuiSurfaces?.available === true ? 'tui' : 'rpc' },\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)\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 isProjectTrusted: () => false,\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: () => (agent as { inbox?: { hasPending?: unknown } } | undefined)?.inbox?.hasPending === true,\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 = ((source as { events?: readonly UnknownRecord[] }).events ?? []) as readonly UnknownRecord[]\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 = ((source as { events?: readonly UnknownRecord[] }).events ?? []) as readonly UnknownRecord[]\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 = 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\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 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 { role: 'user', content: await dshToPiContent(ctx, (record.content ?? []) as ContentBlock[]) }\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\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 && !state.piShutdownAgents.has(previous)) {\n state.piShutdownAgents.add(previous)\n releasePiSessionClaim(state, previous)\n await runInPiRuntime(state, previous, () => dispatch(\n state,\n 'session_shutdown',\n { type: 'session_shutdown', reason: replacementReason(reason) },\n contextFor(ctx, state, previous, signal),\n ))\n }\n\n if (typeof agent === 'object' && agent !== null) {\n state.hostAgent = agent\n state.piShutdownAgents.delete(agent)\n }\n if (!claimPiSessionStart(state, agent)) return\n try {\n await dispatch(\n state,\n 'session_start',\n { type: 'session_start', reason: transitionReason },\n contextFor(ctx, state, agent, signal),\n )\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.piShutdownAgents.add(agent)\n state.hostAgent = undefined\n void dispatch(state, 'session_shutdown', { type: 'session_shutdown', reason: 'quit' }, contextFor(ctx, state, agent, undefined))\n .catch(error => warn('session_shutdown', error))\n }\n }\n })\n\n cordis.on('session/event', (session: UnknownRecord, event: UnknownRecord) => {\n const ownedSession = agentSession(state.ownerAgent)\n if (ownedSession !== undefined ? session !== ownedSession : isSubagentOrigin(session)) return\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 = ((session.events ?? []) as UnknownRecord[]).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,\n }, eventContext).catch(error => warn('tool_execution_start', error))\n }\n if (type === 'assistant/chunk' && (state.handlers.get('message_update')?.length ?? 0) > 0) {\n const data = event.data as UnknownRecord\n const chunk = (data.chunk ?? {}) as UnknownRecord\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 void dispatch(state, 'message_update', {\n type: 'message_update',\n message: { role: 'assistant', content: [{ type: 'text', text: accumulated }] },\n assistantMessageEvent: chunk,\n }, eventContext).catch(error => warn('message_update', error))\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 void 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 }\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 void 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).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\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' ? {} : { reasoningEffort: thinking }),\n }\n })\n\n\n cordis.effect(() => async () => {\n const agent = state.hostAgent\n if (typeof agent === 'object' && agent !== null && !state.piShutdownAgents.has(agent)) {\n state.piShutdownAgents.add(agent)\n state.disposedAgents.add(agent)\n await dispatch(state, 'session_shutdown', { type: 'session_shutdown', reason: 'quit' }, contextFor(ctx, state, agent, undefined))\n }\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 state.eventBus.removeAllListeners()\n }, 'pi2dsh session shutdown')\n}\n\nasync function flushPendingSessionStarts(ctx: Context, state: RuntimeState): Promise<void> {\n state.extensionsReady = true\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}\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 }\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 input = cloneJson(exec.arguments)\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, exec.arguments)) {\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: cloneJson(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 if (systemPrompt !== undefined) {\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: {},\n }\n const results = await dispatch(state, 'before_agent_start', event, contextFor(ctx, state, agent, signal))\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 if (typeof record.systemPrompt === 'string') {\n state.turnSystemPromptOverrides.set(agent, record.systemPrompt)\n event.systemPrompt = record.systemPrompt\n }\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// 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 ((session?.events ?? []) as UnknownRecord[])) {\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 const blocks = await piToDshContent(ctx, typeof shape.content === 'string'\n ? [{ type: 'text', text: shape.content }]\n : shape.content ?? [])\n rebuilt.push(createUserMessage({\n content: blocks,\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 providers: Map<string, UnknownRecord>\n modelCatalog?: ModelCatalog\n catalogSubscribed?: boolean\n loginRegistered?: WeakSet<object>\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}\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\nconst SHARED_HOST_STATE = new WeakMap<object, SharedHostState>()\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. Commands are Agent-scoped,\n// while the provider directory they read is host-shared, so register one\n// command per Agent regardless of how many Pi packages that Agent mounts.\nfunction ensureLoginCommand(ctx: Context, state: RuntimeState): void {\n const scoped = scopeOf(ctx)\n const owner = (typeof scoped === 'object' && scoped !== null ? scoped : ctx) as object\n const registered = (state.shared.loginRegistered ??= new WeakSet())\n if (registered.has(owner)) return\n registered.add(owner)\n try {\n registerLoginCommand(ctx, state)\n } catch (error) {\n registered.delete(owner)\n logger(ctx).warn(`[pi2dsh] /login is already registered by an earlier package in this host; this package's providers use that command (${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 */\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\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 {\n input(title: unknown, placeholder?: unknown): Promise<string | undefined>\n select(title: unknown, options: unknown[]): Promise<string | undefined>\n notify(message: unknown): void\n deviceCode?(title: unknown, detail: unknown, signal?: AbortSignal): Promise<void>\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 const oauthName = ((config.oauth as UnknownRecord | undefined)?.name as string | undefined) ?? providerId\n const commandSignal = commandContext.signal as AbortSignal | undefined\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 (commandSignal !== undefined) {\n if (commandSignal.aborted) active.controller.abort()\n else commandSignal.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\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 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\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 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'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 ? {} : { 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): 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, undefined, operation.signal)\n const collect = { maxBytes: 64 * 1024 * 1024 }\n const handle = service.spawn({\n argv: [executable, ...args],\n cwd: options.cwd ?? cwd,\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 tuiAvailable = state.tuiSurfaces?.available === true || optionalService(ctx, 'tuiScenes') !== undefined\n const name = commandNameForDshTui(validName, tuiAvailable)\n if (name !== piName) {\n const reason = name === 'pi-mcp'\n ? \"because dsh-TUI reserves /mcp for its native MCP status view\"\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 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 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(userQuestions: unknown, agent: UnknownRecord | undefined): 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') return false\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 const canonical = shared.providers.get(name) ?? value\n 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\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) {\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 (!state.shared.providers.has(name)) state.shared.providers.set(name, value)\n if (providerSupportsOAuth(value)) {\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 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, value)\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(value)) {\n logger(ctx).info(`[pi2dsh] Pi provider ${JSON.stringify(name)} registered as a native DSH llm route`)\n }\n } else if (!providerSupportsOAuth(value)) {\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, value)\n },\n unregisterProvider(name: string) {\n state.providers.delete(name)\n releaseSharedProviderRoute(state, name)\n },\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 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 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 exec(command: string, args: string[] = [], options: PiExecOptions = {}) {\n const service = optionalService<DshSubprocessService>(ctx, 'subprocess')\n if (service === undefined) unsupported('exec')\n return executePiCommand(service, cwdOf(currentAgent(state)), command, args, options)\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 })),\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 return () => state.eventBus.off(channel, safeHandler)\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 const infraImport = /import[^;]*?\\b(ModelRuntime|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 const state: RuntimeState = {\n shared,\n packageName: options.manifest.package.name,\n ownerAgent,\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 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 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 currentSystemPrompt: '',\n messageSource: `pi2dsh:${options.manifest.package.name}`,\n eventBus: new EventEmitter(),\n agentScope: new AsyncLocalStorage(),\n llmBridge: undefined,\n piAiRegistry: __createPiAiRuntimeRegistry(),\n subagentSessionFactory: undefined,\n bridge: new PiSessionBridge(),\n theme: new Theme(),\n shortcuts: new Map(),\n messageRenderers: new Map(),\n entryRenderers: new Map(),\n providers: new Map(),\n autocompleteProviders: [],\n editorBuffers: new WeakMap(),\n toolsExpanded: false,\n modelOverrides: new WeakMap(),\n thinkingLevels: new WeakMap(),\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 // dsh-TUI is optional and may be mounted before or after this package.\n // Cordis keeps the child activation aligned with the service lifecycle;\n // by the time a terminal command executes, context.mode/hasUI and\n // ui.custom reflect whether the real terminal surface is available.\n mountTuiSurfaceAdapter(\n ctx as unknown as TuiSurfaceContext,\n state.packageName,\n adapter => { state.tuiSurfaces = adapter },\n typeof ownerAgent?.id === 'string'\n ? ownerAgent.id\n : undefined,\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.\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.providers.has(provider.id)) shared.providers.set(provider.id, config)\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 ensureLoggedInProviderRoute(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 if (options.manifest.skillDirs.length > 0) {\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 const browserSurfaces = state.shared.browserSurfaces ??= new BrowserSurfaces()\n if (state.shared.browserSurfacesRouted !== true) {\n state.shared.browserSurfacesRouted = registerBrowserSurfaceRoute(ctx, browserSurfaces)\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 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 })\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: symbol === 'DefaultPackageManager'\n ? 'installing packages is owned by the DSH host and its security gates (dsh plugin add/remove).'\n : \"standalone model stacks are owned by the DSH host llm configuration (packages read ctx.modelRegistry).\",\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 state.extensionsReady = false\n state.handlers.clear()\n state.eventBus.removeAllListeners()\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}`)\n}\n\nexport const runtimeInternals = {\n compactionReason,\n resolveOfferedChoice,\n dshToPiContent,\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