pi2dsh 0.3.1 → 0.3.2

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 (101) hide show
  1. package/README.md +15 -10
  2. package/README.zh.md +15 -10
  3. package/dist/all-Rt4K68QA.mjs +28512 -0
  4. package/dist/all-Rt4K68QA.mjs.map +1 -0
  5. package/dist/anthropic-messages-Beym0_aC.mjs +6438 -0
  6. package/dist/anthropic-messages-Beym0_aC.mjs.map +1 -0
  7. package/dist/azure-openai-responses-cHqZTgLD.mjs +209 -0
  8. package/dist/azure-openai-responses-cHqZTgLD.mjs.map +1 -0
  9. package/dist/{build-DsGYAgiT.mjs → build-BG7p2Lbr.mjs} +2 -2
  10. package/dist/{build-DsGYAgiT.mjs.map → build-BG7p2Lbr.mjs.map} +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/compat/pi-ai.d.mts +16 -3
  13. package/dist/compat/pi-ai.d.mts.map +1 -1
  14. package/dist/compat/pi-ai.mjs +3 -3
  15. package/dist/compat/pi-coding-agent.d.mts +12 -1
  16. package/dist/compat/pi-coding-agent.d.mts.map +1 -1
  17. package/dist/compat/pi-coding-agent.mjs +2 -2
  18. package/dist/credentials-oauth.mjs +3 -3
  19. package/dist/deferred-tools-BD4g5QUx.mjs +32 -0
  20. package/dist/deferred-tools-BD4g5QUx.mjs.map +1 -0
  21. package/dist/diagnostics-CJye1UFh.mjs +99 -0
  22. package/dist/diagnostics-CJye1UFh.mjs.map +1 -0
  23. package/dist/dist-IQKOgQyt.mjs +10035 -0
  24. package/dist/dist-IQKOgQyt.mjs.map +1 -0
  25. package/dist/dist-QBBA-dL_.mjs +1246 -0
  26. package/dist/dist-QBBA-dL_.mjs.map +1 -0
  27. package/dist/error-body-DKA3lknR.mjs +104 -0
  28. package/dist/error-body-DKA3lknR.mjs.map +1 -0
  29. package/dist/github-copilot-headers-CZo2QHrt.mjs +25 -0
  30. package/dist/github-copilot-headers-CZo2QHrt.mjs.map +1 -0
  31. package/dist/google-generative-ai-B7OZs5lu.mjs +358 -0
  32. package/dist/google-generative-ai-B7OZs5lu.mjs.map +1 -0
  33. package/dist/google-shared-CRsAUItF.mjs +29042 -0
  34. package/dist/google-shared-CRsAUItF.mjs.map +1 -0
  35. package/dist/google-vertex-DmdaHQtB.mjs +402 -0
  36. package/dist/google-vertex-DmdaHQtB.mjs.map +1 -0
  37. package/dist/hash-Dbggamac.mjs +19 -0
  38. package/dist/hash-Dbggamac.mjs.map +1 -0
  39. package/dist/headers-CPzZhJQn.mjs +17 -0
  40. package/dist/headers-CPzZhJQn.mjs.map +1 -0
  41. package/dist/host.d.mts.map +1 -1
  42. package/dist/host.mjs +13 -3
  43. package/dist/host.mjs.map +1 -1
  44. package/dist/images-models-DJtHo9Rp.mjs +1068 -0
  45. package/dist/images-models-DJtHo9Rp.mjs.map +1 -0
  46. package/dist/index.d.mts.map +1 -1
  47. package/dist/index.mjs +1 -1
  48. package/dist/json-parse-CFyFZSLJ.mjs +384 -0
  49. package/dist/json-parse-CFyFZSLJ.mjs.map +1 -0
  50. package/dist/{mcp-config-gqg7GJEE.mjs → mcp-config-D2B3kv-Z.mjs} +34 -16
  51. package/dist/mcp-config-D2B3kv-Z.mjs.map +1 -0
  52. package/dist/mistral-conversations-HHZCcFv_.mjs +42007 -0
  53. package/dist/mistral-conversations-HHZCcFv_.mjs.map +1 -0
  54. package/dist/multipart-parser-CIa5BbwO.mjs +301 -0
  55. package/dist/multipart-parser-CIa5BbwO.mjs.map +1 -0
  56. package/dist/{oauth-bridge-BpPrppjR.mjs → oauth-bridge-C6fL1qSv.mjs} +20 -4
  57. package/dist/oauth-bridge-C6fL1qSv.mjs.map +1 -0
  58. package/dist/openai-DkzRh5_G.mjs +6732 -0
  59. package/dist/openai-DkzRh5_G.mjs.map +1 -0
  60. package/dist/openai-codex-responses-vmovNu-q.mjs +1169 -0
  61. package/dist/openai-codex-responses-vmovNu-q.mjs.map +1 -0
  62. package/dist/openai-completions-fXHhRolF.mjs +947 -0
  63. package/dist/openai-completions-fXHhRolF.mjs.map +1 -0
  64. package/dist/openai-prompt-cache-BDWtZRKh.mjs +11 -0
  65. package/dist/openai-prompt-cache-BDWtZRKh.mjs.map +1 -0
  66. package/dist/openai-responses-DKdCYf3h.mjs +247 -0
  67. package/dist/openai-responses-DKdCYf3h.mjs.map +1 -0
  68. package/dist/openai-responses-shared-D0Jq7yVP.mjs +572 -0
  69. package/dist/openai-responses-shared-D0Jq7yVP.mjs.map +1 -0
  70. package/dist/openrouter-images-fG3Aj6M4.mjs +127 -0
  71. package/dist/openrouter-images-fG3Aj6M4.mjs.map +1 -0
  72. package/dist/otel-BQSQRBLF.mjs +24935 -0
  73. package/dist/otel-BQSQRBLF.mjs.map +1 -0
  74. package/dist/{pi-ai-CWFlgigJ.mjs → pi-ai-DhYGgq4Y.mjs} +49 -12
  75. package/dist/{pi-ai-CWFlgigJ.mjs.map → pi-ai-DhYGgq4Y.mjs.map} +1 -1
  76. package/dist/{pi-coding-agent-Z1hTs61i.mjs → pi-coding-agent-fPHwKP4d.mjs} +27 -3
  77. package/dist/{pi-coding-agent-Z1hTs61i.mjs.map → pi-coding-agent-fPHwKP4d.mjs.map} +1 -1
  78. package/dist/pi-messages-CV-Ts8An.mjs +306 -0
  79. package/dist/pi-messages-CV-Ts8An.mjs.map +1 -0
  80. package/dist/provider-env-C72pF4vP.mjs +40 -0
  81. package/dist/provider-env-C72pF4vP.mjs.map +1 -0
  82. package/dist/provider-retry-Cw6YJ4cr.mjs +80 -0
  83. package/dist/provider-retry-Cw6YJ4cr.mjs.map +1 -0
  84. package/dist/rolldown-runtime-CTfmNlz1.mjs +44 -0
  85. package/dist/{runtime-6DefpI6h.mjs → runtime-B9R7bDWT.mjs} +874 -37
  86. package/dist/runtime-B9R7bDWT.mjs.map +1 -0
  87. package/dist/runtime.d.mts.map +1 -1
  88. package/dist/runtime.mjs +1 -1
  89. package/dist/sanitize-unicode-wLA11KvZ.mjs +29 -0
  90. package/dist/sanitize-unicode-wLA11KvZ.mjs.map +1 -0
  91. package/dist/src-C3WBfOks.mjs +5031 -0
  92. package/dist/src-C3WBfOks.mjs.map +1 -0
  93. package/dist/transform-messages-DGq9mvhA.mjs +379 -0
  94. package/dist/transform-messages-DGq9mvhA.mjs.map +1 -0
  95. package/dist/uuid-DtFT7tOE.mjs +65 -0
  96. package/dist/uuid-DtFT7tOE.mjs.map +1 -0
  97. package/package.json +1 -1
  98. package/dist/mcp-config-gqg7GJEE.mjs.map +0 -1
  99. package/dist/oauth-bridge-BpPrppjR.mjs.map +0 -1
  100. package/dist/rolldown-runtime-D-uZhY3_.mjs +0 -16
  101. package/dist/runtime-6DefpI6h.mjs.map +0 -1
