pi2dsh 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +4 -1
  2. package/README.zh.md +4 -1
  3. package/dist/{analyzer-C86ba-27.mjs → analyzer-CsrBeS8r.mjs} +2 -2
  4. package/dist/{analyzer-C86ba-27.mjs.map → analyzer-CsrBeS8r.mjs.map} +1 -1
  5. package/dist/cli.mjs +3 -3
  6. package/dist/compat/pi-ai.d.mts +2 -1
  7. package/dist/compat/pi-ai.d.mts.map +1 -1
  8. package/dist/compat/pi-ai.mjs +2 -3
  9. package/dist/compat/pi-coding-agent.d.mts +259 -29
  10. package/dist/compat/pi-coding-agent.d.mts.map +1 -1
  11. package/dist/compat/pi-coding-agent.mjs +2 -2
  12. package/dist/credentials-oauth.mjs +2 -2
  13. package/dist/{generator-C0jNM-yu.mjs → generator-CSOv6wYT.mjs} +2 -2
  14. package/dist/{generator-C0jNM-yu.mjs.map → generator-CSOv6wYT.mjs.map} +1 -1
  15. package/dist/host.mjs +1 -1
  16. package/dist/index.mjs +4 -4
  17. package/dist/{mcp-config-Dlou-ZA-.mjs → mcp-config-Cn5gWemZ.mjs} +29 -29
  18. package/dist/mcp-config-Cn5gWemZ.mjs.map +1 -0
  19. package/dist/{pi-ai-BA3h0Dwv.mjs → pi-ai-Dyg4zyLZ.mjs} +196 -75
  20. package/dist/pi-ai-Dyg4zyLZ.mjs.map +1 -0
  21. package/dist/{pi-coding-agent-CznNsOnV.mjs → pi-coding-agent-Ctw-BhoY.mjs} +0 -0
  22. package/dist/pi-coding-agent-Ctw-BhoY.mjs.map +1 -0
  23. package/dist/{runtime-DMEJknhK.mjs → runtime-Ce3PTbWU.mjs} +417 -135
  24. package/dist/runtime-Ce3PTbWU.mjs.map +1 -0
  25. package/dist/runtime.d.mts.map +1 -1
  26. package/dist/runtime.mjs +1 -1
  27. package/package.json +5 -3
  28. package/dist/mcp-config-Dlou-ZA-.mjs.map +0 -1
  29. package/dist/pi-ai-BA3h0Dwv.mjs.map +0 -1
  30. package/dist/pi-coding-agent-CznNsOnV.mjs.map +0 -1
  31. package/dist/pi-uuid-Db8ShZsK.mjs +0 -47
  32. package/dist/pi-uuid-Db8ShZsK.mjs.map +0 -1
  33. package/dist/runtime-DMEJknhK.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
- import { r as registerVisionCompanions } from "./runtime-DMEJknhK.mjs";
2
+ import { r as registerVisionCompanions } from "./runtime-Ce3PTbWU.mjs";
3
3
  import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
4
4
  import { applyPiHost, generateHostBundle, manifestForInstalled } from "./host.mjs";
5
- import { a as CONTEXT_RULES, c as PI_AI_PACKAGES, d as UI_CONTEXT_RULES, f as ruleForApi, g as ruleForUiContextProperty, h as ruleForHostImport, i as API_RULES, l as PI_CODING_AGENT_PACKAGES, m as ruleForEvent, n as convertPiMcpConfig, o as EVENT_RULES, p as ruleForContextProperty, r as renderMcpPatch, s as HOST_IMPORT_RULES, t as collectPiMcpServers, u as PI_TUI_PACKAGES } from "./mcp-config-Dlou-ZA-.mjs";
5
+ import { a as CONTEXT_RULES, c as PI_AI_PACKAGES, d as UI_CONTEXT_RULES, f as ruleForApi, g as ruleForUiContextProperty, h as ruleForHostImport, i as API_RULES, l as PI_CODING_AGENT_PACKAGES, m as ruleForEvent, n as convertPiMcpConfig, o as EVENT_RULES, p as ruleForContextProperty, r as renderMcpPatch, s as HOST_IMPORT_RULES, t as collectPiMcpServers, u as PI_TUI_PACKAGES } from "./mcp-config-Cn5gWemZ.mjs";
6
6
  import { readFile } from "node:fs/promises";
7
7
  import { existsSync } from "node:fs";
8
8
  import { dirname, join } from "node:path";
