pi2dsh 0.23.0 → 0.25.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 (48) hide show
  1. package/README.md +19 -8
  2. package/README.zh.md +16 -6
  3. package/dist/{analyzer-C139Y2S7.mjs → analyzer-DbgL3neo.mjs} +2 -2
  4. package/dist/{analyzer-C139Y2S7.mjs.map → analyzer-DbgL3neo.mjs.map} +1 -1
  5. package/dist/cli.mjs +3 -3
  6. package/dist/compat/pi-ai.d.mts +2 -2
  7. package/dist/compat/pi-ai.mjs +2 -2
  8. package/dist/compat/pi-coding-agent.d.mts +2 -2
  9. package/dist/compat/pi-coding-agent.mjs +2 -2
  10. package/dist/{compatibility-CZs3LwYn.mjs → compatibility-DS6POFZD.mjs} +29 -26
  11. package/dist/compatibility-DS6POFZD.mjs.map +1 -0
  12. package/dist/credentials-oauth.mjs +2 -2
  13. package/dist/{google-generative-ai-Dpb_X-Kt.mjs → google-generative-ai-DYSbNJT7.mjs} +2 -2
  14. package/dist/{google-generative-ai-Dpb_X-Kt.mjs.map → google-generative-ai-DYSbNJT7.mjs.map} +1 -1
  15. package/dist/{google-shared-CL1Za-ev.mjs → google-shared-LEpwok5n.mjs} +2 -2
  16. package/dist/{google-shared-CL1Za-ev.mjs.map → google-shared-LEpwok5n.mjs.map} +1 -1
  17. package/dist/{google-vertex-BXRKa49Y.mjs → google-vertex-BgGRE4WU.mjs} +2 -2
  18. package/dist/{google-vertex-BXRKa49Y.mjs.map → google-vertex-BgGRE4WU.mjs.map} +1 -1
  19. package/dist/host.mjs +2 -2
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +7 -5
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{multipart-parser-CBAi6PxA.mjs → multipart-parser-BOEZ-KGK.mjs} +2 -2
  24. package/dist/{multipart-parser-CBAi6PxA.mjs.map → multipart-parser-BOEZ-KGK.mjs.map} +1 -1
  25. package/dist/{pi-ai-hGbYES_v.d.mts → pi-ai-BHgA3JWd.d.mts} +14 -6
  26. package/dist/{pi-ai-hGbYES_v.d.mts.map → pi-ai-BHgA3JWd.d.mts.map} +1 -1
  27. package/dist/{pi-ai-DQPHUR9S.mjs → pi-ai-Cy_BRMmd.mjs} +23 -6
  28. package/dist/pi-ai-Cy_BRMmd.mjs.map +1 -0
  29. package/dist/pi-cli-client.mjs +25 -0
  30. package/dist/{pi-coding-agent-Pvy0m9tS.d.mts → pi-coding-agent-Cas0oHSx.d.mts} +18 -3
  31. package/dist/{pi-coding-agent-Pvy0m9tS.d.mts.map → pi-coding-agent-Cas0oHSx.d.mts.map} +1 -1
  32. package/dist/{pi-coding-agent-CPXFo0UO.mjs → pi-coding-agent-lcNs9Wos.mjs} +0 -0
  33. package/dist/pi-coding-agent-lcNs9Wos.mjs.map +1 -0
  34. package/dist/{runtime-Dnk9mhrc.mjs → runtime-B3N7s93Q.mjs} +1086 -249
  35. package/dist/runtime-B3N7s93Q.mjs.map +1 -0
  36. package/dist/runtime.d.mts +107 -50
  37. package/dist/runtime.d.mts.map +1 -1
  38. package/dist/runtime.mjs +1 -1
  39. package/dist/{source-0sA5z08z.mjs → source-l77aIDwD.mjs} +76 -3
  40. package/dist/source-l77aIDwD.mjs.map +1 -0
  41. package/dist/{src-85HOaW5W.mjs → src-ChZlNrRV.mjs} +3 -3
  42. package/dist/{src-85HOaW5W.mjs.map → src-ChZlNrRV.mjs.map} +1 -1
  43. package/package.json +24 -14
  44. package/dist/compatibility-CZs3LwYn.mjs.map +0 -1
  45. package/dist/pi-ai-DQPHUR9S.mjs.map +0 -1
  46. package/dist/pi-coding-agent-CPXFo0UO.mjs.map +0 -1
  47. package/dist/runtime-Dnk9mhrc.mjs.map +0 -1
  48. package/dist/source-0sA5z08z.mjs.map +0 -1
