pi2dsh 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/README.zh.md +11 -0
- package/dist/cli.mjs +1 -1
- package/dist/compat/pi-coding-agent.mjs +1 -1
- package/dist/credentials-oauth.mjs +1 -1
- package/dist/host.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{mcp-config-B3h5jTBb.mjs → mcp-config-ByUc0jmD.mjs} +3 -3
- package/dist/mcp-config-ByUc0jmD.mjs.map +1 -0
- package/dist/{pi-coding-agent-COMX0KHL.mjs → pi-coding-agent-C9Y9ql5E.mjs} +2 -2
- package/dist/{pi-coding-agent-COMX0KHL.mjs.map → pi-coding-agent-C9Y9ql5E.mjs.map} +1 -1
- package/dist/{runtime-B7mEIRf-.mjs → runtime-VK4eVnYa.mjs} +153 -5
- package/dist/runtime-VK4eVnYa.mjs.map +1 -0
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +1 -1
- package/package.json +1 -1
- package/dist/mcp-config-B3h5jTBb.mjs.map +0 -1
- package/dist/runtime-B7mEIRf-.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -94,6 +94,23 @@ node dist/cli.mjs mcp-config # Pi mcpServers → DSH patc
|
|
|
94
94
|
dsh plugin --profile headless add file:$PWD/pi-host
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
+
## Examples: copy-paste working capabilities
|
|
98
|
+
|
|
99
|
+
**Every verified capability ships as a complete, runnable example under
|
|
100
|
+
[`examples/`](examples/)** — clone the repo, follow one example's README from
|
|
101
|
+
zero to seeing the feature run. Every command in an example has actually been
|
|
102
|
+
executed against a real DSH loop (CLI and web) before landing here; nothing
|
|
103
|
+
is aspirational.
|
|
104
|
+
|
|
105
|
+
| Example | What you get |
|
|
106
|
+
|---|---|
|
|
107
|
+
| [`examples/vision-bridge`](examples/vision-bridge/) | A text-only model answers questions about images: mention an image path, a configured vision model reads it, the analysis is injected into the conversation (works in CLI and the DSH web app; probe images included) |
|
|
108
|
+
| [`examples/custom-models`](examples/custom-models/) | Define a provider once in Pi's standard `models.json` — it becomes a native DSH llm route: visible in the DSH web model picker, usable as the main model, and resolvable/callable by every Pi plugin through one directory |
|
|
109
|
+
|
|
110
|
+
More verified capabilities (approval guardian, cross-session memory,
|
|
111
|
+
interactive OAuth, MCP config conversion, host mode) get their examples as
|
|
112
|
+
each one is re-verified end to end under the same bar.
|
|
113
|
+
|
|
97
114
|
## Interactive OAuth: sign in with your subscription
|
|
98
115
|
|
|
99
116
|
DSH ships static HTTP headers only; pi2dsh adds the interactive OAuth layer from the Pi ecosystem. Any Pi provider package that registers an `oauth` block gets a working `/login <provider>` command on DSH, driven by the package's own protocol code. Pi's four official flows ship built in (vendored byte-identical): **OpenAI Codex (ChatGPT Plus/Pro)**, **Anthropic**, **GitHub Copilot**, **Kimi Code**.
|
package/README.zh.md
CHANGED
|
@@ -94,6 +94,17 @@ node dist/cli.mjs mcp-config # Pi mcpServers → DSH patc
|
|
|
94
94
|
dsh plugin --profile headless add file:$PWD/pi-host
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
+
## Examples:每个能力都有完整可跑的示例
|
|
98
|
+
|
|
99
|
+
**每个已验证的能力,都在 [`examples/`](examples/) 下有一份完整可直接运行的示例**——克隆仓库,照任意一个示例的 README 从零走到看到效果。示例里的每条命令都在真实 DSH loop(CLI 和 Web 双端)上实际执行过才收录,没有"理论上可以"的内容。
|
|
100
|
+
|
|
101
|
+
| 示例 | 你得到什么 |
|
|
102
|
+
|---|---|
|
|
103
|
+
| [`examples/vision-bridge`](examples/vision-bridge/) | 纯文本模型回答图片问题:消息里带图片路径,配置的视觉模型识图,分析结果注入对话(CLI 与 DSH Web 都能用;附探针测试图) |
|
|
104
|
+
| [`examples/custom-models`](examples/custom-models/) | 在 Pi 标准 `models.json` 里定义一次 provider——它成为原生 DSH llm 路由:出现在 DSH Web 模型选择器、可当主模型对话、所有 Pi 插件经同一个目录可见可调 |
|
|
105
|
+
|
|
106
|
+
更多已验证能力(审批 guardian、跨会话记忆、交互式 OAuth、MCP 配置转换、host 模式)的示例,将按同一标准逐个重新端到端验证后补齐。
|
|
107
|
+
|
|
97
108
|
## 交互式 OAuth:用你的订阅账号登录
|
|
98
109
|
|
|
99
110
|
DSH 原生只有静态 HTTP headers;pi2dsh 把 Pi 生态的交互式 OAuth 层带了过来。任何注册了 `oauth` 块的 Pi provider 包,在 DSH 上都直接获得可用的 `/login <provider>` 命令,登录流程由包自己的协议代码驱动。Pi 的四条官方流内建(vendored 字节级):**OpenAI Codex(ChatGPT Plus/Pro)**、**Anthropic**、**GitHub Copilot**、**Kimi Code**。
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as analyzePackage, c as EVENT_RULES, i as generateBundle, l as HOST_IMPORT_RULES, n as convertPiMcpConfig, o as API_RULES, p as UI_CONTEXT_RULES, r as renderMcpPatch, s as CONTEXT_RULES } from "./mcp-config-
|
|
2
|
+
import { a as analyzePackage, c as EVENT_RULES, i as generateBundle, l as HOST_IMPORT_RULES, n as convertPiMcpConfig, o as API_RULES, p as UI_CONTEXT_RULES, r as renderMcpPatch, s as CONTEXT_RULES } from "./mcp-config-ByUc0jmD.mjs";
|
|
3
3
|
import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
|
|
4
4
|
import { writeFileSync } from "node:fs";
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
2
|
import { t as getAgentDir } from "../pi-config-shim-CZ1wFzqM.mjs";
|
|
3
|
-
import { $ as isBashToolResult, $t as buildSessionContext, A as copyToClipboard, At as createGrepToolDefinition, B as generateSummary, Bt as createLocalBashOperations, C as ToolExecutionComponent, Ct as wrapRegisteredTool, D as calculateContextTokens, Dt as createFindTool, E as __setSubagentSessionFactory, Et as createLsToolDefinition, F as defineTool, Ft as createReadTool, G as getPackageDir, Gt as formatSize, H as getBinDir, Ht as withFileMutationQueue, I as ensureTool, It as createReadToolDefinition, J as getSettingsListTheme, Jt as truncateTail, K as getReadmePath, Kt as truncateHead, L as estimateTokens, Lt as bashToolSystemPromptContribution, M as createCodingTools, Mt as createWriteToolDefinition, N as createEventBus, Nt as createEditTool, O as compact, Ot as createFindToolDefinition, P as createReadOnlyTools, Pt as createEditToolDefinition, Q as initTheme, Qt as buildContextEntries, R as findCutPoint, Rt as createBashTool, S as Theme, St as truncateToVisualLines, T as VERSION, Tt as createLsTool, U as getLanguageFromPath, Ut as DEFAULT_MAX_BYTES, V as generateSummaryWithUsage, Vt as createExtensionRuntime, W as getMarkdownTheme, Wt as DEFAULT_MAX_LINES, X as getToolPath, Xt as SessionManager, Y as getShellConfig, Yt as CURRENT_SESSION_VERSION, Z as highlightCode, Zt as assertValidSessionId, _ as ModelRegistry, _t as resizeImage, a as CustomMessageComponent, an as parseSessionEntries, at as isToolCallEventType, b as SettingsManager, bt as stripFrontmatter, c as DefaultResourceLoader, cn as BRANCH_SUMMARY_SUFFIX, ct as keyText, d as ExtensionInputComponent, dn as bashExecutionToText, dt as parseFrontmatter, en as findMostRecentSession, et as isEditToolResult, f as ExtensionRunner, fn as convertToLlm, ft as parseSkillBlock, g as InMemorySettingsStorage, gt as renderDiff, h as FooterComponent, hn as createCustomMessage, ht as readStoredCredential, i as CustomEditor, in as migrateSessionEntries, it as isReadToolResult, j as createAgentSession, jt as createWriteTool, k as convertToPng, kt as createGrepTool, l as DynamicBorder, ln as COMPACTION_SUMMARY_PREFIX, lt as loadSkills, m as FileSettingsStorage, mn as createCompactionSummaryMessage, mt as rawKeyHint, n as BorderedLoader, nn as getLatestCompactionEntry, nt as isGrepToolResult, o as DEFAULT_COMPACTION_SETTINGS, on as sessionEntryToContextMessages, ot as isWriteToolResult, p as ExtensionSelectorComponent, pn as createBranchSummaryMessage, pt as processImage, q as getSelectListTheme, qt as truncateLine, r as CONFIG_DIR_NAME, rn as loadEntriesFromFile, rt as isLsToolResult, s as DefaultPackageManager, sn as BRANCH_SUMMARY_PREFIX, st as keyHint, t as AssistantMessageComponent, tn as getDefaultSessionDir, tt as isFindToolResult, u as ExtensionEditorComponent, un as COMPACTION_SUMMARY_SUFFIX, ut as loadSkillsFromDir, v as ModelRuntime, vt as serializeConversation, w as UserMessageComponent, wt as formatSkillsForPrompt, x as SettingsSelectorComponent, xt as theme, y as ProjectTrustStore, yt as shouldCompact, z as generateBranchSummary, zt as createBashToolDefinition } from "../pi-coding-agent-
|
|
3
|
+
import { $ as isBashToolResult, $t as buildSessionContext, A as copyToClipboard, At as createGrepToolDefinition, B as generateSummary, Bt as createLocalBashOperations, C as ToolExecutionComponent, Ct as wrapRegisteredTool, D as calculateContextTokens, Dt as createFindTool, E as __setSubagentSessionFactory, Et as createLsToolDefinition, F as defineTool, Ft as createReadTool, G as getPackageDir, Gt as formatSize, H as getBinDir, Ht as withFileMutationQueue, I as ensureTool, It as createReadToolDefinition, J as getSettingsListTheme, Jt as truncateTail, K as getReadmePath, Kt as truncateHead, L as estimateTokens, Lt as bashToolSystemPromptContribution, M as createCodingTools, Mt as createWriteToolDefinition, N as createEventBus, Nt as createEditTool, O as compact, Ot as createFindToolDefinition, P as createReadOnlyTools, Pt as createEditToolDefinition, Q as initTheme, Qt as buildContextEntries, R as findCutPoint, Rt as createBashTool, S as Theme, St as truncateToVisualLines, T as VERSION, Tt as createLsTool, U as getLanguageFromPath, Ut as DEFAULT_MAX_BYTES, V as generateSummaryWithUsage, Vt as createExtensionRuntime, W as getMarkdownTheme, Wt as DEFAULT_MAX_LINES, X as getToolPath, Xt as SessionManager, Y as getShellConfig, Yt as CURRENT_SESSION_VERSION, Z as highlightCode, Zt as assertValidSessionId, _ as ModelRegistry, _t as resizeImage, a as CustomMessageComponent, an as parseSessionEntries, at as isToolCallEventType, b as SettingsManager, bt as stripFrontmatter, c as DefaultResourceLoader, cn as BRANCH_SUMMARY_SUFFIX, ct as keyText, d as ExtensionInputComponent, dn as bashExecutionToText, dt as parseFrontmatter, en as findMostRecentSession, et as isEditToolResult, f as ExtensionRunner, fn as convertToLlm, ft as parseSkillBlock, g as InMemorySettingsStorage, gt as renderDiff, h as FooterComponent, hn as createCustomMessage, ht as readStoredCredential, i as CustomEditor, in as migrateSessionEntries, it as isReadToolResult, j as createAgentSession, jt as createWriteTool, k as convertToPng, kt as createGrepTool, l as DynamicBorder, ln as COMPACTION_SUMMARY_PREFIX, lt as loadSkills, m as FileSettingsStorage, mn as createCompactionSummaryMessage, mt as rawKeyHint, n as BorderedLoader, nn as getLatestCompactionEntry, nt as isGrepToolResult, o as DEFAULT_COMPACTION_SETTINGS, on as sessionEntryToContextMessages, ot as isWriteToolResult, p as ExtensionSelectorComponent, pn as createBranchSummaryMessage, pt as processImage, q as getSelectListTheme, qt as truncateLine, r as CONFIG_DIR_NAME, rn as loadEntriesFromFile, rt as isLsToolResult, s as DefaultPackageManager, sn as BRANCH_SUMMARY_PREFIX, st as keyHint, t as AssistantMessageComponent, tn as getDefaultSessionDir, tt as isFindToolResult, u as ExtensionEditorComponent, un as COMPACTION_SUMMARY_SUFFIX, ut as loadSkillsFromDir, v as ModelRuntime, vt as serializeConversation, w as UserMessageComponent, wt as formatSkillsForPrompt, x as SettingsSelectorComponent, xt as theme, y as ProjectTrustStore, yt as shouldCompact, z as generateBranchSummary, zt as createBashToolDefinition } from "../pi-coding-agent-C9Y9ql5E.mjs";
|
|
4
4
|
export { AssistantMessageComponent, BRANCH_SUMMARY_PREFIX, BRANCH_SUMMARY_SUFFIX, BorderedLoader, COMPACTION_SUMMARY_PREFIX, COMPACTION_SUMMARY_SUFFIX, CONFIG_DIR_NAME, CURRENT_SESSION_VERSION, CustomEditor, CustomMessageComponent, DEFAULT_COMPACTION_SETTINGS, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, DefaultPackageManager, DefaultResourceLoader, DynamicBorder, ExtensionEditorComponent, ExtensionInputComponent, ExtensionRunner, ExtensionSelectorComponent, FileSettingsStorage, FooterComponent, InMemorySettingsStorage, ModelRegistry, ModelRuntime, ProjectTrustStore, SessionManager, SettingsManager, SettingsSelectorComponent, Theme, ToolExecutionComponent, UserMessageComponent, VERSION, __setSubagentSessionFactory, assertValidSessionId, bashExecutionToText, bashToolSystemPromptContribution, buildContextEntries, buildSessionContext, calculateContextTokens, compact, convertToLlm, convertToPng, copyToClipboard, createAgentSession, createBashTool, createBashToolDefinition, createBranchSummaryMessage, createCodingTools, createCompactionSummaryMessage, createCustomMessage, createEditTool, createEditToolDefinition, createEventBus, createExtensionRuntime, createFindTool, createFindToolDefinition, createGrepTool, createGrepToolDefinition, createLocalBashOperations, createLsTool, createLsToolDefinition, createReadOnlyTools, createReadTool, createReadToolDefinition, createWriteTool, createWriteToolDefinition, defineTool, ensureTool, estimateTokens, findCutPoint, findMostRecentSession, formatSize, formatSkillsForPrompt, generateBranchSummary, generateSummary, generateSummaryWithUsage, getAgentDir, getBinDir, getDefaultSessionDir, getLanguageFromPath, getLatestCompactionEntry, getMarkdownTheme, getPackageDir, getReadmePath, getSelectListTheme, getSettingsListTheme, getShellConfig, getToolPath, highlightCode, initTheme, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, keyHint, keyText, loadEntriesFromFile, loadSkills, loadSkillsFromDir, migrateSessionEntries, parseFrontmatter, parseSessionEntries, parseSkillBlock, processImage, rawKeyHint, readStoredCredential, renderDiff, resizeImage, serializeConversation, sessionEntryToContextMessages, shouldCompact, stripFrontmatter, theme, truncateHead, truncateLine, truncateTail, truncateToVisualLines, withFileMutationQueue, wrapRegisteredTool };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
import { a as builtinProviders } from "./pi-ai-B_88Wb0r.mjs";
|
|
3
3
|
import { t as getAgentDir } from "./pi-config-shim-CZ1wFzqM.mjs";
|
|
4
|
-
import "./pi-coding-agent-
|
|
4
|
+
import "./pi-coding-agent-C9Y9ql5E.mjs";
|
|
5
5
|
import { i as resolveOAuthApiKey, o as storedOAuthCredential, r as providerSupportsOAuth, t as FileCredentialStore } from "./oauth-bridge-C6fL1qSv.mjs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { CredentialProvider } from "@deepseek-ai/dsh-credentials";
|
package/dist/host.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { t as applyPiPackage } from "./runtime-
|
|
2
|
+
import { t as applyPiPackage } from "./runtime-VK4eVnYa.mjs";
|
|
3
3
|
import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as ruleForHostImport, a as analyzePackage, c as EVENT_RULES, d as PI_CODING_AGENT_PACKAGES, f as PI_TUI_PACKAGES, g as ruleForEvent, h as ruleForContextProperty, i as generateBundle, l as HOST_IMPORT_RULES, m as ruleForApi, n as convertPiMcpConfig, o as API_RULES, p as UI_CONTEXT_RULES, r as renderMcpPatch, s as CONTEXT_RULES, t as collectPiMcpServers, u as PI_AI_PACKAGES, v as ruleForUiContextProperty } from "./mcp-config-
|
|
2
|
+
import { _ as ruleForHostImport, a as analyzePackage, c as EVENT_RULES, d as PI_CODING_AGENT_PACKAGES, f as PI_TUI_PACKAGES, g as ruleForEvent, h as ruleForContextProperty, i as generateBundle, l as HOST_IMPORT_RULES, m as ruleForApi, n as convertPiMcpConfig, o as API_RULES, p as UI_CONTEXT_RULES, r as renderMcpPatch, s as CONTEXT_RULES, t as collectPiMcpServers, u as PI_AI_PACKAGES, v as ruleForUiContextProperty } from "./mcp-config-ByUc0jmD.mjs";
|
|
3
3
|
import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
|
|
4
4
|
import { applyPiHost, generateHostBundle, manifestForInstalled } from "./host.mjs";
|
|
5
5
|
export { API_RULES, CONTEXT_RULES, EVENT_RULES, HOST_IMPORT_RULES, PI_AI_PACKAGES, PI_CODING_AGENT_PACKAGES, PI_TUI_PACKAGES, UI_CONTEXT_RULES, analyzePackage, applyPiHost, collectPiMcpServers, convertPiMcpConfig, generateBundle, generateHostBundle, manifestForInstalled, renderMcpPatch, resolvePiPackage, ruleForApi, ruleForContextProperty, ruleForEvent, ruleForHostImport, ruleForUiContextProperty };
|
|
@@ -244,8 +244,8 @@ const CONTEXT_RULES = Object.freeze({
|
|
|
244
244
|
getSystemPromptOptions: rule("partial", "Returns an empty Pi option projection in command contexts."),
|
|
245
245
|
waitForIdle: rule("partial", "Mapped to the DSH agent idle boundary when available."),
|
|
246
246
|
sessionManager: rule("partial", "A real read-only projection: DSH durable messages plus pi2dsh sidecar entries, exposed through Pi's exact 14-method surface as a single-branch tree."),
|
|
247
|
-
modelRegistry: rule("partial", "A live registry over the ONE model directory: every Pi provider (package-registered or ~/.pi/agent/models.json) is a DSH llm route, and the registry is that directory's exact Pi projection — Pi-native entries keep api/baseUrl and the full Model shape. getProviderAuth/getApiKeyAndHeaders run Pi's full credential chain (models.json keys resolve with Pi's $ENV/!command semantics); DSH-owned routes keep their credentials inside their adapters by design."),
|
|
248
|
-
model: rule("partial", "The agent's real provider/model route (a setModel() override wins), enriched from the projected catalog."),
|
|
247
|
+
modelRegistry: rule("partial", "A live registry over the ONE model directory: every Pi provider (package-registered or ~/.pi/agent/models.json) is a DSH llm route, and the registry is that directory's exact Pi projection — Pi-native entries keep api/baseUrl and the full Model shape. getProviderAuth/getApiKeyAndHeaders run Pi's full credential chain (models.json keys resolve with Pi's $ENV/!command semantics); DSH-owned routes keep their credentials inside their adapters by design. A models.json entry carrying ONLY modelOverrides that declare input:[\"text\",\"image\"] for an existing route registers a \"<route>-vision\" image-admission companion: a real DSH route that admits images, replaces image blocks with an explicit text notice, and forwards to the original route (Pi itself has no admission layer, so this projection is bridge-defined). Stored attachments are materialized to temp files and the notice names the path — Pi's image vocabulary is inline-or-path, so a path lets any path-taking tool (Pi's read, vision tools) reach the image."),
|
|
248
|
+
model: rule("partial", "The agent's real provider/model route (a setModel() override wins), enriched from the projected catalog. When the selected route is an image-admission companion, ctx.model reports the ORIGINAL route with its true modalities — the generating model is the original text-only one, which is the truth extensions branching on input modalities (a vision bridge's activation check) need."),
|
|
249
249
|
scopedModels: rule("partial", "The projected model catalog (DSH llm directory plus package-registered providers)."),
|
|
250
250
|
hasConfiguredAuth: rule("partial", "Configuration check on the projected registry: true when the model's provider has a live route or package registration (not a key-liveness probe)."),
|
|
251
251
|
thinkingLevel: rule("partial", "Reflects the level recorded by setThinkingLevel(); applied as reasoningEffort on the next request."),
|
|
@@ -1615,4 +1615,4 @@ function renderMcpPatch(result) {
|
|
|
1615
1615
|
//#endregion
|
|
1616
1616
|
export { ruleForHostImport as _, analyzePackage as a, EVENT_RULES as c, PI_CODING_AGENT_PACKAGES as d, PI_TUI_PACKAGES as f, ruleForEvent as g, ruleForContextProperty as h, generateBundle as i, HOST_IMPORT_RULES as l, ruleForApi as m, convertPiMcpConfig as n, API_RULES as o, UI_CONTEXT_RULES as p, renderMcpPatch as r, CONTEXT_RULES as s, collectPiMcpServers as t, PI_AI_PACKAGES as u, ruleForUiContextProperty as v };
|
|
1617
1617
|
|
|
1618
|
-
//# sourceMappingURL=mcp-config-
|
|
1618
|
+
//# sourceMappingURL=mcp-config-ByUc0jmD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-config-ByUc0jmD.mjs","names":["stringRecord","parseYaml"],"sources":["../src/compatibility.ts","../src/module-graph.ts","../src/analyzer.ts","../src/generator.ts","../src/mcp-config.ts"],"sourcesContent":["import type { CompatibilityLevel } from './types.js'\n\ninterface Rule {\n level: CompatibilityLevel\n detail: string\n}\n\nconst rule = (level: CompatibilityLevel, detail: string): Rule => ({ level, detail })\n\nexport const PI_CODING_AGENT_PACKAGES = Object.freeze([\n '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-coding-agent',\n] as const)\n\nexport const PI_TUI_PACKAGES = Object.freeze([\n '@earendil-works/pi-tui',\n '@mariozechner/pi-tui',\n] as const)\n\nexport const PI_AI_PACKAGES = Object.freeze([\n '@earendil-works/pi-ai',\n '@mariozechner/pi-ai',\n] as const)\n\nconst VENDORED = 'Vendored byte-identical from Pi, so semantics match Pi exactly.'\nconst HEADLESS_COMPONENT = 'Constructible headless component with Pi-exact signatures; renders plain text, never a terminal.'\nconst RUNTIME_STUB = 'Importable, but calling it fails explicitly: it belongs to Pi\\'s internal agent runtime and needs a native DSH port.'\nconst VENDORED_TOOL = 'Pi\\'s built-in tool constructor, vendored byte-identical with its pure-logic closure.'\nconst EVENT_GUARD = 'Pi\\'s exact one-line tool-event guard, reimplemented verbatim.'\n\nexport const HOST_IMPORT_RULES: Readonly<Record<string, Readonly<Record<string, Rule>>>> = Object.freeze({\n 'pi-coding-agent': Object.freeze({\n defineTool: rule('full', 'Identity helper, preserved.'),\n CONFIG_DIR_NAME: rule('partial', 'The conventional config directory name is preserved, while DSH owns the actual profile layout.'),\n DEFAULT_MAX_LINES: rule('full', VENDORED),\n DEFAULT_MAX_BYTES: rule('full', VENDORED),\n VERSION: rule('partial', 'Reports a pi2dsh compatibility marker instead of a Pi release version.'),\n CURRENT_SESSION_VERSION: rule('full', VENDORED),\n getAgentDir: rule('partial', 'Redirected to an isolated DSH-owned pi2dsh directory instead of Pi global state.'),\n getPackageDir: rule('partial', 'Resolves inside the DSH-owned pi2dsh agent directory.'),\n formatSize: rule('full', VENDORED),\n truncateHead: rule('full', VENDORED),\n truncateTail: rule('full', VENDORED),\n truncateLine: rule('full', VENDORED),\n withFileMutationQueue: rule('full', VENDORED),\n SessionManager: rule('full', `${VENDORED} Sessions live under the DSH-owned pi2dsh agent directory.`),\n parseSessionEntries: rule('full', VENDORED),\n migrateSessionEntries: rule('full', VENDORED),\n getLatestCompactionEntry: rule('full', VENDORED),\n sessionEntryToContextMessages: rule('full', VENDORED),\n buildContextEntries: rule('full', VENDORED),\n buildSessionContext: rule('full', VENDORED),\n loadEntriesFromFile: rule('full', VENDORED),\n findMostRecentSession: rule('full', VENDORED),\n getDefaultSessionDir: rule('full', VENDORED),\n assertValidSessionId: rule('full', VENDORED),\n convertToLlm: rule('full', VENDORED),\n createCustomMessage: rule('full', VENDORED),\n createBranchSummaryMessage: rule('full', VENDORED),\n createCompactionSummaryMessage: rule('full', VENDORED),\n bashExecutionToText: rule('full', VENDORED),\n estimateTokens: rule('full', 'Reimplements Pi\\'s chars/4 heuristic over the same message roles.'),\n calculateContextTokens: rule('full', 'Sums the Pi chars/4 heuristic across messages.'),\n DEFAULT_COMPACTION_SETTINGS: rule('full', 'Pi\\'s default compaction thresholds, preserved as constants.'),\n serializeConversation: rule('partial', 'JSON serialization without Pi\\'s prompt-oriented formatting.'),\n shouldCompact: rule('partial', 'Always reports false: DSH owns compaction scheduling.'),\n compact: rule('unsupported', 'Pi compaction execution belongs to DSH\\'s native compaction plugin; calling fails explicitly.'),\n findCutPoint: rule('unsupported', RUNTIME_STUB),\n generateSummary: rule('unsupported', RUNTIME_STUB),\n generateSummaryWithUsage: rule('unsupported', RUNTIME_STUB),\n generateBranchSummary: rule('unsupported', RUNTIME_STUB),\n parseFrontmatter: rule('full', 'Frontmatter parsing with Pi-compatible semantics.'),\n stripFrontmatter: rule('full', 'Frontmatter stripping with Pi-compatible semantics.'),\n copyToClipboard: rule('partial', 'Attempts the platform clipboard command (pbcopy/clip/wl-copy/xclip); resolves false when none succeeds.'),\n resizeImage: rule('partial', 'Passes images through un-resized; Pi resizes only to save tokens, so content is preserved.'),\n convertToPng: rule('partial', 'PNG input passes through; other formats fail explicitly without Pi\\'s wasm codec.'),\n getShellConfig: rule('partial', 'Standard shell detection without Pi\\'s managed-bin PATH handling.'),\n getBinDir: rule('partial', 'Reports the first PATH segment instead of Pi\\'s managed bin directory.'),\n Theme: rule('partial', 'Headless theme: styling calls return their input text unstyled.'),\n theme: rule('partial', 'A headless theme singleton; jiti-loaded Pi extensions must not rely on Pi global theme state anyway.'),\n initTheme: rule('partial', 'Accepted as a no-op; DSH surfaces own presentation.'),\n getSettingsListTheme: rule('partial', 'Returns an unstyled theme with Pi\\'s exact field shape.'),\n getSelectListTheme: rule('partial', 'Returns an unstyled theme with Pi\\'s exact field shape.'),\n getMarkdownTheme: rule('partial', 'Returns a plain-text headless theme; Pi terminal styling is intentionally discarded.'),\n getLanguageFromPath: rule('partial', 'Extension-based language detection covering common languages.'),\n highlightCode: rule('partial', 'Splits lines without terminal syntax colors.'),\n DynamicBorder: rule('full', 'Headless implementation of Pi\\'s one-line border component; pass an explicit color function as Pi itself recommends.'),\n SettingsManager: rule('partial', 'In-memory settings with Pi\\'s getter/setter surface; DSH owns real persisted configuration.'),\n InMemorySettingsStorage: rule('partial', 'In-memory storage stub honoring the withLock contract.'),\n FileSettingsStorage: rule('partial', 'Alias of the in-memory storage; DSH owns persisted settings.'),\n ModelRegistry: rule('partial', 'A local registry container; DSH llm adapters own real model routing.'),\n createEventBus: rule('full', 'Pi event-bus semantics: async handler isolation and unsubscribe functions.'),\n readStoredCredential: rule('partial', 'Reads Pi-style auth.json from the pi2dsh-owned agent directory; DSH credentials stay authoritative for DSH model calls.'),\n parseSkillBlock: rule('full', 'Pi\\'s skill_content block parser, reimplemented over the same wire shape.'),\n wrapRegisteredTool: rule('unsupported', RUNTIME_STUB),\n ProjectTrustStore: rule('unsupported', RUNTIME_STUB),\n DefaultResourceLoader: rule('partial', 'A headless resource loader honoring overrides, with empty discovery sets.'),\n DefaultPackageManager: rule('unsupported', RUNTIME_STUB),\n ModelRuntime: rule('unsupported', RUNTIME_STUB),\n createAgentSession: rule('partial', 'Bridged to a genuine DSH child agent through ctx.agents (a Pi model on the options routes the child); compositions without a loop factory fail explicitly.'),\n createCodingTools: rule('full', 'Pi\\'s exact tool set composed from the vendored built-in constructors.'),\n createReadOnlyTools: rule('full', 'Pi\\'s exact read-only tool set composed from the vendored built-in constructors.'),\n createBashTool: rule('full', VENDORED_TOOL),\n createReadTool: rule('full', VENDORED_TOOL),\n createEditTool: rule('full', VENDORED_TOOL),\n createWriteTool: rule('full', VENDORED_TOOL),\n createGrepTool: rule('full', VENDORED_TOOL),\n createFindTool: rule('full', VENDORED_TOOL),\n createLsTool: rule('full', VENDORED_TOOL),\n createBashToolDefinition: rule('full', VENDORED_TOOL),\n createReadToolDefinition: rule('full', VENDORED_TOOL),\n createEditToolDefinition: rule('full', VENDORED_TOOL),\n createWriteToolDefinition: rule('full', VENDORED_TOOL),\n createGrepToolDefinition: rule('full', VENDORED_TOOL),\n createFindToolDefinition: rule('full', VENDORED_TOOL),\n createLsToolDefinition: rule('full', VENDORED_TOOL),\n isToolCallEventType: rule('full', EVENT_GUARD),\n isBashToolResult: rule('full', EVENT_GUARD),\n isReadToolResult: rule('full', EVENT_GUARD),\n isEditToolResult: rule('full', EVENT_GUARD),\n isWriteToolResult: rule('full', EVENT_GUARD),\n isGrepToolResult: rule('full', EVENT_GUARD),\n isFindToolResult: rule('full', EVENT_GUARD),\n isLsToolResult: rule('full', EVENT_GUARD),\n loadSkills: rule('unsupported', RUNTIME_STUB),\n loadSkillsFromDir: rule('unsupported', RUNTIME_STUB),\n formatSkillsForPrompt: rule('full', 'Pi\\'s skill prompt formatter, vendored with logic unchanged.'),\n CustomEditor: rule('partial', HEADLESS_COMPONENT),\n ToolExecutionComponent: rule('partial', HEADLESS_COMPONENT),\n FooterComponent: rule('partial', HEADLESS_COMPONENT),\n BorderedLoader: rule('partial', HEADLESS_COMPONENT),\n CustomMessageComponent: rule('partial', HEADLESS_COMPONENT),\n AssistantMessageComponent: rule('partial', HEADLESS_COMPONENT),\n UserMessageComponent: rule('partial', HEADLESS_COMPONENT),\n ExtensionSelectorComponent: rule('partial', HEADLESS_COMPONENT),\n ExtensionInputComponent: rule('partial', HEADLESS_COMPONENT),\n ExtensionEditorComponent: rule('partial', HEADLESS_COMPONENT),\n SettingsSelectorComponent: rule('partial', HEADLESS_COMPONENT),\n renderDiff: rule('partial', 'Plain unified-style diff lines without terminal colors.'),\n truncateToVisualLines: rule('partial', 'Visual-line truncation backed by Pi\\'s vendored width math.'),\n keyHint: rule('partial', 'Plain-text key hint without theme styling.'),\n keyText: rule('partial', 'Plain-text key name without theme styling.'),\n rawKeyHint: rule('partial', 'Plain-text key hint without theme styling.'),\n }),\n 'pi-tui': Object.freeze({\n visibleWidth: rule('full', VENDORED),\n truncateToWidth: rule('full', VENDORED),\n wrapTextWithAnsi: rule('full', VENDORED),\n sliceByColumn: rule('full', VENDORED),\n sliceWithWidth: rule('full', VENDORED),\n stripTerminalSequences: rule('full', VENDORED),\n getOsc8LinkAtColumn: rule('full', VENDORED),\n normalizeTerminalOutput: rule('full', VENDORED),\n extractAnsiCode: rule('full', VENDORED),\n getGraphemeCellRange: rule('full', VENDORED),\n getGraphemeSegmenter: rule('full', VENDORED),\n getWordSegmenter: rule('full', VENDORED),\n applyBackgroundToLine: rule('full', VENDORED),\n isWhitespaceChar: rule('full', VENDORED),\n isPunctuationChar: rule('full', VENDORED),\n cjkBreakRegex: rule('full', VENDORED),\n PUNCTUATION_REGEX: rule('full', VENDORED),\n fuzzyMatch: rule('full', VENDORED),\n fuzzyFilter: rule('full', VENDORED),\n parseKey: rule('full', VENDORED),\n matchesKey: rule('full', VENDORED),\n isKeyRelease: rule('full', VENDORED),\n isKeyRepeat: rule('full', VENDORED),\n decodeKittyPrintable: rule('full', VENDORED),\n isKittyProtocolActive: rule('full', VENDORED),\n setKittyProtocolActive: rule('full', VENDORED),\n Key: rule('full', VENDORED),\n getKeybindings: rule('full', `${VENDORED} Bindings only match when a surface feeds terminal input, which DSH does not.`),\n setKeybindings: rule('full', VENDORED),\n KeybindingsManager: rule('full', VENDORED),\n TUI_KEYBINDINGS: rule('full', VENDORED),\n parseOsc11BackgroundColor: rule('full', VENDORED),\n parseTerminalColorSchemeReport: rule('full', VENDORED),\n renderLatex: rule('full', VENDORED),\n getPngDimensions: rule('full', VENDORED),\n getJpegDimensions: rule('full', VENDORED),\n getGifDimensions: rule('full', VENDORED),\n getWebpDimensions: rule('full', VENDORED),\n getImageDimensions: rule('full', VENDORED),\n calculateImageRows: rule('full', VENDORED),\n allocateImageId: rule('full', VENDORED),\n encodeKitty: rule('partial', `${VENDORED} No DSH surface consumes the escape sequences.`),\n encodeITerm2: rule('partial', `${VENDORED} No DSH surface consumes the escape sequences.`),\n deleteKittyImage: rule('partial', `${VENDORED} No DSH surface consumes the escape sequences.`),\n deleteAllKittyImages: rule('partial', `${VENDORED} No DSH surface consumes the escape sequences.`),\n detectCapabilities: rule('partial', `${VENDORED} Headless environments report no image protocol.`),\n getCapabilities: rule('partial', VENDORED),\n setCapabilities: rule('partial', VENDORED),\n resetCapabilitiesCache: rule('partial', VENDORED),\n getCellDimensions: rule('partial', VENDORED),\n setCellDimensions: rule('partial', VENDORED),\n hyperlink: rule('full', VENDORED),\n imageFallback: rule('full', VENDORED),\n CombinedAutocompleteProvider: rule('partial', `${VENDORED} Suggestions surface only if a DSH UI asks for them.`),\n Marked: rule('full', 'Re-exported from the same marked dependency Pi uses.'),\n CURSOR_MARKER: rule('full', 'Pi\\'s exact APC marker; vendored width math treats it as zero-width.'),\n Text: rule('partial', HEADLESS_COMPONENT),\n Spacer: rule('partial', HEADLESS_COMPONENT),\n Container: rule('partial', HEADLESS_COMPONENT),\n Box: rule('partial', HEADLESS_COMPONENT),\n Markdown: rule('partial', HEADLESS_COMPONENT),\n TruncatedText: rule('partial', HEADLESS_COMPONENT),\n Editor: rule('partial', `${HEADLESS_COMPONENT} Text editing state works; interactive keyboard flows do not.`),\n Input: rule('partial', `${HEADLESS_COMPONENT} Value state and submit/escape callbacks work; kill-ring editing does not.`),\n SelectList: rule('partial', `${HEADLESS_COMPONENT} Filtering and selection state work; keyboard interaction does not.`),\n SettingsList: rule('partial', `${HEADLESS_COMPONENT} Value updates work; keyboard interaction does not.`),\n ScrollView: rule('partial', HEADLESS_COMPONENT),\n VStack: rule('partial', HEADLESS_COMPONENT),\n HStack: rule('partial', HEADLESS_COMPONENT),\n Loader: rule('partial', HEADLESS_COMPONENT),\n CancellableLoader: rule('partial', HEADLESS_COMPONENT),\n Image: rule('partial', `${HEADLESS_COMPONENT} Renders a text placeholder; image bytes flow through DSH attachments instead.`),\n isFocusable: rule('full', 'Structural check preserved.'),\n isViewportTUI: rule('partial', 'Always false: no viewport TUI exists in DSH surfaces.'),\n }),\n 'pi-ai': Object.freeze({\n StringEnum: rule('full', 'Preserves Pi flat string-enum JSON Schema generation without loading provider SDKs.'),\n registerProvider: rule('partial', 'Recorded in a bridge-local registry; DSH llm adapters own real routing.'),\n getProviders: rule('partial', 'Returns the bridge-local registry contents.'),\n getProvider: rule('partial', 'Reads the bridge-local registry.'),\n getModel: rule('partial', 'Resolves no Pi model objects; DSH owns model routing.'),\n getModels: rule('partial', 'Returns an empty list; DSH owns model routing.'),\n complete: rule('unsupported', 'Pi provider SDK calls have no DSH mapping; calling fails explicitly.'),\n stream: rule('unsupported', 'Pi provider SDK calls have no DSH mapping; calling fails explicitly.'),\n Type: rule('full', 'Re-exported from the same typebox dependency Pi resolves for extensions.'),\n uuidv7: rule('full', VENDORED),\n isContextOverflow: rule('full', VENDORED),\n isRecoverableLength: rule('full', VENDORED),\n isRetryableAssistantError: rule('full', VENDORED),\n contentText: rule('full', 'Pi\\'s text-block joiner, reimplemented with identical semantics.'),\n clampThinkingLevel: rule('full', 'Pi\\'s clamping walk over the extended thinking-level ladder.'),\n getSupportedThinkingLevels: rule('full', 'Pi\\'s thinkingLevelMap filter, preserved.'),\n modelsAreEqual: rule('full', 'Id+provider equality, preserved.'),\n }),\n})\n\nexport const CONTEXT_RULES: Readonly<Record<string, Rule>> = Object.freeze({\n cwd: rule('full', 'Mapped to the active DSH agent session working directory.'),\n signal: rule('full', 'Mapped to the active DSH cancellation signal when one is available.'),\n hasUI: rule('full', 'Reports whether the native DSH userQuestions service is available to back Pi dialogs.'),\n mode: rule('partial', 'Reports rpc mode so Pi extensions can choose their documented headless fallback.'),\n isIdle: rule('partial', 'Command contexts report idle; tool/lifecycle contexts conservatively report non-idle.'),\n isProjectTrusted: rule('partial', 'Fails closed as untrusted because DSH does not expose Pi project-trust state.'),\n hasPendingMessages: rule('partial', 'Conservatively reports no Pi-specific pending-message queue.'),\n getContextUsage: rule('partial', 'Returns no Pi token-usage projection.'),\n getSystemPrompt: rule('full', 'Returns the system prompt currently assembled by the bridge.'),\n getSystemPromptOptions: rule('partial', 'Returns an empty Pi option projection in command contexts.'),\n waitForIdle: rule('partial', 'Mapped to the DSH agent idle boundary when available.'),\n sessionManager: rule('partial', 'A real read-only projection: DSH durable messages plus pi2dsh sidecar entries, exposed through Pi\\'s exact 14-method surface as a single-branch tree.'),\n modelRegistry: rule('partial', 'A live registry over the ONE model directory: every Pi provider (package-registered or ~/.pi/agent/models.json) is a DSH llm route, and the registry is that directory\\'s exact Pi projection — Pi-native entries keep api/baseUrl and the full Model shape. getProviderAuth/getApiKeyAndHeaders run Pi\\'s full credential chain (models.json keys resolve with Pi\\'s $ENV/!command semantics); DSH-owned routes keep their credentials inside their adapters by design. A models.json entry carrying ONLY modelOverrides that declare input:[\"text\",\"image\"] for an existing route registers a \"<route>-vision\" image-admission companion: a real DSH route that admits images, replaces image blocks with an explicit text notice, and forwards to the original route (Pi itself has no admission layer, so this projection is bridge-defined). Stored attachments are materialized to temp files and the notice names the path — Pi\\'s image vocabulary is inline-or-path, so a path lets any path-taking tool (Pi\\'s read, vision tools) reach the image.'),\n model: rule('partial', 'The agent\\'s real provider/model route (a setModel() override wins), enriched from the projected catalog. When the selected route is an image-admission companion, ctx.model reports the ORIGINAL route with its true modalities — the generating model is the original text-only one, which is the truth extensions branching on input modalities (a vision bridge\\'s activation check) need.'),\n scopedModels: rule('partial', 'The projected model catalog (DSH llm directory plus package-registered providers).'),\n hasConfiguredAuth: rule('partial', 'Configuration check on the projected registry: true when the model\\'s provider has a live route or package registration (not a key-liveness probe).'),\n thinkingLevel: rule('partial', 'Reflects the level recorded by setThinkingLevel(); applied as reasoningEffort on the next request.'),\n abort: rule('partial', 'Mapped to agent.cancel({ kind: \"hook\" }) on the live DSH agent.'),\n shutdown: rule('unsupported', 'A migrated package may not shut down the DSH host; calling fails explicitly.'),\n compact: rule('unsupported', 'Pi compaction control requires a native DSH compaction integration; calling fails explicitly.'),\n newSession: rule('unsupported', 'Session replacement belongs to the DSH host; calling fails explicitly.'),\n fork: rule('unsupported', 'Pi entry-tree forking has no DSH equivalent (DSH fork is boundary-based); calling fails explicitly.'),\n navigateTree: rule('unsupported', 'Pi tree navigation has no DSH equivalent; calling fails explicitly.'),\n switchSession: rule('unsupported', 'Session switching belongs to the DSH host; calling fails explicitly.'),\n reload: rule('unsupported', 'Extension reload belongs to the DSH host (HMR); calling fails explicitly.'),\n})\n\nexport const UI_CONTEXT_RULES: Readonly<Record<string, Rule>> = Object.freeze({\n notify: rule('full', 'Captured as a command result when applicable and emitted through DSH logging.'),\n setStatus: rule('partial', 'Accepted as a no-op because DSH owns status presentation.'),\n setWidget: rule('partial', 'Accepted as a no-op because Pi terminal widgets cannot render in DSH.'),\n select: rule('full', 'Mapped to one native DSH userQuestions single-select request.'),\n confirm: rule('full', 'Mapped to one native DSH userQuestions Yes/No request.'),\n input: rule('full', 'Mapped to one native DSH userQuestions free-text request.'),\n editor: rule('partial', 'Mapped to one DSH userQuestions free-text request; multi-line editing UX is not emulated.'),\n custom: rule('partial', 'Resolves undefined, exactly like Pi\\'s own rpc mode; guarded fallbacks keep working.'),\n onTerminalInput: rule('partial', 'Raw terminal input is absent; feature-detected listeners remain disabled.'),\n setWorkingMessage: rule('partial', 'Accepted as a no-op; DSH owns progress presentation.'),\n setWorkingVisible: rule('partial', 'Accepted as a no-op; DSH owns progress presentation.'),\n setWorkingIndicator: rule('partial', 'Accepted as a no-op; DSH owns progress presentation.'),\n setHiddenThinkingLabel: rule('partial', 'Accepted as a no-op; DSH owns thinking presentation.'),\n setFooter: rule('partial', 'Accepted as a no-op; DSH owns footer presentation.'),\n setHeader: rule('partial', 'Accepted as a no-op; DSH owns header presentation.'),\n setTitle: rule('partial', 'Accepted as a no-op; DSH owns window titles.'),\n pasteToEditor: rule('partial', 'Appends to a per-agent editor buffer readable through getEditorText().'),\n setEditorText: rule('partial', 'Stored in a per-agent editor buffer readable through getEditorText().'),\n getEditorText: rule('partial', 'Reads the per-agent editor buffer maintained by the bridge.'),\n addAutocompleteProvider: rule('partial', 'Registration is recorded; no DSH surface requests suggestions.'),\n setEditorComponent: rule('partial', 'Registration is recorded; no DSH surface mounts a Pi editor component.'),\n getEditorComponent: rule('partial', 'Returns the recorded factory.'),\n theme: rule('partial', 'A headless theme whose styling calls return unstyled text.'),\n getAllThemes: rule('partial', 'Lists the single headless theme.'),\n getTheme: rule('partial', 'Resolves only the headless theme.'),\n setTheme: rule('partial', 'Accepts the headless theme; other names report an explicit error result.'),\n getToolsExpanded: rule('partial', 'A bridge-local presentation flag.'),\n setToolsExpanded: rule('partial', 'A bridge-local presentation flag.'),\n})\n\nexport const API_RULES: Readonly<Record<string, Rule>> = Object.freeze({\n registerTool: {\n level: 'partial',\n detail: 'Registered as a native DSH tool. Text and image results use native DSH content/attachments; unsupported JSON Schema constraints and Pi-only error details are explicitly degraded.',\n },\n unregisterTool: {\n level: 'full',\n detail: 'Disposes the exact native DSH tool registration and removes it from the migrated package registry.',\n },\n registerCommand: {\n level: 'partial',\n detail: 'Registered in ctx.commands with Pi\\'s never-throw collision semantics: a package re-registering its own name replaces it, and cross-source collisions mount under Pi\\'s numbered scheme (/name-2 — the earlier registration keeps the bare name, where Pi renumbers both). ui.notify becomes the result, while interactive Pi TUI methods fail explicitly in headless DSH.',\n },\n registerShortcut: {\n level: 'partial',\n detail: 'Registration is recorded and introspectable; DSH surfaces feed no terminal key input, so handlers never fire — the same as Pi\\'s non-TUI modes.',\n },\n registerFlag: {\n level: 'partial',\n detail: 'The declared default is available through getFlag; Pi process flags cannot be added to the DSH launcher.',\n },\n getFlag: {\n level: 'partial',\n detail: 'Returns the migrated flag default because DSH cannot register the original Pi CLI flag.',\n },\n registerProvider: {\n level: 'partial',\n detail: 'The provider declaration is recorded and introspectable; model calls stay on native DSH llm adapters and credentials, which own transports and secrets.',\n },\n unregisterProvider: {\n level: 'partial',\n detail: 'Removes the recorded provider declaration.',\n },\n registerMessageRenderer: {\n level: 'partial',\n detail: 'Registration is accepted; DSH owns presentation, so the renderer is never invoked — matching Pi\\'s non-TUI surfaces.',\n },\n registerEntryRenderer: {\n level: 'partial',\n detail: 'Registration is accepted; DSH owns presentation, so the renderer is never invoked — matching Pi\\'s non-TUI surfaces.',\n },\n registerMarkdownTransformer: {\n level: 'partial',\n detail: 'Registration is accepted; DSH owns presentation, so the transformer is never invoked — matching Pi\\'s non-TUI surfaces.',\n },\n sendMessage: {\n level: 'partial',\n detail: 'Mapped to native DSH inject/steer/followup delivery with honest plugin provenance; Pi display/details metadata awaits the custom session-entry seam.',\n },\n sendUserMessage: {\n level: 'full',\n detail: 'Mapped to native DSH steer/followup delivery with text and attachment-backed image content.',\n },\n appendEntry: {\n level: 'partial',\n detail: 'Persisted in a pi2dsh sidecar next to the DSH session and replayed on session start; DSH\\'s main log stays untouched because it has no out-of-repo plugin-event channel yet.',\n },\n setSessionName: {\n level: 'partial',\n detail: 'Persisted in the pi2dsh sidecar and announced through session_info_changed; DSH\\'s own title events are also projected when present.',\n },\n getSessionName: {\n level: 'partial',\n detail: 'Reads the sidecar-persisted session name.',\n },\n setLabel: {\n level: 'partial',\n detail: 'Persisted in the pi2dsh sidecar and reflected by the sessionManager projection.',\n },\n exec: {\n level: 'partial',\n detail: 'Mapped to ctx.subprocess, so the selected local/E2B provider owns execution, isolation, cancellation, and tree cleanup; output is bounded to 64 MiB per stream.',\n },\n getActiveTools: {\n level: 'partial',\n detail: 'Returns every tool visible in the current DSH agent scope, including native and migrated tools; scope-local tools follow DSH composition rules.',\n },\n getAllTools: {\n level: 'partial',\n detail: 'Returns metadata for all tools visible in the current DSH scope, without Pi-specific prompt guidelines unavailable from DSH schemas.',\n },\n setActiveTools: {\n level: 'partial',\n detail: 'Mapped to the active DSH agent scope through tools.restrict({ allow }), preserving per-agent global-tool visibility without mutating other agents; DSH scope-local tools remain visible by design.',\n },\n getCommands: {\n level: 'partial',\n detail: 'Returns commands registered by this migrated Pi package, not every command visible in the DSH scope.',\n },\n setModel: {\n level: 'partial',\n detail: 'Recorded as a per-agent override applied through the agent/request waterfall on the next model call; DSH remains authoritative for provider routing.',\n },\n getThinkingLevel: {\n level: 'partial',\n detail: 'Returns the level recorded by setThinkingLevel (default off).',\n },\n setThinkingLevel: {\n level: 'partial',\n detail: 'Recorded per agent and applied as reasoningEffort through the agent/request waterfall; DSH validates the effort id at the request boundary.',\n },\n events: {\n level: 'full',\n detail: 'Package-local Pi extension event-bus emit/on semantics are preserved for migrated extensions in the same bundle.',\n },\n})\n\nconst OBSERVED_NEVER_FIRES = (moment: string): Rule => ({\n level: 'partial',\n detail: `Registration is accepted; ${moment} never occurs on DSH surfaces, so the handler never fires. Loading is unaffected.`,\n})\n\nexport const EVENT_RULES: Readonly<Record<string, Rule>> = Object.freeze({\n session_start: { level: 'full', detail: 'Mapped to agent/session-start.' },\n session_shutdown: { level: 'full', detail: 'Mapped to agent disposal and plugin teardown with duplicate suppression.' },\n session_info_changed: { level: 'partial', detail: 'Fired by setSessionName() and projected from DSH session/title events.' },\n agent_start: { level: 'full', detail: 'Mapped to the DSH turn/start boundary.' },\n agent_settled: { level: 'full', detail: 'Mapped to the DSH turn/end boundary.' },\n turn_start: { level: 'full', detail: 'Mapped from durable turn/start events.' },\n tool_execution_start: { level: 'full', detail: 'Mapped from durable tool/call events.' },\n tool_execution_end: { level: 'full', detail: 'Mapped from finalized tools/result events.' },\n tool_execution_update: {\n level: 'partial',\n detail: 'Fired from migrated Pi tools\\' own onUpdate callbacks; DSH-native tools expose no partial-result stream.',\n },\n tool_call: {\n level: 'partial',\n detail: 'Blocking is supported, and in-place argument mutation reaches migrated Pi tools; mutating a DSH-native tool\\'s arguments is rejected because DSH logs arguments before policy.',\n },\n tool_result: {\n level: 'partial',\n detail: 'Text replacement and success-to-error blocking are supported; arbitrary details and error recovery are not.',\n },\n before_agent_start: {\n level: 'full',\n detail: 'Fires at the turn\\'s first pre-step with the real prompt text and image attachments; returned custom messages enter the turn beside the user message, and a returned systemPrompt overrides this turn\\'s assembly.',\n },\n agent_end: {\n level: 'partial',\n detail: 'The lifecycle boundary is mapped, but the reconstructed Pi message history is intentionally minimal.',\n },\n turn_end: {\n level: 'partial',\n detail: 'The lifecycle boundary and tool results are mapped; the exact Pi final-message shape is not guaranteed.',\n },\n message_start: {\n level: 'partial',\n detail: 'Durable user, assistant, and tool-result messages are mapped without Pi-specific provider metadata.',\n },\n message_end: {\n level: 'partial',\n detail: 'Durable messages are observed, but message replacement is not supported.',\n },\n message_update: {\n level: 'partial',\n detail: 'Projected from DSH assistant/chunk events with accumulated text; Pi\\'s full AgentMessage accumulation state is approximated.',\n },\n session_before_compact: {\n level: 'partial',\n detail: 'Projected from DSH compaction/start as a notification; cancel/replace cannot reach DSH\\'s compactor.',\n },\n session_compact: {\n level: 'partial',\n detail: 'Projected from DSH compaction summary/end events.',\n },\n model_select: {\n level: 'partial',\n detail: 'Fired by setModel() and projected from request/header model changes in the durable log.',\n },\n thinking_level_select: {\n level: 'partial',\n detail: 'Fired by setThinkingLevel(); DSH-side reasoning changes surface through request/header projection.',\n },\n context: {\n level: 'partial',\n detail: 'Fires before each step with the full message projection; the transform applies to the step\\'s not-yet-entered messages (the slice packages rewrite), while already-entered history stays read-only under DSH\\'s append-only log.',\n },\n before_provider_request: {\n level: 'unsupported',\n detail: 'Provider payload mutation belongs in a native DSH LLM adapter; the handler is accepted but never fires.',\n },\n before_provider_headers: {\n level: 'unsupported',\n detail: 'Provider header mutation belongs in a native DSH LLM adapter; the handler is accepted but never fires.',\n },\n after_provider_response: {\n level: 'unsupported',\n detail: 'Provider response interception belongs in a native DSH LLM adapter; the handler is accepted but never fires.',\n },\n user_bash: OBSERVED_NEVER_FIRES('Pi\\'s ! command surface'),\n input: OBSERVED_NEVER_FIRES('raw Pi terminal input'),\n project_trust: {\n level: 'unsupported',\n detail: 'Project trust must remain owned by the DSH host; the handler is accepted but never consulted.',\n },\n resources_discover: {\n level: 'unsupported',\n detail: 'Dynamic resource discovery must be converted into DSH providers; the handler is accepted but never fires.',\n },\n session_before_switch: OBSERVED_NEVER_FIRES('Pi session switching'),\n session_before_fork: OBSERVED_NEVER_FIRES('Pi tree forking'),\n session_before_tree: OBSERVED_NEVER_FIRES('Pi session-tree navigation'),\n session_tree: OBSERVED_NEVER_FIRES('Pi session-tree navigation'),\n})\n\nexport function ruleForApi(method: string): Rule | undefined {\n return API_RULES[method]\n}\n\nexport function ruleForEvent(event: string): Rule {\n return EVENT_RULES[event] ?? {\n level: 'unsupported',\n detail: `Unknown Pi event ${JSON.stringify(event)} has no verified DSH mapping.`,\n }\n}\n\nexport function ruleForHostImport(packageName: string, importedName: string): Rule | undefined {\n const family = (PI_CODING_AGENT_PACKAGES as readonly string[]).includes(packageName)\n ? 'pi-coding-agent'\n : (PI_TUI_PACKAGES as readonly string[]).includes(packageName)\n ? 'pi-tui'\n : (PI_AI_PACKAGES as readonly string[]).includes(packageName) ? 'pi-ai' : undefined\n return family === undefined ? undefined : HOST_IMPORT_RULES[family]?.[importedName]\n}\n\nexport function ruleForContextProperty(property: string): Rule | undefined {\n return CONTEXT_RULES[property]\n}\n\nexport function ruleForUiContextProperty(property: string): Rule | undefined {\n return UI_CONTEXT_RULES[property]\n}\n","import { builtinModules } from 'node:module'\nimport { lstat, readFile, readdir, stat } from 'node:fs/promises'\nimport { dirname, extname, join, relative, resolve } from 'node:path'\nimport ts from 'typescript'\n\nexport const SCRIPT_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])\nconst MODULE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.json']\n\ninterface LocalReference {\n kind: 'module' | 'asset'\n specifier: string\n // A lazy reference is only evaluated when some feature runs, never while the\n // extension entry loads: dynamic import()/require() inside a function body,\n // or worker/data assets spawned on demand. Pi's loader therefore succeeds\n // even when a lazy target is unresolvable; problems on lazy paths surface\n // (identically under Pi and pi2dsh) only if that feature is used.\n lazy: boolean\n}\n\nexport interface LocalClosureIssue {\n file: string\n kind: LocalReference['kind']\n specifier: string\n detail: string\n lazy: boolean\n}\n\nexport interface LocalClosure {\n files: string[]\n // Files whose module-level code executes the moment the extension entry\n // loads (transitive non-lazy module edges from the entries).\n loadTimeFiles: Set<string>\n issues: LocalClosureIssue[]\n}\n\nexport function sourceKind(path: string): ts.ScriptKind {\n if (path.endsWith('.js') || path.endsWith('.mjs') || path.endsWith('.cjs')) return ts.ScriptKind.JS\n if (path.endsWith('.jsx')) return ts.ScriptKind.JSX\n if (path.endsWith('.tsx')) return ts.ScriptKind.TSX\n return ts.ScriptKind.TS\n}\n\nfunction literalModule(node: ts.Expression | undefined): string | undefined {\n return node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : undefined\n}\n\nfunction isImportMetaUrl(node: ts.Expression | undefined): boolean {\n return node !== undefined && ts.isPropertyAccessExpression(node) && node.name.text === 'url'\n && ts.isMetaProperty(node.expression) && node.expression.keywordToken === ts.SyntaxKind.ImportKeyword\n}\n\nfunction localReferences(path: string, text: string): LocalReference[] {\n const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, sourceKind(path))\n const values = new Map<string, LocalReference>()\n const createRequireNames = new Set<string>(['createRequire'])\n const requireNames = new Set<string>(['require'])\n const add = (kind: LocalReference['kind'], specifier: string, lazy: boolean): void => {\n // '#'-prefixed specifiers are Node subpath imports resolved through the\n // package's own `imports` map — package-local, not external dependencies.\n if (!specifier.startsWith('.') && !specifier.startsWith('#')) return\n const key = `${kind}:${specifier}`\n const existing = values.get(key)\n // A specifier reached both statically and lazily executes at load time.\n if (existing === undefined) values.set(key, { kind, specifier, lazy })\n else if (existing.lazy && !lazy) existing.lazy = false\n }\n function collectRequireAliases(node: ts.Node): void {\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)\n && (node.moduleSpecifier.text === 'node:module' || node.moduleSpecifier.text === 'module')\n && node.importClause?.namedBindings !== undefined && ts.isNamedImports(node.importClause.namedBindings)) {\n for (const element of node.importClause.namedBindings.elements) {\n if ((element.propertyName?.text ?? element.name.text) === 'createRequire') createRequireNames.add(element.name.text)\n }\n } else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)\n && node.initializer !== undefined && ts.isCallExpression(node.initializer)\n && ts.isIdentifier(node.initializer.expression) && createRequireNames.has(node.initializer.expression.text)) {\n requireNames.add(node.name.text)\n }\n ts.forEachChild(node, collectRequireAliases)\n }\n collectRequireAliases(source)\n function visit(node: ts.Node): void {\n if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier !== undefined\n && ts.isStringLiteral(node.moduleSpecifier)) {\n add('module', node.moduleSpecifier.text, false)\n } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)\n && ts.isStringLiteral(node.moduleReference.expression)) {\n add('module', node.moduleReference.expression.text, false)\n } else if (ts.isCallExpression(node) && node.arguments.length > 0\n && ((node.expression.kind === ts.SyntaxKind.ImportKeyword)\n || (ts.isIdentifier(node.expression) && requireNames.has(node.expression.text)))) {\n const specifier = literalModule(node.arguments[0])\n if (specifier !== undefined) add('module', specifier, insideFunctionBody(node))\n } else if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'URL'\n && isImportMetaUrl(node.arguments?.[1])) {\n const specifier = literalModule(node.arguments?.[0])\n if (specifier !== undefined) add('asset', specifier, false)\n }\n ts.forEachChild(node, visit)\n }\n visit(source)\n return [...values.values()]\n}\n\nfunction externalPackage(specifier: string): string | undefined {\n // `bun:*` counts as a host builtin, not an npm dependency: Pi's official\n // distribution is a Bun-compiled binary, so ecosystem packages gate these\n // requires behind runtime detection and take their declared Node fallback\n // (better-sqlite3, node:sqlite) everywhere else.\n if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('#')\n || specifier.startsWith('node:') || specifier.startsWith('bun:')\n || builtinModules.includes(specifier)) return undefined\n const parts = specifier.split('/')\n return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]\n}\n\nfunction insideTry(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent\n while (current !== undefined) {\n if (ts.isTryStatement(current)) return true\n // Stop at function boundaries: a try in an outer function does not guard\n // an import inside a nested callback executed later.\n if (ts.isFunctionLike(current)) {\n // ...unless the whole function body IS awaited inside the try; keeping\n // this conservative check simple errs toward reporting the dependency.\n return false\n }\n current = current.parent\n }\n return false\n}\n\n// Inside any function body means the expression does not run while the module\n// itself loads — it runs when (if ever) that function is called.\nfunction insideFunctionBody(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent\n while (current !== undefined) {\n if (ts.isFunctionLike(current)) return true\n current = current.parent\n }\n return false\n}\n\nexport interface RuntimeDependencyUse {\n name: string\n // true when every use sits on a lazy path (dynamic import/require inside a\n // function body): the module loads fine without the dependency, exactly as\n // under Pi, and only the feature that calls it needs the install.\n lazy: boolean\n}\n\nexport function runtimeExternalPackages(path: string, text: string): RuntimeDependencyUse[] {\n const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, sourceKind(path))\n const packages = new Map<string, RuntimeDependencyUse>()\n const createRequireNames = new Set<string>(['createRequire'])\n const requireNames = new Set<string>(['require'])\n const add = (specifier: string, lazy: boolean): void => {\n const name = externalPackage(specifier)\n if (name === undefined || name.length === 0) return\n const existing = packages.get(name)\n if (existing === undefined) packages.set(name, { name, lazy })\n else if (existing.lazy && !lazy) existing.lazy = false\n }\n function collectRequireAliases(node: ts.Node): void {\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)\n && (node.moduleSpecifier.text === 'node:module' || node.moduleSpecifier.text === 'module')\n && node.importClause?.namedBindings !== undefined && ts.isNamedImports(node.importClause.namedBindings)) {\n for (const element of node.importClause.namedBindings.elements) {\n if ((element.propertyName?.text ?? element.name.text) === 'createRequire') createRequireNames.add(element.name.text)\n }\n } else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)\n && node.initializer !== undefined && ts.isCallExpression(node.initializer)\n && ts.isIdentifier(node.initializer.expression) && createRequireNames.has(node.initializer.expression.text)) {\n requireNames.add(node.name.text)\n }\n ts.forEachChild(node, collectRequireAliases)\n }\n collectRequireAliases(source)\n function visit(node: ts.Node): void {\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {\n const clause = node.importClause\n const named = clause?.namedBindings\n const namedImportsAreTypeOnly = named !== undefined && ts.isNamedImports(named)\n && named.elements.length > 0 && named.elements.every(element => element.isTypeOnly)\n if (clause === undefined || (!clause.isTypeOnly && (clause.name !== undefined || !namedImportsAreTypeOnly))) {\n add(node.moduleSpecifier.text, false)\n }\n } else if (ts.isExportDeclaration(node) && !node.isTypeOnly\n && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier)) {\n add(node.moduleSpecifier.text, false)\n } else if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly\n && ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) {\n add(node.moduleReference.expression.text, false)\n } else if (ts.isCallExpression(node) && node.arguments.length > 0\n && ((node.expression.kind === ts.SyntaxKind.ImportKeyword)\n || (ts.isIdentifier(node.expression) && requireNames.has(node.expression.text)))) {\n // A dynamic import/require wrapped in try/catch is the ecosystem's\n // optional-dependency idiom (e.g. pi-harness-runtime's \"// Dynamic\n // import for Playwright (optional dependency)\") — its absence is a\n // designed degradation, not an undeclared runtime requirement.\n if (!insideTry(node)) {\n const specifier = literalModule(node.arguments[0])\n if (specifier !== undefined) add(specifier, insideFunctionBody(node))\n }\n }\n ts.forEachChild(node, visit)\n }\n visit(source)\n return [...packages.values()]\n}\n\nfunction inside(rootDir: string, path: string): boolean {\n const pathRelative = relative(rootDir, path)\n return pathRelative === '' || (pathRelative !== '..' && !pathRelative.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`))\n}\n\nfunction sourceAlternates(base: string): string[] {\n const extension = extname(base)\n const stem = extension.length > 0 ? base.slice(0, -extension.length) : base\n if (extension === '.js') return [`${stem}.ts`, `${stem}.tsx`]\n if (extension === '.mjs') return [`${stem}.mts`, `${stem}.ts`]\n if (extension === '.cjs') return [`${stem}.cts`, `${stem}.ts`]\n if (extension === '.jsx') return [`${stem}.tsx`, `${stem}.ts`]\n return []\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n}\n\nfunction subpathImportTarget(rootDir: string, specifier: string, importsMap: Record<string, unknown>): string | undefined {\n const conditionValue = (value: unknown): string | undefined => {\n if (typeof value === 'string') return value\n if (typeof value !== 'object' || value === null) return undefined\n const record = value as Record<string, unknown>\n for (const condition of ['import', 'node', 'default']) {\n const candidate = conditionValue(record[condition])\n if (candidate !== undefined) return candidate\n }\n return undefined\n }\n const direct = conditionValue(importsMap[specifier])\n if (direct !== undefined) return resolve(rootDir, direct)\n for (const [pattern, value] of Object.entries(importsMap)) {\n const star = pattern.indexOf('*')\n if (star === -1) continue\n const prefix = pattern.slice(0, star)\n const suffix = pattern.slice(star + 1)\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) continue\n const wildcard = specifier.slice(prefix.length, specifier.length - suffix.length)\n const target = conditionValue(value)\n if (target !== undefined) return resolve(rootDir, target.replace('*', wildcard))\n }\n return undefined\n}\n\nasync function packageImportsMap(rootDir: string): Promise<Record<string, unknown>> {\n try {\n const parsed = JSON.parse(await readFile(join(rootDir, 'package.json'), 'utf8')) as { imports?: unknown }\n return typeof parsed.imports === 'object' && parsed.imports !== null ? parsed.imports as Record<string, unknown> : {}\n } catch {\n return {}\n }\n}\n\nasync function resolveModule(fromFile: string, specifier: string, rootDir: string, importsMap: Record<string, unknown>): Promise<string> {\n if (specifier.startsWith('#')) {\n const target = subpathImportTarget(rootDir, specifier, importsMap)\n if (target === undefined) {\n throw new Error(`cannot resolve subpath import ${JSON.stringify(specifier)} through the package \"imports\" map`)\n }\n return resolveModule(fromFile, relative(dirname(fromFile), target).startsWith('.')\n ? relative(dirname(fromFile), target)\n : `./${relative(dirname(fromFile), target)}`, rootDir, importsMap)\n }\n const base = resolve(dirname(fromFile), specifier)\n const candidates = [\n base,\n ...sourceAlternates(base),\n ...(extname(base) === '' ? MODULE_EXTENSIONS.map(extension => `${base}${extension}`) : []),\n ...MODULE_EXTENSIONS.map(extension => join(base, `index${extension}`)),\n ]\n for (const candidate of [...new Set(candidates)]) {\n if (!inside(rootDir, candidate)) throw new Error(`extension import escapes the Pi package: ${specifier} from ${fromFile}`)\n if (await isFile(candidate)) return candidate\n }\n throw new Error(`cannot resolve local extension import ${JSON.stringify(specifier)} from ${fromFile}`)\n}\n\nasync function expandAsset(path: string, rootDir: string): Promise<string[]> {\n if (!inside(rootDir, path)) throw new Error(`extension asset escapes the Pi package: ${path}`)\n let info\n try {\n info = await lstat(path)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n // A `new URL('./worker.js', import.meta.url)` asset may only exist in its\n // TypeScript source form before the package builds; track the source.\n for (const alternate of sourceAlternates(path)) {\n if (await isFile(alternate)) return [alternate]\n }\n throw error\n }\n if (info.isSymbolicLink()) throw new Error(`refusing to copy symbolic link from Pi package: ${path}`)\n if (info.isFile()) return [path]\n if (!info.isDirectory()) return []\n const output: string[] = []\n for (const entry of await readdir(path)) output.push(...await expandAsset(join(path, entry), rootDir))\n return output\n}\n\nexport async function collectLocalClosure(rootDir: string, entries: readonly string[]): Promise<LocalClosure> {\n const importsMap = await packageImportsMap(rootDir)\n const graph = new Map<string, Array<{ lazy: boolean, targets: string[] }>>()\n const issues: LocalClosureIssue[] = []\n const queue = entries.map(path => resolve(path))\n // Pass 1: the full local reference graph, lazy edges included, so the\n // snapshot carries every file any feature could ever load.\n while (queue.length > 0) {\n const source = queue.shift() as string\n if (graph.has(source)) continue\n if (!inside(rootDir, source)) throw new Error(`extension source escapes the Pi package: ${source}`)\n const info = await lstat(source)\n if (info.isSymbolicLink()) throw new Error(`refusing to copy symbolic link from Pi package: ${source}`)\n if (!info.isFile()) throw new Error(`extension closure contains a non-file path: ${source}`)\n const edges: Array<{ lazy: boolean, targets: string[] }> = []\n graph.set(source, edges)\n if (!SCRIPT_EXTENSIONS.has(extname(source))) continue\n const text = await readFile(source, 'utf8')\n for (const reference of localReferences(source, text)) {\n // Worker/data assets never execute while the entry loads; the feature\n // that spawns them does, so their whole subtree is a lazy path.\n const lazy = reference.lazy || reference.kind === 'asset'\n try {\n const targets = reference.kind === 'module'\n ? [await resolveModule(source, reference.specifier, rootDir, importsMap)]\n : await expandAsset(resolve(dirname(source), reference.specifier), rootDir)\n edges.push({ lazy, targets })\n queue.push(...targets)\n } catch (error) {\n issues.push({\n file: source,\n kind: reference.kind,\n specifier: reference.specifier,\n detail: error instanceof Error ? error.message : String(error),\n lazy,\n })\n }\n }\n }\n // Pass 2: load-time reachability across non-lazy module edges only. This is\n // the set whose problems actually break `pi` (and pi2dsh) at extension load;\n // everything else fails at feature-use time, identically under both hosts.\n const loadTimeFiles = new Set<string>()\n const loadQueue = entries.map(path => resolve(path)).filter(path => graph.has(path))\n while (loadQueue.length > 0) {\n const source = loadQueue.shift() as string\n if (loadTimeFiles.has(source)) continue\n loadTimeFiles.add(source)\n for (const edge of graph.get(source) ?? []) {\n if (edge.lazy) continue\n for (const target of edge.targets) {\n if (!loadTimeFiles.has(target)) loadQueue.push(target)\n }\n }\n }\n // An issue found inside a file that itself only loads lazily cannot break\n // extension load either, however the reference is written.\n for (const issue of issues) {\n if (!loadTimeFiles.has(issue.file)) issue.lazy = true\n }\n return { files: [...graph.keys()].sort(), loadTimeFiles, issues }\n}\n","import { readFile } from 'node:fs/promises'\nimport { basename, extname, relative } from 'node:path'\nimport ts from 'typescript'\nimport {\n PI_CODING_AGENT_PACKAGES,\n PI_AI_PACKAGES,\n PI_TUI_PACKAGES,\n ruleForApi,\n ruleForContextProperty,\n ruleForEvent,\n ruleForHostImport,\n ruleForUiContextProperty,\n} from './compatibility.js'\nimport { collectLocalClosure, runtimeExternalPackages, SCRIPT_EXTENSIONS, sourceKind } from './module-graph.js'\nimport type {\n CompatibilityFinding,\n CompatibilityLevel,\n CompatibilityReport,\n ResolvedPiPackage,\n} from './types.js'\n\nfunction literalText(node: ts.Node | undefined): string | undefined {\n return node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))\n ? node.text\n : undefined\n}\n\nfunction hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === kind) === true\n}\n\nfunction parameterIdentifier(node: ts.SignatureDeclarationBase): string | undefined {\n const parameter = node.parameters[0]\n return parameter !== undefined && ts.isIdentifier(parameter.name) ? parameter.name.text : undefined\n}\n\nfunction extensionApiReceivers(source: ts.SourceFile): Set<string> {\n const receivers = new Set<string>()\n const functions = new Map<string, ts.FunctionLikeDeclarationBase>()\n\n function index(node: ts.Node): void {\n if (ts.isFunctionDeclaration(node) && node.name !== undefined) functions.set(node.name.text, node)\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)\n && node.initializer !== undefined\n && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {\n functions.set(node.name.text, node.initializer)\n }\n if (ts.isParameter(node) && node.type !== undefined\n && /(?:^|\\.)ExtensionAPI\\b/u.test(node.type.getText(source)) && ts.isIdentifier(node.name)) {\n receivers.add(node.name.text)\n }\n // Published Pi packages commonly ship JavaScript with type annotations\n // erased. `pi` is the documented ExtensionAPI parameter name throughout\n // the ecosystem, including helper functions reached from the entry point.\n if (ts.isParameter(node) && ts.isIdentifier(node.name)\n && /^(?:pi|extensionApi)$/iu.test(node.name.text)) {\n receivers.add(node.name.text)\n }\n ts.forEachChild(node, index)\n }\n index(source)\n\n for (const statement of source.statements) {\n if (ts.isFunctionDeclaration(statement)\n && hasModifier(statement, ts.SyntaxKind.ExportKeyword)\n && hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) {\n const name = parameterIdentifier(statement)\n if (name !== undefined) receivers.add(name)\n }\n if (ts.isExportAssignment(statement)) {\n const expression = statement.expression\n if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) {\n const name = parameterIdentifier(expression)\n if (name !== undefined) receivers.add(name)\n } else if (ts.isIdentifier(expression)) {\n const candidate = functions.get(expression.text)\n if (candidate !== undefined) {\n const name = parameterIdentifier(candidate)\n if (name !== undefined) receivers.add(name)\n }\n }\n }\n if (ts.isExportDeclaration(statement) && statement.moduleSpecifier === undefined\n && statement.exportClause !== undefined && ts.isNamedExports(statement.exportClause)) {\n for (const element of statement.exportClause.elements) {\n if (element.name.text !== 'default' || element.propertyName === undefined || !ts.isIdentifier(element.propertyName)) continue\n const candidate = functions.get(element.propertyName.text)\n if (candidate !== undefined) {\n const name = parameterIdentifier(candidate)\n if (name !== undefined) receivers.add(name)\n }\n }\n }\n }\n return receivers\n}\n\nfunction extensionApiProperties(source: ts.SourceFile, receivers: ReadonlySet<string>): Set<string> {\n const properties = new Set<string>()\n function visit(node: ts.Node): void {\n if ((ts.isPropertyDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name)) {\n const typed = node.type !== undefined && /(?:^|\\.)(?:Pi)?ExtensionAPI\\b/u.test(node.type.getText(source))\n if (typed || /^(?:pi|extensionApi)$/iu.test(node.name.text)) properties.add(node.name.text)\n } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken\n && ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === ts.SyntaxKind.ThisKeyword\n && ts.isIdentifier(node.right) && receivers.has(node.right.text)) {\n properties.add(node.left.name.text)\n }\n ts.forEachChild(node, visit)\n }\n visit(source)\n return properties\n}\n\nfunction enclosingFunctionName(node: ts.ParameterDeclaration): string | undefined {\n const parent = node.parent\n if (ts.isMethodDeclaration(parent) && parent.name !== undefined) return parent.name.getText()\n if ((ts.isArrowFunction(parent) || ts.isFunctionExpression(parent)) && ts.isPropertyAssignment(parent.parent)) {\n return parent.parent.name.getText()\n }\n return undefined\n}\n\nfunction extensionContextReceivers(source: ts.SourceFile): Set<string> {\n const receivers = new Set<string>()\n function visit(node: ts.Node): void {\n if (ts.isParameter(node) && ts.isIdentifier(node.name)) {\n const typedContext = node.type !== undefined\n && /(?:^|\\.)(?:Extension|ExtensionCommand|ToolExecution)Context\\b/u.test(node.type.getText(source))\n const conventionalHandlerContext = /^(?:ctx|context)$/iu.test(node.name.text)\n && /^(?:execute|handler)$/u.test(enclosingFunctionName(node) ?? '')\n if (typedContext || conventionalHandlerContext) receivers.add(node.name.text)\n }\n ts.forEachChild(node, visit)\n }\n visit(source)\n return receivers\n}\n\n// The three Pi packages whose named exports the shim audit tracks.\nconst PI_SHIMMED_PACKAGES = new Set<string>([\n ...PI_CODING_AGENT_PACKAGES,\n ...PI_TUI_PACKAGES,\n ...PI_AI_PACKAGES,\n])\n\n// Everything Pi's loader provides to extensions without a declaration —\n// exempt from the undeclared-runtime-dependency fatal, and (for typebox) not\n// subject to per-symbol shim auditing.\nconst PI_HOST_PACKAGES = new Set<string>([\n ...PI_SHIMMED_PACKAGES,\n 'typebox',\n '@sinclair/typebox',\n])\n\nfunction dependencyNames(packageJson: Record<string, unknown>): Set<string> {\n const names = new Set<string>()\n for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {\n const value = packageJson[field]\n if (typeof value !== 'object' || value === null || Array.isArray(value)) continue\n for (const [name, specifier] of Object.entries(value)) {\n if (typeof specifier === 'string') names.add(name)\n }\n }\n return names\n}\n\nfunction pushFinding(\n findings: CompatibilityFinding[],\n rootDir: string,\n file: string,\n source: ts.SourceFile,\n node: ts.Node,\n capability: string,\n level: CompatibilityLevel,\n detail: string,\n): void {\n const position = source.getLineAndCharacterOfPosition(node.getStart(source))\n findings.push({\n capability,\n level,\n file: relative(rootDir, file).replaceAll('\\\\', '/'),\n line: position.line + 1,\n detail,\n })\n}\n\nasync function analyzeExtension(rootDir: string, file: string): Promise<CompatibilityFinding[]> {\n const text = await readFile(file, 'utf8')\n const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, sourceKind(file))\n const findings: CompatibilityFinding[] = []\n const receivers = extensionApiReceivers(source)\n const apiProperties = extensionApiProperties(source, receivers)\n const contextReceivers = extensionContextReceivers(source)\n const methodAliases = new Map<string, string>()\n const eventBusAliases = new Set<string>()\n const uiAliases = new Set<string>()\n\n function reportHostImport(packageName: string, importedName: string, node: ts.Node): void {\n const matched = ruleForHostImport(packageName, importedName)\n if (matched === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, `host-import(${packageName}:${importedName})`, 'unsupported',\n `The pi2dsh host shim does not export ${JSON.stringify(importedName)} from ${JSON.stringify(packageName)}.`,\n )\n return\n }\n pushFinding(\n findings, rootDir, file, source, node, `host-import(${packageName}:${importedName})`, matched.level, matched.detail,\n )\n }\n\n for (const statement of source.statements) {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)\n && PI_SHIMMED_PACKAGES.has(statement.moduleSpecifier.text)) {\n const packageName = statement.moduleSpecifier.text\n const clause = statement.importClause\n if (clause === undefined) {\n reportHostImport(packageName, '<side-effect>', statement)\n continue\n }\n if (clause.isTypeOnly) continue\n if (clause.name !== undefined) reportHostImport(packageName, 'default', clause.name)\n if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {\n reportHostImport(packageName, '*', clause.namedBindings)\n } else if (clause.namedBindings !== undefined) {\n for (const element of clause.namedBindings.elements) {\n if (!element.isTypeOnly) reportHostImport(packageName, element.propertyName?.text ?? element.name.text, element)\n }\n }\n } else if (ts.isExportDeclaration(statement) && !statement.isTypeOnly\n && statement.moduleSpecifier !== undefined && ts.isStringLiteral(statement.moduleSpecifier)\n && PI_HOST_PACKAGES.has(statement.moduleSpecifier.text)) {\n const packageName = statement.moduleSpecifier.text\n if (statement.exportClause === undefined || ts.isNamespaceExport(statement.exportClause)) {\n reportHostImport(packageName, '*', statement)\n } else {\n for (const element of statement.exportClause.elements) {\n if (!element.isTypeOnly) reportHostImport(packageName, element.propertyName?.text ?? element.name.text, element)\n }\n }\n } else if (ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly\n && ts.isExternalModuleReference(statement.moduleReference)\n && ts.isStringLiteral(statement.moduleReference.expression)\n && PI_HOST_PACKAGES.has(statement.moduleReference.expression.text)) {\n reportHostImport(statement.moduleReference.expression.text, '*', statement)\n }\n }\n\n const declarations: ts.VariableDeclaration[] = []\n const isApiReceiver = (node: ts.Expression): boolean => ts.isIdentifier(node) && receivers.has(node.text)\n || (ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword\n && apiProperties.has(node.name.text))\n function collectDeclarations(node: ts.Node): void {\n if (ts.isVariableDeclaration(node)) declarations.push(node)\n ts.forEachChild(node, collectDeclarations)\n }\n collectDeclarations(source)\n\n for (let pass = 0; pass < declarations.length + 1; pass += 1) {\n let changed = false\n for (const declaration of declarations) {\n const initializer = declaration.initializer\n if (initializer === undefined) continue\n if (ts.isIdentifier(declaration.name) && isApiReceiver(initializer)) {\n if (!receivers.has(declaration.name.text)) {\n receivers.add(declaration.name.text)\n changed = true\n }\n }\n if (ts.isIdentifier(declaration.name) && ts.isIdentifier(initializer) && contextReceivers.has(initializer.text)) {\n if (!contextReceivers.has(declaration.name.text)) {\n contextReceivers.add(declaration.name.text)\n changed = true\n }\n }\n if (ts.isIdentifier(declaration.name) && ts.isPropertyAccessExpression(initializer)\n && initializer.name.text === 'ui' && ts.isIdentifier(initializer.expression)\n && contextReceivers.has(initializer.expression.text) && !uiAliases.has(declaration.name.text)) {\n uiAliases.add(declaration.name.text)\n changed = true\n }\n if (ts.isIdentifier(declaration.name) && ts.isPropertyAccessExpression(initializer)\n && isApiReceiver(initializer.expression)) {\n if (initializer.name.text === 'events') {\n if (!eventBusAliases.has(declaration.name.text)) {\n eventBusAliases.add(declaration.name.text)\n changed = true\n }\n } else if (!methodAliases.has(declaration.name.text)) {\n methodAliases.set(declaration.name.text, initializer.name.text)\n changed = true\n }\n }\n if (ts.isObjectBindingPattern(declaration.name) && isApiReceiver(initializer)) {\n for (const element of declaration.name.elements) {\n if (!ts.isIdentifier(element.name)) continue\n const method = element.propertyName !== undefined && ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : element.name.text\n if (method === 'events') {\n if (!eventBusAliases.has(element.name.text)) {\n eventBusAliases.add(element.name.text)\n changed = true\n }\n } else if (!methodAliases.has(element.name.text)) {\n methodAliases.set(element.name.text, method)\n changed = true\n }\n }\n }\n }\n if (!changed) break\n }\n\n function reportMethod(method: string, args: ts.NodeArray<ts.Expression>, node: ts.Node): void {\n if (method === 'on') {\n const event = literalText(args[0])\n if (event === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, 'on(<dynamic>)', 'unsupported',\n 'Dynamic event names cannot be audited or mapped safely.',\n )\n } else {\n const rule = ruleForEvent(event)\n pushFinding(findings, rootDir, file, source, node, `on(${event})`, rule.level, rule.detail)\n }\n return\n }\n const rule = ruleForApi(method)\n if (rule === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, method, 'unsupported',\n `Unknown ExtensionAPI method ${JSON.stringify(method)} cannot be audited or mapped safely.`,\n )\n return\n }\n pushFinding(findings, rootDir, file, source, node, method, rule.level, rule.detail)\n }\n\n function reportEventBus(method: string, node: ts.Node): void {\n const rule = ruleForApi('events')\n if ((method === 'on' || method === 'emit') && rule !== undefined) {\n pushFinding(findings, rootDir, file, source, node, `events.${method}`, rule.level, rule.detail)\n } else {\n pushFinding(\n findings, rootDir, file, source, node, `events.${method}`, 'unsupported',\n `Unknown Pi event-bus method ${JSON.stringify(method)} cannot be mapped safely.`,\n )\n }\n }\n\n function reportContext(property: string, node: ts.Node): void {\n const matched = ruleForContextProperty(property)\n if (matched === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, `ctx.${property}`, 'unsupported',\n `Unknown Pi extension-context property ${JSON.stringify(property)} cannot be audited or mapped safely.`,\n )\n } else {\n pushFinding(findings, rootDir, file, source, node, `ctx.${property}`, matched.level, matched.detail)\n }\n }\n\n function reportUiContext(property: string, node: ts.Node): void {\n const matched = ruleForUiContextProperty(property)\n if (matched === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, `ctx.ui.${property}`, 'unsupported',\n `Unknown Pi UI-context property ${JSON.stringify(property)} cannot be audited or mapped safely.`,\n )\n } else {\n pushFinding(findings, rootDir, file, source, node, `ctx.ui.${property}`, matched.level, matched.detail)\n }\n }\n\n function visit(node: ts.Node): void {\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {\n const method = methodAliases.get(node.expression.text)\n if (method !== undefined) reportMethod(method, node.arguments, node)\n } else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {\n const target = node.expression.expression\n if (isApiReceiver(target)) {\n reportMethod(node.expression.name.text, node.arguments, node)\n } else if (ts.isIdentifier(target) && eventBusAliases.has(target.text)) {\n reportEventBus(node.expression.name.text, node)\n } else if (ts.isPropertyAccessExpression(target)\n && target.name.text === 'events'\n && isApiReceiver(target.expression)) {\n reportEventBus(node.expression.name.text, node)\n }\n } else if (ts.isCallExpression(node) && ts.isElementAccessExpression(node.expression)\n && isApiReceiver(node.expression.expression)) {\n const method = literalText(node.expression.argumentExpression)\n if (method === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, '<dynamic-api-method>', 'unsupported',\n 'Dynamic ExtensionAPI method access cannot be audited or mapped safely.',\n )\n } else {\n reportMethod(method, node.arguments, node)\n }\n }\n if (ts.isPropertyAccessExpression(node)) {\n const target = node.expression\n if (ts.isPropertyAccessExpression(target) && target.name.text === 'ui'\n && ts.isIdentifier(target.expression) && contextReceivers.has(target.expression.text)) {\n reportUiContext(node.name.text, node)\n } else if (ts.isIdentifier(target) && uiAliases.has(target.text)) {\n reportUiContext(node.name.text, node)\n } else if (ts.isIdentifier(target) && contextReceivers.has(target.text) && node.name.text !== 'ui') {\n reportContext(node.name.text, node)\n }\n } else if (ts.isElementAccessExpression(node) && ts.isIdentifier(node.expression)\n && contextReceivers.has(node.expression.text)) {\n const property = literalText(node.argumentExpression)\n if (property === undefined) {\n pushFinding(\n findings, rootDir, file, source, node, 'ctx.<dynamic>', 'unsupported',\n 'Dynamic Pi extension-context access cannot be audited or mapped safely.',\n )\n } else if (property !== 'ui') {\n reportContext(property, node)\n }\n }\n ts.forEachChild(node, visit)\n }\n\n visit(source)\n return findings\n}\n\nexport async function analyzePackage(pkg: ResolvedPiPackage): Promise<CompatibilityReport> {\n const extensionClosure = await collectLocalClosure(pkg.rootDir, pkg.resources.extensions)\n const findings = (await Promise.all(\n extensionClosure.files.filter(file => SCRIPT_EXTENSIONS.has(extname(file)))\n .map(file => analyzeExtension(pkg.rootDir, file)),\n )).flat()\n\n if (pkg.resources.extensions.length > 0 && findings.length === 0) {\n findings.push({\n capability: 'static-audit',\n level: 'unsupported',\n file: pkg.resources.extensions.map(file => relative(pkg.rootDir, file).replaceAll('\\\\', '/')).join(', '),\n line: 1,\n detail: 'No ExtensionAPI use was statically proven across the local module closure; conversion fails closed instead of claiming compatibility.',\n })\n }\n for (const issue of extensionClosure.issues) {\n // Only a break on the load-time path blocks the package: Pi's own loader\n // fails the same lazy references at feature-use time, and the snapshot\n // preserves the published file layout, so behavior matches Pi exactly.\n const lazyIssue = issue.lazy || issue.kind === 'asset'\n findings.push({\n capability: `${issue.kind}(${issue.specifier})`,\n level: lazyIssue ? 'partial' : 'fatal',\n file: relative(pkg.rootDir, issue.file).replaceAll('\\\\', '/'),\n line: 1,\n detail: lazyIssue\n ? `Unresolved reference on a lazy path: ${issue.detail}. Extension load is unaffected; if the feature that evaluates it runs, it fails the same way under Pi (published file layout is preserved).`\n : `The local extension closure is incomplete: ${issue.detail}`,\n })\n }\n\n const declaredDependencies = dependencyNames(pkg.packageJson)\n for (const file of extensionClosure.files.filter(candidate => SCRIPT_EXTENSIONS.has(extname(candidate)))) {\n const text = await readFile(file, 'utf8')\n const lazyFile = !extensionClosure.loadTimeFiles.has(file)\n for (const use of runtimeExternalPackages(file, text)) {\n if (PI_HOST_PACKAGES.has(use.name) || declaredDependencies.has(use.name)) continue\n // Undeclared imports only crash extension load when they execute at load\n // time. On lazy paths (function-body dynamic imports, or files that are\n // themselves only lazily reachable) Pi degrades per-feature; mirror that.\n const lazyUse = use.lazy || lazyFile\n findings.push({\n capability: lazyUse ? `optional-lazy-dependency(${use.name})` : `undeclared-runtime-dependency(${use.name})`,\n level: lazyUse ? 'partial' : 'fatal',\n file: relative(pkg.rootDir, file).replaceAll('\\\\', '/'),\n line: 1,\n detail: lazyUse\n ? `The extension imports ${JSON.stringify(use.name)} only on a lazily-evaluated path without declaring it; the feature that needs it asks for the module at call time, exactly as under Pi (install ${use.name} to use that feature).`\n : `The extension imports ${JSON.stringify(use.name)} at load time, but the Pi package does not declare it as a dependency.`,\n })\n }\n }\n\n const resourceFinding = (file: string, capability: string, level: CompatibilityLevel, detail: string): CompatibilityFinding => ({\n capability,\n level,\n file: relative(pkg.rootDir, file).replaceAll('\\\\', '/'),\n line: 1,\n detail,\n })\n for (const file of pkg.resources.skills.filter(path => basename(path) === 'SKILL.md' || path.endsWith('.md'))) {\n findings.push(resourceFinding(file, 'skill', 'full', 'Copied as a DSH filesystem skill with its resource directory intact.'))\n }\n for (const file of pkg.resources.prompts) {\n findings.push(resourceFinding(file, 'prompt', 'full', 'Registered as a DSH slash command with Pi-compatible argument expansion.'))\n }\n for (const file of pkg.resources.themes) {\n findings.push(resourceFinding(file, 'theme', 'unsupported', 'Pi terminal themes have no effect in DSH Web or headless surfaces.'))\n }\n findings.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line || left.capability.localeCompare(right.capability))\n\n const summary: Record<CompatibilityLevel, number> = { full: 0, partial: 0, unsupported: 0, fatal: 0 }\n for (const finding of findings) summary[finding.level] += 1\n // Static analysis screens; it does not certify. Only fatal findings block a\n // bundle (it cannot be built or trusted). Everything else installs: verify\n // real behavior with the black-box run instead of trusting this verdict.\n const verdict = summary.fatal > 0 ? 'blocked' : summary.partial > 0 || summary.unsupported > 0 ? 'review' : 'ready'\n\n return {\n schemaVersion: 1,\n package: pkg.identity,\n verdict,\n summary,\n resources: {\n extensions: pkg.resources.extensions.map(file => relative(pkg.rootDir, file).replaceAll('\\\\', '/')),\n skills: pkg.resources.skills.map(file => relative(pkg.rootDir, file).replaceAll('\\\\', '/')),\n prompts: pkg.resources.prompts.map(file => relative(pkg.rootDir, file).replaceAll('\\\\', '/')),\n themes: pkg.resources.themes.map(file => relative(pkg.rootDir, file).replaceAll('\\\\', '/')),\n },\n findings,\n }\n}\n","import { cp, lstat, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { parse as parseYaml } from 'yaml'\nimport { analyzePackage } from './analyzer.js'\nimport { collectLocalClosure, runtimeExternalPackages, SCRIPT_EXTENSIONS } from './module-graph.js'\nimport type {\n CompatibilityReport,\n GenerateOptions,\n GeneratedRuntimeManifest,\n ResolvedPiPackage,\n} from './types.js'\n\ninterface PromptMetadata {\n name: string\n description: string\n argumentHint?: string\n path: string\n}\n\nconst SHIMMED_PI_HOST_PACKAGES = new Set([\n '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-coding-agent',\n '@earendil-works/pi-tui',\n '@mariozechner/pi-tui',\n '@earendil-works/pi-ai',\n '@mariozechner/pi-ai',\n // Host-provided in Pi's loader whitelist; the runtime aliases them too.\n 'typebox',\n '@sinclair/typebox',\n])\n\nfunction packageSlug(name: string): string {\n const slug = name.replace(/^@/u, '').replaceAll('/', '-').replace(/[^a-zA-Z0-9._-]+/gu, '-').toLowerCase()\n return slug.replace(/^-+|-+$/gu, '') || 'package'\n}\n\nfunction stringRecord(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}\n return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))\n}\n\nasync function assertEmptyOrMissing(path: string): Promise<void> {\n try {\n const info = await stat(path)\n if (!info.isDirectory()) throw new Error(`output exists and is not a directory: ${path}`)\n const entries = await readdir(path)\n if (entries.length > 0) throw new Error(`output directory is not empty: ${path}`)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n}\n\nfunction parseFrontmatter(text: string): { attributes: Record<string, string>; body: string } {\n const normalized = text.replace(/\\r\\n?/gu, '\\n')\n if (!normalized.startsWith('---')) return { attributes: {}, body: normalized }\n const endIndex = normalized.indexOf('\\n---', 3)\n if (endIndex === -1) return { attributes: {}, body: normalized }\n const raw: unknown = parseYaml(normalized.slice(4, endIndex))\n const attributes = typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? stringRecord(raw)\n : {}\n return { attributes, body: normalized.slice(endIndex + 4).trim() }\n}\n\nasync function assertNoSymlinks(path: string): Promise<void> {\n const info = await lstat(path)\n if (info.isSymbolicLink()) throw new Error(`refusing to copy symbolic link from Pi package: ${path}`)\n if (!info.isDirectory()) return\n for (const entry of await readdir(path)) await assertNoSymlinks(join(path, entry))\n}\n\nasync function copyExtensions(pkg: ResolvedPiPackage, outDir: string): Promise<{ entries: string[]; runtimePackages: Set<string>; skillScriptPackages: Set<string> }> {\n const copied: string[] = []\n const runtimePackages = new Set<string>()\n const closure = await collectLocalClosure(pkg.rootDir, pkg.resources.extensions)\n // Unresolved references never block the snapshot here: the analyzer grades\n // them (fatal only on the load-time path) and enforceReport is the gate.\n // The copy below preserves the published layout, so lazy dead references\n // behave exactly as they would under Pi.\n for (const issue of closure.issues) {\n console.warn(`pi2dsh: unresolved ${issue.kind} reference ${JSON.stringify(issue.specifier)} from ${relative(pkg.rootDir, issue.file)} (${issue.lazy ? 'lazy path — fails at feature use, as under Pi' : 'load-time path'})`)\n }\n for (const source of closure.files) {\n if (SCRIPT_EXTENSIONS.has(extname(source))) {\n const text = await readFile(source, 'utf8')\n // Lazy undeclared imports stay out of bundle dependencies: the package\n // works without them (Pi semantics) and they may not even be installable.\n // Lazy means the import site OR the whole file only evaluates on demand\n // (a top-level import inside a dynamically-imported module loads lazily).\n const lazyFile = !closure.loadTimeFiles.has(source)\n for (const use of runtimeExternalPackages(source, text)) {\n if ((!use.lazy && !lazyFile) || use.name in stringRecord(pkg.packageJson.dependencies)) runtimePackages.add(use.name)\n }\n }\n const sourceRelative = relative(pkg.rootDir, source).replaceAll('\\\\', '/')\n const targetRelative = `vendor/${sourceRelative}`\n const target = join(outDir, targetRelative)\n await mkdir(dirname(target), { recursive: true })\n await cp(source, target, { dereference: false })\n if (pkg.resources.extensions.map(entry => resolve(entry)).includes(source)) copied.push(targetRelative)\n }\n // Skill helper scripts run on the user's explicit request, not at extension\n // load; their imports (often themselves try/catch-guarded) are informational,\n // never a conversion blocker (mitsupi ships googleapis-using skill scripts\n // this way and works fine in Pi).\n const skillScriptPackages = new Set<string>()\n for (const source of pkg.resources.skills) {\n if (!SCRIPT_EXTENSIONS.has(extname(source))) continue\n const text = await readFile(source, 'utf8')\n for (const use of runtimeExternalPackages(source, text)) skillScriptPackages.add(use.name)\n }\n return { entries: copied, runtimePackages, skillScriptPackages }\n}\n\nasync function copySkills(pkg: ResolvedPiPackage, outDir: string): Promise<string[]> {\n const entryFiles = pkg.resources.skills.filter(file => basename(file) === 'SKILL.md' || file.endsWith('.md'))\n if (entryFiles.length === 0) return []\n const names = new Set<string>()\n for (const entry of entryFiles) {\n const isBundle = basename(entry) === 'SKILL.md'\n let name = isBundle ? basename(dirname(entry)) : basename(entry, '.md')\n if (names.has(name)) {\n // Same-named skills under different parents (piolium ships several):\n // disambiguate with the parent directory instead of refusing the package.\n const parent = basename(dirname(isBundle ? dirname(entry) : entry))\n const candidate = `${parent}-${name}`.replace(/[^a-zA-Z0-9._-]+/gu, '-')\n name = names.has(candidate) ? `${candidate}-${names.size}` : candidate\n }\n names.add(name)\n const target = join(outDir, 'skills', isBundle ? name : `${name}.md`)\n await mkdir(dirname(target), { recursive: true })\n const source = isBundle ? dirname(entry) : entry\n await assertNoSymlinks(source)\n await cp(source, target, { recursive: isBundle, dereference: false })\n }\n return ['skills']\n}\n\nasync function copyPrompts(pkg: ResolvedPiPackage, outDir: string): Promise<PromptMetadata[]> {\n const prompts: PromptMetadata[] = []\n const names = new Set<string>()\n for (const source of pkg.resources.prompts) {\n const name = basename(source, '.md').toLowerCase().replace(/[^a-z0-9_-]+/gu, '-')\n if (names.has(name)) throw new Error(`prompt command name collision while flattening Pi package: ${name}`)\n names.add(name)\n const targetRelative = `prompts/${name}.md`\n const target = join(outDir, targetRelative)\n await mkdir(dirname(target), { recursive: true })\n await assertNoSymlinks(source)\n await cp(source, target, { dereference: false })\n const { attributes, body } = parseFrontmatter(await readFile(source, 'utf8'))\n const firstLine = body.split(/\\r?\\n/u).map(line => line.trim()).find(Boolean)\n prompts.push({\n name,\n description: attributes.description ?? firstLine ?? `Run migrated Pi prompt ${name}`,\n ...(attributes['argument-hint'] !== undefined ? { argumentHint: attributes['argument-hint'] } : {}),\n path: targetRelative,\n })\n }\n return prompts\n}\n\nasync function copyNotices(pkg: ResolvedPiPackage, outDir: string): Promise<string[]> {\n const copied: string[] = []\n for (const entry of await readdir(pkg.rootDir)) {\n if (!/^(?:licen[cs]e|notice|copying)(?:[._-].*)?$/iu.test(entry)) continue\n const source = join(pkg.rootDir, entry)\n const info = await lstat(source)\n if (info.isSymbolicLink()) throw new Error(`refusing to copy symbolic link from Pi package: ${source}`)\n if (!info.isFile()) continue\n await cp(source, join(outDir, entry), { dereference: false })\n copied.push(entry)\n }\n return copied.sort()\n}\n\nfunction generatedPackageJson(\n pkg: ResolvedPiPackage,\n generatedName: string,\n runtimeSpec: string | undefined,\n runtimePackages: ReadonlySet<string>,\n hasSkills: boolean,\n): Record<string, unknown> {\n const declaredDependencies = {\n ...stringRecord(pkg.packageJson.dependencies),\n ...stringRecord(pkg.packageJson.optionalDependencies),\n ...stringRecord(pkg.packageJson.peerDependencies),\n }\n const externalRuntimePackages = [...runtimePackages].filter(name => !SHIMMED_PI_HOST_PACKAGES.has(name))\n const missing = externalRuntimePackages.filter(name => declaredDependencies[name] === undefined)\n if (missing.length > 0) {\n throw new Error(`runtime dependencies are imported but not declared by the Pi package: ${missing.join(', ')}`)\n }\n // Carry EVERY declared runtime dependency, not only statically detected\n // imports: packages load their own deps dynamically (computed require,\n // optional native backends) and the original manifest is the authority on\n // what they need.\n const declaredRuntime = {\n ...stringRecord(pkg.packageJson.dependencies),\n ...stringRecord(pkg.packageJson.optionalDependencies),\n }\n const dependencies = {\n ...Object.fromEntries(Object.entries(declaredRuntime).filter(([name]) => !SHIMMED_PI_HOST_PACKAGES.has(name))),\n ...Object.fromEntries(externalRuntimePackages.sort().map(name => [name, declaredDependencies[name]])),\n // The embedded runtime's own runtime dependencies (vendored Pi width math\n // uses get-east-asian-width; the pi-tui shim re-exports marked; typebox is\n // the host-provided schema library Pi's loader gives every extension;\n // vendored Pi bash tooling spawns through cross-spawn exactly as Pi does).\n ...(runtimeSpec === undefined\n ? { jiti: '^2.7.0', 'get-east-asian-width': '^1.6.0', marked: '^16.4.1', typebox: '^1.0.4', 'cross-spawn': '^7.0.6', diff: '^9.0.0' }\n : {}),\n // The real pi-ai wire clients back the single model directory: providers\n // without their own transport (models.json entries, catalog-only\n // packages) stream through them — a bundle is a deployment unit, so it\n // carries the transport library a Pi host would provide.\n '@earendil-works/pi-ai': '^0.84.1',\n ...(hasSkills ? { '@deepseek-ai/dsh-skill-filesystem': '^0.1.0-rc.6' } : {}),\n ...(runtimeSpec !== undefined ? { pi2dsh: runtimeSpec } : {}),\n }\n // Re-point the package's Node subpath-imports map (\"#x\": \"./src/x.js\") at\n // the vendored snapshot so '#'-imports keep resolving inside the bundle.\n const remapImports = (value: unknown): unknown => {\n if (typeof value === 'string') return value.startsWith('./') ? `./vendor/${value.slice(2)}` : value\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, remapImports(entry)]))\n }\n return value\n }\n const sourceImports = pkg.packageJson.imports\n return {\n name: generatedName,\n version: pkg.identity.version,\n description: `DeepSeek Harness adapter generated from ${pkg.identity.name}`,\n type: 'module',\n main: './index.js',\n ...(typeof sourceImports === 'object' && sourceImports !== null\n ? { imports: remapImports(sourceImports) as Record<string, unknown> }\n : {}),\n files: ['index.js', 'cordis.patch.yml', 'pi2dsh.manifest.json', 'pi2dsh.report.json', 'README.md', 'LICENSE*', 'NOTICE*', 'COPYING*', 'PI2DSH-LICENSE', 'runtime', 'vendor', 'skills', 'prompts'],\n dependencies,\n ...(runtimeSpec === undefined\n ? {\n peerDependencies: {\n '@deepseek-ai/dsh-llm': '^0.1.0-rc.6',\n '@deepseek-ai/dsh-system-prompt': '^0.1.0-rc.6',\n },\n }\n : {}),\n keywords: ['dsh-plugin', 'deepseek-harness', 'pi-package', 'pi2dsh'],\n license: typeof pkg.packageJson.license === 'string' ? pkg.packageJson.license : 'UNLICENSED',\n dsh: { bundle: { patch: './cordis.patch.yml' } },\n }\n}\n\nfunction generatedReadme(pkg: ResolvedPiPackage, packageName: string, report: CompatibilityReport): string {\n return `# ${packageName}\\n\\n`\n + `Generated by [pi2dsh](https://github.com/weijiafu14/pi2dsh) from \\`${pkg.identity.name}@${pkg.identity.version}\\`.\\n\\n`\n + `Compatibility verdict: **${report.verdict}** (full ${report.summary.full}, partial ${report.summary.partial}, unsupported ${report.summary.unsupported}).\\n\\n`\n + `Review \\`pi2dsh.report.json\\` before installation. This bundle executes the original Pi extension source and should only be installed when that source is trusted.\\n\\n`\n + `Install with DeepSeek Harness (keep the \\`file:\\` prefix so pnpm installs this bundle's dependencies instead of creating a bare link):\\n\\n`\n + `\\`\\`\\`sh\\ndsh plugin --profile headless add file:$PWD\\ndsh --profile headless --dump-config\\n\\`\\`\\`\\n\\n`\n + `If the install stops with \\`ERR_PNPM_IGNORED_BUILDS\\` (pnpm 10+ blocks dependency build scripts by default), approve the listed packages — either run \\`pnpm approve-builds\\` inside the profile directory, or set them to \\`true\\` under \\`allowBuilds\\` in the profile's \\`pnpm-workspace.yaml\\` — then re-run the add command.\\n`\n}\n\nfunction pluginSource(manifest: GeneratedRuntimeManifest, runtimeImport: string): string {\n const injections = ['tools', 'systemPrompt']\n if (manifest.prompts.length > 0 || manifest.report?.findings.some(item => item.capability === 'registerCommand') === true) {\n injections.push('commands')\n }\n if (manifest.skillDirs.length > 0) injections.push('skills')\n return `import { applyPiPackage } from ${JSON.stringify(runtimeImport)}\\n\\n`\n + `export const name = ${JSON.stringify(`pi2dsh:${packageSlug(manifest.package.name)}`)}\\n`\n + `export const inject = ${JSON.stringify(injections)}\\n\\n`\n + `const manifest = ${JSON.stringify(manifest, null, 2)}\\n\\n`\n + `export async function apply(ctx, config = {}) {\\n`\n + ` await applyPiPackage(ctx, { rootUrl: new URL('.', import.meta.url), manifest, config })\\n`\n + `}\\n`\n}\n\nasync function firstExisting(paths: string[]): Promise<string> {\n for (const path of paths) {\n try {\n await stat(path)\n return path\n } catch {\n // Try the next package/source layout.\n }\n }\n throw new Error(`cannot locate pi2dsh runtime artifact; tried: ${paths.join(', ')}`)\n}\n\nasync function copyEmbeddedRuntime(outDir: string): Promise<void> {\n const moduleDir = dirname(fileURLToPath(import.meta.url))\n const runtimeSource = await firstExisting([\n join(moduleDir, 'runtime.mjs'),\n join(moduleDir, '../dist/runtime.mjs'),\n ])\n const runtimeRoot = dirname(runtimeSource)\n const targetRoot = join(outDir, 'runtime')\n await mkdir(targetRoot, { recursive: true })\n // Copy every emitted module, including bundler-named shared chunks — a\n // fixed file list silently breaks whenever the bundler re-splits chunks.\n for (const entry of await readdir(runtimeRoot)) {\n if (entry.endsWith('.mjs')) await cp(join(runtimeRoot, entry), join(targetRoot, entry))\n }\n for (const sub of ['compat', join('compat', 'vendor')]) {\n const sourceDir = join(runtimeRoot, sub)\n try {\n const entries = await readdir(sourceDir)\n await mkdir(join(targetRoot, sub), { recursive: true })\n for (const entry of entries) {\n if (entry.endsWith('.mjs')) await cp(join(sourceDir, entry), join(targetRoot, sub, entry))\n }\n } catch {\n // dist layout without that subdirectory\n }\n }\n await cp(join(targetRoot, 'runtime.mjs'), join(targetRoot, 'pi2dsh-runtime.mjs'))\n const license = await firstExisting([join(moduleDir, '../LICENSE'), join(moduleDir, '../../LICENSE')])\n await cp(license, join(outDir, 'PI2DSH-LICENSE'))\n}\n\nfunction patchSource(generatedName: string, slug: string): string {\n return `- insert:\\n - id: pi2dsh-${slug}\\n name: ${JSON.stringify(generatedName)}\\n`\n}\n\nfunction enforceReport(report: CompatibilityReport, options: GenerateOptions): void {\n // Fatal findings (incomplete module closure, undeclared runtime deps,\n // resource escapes) mean the bundle cannot be built or trusted; no flag\n // bypasses them. Unsupported findings are explicit, load-safe degradations\n // — the bundle installs and the black-box run decides real usability.\n if (report.summary.fatal > 0) {\n throw new Error(\n `conversion blocked: ${report.summary.fatal} fatal finding(s) — the bundle cannot be built or trusted; run inspect for details`,\n )\n }\n if (options.strict && (report.summary.partial > 0 || report.summary.unsupported > 0)) {\n throw new Error('strict conversion requires every detected Pi API use to have full compatibility')\n }\n}\n\nexport async function generateBundle(\n pkg: ResolvedPiPackage,\n options: GenerateOptions,\n): Promise<{ outDir: string; report: CompatibilityReport; packageName: string }> {\n const outDir = resolve(options.outDir)\n const report = await analyzePackage(pkg)\n enforceReport(report, options)\n await assertEmptyOrMissing(outDir)\n await mkdir(outDir, { recursive: true })\n\n const slug = packageSlug(pkg.identity.name)\n const packageName = `dsh-pi-${slug}`\n const extensionSnapshot = await copyExtensions(pkg, outDir)\n const skillDirs = await copySkills(pkg, outDir)\n const prompts = await copyPrompts(pkg, outDir)\n await copyNotices(pkg, outDir)\n const manifest: GeneratedRuntimeManifest = {\n schemaVersion: 1,\n package: pkg.identity,\n extensions: extensionSnapshot.entries,\n skillDirs,\n prompts,\n report,\n }\n const runtimeSpec = options.runtimeSpec\n if (runtimeSpec === undefined) await copyEmbeddedRuntime(outDir)\n const optionalSkillDeps = [...extensionSnapshot.skillScriptPackages]\n .filter(name => !SHIMMED_PI_HOST_PACKAGES.has(name) && !(name in stringRecord(pkg.packageJson.dependencies)))\n if (optionalSkillDeps.length > 0) {\n console.warn(`pi2dsh: skill helper scripts reference ${optionalSkillDeps.join(', ')}; install them only if you use those skills`)\n }\n\n await Promise.all([\n writeFile(join(outDir, 'package.json'), `${JSON.stringify(generatedPackageJson(pkg, packageName, runtimeSpec, extensionSnapshot.runtimePackages, skillDirs.length > 0), null, 2)}\\n`),\n writeFile(join(outDir, 'pi2dsh.manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`),\n writeFile(join(outDir, 'pi2dsh.report.json'), `${JSON.stringify(report, null, 2)}\\n`),\n writeFile(join(outDir, 'index.js'), pluginSource(manifest, runtimeSpec === undefined ? './runtime/pi2dsh-runtime.mjs' : 'pi2dsh/runtime')),\n writeFile(join(outDir, 'cordis.patch.yml'), patchSource(packageName, slug)),\n writeFile(join(outDir, 'README.md'), generatedReadme(pkg, packageName, report)),\n ])\n return { outDir, report, packageName }\n}\n","// Pi MCP configuration -> DSH mcp-client patch entries.\n//\n// Pi (via pi-mcp-adapter) reads the standard `mcpServers` files. DSH ships an\n// official MCP client (`@deepseek-ai/dsh-mcp-client`) configured through\n// cordis patch layers — so migration is config translation, not running Pi's\n// adapter code. This module reads Pi's documented six-layer precedence,\n// resolves `disabled` flags, and emits one patch entry per enabled server.\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { getAgentDir } from './compat/vendor/pi-config-shim.js'\n\ntype UnknownRecord = Record<string, unknown>\n\nexport interface PiMcpServer {\n name: string\n sourcePath: string\n transport: 'stdio' | 'streamable-http'\n command?: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n url?: string\n headers?: Record<string, string>\n disabled: boolean\n}\n\nexport interface McpConversionWarning {\n server: string\n message: string\n}\n\nexport interface McpConversionResult {\n servers: PiMcpServer[]\n entries: UnknownRecord[]\n warnings: McpConversionWarning[]\n sources: string[]\n}\n\n/** Pi's documented config precedence, lowest to highest. */\nexport function piMcpConfigPaths(cwd: string): string[] {\n const home = homedir()\n return [\n join(home, '.config', 'mcp', 'mcp.json'),\n join(home, '.agents', 'mcp.json'),\n join(home, '.agents', 'mcp', 'mcp.json'),\n join(getAgentDir(), 'mcp.json'),\n join(cwd, '.mcp.json'),\n join(cwd, '.pi', 'mcp.json'),\n ]\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const entries = Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n return entries.length === 0 ? undefined : Object.fromEntries(entries)\n}\n\nfunction parseServer(name: string, raw: unknown, sourcePath: string): PiMcpServer | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined\n const record = raw as UnknownRecord\n const disabled = record.disabled === true\n if (typeof record.url === 'string') {\n return {\n name, sourcePath, transport: 'streamable-http', url: record.url,\n ...(stringRecord(record.headers) === undefined ? {} : { headers: stringRecord(record.headers)! }),\n disabled,\n }\n }\n if (typeof record.command === 'string') {\n return {\n name, sourcePath, transport: 'stdio', command: record.command,\n ...(Array.isArray(record.args) ? { args: record.args.map(String) } : {}),\n ...(stringRecord(record.env) === undefined ? {} : { env: stringRecord(record.env)! }),\n ...(typeof record.cwd === 'string' ? { cwd: record.cwd } : {}),\n disabled,\n }\n }\n return undefined\n}\n\nexport function collectPiMcpServers(cwd: string, extraPaths: string[] = []): { servers: Map<string, PiMcpServer>; sources: string[] } {\n const servers = new Map<string, PiMcpServer>()\n const sources: string[] = []\n for (const path of [...piMcpConfigPaths(cwd), ...extraPaths]) {\n if (!existsSync(path)) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'))\n } catch {\n continue\n }\n const mcpServers = (parsed as UnknownRecord | undefined)?.mcpServers\n if (typeof mcpServers !== 'object' || mcpServers === null) continue\n sources.push(path)\n for (const [name, raw] of Object.entries(mcpServers)) {\n const record = raw as UnknownRecord | null\n const existing = servers.get(name)\n // Later (higher-precedence) layers override whole entries; a bare\n // `disabled` toggle updates the effective server from a lower layer.\n if (existing !== undefined && typeof record === 'object' && record !== null\n && record.command === undefined && record.url === undefined && typeof record.disabled === 'boolean') {\n servers.set(name, { ...existing, disabled: record.disabled, sourcePath: path })\n continue\n }\n const server = parseServer(name, raw, path)\n if (server !== undefined) servers.set(name, server)\n }\n }\n return { servers, sources }\n}\n\nconst SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/u\nconst ENV_REFERENCE_PATTERN = /^\\$\\{?([A-Za-z_][A-Za-z0-9_]*)\\}?$/u\nconst SECRETISH_KEY_PATTERN = /token|secret|key|password|credential/iu\n\ninterface JsExpression {\n __pi2dshJs: string\n}\n\nfunction js(expression: string): JsExpression {\n return { __pi2dshJs: expression }\n}\n\nfunction convertValueMap(\n server: string,\n kind: 'env' | 'headers',\n values: Record<string, string> | undefined,\n warnings: McpConversionWarning[],\n): Record<string, string | JsExpression> | undefined {\n if (values === undefined) return undefined\n const output: Record<string, string | JsExpression> = {}\n for (const [key, value] of Object.entries(values)) {\n const reference = ENV_REFERENCE_PATTERN.exec(value)\n if (reference !== null) {\n output[key] = js(`process.env.${reference[1]}`)\n continue\n }\n if (SECRETISH_KEY_PATTERN.test(key)) {\n warnings.push({\n server,\n message: `${kind}.${key} carries a literal value; move the secret to an environment variable and reference it as $NAME so the patch stays credential-free`,\n })\n }\n output[key] = value\n }\n return output\n}\n\nexport function convertPiMcpConfig(cwd: string, extraPaths: string[] = []): McpConversionResult {\n const { servers, sources } = collectPiMcpServers(cwd, extraPaths)\n const warnings: McpConversionWarning[] = []\n const entries: UnknownRecord[] = []\n for (const server of servers.values()) {\n if (server.disabled) {\n warnings.push({ server: server.name, message: 'skipped: disabled in Pi configuration' })\n continue\n }\n if (!SERVER_NAME_PATTERN.test(server.name)) {\n warnings.push({\n server: server.name,\n message: 'skipped: DSH serverName must match [A-Za-z0-9_-]{1,32}; rename the server in the Pi config',\n })\n continue\n }\n const config: UnknownRecord = { serverName: server.name, transport: server.transport }\n if (server.transport === 'stdio') {\n config.command = server.command\n if (server.args !== undefined) config.args = server.args\n const env = convertValueMap(server.name, 'env', server.env, warnings)\n if (env !== undefined) config.env = env\n if (server.cwd !== undefined) config.cwd = server.cwd\n } else {\n config.url = server.url\n const headers = convertValueMap(server.name, 'headers', server.headers, warnings)\n if (headers !== undefined) config.headers = headers\n }\n entries.push({ id: `mcp-${server.name}`, name: '@deepseek-ai/dsh-mcp-client', config })\n }\n return { servers: [...servers.values()], entries, warnings, sources }\n}\n\nfunction yamlScalar(value: unknown, indent: string): string {\n if (typeof value === 'object' && value !== null && '__pi2dshJs' in (value as JsExpression)) {\n return `!!js ${(value as JsExpression).__pi2dshJs}`\n }\n if (typeof value === 'string') {\n return /^[A-Za-z0-9@._\\/:-]+$/u.test(value) ? value : JSON.stringify(value)\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]'\n return `\\n${value.map(item => `${indent} - ${yamlScalar(item, `${indent} `)}`).join('\\n')}`\n }\n if (typeof value === 'object' && value !== null) {\n const record = value as UnknownRecord\n const keys = Object.keys(record)\n if (keys.length === 0) return '{}'\n return `\\n${keys.map(key => `${indent} ${key}: ${yamlScalar(record[key], `${indent} `)}`).join('\\n')}`\n }\n return String(value)\n}\n\n/** Render the converted entries as a cordis.patch.yml `insert` block. */\nexport function renderMcpPatch(result: McpConversionResult): string {\n if (result.entries.length === 0) return '# no enabled MCP servers found in Pi configuration\\n'\n const lines: string[] = ['- insert:']\n for (const entry of result.entries) {\n lines.push(` - id: ${String(entry.id)}`)\n lines.push(` name: '@deepseek-ai/dsh-mcp-client'`)\n lines.push(` inject: [tools]`)\n lines.push(` config:${yamlScalar(entry.config, ' ')}`)\n }\n return `${lines.join('\\n')}\\n`\n}\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,QAAQ,OAA2B,YAA0B;CAAE;CAAO;AAAO;AAEnF,MAAa,2BAA2B,OAAO,OAAO,CACpD,mCACA,+BACF,CAAU;AAEV,MAAa,kBAAkB,OAAO,OAAO,CAC3C,0BACA,sBACF,CAAU;AAEV,MAAa,iBAAiB,OAAO,OAAO,CAC1C,yBACA,qBACF,CAAU;AAEV,MAAM,WAAW;AACjB,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,cAAc;AAEpB,MAAa,oBAA8E,OAAO,OAAO;CACvG,mBAAmB,OAAO,OAAO;EAC/B,YAAY,KAAK,QAAQ,6BAA6B;EACtD,iBAAiB,KAAK,WAAW,gGAAgG;EACjI,mBAAmB,KAAK,QAAQ,QAAQ;EACxC,mBAAmB,KAAK,QAAQ,QAAQ;EACxC,SAAS,KAAK,WAAW,wEAAwE;EACjG,yBAAyB,KAAK,QAAQ,QAAQ;EAC9C,aAAa,KAAK,WAAW,kFAAkF;EAC/G,eAAe,KAAK,WAAW,uDAAuD;EACtF,YAAY,KAAK,QAAQ,QAAQ;EACjC,cAAc,KAAK,QAAQ,QAAQ;EACnC,cAAc,KAAK,QAAQ,QAAQ;EACnC,cAAc,KAAK,QAAQ,QAAQ;EACnC,uBAAuB,KAAK,QAAQ,QAAQ;EAC5C,gBAAgB,KAAK,QAAQ,GAAG,SAAS,2DAA2D;EACpG,qBAAqB,KAAK,QAAQ,QAAQ;EAC1C,uBAAuB,KAAK,QAAQ,QAAQ;EAC5C,0BAA0B,KAAK,QAAQ,QAAQ;EAC/C,+BAA+B,KAAK,QAAQ,QAAQ;EACpD,qB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W;CACpC,KAAK,MAAM,SAAS,OAAO,SAAS;EAClC,MAAM,KAAK,aAAa,OAAO,MAAM,EAAE,GAAG;EAC1C,MAAM,KAAK,2CAA2C;EACtD,MAAM,KAAK,uBAAuB;EAClC,MAAM,KAAK,gBAAgB,WAAW,MAAM,QAAQ,QAAQ,GAAG;CACjE;CACA,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC7B"}
|
|
@@ -6,9 +6,9 @@ import { access, open, readFile, readdir, realpath, stat } from "node:fs/promise
|
|
|
6
6
|
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
7
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
8
|
import { constants, createWriteStream, existsSync, readFileSync } from "node:fs";
|
|
9
|
-
import { randomBytes } from "node:crypto";
|
|
10
9
|
import * as os from "node:os";
|
|
11
10
|
import { homedir, tmpdir } from "node:os";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
12
|
import { randomUUID as randomUUID$1 } from "crypto";
|
|
13
13
|
import { appendFileSync as appendFileSync$1, closeSync, constants as constants$1, createReadStream, existsSync as existsSync$1, mkdirSync as mkdirSync$1, openSync, readSync, readdirSync, statSync, writeFileSync as writeFileSync$1 } from "fs";
|
|
14
14
|
import { access as access$1, mkdir as mkdir$1, readFile as readFile$1, readdir as readdir$1, stat as stat$1, writeFile as writeFile$1 } from "fs/promises";
|
|
@@ -5299,4 +5299,4 @@ function rawKeyHint(key, description) {
|
|
|
5299
5299
|
//#endregion
|
|
5300
5300
|
export { isBashToolResult as $, buildSessionContext as $t, copyToClipboard as A, createGrepToolDefinition as At, generateSummary as B, createLocalBashOperations as Bt, ToolExecutionComponent as C, wrapRegisteredTool as Ct, calculateContextTokens as D, createFindTool as Dt, __setSubagentSessionFactory as E, createLsToolDefinition as Et, defineTool as F, createReadTool as Ft, getPackageDir as G, formatSize$1 as Gt, getBinDir as H, withFileMutationQueue$1 as Ht, ensureTool as I, createReadToolDefinition as It, getSettingsListTheme as J, truncateTail$1 as Jt, getReadmePath as K, truncateHead$1 as Kt, estimateTokens as L, bashToolSystemPromptContribution as Lt, createCodingTools as M, createWriteToolDefinition as Mt, createEventBus as N, createEditTool as Nt, compact as O, createFindToolDefinition as Ot, createReadOnlyTools as P, createEditToolDefinition as Pt, initTheme as Q, buildContextEntries as Qt, findCutPoint as R, createBashTool as Rt, Theme as S, truncateToVisualLines as St, VERSION as T, createLsTool as Tt, getLanguageFromPath as U, DEFAULT_MAX_BYTES$1 as Ut, generateSummaryWithUsage as V, createExtensionRuntime as Vt, getMarkdownTheme as W, DEFAULT_MAX_LINES$1 as Wt, getToolPath as X, SessionManager as Xt, getShellConfig as Y, CURRENT_SESSION_VERSION as Yt, highlightCode as Z, assertValidSessionId as Zt, ModelRegistry as _, resizeImage as _t, CustomMessageComponent as a, parseSessionEntries as an, isToolCallEventType as at, SettingsManager as b, stripFrontmatter as bt, DefaultResourceLoader as c, BRANCH_SUMMARY_SUFFIX as cn, keyText as ct, ExtensionInputComponent as d, bashExecutionToText as dn, parseFrontmatter as dt, findMostRecentSession as en, isEditToolResult as et, ExtensionRunner as f, convertToLlm as fn, parseSkillBlock as ft, InMemorySettingsStorage as g, renderDiff as gt, FooterComponent as h, createCustomMessage as hn, readStoredCredential as ht, CustomEditor as i, migrateSessionEntries as in, isReadToolResult as it, createAgentSession as j, createWriteTool as jt, convertToPng as k, createGrepTool as kt, DynamicBorder as l, COMPACTION_SUMMARY_PREFIX as ln, loadSkills as lt, FileSettingsStorage as m, createCompactionSummaryMessage as mn, rawKeyHint as mt, BorderedLoader as n, getLatestCompactionEntry as nn, isGrepToolResult as nt, DEFAULT_COMPACTION_SETTINGS as o, sessionEntryToContextMessages as on, isWriteToolResult as ot, ExtensionSelectorComponent as p, createBranchSummaryMessage as pn, processImage as pt, getSelectListTheme as q, truncateLine$1 as qt, CONFIG_DIR_NAME as r, loadEntriesFromFile as rn, isLsToolResult as rt, DefaultPackageManager as s, BRANCH_SUMMARY_PREFIX as sn, keyHint as st, AssistantMessageComponent as t, getDefaultSessionDir as tn, isFindToolResult as tt, ExtensionEditorComponent as u, COMPACTION_SUMMARY_SUFFIX as un, loadSkillsFromDir as ut, ModelRuntime as v, serializeConversation as vt, UserMessageComponent as w, formatSkillsForPrompt as wt, SettingsSelectorComponent as x, theme as xt, ProjectTrustStore as y, shouldCompact as yt, generateBranchSummary as z, createBashToolDefinition as zt };
|
|
5301
5301
|
|
|
5302
|
-
//# sourceMappingURL=pi-coding-agent-
|
|
5302
|
+
//# sourceMappingURL=pi-coding-agent-C9Y9ql5E.mjs.map
|