@@ -114,7 +114,7 @@ async function apply(ctx, config = {}) {
114
114
  * @returns the compatibility report.
115
115
  */
116
116
  async function analyzePackage(pkg) {
117
- const { analyzePackage: run } = await import("./analyzer-C86ba-27.mjs");
117
+ const { analyzePackage: run } = await import("./analyzer-CsrBeS8r.mjs");
118
118
  return run(pkg);
119
119
  }
120
120
  /**
@@ -123,7 +123,7 @@ async function analyzePackage(pkg) {
123
123
  * @returns the generation result.
124
124
  */
125
125
  async function generateBundle(...args) {
126
- const { generateBundle: run } = await import("./generator-C0jNM-yu.mjs");
126
+ const { generateBundle: run } = await import("./generator-CSOv6wYT.mjs");
127
127
  return run(...args);
128
128
  }
129
129
  //#endregion
@@ -13,9 +13,9 @@ const PI_TUI_PACKAGES = Object.freeze(["@earendil-works/pi-tui", "@mariozechner/
13
13
  const PI_AI_PACKAGES = Object.freeze(["@earendil-works/pi-ai", "@mariozechner/pi-ai"]);
14
14
  const VENDORED = "Vendored byte-identical from Pi, so semantics match Pi exactly.";
15
15
  const HEADLESS_COMPONENT = "Constructible headless component with Pi-exact signatures; renders plain text, never a terminal.";
16
- const RUNTIME_STUB = "Importable, but calling it fails explicitly: it belongs to Pi's internal agent runtime and needs a native DSH port.";
17
16
  const VENDORED_TOOL = "Pi's built-in tool constructor, vendored byte-identical with its pure-logic closure.";
18
17
  const EVENT_GUARD = "Pi's exact one-line tool-event guard, reimplemented verbatim.";
18
+ const VENDORED_SUMMARIZER = "Vendored Pi logic; the model call fills Pi's own streamFn injection point with the DSH llm bridge when the caller passes none, so summarization runs on the ONE model path. Without a mounted llm service it fails explicitly.";
19
19
  const HOST_IMPORT_RULES = Object.freeze({
20
20
  "pi-coding-agent": Object.freeze({
21
21
  defineTool: rule("full", "Identity helper, preserved."),
@@ -47,18 +47,18 @@ const HOST_IMPORT_RULES = Object.freeze({
47
47
  createBranchSummaryMessage: rule("full", VENDORED),
48
48
  createCompactionSummaryMessage: rule("full", VENDORED),
49
49
  bashExecutionToText: rule("full", VENDORED),
50
- estimateTokens: rule("full", "Reimplements Pi's chars/4 heuristic over the same message roles."),
51
- calculateContextTokens: rule("full", "Sums the Pi chars/4 heuristic across messages."),
52
- DEFAULT_COMPACTION_SETTINGS: rule("full", "Pi's default compaction thresholds, preserved as constants."),
53
- serializeConversation: rule("partial", "JSON serialization without Pi's prompt-oriented formatting."),
54
- shouldCompact: rule("partial", "Always reports false: DSH owns compaction scheduling."),
55
- compact: rule("unsupported", "Pi compaction execution belongs to DSH's native compaction plugin; calling fails explicitly."),
56
- findCutPoint: rule("unsupported", RUNTIME_STUB),
57
- generateSummary: rule("unsupported", RUNTIME_STUB),
58
- generateSummaryWithUsage: rule("unsupported", RUNTIME_STUB),
59
- generateBranchSummary: rule("unsupported", RUNTIME_STUB),
60
- parseFrontmatter: rule("full", "Frontmatter parsing with Pi-compatible semantics."),
61
- stripFrontmatter: rule("full", "Frontmatter stripping with Pi-compatible semantics."),
50
+ estimateTokens: rule("full", VENDORED),
51
+ calculateContextTokens: rule("full", `${VENDORED} Pi\'s Usage-based total (an earlier reimplementation summed message estimates — same name, different meaning — and was replaced).`),
52
+ DEFAULT_COMPACTION_SETTINGS: rule("full", VENDORED),
53
+ serializeConversation: rule("full", VENDORED),
54
+ shouldCompact: rule("full", `${VENDORED} The pure threshold check; DSH still owns automatic compaction scheduling.`),
55
+ compact: rule("partial", VENDORED_SUMMARIZER),
56
+ findCutPoint: rule("full", VENDORED),
57
+ generateSummary: rule("partial", VENDORED_SUMMARIZER),
58
+ generateSummaryWithUsage: rule("partial", VENDORED_SUMMARIZER),
59
+ generateBranchSummary: rule("partial", VENDORED_SUMMARIZER),
60
+ parseFrontmatter: rule("full", `${VENDORED} Returns Pi\'s public { frontmatter, body } shape with YAML-parsed values (an earlier reimplementation returned { attributes } with string values and was replaced).`),
61
+ stripFrontmatter: rule("full", VENDORED),
62
62
  copyToClipboard: rule("partial", "Attempts the platform clipboard command (pbcopy/clip/wl-copy/xclip); resolves false when none succeeds."),
63
63
  resizeImage: rule("partial", "Passes images through un-resized; Pi resizes only to save tokens, so content is preserved."),
64
64
  convertToPng: rule("partial", "PNG input passes through; other formats fail explicitly without Pi's wasm codec."),
@@ -80,11 +80,11 @@ const HOST_IMPORT_RULES = Object.freeze({
80
80
  createEventBus: rule("full", "Pi event-bus semantics: async handler isolation and unsubscribe functions."),
81
81
  readStoredCredential: rule("partial", "Reads Pi-style auth.json from the pi2dsh-owned agent directory; DSH credentials stay authoritative for DSH model calls."),
82
82
  parseSkillBlock: rule("full", "Pi's skill_content block parser, reimplemented over the same wire shape."),
83
- wrapRegisteredTool: rule("unsupported", RUNTIME_STUB),
84
- ProjectTrustStore: rule("unsupported", RUNTIME_STUB),
83
+ wrapRegisteredTool: rule("full", `${VENDORED} The runner argument is used exactly as Pi uses it (createContext + getActiveTools), which the pi2dsh projection provides.`),
84
+ ProjectTrustStore: rule("partial", `${VENDORED} The store operates on trust.json under the caller\'s agentDir — with the redirected getAgentDir convention that is package-visible state inside the DSH-owned pi2dsh directory. The DSH host never consults it; host trust stays a DSH decision (ctx.isProjectTrusted fails closed).`),
85
85
  DefaultResourceLoader: rule("partial", "A headless resource loader honoring overrides, with empty discovery sets."),
86
- DefaultPackageManager: rule("unsupported", RUNTIME_STUB),
87
- ModelRuntime: rule("unsupported", RUNTIME_STUB),
86
+ DefaultPackageManager: rule("unsupported", "Installing packages is owned by the DSH host and its security gates (dsh plugin add/remove behind pnpm's build-script approval). Importing it is flagged at mount time (startup check); constructing it throws a structured PiCapabilityError, and doing so during entry setup marks the package unusable."),
87
+ ModelRuntime: rule("unsupported", "Standalone model stacks are owned by the DSH host llm configuration; packages read the ONE directory through ctx.modelRegistry. Importing it is flagged at mount time (startup check); constructing it throws a structured PiCapabilityError, and doing so during entry setup marks the package unusable."),
88
88
  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."),
89
89
  createCodingTools: rule("full", "Pi's exact tool set composed from the vendored built-in constructors."),
90
90
  createReadOnlyTools: rule("full", "Pi's exact read-only tool set composed from the vendored built-in constructors."),
@@ -110,8 +110,8 @@ const HOST_IMPORT_RULES = Object.freeze({
110
110
  isGrepToolResult: rule("full", EVENT_GUARD),
111
111
  isFindToolResult: rule("full", EVENT_GUARD),
112
112
  isLsToolResult: rule("full", EVENT_GUARD),
113
- loadSkills: rule("unsupported", RUNTIME_STUB),
114
- loadSkillsFromDir: rule("unsupported", RUNTIME_STUB),
113
+ loadSkills: rule("partial", `${VENDORED} Real directory discovery with Pi\'s exact rules; default locations resolve through the redirected getAgentDir, i.e. inside the DSH-owned pi2dsh directory.`),
114
+ loadSkillsFromDir: rule("full", `${VENDORED} Real directory discovery: SKILL.md roots, direct .md children, ignore files, symlink dedup, and Pi\'s name/description validation.`),
115
115
  formatSkillsForPrompt: rule("full", "Pi's skill prompt formatter, vendored with logic unchanged."),
116
116
  CustomEditor: rule("partial", HEADLESS_COMPONENT),
117
117
  ToolExecutionComponent: rule("partial", HEADLESS_COMPONENT),
@@ -213,8 +213,8 @@ const HOST_IMPORT_RULES = Object.freeze({
213
213
  getProvider: rule("partial", "Reads the bridge-local registry."),
214
214
  getModel: rule("partial", "Resolves no Pi model objects; DSH owns model routing."),
215
215
  getModels: rule("partial", "Returns an empty list; DSH owns model routing."),
216
- complete: rule("unsupported", "Pi provider SDK calls have no DSH mapping; calling fails explicitly."),
217
- stream: rule("unsupported", "Pi provider SDK calls have no DSH mapping; calling fails explicitly."),
216
+ complete: rule("partial", "Real model calls through the DSH llm bridge (the host installs it at mount); without a mounted llm service the call fails explicitly. Provider SDKs are never loaded."),
217
+ stream: rule("partial", "Real streaming model calls through the DSH llm bridge (the host installs it at mount); without a mounted llm service the call fails explicitly. Provider SDKs are never loaded."),
218
218
  Type: rule("full", "Re-exported from the same typebox dependency Pi resolves for extensions."),
219
219
  uuidv7: rule("full", VENDORED),
220
220
  isContextOverflow: rule("full", VENDORED),
@@ -245,13 +245,13 @@ const CONTEXT_RULES = Object.freeze({
245
245
  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)."),
246
246
  thinkingLevel: rule("partial", "Reflects the level recorded by setThinkingLevel(); applied as reasoningEffort on the next request."),
247
247
  abort: rule("partial", "Mapped to agent.cancel({ kind: \"hook\" }) on the live DSH agent."),
248
- shutdown: rule("unsupported", "A migrated package may not shut down the DSH host; calling fails explicitly."),
249
- compact: rule("unsupported", "Pi compaction control requires a native DSH compaction integration; calling fails explicitly."),
250
- newSession: rule("unsupported", "Session replacement belongs to the DSH host; calling fails explicitly."),
251
- fork: rule("unsupported", "Pi entry-tree forking has no DSH equivalent (DSH fork is boundary-based); calling fails explicitly."),
252
- navigateTree: rule("unsupported", "Pi tree navigation has no DSH equivalent; calling fails explicitly."),
253
- switchSession: rule("unsupported", "Session switching belongs to the DSH host; calling fails explicitly."),
254
- reload: rule("unsupported", "Extension reload belongs to the DSH host (HMR); calling fails explicitly.")
248
+ shutdown: rule("partial", "Pi defines shutdown behavior as host-provided (runner.ts bindExtensions); this host absorbs the request — the user owns DSH process exit — and informs the user once. The package keeps running."),
249
+ compact: rule("partial", "Pi's fire-and-forget trigger, translated to DSH's official manual compaction (ctx.compaction.compactNow on the live agent). onComplete receives the real summary text and the shadowed-content token estimate as tokensBefore; firstKeptEntryId is empty because the DSH log has no Pi entry ids. Without a compaction service the gap flows through Pi's onError callback and the capability ledger."),
250
+ newSession: rule("partial", "Really creates a DSH session (ctx.sessions.create) with parent lineage; withSession runs against a projection context bound to it. DSH has no host-level \"current session pointer\" a plugin could move — which session the surface shows stays a host choice, announced once."),
251
+ fork: rule("partial", "Really forks on DSH's official prefix-fork surface (ctx.sessions.fork with lineage metadata). Anchors are durable-log entries (projected ids \"dsh-<seq>\"); Pi's default position \"before\" is honored, and the boundary shrinks to the nearest completed-turn edge because DSH seeds must not split an open turn. Sidecar entries cannot anchor a fork."),
252
+ navigateTree: rule("partial", "Expressed through DSH's session model: the DSH tree lives BETWEEN sessions (fork lineage), not inside one log, so navigation forks at the target boundary. summarize runs Pi's vendored branch summarizer over the abandoned durable slice (model call on the DSH llm bridge) and lands the summary as a branch_summary entry in the new session's projection; label lands as a label entry."),
253
+ switchSession: rule("partial", "Targets a LIVE DSH session by id (or a Pi-style path whose basename is \"<id>.jsonl\"); withSession runs against its projection. Switching to persisted sessions is host-owned — resume them from the DSH surface first. Which session the surface shows stays a host choice."),
254
+ reload: rule("partial", "Really remounts every mounted package's extension entries through a fresh loader (registrations replaced via the same-name path, event handlers reset), so edited plugin code takes effect. Skills, prompts, and themes are host-managed and reload with dsh itself.")
255
255
  });
256
256
  const UI_CONTEXT_RULES = Object.freeze({
257
257
  notify: rule("full", "Captured as a command result when applicable and emitted through DSH logging."),
@@ -704,4 +704,4 @@ function renderMcpPatch(result) {
704
704
  //#endregion
705
705
  export { CONTEXT_RULES as a, PI_AI_PACKAGES as c, UI_CONTEXT_RULES as d, ruleForApi as f, ruleForUiContextProperty as g, ruleForHostImport as h, API_RULES as i, PI_CODING_AGENT_PACKAGES as l, ruleForEvent as m, convertPiMcpConfig as n, EVENT_RULES as o, ruleForContextProperty as p, renderMcpPatch as r, HOST_IMPORT_RULES as s, collectPiMcpServers as t, PI_TUI_PACKAGES as u };
706
706
 
707
- //# sourceMappingURL=mcp-config-Dlou-ZA-.mjs.map
707
+ //# sourceMappingURL=mcp-config-Cn5gWemZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-config-Cn5gWemZ.mjs","names":[],"sources":["../src/compatibility.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 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.'\nconst VENDORED_SUMMARIZER = 'Vendored Pi logic; the model call fills Pi\\'s own streamFn injection point with the DSH llm bridge when the caller passes none, so summarization runs on the ONE model path. Without a mounted llm service it fails explicitly.'\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', VENDORED),\n calculateContextTokens: rule('full', `${VENDORED} Pi\\'s Usage-based total (an earlier reimplementation summed message estimates — same name, different meaning — and was replaced).`),\n DEFAULT_COMPACTION_SETTINGS: rule('full', VENDORED),\n serializeConversation: rule('full', VENDORED),\n shouldCompact: rule('full', `${VENDORED} The pure threshold check; DSH still owns automatic compaction scheduling.`),\n compact: rule('partial', VENDORED_SUMMARIZER),\n findCutPoint: rule('full', VENDORED),\n generateSummary: rule('partial', VENDORED_SUMMARIZER),\n generateSummaryWithUsage: rule('partial', VENDORED_SUMMARIZER),\n generateBranchSummary: rule('partial', VENDORED_SUMMARIZER),\n parseFrontmatter: rule('full', `${VENDORED} Returns Pi\\'s public { frontmatter, body } shape with YAML-parsed values (an earlier reimplementation returned { attributes } with string values and was replaced).`),\n stripFrontmatter: rule('full', VENDORED),\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('full', `${VENDORED} The runner argument is used exactly as Pi uses it (createContext + getActiveTools), which the pi2dsh projection provides.`),\n ProjectTrustStore: rule('partial', `${VENDORED} The store operates on trust.json under the caller\\'s agentDir — with the redirected getAgentDir convention that is package-visible state inside the DSH-owned pi2dsh directory. The DSH host never consults it; host trust stays a DSH decision (ctx.isProjectTrusted fails closed).`),\n DefaultResourceLoader: rule('partial', 'A headless resource loader honoring overrides, with empty discovery sets.'),\n DefaultPackageManager: rule('unsupported', 'Installing packages is owned by the DSH host and its security gates (dsh plugin add/remove behind pnpm\\'s build-script approval). Importing it is flagged at mount time (startup check); constructing it throws a structured PiCapabilityError, and doing so during entry setup marks the package unusable.'),\n ModelRuntime: rule('unsupported', 'Standalone model stacks are owned by the DSH host llm configuration; packages read the ONE directory through ctx.modelRegistry. Importing it is flagged at mount time (startup check); constructing it throws a structured PiCapabilityError, and doing so during entry setup marks the package unusable.'),\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('partial', `${VENDORED} Real directory discovery with Pi\\'s exact rules; default locations resolve through the redirected getAgentDir, i.e. inside the DSH-owned pi2dsh directory.`),\n loadSkillsFromDir: rule('full', `${VENDORED} Real directory discovery: SKILL.md roots, direct .md children, ignore files, symlink dedup, and Pi\\'s name/description validation.`),\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('partial', 'Real model calls through the DSH llm bridge (the host installs it at mount); without a mounted llm service the call fails explicitly. Provider SDKs are never loaded.'),\n stream: rule('partial', 'Real streaming model calls through the DSH llm bridge (the host installs it at mount); without a mounted llm service the call fails explicitly. Provider SDKs are never loaded.'),\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 — the DSH llm directory — projected exactly into Pi vocabulary; package-registered Pi-native routes keep api/baseUrl and the full Model shape through the round trip. Custom gateways are HOST configuration (the official llm-pi-ai adapter\\'s settings), never a Pi-side file: Pi\\'s ~/.pi/agent/models.json is deliberately NOT read — user-facing configuration is DSH-shaped only. getProviderAuth/getApiKeyAndHeaders run Pi\\'s full credential chain for package-registered providers and the host\\'s configurable-provider + credentials seams for DSH routes. Host configuration may declare \"<route>-vision\" image-admission companions: real DSH routes that admit images, replace image blocks with explicit path-carrying notices (materialized attachment files any path-taking tool can read), and forward text-only to the original route; Pi\\'s ctx.model reports the original route for a companion selection.'),\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('partial', 'Pi defines shutdown behavior as host-provided (runner.ts bindExtensions); this host absorbs the request — the user owns DSH process exit — and informs the user once. The package keeps running.'),\n compact: rule('partial', 'Pi\\'s fire-and-forget trigger, translated to DSH\\'s official manual compaction (ctx.compaction.compactNow on the live agent). onComplete receives the real summary text and the shadowed-content token estimate as tokensBefore; firstKeptEntryId is empty because the DSH log has no Pi entry ids. Without a compaction service the gap flows through Pi\\'s onError callback and the capability ledger.'),\n newSession: rule('partial', 'Really creates a DSH session (ctx.sessions.create) with parent lineage; withSession runs against a projection context bound to it. DSH has no host-level \"current session pointer\" a plugin could move — which session the surface shows stays a host choice, announced once.'),\n fork: rule('partial', 'Really forks on DSH\\'s official prefix-fork surface (ctx.sessions.fork with lineage metadata). Anchors are durable-log entries (projected ids \"dsh-<seq>\"); Pi\\'s default position \"before\" is honored, and the boundary shrinks to the nearest completed-turn edge because DSH seeds must not split an open turn. Sidecar entries cannot anchor a fork.'),\n navigateTree: rule('partial', 'Expressed through DSH\\'s session model: the DSH tree lives BETWEEN sessions (fork lineage), not inside one log, so navigation forks at the target boundary. summarize runs Pi\\'s vendored branch summarizer over the abandoned durable slice (model call on the DSH llm bridge) and lands the summary as a branch_summary entry in the new session\\'s projection; label lands as a label entry.'),\n switchSession: rule('partial', 'Targets a LIVE DSH session by id (or a Pi-style path whose basename is \"<id>.jsonl\"); withSession runs against its projection. Switching to persisted sessions is host-owned — resume them from the DSH surface first. Which session the surface shows stays a host choice.'),\n reload: rule('partial', 'Really remounts every mounted package\\'s extension entries through a fresh loader (registrations replaced via the same-name path, event handlers reset), so edited plugin code takes effect. Skills, prompts, and themes are host-managed and reload with dsh itself.'),\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","// 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,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AAM,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"}
@@ -4,6 +4,197 @@ import { Type as Type$1 } from "typebox";
4
4
  //#region \0rolldown/runtime.js
5
5
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
6
6
  //#endregion
7
+ //#region src/compat/vendor/pi-uuid.ts
8
+ let lastTimestamp = -Infinity;
9
+ let sequence = 0;
10
+ function fillRandomBytes(bytes) {
11
+ if (globalThis.crypto?.getRandomValues) {
12
+ globalThis.crypto.getRandomValues(bytes);
13
+ return;
14
+ }
15
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
16
+ }
17
+ /** Generate a time-ordered UUIDv7. */
18
+ function uuidv7() {
19
+ const random = /* @__PURE__ */ new Uint8Array(16);
20
+ fillRandomBytes(random);
21
+ const timestamp = Date.now();
22
+ if (timestamp > lastTimestamp) {
23
+ sequence = random[6] * 16777216 + random[7] * 65536 + random[8] * 256 + random[9];
24
+ lastTimestamp = timestamp;
25
+ } else {
26
+ sequence = sequence + 1 >>> 0;
27
+ if (sequence === 0) lastTimestamp++;
28
+ }
29
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
30
+ bytes[0] = lastTimestamp / 1099511627776 & 255;
31
+ bytes[1] = lastTimestamp / 4294967296 & 255;
32
+ bytes[2] = lastTimestamp / 16777216 & 255;
33
+ bytes[3] = lastTimestamp / 65536 & 255;
34
+ bytes[4] = lastTimestamp / 256 & 255;
35
+ bytes[5] = lastTimestamp & 255;
36
+ bytes[6] = 112 | sequence >>> 28 & 15;
37
+ bytes[7] = sequence >>> 20 & 255;
38
+ bytes[8] = 128 | sequence >>> 14 & 63;
39
+ bytes[9] = sequence >>> 6 & 255;
40
+ bytes[10] = (sequence & 63) << 2 | random[10] & 3;
41
+ bytes[11] = random[11];
42
+ bytes[12] = random[12];
43
+ bytes[13] = random[13];
44
+ bytes[14] = random[14];
45
+ bytes[15] = random[15];
46
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
47
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
48
+ }
49
+ //#endregion
50
+ //#region src/compat/vendor/pi-ai-retry.ts
51
+ function buildProviderErrorPattern(patterns) {
52
+ return new RegExp(patterns.join("|"), "i");
53
+ }
54
+ const NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([
55
+ "GoUsageLimitError",
56
+ "FreeUsageLimitError",
57
+ "Monthly usage limit reached",
58
+ "available balance",
59
+ "insufficient_quota",
60
+ "out of budget",
61
+ "quota exceeded",
62
+ "billing"
63
+ ]);
64
+ const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
65
+ "overloaded",
66
+ "rate.?limit",
67
+ "too many requests",
68
+ "429",
69
+ "500",
70
+ "502",
71
+ "503",
72
+ "504",
73
+ "524",
74
+ "service.?unavailable",
75
+ "server.?error",
76
+ "internal.?error",
77
+ "provider.?returned.?error",
78
+ "exceeded request buffer limit while retrying upstream",
79
+ "network.?error",
80
+ "connection.?error",
81
+ "connection.?refused",
82
+ "connection.?lost",
83
+ "other side closed",
84
+ "fetch failed",
85
+ "getaddrinfo",
86
+ "ENOTFOUND",
87
+ "EAI_AGAIN",
88
+ "upstream.?connect",
89
+ "reset before headers",
90
+ "socket hang up",
91
+ "socket connection was closed",
92
+ "timed? out",
93
+ "timeout",
94
+ "terminated",
95
+ "websocket.?closed",
96
+ "websocket.?error",
97
+ "ended without",
98
+ "stream ended before message_stop",
99
+ "stream ended before a terminal response event",
100
+ "http2 request did not get a response",
101
+ "retry delay",
102
+ "you can retry your request",
103
+ "try your request again",
104
+ "please retry your request",
105
+ "ResourceExhausted"
106
+ ]);
107
+ var RetrySleepAbortError = class extends Error {
108
+ constructor() {
109
+ super("Aborted");
110
+ }
111
+ };
112
+ function sleep$1(ms, signal) {
113
+ return new Promise((resolve, reject) => {
114
+ if (signal?.aborted) {
115
+ reject(new RetrySleepAbortError());
116
+ return;
117
+ }
118
+ const timeout = setTimeout(resolve, ms);
119
+ signal?.addEventListener("abort", () => {
120
+ clearTimeout(timeout);
121
+ reject(new RetrySleepAbortError());
122
+ }, { once: true });
123
+ });
124
+ }
125
+ /**
126
+ * Run a single assistant-producing call with bounded retry on transient errors.
127
+ *
128
+ * Behavior:
129
+ * - A successful response is returned immediately. Aborts are terminal and never
130
+ * retried, but reported as unsuccessful if they happen after a retry was scheduled.
131
+ * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`
132
+ * too, so callers do not need to care when cancellation happened.
133
+ * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/
134
+ * billing exhaustion) is returned immediately so deterministic errors fail fast.
135
+ * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting
136
+ * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before
137
+ * the retried call starts, and `onRetryFinished` once at the end (whether the loop
138
+ * ends in success, exhausted retries, or an aborted backoff).
139
+ *
140
+ * When `policy` is undefined or disabled, the first response is returned unchanged
141
+ * (equivalent to calling `produce()` directly).
142
+ */
143
+ async function retryAssistantCall(produce, policy, signal, callbacks) {
144
+ const maxAttempts = policy?.enabled ? policy.maxRetries : 0;
145
+ let attempt = 0;
146
+ let lastRetry;
147
+ for (;;) {
148
+ const response = await produce();
149
+ if (response.stopReason === "aborted") {
150
+ if (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);
151
+ return response;
152
+ }
153
+ if (response.stopReason !== "error") {
154
+ if (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);
155
+ return response;
156
+ }
157
+ if (attempt >= maxAttempts || !isRetryableAssistantError(response)) {
158
+ if (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);
159
+ return response;
160
+ }
161
+ attempt++;
162
+ lastRetry = {
163
+ attempt,
164
+ errorMessage: response.errorMessage || "Unknown error"
165
+ };
166
+ const delayMs = policy.baseDelayMs * 2 ** (attempt - 1);
167
+ await callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);
168
+ try {
169
+ await sleep$1(delayMs, signal);
170
+ } catch (error) {
171
+ await callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);
172
+ if (error instanceof RetrySleepAbortError) return {
173
+ ...response,
174
+ stopReason: "aborted",
175
+ errorMessage: void 0
176
+ };
177
+ throw error;
178
+ }
179
+ await callbacks?.onRetryAttemptStart?.();
180
+ }
181
+ }
182
+ /**
183
+ * Classifies whether a failed assistant message looks like a transient provider
184
+ * or transport error, so callers can decide if the last assistant turn should be
185
+ * restarted.
186
+ *
187
+ * This does not implement retry policy. Callers should first handle context
188
+ * overflow separately, then apply their own retry budget, backoff, and reporting
189
+ * before restarting the assistant turn.
190
+ */
191
+ function isRetryableAssistantError(message) {
192
+ if (message.stopReason !== "error" || !message.errorMessage) return false;
193
+ const errorMessage = message.errorMessage;
194
+ if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;
195
+ return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);
196
+ }
197
+ //#endregion
7
198
  //#region src/compat/vendor/pi-ai-overflow.ts
8
199
  /**
9
200
  * Regex patterns to detect context overflow errors from different providers.
@@ -156,79 +347,6 @@ function isRecoverableLength(message, desiredMaxOutput) {
156
347
  return message.stopReason === "length" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;
157
348
  }
158
349
  //#endregion
159
- //#region src/compat/vendor/pi-ai-retry.ts
160
- function buildProviderErrorPattern(patterns) {
161
- return new RegExp(patterns.join("|"), "i");
162
- }
163
- const NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([
164
- "GoUsageLimitError",
165
- "FreeUsageLimitError",
166
- "Monthly usage limit reached",
167
- "available balance",
168
- "insufficient_quota",
169
- "out of budget",
170
- "quota exceeded",
171
- "billing"
172
- ]);
173
- const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
174
- "overloaded",
175
- "rate.?limit",
176
- "too many requests",
177
- "429",
178
- "500",
179
- "502",
180
- "503",
181
- "504",
182
- "524",
183
- "service.?unavailable",
184
- "server.?error",
185
- "internal.?error",
186
- "provider.?returned.?error",
187
- "exceeded request buffer limit while retrying upstream",
188
- "network.?error",
189
- "connection.?error",
190
- "connection.?refused",
191
- "connection.?lost",
192
- "other side closed",
193
- "fetch failed",
194
- "getaddrinfo",
195
- "ENOTFOUND",
196
- "EAI_AGAIN",
197
- "upstream.?connect",
198
- "reset before headers",
199
- "socket hang up",
200
- "socket connection was closed",
201
- "timed? out",
202
- "timeout",
203
- "terminated",
204
- "websocket.?closed",
205
- "websocket.?error",
206
- "ended without",
207
- "stream ended before message_stop",
208
- "stream ended before a terminal response event",
209
- "http2 request did not get a response",
210
- "retry delay",
211
- "you can retry your request",
212
- "try your request again",
213
- "please retry your request",
214
- "ResourceExhausted"
215
- ]);
216
- /**
217
- * Classifies whether a failed assistant message looks like a transient provider
218
- * or transport error, so callers can decide if the last assistant turn should be
219
- * restarted.
220
- *
221
- * This does not implement retry policy. Callers should first handle context
222
- * overflow separately, then apply their own retry budget, backoff, and reporting
223
- * before restarting the assistant turn.
224
- */
225
- function isRetryableAssistantError(message) {
226
- if (message.stopReason !== "error" || !message.errorMessage) return false;
227
- const errorMessage = message.errorMessage;
228
- if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;
229
- return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);
230
- }
231
- //#endregion
232
350
  //#region src/compat/vendor/pi-ai-event-stream.ts
233
351
  var EventStream = class {
234
352
  queue = [];
@@ -2919,6 +3037,9 @@ let activeLlmBridge;
2919
3037
  function __setPiAiLlmBridge(bridge) {
2920
3038
  activeLlmBridge = bridge;
2921
3039
  }
3040
+ function __getPiAiLlmBridge() {
3041
+ return activeLlmBridge;
3042
+ }
2922
3043
  function requireLlmBridge(api) {
2923
3044
  if (activeLlmBridge === void 0) throw new Error(`pi2dsh: pi-ai ${api}() needs a DSH llm service; this composition mounts none, so model calls cannot be routed`);
2924
3045
  return activeLlmBridge;
@@ -2940,6 +3061,6 @@ function StringEnum(values, options = {}) {
2940
3061
  };
2941
3062
  }
2942
3063
  //#endregion
2943
- export { ModelsError as A, unregisterApiProviders as C, openaiCodexOAuth as D, anthropicOAuth as E, isRetryableAssistantError as F, isContextOverflow as I, isRecoverableLength as L, lazyApi as M, lazyStream as N, generatePKCE as O, AssistantMessageEventStream as P, stream as S, githubCopilotOAuth as T, loadKimiCodingOAuth as _, clampThinkingLevel as a, registerApiProvider as b, getApiProvider as c, getModels as d, getProvider as f, loadGitHubCopilotOAuth as g, loadAnthropicOAuth as h, builtinProviders as i, createProvider as j, pollOAuthDeviceCodeFlow as k, getApiProviders as l, getSupportedThinkingLevels as m, Type$1 as n, complete as o, getProviders as p, __setPiAiLlmBridge as r, contentText as s, StringEnum as t, getModel as u, loadOpenAICodexOAuth as v, kimiCodingOAuth as w, registerProvider as x, modelsAreEqual as y };
3064
+ export { pollOAuthDeviceCodeFlow as A, uuidv7 as B, stream as C, anthropicOAuth as D, githubCopilotOAuth as E, AssistantMessageEventStream as F, isContextOverflow as I, isRecoverableLength as L, createProvider as M, lazyApi as N, openaiCodexOAuth as O, lazyStream as P, isRetryableAssistantError as R, registerProvider as S, kimiCodingOAuth as T, loadGitHubCopilotOAuth as _, builtinProviders as a, modelsAreEqual as b, contentText as c, getModel as d, getModels as f, loadAnthropicOAuth as g, getSupportedThinkingLevels as h, __setPiAiLlmBridge as i, ModelsError as j, generatePKCE as k, getApiProvider as l, getProviders as m, Type$1 as n, clampThinkingLevel as o, getProvider as p, __getPiAiLlmBridge as r, complete as s, StringEnum as t, getApiProviders as u, loadKimiCodingOAuth as v, unregisterApiProviders as w, registerApiProvider as x, loadOpenAICodexOAuth as y, retryAssistantCall as z };
2944
3065
 
2945
- //# sourceMappingURL=pi-ai-BA3h0Dwv.mjs.map
3066
+ //# sourceMappingURL=pi-ai-Dyg4zyLZ.mjs.map