@@ -4,7 +4,7 @@ import { m as clampThinkingLevel, p as calculateCost, r as buildBaseOptions, s a
4
4
  import { n as normalizeProviderError, t as formatProviderError } from "./error-body-DKA3lknR.mjs";
5
5
  import { n as providerHeadersToRecord } from "./headers-CPzZhJQn.mjs";
6
6
  import { t as getProviderEnvValue } from "./provider-env-C72pF4vP.mjs";
7
- import { a as resolveGoogleFunctionCallingMode, c as supportsGoogleStrictToolSampling, d as ThinkingLevel, i as mapStopReason, l as GoogleGenAI, n as convertTools, o as retainThoughtSignature, r as isThinkingPart, s as retryGoogleRequest, t as convertMessages, u as ResourceScope } from "./google-shared-CL1Za-ev.mjs";
7
+ import { a as resolveGoogleFunctionCallingMode, c as supportsGoogleStrictToolSampling, d as ThinkingLevel, i as mapStopReason, l as GoogleGenAI, n as convertTools, o as retainThoughtSignature, r as isThinkingPart, s as retryGoogleRequest, t as convertMessages, u as ResourceScope } from "./google-shared-LEpwok5n.mjs";
8
8
  //#region node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js
9
9
  const API_VERSION = "v1";
10
10
  const GCP_VERTEX_CREDENTIALS_MARKER = "gcp-vertex-credentials";
@@ -397,4 +397,4 @@ function getGoogleBudget(model, effort, customBudgets) {
397
397
  //#endregion
398
398
  export { stream, streamSimple };
399
399
 
400
- //# sourceMappingURL=google-vertex-BXRKa49Y.mjs.map
400
+ //# sourceMappingURL=google-vertex-BgGRE4WU.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"google-vertex-BXRKa49Y.mjs","names":[],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js"],"sourcesContent":["import { GoogleGenAI, ResourceScope, ThinkingLevel, } from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { providerHeadersToRecord } from \"../utils/headers.js\";\nimport { getProviderEnvValue } from \"../utils/provider-env.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { convertMessages, convertTools, isThinkingPart, mapStopReason, resolveGoogleFunctionCallingMode, retainThoughtSignature, retryGoogleRequest, supportsGoogleStrictToolSampling, } from \"./google-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nconst API_VERSION = \"v1\";\nconst GCP_VERTEX_CREDENTIALS_MARKER = \"gcp-vertex-credentials\";\nconst THINKING_LEVEL_MAP = {\n THINKING_LEVEL_UNSPECIFIED: ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n MINIMAL: ThinkingLevel.MINIMAL,\n LOW: ThinkingLevel.LOW,\n MEDIUM: ThinkingLevel.MEDIUM,\n HIGH: ThinkingLevel.HIGH,\n};\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\nexport const stream = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: \"google-vertex\",\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"pending\",\n timestamp: Date.now(),\n };\n try {\n if (options?.fetch && options.fetch !== globalThis.fetch) {\n throw new Error(\"Custom fetch is not supported by the Google Vertex adapter\");\n }\n const apiKey = resolveApiKey(options);\n // Create the client using either a Vertex API key, if provided, or ADC with project and location\n const client = apiKey\n ? createClientWithApiKey(model, apiKey, options?.headers)\n : createClient(model, resolveProject(options), resolveLocation(options), options?.headers, options?.env);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n stream.push({ type: \"start\", partial: output });\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const chunk of googleStream) {\n // Vertex uses the same @google/genai GenerateContentResponse type as Gemini.\n // responseId is documented there as an output-only identifier for each response.\n output.responseId ||= chunk.responseId;\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n if (part.text !== undefined) {\n const isThinking = isThinkingPart(part);\n if (!currentBlock ||\n (isThinking && currentBlock.type !== \"thinking\") ||\n (!isThinking && currentBlock.type !== \"text\")) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blocks.length - 1,\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (isThinking) {\n currentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else {\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n if (currentBlock.type === \"thinking\") {\n currentBlock.thinking += part.text;\n currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n else {\n currentBlock.text += part.text;\n currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n }\n if (part.functionCall) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n currentBlock = null;\n }\n const providedId = part.functionCall.id;\n const needsNewId = !providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n const toolCallId = needsNewId\n ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n : providedId;\n const toolCall = {\n type: \"toolCall\",\n id: toolCallId,\n name: part.functionCall.name || \"\",\n arguments: part.functionCall.args ?? {},\n ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n };\n output.content.push(toolCall);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: JSON.stringify(toolCall.arguments),\n partial: output,\n });\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n }\n if (candidate?.finishReason) {\n output.rawStopReason = candidate.finishReason;\n output.stopReason = mapStopReason(candidate.finishReason);\n if (output.content.some((b) => b.type === \"toolCall\")) {\n output.stopReason = \"toolUse\";\n }\n }\n if (chunk.usageMetadata) {\n output.usage = {\n input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n cacheWrite: 0,\n reasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n totalTokens: chunk.usageMetadata.totalTokenCount || 0,\n cost: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n total: 0,\n },\n };\n calculateCost(model, output.usage);\n }\n }\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"pending\") {\n throw new Error(\"Google Vertex stream ended without a finish reason\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n const errorMessage = output.rawStopReason\n ? `Provider stopped with: ${output.rawStopReason}`\n : \"An unknown error occurred\";\n throw new Error(errorMessage);\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n // Remove internal index property used during streaming\n for (const block of output.content) {\n if (\"index\" in block) {\n delete block.index;\n }\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatProviderError(normalizeProviderError(error));\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimple = (model, context, options) => {\n const base = buildBaseOptions(model, context, options, undefined);\n if (!options?.reasoning) {\n return stream(model, context, {\n ...base,\n thinking: { enabled: false },\n });\n }\n const clampedReasoning = clampThinkingLevel(model, options.reasoning);\n const effort = (clampedReasoning === \"off\" ? \"high\" : clampedReasoning);\n const geminiModel = model;\n if (isGemini3ProModel(geminiModel) || isGemini3FlashModel(geminiModel)) {\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n level: getGemini3ThinkingLevel(effort, geminiModel),\n },\n });\n }\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n budgetTokens: getGoogleBudget(geminiModel, effort, options.thinkingBudgets),\n },\n });\n};\nfunction createClient(model, project, location, optionsHeaders, env) {\n const googleAuthOptions = buildGoogleAuthOptions(env);\n return new GoogleGenAI({\n vertexai: true,\n project,\n location,\n apiVersion: API_VERSION,\n ...(googleAuthOptions ? { googleAuthOptions } : {}),\n httpOptions: buildHttpOptions(model, optionsHeaders),\n });\n}\nfunction createClientWithApiKey(model, apiKey, optionsHeaders) {\n return new GoogleGenAI({\n vertexai: true,\n apiKey,\n apiVersion: API_VERSION,\n httpOptions: buildHttpOptions(model, optionsHeaders),\n });\n}\nfunction buildHttpOptions(model, optionsHeaders) {\n const httpOptions = {};\n const baseUrl = resolveCustomBaseUrl(model.baseUrl);\n if (baseUrl) {\n httpOptions.baseUrl = baseUrl;\n httpOptions.baseUrlResourceScope = ResourceScope.COLLECTION;\n if (baseUrlIncludesApiVersion(baseUrl)) {\n httpOptions.apiVersion = \"\";\n }\n }\n const headers = providerHeadersToRecord({ ...model.headers, ...optionsHeaders });\n if (headers) {\n httpOptions.headers = headers;\n }\n return Object.keys(httpOptions).length > 0 ? httpOptions : undefined;\n}\nfunction resolveCustomBaseUrl(baseUrl) {\n const trimmed = baseUrl.trim();\n if (!trimmed || trimmed.includes(\"{location}\")) {\n return undefined;\n }\n return trimmed;\n}\nfunction baseUrlIncludesApiVersion(baseUrl) {\n try {\n const url = new URL(baseUrl);\n return url.pathname.split(\"/\").some((part) => /^v\\d+(?:beta\\d*)?$/.test(part));\n }\n catch {\n return /(?:^|\\/)v\\d+(?:beta\\d*)?(?:\\/|$)/.test(baseUrl);\n }\n}\nfunction buildGoogleAuthOptions(env) {\n const keyFilename = getProviderEnvValue(\"GOOGLE_APPLICATION_CREDENTIALS\", env);\n return keyFilename ? { keyFilename } : undefined;\n}\nfunction resolveApiKey(options) {\n const apiKey = options?.apiKey?.trim();\n if (!apiKey || apiKey === GCP_VERTEX_CREDENTIALS_MARKER || isPlaceholderApiKey(apiKey)) {\n return undefined;\n }\n return apiKey;\n}\nfunction isPlaceholderApiKey(apiKey) {\n return /^<[^>]+>$/.test(apiKey);\n}\nfunction resolveProject(options) {\n const project = options?.project ||\n getProviderEnvValue(\"GOOGLE_CLOUD_PROJECT\", options?.env) ||\n getProviderEnvValue(\"GCLOUD_PROJECT\", options?.env);\n if (!project) {\n throw new Error(\"Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.\");\n }\n return project;\n}\nfunction resolveLocation(options) {\n const location = options?.location || getProviderEnvValue(\"GOOGLE_CLOUD_LOCATION\", options?.env);\n if (!location) {\n throw new Error(\"Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.\");\n }\n return location;\n}\nfunction buildParams(model, context, options = {}) {\n const contents = convertMessages(model, context);\n const generationConfig = {};\n if (options.temperature !== undefined) {\n generationConfig.temperature = options.temperature;\n }\n if (options.maxTokens !== undefined) {\n generationConfig.maxOutputTokens = options.maxTokens;\n }\n const functionCallingMode = context.tools?.length\n ? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id))\n : undefined;\n const config = {\n ...(Object.keys(generationConfig).length > 0 && generationConfig),\n ...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n ...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),\n ...(functionCallingMode !== undefined && {\n toolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n }),\n };\n if (options.thinking?.enabled && model.reasoning) {\n const thinkingConfig = { includeThoughts: true };\n if (options.thinking.level !== undefined) {\n thinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];\n }\n else if (options.thinking.budgetTokens !== undefined) {\n thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n }\n config.thinkingConfig = thinkingConfig;\n }\n else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n config.thinkingConfig = getDisabledThinkingConfig(model);\n }\n if (options.signal) {\n if (options.signal.aborted) {\n throw new Error(\"Request aborted\");\n }\n config.abortSignal = options.signal;\n }\n const params = {\n model: model.id,\n contents,\n config,\n };\n return params;\n}\nfunction isGemini3ProModel(model) {\n return /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\nfunction isGemini3FlashModel(model) {\n const id = model.id.toLowerCase();\n return /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\nfunction getDisabledThinkingConfig(model) {\n // Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n // do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n // thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n const geminiModel = model;\n if (isGemini3ProModel(geminiModel)) {\n return { thinkingLevel: ThinkingLevel.LOW };\n }\n if (isGemini3FlashModel(geminiModel)) {\n return { thinkingLevel: ThinkingLevel.MINIMAL };\n }\n // Gemini 2.x supports disabling via thinkingBudget = 0.\n return { thinkingBudget: 0 };\n}\nfunction getGemini3ThinkingLevel(effort, model) {\n if (isGemini3ProModel(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"LOW\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n switch (effort) {\n case \"minimal\":\n return \"MINIMAL\";\n case \"low\":\n return \"LOW\";\n case \"medium\":\n return \"MEDIUM\";\n case \"high\":\n return \"HIGH\";\n }\n}\nfunction getGoogleBudget(model, effort, customBudgets) {\n if (customBudgets?.[effort] !== undefined) {\n return customBudgets[effort];\n }\n if (model.id.includes(\"2.5-pro\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 32768,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n return -1;\n}\n//# sourceMappingURL=google-vertex.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;AASA,MAAM,cAAc;AACpB,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;CACvB,4BAA4B,cAAc;CAC1C,SAAS,cAAc;CACvB,KAAK,cAAc;CACnB,QAAQ,cAAc;CACtB,MAAM,cAAc;AACxB;AAEA,IAAI,kBAAkB;AACtB,MAAa,UAAU,OAAO,SAAS,YAAY;CAC/C,MAAM,SAAS,IAAI,4BAA4B;CAC/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK;GACL,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,aAAa;IACb,MAAM;KAAE,OAAO;KAAG,QAAQ;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AI,MAAM,GAAG,SAAS,SAAS,GAO3B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,WAAW,GAO7B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,OAAO;AACX"}
1
+ {"version":3,"file":"google-vertex-BgGRE4WU.mjs","names":[],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js"],"sourcesContent":["import { GoogleGenAI, ResourceScope, ThinkingLevel, } from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { providerHeadersToRecord } from \"../utils/headers.js\";\nimport { getProviderEnvValue } from \"../utils/provider-env.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { convertMessages, convertTools, isThinkingPart, mapStopReason, resolveGoogleFunctionCallingMode, retainThoughtSignature, retryGoogleRequest, supportsGoogleStrictToolSampling, } from \"./google-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nconst API_VERSION = \"v1\";\nconst GCP_VERTEX_CREDENTIALS_MARKER = \"gcp-vertex-credentials\";\nconst THINKING_LEVEL_MAP = {\n THINKING_LEVEL_UNSPECIFIED: ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n MINIMAL: ThinkingLevel.MINIMAL,\n LOW: ThinkingLevel.LOW,\n MEDIUM: ThinkingLevel.MEDIUM,\n HIGH: ThinkingLevel.HIGH,\n};\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\nexport const stream = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: \"google-vertex\",\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"pending\",\n timestamp: Date.now(),\n };\n try {\n if (options?.fetch && options.fetch !== globalThis.fetch) {\n throw new Error(\"Custom fetch is not supported by the Google Vertex adapter\");\n }\n const apiKey = resolveApiKey(options);\n // Create the client using either a Vertex API key, if provided, or ADC with project and location\n const client = apiKey\n ? createClientWithApiKey(model, apiKey, options?.headers)\n : createClient(model, resolveProject(options), resolveLocation(options), options?.headers, options?.env);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n stream.push({ type: \"start\", partial: output });\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const chunk of googleStream) {\n // Vertex uses the same @google/genai GenerateContentResponse type as Gemini.\n // responseId is documented there as an output-only identifier for each response.\n output.responseId ||= chunk.responseId;\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n if (part.text !== undefined) {\n const isThinking = isThinkingPart(part);\n if (!currentBlock ||\n (isThinking && currentBlock.type !== \"thinking\") ||\n (!isThinking && currentBlock.type !== \"text\")) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blocks.length - 1,\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (isThinking) {\n currentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else {\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n if (currentBlock.type === \"thinking\") {\n currentBlock.thinking += part.text;\n currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n else {\n currentBlock.text += part.text;\n currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n }\n if (part.functionCall) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n currentBlock = null;\n }\n const providedId = part.functionCall.id;\n const needsNewId = !providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n const toolCallId = needsNewId\n ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n : providedId;\n const toolCall = {\n type: \"toolCall\",\n id: toolCallId,\n name: part.functionCall.name || \"\",\n arguments: part.functionCall.args ?? {},\n ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n };\n output.content.push(toolCall);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: JSON.stringify(toolCall.arguments),\n partial: output,\n });\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n }\n if (candidate?.finishReason) {\n output.rawStopReason = candidate.finishReason;\n output.stopReason = mapStopReason(candidate.finishReason);\n if (output.content.some((b) => b.type === \"toolCall\")) {\n output.stopReason = \"toolUse\";\n }\n }\n if (chunk.usageMetadata) {\n output.usage = {\n input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n cacheWrite: 0,\n reasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n totalTokens: chunk.usageMetadata.totalTokenCount || 0,\n cost: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n total: 0,\n },\n };\n calculateCost(model, output.usage);\n }\n }\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"pending\") {\n throw new Error(\"Google Vertex stream ended without a finish reason\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n const errorMessage = output.rawStopReason\n ? `Provider stopped with: ${output.rawStopReason}`\n : \"An unknown error occurred\";\n throw new Error(errorMessage);\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n // Remove internal index property used during streaming\n for (const block of output.content) {\n if (\"index\" in block) {\n delete block.index;\n }\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatProviderError(normalizeProviderError(error));\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimple = (model, context, options) => {\n const base = buildBaseOptions(model, context, options, undefined);\n if (!options?.reasoning) {\n return stream(model, context, {\n ...base,\n thinking: { enabled: false },\n });\n }\n const clampedReasoning = clampThinkingLevel(model, options.reasoning);\n const effort = (clampedReasoning === \"off\" ? \"high\" : clampedReasoning);\n const geminiModel = model;\n if (isGemini3ProModel(geminiModel) || isGemini3FlashModel(geminiModel)) {\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n level: getGemini3ThinkingLevel(effort, geminiModel),\n },\n });\n }\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n budgetTokens: getGoogleBudget(geminiModel, effort, options.thinkingBudgets),\n },\n });\n};\nfunction createClient(model, project, location, optionsHeaders, env) {\n const googleAuthOptions = buildGoogleAuthOptions(env);\n return new GoogleGenAI({\n vertexai: true,\n project,\n location,\n apiVersion: API_VERSION,\n ...(googleAuthOptions ? { googleAuthOptions } : {}),\n httpOptions: buildHttpOptions(model, optionsHeaders),\n });\n}\nfunction createClientWithApiKey(model, apiKey, optionsHeaders) {\n return new GoogleGenAI({\n vertexai: true,\n apiKey,\n apiVersion: API_VERSION,\n httpOptions: buildHttpOptions(model, optionsHeaders),\n });\n}\nfunction buildHttpOptions(model, optionsHeaders) {\n const httpOptions = {};\n const baseUrl = resolveCustomBaseUrl(model.baseUrl);\n if (baseUrl) {\n httpOptions.baseUrl = baseUrl;\n httpOptions.baseUrlResourceScope = ResourceScope.COLLECTION;\n if (baseUrlIncludesApiVersion(baseUrl)) {\n httpOptions.apiVersion = \"\";\n }\n }\n const headers = providerHeadersToRecord({ ...model.headers, ...optionsHeaders });\n if (headers) {\n httpOptions.headers = headers;\n }\n return Object.keys(httpOptions).length > 0 ? httpOptions : undefined;\n}\nfunction resolveCustomBaseUrl(baseUrl) {\n const trimmed = baseUrl.trim();\n if (!trimmed || trimmed.includes(\"{location}\")) {\n return undefined;\n }\n return trimmed;\n}\nfunction baseUrlIncludesApiVersion(baseUrl) {\n try {\n const url = new URL(baseUrl);\n return url.pathname.split(\"/\").some((part) => /^v\\d+(?:beta\\d*)?$/.test(part));\n }\n catch {\n return /(?:^|\\/)v\\d+(?:beta\\d*)?(?:\\/|$)/.test(baseUrl);\n }\n}\nfunction buildGoogleAuthOptions(env) {\n const keyFilename = getProviderEnvValue(\"GOOGLE_APPLICATION_CREDENTIALS\", env);\n return keyFilename ? { keyFilename } : undefined;\n}\nfunction resolveApiKey(options) {\n const apiKey = options?.apiKey?.trim();\n if (!apiKey || apiKey === GCP_VERTEX_CREDENTIALS_MARKER || isPlaceholderApiKey(apiKey)) {\n return undefined;\n }\n return apiKey;\n}\nfunction isPlaceholderApiKey(apiKey) {\n return /^<[^>]+>$/.test(apiKey);\n}\nfunction resolveProject(options) {\n const project = options?.project ||\n getProviderEnvValue(\"GOOGLE_CLOUD_PROJECT\", options?.env) ||\n getProviderEnvValue(\"GCLOUD_PROJECT\", options?.env);\n if (!project) {\n throw new Error(\"Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.\");\n }\n return project;\n}\nfunction resolveLocation(options) {\n const location = options?.location || getProviderEnvValue(\"GOOGLE_CLOUD_LOCATION\", options?.env);\n if (!location) {\n throw new Error(\"Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.\");\n }\n return location;\n}\nfunction buildParams(model, context, options = {}) {\n const contents = convertMessages(model, context);\n const generationConfig = {};\n if (options.temperature !== undefined) {\n generationConfig.temperature = options.temperature;\n }\n if (options.maxTokens !== undefined) {\n generationConfig.maxOutputTokens = options.maxTokens;\n }\n const functionCallingMode = context.tools?.length\n ? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id))\n : undefined;\n const config = {\n ...(Object.keys(generationConfig).length > 0 && generationConfig),\n ...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n ...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),\n ...(functionCallingMode !== undefined && {\n toolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n }),\n };\n if (options.thinking?.enabled && model.reasoning) {\n const thinkingConfig = { includeThoughts: true };\n if (options.thinking.level !== undefined) {\n thinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];\n }\n else if (options.thinking.budgetTokens !== undefined) {\n thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n }\n config.thinkingConfig = thinkingConfig;\n }\n else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n config.thinkingConfig = getDisabledThinkingConfig(model);\n }\n if (options.signal) {\n if (options.signal.aborted) {\n throw new Error(\"Request aborted\");\n }\n config.abortSignal = options.signal;\n }\n const params = {\n model: model.id,\n contents,\n config,\n };\n return params;\n}\nfunction isGemini3ProModel(model) {\n return /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\nfunction isGemini3FlashModel(model) {\n const id = model.id.toLowerCase();\n return /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\nfunction getDisabledThinkingConfig(model) {\n // Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n // do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n // thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n const geminiModel = model;\n if (isGemini3ProModel(geminiModel)) {\n return { thinkingLevel: ThinkingLevel.LOW };\n }\n if (isGemini3FlashModel(geminiModel)) {\n return { thinkingLevel: ThinkingLevel.MINIMAL };\n }\n // Gemini 2.x supports disabling via thinkingBudget = 0.\n return { thinkingBudget: 0 };\n}\nfunction getGemini3ThinkingLevel(effort, model) {\n if (isGemini3ProModel(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"LOW\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n switch (effort) {\n case \"minimal\":\n return \"MINIMAL\";\n case \"low\":\n return \"LOW\";\n case \"medium\":\n return \"MEDIUM\";\n case \"high\":\n return \"HIGH\";\n }\n}\nfunction getGoogleBudget(model, effort, customBudgets) {\n if (customBudgets?.[effort] !== undefined) {\n return customBudgets[effort];\n }\n if (model.id.includes(\"2.5-pro\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 32768,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n return -1;\n}\n//# sourceMappingURL=google-vertex.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;AASA,MAAM,cAAc;AACpB,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;CACvB,4BAA4B,cAAc;CAC1C,SAAS,cAAc;CACvB,KAAK,cAAc;CACnB,QAAQ,cAAc;CACtB,MAAM,cAAc;AACxB;AAEA,IAAI,kBAAkB;AACtB,MAAa,UAAU,OAAO,SAAS,YAAY;CAC/C,MAAM,SAAS,IAAI,4BAA4B;CAC/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK;GACL,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,aAAa;IACb,MAAM;KAAE,OAAO;KAAG,QAAQ;KAAG,WAAW;KAAG,YAAY;KAAG,OAAO;IAAE;GACvE;GACA,YAAY;GACZ,WAAW,KAAK,IAAI;EACxB;EACA,IAAI;GACA,IAAI,SAAS,SAAS,QAAQ,UAAU,WAAW,OAC/C,MAAM,IAAI,MAAM,4DAA4D;GAEhF,MAAM,SAAS,cAAc,OAAO;GAEpC,MAAM,SAAS,SACT,uBAAuB,OAAO,QAAQ,SAAS,OAAO,IACtD,aAAa,OAAO,eAAe,OAAO,GAAG,gBAAgB,OAAO,GAAG,SAAS,SAAS,SAAS,GAAG;GAC3G,IAAI,SAAS,YAAY,OAAO,SAAS,OAAO;GAChD,MAAM,aAAa,MAAM,SAAS,YAAY,QAAQ,KAAK;GAC3D,IAAI,eAAe,KAAA,GACf,SAAS;GAEb,MAAM,eAAe,MAAM,yBAAyB,OAAO,OAAO,sBAAsB,MAAM,GAAG,OAAO;GACxG,OAAO,KAAK;IAAE,MAAM;IAAS,SAAS;GAAO,CAAC;GAC9C,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KAAK,EAAE,KAAK,OAAO,yBAAyB,OAAO;AACzF;AACA,SAAS,0BAA0B,OAAO;CAItC,MAAM,cAAc;CACpB,IAAI,kBAAkB,WAAW,GAC7B,OAAO,EAAE,eAAe,cAAc,IAAI;CAE9C,IAAI,oBAAoB,WAAW,GAC/B,OAAO,EAAE,eAAe,cAAc,QAAQ;CAGlD,OAAO,EAAE,gBAAgB,EAAE;AAC/B;AACA,SAAS,wBAAwB,QAAQ,OAAO;CAC5C,IAAI,kBAAkB,KAAK,GACvB,QAAQ,QAAR;EACI,KAAK;EACL,KAAK,OACD,OAAO;EACX,KAAK;EACL,KAAK,QACD,OAAO;CACf;CAEJ,QAAQ,QAAR;EACI,KAAK,WACD,OAAO;EACX,KAAK,OACD,OAAO;EACX,KAAK,UACD,OAAO;EACX,KAAK,QACD,OAAO;CACf;AACJ;AACA,SAAS,gBAAgB,OAAO,QAAQ,eAAe;CACnD,IAAI,gBAAgB,YAAY,KAAA,GAC5B,OAAO,cAAc;CAEzB,IAAI,MAAM,GAAG,SAAS,SAAS,GAO3B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,WAAW,GAO7B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,OAAO;AACX"}
package/dist/host.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { s as registerVisionCompanions, t as applyPiPackage } from "./runtime-Dnk9mhrc.mjs";
3
- import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
2
+ import { s as registerVisionCompanions, t as applyPiPackage } from "./runtime-B3N7s93Q.mjs";
3
+ import { t as resolvePiPackage } from "./source-l77aIDwD.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { existsSync } from "node:fs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/engine.ts","../src/compatibility.ts","../src/mcp-config.ts","../src/source.ts","../src/index.ts"],"mappings":";;;;;UA8BiB;;EAEf;;EAEA;;;;;;;;EAQA,2BAA2B;;;;;;;;;;EAU3B;;;;;;;;EAQA;;;iBAIc,gBAAgB;UAUtB;EACR;EACA;;;;EAIA;;;;;;;;iBAyBoB,0BACpB,qBACA;EAAW;EAAoB,QAAQ;IACtC,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8HK,yBACd,KAAK,SACL,kBAAkB,iBAAiB,0BACnC;EAAU,KAAK;;;cA2QJ;cACA;iBAES,MAAM,KAAK,SAAS,SAAQ,eAAoB;;;UCzf5D;EACR,OAAO;EACP;;EAEA;;;;;;;;;UAUQ,oBAAoB;EAC5B;;cAQW;cAKA;cAKA;cAYA,mBAAmB,SAAS,eAAe,SAAS,eAAe;cA+NnE,eAAe,SAAS,eAAe;cA4BvC,kBAAkB,SAAS,eAAe;cA+B1C,WAAW,SAAS,eAAe;cA8InC,aAAa,SAAS,eAAe;iBAgHlC,WAAW,iBAAiB;iBAI5B,aAAa,gBAAgB;iBAO7B,kBAAkB,qBAAqB,uBAAuB;iBAS9D,uBAAuB,mBAAmB;iBAI1C,yBAAyB,mBAAmB;;;KCllBvD,gBAAgB;UAEJ;EACf;EACA;EACA;EACA;EACA;EACA,MAAM;EACN;EACA;EACA,UAAU;EACV;;UAGe;EACf;EACA;;UAGe;EACf,SAAS;EACT,SAAS;EACT,UAAU;EACV;;iBA6Cc,oBAAoB,aAAa;EAA8B,SAAS,YAAY;EAAc;;iBAuElG,mBAAmB,aAAa,wBAA4B;;iBAsD5D,eAAe,QAAQ;;;iBC/EjB,iBAAiB,gBAAgB,eAAsB,QAAQ;;;;;;;;iBChH/D,eAAe,KAAK,oBAAoB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/engine.ts","../src/compatibility.ts","../src/mcp-config.ts","../src/source.ts","../src/index.ts"],"mappings":";;;;;UA8BiB;;EAEf;;EAEA;;;;;;;;EAQA,2BAA2B;;;;;;;;;;EAU3B;;;;;;;;EAQA;;;iBAIc,gBAAgB;UAUtB;EACR;EACA;;;;EAIA;;;;;;;;iBAyBoB,0BACpB,qBACA;EAAW;EAAoB,QAAQ;IACtC,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8HK,yBACd,KAAK,SACL,kBAAkB,iBAAiB,0BACnC;EAAU,KAAK;;;cA2QJ;cACA;iBAES,MAAM,KAAK,SAAS,SAAQ,eAAoB;;;UCzf5D;EACR,OAAO;EACP;;EAEA;;;;;;;;;UAUQ,oBAAoB;EAC5B;;cAQW;cAKA;cAKA;cAYA,mBAAmB,SAAS,eAAe,SAAS,eAAe;cAkOnE,eAAe,SAAS,eAAe;cA4BvC,kBAAkB,SAAS,eAAe;cA+B1C,WAAW,SAAS,eAAe;cA8InC,aAAa,SAAS,eAAe;iBAgHlC,WAAW,iBAAiB;iBAI5B,aAAa,gBAAgB;iBAO7B,kBAAkB,qBAAqB,uBAAuB;iBAS9D,uBAAuB,mBAAmB;iBAI1C,yBAAyB,mBAAmB;;;KCrlBvD,gBAAgB;UAEJ;EACf;EACA;EACA;EACA;EACA;EACA,MAAM;EACN;EACA;EACA,UAAU;EACV;;UAGe;EACf;EACA;;UAGe;EACf,SAAS;EACT,SAAS;EACT,UAAU;EACV;;iBA6Cc,oBAAoB,aAAa;EAA8B,SAAS,YAAY;EAAc;;iBAuElG,mBAAmB,aAAa,wBAA4B;;iBAsD5D,eAAe,QAAQ;;;iBCajB,iBAAiB,gBAAgB,eAAsB,QAAQ;;;;;;;;iBC5M/D,eAAe,KAAK,oBAAoB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
 
2
- import { ot as providePiExtensionDiscovery } from "./pi-coding-agent-CPXFo0UO.mjs";
3
- import { c as runtimeInternals, n as getSharedChildExtensionCatalog, o as registerChildExtensionCatalog, s as registerVisionCompanions } from "./runtime-Dnk9mhrc.mjs";
2
+ import { c as runtimeInternals, n as getSharedChildExtensionCatalog, o as registerChildExtensionCatalog, s as registerVisionCompanions } from "./runtime-B3N7s93Q.mjs";
3
+ import { ot as providePiExtensionDiscovery } from "./pi-coding-agent-lcNs9Wos.mjs";
4
+ import { t as getAgentDir } from "./pi-config-shim-CZ1wFzqM.mjs";
4
5
  import { i as renderMcpPatch, n as convertPiMcpConfig, t as collectPiMcpServers } from "./mcp-config-C1K-IzzB.mjs";
5
- import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
6
+ import { t as resolvePiPackage } from "./source-l77aIDwD.mjs";
6
7
  import { applyPiHost, applyPreparedPiHost, manifestForInstalled, preparePiHost } from "./host.mjs";
7
- import { a as PI_AI_PACKAGES, c as UI_CONTEXT_RULES, d as ruleForEvent, f as ruleForHostImport, i as HOST_IMPORT_RULES, l as ruleForApi, n as CONTEXT_RULES, o as PI_CODING_AGENT_PACKAGES, p as ruleForUiContextProperty, r as EVENT_RULES, s as PI_TUI_PACKAGES, t as API_RULES, u as ruleForContextProperty } from "./compatibility-CZs3LwYn.mjs";
8
+ import { a as PI_AI_PACKAGES, c as UI_CONTEXT_RULES, d as ruleForEvent, f as ruleForHostImport, i as HOST_IMPORT_RULES, l as ruleForApi, n as CONTEXT_RULES, o as PI_CODING_AGENT_PACKAGES, p as ruleForUiContextProperty, r as EVENT_RULES, s as PI_TUI_PACKAGES, t as API_RULES, u as ruleForContextProperty } from "./compatibility-DS6POFZD.mjs";
8
9
  import { readFile } from "node:fs/promises";
9
10
  import { existsSync, realpathSync } from "node:fs";
10
11
  import { dirname, join, resolve } from "node:path";
@@ -317,6 +318,7 @@ const inject = [
317
318
  "skills"
318
319
  ];
319
320
  async function apply(ctx, config = {}) {
321
+ if (process.env.PI_CODING_AGENT_DIR === void 0 || process.env.PI_CODING_AGENT_DIR === "") process.env.PI_CODING_AGENT_DIR = getAgentDir();
320
322
  const log = ctx.logger;
321
323
  const warn = (message) => {
322
324
  log?.warn?.(message);
@@ -407,7 +409,7 @@ async function apply(ctx, config = {}) {
407
409
  * @returns the compatibility report.
408
410
  */
409
411
  async function analyzePackage(pkg) {
410
- const { analyzePackage: run } = await import("./analyzer-C139Y2S7.mjs");
412
+ const { analyzePackage: run } = await import("./analyzer-DbgL3neo.mjs");
411
413
  return run(pkg);
412
414
  }
413
415
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/engine.ts","../src/index.ts"],"sourcesContent":["// The pi2dsh engine: ONE installed copy of the bridge that mounts every Pi\n// package the user has added to their DSH profile.\n//\n// dsh plugin --profile p add pi2dsh ← the engine (this plugin)\n// dsh plugin --profile p add @kassing/pi-vision ← plain npm dependency\n// dsh plugin --profile p add pi-vision-tool ← plain npm dependency\n//\n// DSH's plugin manager records only packages that declare `dsh.bundle` as\n// profile layers; everything else stays an ordinary dependency (\"a plain\n// library is fine\"). The engine reads the profile manifest's DIRECT\n// dependencies — every entry there was an explicit `dsh plugin add` — and\n// mounts each package that identifies as a Pi package, all through one\n// bridge instance: one model ledger, one command space, one upgrade unit.\n//\n// Discovery is manifest-driven, never a node_modules scan (the lesson from\n// Prettier 3 dropping directory-based plugin discovery): the dependency list\n// is the user's explicit intent, and package identification uses the same\n// Pi markers `resolvePiPackage` has always used (the `pi` manifest field,\n// with Pi's directory conventions as fallback).\n\nimport { readFile } from 'node:fs/promises'\nimport { existsSync, realpathSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { applyPreparedPiHost, preparePiHost, type PreparedPiHostPackage } from './host.js'\nimport { getSharedChildExtensionCatalog, registerChildExtensionCatalog, registerVisionCompanions, runtimeInternals } from './runtime.js'\nimport { providePiExtensionDiscovery } from './compat/pi-coding-agent.js'\nimport { resolvePiPackage } from './source.js'\n\nexport interface EngineConfig {\n /** Mount exactly these packages (skips discovery). */\n packages?: string[]\n /** Never mount these packages even when discovered. */\n exclude?: string[]\n /**\n * Image-admission companion routes. Default: AUTOMATIC — every text-only\n * llm route gets a \\`<route>-vision\\` companion that admits pasted images\n * (a mounted vision extension analyzes them; without one the image is\n * materialized to a file any image-capable tool can read). \\`false\\`\n * turns companions off; an explicit \\`{ <route>: [modelIds] }\\` narrows.\n */\n visionCompanions?: false | Record<string, readonly string[]>\n /**\n * Serve the browser presentation surfaces (the `/pi2dsh` state route the\n * web renderer polls, and with it the `mode: 'tui'` claim on the web\n * composition). Default: OFF — the engine alone projects nothing into the\n * browser, so a web session behaves exactly like the headless CLI (Pi's\n * own rpc mode; packages degrade gracefully on their own). The dsh-work-x\n * suite turns this on and carries the actual renderer in its client\n * bundle; any other product layer that ships a renderer can do the same.\n */\n browserPresentation?: boolean\n /**\n * Serve DSH-native subagents with the profile's Pi packages (default: OFF —\n * such children run as plain DSH agents, today's behavior). Children the Pi\n * subagent bridge mints are NEVER covered: they already receive the creator's\n * own per-spawn loader mount and are recognized by the `pi2dsh-sub-` session-id\n * prefix.\n */\n serveNativeSubagents?: boolean\n}\n\n/** Locate the DSH profile root: the nearest ancestor holding cordis.yml. */\nexport function findProfileRoot(start: string): string | undefined {\n let dir = start\n for (;;) {\n if (existsSync(join(dir, 'cordis.yml')) && existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\ninterface DiscoveredPackage {\n name: string\n dir: string\n /** Resolution anchor when the package is carried by a suite (its members\n * are the suite's dependencies, unreachable from the profile root under\n * pnpm's isolated layout). */\n anchor?: string\n}\n\ninterface ProfileManifest {\n dependencies?: Record<string, string>\n dsh?: { profile?: { bundles?: string[] } }\n}\n\nasync function readProfileManifest(profileRoot: string): Promise<ProfileManifest> {\n return JSON.parse(await readFile(join(profileRoot, 'package.json'), 'utf8')) as ProfileManifest\n}\n\nfunction resolveDependencyDir(profileRoot: string, name: string): string | undefined {\n // Direct dependencies of the profile live under its node_modules by name\n // (pnpm links them there); resolving by path needs no exports gymnastics.\n const dir = join(profileRoot, 'node_modules', name)\n return existsSync(join(dir, 'package.json')) ? dir : undefined\n}\n\n/**\n * The profile's direct dependencies that identify as Pi packages: not the\n * engine itself, not a `dsh.bundle` (those are DSH plugins, not Pi\n * packages), carrying either Pi's `pi` manifest field or extension sources\n * under Pi's directory conventions.\n */\nexport async function discoverProfilePiPackages(\n profileRoot: string,\n options: { exclude?: string[], warn?: (message: string) => void } = {},\n): Promise<DiscoveredPackage[]> {\n const warn = options.warn ?? (() => {})\n const excluded = new Set(options.exclude ?? [])\n const manifest = await readProfileManifest(profileRoot)\n const discovered: DiscoveredPackage[] = []\n for (const name of Object.keys(manifest.dependencies ?? {})) {\n if (name === 'pi2dsh' || excluded.has(name)) continue\n const dir = resolveDependencyDir(profileRoot, name)\n if (dir === undefined) {\n warn(`[pi2dsh engine] dependency ${JSON.stringify(name)} is not installed under the profile; skipping`)\n continue\n }\n let packageJson: Record<string, unknown>\n try {\n packageJson = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>\n } catch (error) {\n warn(`[pi2dsh engine] cannot read ${name}/package.json (${error instanceof Error ? error.message : String(error)}); skipping`)\n continue\n }\n // A suite: `pi2dsh: { suite: [names...] }` mounts the listed Pi packages\n // as if the user had added each one. The list is an explicit manifest —\n // the same discovery covenant as the profile dependency list, one hop\n // deeper — and the members are the suite's own dependencies, so each\n // resolves anchored at the suite package (pnpm keeps transitive\n // dependencies out of the profile root). One level only, no recursion.\n const suite = (packageJson.pi2dsh as { suite?: unknown } | undefined)?.suite\n if (Array.isArray(suite)) {\n // The anchor must be the suite's REAL directory: the profile's\n // node_modules entry is a pnpm symlink into .pnpm, and Node resolution\n // walks up from the anchor's literal path — only the realpath has the\n // suite's own dependencies as .pnpm neighbours.\n let anchorDir = dir\n try {\n anchorDir = realpathSync(dir)\n } catch { /* an unreadable dir keeps the literal path and fails loud in prepare */ }\n for (const member of suite) {\n if (typeof member !== 'string' || member.length === 0) continue\n if (member === 'pi2dsh' || excluded.has(member)) continue\n discovered.push({ name: member, dir, anchor: join(anchorDir, 'package.json') })\n }\n continue\n }\n // A dsh.bundle-declaring package is a DSH plugin layer, never a Pi package.\n if ((packageJson.dsh as { bundle?: unknown } | undefined)?.bundle !== undefined) continue\n if (packageJson.pi !== undefined && typeof packageJson.pi === 'object') {\n discovered.push({ name, dir })\n continue\n }\n // No `pi` field: fall back to Pi's directory conventions via the same\n // resolver every other mount path uses (a package with zero extension\n // sources is a plain library and stays unmounted).\n try {\n const pkg = await resolvePiPackage(dir)\n try {\n if (pkg.resources.extensions.length > 0) discovered.push({ name, dir })\n } finally {\n await pkg.dispose()\n }\n } catch {\n // Not resolvable as a Pi package — a plain library.\n }\n }\n // One mount per name. A package that is both a direct dependency and a\n // suite member mounts as the DIRECT dependency (the user's own explicit\n // add, resolved from the profile root) — the suite copy yields.\n const byName = new Map<string, DiscoveredPackage>()\n for (const pkg of discovered) {\n const existing = byName.get(pkg.name)\n if (existing === undefined || (existing.anchor !== undefined && pkg.anchor === undefined)) {\n byName.set(pkg.name, pkg)\n }\n }\n return [...byName.values()]\n}\n\ninterface AgentScopedMount {\n ready: Promise<void>\n /** Set when the mount failed; the agent then runs as a plain DSH agent. */\n failure?: string\n}\n\n/** The loose shapes of the official DSH seams this file consumes. */\ninterface AgentLike {\n ctx: Context\n}\ninterface EngineHostContext {\n /** Un-injected reflection access (the ctx.get('loader') idiom): the engine\n * must not hard-depend on the agent registry — compositions without one\n * (bare test hosts) simply have no agents to mount for. */\n get?(name: string): unknown\n tools?: { schemas?(scope: unknown): Array<{ name: string }> }\n on(name: string, listener: (...args: never[]) => unknown): () => void\n}\ninterface AgentRegistryLike {\n roots?(): AgentLike[]\n}\n\n/**\n * The single mount path on every DSH surface: one Pi runtime per root Agent.\n *\n * Pi instantiates its extensions once per session; DSH's twin of that scope is\n * the Agent with its public `agent.ctx` (\"contributions are agent-local,\n * unwind on disposal\"). Mounting is driven purely by official core seams, so\n * the same semantics hold on the TUI, web, headless, ACP and config-declared\n * agents alike:\n *\n * - `agent/created` fires on every publication path before the loop can run\n * a first turn; it eagerly starts that agent's mount.\n * - `system-prompt/assemble` (awaited waterfall, runs in every step's\n * preStep) gates the assembly on the mount and patches the pre-waterfall\n * tools snapshot from the official scoped projection `tools.schemas()` —\n * stock DSH collects `assembly.tools` before dispatching the waterfall,\n * so a mount that lands during the wait would otherwise miss turn one.\n * - `tools/pre-execute` (awaited waterfall) closes the same window for\n * direct executions that bypass assembly.\n *\n * `agent/session-start` deliberately is NOT the trigger: DSH documents it as a\n * veto-less notification that cannot gate startup. The waterfalls above are\n * the officially awaited seams, and the exact pattern of registering onto a\n * foreign agent's ctx from a lifecycle event is what DSH's own schedule\n * plugin ships.\n *\n * A mount failure never takes the Agent down: the agent keeps running as a\n * plain DSH agent, the failure is reported loudly once, and only the Pi\n * packages are missing — the capability-gap discipline, not a rollback.\n */\nexport function installAgentScopedMounts(\n ctx: Context,\n preparedPackages: Promise<readonly PreparedPiHostPackage[]>,\n report: { warn(message: string): void },\n): void {\n const host = ctx as unknown as EngineHostContext\n const mounts = new WeakMap<object, AgentScopedMount>()\n\n const registry = (): AgentRegistryLike | undefined => {\n try {\n return host.get?.('agents') as AgentRegistryLike | undefined\n } catch {\n return undefined\n }\n }\n\n const isRootAgent = (agent: object): boolean => {\n // Subagents keep Pi's own sub-session semantics through the session\n // bridge; only runtime roots receive a Pi runtime (the same distinction\n // DSH's schedule plugin draws via agents.roots()).\n const agents = registry()\n const roots = agents?.roots\n if (typeof roots !== 'function') return true\n try {\n return (roots.call(agents) as unknown[]).includes(agent)\n } catch {\n return true\n }\n }\n\n const ensureMount = (agent: AgentLike): AgentScopedMount => {\n let mount = mounts.get(agent)\n if (mount === undefined) {\n const started: AgentScopedMount = { ready: Promise.resolve() }\n started.ready = preparedPackages.then(async prepared => {\n if (prepared.length === 0) return\n try {\n await applyPreparedPiHost(agent.ctx, prepared, agent as unknown as Record<string, unknown>)\n } catch (error) {\n // Loud, once per agent; the gates resolve so the plain DSH agent\n // keeps working. Faking success is forbidden — the message names\n // what is missing.\n started.failure = error instanceof Error ? error.message : String(error)\n report.warn(`[pi2dsh engine] Pi packages failed to mount for this agent; it continues without them: ${started.failure}`)\n }\n })\n mounts.set(agent, started)\n mount = started\n }\n return mount\n }\n\n // Eager start on publication. `agent/created` reaches host-level listeners\n // on every create/resume/config path, before the loop can open a turn.\n host.on('agent/created', ((payload: { agent: AgentLike }) => {\n if (isRootAgent(payload.agent)) ensureMount(payload.agent)\n }) as never)\n\n // Correctness boundary #1: no prompt assembly for a root agent proceeds\n // before its Pi runtime is mounted, and the tools snapshot taken before\n // this waterfall is reconciled against the official scoped projection.\n host.on('system-prompt/assemble', (async (\n assembly: { tools: Array<{ name: string }> },\n context: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = context.agent\n if (agent !== undefined && isRootAgent(agent)) {\n await ensureMount(agent).ready\n const schemas = host.tools?.schemas\n if (typeof schemas === 'function') {\n const present = new Set(assembly.tools.map(tool => tool.name))\n for (const schema of schemas.call(host.tools, agent)) {\n if (!present.has(schema.name)) assembly.tools.push(schema)\n }\n }\n }\n return next()\n }) as never)\n\n // Correctness boundary #2: tool execution for a root agent waits for the\n // same mount (serially awaited by the tool runtime before dispatch).\n host.on('tools/pre-execute', (async (\n exec: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n if (exec.agent !== undefined && isRootAgent(exec.agent)) await ensureMount(exec.agent).ready\n return next()\n }) as never)\n\n // Backfill: agents published before this plugin finished loading (a surface\n // that skips the official await-the-loader pattern DSH's headless runner\n // uses). Their next assembly still passes the gates above.\n void preparedPackages.then(() => {\n const agents = registry()\n const roots = agents?.roots\n if (typeof roots !== 'function') return\n for (const agent of roots.call(agents)) ensureMount(agent)\n })\n}\n\n/** Session-id prefix minted by the Pi subagent bridge (src/subagent-bridge.ts). */\nexport const BRIDGE_CHILD_SESSION_ID_PREFIX = 'pi2dsh-sub-'\n\n/**\n * Optional coverage for DSH-native subagents, enabled by the\n * `serveNativeSubagents` engine config.\n *\n * The Pi subagent bridge already serves the children IT mints: the creator's\n * per-spawn loader mount (a8b7a0a) runs at creation and again on a persisted\n * resume. This covers the OTHER lineage — children a DSH surface mints\n * directly (DSH-native delegation, headless subagents, a second agent in the\n * web UI) — which carry no Pi lineage and would otherwise run as plain DSH\n * agents with none of the profile's Pi extensions.\n *\n * One lineage check per created Agent (maintainer point 2): subagent origin\n * AND a session id that does not carry the bridge prefix. The bridge mints\n * `pi2dsh-sub-` ids at creation and a persisted resume keeps the original id,\n * so the skip holds on both bridge paths and a bridge child is never mounted\n * twice.\n *\n * The mount reuses the engine's own child-extension catalog (maintainer\n * point 3) — the same object the bridge's hook consumes — so a native child's\n * tool set is exactly Pi's default-discovered set (the catalog's no-loader\n * path), the mount lands on the child's OWN ctx and unwinds with the child,\n * and there is no second registration path to drift out of sync.\n *\n * Partition with the root-mount path: agents the registry reports as runtime\n * roots are installAgentScopedMounts' territory (it gates them the same way\n * this path does). Live delegation shows a DSH-native child of a top-level\n * session CAN be a runtime root — serving it here as well raced two mount\n * passes onto the same scope (each package survived via the prompt-section\n * guard, but the double attempt is exactly what this flag must not do). This\n * listener therefore serves exactly the remainder: subagent-origin,\n * non-bridge, non-root agents. The predicate is the root path's own, applied\n * at the same event; its fail-open (roots() unavailable ⇒ every agent is a\n * root) mirrors here as fail-closed (this listener serves nothing).\n *\n * The readiness promise is memoized on the child's SCOPE (agent.ctx), not the\n * agent object: a re-announced agent for the same session reuses the scope,\n * and the dedupe must key on what the mount actually lands in.\n *\n * First-turn gates mirror the root path's exactly: the child's first prompt\n * assembly and its direct tool executions await the mount, and the\n * pre-waterfall tools snapshot is reconciled against the official scoped\n * projection. Without the gate a mount that lands after the first turn's\n * snapshot leaves the child's first (and sometimes only) turn tool-less —\n * proven live at depth 2, where the child's grandchild saw zero extension\n * tools because its mount raced its first model call.\n *\n * A mount failure never takes the child down: the same capability-gap\n * discipline as root mounting — the child keeps running as a plain DSH agent\n * and the failure is reported loudly once.\n */\nexport function installNativeSubagentMounts(\n ctx: Context,\n preparedPackages: Promise<readonly PreparedPiHostPackage[]>,\n enabled: boolean,\n report: { warn(message: string): void },\n): void {\n if (!enabled) return\n const host = ctx as unknown as EngineHostContext\n\n // The root path's own predicate, applied at the same event it applies its\n // (see installAgentScopedMounts): a runtime root is served — and gated —\n // there. Failing closed keeps the partition exact when roots() is absent.\n const isRootAgent = (agent: object): boolean => {\n let agents: AgentRegistryLike | undefined\n try {\n agents = host.get?.('agents') as AgentRegistryLike | undefined\n } catch {\n return true\n }\n const roots = agents?.roots\n if (typeof roots !== 'function') return true\n try {\n return (roots.call(agents) as unknown[]).includes(agent)\n } catch {\n return true\n }\n }\n\n // child scope (agent.ctx) -> its mount's readiness. Reading the catalog\n // after preparation (never before) covers children published while the\n // engine was still preparing; no catalog = plain child, exactly the bridge\n // hook's no-catalog behavior.\n const mounts = new WeakMap<object, Promise<void>>()\n\n const ensureMount = (agent: AgentLike): Promise<void> => {\n const scope = agent.ctx\n let ready = mounts.get(scope)\n if (ready === undefined) {\n ready = preparedPackages.then(async () => {\n const catalog = getSharedChildExtensionCatalog(ctx)\n if (catalog === undefined) return\n // Native children have no creator loader: the full discovered set is\n // Pi's default discovery (the no-loader path of\n // resolveChildExtensionPackages).\n const names = [...new Set(catalog.packageByEntryPath.values())]\n if (names.length === 0) return\n try {\n const failures = await catalog.mount(agent as unknown as Record<string, unknown>, names)\n for (const failure of failures) {\n // Same message shape the bridge's own mount path uses.\n report.warn(`[pi2dsh] child extension ${failure.name} did not mount: ${failure.error}`)\n }\n } catch (error) {\n report.warn(`[pi2dsh] child extension mount failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n })\n mounts.set(scope, ready)\n }\n return ready\n }\n\n const handle = (agent: AgentLike): void => {\n // The single lineage check: DSH-native subagents only. Pi-origin\n // (bridge) children are already served by the creator's per-spawn loader\n // mount; the `pi2dsh-sub-` prefix identifies them on creation AND on a\n // persisted resume, where the original session id survives.\n if (!runtimeInternals.isSubagentOrigin(agent as unknown as Record<string, unknown>)) return\n const session = (agent as { session?: { id?: unknown } }).session ?? agent\n if (String((session as { id?: unknown }).id ?? '').startsWith(BRIDGE_CHILD_SESSION_ID_PREFIX)) return\n // Runtime roots are the root-mount path's territory; serving them here\n // would race a second mount onto the same scope.\n if (isRootAgent(agent)) return\n void ensureMount(agent)\n }\n\n host.on('agent/created', ((payload: { agent: AgentLike }) => {\n if (payload.agent !== undefined) handle(payload.agent)\n }) as never)\n\n // Correctness boundary #1 (mirror of the root path's): no prompt assembly\n // for a served child proceeds before its mount lands, and the pre-waterfall\n // tools snapshot is reconciled against the official scoped projection.\n host.on('system-prompt/assemble', (async (\n assembly: { tools: Array<{ name: string }> },\n context: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = context.agent\n const ready = agent === undefined ? undefined : mounts.get(agent.ctx)\n if (ready !== undefined) {\n await ready\n const schemas = host.tools?.schemas\n if (typeof schemas === 'function') {\n const present = new Set(assembly.tools.map(tool => tool.name))\n for (const schema of schemas.call(host.tools, agent)) {\n if (!present.has(schema.name)) assembly.tools.push(schema)\n }\n }\n }\n return next()\n }) as never)\n\n // Correctness boundary #2 (mirror of the root path's): direct tool\n // executions for a served child wait for the same mount.\n host.on('tools/pre-execute', (async (\n exec: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = exec.agent\n const ready = agent === undefined ? undefined : mounts.get(agent.ctx)\n if (ready !== undefined) await ready\n return next()\n }) as never)\n}\n\n/** Cordis plugin surface: `dsh plugin add pi2dsh` mounts this. */\nexport const name = 'pi2dsh'\nexport const inject = ['tools', 'systemPrompt', 'commands', 'skills']\n\nexport async function apply(ctx: Context, config: EngineConfig = {}): Promise<void> {\n // Same emission as the runtime's logger helper: the cordis logger AND the\n // console — profile logger levels must never hide what the engine mounted.\n const log = (ctx as unknown as { logger?: { info?(m: string): void, warn?(m: string): void } }).logger\n const warn = (message: string): void => { log?.warn?.(message); console.warn(message) }\n const info = (message: string): void => { log?.info?.(message); console.log(message) }\n\n // The loader resolves plugins against the profile's baseUrl; that IS the\n // profile root. The ancestor walk from the installed engine is the\n // fallback for compositions without a loader (tests, hand-built hosts).\n const baseUrl = (ctx as unknown as { baseUrl?: string }).baseUrl\n const profileRoot = (baseUrl !== undefined ? findProfileRoot(fileURLToPath(new URL('.', baseUrl))) : undefined)\n ?? findProfileRoot(dirname(fileURLToPath(import.meta.url)))\n if (profileRoot === undefined) {\n throw new Error('pi2dsh engine: no DSH profile root (cordis.yml + package.json) above the installed engine — is pi2dsh installed via `dsh plugin add pi2dsh`?')\n }\n\n // The single mount path, before any await: gates and lifecycle listeners\n // must exist the moment a surface can publish its first Agent. Package\n // preparation resolves behind this promise; the gates hold each agent's\n // first assembly until its own mount lands.\n let resolvePrepared!: (prepared: readonly PreparedPiHostPackage[]) => void\n const preparedPackages = new Promise<readonly PreparedPiHostPackage[]>(resolve => {\n resolvePrepared = resolve\n })\n installAgentScopedMounts(ctx, preparedPackages, { warn })\n installNativeSubagentMounts(ctx, preparedPackages, config.serveNativeSubagents === true, { warn })\n\n registerVisionCompanions(ctx, config.visionCompanions)\n\n try {\n // The host half, mounted exactly once regardless of packages or agents:\n // Pi's built-in provider directory, `/login`, and credential recovery.\n // Without it a fresh engine cannot run `/login openai-codex`: DSH treats\n // the unknown slash line as a model prompt and fails on the unrelated\n // default provider credential. Community packages join the same\n // SharedHostState (keyed on ctx.root), so host-level resources stay\n // single-instance no matter which agent scope mounts them.\n await applyPreparedPiHost(ctx, [{\n name: 'pi2dsh-builtins',\n rootUrl: new URL('.', import.meta.url),\n manifest: {\n schemaVersion: 1,\n package: { name: 'pi2dsh-builtins', version: '0.0.0', source: 'engine' },\n extensions: [],\n skillDirs: [],\n prompts: [],\n },\n }])\n\n const packages: Array<{ name: string, anchor?: string }> = Array.isArray(config.packages) && config.packages.length > 0\n ? config.packages.map(name => ({ name }))\n : await discoverProfilePiPackages(profileRoot, {\n ...(Array.isArray(config.exclude) ? { exclude: config.exclude } : {}),\n warn,\n })\n if (packages.length === 0) {\n info('[pi2dsh engine] no Pi packages installed in this profile yet — add one with: dsh plugin --profile <p> add <pi-package>')\n resolvePrepared([])\n return\n }\n info(`[pi2dsh engine] preparing ${packages.length} Pi package(s): ${packages.map(pkg => pkg.name).join(', ')}`)\n const prepared = await preparePiHost(\n {\n packages: packages.map(pkg =>\n pkg.anchor === undefined ? { name: pkg.name } : { name: pkg.name, anchor: pkg.anchor }),\n },\n join(profileRoot, 'package.json'),\n )\n // Child-extension catalog: what real Pi's createAgentSession \"default-\n // discovered extensions\" means on this host. Entries are each package's\n // DECLARED pi extension files (absolute, inside the installed dir), so a\n // creator's own filter code (pi-subagents' extensions/exclude/ext:\n // machinery) canonicalizes them exactly as it does on Pi. Mounting lands\n // on the child agent's OWN ctx — contributions unwind with the agent,\n // which is what makes per-child instances leak-free by construction.\n const entryCatalog = new Map<string, string>()\n for (const pkg of prepared) {\n const rootDir = fileURLToPath(pkg.rootUrl)\n // Resolved keys, because the consumer looks entries up by resolved path.\n for (const rel of pkg.manifest.extensions) entryCatalog.set(resolve(rootDir, rel), pkg.name)\n }\n providePiExtensionDiscovery([...entryCatalog.keys()].map(path => ({ path })))\n registerChildExtensionCatalog(ctx, {\n packageByEntryPath: entryCatalog,\n mount: async (childAgent, packageNames) => {\n const wanted = new Set(packageNames)\n const subset = prepared.filter(pkg => wanted.has(pkg.name))\n const scope = (childAgent as { ctx?: Context }).ctx\n if (scope === undefined) {\n return subset.map(pkg => ({ name: pkg.name, error: 'the child agent exposes no ctx scope to mount into' }))\n }\n return applyPreparedPiHost(scope, subset, childAgent)\n },\n })\n\n // Host anchors, before the per-Agent gates open: every package's\n // HOST-level contributions (provider routes, OAuth accounts, /login,\n // credential recovery, companions, skills) exist from engine apply — a\n // surface with zero live Agents (web at boot) still advertises them, the\n // first Agent's model resolution finds its routes, and routes survive\n // Agent churn. Anchors serve no Agent; sessions belong to the per-Agent\n // instances the gates mount.\n // The engine-level browserPresentation flag rides into every package\n // mount's config: the /pi2dsh route (and the web `mode: 'tui'` claim)\n // exists only when a product layer configured a renderer. Stamped here\n // rather than defaulted in the runtime so per-Agent remounts and the\n // host anchor agree on one answer.\n const presented = config.browserPresentation === true\n ? prepared.map(pkg => ({ ...pkg, config: { ...(pkg.config ?? {}), browserPresentation: true } }))\n : prepared\n await applyPreparedPiHost(ctx, presented, undefined, { hostAnchor: true })\n resolvePrepared(presented)\n } catch (error) {\n // The gates must never hang on a failed preparation; agents keep running\n // as plain DSH agents while the engine failure propagates loudly.\n resolvePrepared([])\n throw error\n }\n}\n","// Engine surface: `dsh plugin add pi2dsh` resolves this entry as a cordis\n// plugin (named exports, no default — a default export would make the\n// loader discard the function-plugin namespace).\nexport { apply, inject, name, discoverProfilePiPackages, findProfileRoot, installAgentScopedMounts, type EngineConfig } from './engine.js'\n\n// The CLI-only analysis surface loads lazily: its static-analysis dependency\n// (the 23 MB typescript compiler, an optional peer) must never be pulled\n// into a profile that installs the ENGINE. The dynamic import below keeps\n// the analyzer in its own chunk, off the engine's load path.\nimport type { CompatibilityReport, ResolvedPiPackage } from './types.js'\n\n/**\n * Static compatibility analysis of one resolved Pi package (CLI `inspect`).\n * @param pkg - the resolved package.\n * @returns the compatibility report.\n */\nexport async function analyzePackage(pkg: ResolvedPiPackage): Promise<CompatibilityReport> {\n const { analyzePackage: run } = await import('./analyzer.js')\n return run(pkg)\n}\n\nexport {\n API_RULES,\n CONTEXT_RULES,\n EVENT_RULES,\n HOST_IMPORT_RULES,\n PI_AI_PACKAGES,\n PI_CODING_AGENT_PACKAGES,\n PI_TUI_PACKAGES,\n UI_CONTEXT_RULES,\n ruleForApi,\n ruleForContextProperty,\n ruleForEvent,\n ruleForHostImport,\n ruleForUiContextProperty,\n} from './compatibility.js'\nexport { applyPiHost, applyPreparedPiHost, manifestForInstalled, preparePiHost } from './host.js'\nexport { collectPiMcpServers, convertPiMcpConfig, renderMcpPatch } from './mcp-config.js'\nexport { resolvePiPackage } from './source.js'\nexport type *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A,GAAW,EAAE,YAAY,KAAK,CAAC;EACzE,gBAAgB,SAAS;CAC3B,SAAS,OAAO;EAGd,gBAAgB,CAAC,CAAC;EAClB,MAAM;CACR;AACF;;;;;;;;AClmBA,eAAsB,eAAe,KAAsD;CACzF,MAAM,EAAE,gBAAgB,QAAQ,MAAM,OAAO;CAC7C,OAAO,IAAI,GAAG;AAChB"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/engine.ts","../src/index.ts"],"sourcesContent":["// The pi2dsh engine: ONE installed copy of the bridge that mounts every Pi\n// package the user has added to their DSH profile.\n//\n// dsh plugin --profile p add pi2dsh ← the engine (this plugin)\n// dsh plugin --profile p add @kassing/pi-vision ← plain npm dependency\n// dsh plugin --profile p add pi-vision-tool ← plain npm dependency\n//\n// DSH's plugin manager records only packages that declare `dsh.bundle` as\n// profile layers; everything else stays an ordinary dependency (\"a plain\n// library is fine\"). The engine reads the profile manifest's DIRECT\n// dependencies — every entry there was an explicit `dsh plugin add` — and\n// mounts each package that identifies as a Pi package, all through one\n// bridge instance: one model ledger, one command space, one upgrade unit.\n//\n// Discovery is manifest-driven, never a node_modules scan (the lesson from\n// Prettier 3 dropping directory-based plugin discovery): the dependency list\n// is the user's explicit intent, and package identification uses the same\n// Pi markers `resolvePiPackage` has always used (the `pi` manifest field,\n// with Pi's directory conventions as fallback).\n\nimport { readFile } from 'node:fs/promises'\nimport { existsSync, realpathSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { applyPreparedPiHost, preparePiHost, type PreparedPiHostPackage } from './host.js'\nimport { getSharedChildExtensionCatalog, registerChildExtensionCatalog, registerVisionCompanions, runtimeInternals } from './runtime.js'\nimport { getAgentDir, providePiExtensionDiscovery } from './compat/pi-coding-agent.js'\nimport { resolvePiPackage } from './source.js'\n\nexport interface EngineConfig {\n /** Mount exactly these packages (skips discovery). */\n packages?: string[]\n /** Never mount these packages even when discovered. */\n exclude?: string[]\n /**\n * Image-admission companion routes. Default: AUTOMATIC — every text-only\n * llm route gets a \\`<route>-vision\\` companion that admits pasted images\n * (a mounted vision extension analyzes them; without one the image is\n * materialized to a file any image-capable tool can read). \\`false\\`\n * turns companions off; an explicit \\`{ <route>: [modelIds] }\\` narrows.\n */\n visionCompanions?: false | Record<string, readonly string[]>\n /**\n * Serve the browser presentation surfaces (the `/pi2dsh` state route the\n * web renderer polls, and with it the `mode: 'tui'` claim on the web\n * composition). Default: OFF — the engine alone projects nothing into the\n * browser, so a web session behaves exactly like the headless CLI (Pi's\n * own rpc mode; packages degrade gracefully on their own). The dsh-work-x\n * suite turns this on and carries the actual renderer in its client\n * bundle; any other product layer that ships a renderer can do the same.\n */\n browserPresentation?: boolean\n /**\n * Serve DSH-native subagents with the profile's Pi packages (default: OFF —\n * such children run as plain DSH agents, today's behavior). Children the Pi\n * subagent bridge mints are NEVER covered: they already receive the creator's\n * own per-spawn loader mount and are recognized by the `pi2dsh-sub-` session-id\n * prefix.\n */\n serveNativeSubagents?: boolean\n}\n\n/** Locate the DSH profile root: the nearest ancestor holding cordis.yml. */\nexport function findProfileRoot(start: string): string | undefined {\n let dir = start\n for (;;) {\n if (existsSync(join(dir, 'cordis.yml')) && existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\ninterface DiscoveredPackage {\n name: string\n dir: string\n /** Resolution anchor when the package is carried by a suite (its members\n * are the suite's dependencies, unreachable from the profile root under\n * pnpm's isolated layout). */\n anchor?: string\n}\n\ninterface ProfileManifest {\n dependencies?: Record<string, string>\n dsh?: { profile?: { bundles?: string[] } }\n}\n\nasync function readProfileManifest(profileRoot: string): Promise<ProfileManifest> {\n return JSON.parse(await readFile(join(profileRoot, 'package.json'), 'utf8')) as ProfileManifest\n}\n\nfunction resolveDependencyDir(profileRoot: string, name: string): string | undefined {\n // Direct dependencies of the profile live under its node_modules by name\n // (pnpm links them there); resolving by path needs no exports gymnastics.\n const dir = join(profileRoot, 'node_modules', name)\n return existsSync(join(dir, 'package.json')) ? dir : undefined\n}\n\n/**\n * The profile's direct dependencies that identify as Pi packages: not the\n * engine itself, not a `dsh.bundle` (those are DSH plugins, not Pi\n * packages), carrying either Pi's `pi` manifest field or extension sources\n * under Pi's directory conventions.\n */\nexport async function discoverProfilePiPackages(\n profileRoot: string,\n options: { exclude?: string[], warn?: (message: string) => void } = {},\n): Promise<DiscoveredPackage[]> {\n const warn = options.warn ?? (() => {})\n const excluded = new Set(options.exclude ?? [])\n const manifest = await readProfileManifest(profileRoot)\n const discovered: DiscoveredPackage[] = []\n for (const name of Object.keys(manifest.dependencies ?? {})) {\n if (name === 'pi2dsh' || excluded.has(name)) continue\n const dir = resolveDependencyDir(profileRoot, name)\n if (dir === undefined) {\n warn(`[pi2dsh engine] dependency ${JSON.stringify(name)} is not installed under the profile; skipping`)\n continue\n }\n let packageJson: Record<string, unknown>\n try {\n packageJson = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>\n } catch (error) {\n warn(`[pi2dsh engine] cannot read ${name}/package.json (${error instanceof Error ? error.message : String(error)}); skipping`)\n continue\n }\n // A suite: `pi2dsh: { suite: [names...] }` mounts the listed Pi packages\n // as if the user had added each one. The list is an explicit manifest —\n // the same discovery covenant as the profile dependency list, one hop\n // deeper — and the members are the suite's own dependencies, so each\n // resolves anchored at the suite package (pnpm keeps transitive\n // dependencies out of the profile root). One level only, no recursion.\n const suite = (packageJson.pi2dsh as { suite?: unknown } | undefined)?.suite\n if (Array.isArray(suite)) {\n // The anchor must be the suite's REAL directory: the profile's\n // node_modules entry is a pnpm symlink into .pnpm, and Node resolution\n // walks up from the anchor's literal path — only the realpath has the\n // suite's own dependencies as .pnpm neighbours.\n let anchorDir = dir\n try {\n anchorDir = realpathSync(dir)\n } catch { /* an unreadable dir keeps the literal path and fails loud in prepare */ }\n for (const member of suite) {\n if (typeof member !== 'string' || member.length === 0) continue\n if (member === 'pi2dsh' || excluded.has(member)) continue\n discovered.push({ name: member, dir, anchor: join(anchorDir, 'package.json') })\n }\n continue\n }\n // A dsh.bundle-declaring package is a DSH plugin layer, never a Pi package.\n if ((packageJson.dsh as { bundle?: unknown } | undefined)?.bundle !== undefined) continue\n if (packageJson.pi !== undefined && typeof packageJson.pi === 'object') {\n discovered.push({ name, dir })\n continue\n }\n // No `pi` field: fall back to Pi's directory conventions via the same\n // resolver every other mount path uses (a package with zero extension\n // sources is a plain library and stays unmounted).\n try {\n const pkg = await resolvePiPackage(dir)\n try {\n if (pkg.resources.extensions.length > 0) discovered.push({ name, dir })\n } finally {\n await pkg.dispose()\n }\n } catch {\n // Not resolvable as a Pi package — a plain library.\n }\n }\n // One mount per name. A package that is both a direct dependency and a\n // suite member mounts as the DIRECT dependency (the user's own explicit\n // add, resolved from the profile root) — the suite copy yields.\n const byName = new Map<string, DiscoveredPackage>()\n for (const pkg of discovered) {\n const existing = byName.get(pkg.name)\n if (existing === undefined || (existing.anchor !== undefined && pkg.anchor === undefined)) {\n byName.set(pkg.name, pkg)\n }\n }\n return [...byName.values()]\n}\n\ninterface AgentScopedMount {\n ready: Promise<void>\n /** Set when the mount failed; the agent then runs as a plain DSH agent. */\n failure?: string\n}\n\n/** The loose shapes of the official DSH seams this file consumes. */\ninterface AgentLike {\n ctx: Context\n}\ninterface EngineHostContext {\n /** Un-injected reflection access (the ctx.get('loader') idiom): the engine\n * must not hard-depend on the agent registry — compositions without one\n * (bare test hosts) simply have no agents to mount for. */\n get?(name: string): unknown\n tools?: { schemas?(scope: unknown): Array<{ name: string }> }\n on(name: string, listener: (...args: never[]) => unknown): () => void\n}\ninterface AgentRegistryLike {\n roots?(): AgentLike[]\n}\n\n/**\n * The single mount path on every DSH surface: one Pi runtime per root Agent.\n *\n * Pi instantiates its extensions once per session; DSH's twin of that scope is\n * the Agent with its public `agent.ctx` (\"contributions are agent-local,\n * unwind on disposal\"). Mounting is driven purely by official core seams, so\n * the same semantics hold on the TUI, web, headless, ACP and config-declared\n * agents alike:\n *\n * - `agent/created` fires on every publication path before the loop can run\n * a first turn; it eagerly starts that agent's mount.\n * - `system-prompt/assemble` (awaited waterfall, runs in every step's\n * preStep) gates the assembly on the mount and patches the pre-waterfall\n * tools snapshot from the official scoped projection `tools.schemas()` —\n * stock DSH collects `assembly.tools` before dispatching the waterfall,\n * so a mount that lands during the wait would otherwise miss turn one.\n * - `tools/pre-execute` (awaited waterfall) closes the same window for\n * direct executions that bypass assembly.\n *\n * `agent/session-start` deliberately is NOT the trigger: DSH documents it as a\n * veto-less notification that cannot gate startup. The waterfalls above are\n * the officially awaited seams, and the exact pattern of registering onto a\n * foreign agent's ctx from a lifecycle event is what DSH's own schedule\n * plugin ships.\n *\n * A mount failure never takes the Agent down: the agent keeps running as a\n * plain DSH agent, the failure is reported loudly once, and only the Pi\n * packages are missing — the capability-gap discipline, not a rollback.\n */\nexport function installAgentScopedMounts(\n ctx: Context,\n preparedPackages: Promise<readonly PreparedPiHostPackage[]>,\n report: { warn(message: string): void },\n): void {\n const host = ctx as unknown as EngineHostContext\n const mounts = new WeakMap<object, AgentScopedMount>()\n\n const registry = (): AgentRegistryLike | undefined => {\n try {\n return host.get?.('agents') as AgentRegistryLike | undefined\n } catch {\n return undefined\n }\n }\n\n const isRootAgent = (agent: object): boolean => {\n // Subagents keep Pi's own sub-session semantics through the session\n // bridge; only runtime roots receive a Pi runtime (the same distinction\n // DSH's schedule plugin draws via agents.roots()).\n const agents = registry()\n const roots = agents?.roots\n if (typeof roots !== 'function') return true\n try {\n return (roots.call(agents) as unknown[]).includes(agent)\n } catch {\n return true\n }\n }\n\n const ensureMount = (agent: AgentLike): AgentScopedMount => {\n let mount = mounts.get(agent)\n if (mount === undefined) {\n const started: AgentScopedMount = { ready: Promise.resolve() }\n started.ready = preparedPackages.then(async prepared => {\n if (prepared.length === 0) return\n try {\n await applyPreparedPiHost(agent.ctx, prepared, agent as unknown as Record<string, unknown>)\n } catch (error) {\n // Loud, once per agent; the gates resolve so the plain DSH agent\n // keeps working. Faking success is forbidden — the message names\n // what is missing.\n started.failure = error instanceof Error ? error.message : String(error)\n report.warn(`[pi2dsh engine] Pi packages failed to mount for this agent; it continues without them: ${started.failure}`)\n }\n })\n mounts.set(agent, started)\n mount = started\n }\n return mount\n }\n\n // Eager start on publication. `agent/created` reaches host-level listeners\n // on every create/resume/config path, before the loop can open a turn.\n host.on('agent/created', ((payload: { agent: AgentLike }) => {\n if (isRootAgent(payload.agent)) ensureMount(payload.agent)\n }) as never)\n\n // Correctness boundary #1: no prompt assembly for a root agent proceeds\n // before its Pi runtime is mounted, and the tools snapshot taken before\n // this waterfall is reconciled against the official scoped projection.\n host.on('system-prompt/assemble', (async (\n assembly: { tools: Array<{ name: string }> },\n context: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = context.agent\n if (agent !== undefined && isRootAgent(agent)) {\n await ensureMount(agent).ready\n const schemas = host.tools?.schemas\n if (typeof schemas === 'function') {\n const present = new Set(assembly.tools.map(tool => tool.name))\n for (const schema of schemas.call(host.tools, agent)) {\n if (!present.has(schema.name)) assembly.tools.push(schema)\n }\n }\n }\n return next()\n }) as never)\n\n // Correctness boundary #2: tool execution for a root agent waits for the\n // same mount (serially awaited by the tool runtime before dispatch).\n host.on('tools/pre-execute', (async (\n exec: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n if (exec.agent !== undefined && isRootAgent(exec.agent)) await ensureMount(exec.agent).ready\n return next()\n }) as never)\n\n // Backfill: agents published before this plugin finished loading (a surface\n // that skips the official await-the-loader pattern DSH's headless runner\n // uses). Their next assembly still passes the gates above.\n void preparedPackages.then(() => {\n const agents = registry()\n const roots = agents?.roots\n if (typeof roots !== 'function') return\n for (const agent of roots.call(agents)) ensureMount(agent)\n })\n}\n\n/** Session-id prefix minted by the Pi subagent bridge (src/subagent-bridge.ts). */\nexport const BRIDGE_CHILD_SESSION_ID_PREFIX = 'pi2dsh-sub-'\n\n/**\n * Optional coverage for DSH-native subagents, enabled by the\n * `serveNativeSubagents` engine config.\n *\n * The Pi subagent bridge already serves the children IT mints: the creator's\n * per-spawn loader mount (a8b7a0a) runs at creation and again on a persisted\n * resume. This covers the OTHER lineage — children a DSH surface mints\n * directly (DSH-native delegation, headless subagents, a second agent in the\n * web UI) — which carry no Pi lineage and would otherwise run as plain DSH\n * agents with none of the profile's Pi extensions.\n *\n * One lineage check per created Agent (maintainer point 2): subagent origin\n * AND a session id that does not carry the bridge prefix. The bridge mints\n * `pi2dsh-sub-` ids at creation and a persisted resume keeps the original id,\n * so the skip holds on both bridge paths and a bridge child is never mounted\n * twice.\n *\n * The mount reuses the engine's own child-extension catalog (maintainer\n * point 3) — the same object the bridge's hook consumes — so a native child's\n * tool set is exactly Pi's default-discovered set (the catalog's no-loader\n * path), the mount lands on the child's OWN ctx and unwinds with the child,\n * and there is no second registration path to drift out of sync.\n *\n * Partition with the root-mount path: agents the registry reports as runtime\n * roots are installAgentScopedMounts' territory (it gates them the same way\n * this path does). Live delegation shows a DSH-native child of a top-level\n * session CAN be a runtime root — serving it here as well raced two mount\n * passes onto the same scope (each package survived via the prompt-section\n * guard, but the double attempt is exactly what this flag must not do). This\n * listener therefore serves exactly the remainder: subagent-origin,\n * non-bridge, non-root agents. The predicate is the root path's own, applied\n * at the same event; its fail-open (roots() unavailable ⇒ every agent is a\n * root) mirrors here as fail-closed (this listener serves nothing).\n *\n * The readiness promise is memoized on the child's SCOPE (agent.ctx), not the\n * agent object: a re-announced agent for the same session reuses the scope,\n * and the dedupe must key on what the mount actually lands in.\n *\n * First-turn gates mirror the root path's exactly: the child's first prompt\n * assembly and its direct tool executions await the mount, and the\n * pre-waterfall tools snapshot is reconciled against the official scoped\n * projection. Without the gate a mount that lands after the first turn's\n * snapshot leaves the child's first (and sometimes only) turn tool-less —\n * proven live at depth 2, where the child's grandchild saw zero extension\n * tools because its mount raced its first model call.\n *\n * A mount failure never takes the child down: the same capability-gap\n * discipline as root mounting — the child keeps running as a plain DSH agent\n * and the failure is reported loudly once.\n */\nexport function installNativeSubagentMounts(\n ctx: Context,\n preparedPackages: Promise<readonly PreparedPiHostPackage[]>,\n enabled: boolean,\n report: { warn(message: string): void },\n): void {\n if (!enabled) return\n const host = ctx as unknown as EngineHostContext\n\n // The root path's own predicate, applied at the same event it applies its\n // (see installAgentScopedMounts): a runtime root is served — and gated —\n // there. Failing closed keeps the partition exact when roots() is absent.\n const isRootAgent = (agent: object): boolean => {\n let agents: AgentRegistryLike | undefined\n try {\n agents = host.get?.('agents') as AgentRegistryLike | undefined\n } catch {\n return true\n }\n const roots = agents?.roots\n if (typeof roots !== 'function') return true\n try {\n return (roots.call(agents) as unknown[]).includes(agent)\n } catch {\n return true\n }\n }\n\n // child scope (agent.ctx) -> its mount's readiness. Reading the catalog\n // after preparation (never before) covers children published while the\n // engine was still preparing; no catalog = plain child, exactly the bridge\n // hook's no-catalog behavior.\n const mounts = new WeakMap<object, Promise<void>>()\n\n const ensureMount = (agent: AgentLike): Promise<void> => {\n const scope = agent.ctx\n let ready = mounts.get(scope)\n if (ready === undefined) {\n ready = preparedPackages.then(async () => {\n const catalog = getSharedChildExtensionCatalog(ctx)\n if (catalog === undefined) return\n // Native children have no creator loader: the full discovered set is\n // Pi's default discovery (the no-loader path of\n // resolveChildExtensionPackages).\n const names = [...new Set(catalog.packageByEntryPath.values())]\n if (names.length === 0) return\n try {\n const failures = await catalog.mount(agent as unknown as Record<string, unknown>, names)\n for (const failure of failures) {\n // Same message shape the bridge's own mount path uses.\n report.warn(`[pi2dsh] child extension ${failure.name} did not mount: ${failure.error}`)\n }\n } catch (error) {\n report.warn(`[pi2dsh] child extension mount failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n })\n mounts.set(scope, ready)\n }\n return ready\n }\n\n const handle = (agent: AgentLike): void => {\n // The single lineage check: DSH-native subagents only. Pi-origin\n // (bridge) children are already served by the creator's per-spawn loader\n // mount; the `pi2dsh-sub-` prefix identifies them on creation AND on a\n // persisted resume, where the original session id survives.\n if (!runtimeInternals.isSubagentOrigin(agent as unknown as Record<string, unknown>)) return\n const session = (agent as { session?: { id?: unknown } }).session ?? agent\n if (String((session as { id?: unknown }).id ?? '').startsWith(BRIDGE_CHILD_SESSION_ID_PREFIX)) return\n // Runtime roots are the root-mount path's territory; serving them here\n // would race a second mount onto the same scope.\n if (isRootAgent(agent)) return\n void ensureMount(agent)\n }\n\n host.on('agent/created', ((payload: { agent: AgentLike }) => {\n if (payload.agent !== undefined) handle(payload.agent)\n }) as never)\n\n // Correctness boundary #1 (mirror of the root path's): no prompt assembly\n // for a served child proceeds before its mount lands, and the pre-waterfall\n // tools snapshot is reconciled against the official scoped projection.\n host.on('system-prompt/assemble', (async (\n assembly: { tools: Array<{ name: string }> },\n context: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = context.agent\n const ready = agent === undefined ? undefined : mounts.get(agent.ctx)\n if (ready !== undefined) {\n await ready\n const schemas = host.tools?.schemas\n if (typeof schemas === 'function') {\n const present = new Set(assembly.tools.map(tool => tool.name))\n for (const schema of schemas.call(host.tools, agent)) {\n if (!present.has(schema.name)) assembly.tools.push(schema)\n }\n }\n }\n return next()\n }) as never)\n\n // Correctness boundary #2 (mirror of the root path's): direct tool\n // executions for a served child wait for the same mount.\n host.on('tools/pre-execute', (async (\n exec: { agent?: AgentLike },\n next: () => Promise<unknown>,\n ) => {\n const agent = exec.agent\n const ready = agent === undefined ? undefined : mounts.get(agent.ctx)\n if (ready !== undefined) await ready\n return next()\n }) as never)\n}\n\n/** Cordis plugin surface: `dsh plugin add pi2dsh` mounts this. */\nexport const name = 'pi2dsh'\nexport const inject = ['tools', 'systemPrompt', 'commands', 'skills']\n\nexport async function apply(ctx: Context, config: EngineConfig = {}): Promise<void> {\n // The redirected Pi agent directory must be visible to PLUGIN code, not\n // just to the bridge's own vendored components. Packages that import\n // `getAgentDir` from the aliased pi-coding-agent are redirected already,\n // but real packages also read `process.env.PI_CODING_AGENT_DIR` (or fall\n // back to ~/.pi/agent) at module load — pi-hermes-memory's paths.ts does\n // exactly that, and without this line its store landed in the REAL\n // ~/.pi/agent, colliding with any actual Pi installation. Publishing the\n // same path the shim computes keeps both classes on one directory; a\n // user-set value is honored (the shim reads the env first, so the two can\n // never disagree). Set before any package module is imported.\n if (process.env.PI_CODING_AGENT_DIR === undefined || process.env.PI_CODING_AGENT_DIR === '') {\n process.env.PI_CODING_AGENT_DIR = getAgentDir()\n }\n\n // Same emission as the runtime's logger helper: the cordis logger AND the\n // console — profile logger levels must never hide what the engine mounted.\n const log = (ctx as unknown as { logger?: { info?(m: string): void, warn?(m: string): void } }).logger\n const warn = (message: string): void => { log?.warn?.(message); console.warn(message) }\n const info = (message: string): void => { log?.info?.(message); console.log(message) }\n\n // The loader resolves plugins against the profile's baseUrl; that IS the\n // profile root. The ancestor walk from the installed engine is the\n // fallback for compositions without a loader (tests, hand-built hosts).\n const baseUrl = (ctx as unknown as { baseUrl?: string }).baseUrl\n const profileRoot = (baseUrl !== undefined ? findProfileRoot(fileURLToPath(new URL('.', baseUrl))) : undefined)\n ?? findProfileRoot(dirname(fileURLToPath(import.meta.url)))\n if (profileRoot === undefined) {\n throw new Error('pi2dsh engine: no DSH profile root (cordis.yml + package.json) above the installed engine — is pi2dsh installed via `dsh plugin add pi2dsh`?')\n }\n\n // The single mount path, before any await: gates and lifecycle listeners\n // must exist the moment a surface can publish its first Agent. Package\n // preparation resolves behind this promise; the gates hold each agent's\n // first assembly until its own mount lands.\n let resolvePrepared!: (prepared: readonly PreparedPiHostPackage[]) => void\n const preparedPackages = new Promise<readonly PreparedPiHostPackage[]>(resolve => {\n resolvePrepared = resolve\n })\n installAgentScopedMounts(ctx, preparedPackages, { warn })\n installNativeSubagentMounts(ctx, preparedPackages, config.serveNativeSubagents === true, { warn })\n\n registerVisionCompanions(ctx, config.visionCompanions)\n\n try {\n // The host half, mounted exactly once regardless of packages or agents:\n // Pi's built-in provider directory, `/login`, and credential recovery.\n // Without it a fresh engine cannot run `/login openai-codex`: DSH treats\n // the unknown slash line as a model prompt and fails on the unrelated\n // default provider credential. Community packages join the same\n // SharedHostState (keyed on ctx.root), so host-level resources stay\n // single-instance no matter which agent scope mounts them.\n await applyPreparedPiHost(ctx, [{\n name: 'pi2dsh-builtins',\n rootUrl: new URL('.', import.meta.url),\n manifest: {\n schemaVersion: 1,\n package: { name: 'pi2dsh-builtins', version: '0.0.0', source: 'engine' },\n extensions: [],\n skillDirs: [],\n prompts: [],\n },\n }])\n\n const packages: Array<{ name: string, anchor?: string }> = Array.isArray(config.packages) && config.packages.length > 0\n ? config.packages.map(name => ({ name }))\n : await discoverProfilePiPackages(profileRoot, {\n ...(Array.isArray(config.exclude) ? { exclude: config.exclude } : {}),\n warn,\n })\n if (packages.length === 0) {\n info('[pi2dsh engine] no Pi packages installed in this profile yet — add one with: dsh plugin --profile <p> add <pi-package>')\n resolvePrepared([])\n return\n }\n info(`[pi2dsh engine] preparing ${packages.length} Pi package(s): ${packages.map(pkg => pkg.name).join(', ')}`)\n const prepared = await preparePiHost(\n {\n packages: packages.map(pkg =>\n pkg.anchor === undefined ? { name: pkg.name } : { name: pkg.name, anchor: pkg.anchor }),\n },\n join(profileRoot, 'package.json'),\n )\n // Child-extension catalog: what real Pi's createAgentSession \"default-\n // discovered extensions\" means on this host. Entries are each package's\n // DECLARED pi extension files (absolute, inside the installed dir), so a\n // creator's own filter code (pi-subagents' extensions/exclude/ext:\n // machinery) canonicalizes them exactly as it does on Pi. Mounting lands\n // on the child agent's OWN ctx — contributions unwind with the agent,\n // which is what makes per-child instances leak-free by construction.\n const entryCatalog = new Map<string, string>()\n for (const pkg of prepared) {\n const rootDir = fileURLToPath(pkg.rootUrl)\n // Resolved keys, because the consumer looks entries up by resolved path.\n for (const rel of pkg.manifest.extensions) entryCatalog.set(resolve(rootDir, rel), pkg.name)\n }\n providePiExtensionDiscovery([...entryCatalog.keys()].map(path => ({ path })))\n registerChildExtensionCatalog(ctx, {\n packageByEntryPath: entryCatalog,\n mount: async (childAgent, packageNames) => {\n const wanted = new Set(packageNames)\n const subset = prepared.filter(pkg => wanted.has(pkg.name))\n const scope = (childAgent as { ctx?: Context }).ctx\n if (scope === undefined) {\n return subset.map(pkg => ({ name: pkg.name, error: 'the child agent exposes no ctx scope to mount into' }))\n }\n return applyPreparedPiHost(scope, subset, childAgent)\n },\n })\n\n // Host anchors, before the per-Agent gates open: every package's\n // HOST-level contributions (provider routes, OAuth accounts, /login,\n // credential recovery, companions, skills) exist from engine apply — a\n // surface with zero live Agents (web at boot) still advertises them, the\n // first Agent's model resolution finds its routes, and routes survive\n // Agent churn. Anchors serve no Agent; sessions belong to the per-Agent\n // instances the gates mount.\n // The engine-level browserPresentation flag rides into every package\n // mount's config: the /pi2dsh route (and the web `mode: 'tui'` claim)\n // exists only when a product layer configured a renderer. Stamped here\n // rather than defaulted in the runtime so per-Agent remounts and the\n // host anchor agree on one answer.\n const presented = config.browserPresentation === true\n ? prepared.map(pkg => ({ ...pkg, config: { ...(pkg.config ?? {}), browserPresentation: true } }))\n : prepared\n await applyPreparedPiHost(ctx, presented, undefined, { hostAnchor: true })\n resolvePrepared(presented)\n } catch (error) {\n // The gates must never hang on a failed preparation; agents keep running\n // as plain DSH agents while the engine failure propagates loudly.\n resolvePrepared([])\n throw error\n }\n}\n","// Engine surface: `dsh plugin add pi2dsh` resolves this entry as a cordis\n// plugin (named exports, no default — a default export would make the\n// loader discard the function-plugin namespace).\nexport { apply, inject, name, discoverProfilePiPackages, findProfileRoot, installAgentScopedMounts, type EngineConfig } from './engine.js'\n\n// The CLI-only analysis surface loads lazily: its static-analysis dependency\n// (the 23 MB typescript compiler, an optional peer) must never be pulled\n// into a profile that installs the ENGINE. The dynamic import below keeps\n// the analyzer in its own chunk, off the engine's load path.\nimport type { CompatibilityReport, ResolvedPiPackage } from './types.js'\n\n/**\n * Static compatibility analysis of one resolved Pi package (CLI `inspect`).\n * @param pkg - the resolved package.\n * @returns the compatibility report.\n */\nexport async function analyzePackage(pkg: ResolvedPiPackage): Promise<CompatibilityReport> {\n const { analyzePackage: run } = await import('./analyzer.js')\n return run(pkg)\n}\n\nexport {\n API_RULES,\n CONTEXT_RULES,\n EVENT_RULES,\n HOST_IMPORT_RULES,\n PI_AI_PACKAGES,\n PI_CODING_AGENT_PACKAGES,\n PI_TUI_PACKAGES,\n UI_CONTEXT_RULES,\n ruleForApi,\n ruleForContextProperty,\n ruleForEvent,\n ruleForHostImport,\n ruleForUiContextProperty,\n} from './compatibility.js'\nexport { applyPiHost, applyPreparedPiHost, manifestForInstalled, preparePiHost } from './host.js'\nexport { collectPiMcpServers, convertPiMcpConfig, renderMcpPatch } from './mcp-config.js'\nexport { resolvePiPackage } from './source.js'\nexport type * from './types.js'\n"],"mappings":";;;;;;;;;;;;;;AAgEA,SAAgB,gBAAgB,OAAmC;CACjE,IAAI,MAAM;CACV,SAAS;EACP,IAAI,WAAW,KAAK,KAAK,YAAY,CAAC,KAAK,WAAW,KAAK,KAAK,cAAc,CAAC,GAAG,OAAO;EACzF,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAgBA,eAAe,oBAAoB,aAA+C;CAChF,OAAO,KAAK,MAAM,MAAM,SAAS,KAAK,aAAa,cAAc,GAAG,MAAM,CAAC;AAC7E;AAEA,SAAS,qBAAqB,aAAqB,MAAkC;CAGnF,MAAM,MAAM,KAAK,aAAa,gBAAgB,IAAI;CAClD,OAAO,WAAW,KAAK,KAAK,cAAc,CAAC,IAAI,MAAM,KAAA;AACvD;;;;;;;AAQA,eAAsB,0BACpB,aACA,UAAoE,CAAC,GACvC;CAC9B,MAAM,OAAO,QAAQ,eAAe,CAAC;CACrC,MAAM,WAAW,IAAI,IAAI,QAAQ,WAAW,CAAC,CAAC;CAC9C,MAAM,WAAW,MAAM,oBAAoB,WAAW;CACtD,MAAM,aAAkC,CAAC;CACzC,KAAK,MAAM,QAAQ,OAAO,KAAK,SAAS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AE,CAAC;EAC5E,8BAA8B,KAAK;GACjC,oBAAoB;GACpB,OAAO,OAAO,YAAY,iBAAiB;IACzC,MAAM,SAAS,IAAI,IAAI,YAAY;IACnC,MAAM,SAAS,SAAS,QAAO,QAAO,OAAO,IAAI,IAAI,IAAI,CAAC;IAC1D,MAAM,QAAS,WAAiC;IAChD,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,KAAI,SAAQ;KAAE,MAAM,IAAI;KAAM,OAAO;IAAqD,EAAE;IAE5G,OAAO,oBAAoB,OAAO,QAAQ,UAAU;GACtD;EACF,CAAC;EAcD,MAAM,YAAY,OAAO,wBAAwB,OAC7C,SAAS,KAAI,SAAQ;GAAE,GAAG;GAAK,QAAQ;IAAE,GAAI,IAAI,UAAU,CAAC;IAAI,qBAAqB;GAAK;EAAE,EAAE,IAC9F;EACJ,MAAM,oBAAoB,KAAK,WAAW,KAAA,GAAW,EAAE,YAAY,KAAK,CAAC;EACzE,gBAAgB,SAAS;CAC3B,SAAS,OAAO;EAGd,gBAAgB,CAAC,CAAC;EAClB,MAAM;CACR;AACF;;;;;;;;AChnBA,eAAsB,eAAe,KAAsD;CACzF,MAAM,EAAE,gBAAgB,QAAQ,MAAM,OAAO;CAC7C,OAAO,IAAI,GAAG;AAChB"}
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { n as __esmMin } from "./rolldown-runtime-CTfmNlz1.mjs";
3
- import { i as File, n as FormData, r as init_esm_min, t as init_from } from "./src-85HOaW5W.mjs";
3
+ import { i as File, n as FormData, r as init_esm_min, t as init_from } from "./src-ChZlNrRV.mjs";
4
4
  //#region node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js
5
5
  function _fileName(headerValue) {
6
6
  const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
@@ -298,4 +298,4 @@ __esmMin((() => {
298
298
  }))();
299
299
  export { toFormData };
300
300
 
301
- //# sourceMappingURL=multipart-parser-CBAi6PxA.mjs.map
301
+ //# sourceMappingURL=multipart-parser-BOEZ-KGK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"multipart-parser-CBAi6PxA.mjs","names":[],"sources":["../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"],"sourcesContent":["import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/&#(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;AA+TA,SAAS,UAAU,aAAa;CAE/B,MAAM,IAAI,YAAY,MAAM,4DAA4D;CACxF,IAAI,CAAC,GACJ;CAGD,MAAM,QAAQ,EAAE,MAAM,EAAE,MAAM;CAC9B,IAAI,WAAW,MAAM,MAAM,MAAM,YAAY,IAAI,IAAI,CAAC;CACtD,WAAW,SAAS,QAAQ,QAAQ,IAAG;CACvC,WAAW,SAAS,QAAQ,gBAAgB,GAAG,SAAS;EACvD,OAAO,OAAO,aAAa,IAAI;CAChC,CAAC;CACD,OAAO;AACR;AAEA,eAAsB,WAAW,MAAM,IAAI;CAC1C,IAAI,CAAC,aAAa,KAAK,EAAE,GACxB,MAAM,IAAI,UAAU,iBAAiB;CAGtC,MAAM,IAAI,GAAG,MAAM,iCAAiC;CAEpD,IAAI,CAAC,GACJ,MAAM,IAAI,UAAU,sDAAsD;CAG3E,MAAM,SAAS,IAAI,gBAAgB,EAAE,MAAM,EAAE,EAAE;CAE/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,cAAc,CAAC;CACrB,MAAM,WAAW,IAAI,SAAS;CAE9B,MAAM,cAAa,SAAQ;EAC1B,cAAc,QAAQ,OAAO,MAAM,EAAC,QAAQ,KAAI,CAAC;CAClD;CAEA,MAAM,gBAAe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AAe,WAAW;OACpD,gBAAgB;OAChB,KAAK,YAAY;OAIjB;MACD;MAEA;KACD,KAAK,EAAE,KACN;KACD,SACC,MAAM,IAAI,MAAM,6BAA6B,OAAO;IACtD;GACD;GAEA,aAAa,eAAe;GAC5B,aAAa,eAAe;GAC5B,aAAa,YAAY;GAGzB,KAAK,QAAQ;GACb,KAAK,QAAQ;GACb,KAAK,QAAQ;EACd;EAEA,MAAM;GACL,IAAK,KAAK,UAAU,EAAE,sBAAsB,KAAK,UAAU,KACzD,KAAK,UAAU,EAAE,aAAa,KAAK,UAAU,KAAK,SAAS,QAC5D,KAAK,UAAU;QACT,IAAI,KAAK,UAAU,EAAE,KAC3B,MAAM,IAAI,MAAM,kDAAkD;EAEpE;CACD"}
1
+ {"version":3,"file":"multipart-parser-BOEZ-KGK.mjs","names":[],"sources":["../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"],"sourcesContent":["import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/&#(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;AA+TA,SAAS,UAAU,aAAa;CAE/B,MAAM,IAAI,YAAY,MAAM,4DAA4D;CACxF,IAAI,CAAC,GACJ;CAGD,MAAM,QAAQ,EAAE,MAAM,EAAE,MAAM;CAC9B,IAAI,WAAW,MAAM,MAAM,MAAM,YAAY,IAAI,IAAI,CAAC;CACtD,WAAW,SAAS,QAAQ,QAAQ,IAAG;CACvC,WAAW,SAAS,QAAQ,gBAAgB,GAAG,SAAS;EACvD,OAAO,OAAO,aAAa,IAAI;CAChC,CAAC;CACD,OAAO;AACR;AAEA,eAAsB,WAAW,MAAM,IAAI;CAC1C,IAAI,CAAC,aAAa,KAAK,EAAE,GACxB,MAAM,IAAI,UAAU,iBAAiB;CAGt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ACZ,SAAS,WAAW;SACpB,SAAS,aAAa;SACtB,QAAQ,EAAE;SACV;QACD;OACD,OAAO,IAAI,QAAQ,EAAE,eAAe;QACnC,IAAI,MAAM,QAAQ;SACjB,SAAS,WAAW;SACpB,QAAQ,EAAE;SACV,QAAQ;QACT,OACC,QAAQ;OAEV,OACC,QAAQ;MAEV;MAEA,IAAI,QAAQ,GAGX,WAAW,QAAQ,KAAK;WAClB,IAAI,gBAAgB,GAAG;OAG7B,MAAM,cAAc,IAAI,WAAW,WAAW,QAAQ,WAAW,YAAY,WAAW,UAAU;OAClG,SAAS,cAAc,GAAG,eAAe,WAAW;OACpD,gBAAgB;OAChB,KAAK,YAAY;OAIjB;MACD;MAEA;KACD,KAAK,EAAE,KACN;KACD,SACC,MAAM,IAAI,MAAM,6BAA6B,OAAO;IACtD;GACD;GAEA,aAAa,eAAe;GAC5B,aAAa,eAAe;GAC5B,aAAa,YAAY;GAGzB,KAAK,QAAQ;GACb,KAAK,QAAQ;GACb,KAAK,QAAQ;EACd;EAEA,MAAM;GACL,IAAK,KAAK,UAAU,EAAE,sBAAsB,KAAK,UAAU,KACzD,KAAK,UAAU,EAAE,aAAa,KAAK,UAAU,KAAK,SAAS,QAC5D,KAAK,UAAU;QACT,IAAI,KAAK,UAAU,EAAE,KAC3B,MAAM,IAAI,MAAM,kDAAkD;EAEpE;CACD"}
@@ -2,11 +2,11 @@
2
2
  /// <reference types="node" />
3
3
  import { n as AssistantMessage$1 } from "./pi-types-KazmR2O5.mjs";
4
4
  import { URL as URL$1, URLSearchParams as URLSearchParams$1 } from "node:url";
5
+ import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from "node:net";
5
6
  import { EventEmitter } from "node:events";
6
7
  import { Static as Static$1, TSchema, TSchema as TSchema$1, Type as Type$1 } from "typebox";
7
8
  import { Duplex, Readable, Writable } from "node:stream";
8
9
  import { Blob as Blob$1, File as File$1 } from "node:buffer";
9
- import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from "node:net";
10
10
  import { ConnectionOptions, TLSSocket } from "node:tls";
11
11
  import { SessionOptions } from "node:http2";
12
12
  //#region src/compat/vendor/pi-ai-overflow.d.ts
@@ -1979,11 +1979,11 @@ type DeferredCancelOptions = ProviderRequestOptions<Model$1<Api$1>>;
1979
1979
  */
1980
1980
  interface ProviderStreams {
1981
1981
  stream(model: Model$1<Api$1>, context: Context, options?: StreamOptions): AssistantMessageEventStream;
1982
- streamSimple(model: Model$1<Api$1>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream;
1982
+ streamSimple(model: Model$1<Api$1>, context: Context, options?: SimpleStreamOptions$1): AssistantMessageEventStream;
1983
1983
  fetchDeferred?(model: Model$1<Api$1>, handle: DeferredHandle, options?: DeferredFetchOptions): AssistantMessageEventStream;
1984
1984
  cancelDeferred?(model: Model$1<Api$1>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;
1985
1985
  }
1986
- interface SimpleStreamOptions extends StreamOptions {
1986
+ interface SimpleStreamOptions$1 extends StreamOptions {
1987
1987
  reasoning?: ThinkingLevel$1;
1988
1988
  /** Ask a capable provider to return a durable handle and continue the request asynchronously. */
1989
1989
  deferred?: boolean | {
@@ -2433,7 +2433,7 @@ interface Model$1<TApi extends Api$1> {
2433
2433
  }
2434
2434
  //#endregion
2435
2435
  //#region node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts
2436
- declare const streamSimple: StreamFunction<"openai-responses", SimpleStreamOptions>;
2436
+ declare const streamSimple$1: StreamFunction<"openai-responses", SimpleStreamOptions$1>;
2437
2437
  //#endregion
2438
2438
  //#region src/compat/vendor/pi-oauth-flows/openai-codex.d.ts
2439
2439
  declare const openaiCodexOAuth: {
@@ -2663,6 +2663,14 @@ declare function __runWithPiAiRuntime<T>(bridge: PiAiLlmBridge | undefined, runt
2663
2663
  declare function __getPiAiLlmBridge(): PiAiLlmBridge | undefined;
2664
2664
  declare function complete(model: UnknownRecord, context: UnknownRecord, options?: UnknownRecord): Promise<unknown>;
2665
2665
  declare function stream(model: UnknownRecord, context: UnknownRecord, options?: UnknownRecord): unknown;
2666
+ declare function streamSimple(model: UnknownRecord, context: UnknownRecord, options?: UnknownRecord): unknown;
2667
+ declare function completeSimple(model: UnknownRecord, context: UnknownRecord, options?: UnknownRecord): Promise<unknown>;
2668
+ interface SimpleStreamOptions extends Record<string, unknown> {
2669
+ reasoning?: ThinkingLevel;
2670
+ maxTokens?: number;
2671
+ temperature?: number;
2672
+ signal?: AbortSignal;
2673
+ }
2666
2674
  interface StringEnumOptions<T extends readonly string[]> {
2667
2675
  description?: string;
2668
2676
  default?: T[number];
@@ -2674,5 +2682,5 @@ declare function StringEnum<T extends readonly string[]>(values: T, options?: St
2674
2682
  default?: T[number];
2675
2683
  };
2676
2684
  //#endregion
2677
- export { githubCopilotOAuth as $, getSupportedThinkingLevels as A, piMessagesApi as B, getBuiltinModel as C, getModels as D, getModel as E, modelsAreEqual as F, azureOpenAIResponsesApi as G, mistralConversationsApi as H, registerApiProvider as I, openAICompletionsApi as J, openAICodexResponsesApi as K, registerProvider as L, loadGitHubCopilotOAuth as M, loadKimiCodingOAuth as N, getProvider as O, loadOpenAICodexOAuth as P, kimiCodingOAuth as Q, stream as R, getApiProviders as S, getBuiltinProviders as T, googleVertexApi as U, bedrockConverseStreamApi as V, googleGenerativeAIApi as W, pollOAuthDeviceCodeFlow as X, anthropicMessagesApi as Y, generatePKCE as Z, clampThinkingLevel as _, StringEnum as a, AssistantMessageEventStream$1 as at, envApiKeyAuth as b, ThinkingLevel as c, uuidv7 as ct, __createPiAiRuntimeRegistry as d, isRecoverableLength as dt, anthropicOAuth as et, __getPiAiLlmBridge as f, builtinProviders as g, __setPiAiLlmBridge as h, Static$1 as i, lazyStream as it, loadAnthropicOAuth as j, getProviders as k, ThinkingLevelMap as l, isRetryableAssistantError as lt, __runWithPiAiRuntime as m, Model as n, streamSimple as nt, StringEnumOptions as o, ModelsError as ot, __runWithPiAiLlmBridge as p, openAIResponsesApi as q, ModelThinkingLevel as r, lazyApi as rt, TSchema$1 as s, createProvider as st, Api as t, openaiCodexOAuth as tt, Type$1 as u, isContextOverflow as ut, complete as v, getBuiltinModels as w, getApiProvider as x, contentText as y, unregisterApiProviders as z };
2678
- //# sourceMappingURL=pi-ai-hGbYES_v.d.mts.map
2685
+ export { pollOAuthDeviceCodeFlow as $, getProvider as A, stream as B, getApiProvider as C, getBuiltinProviders as D, getBuiltinModels as E, loadKimiCodingOAuth as F, mistralConversationsApi as G, unregisterApiProviders as H, loadOpenAICodexOAuth as I, azureOpenAIResponsesApi as J, googleVertexApi as K, modelsAreEqual as L, getSupportedThinkingLevels as M, loadAnthropicOAuth as N, getModel as O, loadGitHubCopilotOAuth as P, anthropicMessagesApi as Q, registerApiProvider as R, envApiKeyAuth as S, getBuiltinModel as T, piMessagesApi as U, streamSimple as V, bedrockConverseStreamApi as W, openAIResponsesApi as X, openAICodexResponsesApi as Y, openAICompletionsApi as Z, builtinProviders as _, Static$1 as a, streamSimple$1 as at, completeSimple as b, TSchema$1 as c, AssistantMessageEventStream$1 as ct, Type$1 as d, uuidv7 as dt, generatePKCE as et, __createPiAiRuntimeRegistry as f, isRetryableAssistantError as ft, __setPiAiLlmBridge as g, __runWithPiAiRuntime as h, SimpleStreamOptions as i, openaiCodexOAuth as it, getProviders as j, getModels as k, ThinkingLevel as l, ModelsError as lt, __runWithPiAiLlmBridge as m, isRecoverableLength as mt, Model as n, githubCopilotOAuth as nt, StringEnum as o, lazyApi as ot, __getPiAiLlmBridge as p, isContextOverflow as pt, googleGenerativeAIApi as q, ModelThinkingLevel as r, anthropicOAuth as rt, StringEnumOptions as s, lazyStream as st, Api as t, kimiCodingOAuth as tt, ThinkingLevelMap as u, createProvider as ut, clampThinkingLevel as v, getApiProviders as w, contentText as x, complete as y, registerProvider as z };
2686
+ //# sourceMappingURL=pi-ai-BHgA3JWd.d.mts.map