@@ -0,0 +1,402 @@
1
+
2
+ import { a as AssistantMessageEventStream } from "./diagnostics-CJye1UFh.mjs";
3
+ import { a as calculateCost, o as clampThinkingLevel } from "./images-models-DJtHo9Rp.mjs";
4
+ import { n as providerHeadersToRecord } from "./headers-CPzZhJQn.mjs";
5
+ import { t as getProviderEnvValue } from "./provider-env-C72pF4vP.mjs";
6
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-wLA11KvZ.mjs";
7
+ import { i as buildBaseOptions } from "./transform-messages-DGq9mvhA.mjs";
8
+ import { n as normalizeProviderError, t as formatProviderError } from "./error-body-DKA3lknR.mjs";
9
+ 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-CRsAUItF.mjs";
10
+ //#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
11
+ const API_VERSION = "v1";
12
+ const GCP_VERTEX_CREDENTIALS_MARKER = "gcp-vertex-credentials";
13
+ const THINKING_LEVEL_MAP = {
14
+ THINKING_LEVEL_UNSPECIFIED: ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,
15
+ MINIMAL: ThinkingLevel.MINIMAL,
16
+ LOW: ThinkingLevel.LOW,
17
+ MEDIUM: ThinkingLevel.MEDIUM,
18
+ HIGH: ThinkingLevel.HIGH
19
+ };
20
+ let toolCallCounter = 0;
21
+ const stream = (model, context, options) => {
22
+ const stream = new AssistantMessageEventStream();
23
+ (async () => {
24
+ const output = {
25
+ role: "assistant",
26
+ content: [],
27
+ api: "google-vertex",
28
+ provider: model.provider,
29
+ model: model.id,
30
+ usage: {
31
+ input: 0,
32
+ output: 0,
33
+ cacheRead: 0,
34
+ cacheWrite: 0,
35
+ totalTokens: 0,
36
+ cost: {
37
+ input: 0,
38
+ output: 0,
39
+ cacheRead: 0,
40
+ cacheWrite: 0,
41
+ total: 0
42
+ }
43
+ },
44
+ stopReason: "pending",
45
+ timestamp: Date.now()
46
+ };
47
+ try {
48
+ if (options?.fetch && options.fetch !== globalThis.fetch) throw new Error("Custom fetch is not supported by the Google Vertex adapter");
49
+ const apiKey = resolveApiKey(options);
50
+ const client = apiKey ? createClientWithApiKey(model, apiKey, options?.headers) : createClient(model, resolveProject(options), resolveLocation(options), options?.headers, options?.env);
51
+ let params = buildParams(model, context, options);
52
+ const nextParams = await options?.onPayload?.(params, model);
53
+ if (nextParams !== void 0) params = nextParams;
54
+ const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);
55
+ stream.push({
56
+ type: "start",
57
+ partial: output
58
+ });
59
+ let currentBlock = null;
60
+ const blocks = output.content;
61
+ const blockIndex = () => blocks.length - 1;
62
+ for await (const chunk of googleStream) {
63
+ output.responseId ||= chunk.responseId;
64
+ const candidate = chunk.candidates?.[0];
65
+ if (candidate?.content?.parts) for (const part of candidate.content.parts) {
66
+ if (part.text !== void 0) {
67
+ const isThinking = isThinkingPart(part);
68
+ if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") {
69
+ if (currentBlock) {
70
+ if (currentBlock.type === "text") stream.push({
71
+ type: "text_end",
72
+ contentIndex: blocks.length - 1,
73
+ content: currentBlock.text,
74
+ partial: output
75
+ });
76
+ else stream.push({
77
+ type: "thinking_end",
78
+ contentIndex: blockIndex(),
79
+ content: currentBlock.thinking,
80
+ partial: output
81
+ });
82
+ }
83
+ if (isThinking) {
84
+ currentBlock = {
85
+ type: "thinking",
86
+ thinking: "",
87
+ thinkingSignature: void 0
88
+ };
89
+ output.content.push(currentBlock);
90
+ stream.push({
91
+ type: "thinking_start",
92
+ contentIndex: blockIndex(),
93
+ partial: output
94
+ });
95
+ } else {
96
+ currentBlock = {
97
+ type: "text",
98
+ text: ""
99
+ };
100
+ output.content.push(currentBlock);
101
+ stream.push({
102
+ type: "text_start",
103
+ contentIndex: blockIndex(),
104
+ partial: output
105
+ });
106
+ }
107
+ }
108
+ if (currentBlock.type === "thinking") {
109
+ currentBlock.thinking += part.text;
110
+ currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
111
+ stream.push({
112
+ type: "thinking_delta",
113
+ contentIndex: blockIndex(),
114
+ delta: part.text,
115
+ partial: output
116
+ });
117
+ } else {
118
+ currentBlock.text += part.text;
119
+ currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
120
+ stream.push({
121
+ type: "text_delta",
122
+ contentIndex: blockIndex(),
123
+ delta: part.text,
124
+ partial: output
125
+ });
126
+ }
127
+ }
128
+ if (part.functionCall) {
129
+ if (currentBlock) {
130
+ if (currentBlock.type === "text") stream.push({
131
+ type: "text_end",
132
+ contentIndex: blockIndex(),
133
+ content: currentBlock.text,
134
+ partial: output
135
+ });
136
+ else stream.push({
137
+ type: "thinking_end",
138
+ contentIndex: blockIndex(),
139
+ content: currentBlock.thinking,
140
+ partial: output
141
+ });
142
+ currentBlock = null;
143
+ }
144
+ const providedId = part.functionCall.id;
145
+ const toolCall = {
146
+ type: "toolCall",
147
+ id: !providedId || output.content.some((b) => b.type === "toolCall" && b.id === providedId) ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}` : providedId,
148
+ name: part.functionCall.name || "",
149
+ arguments: part.functionCall.args ?? {},
150
+ ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature }
151
+ };
152
+ output.content.push(toolCall);
153
+ stream.push({
154
+ type: "toolcall_start",
155
+ contentIndex: blockIndex(),
156
+ partial: output
157
+ });
158
+ stream.push({
159
+ type: "toolcall_delta",
160
+ contentIndex: blockIndex(),
161
+ delta: JSON.stringify(toolCall.arguments),
162
+ partial: output
163
+ });
164
+ stream.push({
165
+ type: "toolcall_end",
166
+ contentIndex: blockIndex(),
167
+ toolCall,
168
+ partial: output
169
+ });
170
+ }
171
+ }
172
+ if (candidate?.finishReason) {
173
+ output.rawStopReason = candidate.finishReason;
174
+ output.stopReason = mapStopReason(candidate.finishReason);
175
+ if (output.content.some((b) => b.type === "toolCall")) output.stopReason = "toolUse";
176
+ }
177
+ if (chunk.usageMetadata) {
178
+ output.usage = {
179
+ input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),
180
+ output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),
181
+ cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
182
+ cacheWrite: 0,
183
+ reasoning: chunk.usageMetadata.thoughtsTokenCount || 0,
184
+ totalTokens: chunk.usageMetadata.totalTokenCount || 0,
185
+ cost: {
186
+ input: 0,
187
+ output: 0,
188
+ cacheRead: 0,
189
+ cacheWrite: 0,
190
+ total: 0
191
+ }
192
+ };
193
+ calculateCost(model, output.usage);
194
+ }
195
+ }
196
+ if (currentBlock) {
197
+ if (currentBlock.type === "text") stream.push({
198
+ type: "text_end",
199
+ contentIndex: blockIndex(),
200
+ content: currentBlock.text,
201
+ partial: output
202
+ });
203
+ else stream.push({
204
+ type: "thinking_end",
205
+ contentIndex: blockIndex(),
206
+ content: currentBlock.thinking,
207
+ partial: output
208
+ });
209
+ }
210
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
211
+ if (output.stopReason === "pending") throw new Error("Google Vertex stream ended without a finish reason");
212
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
213
+ const errorMessage = output.rawStopReason ? `Provider stopped with: ${output.rawStopReason}` : "An unknown error occurred";
214
+ throw new Error(errorMessage);
215
+ }
216
+ stream.push({
217
+ type: "done",
218
+ reason: output.stopReason,
219
+ message: output
220
+ });
221
+ stream.end();
222
+ } catch (error) {
223
+ for (const block of output.content) if ("index" in block) delete block.index;
224
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
225
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
226
+ stream.push({
227
+ type: "error",
228
+ reason: output.stopReason,
229
+ error: output
230
+ });
231
+ stream.end();
232
+ }
233
+ })();
234
+ return stream;
235
+ };
236
+ const streamSimple = (model, context, options) => {
237
+ const base = buildBaseOptions(model, context, options, void 0);
238
+ if (!options?.reasoning) return stream(model, context, {
239
+ ...base,
240
+ thinking: { enabled: false }
241
+ });
242
+ const clampedReasoning = clampThinkingLevel(model, options.reasoning);
243
+ const effort = clampedReasoning === "off" ? "high" : clampedReasoning;
244
+ const geminiModel = model;
245
+ if (isGemini3ProModel(geminiModel) || isGemini3FlashModel(geminiModel)) return stream(model, context, {
246
+ ...base,
247
+ thinking: {
248
+ enabled: true,
249
+ level: getGemini3ThinkingLevel(effort, geminiModel)
250
+ }
251
+ });
252
+ return stream(model, context, {
253
+ ...base,
254
+ thinking: {
255
+ enabled: true,
256
+ budgetTokens: getGoogleBudget(geminiModel, effort, options.thinkingBudgets)
257
+ }
258
+ });
259
+ };
260
+ function createClient(model, project, location, optionsHeaders, env) {
261
+ const googleAuthOptions = buildGoogleAuthOptions(env);
262
+ return new GoogleGenAI({
263
+ vertexai: true,
264
+ project,
265
+ location,
266
+ apiVersion: API_VERSION,
267
+ ...googleAuthOptions ? { googleAuthOptions } : {},
268
+ httpOptions: buildHttpOptions(model, optionsHeaders)
269
+ });
270
+ }
271
+ function createClientWithApiKey(model, apiKey, optionsHeaders) {
272
+ return new GoogleGenAI({
273
+ vertexai: true,
274
+ apiKey,
275
+ apiVersion: API_VERSION,
276
+ httpOptions: buildHttpOptions(model, optionsHeaders)
277
+ });
278
+ }
279
+ function buildHttpOptions(model, optionsHeaders) {
280
+ const httpOptions = {};
281
+ const baseUrl = resolveCustomBaseUrl(model.baseUrl);
282
+ if (baseUrl) {
283
+ httpOptions.baseUrl = baseUrl;
284
+ httpOptions.baseUrlResourceScope = ResourceScope.COLLECTION;
285
+ if (baseUrlIncludesApiVersion(baseUrl)) httpOptions.apiVersion = "";
286
+ }
287
+ const headers = providerHeadersToRecord({
288
+ ...model.headers,
289
+ ...optionsHeaders
290
+ });
291
+ if (headers) httpOptions.headers = headers;
292
+ return Object.keys(httpOptions).length > 0 ? httpOptions : void 0;
293
+ }
294
+ function resolveCustomBaseUrl(baseUrl) {
295
+ const trimmed = baseUrl.trim();
296
+ if (!trimmed || trimmed.includes("{location}")) return;
297
+ return trimmed;
298
+ }
299
+ function baseUrlIncludesApiVersion(baseUrl) {
300
+ try {
301
+ return new URL(baseUrl).pathname.split("/").some((part) => /^v\d+(?:beta\d*)?$/.test(part));
302
+ } catch {
303
+ return /(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl);
304
+ }
305
+ }
306
+ function buildGoogleAuthOptions(env) {
307
+ const keyFilename = getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS", env);
308
+ return keyFilename ? { keyFilename } : void 0;
309
+ }
310
+ function resolveApiKey(options) {
311
+ const apiKey = options?.apiKey?.trim();
312
+ if (!apiKey || apiKey === GCP_VERTEX_CREDENTIALS_MARKER || isPlaceholderApiKey(apiKey)) return;
313
+ return apiKey;
314
+ }
315
+ function isPlaceholderApiKey(apiKey) {
316
+ return /^<[^>]+>$/.test(apiKey);
317
+ }
318
+ function resolveProject(options) {
319
+ const project = options?.project || getProviderEnvValue("GOOGLE_CLOUD_PROJECT", options?.env) || getProviderEnvValue("GCLOUD_PROJECT", options?.env);
320
+ if (!project) throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");
321
+ return project;
322
+ }
323
+ function resolveLocation(options) {
324
+ const location = options?.location || getProviderEnvValue("GOOGLE_CLOUD_LOCATION", options?.env);
325
+ if (!location) throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");
326
+ return location;
327
+ }
328
+ function buildParams(model, context, options = {}) {
329
+ const contents = convertMessages(model, context);
330
+ const generationConfig = {};
331
+ if (options.temperature !== void 0) generationConfig.temperature = options.temperature;
332
+ if (options.maxTokens !== void 0) generationConfig.maxOutputTokens = options.maxTokens;
333
+ const functionCallingMode = context.tools?.length ? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id)) : void 0;
334
+ const config = {
335
+ ...Object.keys(generationConfig).length > 0 && generationConfig,
336
+ ...context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) },
337
+ ...context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) },
338
+ ...functionCallingMode !== void 0 && { toolConfig: { functionCallingConfig: { mode: functionCallingMode } } }
339
+ };
340
+ if (options.thinking?.enabled && model.reasoning) {
341
+ const thinkingConfig = { includeThoughts: true };
342
+ if (options.thinking.level !== void 0) thinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];
343
+ else if (options.thinking.budgetTokens !== void 0) thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
344
+ config.thinkingConfig = thinkingConfig;
345
+ } else if (model.reasoning && options.thinking && !options.thinking.enabled) config.thinkingConfig = getDisabledThinkingConfig(model);
346
+ if (options.signal) {
347
+ if (options.signal.aborted) throw new Error("Request aborted");
348
+ config.abortSignal = options.signal;
349
+ }
350
+ return {
351
+ model: model.id,
352
+ contents,
353
+ config
354
+ };
355
+ }
356
+ function isGemini3ProModel(model) {
357
+ return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase());
358
+ }
359
+ function isGemini3FlashModel(model) {
360
+ const id = model.id.toLowerCase();
361
+ return /gemini-3(?:\.\d+)?-flash/.test(id) || id === "gemini-flash-latest" || id === "gemini-flash-lite-latest";
362
+ }
363
+ function getDisabledThinkingConfig(model) {
364
+ const geminiModel = model;
365
+ if (isGemini3ProModel(geminiModel)) return { thinkingLevel: ThinkingLevel.LOW };
366
+ if (isGemini3FlashModel(geminiModel)) return { thinkingLevel: ThinkingLevel.MINIMAL };
367
+ return { thinkingBudget: 0 };
368
+ }
369
+ function getGemini3ThinkingLevel(effort, model) {
370
+ if (isGemini3ProModel(model)) switch (effort) {
371
+ case "minimal":
372
+ case "low": return "LOW";
373
+ case "medium":
374
+ case "high": return "HIGH";
375
+ }
376
+ switch (effort) {
377
+ case "minimal": return "MINIMAL";
378
+ case "low": return "LOW";
379
+ case "medium": return "MEDIUM";
380
+ case "high": return "HIGH";
381
+ }
382
+ }
383
+ function getGoogleBudget(model, effort, customBudgets) {
384
+ if (customBudgets?.[effort] !== void 0) return customBudgets[effort];
385
+ if (model.id.includes("2.5-pro")) return {
386
+ minimal: 128,
387
+ low: 2048,
388
+ medium: 8192,
389
+ high: 32768
390
+ }[effort];
391
+ if (model.id.includes("2.5-flash")) return {
392
+ minimal: 128,
393
+ low: 2048,
394
+ medium: 8192,
395
+ high: 24576
396
+ }[effort];
397
+ return -1;
398
+ }
399
+ //#endregion
400
+ export { stream, streamSimple };
401
+
402
+ //# sourceMappingURL=google-vertex-DmdaHQtB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google-vertex-DmdaHQtB.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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O;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"}
@@ -0,0 +1,19 @@
1
+
2
+ //#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/utils/hash.js
3
+ /** Fast deterministic hash to shorten long strings */
4
+ function shortHash(str) {
5
+ let h1 = 3735928559;
6
+ let h2 = 1103547991;
7
+ for (let i = 0; i < str.length; i++) {
8
+ const ch = str.charCodeAt(i);
9
+ h1 = Math.imul(h1 ^ ch, 2654435761);
10
+ h2 = Math.imul(h2 ^ ch, 1597334677);
11
+ }
12
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
13
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
14
+ return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
15
+ }
16
+ //#endregion
17
+ export { shortHash as t };
18
+
19
+ //# sourceMappingURL=hash-Dbggamac.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-Dbggamac.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/utils/hash.js"],"sourcesContent":["/** Fast deterministic hash to shorten long strings */\nexport function shortHash(str) {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);\n}\n//# sourceMappingURL=hash.js.map"],"x_google_ignoreList":[0],"mappings":";;;AACA,SAAgB,UAAU,KAAK;CAC3B,IAAI,KAAK;CACT,IAAI,KAAK;CACT,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACjC,MAAM,KAAK,IAAI,WAAW,CAAC;EAC3B,KAAK,KAAK,KAAK,KAAK,IAAI,UAAU;EAClC,KAAK,KAAK,KAAK,KAAK,IAAI,UAAU;CACtC;CACA,KAAK,KAAK,KAAK,KAAM,OAAO,IAAK,UAAU,IAAI,KAAK,KAAK,KAAM,OAAO,IAAK,UAAU;CACrF,KAAK,KAAK,KAAK,KAAM,OAAO,IAAK,UAAU,IAAI,KAAK,KAAK,KAAM,OAAO,IAAK,UAAU;CACrF,QAAQ,OAAO,EAAA,CAAG,SAAS,EAAE,KAAK,OAAO,EAAA,CAAG,SAAS,EAAE;AAC3D"}
@@ -0,0 +1,17 @@
1
+
2
+ //#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/utils/headers.js
3
+ function headersToRecord(headers) {
4
+ const result = {};
5
+ for (const [key, value] of headers.entries()) result[key] = value;
6
+ return result;
7
+ }
8
+ function providerHeadersToRecord(headers) {
9
+ if (!headers) return void 0;
10
+ const result = {};
11
+ for (const [key, value] of Object.entries(headers)) if (value !== null) result[key] = value;
12
+ return Object.keys(result).length > 0 ? result : void 0;
13
+ }
14
+ //#endregion
15
+ export { providerHeadersToRecord as n, headersToRecord as t };
16
+
17
+ //# sourceMappingURL=headers-CPzZhJQn.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headers-CPzZhJQn.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/utils/headers.js"],"sourcesContent":["export function headersToRecord(headers) {\n const result = {};\n for (const [key, value] of headers.entries()) {\n result[key] = value;\n }\n return result;\n}\nexport function providerHeadersToRecord(headers) {\n if (!headers)\n return undefined;\n const result = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value !== null)\n result[key] = value;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n//# sourceMappingURL=headers.js.map"],"x_google_ignoreList":[0],"mappings":";;AAAA,SAAgB,gBAAgB,SAAS;CACrC,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,CAAC,KAAK,UAAU,QAAQ,QAAQ,GACvC,OAAO,OAAO;CAElB,OAAO;AACX;AACA,SAAgB,wBAAwB,SAAS;CAC7C,IAAI,CAAC,SACD,OAAO,KAAA;CACX,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC7C,IAAI,UAAU,MACV,OAAO,OAAO;CAEtB,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS,KAAA;AACrD"}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.mts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KAkBK,gBAAgB;UAEJ;;EAEf;;EAEA,SAAS;;UAGM;EACf,UAAU,eAAe;;;iBAuBL,qBAAqB,KAAK,oBAAoB,QAAQ;;;;;;iBAkDtD,YAAY,KAAK,SAAS,QAAQ,cAAc,kBAAkB;UAmCvE;EACf;;EAEA;EACA;;iBA+CoB,mBAAmB,SAAS,oBAAoB;EAAU;EAAgB"}
1
+ {"version":3,"file":"host.d.mts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KAmBK,gBAAgB;UAEJ;;EAEf;;EAEA,SAAS;;UAGM;EACf,UAAU,eAAe;;;iBAuBL,qBAAqB,KAAK,oBAAoB,QAAQ;;;;;;iBA8DtD,YAAY,KAAK,SAAS,QAAQ,cAAc,kBAAkB;UAmCvE;EACf;;EAEA;EACA;;iBA+CoB,mBAAmB,SAAS,oBAAoB;EAAU;EAAgB"}
package/dist/host.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
 
2
- import { t as applyPiPackage } from "./runtime-6DefpI6h.mjs";
2
+ import { t as applyPiPackage } from "./runtime-B9R7bDWT.mjs";
3
3
  import { t as resolvePiPackage } from "./source-0sA5z08z.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, join, relative } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { existsSync } from "node:fs";
8
9
  //#region src/host.ts
9
10
  function parseFrontmatter(text) {
10
11
  const normalized = text.replace(/\r\n?/gu, "\n");
@@ -64,7 +65,15 @@ function normalizeSpecs(config) {
64
65
  }
65
66
  function resolveInstalledDir(anchor, packageName) {
66
67
  const require = createRequire(anchor);
67
- return dirname(require.resolve(`${packageName}/package.json`));
68
+ try {
69
+ return dirname(require.resolve(`${packageName}/package.json`));
70
+ } catch {
71
+ for (const candidate of require.resolve.paths(packageName) ?? []) {
72
+ const dir = join(candidate, packageName);
73
+ if (existsSync(join(dir, "package.json"))) return dir;
74
+ }
75
+ throw new Error(`cannot locate the installed package directory for ${JSON.stringify(packageName)} near ${JSON.stringify(anchor)}`);
76
+ }
68
77
  }
69
78
  /**
70
79
  * Mount every configured Pi package from the host bundle's own node_modules.
@@ -159,7 +168,8 @@ async function generateHostBundle(options) {
159
168
  tinyglobby: "^0.2.15",
160
169
  "cross-spawn": "^7.0.6",
161
170
  diff: "^9.0.0",
162
- "@deepseek-ai/dsh-skill-filesystem": "^0.1.0-rc.6"
171
+ "@deepseek-ai/dsh-skill-filesystem": "^0.1.0-rc.6",
172
+ "@earendil-works/pi-ai": "*"
163
173
  },
164
174
  peerDependencies: {
165
175
  "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
package/dist/host.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.mjs","names":[],"sources":["../src/host.ts"],"sourcesContent":["// PiHostOnDSH: one DSH plugin that hosts unmodified Pi packages.\n//\n// Instead of converting each package into a vendored bundle, the host bundle\n// declares Pi packages as ordinary npm dependencies; DSH's plugin manager\n// (pnpm) installs them, and at load time this module resolves each installed\n// package, discovers its Pi entry points, and mounts it through the same\n// package-agnostic runtime as converted bundles. One host, any package —\n// there is deliberately no per-package branching here.\n\nimport { readdir, readFile, stat, writeFile, mkdir, cp } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, relative } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { applyPiPackage } from './runtime.js'\nimport { resolvePiPackage } from './source.js'\nimport type { GeneratedRuntimeManifest, ResolvedPiPackage } from './types.js'\n\ntype UnknownRecord = Record<string, unknown>\n\nexport interface PiHostPackageSpec {\n /** npm package name as installed in the host bundle's node_modules. */\n name: string\n /** Optional per-package config forwarded to the runtime. */\n config?: UnknownRecord\n}\n\nexport interface PiHostConfig {\n packages: Array<string | PiHostPackageSpec>\n}\n\nfunction parseFrontmatter(text: string): { attributes: Record<string, string>; body: string } {\n const normalized = text.replace(/\\r\\n?/gu, '\\n')\n if (!normalized.startsWith('---')) return { attributes: {}, body: normalized }\n const endIndex = normalized.indexOf('\\n---', 3)\n if (endIndex === -1) return { attributes: {}, body: normalized }\n const attributes: Record<string, string> = {}\n for (const line of normalized.slice(4, endIndex).split('\\n')) {\n const separator = line.indexOf(':')\n if (separator === -1) continue\n const key = line.slice(0, separator).trim()\n let value = line.slice(separator + 1).trim()\n if ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1)\n }\n if (key.length > 0) attributes[key] = value\n }\n return { attributes, body: normalized.slice(endIndex + 4).trim() }\n}\n\n/** Build a runtime manifest in place over an installed Pi package directory. */\nexport async function manifestForInstalled(pkg: ResolvedPiPackage): Promise<GeneratedRuntimeManifest> {\n const relativeTo = (file: string): string => relative(pkg.rootDir, file).replaceAll('\\\\', '/')\n\n const skillDirs = new Set<string>()\n for (const file of pkg.resources.skills) {\n // <dir>/<name>/SKILL.md contributes <dir>; a flat <dir>/<name>.md contributes <dir>.\n skillDirs.add(relativeTo(basename(file) === 'SKILL.md' ? dirname(dirname(file)) : dirname(file)))\n }\n\n const prompts: GeneratedRuntimeManifest['prompts'] = []\n const promptNames = new Set<string>()\n for (const source of pkg.resources.prompts) {\n const name = basename(source, '.md').toLowerCase().replace(/[^a-z0-9_-]+/gu, '-')\n if (promptNames.has(name)) throw new Error(`prompt command name collision in ${pkg.identity.name}: ${name}`)\n promptNames.add(name)\n const { attributes, body } = parseFrontmatter(await readFile(source, 'utf8'))\n const firstLine = body.split(/\\r?\\n/u).map(line => line.trim()).find(Boolean)\n prompts.push({\n name,\n description: attributes.description ?? firstLine ?? `Run migrated Pi prompt ${name}`,\n ...(attributes['argument-hint'] !== undefined ? { argumentHint: attributes['argument-hint'] } : {}),\n path: relativeTo(source),\n })\n }\n\n return {\n schemaVersion: 1,\n package: pkg.identity,\n extensions: pkg.resources.extensions.map(relativeTo),\n skillDirs: [...skillDirs].sort(),\n prompts,\n }\n}\n\nfunction normalizeSpecs(config: PiHostConfig): PiHostPackageSpec[] {\n const packages = Array.isArray(config?.packages) ? config.packages : []\n return packages.map(spec => (typeof spec === 'string' ? { name: spec } : spec))\n .filter(spec => typeof spec?.name === 'string' && spec.name.length > 0)\n}\n\nfunction resolveInstalledDir(anchor: string, packageName: string): string {\n const require = createRequire(anchor)\n return dirname(require.resolve(`${packageName}/package.json`))\n}\n\n/**\n * Mount every configured Pi package from the host bundle's own node_modules.\n * Packages that fail to mount report their error and do not take down the\n * host or their siblings — matching Pi's own per-extension error isolation.\n */\nexport async function applyPiHost(ctx: Context, config: PiHostConfig, anchor?: string): Promise<void> {\n const anchorPath = anchor ?? fileURLToPath(import.meta.url)\n const errors: Array<{ name: string; error: string }> = []\n for (const spec of normalizeSpecs(config)) {\n try {\n const dir = resolveInstalledDir(anchorPath, spec.name)\n const pkg = await resolvePiPackage(dir)\n try {\n const manifest = await manifestForInstalled(pkg)\n await applyPiPackage(ctx, {\n rootUrl: pathToFileURL(`${pkg.rootDir}/`),\n manifest,\n ...(spec.config === undefined ? {} : { config: spec.config }),\n })\n } finally {\n await pkg.dispose()\n }\n } catch (error) {\n errors.push({ name: spec.name, error: error instanceof Error ? error.message : String(error) })\n }\n }\n for (const failure of errors) {\n const log = (ctx as unknown as { logger?: { warn?(message: string): void } }).logger\n const warn = log?.warn?.bind(log) ?? console.warn\n warn(`[pi2dsh host] failed to mount ${failure.name}: ${failure.error}`)\n }\n if (errors.length > 0 && errors.length === normalizeSpecs(config).length) {\n throw new Error(`pi2dsh host mounted no packages; first failure: ${errors[0]!.name}: ${errors[0]!.error}`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Host bundle generation\n// ---------------------------------------------------------------------------\n\nexport interface HostBundleOptions {\n outDir: string\n /** npm specs, e.g. \"@narumitw/pi-lsp@0.49.4\" or \"pi-ask-user\". */\n packages: string[]\n bundleName?: string\n}\n\nfunction splitSpec(spec: string): { name: string; range: string } {\n const at = spec.lastIndexOf('@')\n if (at > 0) return { name: spec.slice(0, at), range: spec.slice(at + 1) }\n return { name: spec, range: '*' }\n}\n\nasync function firstExisting(paths: string[]): Promise<string> {\n for (const path of paths) {\n try {\n await stat(path)\n return path\n } catch {\n // Try the next layout.\n }\n }\n throw new Error(`cannot locate pi2dsh runtime artifact; tried: ${paths.join(', ')}`)\n}\n\nasync function copyEmbeddedHostRuntime(outDir: string): Promise<void> {\n const moduleDir = dirname(fileURLToPath(import.meta.url))\n const hostSource = await firstExisting([\n join(moduleDir, 'host.mjs'),\n join(moduleDir, '../dist/host.mjs'),\n ])\n const distRoot = dirname(hostSource)\n const targetRoot = join(outDir, 'runtime')\n await mkdir(join(targetRoot, 'compat', 'vendor'), { recursive: true })\n for (const entry of await readdir(distRoot)) {\n if (entry.endsWith('.mjs') || entry.endsWith('.d.mts')) {\n await cp(join(distRoot, entry), join(targetRoot, entry))\n }\n }\n for (const sub of ['compat', join('compat', 'vendor')]) {\n const dir = join(distRoot, sub)\n try {\n for (const entry of await readdir(dir)) {\n if (entry.endsWith('.mjs')) await cp(join(dir, entry), join(targetRoot, sub, entry))\n }\n } catch {\n // dist layout without that subdirectory\n }\n }\n}\n\nexport async function generateHostBundle(options: HostBundleOptions): Promise<{ outDir: string; packageName: string }> {\n const specs = options.packages.map(splitSpec)\n if (specs.length === 0) throw new Error('host bundle requires at least one Pi package spec')\n const packageName = options.bundleName ?? 'dsh-pi-host'\n await mkdir(options.outDir, { recursive: true })\n await copyEmbeddedHostRuntime(options.outDir)\n\n const packageJson = {\n name: packageName,\n version: '0.1.0',\n description: `pi2dsh host bundle mounting ${specs.map(spec => spec.name).join(', ')} as native DSH plugins`,\n type: 'module',\n main: './index.js',\n files: ['index.js', 'cordis.patch.yml', 'runtime', 'PI2DSH-LICENSE', 'README.md'],\n dependencies: {\n ...Object.fromEntries(specs.map(spec => [spec.name, spec.range])),\n jiti: '^2.7.0',\n 'get-east-asian-width': '^1.6.0',\n marked: '^16.4.1',\n typebox: '^1.0.4',\n tinyglobby: '^0.2.15',\n // The vendored Pi built-in tool constructors spawn through cross-spawn\n // and diff exactly as Pi does — same runtime set the convert bundle\n // carries (generator.ts keeps the sibling list).\n 'cross-spawn': '^7.0.6',\n diff: '^9.0.0',\n '@deepseek-ai/dsh-skill-filesystem': '^0.1.0-rc.6',\n },\n peerDependencies: {\n '@deepseek-ai/dsh-llm': '^0.1.0-rc.6',\n '@deepseek-ai/dsh-system-prompt': '^0.1.0-rc.6',\n },\n keywords: ['dsh-plugin', 'deepseek-harness', 'pi-package', 'pi2dsh', 'pi-host'],\n license: 'MIT',\n dsh: { bundle: { patch: './cordis.patch.yml' } },\n }\n await writeFile(join(options.outDir, 'package.json'), `${JSON.stringify(packageJson, null, 2)}\\n`)\n\n const hostConfig: PiHostConfig = { packages: specs.map(spec => spec.name) }\n const indexSource = `import { applyPiHost } from './runtime/host.mjs'\\n\\n`\n + `export const name = ${JSON.stringify(packageName)}\\n`\n + `export const inject = ${JSON.stringify(['tools', 'systemPrompt', 'commands', 'skills'])}\\n\\n`\n + `const hostConfig = ${JSON.stringify(hostConfig, null, 2)}\\n\\n`\n + `export async function apply(ctx, config = {}) {\\n`\n + ` await applyPiHost(ctx, { ...hostConfig, ...config }, new URL(import.meta.url).pathname)\\n`\n + `}\\n`\n await writeFile(join(options.outDir, 'index.js'), indexSource)\n\n await writeFile(join(options.outDir, 'cordis.patch.yml'),\n `- insert:\\n - id: ${packageName}\\n name: ${JSON.stringify(packageName)}\\n`)\n\n const licenseSource = await firstExisting([\n join(dirname(fileURLToPath(import.meta.url)), 'compat/vendor/PI-LICENSE'),\n join(dirname(fileURLToPath(import.meta.url)), '../src/compat/vendor/PI-LICENSE'),\n ])\n await cp(licenseSource, join(options.outDir, 'PI2DSH-LICENSE'))\n\n await writeFile(join(options.outDir, 'README.md'),\n `# ${packageName}\\n\\n`\n + `A [pi2dsh](https://github.com/weijiafu14/pi2dsh) host bundle. The Pi packages below are installed as ordinary npm dependencies and mounted at load time — no per-package conversion, no vendored source snapshots.\\n\\n`\n + specs.map(spec => `- \\`${spec.name}@${spec.range}\\`\\n`).join('')\n + `\\nInstall:\\n\\n\\`\\`\\`sh\\ndsh plugin --profile headless add file:$PWD\\ndsh --profile headless --dump-config\\n\\`\\`\\`\\n`\n + `\\nThe packages execute their original Pi extension source inside the pi2dsh Host ABI; install only sources you trust. Run \\`pi2dsh inspect <package>\\` for each package's compatibility report.\\n`)\n\n return { outDir: options.outDir, packageName }\n}\n"],"mappings":";;;;;;;;AA+BA,SAAS,iBAAiB,MAAoE;CAC5F,MAAM,aAAa,KAAK,QAAQ,WAAW,IAAI;CAC/C,IAAI,CAAC,WAAW,WAAW,KAAK,GAAG,OAAO;EAAE,YAAY,CAAC;EAAG,MAAM;CAAW;CAC7E,MAAM,WAAW,WAAW,QAAQ,SAAS,CAAC;CAC9C,IAAI,aAAa,IAAI,OAAO;EAAE,YAAY,CAAC;EAAG,MAAM;CAAW;CAC/D,MAAM,aAAqC,CAAC;CAC5C,KAAK,MAAM,QAAQ,WAAW,MAAM,GAAG,QAAQ,CAAC,CAAC,MAAM,IAAI,GAAG;EAC5D,MAAM,YAAY,KAAK,QAAQ,GAAG;EAClC,IAAI,cAAc,IAAI;EACtB,MAAM,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK;EAC1C,IAAI,QAAQ,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK;EAC3C,IAAK,MAAM,WAAW,IAAG,KAAK,MAAM,SAAS,IAAG,KAAO,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,GAAG,GAChG,QAAQ,MAAM,MAAM,GAAG,EAAE;EAE3B,IAAI,IAAI,SAAS,GAAG,WAAW,OAAO;CACxC;CACA,OAAO;EAAE;EAAY,MAAM,WAAW,MAAM,WAAW,CAAC,CAAC,CAAC,KAAK;CAAE;AACnE;;AAGA,eAAsB,qBAAqB,KAA2D;CACpG,MAAM,cAAc,SAAyB,SAAS,IAAI,SAAS,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CAE7F,MAAM,4BAAY,IAAI,IAAY;CAClC,KAAK,MAAM,QAAQ,IAAI,UAAU,QAE/B,UAAU,IAAI,WAAW,SAAS,IAAI,MAAM,aAAa,QAAQ,QAAQ,IAAI,CAAC,IAAI,QAAQ,IAAI,CAAC,CAAC;CAGl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KAAK,MAAM,KAAK,CAAC,CAAC,KAAK,EAAE,IAC/D,8SACmM;CAEvM,OAAO;EAAE,QAAQ,QAAQ;EAAQ;CAAY;AAC/C"}
1
+ {"version":3,"file":"host.mjs","names":[],"sources":["../src/host.ts"],"sourcesContent":["// PiHostOnDSH: one DSH plugin that hosts unmodified Pi packages.\n//\n// Instead of converting each package into a vendored bundle, the host bundle\n// declares Pi packages as ordinary npm dependencies; DSH's plugin manager\n// (pnpm) installs them, and at load time this module resolves each installed\n// package, discovers its Pi entry points, and mounts it through the same\n// package-agnostic runtime as converted bundles. One host, any package —\n// there is deliberately no per-package branching here.\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { readdir, readFile, stat, writeFile, mkdir, cp } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, relative } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { applyPiPackage } from './runtime.js'\nimport { resolvePiPackage } from './source.js'\nimport type { GeneratedRuntimeManifest, ResolvedPiPackage } from './types.js'\n\ntype UnknownRecord = Record<string, unknown>\n\nexport interface PiHostPackageSpec {\n /** npm package name as installed in the host bundle's node_modules. */\n name: string\n /** Optional per-package config forwarded to the runtime. */\n config?: UnknownRecord\n}\n\nexport interface PiHostConfig {\n packages: Array<string | PiHostPackageSpec>\n}\n\nfunction parseFrontmatter(text: string): { attributes: Record<string, string>; body: string } {\n const normalized = text.replace(/\\r\\n?/gu, '\\n')\n if (!normalized.startsWith('---')) return { attributes: {}, body: normalized }\n const endIndex = normalized.indexOf('\\n---', 3)\n if (endIndex === -1) return { attributes: {}, body: normalized }\n const attributes: Record<string, string> = {}\n for (const line of normalized.slice(4, endIndex).split('\\n')) {\n const separator = line.indexOf(':')\n if (separator === -1) continue\n const key = line.slice(0, separator).trim()\n let value = line.slice(separator + 1).trim()\n if ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1)\n }\n if (key.length > 0) attributes[key] = value\n }\n return { attributes, body: normalized.slice(endIndex + 4).trim() }\n}\n\n/** Build a runtime manifest in place over an installed Pi package directory. */\nexport async function manifestForInstalled(pkg: ResolvedPiPackage): Promise<GeneratedRuntimeManifest> {\n const relativeTo = (file: string): string => relative(pkg.rootDir, file).replaceAll('\\\\', '/')\n\n const skillDirs = new Set<string>()\n for (const file of pkg.resources.skills) {\n // <dir>/<name>/SKILL.md contributes <dir>; a flat <dir>/<name>.md contributes <dir>.\n skillDirs.add(relativeTo(basename(file) === 'SKILL.md' ? dirname(dirname(file)) : dirname(file)))\n }\n\n const prompts: GeneratedRuntimeManifest['prompts'] = []\n const promptNames = new Set<string>()\n for (const source of pkg.resources.prompts) {\n const name = basename(source, '.md').toLowerCase().replace(/[^a-z0-9_-]+/gu, '-')\n if (promptNames.has(name)) throw new Error(`prompt command name collision in ${pkg.identity.name}: ${name}`)\n promptNames.add(name)\n const { attributes, body } = parseFrontmatter(await readFile(source, 'utf8'))\n const firstLine = body.split(/\\r?\\n/u).map(line => line.trim()).find(Boolean)\n prompts.push({\n name,\n description: attributes.description ?? firstLine ?? `Run migrated Pi prompt ${name}`,\n ...(attributes['argument-hint'] !== undefined ? { argumentHint: attributes['argument-hint'] } : {}),\n path: relativeTo(source),\n })\n }\n\n return {\n schemaVersion: 1,\n package: pkg.identity,\n extensions: pkg.resources.extensions.map(relativeTo),\n skillDirs: [...skillDirs].sort(),\n prompts,\n }\n}\n\nfunction normalizeSpecs(config: PiHostConfig): PiHostPackageSpec[] {\n const packages = Array.isArray(config?.packages) ? config.packages : []\n return packages.map(spec => (typeof spec === 'string' ? { name: spec } : spec))\n .filter(spec => typeof spec?.name === 'string' && spec.name.length > 0)\n}\n\nfunction resolveInstalledDir(anchor: string, packageName: string): string {\n const require = createRequire(anchor)\n try {\n return dirname(require.resolve(`${packageName}/package.json`))\n } catch {\n // Modern strict `exports` maps refuse the package.json subpath, and pure\n // ESM packages (no \"require\" condition) refuse CJS entry resolution too.\n // Locate the installed directory on the filesystem instead: probe every\n // node_modules candidate on the resolution path — no exports involved.\n for (const candidate of require.resolve.paths(packageName) ?? []) {\n const dir = join(candidate, packageName)\n if (existsSync(join(dir, 'package.json'))) return dir\n }\n throw new Error(`cannot locate the installed package directory for ${JSON.stringify(packageName)} near ${JSON.stringify(anchor)}`)\n }\n}\n\n/**\n * Mount every configured Pi package from the host bundle's own node_modules.\n * Packages that fail to mount report their error and do not take down the\n * host or their siblings — matching Pi's own per-extension error isolation.\n */\nexport async function applyPiHost(ctx: Context, config: PiHostConfig, anchor?: string): Promise<void> {\n const anchorPath = anchor ?? fileURLToPath(import.meta.url)\n const errors: Array<{ name: string; error: string }> = []\n for (const spec of normalizeSpecs(config)) {\n try {\n const dir = resolveInstalledDir(anchorPath, spec.name)\n const pkg = await resolvePiPackage(dir)\n try {\n const manifest = await manifestForInstalled(pkg)\n await applyPiPackage(ctx, {\n rootUrl: pathToFileURL(`${pkg.rootDir}/`),\n manifest,\n ...(spec.config === undefined ? {} : { config: spec.config }),\n })\n } finally {\n await pkg.dispose()\n }\n } catch (error) {\n errors.push({ name: spec.name, error: error instanceof Error ? error.message : String(error) })\n }\n }\n for (const failure of errors) {\n const log = (ctx as unknown as { logger?: { warn?(message: string): void } }).logger\n const warn = log?.warn?.bind(log) ?? console.warn\n warn(`[pi2dsh host] failed to mount ${failure.name}: ${failure.error}`)\n }\n if (errors.length > 0 && errors.length === normalizeSpecs(config).length) {\n throw new Error(`pi2dsh host mounted no packages; first failure: ${errors[0]!.name}: ${errors[0]!.error}`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Host bundle generation\n// ---------------------------------------------------------------------------\n\nexport interface HostBundleOptions {\n outDir: string\n /** npm specs, e.g. \"@narumitw/pi-lsp@0.49.4\" or \"pi-ask-user\". */\n packages: string[]\n bundleName?: string\n}\n\nfunction splitSpec(spec: string): { name: string; range: string } {\n const at = spec.lastIndexOf('@')\n if (at > 0) return { name: spec.slice(0, at), range: spec.slice(at + 1) }\n return { name: spec, range: '*' }\n}\n\nasync function firstExisting(paths: string[]): Promise<string> {\n for (const path of paths) {\n try {\n await stat(path)\n return path\n } catch {\n // Try the next layout.\n }\n }\n throw new Error(`cannot locate pi2dsh runtime artifact; tried: ${paths.join(', ')}`)\n}\n\nasync function copyEmbeddedHostRuntime(outDir: string): Promise<void> {\n const moduleDir = dirname(fileURLToPath(import.meta.url))\n const hostSource = await firstExisting([\n join(moduleDir, 'host.mjs'),\n join(moduleDir, '../dist/host.mjs'),\n ])\n const distRoot = dirname(hostSource)\n const targetRoot = join(outDir, 'runtime')\n await mkdir(join(targetRoot, 'compat', 'vendor'), { recursive: true })\n for (const entry of await readdir(distRoot)) {\n if (entry.endsWith('.mjs') || entry.endsWith('.d.mts')) {\n await cp(join(distRoot, entry), join(targetRoot, entry))\n }\n }\n for (const sub of ['compat', join('compat', 'vendor')]) {\n const dir = join(distRoot, sub)\n try {\n for (const entry of await readdir(dir)) {\n if (entry.endsWith('.mjs')) await cp(join(dir, entry), join(targetRoot, sub, entry))\n }\n } catch {\n // dist layout without that subdirectory\n }\n }\n}\n\nexport async function generateHostBundle(options: HostBundleOptions): Promise<{ outDir: string; packageName: string }> {\n const specs = options.packages.map(splitSpec)\n if (specs.length === 0) throw new Error('host bundle requires at least one Pi package spec')\n const packageName = options.bundleName ?? 'dsh-pi-host'\n await mkdir(options.outDir, { recursive: true })\n await copyEmbeddedHostRuntime(options.outDir)\n\n const packageJson = {\n name: packageName,\n version: '0.1.0',\n description: `pi2dsh host bundle mounting ${specs.map(spec => spec.name).join(', ')} as native DSH plugins`,\n type: 'module',\n main: './index.js',\n files: ['index.js', 'cordis.patch.yml', 'runtime', 'PI2DSH-LICENSE', 'README.md'],\n dependencies: {\n ...Object.fromEntries(specs.map(spec => [spec.name, spec.range])),\n jiti: '^2.7.0',\n 'get-east-asian-width': '^1.6.0',\n marked: '^16.4.1',\n typebox: '^1.0.4',\n tinyglobby: '^0.2.15',\n // The vendored Pi built-in tool constructors spawn through cross-spawn\n // and diff exactly as Pi does — same runtime set the convert bundle\n // carries (generator.ts keeps the sibling list).\n 'cross-spawn': '^7.0.6',\n diff: '^9.0.0',\n '@deepseek-ai/dsh-skill-filesystem': '^0.1.0-rc.6',\n // The REAL pi-ai: a host bundle provides the peer exactly as a Pi host\n // would. Packages still import the shim (jiti alias); the bridge's\n // wire-protocol transport factories (openai-completions etc.) forward\n // to this real implementation so gateway providers stream for real.\n '@earendil-works/pi-ai': '*',\n },\n peerDependencies: {\n '@deepseek-ai/dsh-llm': '^0.1.0-rc.6',\n '@deepseek-ai/dsh-system-prompt': '^0.1.0-rc.6',\n },\n keywords: ['dsh-plugin', 'deepseek-harness', 'pi-package', 'pi2dsh', 'pi-host'],\n license: 'MIT',\n dsh: { bundle: { patch: './cordis.patch.yml' } },\n }\n await writeFile(join(options.outDir, 'package.json'), `${JSON.stringify(packageJson, null, 2)}\\n`)\n\n const hostConfig: PiHostConfig = { packages: specs.map(spec => spec.name) }\n const indexSource = `import { applyPiHost } from './runtime/host.mjs'\\n\\n`\n + `export const name = ${JSON.stringify(packageName)}\\n`\n + `export const inject = ${JSON.stringify(['tools', 'systemPrompt', 'commands', 'skills'])}\\n\\n`\n + `const hostConfig = ${JSON.stringify(hostConfig, null, 2)}\\n\\n`\n + `export async function apply(ctx, config = {}) {\\n`\n + ` await applyPiHost(ctx, { ...hostConfig, ...config }, new URL(import.meta.url).pathname)\\n`\n + `}\\n`\n await writeFile(join(options.outDir, 'index.js'), indexSource)\n\n await writeFile(join(options.outDir, 'cordis.patch.yml'),\n `- insert:\\n - id: ${packageName}\\n name: ${JSON.stringify(packageName)}\\n`)\n\n const licenseSource = await firstExisting([\n join(dirname(fileURLToPath(import.meta.url)), 'compat/vendor/PI-LICENSE'),\n join(dirname(fileURLToPath(import.meta.url)), '../src/compat/vendor/PI-LICENSE'),\n ])\n await cp(licenseSource, join(options.outDir, 'PI2DSH-LICENSE'))\n\n await writeFile(join(options.outDir, 'README.md'),\n `# ${packageName}\\n\\n`\n + `A [pi2dsh](https://github.com/weijiafu14/pi2dsh) host bundle. The Pi packages below are installed as ordinary npm dependencies and mounted at load time — no per-package conversion, no vendored source snapshots.\\n\\n`\n + specs.map(spec => `- \\`${spec.name}@${spec.range}\\`\\n`).join('')\n + `\\nInstall:\\n\\n\\`\\`\\`sh\\ndsh plugin --profile headless add file:$PWD\\ndsh --profile headless --dump-config\\n\\`\\`\\`\\n`\n + `\\nThe packages execute their original Pi extension source inside the pi2dsh Host ABI; install only sources you trust. Run \\`pi2dsh inspect <package>\\` for each package's compatibility report.\\n`)\n\n return { outDir: options.outDir, packageName }\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,iBAAiB,MAAoE;CAC5F,MAAM,aAAa,KAAK,QAAQ,WAAW,IAAI;CAC/C,IAAI,CAAC,WAAW,WAAW,KAAK,GAAG,OAAO;EAAE,YAAY,CAAC;EAAG,MAAM;CAAW;CAC7E,MAAM,WAAW,WAAW,QAAQ,SAAS,CAAC;CAC9C,IAAI,aAAa,IAAI,OAAO;EAAE,YAAY,CAAC;EAAG,MAAM;CAAW;CAC/D,MAAM,aAAqC,CAAC;CAC5C,KAAK,MAAM,QAAQ,WAAW,MAAM,GAAG,QAAQ,CAAC,CAAC,MAAM,IAAI,GAAG;EAC5D,MAAM,YAAY,KAAK,QAAQ,GAAG;EAClC,IAAI,cAAc,IAAI;EACtB,MAAM,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK;EAC1C,IAAI,QAAQ,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK;EAC3C,IAAK,MAAM,WAAW,IAAG,KAAK,MAAM,SAAS,IAAG,KAAO,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,GAAG,GAChG,QAAQ,MAAM,MAAM,GAAG,EAAE;EAE3B,IAAI,IAAI,SAAS,GAAG,WAAW,OAAO;CACxC;CACA,OAAO;EAAE;EAAY,MAAM,WAAW,MA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