@nomadop/session-watcher-dsh 0.10.1 → 0.11.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.
@@ -0,0 +1,1565 @@
1
+ //! The code of the DeepSeek Harness plugin @deepseek-ai/dsh-llm-pi-ai bundled in this file is under this license:
2
+ //! MIT License
3
+ //!
4
+ //! Copyright (c) 2026 DeepSeek
5
+ //!
6
+ //! Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ //! of this software and associated documentation files (the "Software"), to deal
8
+ //! in the Software without restriction, including without limitation the rights
9
+ //! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ //! copies of the Software, and to permit persons to whom the Software is
11
+ //! furnished to do so, subject to the following conditions:
12
+ //!
13
+ //! The above copyright notice and this permission notice shall be included in all
14
+ //! copies or substantial portions of the Software.
15
+ //!
16
+ //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ //! SOFTWARE.
23
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
24
+
25
+ // lib/harness/dsh/inner-seal-message.js
26
+ var CARRIER_WORDING = {
27
+ addresses: "These summaries stand in for earlier turns of this session; replacing them changed no file and no state, so the work carries on from them. Each summary line below opens with seq numbers: the addresses, in this session's log, of the events it summarizes, which the session history tools can read. A line marked user: holds the user's own words instead, cut where a marker says so.",
28
+ slotLine: (seqs) => `seq ${seqs.join(", ")}: `,
29
+ imageSaved: (name2) => `The image ${name2} is not in the current context; read_image can read the file below when it is needed.`,
30
+ carried: "Evidence carried from the replaced context as of this summary: file text as read from disk when it was written, and skill text as the log recorded it. Each entry changes what the evidence of any earlier summary or kept file excerpt here states. The reads behind this file text still count in this session, so edit a file without reading it again.",
31
+ empty: (path) => `${path} is empty.`,
32
+ unreadable: (path, reason) => `${path} could not be read (${reason}). This is not its text and not a tool failure; read the file directly when it is needed.`,
33
+ skill: (name2, text) => `Skill ${name2}:
34
+ ${text}`,
35
+ stateHeading: (seq) => `Session state as of session seq ${seq}:`,
36
+ stateLabels: {
37
+ workingDirectory: (tool) => `Working directory, as ${tool} would show:`,
38
+ subagents: (tool) => `Running subagents, as ${tool} would show:`,
39
+ jobs: (tool) => `Running jobs, as ${tool} would show:`,
40
+ todos: (tool) => `Todo list, as ${tool} last left it:`
41
+ },
42
+ stateList: (entries) => entries.map(({ id, label: label2 }) => `${id} \u2014 ${label2}`).join("; "),
43
+ stateUnchanged: "unchanged since the last summary that shows it",
44
+ stateEmpty: "(empty)",
45
+ questionMark: "A line marked question: holds the original question.",
46
+ questionLine: (question) => `question: ${question}`,
47
+ userLine: (user) => `user: ${user}`,
48
+ askCall: ({ id, name: name2, arguments: args }) => `Original ${name2} call ${id}, arguments:
49
+ ${args}`,
50
+ askResult: (id, { text, isError }) => `Original result of call ${id}${isError ? " (marked as an error)" : ""}:
51
+ ${text}`
52
+ };
53
+ var isTodoItem = (item) => item !== null && typeof item === "object" && typeof item.content === "string" && typeof item.status === "string";
54
+ function todoItemsOf(value) {
55
+ if (value === null) return [];
56
+ if (!Array.isArray(value) || !value.every(isTodoItem)) throw new Error("the todo list is neither null nor a list of items with a content text and a status text");
57
+ return value.map(({ content, status }) => ({ content, status }));
58
+ }
59
+ function textEntriesOf(value, fields, what) {
60
+ if (!Array.isArray(value) || !value.every((entry) => entry !== null && typeof entry === "object" && fields.every((field) => typeof entry[field] === "string"))) {
61
+ throw new Error(`the ${what} is not a list of entries with ${fields.join(" and ")} texts`);
62
+ }
63
+ return value.map((entry) => Object.fromEntries(fields.map((field) => [field, entry[field]])));
64
+ }
65
+ var sameEntries = (fields, a, b) => a.length === b.length && a.every((entry, at) => fields.every((field) => entry[field] === b[at][field]));
66
+ var AGENT_FIELDS = ["id", "label"];
67
+ var TODO_FIELDS = ["content", "status"];
68
+ var STATE_ITEMS = Object.freeze([
69
+ Object.freeze({
70
+ key: "workingDirectory",
71
+ tool: "working_directory",
72
+ normalize: (value) => {
73
+ if (typeof value !== "string" || value === "") throw new Error("the working directory is not a path text");
74
+ return value;
75
+ },
76
+ isEmpty: () => false,
77
+ same: (a, b) => a === b,
78
+ text: (value) => value
79
+ }),
80
+ Object.freeze({
81
+ key: "subagents",
82
+ tool: "list_agents",
83
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "subagent list"),
84
+ isEmpty: (entries) => entries.length === 0,
85
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
86
+ text: CARRIER_WORDING.stateList
87
+ }),
88
+ Object.freeze({
89
+ key: "jobs",
90
+ tool: "job_list",
91
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "job list"),
92
+ isEmpty: (entries) => entries.length === 0,
93
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
94
+ text: CARRIER_WORDING.stateList
95
+ }),
96
+ Object.freeze({
97
+ key: "todos",
98
+ tool: "todo_write",
99
+ normalize: todoItemsOf,
100
+ isEmpty: (items) => items.length === 0,
101
+ same: (a, b) => sameEntries(TODO_FIELDS, a, b),
102
+ text: (items) => JSON.stringify(items)
103
+ })
104
+ ]);
105
+
106
+ // dsh/vendor/dsh-llm-pi-ai/src/config.ts
107
+ import z from "@deepseek-ai/schemastery";
108
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
109
+ import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
110
+ import { resolveRetryPolicy, RetryPolicySchema } from "@deepseek-ai/dsh-llm";
111
+ import { deepEqualJson } from "@deepseek-ai/dsh-util-values";
112
+
113
+ // dsh/vendor/dsh-llm-pi-ai/src/catalog.ts
114
+ import { builtinProviders, getAllBuiltinModels, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
115
+ var NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
116
+ var MODALITY_GATE = {
117
+ text: true,
118
+ image: true
119
+ };
120
+ var MODALITIES = Object.keys(MODALITY_GATE);
121
+ function declaredInput(configured) {
122
+ return configured === void 0 || configured.length === 0 ? void 0 : [...configured];
123
+ }
124
+ var THINKING_LEVEL_GATE = {
125
+ off: true,
126
+ minimal: true,
127
+ low: true,
128
+ medium: true,
129
+ high: true,
130
+ xhigh: true,
131
+ max: true
132
+ };
133
+ var THINKING_LEVELS = Object.keys(THINKING_LEVEL_GATE);
134
+ var THINKING_FORMAT_GATE = {
135
+ "openai": true,
136
+ "deepseek": true,
137
+ "openrouter": true,
138
+ "together": true,
139
+ "baseten": true,
140
+ "zai": true,
141
+ "qwen": true,
142
+ "chat-template": true,
143
+ "qwen-chat-template": true,
144
+ "string-thinking": true,
145
+ "ant-ling": true
146
+ };
147
+ var SUPPORTED_THINKING_FORMATS = Object.keys(THINKING_FORMAT_GATE);
148
+ var MAX_TOKENS_FIELD_GATE = {
149
+ max_completion_tokens: true,
150
+ max_tokens: true
151
+ };
152
+ var MAX_TOKENS_FIELDS = Object.keys(MAX_TOKENS_FIELD_GATE);
153
+ var THINKING_TOKEN_BUDGET_FIELD_GATE = {
154
+ thinking_token_budget: true,
155
+ thinking_budget: true,
156
+ thinking_budget_tokens: true
157
+ };
158
+ var THINKING_TOKEN_BUDGET_FIELDS = Object.keys(THINKING_TOKEN_BUDGET_FIELD_GATE);
159
+ var CACHE_CONTROL_FORMAT_GATE = {
160
+ anthropic: true
161
+ };
162
+ var CACHE_CONTROL_FORMATS = Object.keys(CACHE_CONTROL_FORMAT_GATE);
163
+ var CHAT_TEMPLATE_VAR_GATE = {
164
+ "thinking.enabled": true,
165
+ "thinking.effort": true,
166
+ "thinking.budget": true
167
+ };
168
+ var CHAT_TEMPLATE_VARS = Object.keys(CHAT_TEMPLATE_VAR_GATE);
169
+ var providerIndex;
170
+ function servesChat(provider) {
171
+ const id = provider.id;
172
+ return getBuiltinModels(id).length > 0 || getAllBuiltinModels(id).length === 0;
173
+ }
174
+ function catalogProviders() {
175
+ providerIndex ??= new Map(builtinProviders().filter(servesChat).map((provider) => [provider.id, provider]));
176
+ return providerIndex;
177
+ }
178
+ function catalogProvider(provider) {
179
+ return catalogProviders().get(provider);
180
+ }
181
+ function catalogProviderIds() {
182
+ return [...catalogProviders().keys()];
183
+ }
184
+ function catalogModels(provider) {
185
+ if (!catalogProviders().has(provider)) return /* @__PURE__ */ new Map();
186
+ const models = getBuiltinModels(provider);
187
+ return new Map(models.map((model) => [model.id, model]));
188
+ }
189
+ var COMPLETIONS_COMPAT_GATE = {
190
+ supportsStore: "offer",
191
+ supportsDeveloperRole: "offer",
192
+ supportsReasoningEffort: "offer",
193
+ supportsUsageInStreaming: "offer",
194
+ supportsFinishReason: "offer",
195
+ maxTokensField: "offer",
196
+ requiresToolResultName: "offer",
197
+ requiresAssistantAfterToolResult: "offer",
198
+ requiresThinkingAsText: "offer",
199
+ requiresReasoningContentOnAssistantMessages: "offer",
200
+ thinkingFormat: "offer",
201
+ chatTemplateKwargs: "offer",
202
+ chatTemplateArgs: "offer",
203
+ supportsThinkingTokenBudget: "offer",
204
+ thinkingTokenBudgetField: "offer",
205
+ vllmPriority: "offer",
206
+ supportsStrictMode: "offer",
207
+ cacheControlFormat: "offer",
208
+ supportsLongCacheRetention: "offer",
209
+ openRouterRouting: "withhold",
210
+ vercelGatewayRouting: "withhold",
211
+ zaiToolStream: "withhold",
212
+ supportsOpenAIGrammarTools: "withhold",
213
+ sendSessionAffinityHeaders: "withhold",
214
+ supportsMidConvoSystemMessages: "withhold",
215
+ supportsMidConvoToolAdditions: "withhold",
216
+ sessionAffinityFormat: "withhold"
217
+ };
218
+ var RESPONSES_COMPAT_GATE = {
219
+ supportsDeveloperRole: "offer",
220
+ supportsMaxOutputTokens: "offer",
221
+ supportsStrictMode: "offer",
222
+ supportsLongCacheRetention: "offer",
223
+ sessionAffinityFormat: "withhold",
224
+ supportsOpenAIGrammarTools: "withhold",
225
+ supportsAdditionalTools: "withhold",
226
+ supportsToolSearch: "withhold",
227
+ supportsExplicitPromptCacheMode: "withhold",
228
+ supportsMidConvoSystemMessages: "withhold",
229
+ supportsMidConvoEffort: "withhold"
230
+ };
231
+ var OPENAI_RESPONSES_COMPAT_GATE = {
232
+ ...RESPONSES_COMPAT_GATE,
233
+ supportsExplicitPromptCacheMode: "offer"
234
+ };
235
+ var ANTHROPIC_COMPAT_GATE = {
236
+ supportsEagerToolInputStreaming: "offer",
237
+ supportsLongCacheRetention: "offer",
238
+ supportsCacheControlOnTools: "offer",
239
+ supportsTemperature: "offer",
240
+ forceAdaptiveThinking: "offer",
241
+ allowEmptySignature: "offer",
242
+ supportsStrictTools: "offer",
243
+ sendSessionAffinityHeaders: "withhold",
244
+ sessionAffinityFormat: "withhold",
245
+ supportsMidConvoSystemMessages: "withhold",
246
+ supportsMidConvoToolChanges: "withhold",
247
+ supportsMidConvoEffort: "withhold",
248
+ allowedFallbackModels: "withhold"
249
+ };
250
+ var BEDROCK_COMPAT_GATE = {
251
+ supportsStrictMode: "offer"
252
+ };
253
+ var MISTRAL_COMPAT_GATE = {
254
+ supportsMidConvoSystemMessages: "withhold"
255
+ };
256
+ var COMPAT_GATES = {
257
+ "mistral-conversations": MISTRAL_COMPAT_GATE,
258
+ "openai-completions": COMPLETIONS_COMPAT_GATE,
259
+ "openai-responses": OPENAI_RESPONSES_COMPAT_GATE,
260
+ "azure-openai-responses": RESPONSES_COMPAT_GATE,
261
+ "openai-codex-responses": RESPONSES_COMPAT_GATE,
262
+ "anthropic-messages": ANTHROPIC_COMPAT_GATE,
263
+ "bedrock-converse-stream": BEDROCK_COMPAT_GATE
264
+ };
265
+ function compatGate(api) {
266
+ return COMPAT_GATES[api];
267
+ }
268
+ function configuredCompatEntries(compat) {
269
+ return Object.entries(compat ?? {}).flatMap(([field, value]) => {
270
+ const empty = typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
271
+ return empty ? [] : [[field, value]];
272
+ });
273
+ }
274
+ function compatProtocols(field) {
275
+ return Object.entries(COMPAT_GATES).flatMap(([api, gate]) => gate[field] === "offer" ? [api] : []);
276
+ }
277
+ function offeredCompatFields(api) {
278
+ return Object.entries(compatGate(api) ?? {}).flatMap(([field, disposition]) => disposition === "offer" ? [field] : []);
279
+ }
280
+ function allOfferedCompatFields() {
281
+ const fields = /* @__PURE__ */ new Set();
282
+ for (const api of Object.keys(COMPAT_GATES)) {
283
+ for (const field of offeredCompatFields(api)) fields.add(field);
284
+ }
285
+ return [...fields];
286
+ }
287
+ function assertOfferedCompatFields(provider, site, compat) {
288
+ for (const [field, value] of Object.entries(compat ?? {})) {
289
+ if (compatProtocols(field).length === 0) {
290
+ const declared = Object.values(COMPAT_GATES).some((gate) => gate[field] !== void 0);
291
+ if (declared) {
292
+ invalid(provider, `${site} sets compat "${field}", which is not configurable here: pi-ai's installed catalog sets it for the vendors that need it, so name that provider as the route instead`);
293
+ }
294
+ invalid(provider, `${site} sets compat "${field}", which no wire protocol declares; the configurable switches are ${allOfferedCompatFields().join(", ")}`);
295
+ }
296
+ if (value == null) {
297
+ invalid(provider, `${site} sets compat "${field}" with no value; give it one, or remove the key to leave the field to the next layer \u2014 the installed catalog entry, then pi-ai's own detection`);
298
+ }
299
+ }
300
+ }
301
+ var PiAiCatalogError = class extends Error {
302
+ };
303
+ function invalid(provider, detail) {
304
+ throw new PiAiCatalogError(`llm-pi-ai: provider "${provider}" ${detail}`);
305
+ }
306
+ function sharedCatalogApi(defaults) {
307
+ const apis = /* @__PURE__ */ new Set();
308
+ for (const model of defaults.values()) apis.add(model.api);
309
+ return apis.size === 1 ? [...apis][0] : void 0;
310
+ }
311
+ function resolveModelReasoning(provider, entry, base) {
312
+ const efforts = entry.reasoningEfforts;
313
+ if (efforts === void 0) {
314
+ return { reasoning: base?.reasoning ?? false };
315
+ }
316
+ if (efforts === false) return { reasoning: false };
317
+ if (efforts === null || Object.keys(efforts).length === 0) {
318
+ invalid(provider, `model "${entry.id}" has an empty reasoningEfforts; declare the offered levels, set false for a non-reasoning model, or omit the field to keep the installed catalog's capability`);
319
+ }
320
+ const declared = THINKING_LEVELS.flatMap((level) => {
321
+ const wire = efforts[level];
322
+ return wire === void 0 ? [] : [[level, wire]];
323
+ });
324
+ for (const [level, wire] of declared) {
325
+ if (wire === null) {
326
+ if (level !== "off") {
327
+ invalid(provider, `model "${entry.id}" reasoningEfforts.${level} needs the wire value dispatch should send; only "off" may leave it empty`);
328
+ }
329
+ } else if (wire.length === 0) {
330
+ invalid(provider, `model "${entry.id}" reasoningEfforts.${level} must not be an empty string`);
331
+ }
332
+ }
333
+ if (!declared.some(([level]) => level !== "off")) {
334
+ invalid(provider, `model "${entry.id}" reasoningEfforts offers no level beyond "off"; declare a thinking level, or set reasoningEfforts to false for a non-reasoning model`);
335
+ }
336
+ const map = {};
337
+ for (const level of THINKING_LEVELS) {
338
+ const wire = efforts[level];
339
+ if (wire === void 0) {
340
+ map[level] = null;
341
+ } else if (wire !== null) {
342
+ map[level] = wire;
343
+ }
344
+ }
345
+ return { reasoning: true, thinkingLevelMap: map };
346
+ }
347
+ function resolveModelCompat(provider, entry, route, base, api) {
348
+ const gate = compatGate(api);
349
+ const configured = {};
350
+ for (const [field, value] of configuredCompatEntries(route)) {
351
+ if (gate?.[field] !== "offer") continue;
352
+ configured[field] = value;
353
+ }
354
+ for (const [field, value] of configuredCompatEntries(entry.compat)) {
355
+ if (gate?.[field] !== "offer") {
356
+ const offered = offeredCompatFields(api);
357
+ invalid(provider, `model "${entry.id}" sets compat "${field}", but its api is "${api}", which does not take it; that switch exists on ${compatProtocols(field).join(", ")}, and "${api}" offers ${offered.length === 0 ? "no configurable compat" : offered.join(", ")}`);
358
+ }
359
+ configured[field] = value;
360
+ }
361
+ if (Object.keys(configured).length === 0) return {};
362
+ const inherited = base?.api === api ? base.compat : void 0;
363
+ return { compat: { ...inherited, ...configured } };
364
+ }
365
+ function resolveRouteModels(request, validation = "strict") {
366
+ const { provider } = request;
367
+ const defaults = catalogModels(provider);
368
+ const providerBaseUrl = catalogProvider(provider)?.baseUrl;
369
+ const configured = request.models ?? [];
370
+ const overrides = request.modelOverrides ?? {};
371
+ const modelErrors = /* @__PURE__ */ new Map();
372
+ for (const [id, override] of Object.entries(overrides)) {
373
+ if (id.length === 0) invalid(provider, "has a modelOverrides entry with an empty model id");
374
+ if (defaults.size === 0) {
375
+ invalid(provider, `sets modelOverrides for "${id}", but the installed catalog does not describe this route; a declared route spells every model out in its models list`);
376
+ }
377
+ if (configured.length > 0) {
378
+ invalid(provider, `sets modelOverrides for "${id}" beside a models list; models already replaces the served catalog, so declare the fields on its entries`);
379
+ }
380
+ if (!defaults.has(id)) {
381
+ const message = `modelOverrides names "${id}", which the installed catalog does not describe`;
382
+ if (validation === "strict") invalid(provider, message);
383
+ modelErrors.set(id, `llm-pi-ai: provider "${provider}" ${message}`);
384
+ }
385
+ if ("id" in override) {
386
+ invalid(provider, `modelOverrides entry "${id}" sets "id", which is the dict key`);
387
+ }
388
+ }
389
+ const entries = configured.length > 0 ? configured : [...defaults.values()].map((model) => ({ id: model.id, ...overrides[model.id] }));
390
+ if (entries.length === 0) {
391
+ invalid(provider, "resolves no models; the installed catalog does not describe this route, so its models must be listed in configuration");
392
+ }
393
+ const routeApi = sharedCatalogApi(defaults);
394
+ assertOfferedCompatFields(provider, "route", request.compat);
395
+ const seen = /* @__PURE__ */ new Set();
396
+ const configuredMaxTokens = /* @__PURE__ */ new Map();
397
+ const resolveEntry = (entry) => {
398
+ assertOfferedCompatFields(provider, `model "${entry.id}"`, entry.compat);
399
+ if (entry.id.length === 0) invalid(provider, "has a model with an empty id");
400
+ if (seen.has(entry.id)) invalid(provider, `lists model "${entry.id}" more than once`);
401
+ seen.add(entry.id);
402
+ const base = defaults.get(entry.id);
403
+ const api = request.api ?? base?.api ?? routeApi;
404
+ if (api === void 0) {
405
+ invalid(provider, `model "${entry.id}" needs an api; the installed catalog does not describe it, so set the route's api to the wire protocol its endpoint speaks`);
406
+ }
407
+ const baseUrl = request.baseURL ?? base?.baseUrl ?? providerBaseUrl;
408
+ if (baseUrl === void 0) {
409
+ invalid(provider, `model "${entry.id}" needs a baseURL; the installed catalog does not describe this route`);
410
+ }
411
+ const contextWindow = entry.contextWindow ?? base?.contextWindow ?? request.defaultContextWindow;
412
+ if (!Number.isInteger(contextWindow) || contextWindow <= 0) {
413
+ invalid(provider, `model "${entry.id}" contextWindow must be a positive integer`);
414
+ }
415
+ const maxTokens = entry.maxTokens ?? base?.maxTokens ?? request.defaultMaxTokens;
416
+ if (!Number.isInteger(maxTokens) || maxTokens <= 0) {
417
+ invalid(provider, `model "${entry.id}" maxTokens must be a positive integer`);
418
+ }
419
+ if (entry.maxTokens !== void 0) configuredMaxTokens.set(entry.id, entry.maxTokens);
420
+ return {
421
+ // The installed entry lays the floor, and the fields below override it.
422
+ // Enumerating instead would silently drop every `Model` field this
423
+ // package does not model — reasoning-level spellings, compatibility
424
+ // quirks, model headers, and whatever a pi-ai upgrade adds next. Spread,
425
+ // never enumerate.
426
+ ...base,
427
+ id: entry.id,
428
+ name: entry.name ?? base?.name ?? entry.id,
429
+ api,
430
+ provider,
431
+ baseUrl,
432
+ input: declaredInput(entry.input) ?? base?.input ?? [...request.defaultInput],
433
+ cost: base?.cost ?? NO_COST,
434
+ contextWindow,
435
+ maxTokens,
436
+ ...resolveModelReasoning(provider, entry, base),
437
+ ...resolveModelCompat(provider, entry, request.compat, base, api)
438
+ };
439
+ };
440
+ const models = [];
441
+ for (const entry of entries) {
442
+ let model;
443
+ try {
444
+ model = resolveEntry(entry);
445
+ } catch (error) {
446
+ if (validation === "strict" || !(error instanceof PiAiCatalogError)) throw error;
447
+ modelErrors.set(entry.id, error.message);
448
+ continue;
449
+ }
450
+ models.push(model);
451
+ }
452
+ const serviceableModels = models.filter((model) => !modelErrors.has(model.id));
453
+ for (const [field] of configuredCompatEntries(request.compat)) {
454
+ const takers = compatProtocols(field);
455
+ if (serviceableModels.some((model) => takers.includes(model.api))) continue;
456
+ invalid(provider, `sets compat "${field}", but no model on the route speaks a protocol that takes it; it exists on ${takers.join(", ")}`);
457
+ }
458
+ return { models: serviceableModels, configuredMaxTokens, modelErrors };
459
+ }
460
+
461
+ // dsh/vendor/dsh-llm-pi-ai/src/provider.ts
462
+ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
463
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
464
+ import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
465
+
466
+ // dsh/vendor/dsh-llm-pi-ai/src/models.ts
467
+ import { builtinModels } from "@earendil-works/pi-ai/providers/all";
468
+ function createModels(options) {
469
+ const models = builtinModels(options);
470
+ models.clearProviders();
471
+ return models;
472
+ }
473
+ function createProvider(input) {
474
+ return {
475
+ id: input.id,
476
+ name: input.name,
477
+ ...input.baseUrl === void 0 ? {} : { baseUrl: input.baseUrl },
478
+ auth: input.auth,
479
+ getModels: () => input.models,
480
+ stream: (model, context, options) => input.api.stream(model, context, options),
481
+ streamSimple: (model, context, options) => input.api.streamSimple(model, context, options)
482
+ };
483
+ }
484
+
485
+ // dsh/vendor/dsh-llm-pi-ai/src/provider.ts
486
+ var PROTOCOLS = {
487
+ "openai-completions": openAICompletionsApi,
488
+ "openai-responses": openAIResponsesApi,
489
+ "anthropic-messages": anthropicMessagesApi
490
+ };
491
+ function supportedProtocols() {
492
+ return Object.keys(PROTOCOLS);
493
+ }
494
+ function harnessApiKeyAuth(name2) {
495
+ return {
496
+ name: name2,
497
+ resolve: ({ credential }) => Promise.resolve({
498
+ auth: credential?.key === void 0 ? {} : { apiKey: credential.key },
499
+ source: name2
500
+ })
501
+ };
502
+ }
503
+ function routeAuth(spec, catalog) {
504
+ if (catalog === void 0) return { apiKey: harnessApiKeyAuth(spec.displayName) };
505
+ if (catalog.auth.apiKey !== void 0 || !spec.namesCredential) return catalog.auth;
506
+ return { ...catalog.auth, apiKey: harnessApiKeyAuth(spec.displayName) };
507
+ }
508
+ function reuseCatalogProvider(base, spec) {
509
+ const baseUrl = spec.baseURL ?? base.baseUrl;
510
+ return {
511
+ id: spec.provider,
512
+ name: spec.displayName,
513
+ ...baseUrl === void 0 ? {} : { baseUrl },
514
+ auth: routeAuth(spec, base),
515
+ getModels: () => spec.models,
516
+ // Delegated rather than copied: the catalog provider stays the receiver, so
517
+ // an implementation holding state on itself keeps working.
518
+ stream: (model, context, options) => base.stream(model, context, options),
519
+ streamSimple: (model, context, options) => base.streamSimple(model, context, options)
520
+ };
521
+ }
522
+ function buildProvider(spec) {
523
+ const catalog = catalogProvider(spec.provider);
524
+ if (catalog !== void 0 && spec.api === void 0) return reuseCatalogProvider(catalog, spec);
525
+ const factory = spec.api === void 0 ? void 0 : PROTOCOLS[spec.api];
526
+ if (factory === void 0) {
527
+ throw new PiAiCatalogError(
528
+ `llm-pi-ai: provider "${spec.provider}" names api "${spec.api}", which this build cannot serve; supported protocols are ${supportedProtocols().join(", ")}`
529
+ );
530
+ }
531
+ return createProvider({
532
+ id: spec.provider,
533
+ name: spec.displayName,
534
+ ...spec.baseURL === void 0 ? {} : { baseUrl: spec.baseURL },
535
+ auth: routeAuth(spec, catalog),
536
+ models: spec.models,
537
+ api: factory()
538
+ });
539
+ }
540
+
541
+ // dsh/vendor/dsh-llm-pi-ai/src/config.ts
542
+ var DEFAULT_STREAM_IDLE_TIMEOUT_MS = 3e5;
543
+ var DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
544
+ var DEFAULT_MAX_REQUEST_IMAGES = 50;
545
+ var DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM = 10;
546
+ var DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
547
+ var DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
548
+ var DEFAULT_CONTEXT_WINDOW = 1e6;
549
+ var DEFAULT_MAX_TOKENS = 128e3;
550
+ var DEFAULT_INPUT = ["text"];
551
+ var thinkingBudgets = z.object({
552
+ minimal: z.number(),
553
+ low: z.number(),
554
+ medium: z.number(),
555
+ high: z.number()
556
+ });
557
+ var chatTemplateKwarg = z.union([
558
+ z.string(),
559
+ z.number(),
560
+ z.boolean(),
561
+ z.const(null),
562
+ z.object({
563
+ $var: z.union(CHAT_TEMPLATE_VARS).required(),
564
+ omitWhenOff: z.boolean()
565
+ })
566
+ ]);
567
+ var compatProfile = z.object({
568
+ supportsStore: z.boolean(),
569
+ supportsDeveloperRole: z.boolean(),
570
+ supportsReasoningEffort: z.boolean(),
571
+ supportsUsageInStreaming: z.boolean(),
572
+ supportsFinishReason: z.boolean(),
573
+ maxTokensField: z.union(MAX_TOKENS_FIELDS),
574
+ requiresToolResultName: z.boolean(),
575
+ requiresAssistantAfterToolResult: z.boolean(),
576
+ requiresThinkingAsText: z.boolean(),
577
+ requiresReasoningContentOnAssistantMessages: z.boolean(),
578
+ thinkingFormat: z.union(SUPPORTED_THINKING_FORMATS),
579
+ chatTemplateKwargs: z.dict(chatTemplateKwarg),
580
+ chatTemplateArgs: z.dict(chatTemplateKwarg),
581
+ supportsThinkingTokenBudget: z.boolean(),
582
+ thinkingTokenBudgetField: z.union(THINKING_TOKEN_BUDGET_FIELDS),
583
+ vllmPriority: z.number().step(1),
584
+ supportsMaxOutputTokens: z.boolean(),
585
+ supportsStrictMode: z.boolean(),
586
+ cacheControlFormat: z.union(CACHE_CONTROL_FORMATS),
587
+ supportsLongCacheRetention: z.boolean(),
588
+ supportsExplicitPromptCacheMode: z.boolean(),
589
+ supportsEagerToolInputStreaming: z.boolean(),
590
+ supportsCacheControlOnTools: z.boolean(),
591
+ supportsTemperature: z.boolean(),
592
+ forceAdaptiveThinking: z.boolean(),
593
+ allowEmptySignature: z.boolean(),
594
+ supportsStrictTools: z.boolean()
595
+ });
596
+ var reasoningEfforts = z.dict(
597
+ z.union([z.string(), z.const(null)]),
598
+ z.union(THINKING_LEVELS)
599
+ );
600
+ var modelFields = {
601
+ name: z.string(),
602
+ contextWindow: z.number().step(1).min(1),
603
+ maxTokens: z.number().step(1).min(1),
604
+ // No explicit default, unlike the route's `defaultInput`: schemastery
605
+ // materializes `[]` for an absent array, and resolution reads that as "no
606
+ // answer here" so the catalog entry below still applies.
607
+ input: z.array(z.union(MODALITIES)),
608
+ // The union, not a bare dict: schemastery materializes an absent dict as
609
+ // `{}`, and absent must stay distinguishable — it means "inherit the
610
+ // installed catalog's capability", while `false` disables reasoning.
611
+ reasoningEfforts: z.union([z.const(false), reasoningEfforts]),
612
+ compat: compatProfile
613
+ };
614
+ var modelProfile = z.object({
615
+ id: z.string().required(),
616
+ ...modelFields
617
+ });
618
+ var modelOverride = z.object(modelFields);
619
+ var profile = z.object({
620
+ apiKeyEnv: z.string().role("credential-ref"),
621
+ displayName: z.string(),
622
+ api: z.union(supportedProtocols()),
623
+ baseURL: z.string(),
624
+ models: z.array(modelProfile),
625
+ modelOverrides: z.dict(modelOverride),
626
+ compat: compatProfile,
627
+ defaultContextWindow: z.number().step(1).min(1).default(DEFAULT_CONTEXT_WINDOW),
628
+ defaultMaxTokens: z.number().step(1).min(1).default(DEFAULT_MAX_TOKENS),
629
+ defaultInput: z.array(z.union(MODALITIES)).default([...DEFAULT_INPUT]),
630
+ headers: z.dict(z.string()),
631
+ reasoning: z.union(THINKING_LEVELS),
632
+ thinkingBudgets,
633
+ cacheRetention: z.union(["none", "short", "long"]),
634
+ transport: z.union(["sse", "websocket", "websocket-cached", "auto"]),
635
+ timeoutMs: z.natural(),
636
+ websocketConnectTimeoutMs: z.natural(),
637
+ streamIdleTimeoutMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_STREAM_IDLE_TIMEOUT_MS),
638
+ maxRequestImageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES),
639
+ maxRequestImages: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGES),
640
+ imageOffloadCountQuantum: z.number().step(1).min(1),
641
+ requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET),
642
+ requestImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_MAX_BYTES),
643
+ retryPolicy: RetryPolicySchema
644
+ });
645
+ var Config = z.object({
646
+ providers: z.dict(profile).default({}).volatile()
647
+ });
648
+ function assertServiceable(config, previous) {
649
+ const changed = Object.fromEntries(Object.entries(config.providers ?? {}).filter(([provider, profile2]) => !deepEqualJson(profile2, previous?.providers?.[provider])));
650
+ resolveProfiles(changed);
651
+ }
652
+ function rejectRemovedFields(provider, source) {
653
+ const legacy = source;
654
+ if ("provider" in legacy) {
655
+ throw new Error(`llm-pi-ai: provider "${provider}" sets "provider", which moved to the providers dict key`);
656
+ }
657
+ if ("maxRetries" in legacy || "maxRetryDelayMs" in legacy) {
658
+ throw new Error(
659
+ `llm-pi-ai: provider "${provider}" sets maxRetries or maxRetryDelayMs, which were removed; compose agent recovery with dsh-llm-retry`
660
+ );
661
+ }
662
+ }
663
+ function assertValidHeaders(provider, headers) {
664
+ for (const [name2, value] of Object.entries(headers ?? {})) {
665
+ try {
666
+ new Headers([[name2, value]]);
667
+ } catch {
668
+ throw new Error(
669
+ `llm-pi-ai: provider "${provider}" header "${name2}" is not valid for Fetch; use a valid HTTP field name and a single-line value representable as bytes`
670
+ );
671
+ }
672
+ }
673
+ }
674
+ function resolveProfiles(providers, validation = "strict") {
675
+ if (Array.isArray(providers)) {
676
+ throw new Error("llm-pi-ai: providers is now a dict keyed by provider route, not an array of profiles");
677
+ }
678
+ const entries = Object.entries(providers ?? {});
679
+ const resolved = /* @__PURE__ */ new Map();
680
+ for (const [provider, source] of entries) {
681
+ rejectRemovedFields(provider, source);
682
+ if (provider.length === 0) throw new Error("llm-pi-ai: provider names must be non-empty");
683
+ if (source.baseURL !== void 0 && source.baseURL.length === 0) {
684
+ throw new Error(`llm-pi-ai: provider "${provider}" has an empty baseURL`);
685
+ }
686
+ if (source.displayName !== void 0 && source.displayName.length === 0) {
687
+ throw new Error(`llm-pi-ai: provider "${provider}" has an empty displayName`);
688
+ }
689
+ assertValidHeaders(provider, source.headers);
690
+ const streamIdleTimeoutMs = source.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS;
691
+ if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0 || streamIdleTimeoutMs > MAX_TIMER_DELAY_MS) {
692
+ throw new Error(
693
+ `llm-pi-ai: provider "${provider}" streamIdleTimeoutMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`
694
+ );
695
+ }
696
+ const maxRequestImageBytes = source.maxRequestImageBytes ?? DEFAULT_MAX_REQUEST_IMAGE_BYTES;
697
+ if (!Number.isInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) {
698
+ throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`);
699
+ }
700
+ const maxRequestImages = source.maxRequestImages ?? DEFAULT_MAX_REQUEST_IMAGES;
701
+ if (!Number.isSafeInteger(maxRequestImages) || maxRequestImages <= 0) {
702
+ throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImages must be a positive safe integer`);
703
+ }
704
+ const imageOffloadCountQuantum = source.imageOffloadCountQuantum ?? Math.min(DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, maxRequestImages);
705
+ if (!Number.isSafeInteger(imageOffloadCountQuantum) || imageOffloadCountQuantum <= 0 || imageOffloadCountQuantum > maxRequestImages) {
706
+ throw new Error(`llm-pi-ai: provider "${provider}" imageOffloadCountQuantum must be a positive safe integer no greater than maxRequestImages`);
707
+ }
708
+ const requestImagePixelBudget = source.requestImagePixelBudget ?? DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET;
709
+ if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) {
710
+ throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`);
711
+ }
712
+ const requestImageMaxBytes = source.requestImageMaxBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES;
713
+ if (!Number.isSafeInteger(requestImageMaxBytes) || requestImageMaxBytes <= 0) {
714
+ throw new Error(`llm-pi-ai: provider "${provider}" requestImageMaxBytes must be a positive safe integer`);
715
+ }
716
+ const defaultInput = [...source.defaultInput ?? DEFAULT_INPUT];
717
+ if (defaultInput.length === 0) {
718
+ throw new Error(`llm-pi-ai: provider "${provider}" defaultInput must name at least one modality`);
719
+ }
720
+ const displayName = source.displayName ?? provider;
721
+ let catalog;
722
+ let piProvider;
723
+ let catalogError;
724
+ try {
725
+ catalog = resolveRouteModels({
726
+ provider,
727
+ ...source.api === void 0 ? {} : { api: source.api },
728
+ ...source.baseURL === void 0 ? {} : { baseURL: source.baseURL },
729
+ ...source.models === void 0 ? {} : { models: source.models },
730
+ ...source.modelOverrides === void 0 ? {} : { modelOverrides: source.modelOverrides },
731
+ ...source.compat === void 0 ? {} : { compat: source.compat },
732
+ defaultInput,
733
+ defaultContextWindow: source.defaultContextWindow ?? DEFAULT_CONTEXT_WINDOW,
734
+ defaultMaxTokens: source.defaultMaxTokens ?? DEFAULT_MAX_TOKENS
735
+ }, validation);
736
+ catalogError = catalog.modelErrors.values().next().value;
737
+ piProvider = buildProvider({
738
+ provider,
739
+ displayName,
740
+ ...source.api === void 0 ? {} : { api: source.api },
741
+ ...source.baseURL === void 0 ? {} : { baseURL: source.baseURL },
742
+ models: catalog.models,
743
+ namesCredential: source.apiKeyEnv !== void 0
744
+ });
745
+ } catch (error) {
746
+ if (validation === "strict" || !(error instanceof PiAiCatalogError)) throw error;
747
+ catalogError ??= error.message;
748
+ }
749
+ const { apiKeyEnv, retryPolicy, models: _models, displayName: _displayName, ...rest } = source;
750
+ resolved.set(provider, {
751
+ ...rest,
752
+ provider,
753
+ displayName,
754
+ ...apiKeyEnv === void 0 ? {} : { apiKeyEnv: credentialRef(apiKeyEnv) },
755
+ streamIdleTimeoutMs,
756
+ maxRequestImageBytes,
757
+ maxRequestImages,
758
+ imageOffloadCountQuantum,
759
+ requestImagePixelBudget,
760
+ requestImageMaxBytes,
761
+ retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`),
762
+ ...rest.headers === void 0 ? {} : { headers: { ...rest.headers } },
763
+ ...rest.thinkingBudgets === void 0 ? {} : { thinkingBudgets: { ...rest.thinkingBudgets } },
764
+ configuredMaxTokens: catalog?.configuredMaxTokens ?? /* @__PURE__ */ new Map(),
765
+ modelErrors: catalog?.modelErrors ?? /* @__PURE__ */ new Map(),
766
+ ...piProvider === void 0 ? {} : { piProvider },
767
+ ...catalogError === void 0 ? {} : { catalogError }
768
+ });
769
+ }
770
+ return resolved;
771
+ }
772
+
773
+ // dsh/vendor/dsh-llm-pi-ai/src/index.ts
774
+ import { launchEnvironmentOf as launchEnvironmentOf2 } from "@deepseek-ai/dsh-launch-environment";
775
+ import { assertUsableApiKey, LlmError as LlmError3, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
776
+ import { deepEqualJson as deepEqualJson2 } from "@deepseek-ai/dsh-util-values";
777
+ import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
778
+
779
+ // dsh/vendor/dsh-llm-pi-ai/src/auth.ts
780
+ import { homedir } from "node:os";
781
+ import { access } from "node:fs/promises";
782
+ import { resolve as resolvePath } from "node:path";
783
+ import {
784
+ credentialKey,
785
+ credentialKeyId,
786
+ credentialKeyScope,
787
+ credentialRef as credentialRef2,
788
+ isCredentialKeySegment,
789
+ isCredentialRefName
790
+ } from "@deepseek-ai/dsh-credentials";
791
+ import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
792
+ import { LlmError } from "@deepseek-ai/dsh-llm";
793
+ var RECORD_SCOPE = "llm-pi-ai";
794
+ function recordKeyFor(providerId) {
795
+ return credentialKey(RECORD_SCOPE, providerId);
796
+ }
797
+ function jsonImage(value) {
798
+ if (Array.isArray(value)) return value.map((entry) => entry === void 0 ? null : jsonImage(entry));
799
+ if (typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
800
+ const image = {};
801
+ for (const [key, member] of Object.entries(value)) {
802
+ if (member !== void 0) image[key] = jsonImage(member);
803
+ }
804
+ return image;
805
+ }
806
+ return value;
807
+ }
808
+ function toPiCredential(record) {
809
+ if (record === void 0) return void 0;
810
+ if (record.kind === "api-key") {
811
+ return {
812
+ type: "api_key",
813
+ ...record.key === void 0 ? {} : { key: record.key },
814
+ ...record.env === void 0 ? {} : { env: { ...record.env } }
815
+ };
816
+ }
817
+ return record.payload;
818
+ }
819
+ function toRecord(credential) {
820
+ if (credential.type === "api_key") {
821
+ return {
822
+ kind: "api-key",
823
+ ...credential.key === void 0 ? {} : { key: credential.key },
824
+ ...credential.env === void 0 ? {} : { env: { ...credential.env } }
825
+ };
826
+ }
827
+ return { kind: "grant", payload: jsonImage(credential) };
828
+ }
829
+ function writableStore(ctx) {
830
+ const credentials = ctx.get("credentials");
831
+ if (credentials === void 0) {
832
+ throw new LlmError(
833
+ "llm-pi-ai: this composition mounts no credentials service, so there is nowhere to store the credential a sign-in produces; mount one (dsh-credentials-local) to sign in",
834
+ "NO_CREDENTIAL_STORE"
835
+ );
836
+ }
837
+ return credentials;
838
+ }
839
+ function credentialStoreFrom(ctx) {
840
+ return {
841
+ async read(providerId) {
842
+ const credentials = ctx.get("credentials");
843
+ if (credentials === void 0) return void 0;
844
+ if (!isCredentialKeySegment(providerId)) return void 0;
845
+ return toPiCredential(await credentials.readRecord(recordKeyFor(providerId)));
846
+ },
847
+ async list() {
848
+ const stored = await ctx.get("credentials")?.listRecords() ?? [];
849
+ const mine = [];
850
+ for (const entry of stored) {
851
+ if (credentialKeyScope(entry.key) !== RECORD_SCOPE) continue;
852
+ mine.push({
853
+ providerId: credentialKeyId(entry.key),
854
+ type: entry.kind === "api-key" ? "api_key" : "oauth"
855
+ });
856
+ }
857
+ return mine;
858
+ },
859
+ async modify(providerId, mutate) {
860
+ if (!isCredentialKeySegment(providerId)) {
861
+ throw new LlmError(
862
+ `llm-pi-ai: provider id "${providerId}" cannot address a stored credential record (a record id is a lowercase hyphenated identifier); authenticate this route through apiKeyEnv instead of a stored credential`,
863
+ "UNSTORABLE_PROVIDER_ID"
864
+ );
865
+ }
866
+ const stored = await writableStore(ctx).modifyRecord(recordKeyFor(providerId), async (current) => {
867
+ const next = await mutate(toPiCredential(current));
868
+ return next === void 0 ? void 0 : toRecord(next);
869
+ });
870
+ return toPiCredential(stored);
871
+ },
872
+ // `async` so a missing service reaches the caller as a rejection: pi-ai's
873
+ // store contract is promise-returning, and a synchronous throw would
874
+ // escape the `ModelsError` wrapper every other storage failure gets.
875
+ async delete(providerId) {
876
+ if (!isCredentialKeySegment(providerId)) return;
877
+ await writableStore(ctx).deleteRecord(recordKeyFor(providerId));
878
+ }
879
+ };
880
+ }
881
+ function authContextFrom(ctx) {
882
+ return {
883
+ async env(name2) {
884
+ if (isCredentialRefName(name2)) {
885
+ const credentials = ctx.get("credentials");
886
+ const hit = await credentials?.resolve(credentialRef2(name2));
887
+ if (hit !== void 0) return hit.value;
888
+ }
889
+ return launchEnvironmentOf(ctx).get(name2)?.value;
890
+ },
891
+ async fileExists(path) {
892
+ const expanded = path.startsWith("~/") || path === "~" ? resolvePath(homedir(), path.slice(1).replace(/^\//, "")) : path;
893
+ try {
894
+ await access(expanded);
895
+ return true;
896
+ } catch {
897
+ return false;
898
+ }
899
+ }
900
+ };
901
+ }
902
+
903
+ // dsh/vendor/dsh-llm-pi-ai/src/discovery.ts
904
+ import { INVALID_CREDENTIAL_CODE, LlmError as LlmError2, normalizeApiKey } from "@deepseek-ai/dsh-llm";
905
+ import { attributionHeaders } from "@deepseek-ai/dsh-llm";
906
+ var LISTABLE_PROTOCOLS = /* @__PURE__ */ new Set([
907
+ "anthropic-messages",
908
+ "openai-completions",
909
+ "openai-responses"
910
+ ]);
911
+ var ANTHROPIC_VERSION = "2023-06-01";
912
+ var ANTHROPIC_MODEL_LIMIT = 1e3;
913
+ var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
914
+ function capacity(...candidates) {
915
+ for (const candidate of candidates) {
916
+ if (typeof candidate === "number" && Number.isInteger(candidate) && candidate > 0) return candidate;
917
+ }
918
+ return void 0;
919
+ }
920
+ function label(...candidates) {
921
+ for (const candidate of candidates) {
922
+ if (typeof candidate === "string" && candidate.length > 0) return candidate;
923
+ }
924
+ return void 0;
925
+ }
926
+ function listingUrl(baseURL, api) {
927
+ const base = baseURL.replace(/\/+$/, "");
928
+ if (api !== "anthropic-messages") return `${base}/models`;
929
+ const root = base.endsWith("/v1") ? base.slice(0, -3) : base;
930
+ return `${root}/v1/models?limit=${String(ANTHROPIC_MODEL_LIMIT)}`;
931
+ }
932
+ async function readBounded(response, url) {
933
+ const oversized = () => new LlmError2(`${url} answered with more than ${MAX_RESPONSE_BYTES} bytes`, "DISCOVERY_FAILED");
934
+ const declared = Number(response.headers.get("content-length") ?? Number.NaN);
935
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
936
+ await response.body?.cancel();
937
+ throw oversized();
938
+ }
939
+ if (response.body === null) return "";
940
+ const reader = response.body.getReader();
941
+ const chunks = [];
942
+ let total = 0;
943
+ try {
944
+ for (; ; ) {
945
+ const { done, value } = await reader.read();
946
+ if (done) break;
947
+ total += value.byteLength;
948
+ if (total > MAX_RESPONSE_BYTES) throw oversized();
949
+ chunks.push(value);
950
+ }
951
+ } finally {
952
+ await reader.cancel().catch(() => {
953
+ });
954
+ }
955
+ const body = new Uint8Array(total);
956
+ let offset = 0;
957
+ for (const chunk of chunks) {
958
+ body.set(chunk, offset);
959
+ offset += chunk.byteLength;
960
+ }
961
+ return new TextDecoder().decode(body);
962
+ }
963
+ function readListing(body) {
964
+ const listing = body;
965
+ const data = listing?.data;
966
+ let listed;
967
+ if (Array.isArray(data)) {
968
+ const rows = data;
969
+ listed = rows.map((raw) => ({ raw }));
970
+ } else {
971
+ const models2 = listing?.models;
972
+ if (models2 === null || typeof models2 !== "object" || Array.isArray(models2)) {
973
+ throw new LlmError2(
974
+ `the endpoint's model listing has neither a "data" array nor a "models" object; enter this provider's models by hand`,
975
+ "DISCOVERY_FAILED"
976
+ );
977
+ }
978
+ listed = Object.entries(models2).filter(([, raw]) => raw !== null && typeof raw === "object" && !Array.isArray(raw)).map(([key, raw]) => ({ key, raw }));
979
+ }
980
+ const models = [];
981
+ for (const { key, raw } of listed) {
982
+ const entry = raw;
983
+ const id = label(key, entry?.id);
984
+ if (id === void 0) continue;
985
+ const name2 = label(entry?.name, entry?.display_name, entry?.displayName) ?? id;
986
+ const contextWindow = capacity(
987
+ entry?.contextWindow,
988
+ entry?.context_window,
989
+ entry?.context_length,
990
+ entry?.max_input_tokens,
991
+ entry?.limit?.context
992
+ );
993
+ const maxTokens = capacity(
994
+ entry?.maxOutputTokens,
995
+ entry?.max_output_tokens,
996
+ entry?.maxTokens,
997
+ entry?.max_tokens,
998
+ entry?.limit?.output,
999
+ entry?.top_provider?.max_completion_tokens
1000
+ );
1001
+ models.push({
1002
+ id,
1003
+ name: name2,
1004
+ ...contextWindow === void 0 ? {} : { contextWindow },
1005
+ ...maxTokens === void 0 ? {} : { maxTokens }
1006
+ });
1007
+ }
1008
+ return models;
1009
+ }
1010
+ function usableProbeKey(raw) {
1011
+ const checked = normalizeApiKey(raw);
1012
+ if (checked.ok) return checked.value;
1013
+ throw new LlmError2(
1014
+ checked.reason === "empty" ? "this provider's API key is blank; enter it on the Models page, or clear it to probe unauthenticated" : "this provider's API key contains characters no HTTP header can carry; paste the raw key only",
1015
+ INVALID_CREDENTIAL_CODE
1016
+ );
1017
+ }
1018
+ async function discoverModels(request, storedProfile) {
1019
+ if (request.provider !== void 0) {
1020
+ const installed = catalogModels(request.provider);
1021
+ if (installed.size > 0) {
1022
+ return [...installed.values()].map((model) => ({
1023
+ id: model.id,
1024
+ name: model.name,
1025
+ contextWindow: model.contextWindow,
1026
+ maxTokens: model.maxTokens,
1027
+ inputModalities: [...model.input]
1028
+ }));
1029
+ }
1030
+ }
1031
+ if (request.baseURL === void 0 || request.baseURL.length === 0) {
1032
+ throw new LlmError2(
1033
+ `pi-ai ships no catalog for provider "${request.provider ?? ""}", so its models can only come from its endpoint; set a baseURL, or enter this provider's models by hand`,
1034
+ "DISCOVERY_FAILED"
1035
+ );
1036
+ }
1037
+ const api = request.api ?? "openai-completions";
1038
+ if (!LISTABLE_PROTOCOLS.has(api)) {
1039
+ throw new LlmError2(
1040
+ `pi-ai protocol "${api}" has no model listing this build can read; enter this provider's models by hand`,
1041
+ "DISCOVERY_UNSUPPORTED"
1042
+ );
1043
+ }
1044
+ const url = listingUrl(request.baseURL, api);
1045
+ const stored = storedProfile?.();
1046
+ const supplied = request.apiKey ?? await stored?.resolveApiKey();
1047
+ const apiKey = supplied === void 0 ? void 0 : usableProbeKey(supplied);
1048
+ let response;
1049
+ try {
1050
+ const headers = new Headers(stored?.headers === void 0 ? void 0 : Object.entries(stored.headers));
1051
+ headers.set("accept", "application/json");
1052
+ if (api === "anthropic-messages") {
1053
+ headers.set("anthropic-version", ANTHROPIC_VERSION);
1054
+ if (apiKey !== void 0) headers.set("x-api-key", apiKey);
1055
+ } else if (apiKey !== void 0) {
1056
+ headers.set("authorization", `Bearer ${apiKey}`);
1057
+ }
1058
+ for (const [name2, value] of Object.entries(attributionHeaders())) headers.set(name2, value);
1059
+ response = await fetch(url, {
1060
+ method: "GET",
1061
+ headers,
1062
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1063
+ });
1064
+ } catch (error) {
1065
+ if (request.signal?.aborted) {
1066
+ throw new LlmError2("model discovery aborted by caller", "ABORTED", { cause: error });
1067
+ }
1068
+ throw new LlmError2(`could not reach ${url}`, "DISCOVERY_FAILED", { cause: error });
1069
+ }
1070
+ if (!response.ok) {
1071
+ throw new LlmError2(
1072
+ `${url} answered ${response.status}${response.status === 401 || response.status === 403 ? "; check the API key" : ""}`,
1073
+ "DISCOVERY_FAILED"
1074
+ );
1075
+ }
1076
+ let text;
1077
+ try {
1078
+ text = await readBounded(response, url);
1079
+ } catch (error) {
1080
+ if (request.signal?.aborted) {
1081
+ throw new LlmError2("model discovery aborted by caller", "ABORTED", { cause: error });
1082
+ }
1083
+ throw error;
1084
+ }
1085
+ let body;
1086
+ try {
1087
+ body = JSON.parse(text);
1088
+ } catch (error) {
1089
+ throw new LlmError2(`${url} did not answer with JSON`, "DISCOVERY_FAILED", { cause: error });
1090
+ }
1091
+ return readListing(body);
1092
+ }
1093
+
1094
+ // dsh/vendor/dsh-llm-pi-ai/src/login.ts
1095
+ import { isCredentialKeySegment as isCredentialKeySegment2 } from "@deepseek-ai/dsh-credentials";
1096
+ var UNSERVED_OAUTH = /* @__PURE__ */ new Set(["openai"]);
1097
+ function loginMethods(provider) {
1098
+ const methods = [];
1099
+ const oauth = provider === void 0 || UNSERVED_OAUTH.has(provider.id) ? void 0 : provider.auth.oauth;
1100
+ if (oauth !== void 0) methods.push({ id: "oauth", label: oauth.loginLabel ?? oauth.name });
1101
+ const apiKey = provider?.auth.apiKey;
1102
+ if (apiKey?.login !== void 0) methods.push({ id: "api-key", label: apiKey.name });
1103
+ return methods;
1104
+ }
1105
+ function relay(event, session) {
1106
+ switch (event.type) {
1107
+ case "info": {
1108
+ const link = event.links?.[0];
1109
+ session.notify({ message: event.message, ...link === void 0 ? {} : { url: link.url } });
1110
+ return;
1111
+ }
1112
+ case "auth_url":
1113
+ session.notify({
1114
+ message: event.instructions ?? "Open this page to continue signing in.",
1115
+ url: event.url
1116
+ });
1117
+ return;
1118
+ case "device_code":
1119
+ session.notify({
1120
+ message: "Enter this code on the verification page to finish signing in.",
1121
+ url: event.verificationUri,
1122
+ code: event.userCode
1123
+ });
1124
+ return;
1125
+ case "progress":
1126
+ session.notify({ message: event.message });
1127
+ return;
1128
+ default:
1129
+ session.notify({ message: "Signing in\u2026" });
1130
+ }
1131
+ }
1132
+ function restate(prompt) {
1133
+ const signal = prompt.signal === void 0 ? {} : { signal: prompt.signal };
1134
+ switch (prompt.type) {
1135
+ case "select":
1136
+ return { ...signal, kind: "select", message: prompt.message, options: prompt.options };
1137
+ case "secret":
1138
+ return {
1139
+ ...signal,
1140
+ kind: "secret",
1141
+ message: prompt.message,
1142
+ ...prompt.placeholder === void 0 ? {} : { placeholder: prompt.placeholder }
1143
+ };
1144
+ default:
1145
+ return {
1146
+ ...signal,
1147
+ kind: "text",
1148
+ message: prompt.message,
1149
+ ...prompt.placeholder === void 0 ? {} : { placeholder: prompt.placeholder }
1150
+ };
1151
+ }
1152
+ }
1153
+ function registerPiAiFlows(ctx, auth) {
1154
+ for (const providerId of catalogProviderIds()) {
1155
+ const provider = catalogProvider(providerId);
1156
+ const [first, ...rest] = loginMethods(provider);
1157
+ if (provider === void 0 || first === void 0) continue;
1158
+ if (!isCredentialKeySegment2(providerId)) {
1159
+ ctx.logger.warn(
1160
+ 'llm-pi-ai: catalog provider "%s" cannot address a credential record; its sign-in is not offered',
1161
+ providerId
1162
+ );
1163
+ continue;
1164
+ }
1165
+ ctx.authorization.registerFlow({
1166
+ key: recordKeyFor(providerId),
1167
+ label: provider.name,
1168
+ methods: [first, ...rest],
1169
+ async run(session) {
1170
+ const models = createModels(auth);
1171
+ models.setProvider(provider);
1172
+ const type = session.method === "oauth" ? "oauth" : "api_key";
1173
+ await models.login(providerId, type, {
1174
+ signal: session.signal,
1175
+ notify: (event) => {
1176
+ relay(event, session);
1177
+ },
1178
+ prompt: (prompt) => session.prompt(restate(prompt))
1179
+ });
1180
+ }
1181
+ });
1182
+ }
1183
+ }
1184
+
1185
+ // dsh/vendor/dsh-llm-pi-ai/src/provider-data.generated.ts
1186
+ var PROVIDER_DATA = {
1187
+ "amazon-bedrock": { env: ["AWS_BEARER_TOKEN_BEDROCK", "AWS_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_WEB_IDENTITY_TOKEN_FILE"], baseURLEnv: ["AWS_REGION", "AWS_DEFAULT_REGION"] },
1188
+ "ant-ling": { env: ["ANT_LING_API_KEY"], defaultBaseURL: "https://api.ant-ling.com/v1" },
1189
+ "anthropic": { env: ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_FEDERATION_RULE_ID", "ANTHROPIC_ORGANIZATION_ID", "ANTHROPIC_IDENTITY_TOKEN_FILE", "ANTHROPIC_SERVICE_ACCOUNT_ID", "ANTHROPIC_WORKSPACE_ID"], defaultBaseURL: "https://api.anthropic.com" },
1190
+ "azure": { env: ["AZURE_OPENAI_API_KEY"], baseURLEnv: ["AZURE_OPENAI_BASE_URL", "AZURE_OPENAI_RESOURCE_NAME"] },
1191
+ "baseten": { env: ["BASETEN_API_KEY"], defaultBaseURL: "https://inference.baseten.co/v1" },
1192
+ "cerebras": { env: ["CEREBRAS_API_KEY"], defaultBaseURL: "https://api.cerebras.ai/v1" },
1193
+ "cloudflare-ai-gateway": { env: ["CLOUDFLARE_API_KEY", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_GATEWAY_ID"], baseURLEnv: ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_GATEWAY_ID"] },
1194
+ "cloudflare-workers-ai": { env: ["CLOUDFLARE_API_KEY", "CLOUDFLARE_ACCOUNT_ID"], baseURLEnv: ["CLOUDFLARE_ACCOUNT_ID"] },
1195
+ "deepseek": { env: ["DEEPSEEK_API_KEY"], defaultBaseURL: "https://api.deepseek.com" },
1196
+ "fireworks": { env: ["FIREWORKS_API_KEY"], defaultBaseURL: "https://api.fireworks.ai/inference" },
1197
+ "github-copilot": { env: ["COPILOT_GITHUB_TOKEN"], defaultBaseURL: "https://api.individual.githubcopilot.com" },
1198
+ "google": { env: ["GEMINI_API_KEY"], defaultBaseURL: "https://generativelanguage.googleapis.com/v1beta" },
1199
+ "google-vertex": { env: ["GOOGLE_CLOUD_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION"], baseURLEnv: ["GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION"] },
1200
+ "groq": { env: ["GROQ_API_KEY"], defaultBaseURL: "https://api.groq.com/openai/v1" },
1201
+ "huggingface": { env: ["HF_TOKEN"], defaultBaseURL: "https://router.huggingface.co/v1" },
1202
+ "kimi-coding": { env: ["KIMI_API_KEY"], defaultBaseURL: "https://api.kimi.com/coding/v1" },
1203
+ "meta": { env: ["META_API_KEY"], defaultBaseURL: "https://api.meta.ai/v1" },
1204
+ "minimax": { env: ["MINIMAX_API_KEY"], defaultBaseURL: "https://api.minimax.io/anthropic" },
1205
+ "minimax-cn": { env: ["MINIMAX_CN_API_KEY"], defaultBaseURL: "https://api.minimaxi.com/anthropic" },
1206
+ "mistral": { env: ["MISTRAL_API_KEY"], defaultBaseURL: "https://api.mistral.ai" },
1207
+ "moonshotai": { env: ["MOONSHOT_API_KEY"], defaultBaseURL: "https://api.moonshot.ai/v1" },
1208
+ "moonshotai-cn": { env: ["MOONSHOT_API_KEY"], defaultBaseURL: "https://api.moonshot.cn/v1" },
1209
+ "nvidia": { env: ["NVIDIA_API_KEY"], defaultBaseURL: "https://integrate.api.nvidia.com/v1" },
1210
+ "openai": { env: ["OPENAI_API_KEY"], defaultBaseURL: "https://api.openai.com/v1" },
1211
+ "openai-codex": { env: [], defaultBaseURL: "https://chatgpt.com/backend-api" },
1212
+ "opencode": { env: ["OPENCODE_API_KEY"] },
1213
+ "opencode-go": { env: ["OPENCODE_API_KEY"] },
1214
+ "openrouter": { env: ["OPENROUTER_API_KEY"], defaultBaseURL: "https://openrouter.ai/api/v1" },
1215
+ "qwen-token-plan": { env: ["QWEN_TOKEN_PLAN_API_KEY"], defaultBaseURL: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" },
1216
+ "qwen-token-plan-cn": { env: ["QWEN_TOKEN_PLAN_CN_API_KEY"], defaultBaseURL: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1" },
1217
+ "qwen-token-plan-individual": { env: ["QWEN_TOKEN_PLAN_API_KEY"], defaultBaseURL: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" },
1218
+ "radius": { env: ["RADIUS_API_KEY"], defaultBaseURL: "https://radius.pi.dev/v1" },
1219
+ "together": { env: ["TOGETHER_API_KEY"], defaultBaseURL: "https://api.together.ai/v1" },
1220
+ "typesafe": { env: ["TYPESAFE_API_KEY"] },
1221
+ "vercel-ai-gateway": { env: ["AI_GATEWAY_API_KEY"], defaultBaseURL: "https://ai-gateway.vercel.sh" },
1222
+ "xai": { env: ["XAI_API_KEY"], defaultBaseURL: "https://api.x.ai/v1" },
1223
+ "xiaomi": { env: ["XIAOMI_API_KEY"], defaultBaseURL: "https://api.xiaomimimo.com/v1" },
1224
+ "xiaomi-token-plan-ams": { env: ["XIAOMI_TOKEN_PLAN_AMS_API_KEY"], defaultBaseURL: "https://token-plan-ams.xiaomimimo.com/v1" },
1225
+ "xiaomi-token-plan-cn": { env: ["XIAOMI_TOKEN_PLAN_CN_API_KEY"], defaultBaseURL: "https://token-plan-cn.xiaomimimo.com/v1" },
1226
+ "xiaomi-token-plan-sgp": { env: ["XIAOMI_TOKEN_PLAN_SGP_API_KEY"], defaultBaseURL: "https://token-plan-sgp.xiaomimimo.com/v1" },
1227
+ "zai": { env: ["ZAI_API_KEY"], defaultBaseURL: "https://api.z.ai/api/coding/paas/v4" },
1228
+ "zai-coding-cn": { env: ["ZAI_CODING_CN_API_KEY"], defaultBaseURL: "https://open.bigmodel.cn/api/coding/paas/v4" }
1229
+ };
1230
+
1231
+ // dsh/vendor/dsh-llm-pi-ai/src/provider-data.ts
1232
+ function providerDefaultsOf(provider) {
1233
+ const data = PROVIDER_DATA[provider.id];
1234
+ if (data === void 0) return provider.baseUrl && !provider.baseUrl.includes("{") ? { defaultBaseURL: provider.baseUrl } : {};
1235
+ const { env, ...endpoint } = data;
1236
+ return { ...endpoint, nativeAuth: { env, oauth: provider.auth.oauth !== void 0 } };
1237
+ }
1238
+
1239
+ // dsh/vendor/dsh-llm-pi-ai/src/index.ts
1240
+ var name = "llm-pi-ai-carrier-cache";
1241
+ var NS = "llm-pi-ai";
1242
+ function registrationFacts(profiles) {
1243
+ return [...profiles.entries()].map(([provider, profile2]) => ({
1244
+ provider,
1245
+ displayName: profile2.displayName,
1246
+ retryPolicy: profile2.retryPolicy
1247
+ })).sort((left, right) => left.provider.localeCompare(right.provider));
1248
+ }
1249
+ function directoryEntries(profiles, settingsNs) {
1250
+ const entries = /* @__PURE__ */ new Map();
1251
+ const declare = (provider, displayName, error) => {
1252
+ const installed = catalogProvider(provider);
1253
+ entries.set(provider, {
1254
+ provider,
1255
+ displayName,
1256
+ settingsNs,
1257
+ settingsPath: ["providers", provider],
1258
+ // Membership of the installed catalog, not of the settings document:
1259
+ // narrowing a shipped provider's models stores a profile too, and that
1260
+ // route is still one pi-ai knows.
1261
+ declared: installed === void 0,
1262
+ ...installed === void 0 ? {} : providerDefaultsOf(installed),
1263
+ ...error === void 0 ? {} : { error }
1264
+ });
1265
+ };
1266
+ for (const provider of catalogProviderIds()) declare(provider, provider);
1267
+ for (const [provider, profile2] of profiles) declare(provider, profile2.displayName, profile2.catalogError);
1268
+ return [...entries.values()];
1269
+ }
1270
+ function bootstrap(ctx, config, decorateProfiles) {
1271
+ ctx.inject(["settings"], (child) => {
1272
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
1273
+ });
1274
+ const settingsNs = ctx.fiber.entry?.options.id ?? NS;
1275
+ let lastRaw;
1276
+ let memoized;
1277
+ const profiles = () => {
1278
+ const raw = config.providers.get();
1279
+ if (raw === lastRaw && memoized !== void 0) return memoized;
1280
+ const next = decorateProfiles(resolveProfiles(structuredClone(raw), "deferred"));
1281
+ lastRaw = raw;
1282
+ memoized = next;
1283
+ return next;
1284
+ };
1285
+ profiles();
1286
+ ctx.on("internal/config", (fiber, next) => {
1287
+ const raw = next();
1288
+ if (fiber !== ctx.fiber) return raw;
1289
+ const candidate = Config(raw);
1290
+ assertServiceable(
1291
+ { providers: structuredClone(candidate.providers.get()) },
1292
+ { providers: structuredClone(config.providers.get()) }
1293
+ );
1294
+ return raw;
1295
+ });
1296
+ const resolveApiKey = async (provider, profile2) => {
1297
+ const ref = profile2.apiKeyEnv;
1298
+ if (ref === void 0) return void 0;
1299
+ const credentials = ctx.get("credentials");
1300
+ const hit = credentials !== void 0 ? (await credentials.resolve(ref))?.value : launchEnvironmentOf2(ctx).get(ref)?.value;
1301
+ if (hit !== void 0 && hit.length > 0) return assertUsableApiKey(hit, "llm-pi-ai", ref);
1302
+ throw new LlmError3(
1303
+ `llm-pi-ai: no credential for provider route "${provider}"; its profile resolves ${ref}, which is not set \u2014 store ${ref} through the credentials service (the web Models page writes it) or export it, and remove apiKeyEnv only if this provider should authenticate from pi-ai's own environment discovery`,
1304
+ "MISSING_CREDENTIAL"
1305
+ );
1306
+ };
1307
+ const auth = { credentials: credentialStoreFrom(ctx), authContext: authContextFrom(ctx) };
1308
+ const adapter = new PiAiAdapter({
1309
+ profiles,
1310
+ resolveApiKey,
1311
+ auth,
1312
+ prepareHeaders: (request, headers) => ctx.waterfall("llm-pi-ai/request-headers", request, headers, () => headers),
1313
+ resolveAttachments: () => ctx.get("attachments"),
1314
+ resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(
1315
+ attachments,
1316
+ (hostPath) => ctx.get("fs")?.processPathFromHostPath(hostPath),
1317
+ ref
1318
+ ),
1319
+ onReplayDegrade: ({ provider, model, reason }) => {
1320
+ ctx.logger.warn(
1321
+ `llm-pi-ai: unusable replay state on assistant history for route "${provider}/${model}"; sending that message as provider-neutral content (${reason})`
1322
+ );
1323
+ }
1324
+ });
1325
+ ctx.inject(["authorization"], (authorized) => {
1326
+ registerPiAiFlows(authorized, auth);
1327
+ });
1328
+ let directory;
1329
+ let directoryFacts;
1330
+ const ensureDirectory = () => {
1331
+ const entries = directoryEntries(profiles(), settingsNs);
1332
+ if (deepEqualJson2(entries, directoryFacts)) return;
1333
+ if (directory === void 0) {
1334
+ directory = ctx.llm.registerConfigurableProviders(entries);
1335
+ } else {
1336
+ directory.replace(entries);
1337
+ }
1338
+ directoryFacts = entries;
1339
+ };
1340
+ ensureDirectory();
1341
+ const storedDiscoveryProfile = (provider) => {
1342
+ if (provider === void 0) return void 0;
1343
+ const profile2 = profiles().get(provider);
1344
+ if (profile2 === void 0) return void 0;
1345
+ return {
1346
+ headers: profile2.headers,
1347
+ resolveApiKey: () => resolveApiKey(provider, profile2)
1348
+ };
1349
+ };
1350
+ ctx.llm.registerModelDiscovery(settingsNs, (request, signal) => discoverModels(
1351
+ { ...request, ...signal === void 0 ? {} : { signal } },
1352
+ () => storedDiscoveryProfile(request.provider)
1353
+ ));
1354
+ let registration;
1355
+ let registeredFacts;
1356
+ let registeredRoutes = [];
1357
+ const ensureRegistrationFacts = () => {
1358
+ const facts = registrationFacts(profiles());
1359
+ if (deepEqualJson2(facts, registeredFacts)) return;
1360
+ const routes = [...profiles().keys()];
1361
+ if (registration === void 0) {
1362
+ if (routes.length === 0) {
1363
+ registeredFacts = facts;
1364
+ return;
1365
+ }
1366
+ registration = ctx.llm.registerAdapter(routes, adapter);
1367
+ } else {
1368
+ registration.replace(routes);
1369
+ }
1370
+ registeredFacts = facts;
1371
+ registeredRoutes = routes;
1372
+ };
1373
+ ensureRegistrationFacts();
1374
+ ctx.on("loader/volatile-update", () => {
1375
+ try {
1376
+ ensureRegistrationFacts();
1377
+ ensureDirectory();
1378
+ } catch (error) {
1379
+ ctx.logger.error("llm-pi-ai: configuration conflicts with an existing provider route");
1380
+ ctx.logger.error(error);
1381
+ }
1382
+ });
1383
+ return { registeredRoutes: () => [...registeredRoutes] };
1384
+ }
1385
+
1386
+ // dsh/src/carrier-cache.js
1387
+ var MAX_CONTROL_POINTS = 4;
1388
+ var ADDED = Object.freeze({ result: "added" });
1389
+ var NATIVE = Object.freeze({ result: "native" });
1390
+ var skipped = (reason) => Object.freeze({ result: "skipped", reason });
1391
+ var NO_CARRIER = skipped("no-carrier");
1392
+ var NO_NATIVE_POINT = skipped("no-native-point");
1393
+ var POINTS_FULL = skipped("points-full");
1394
+ var RESPONSES_OFF = skipped("responses-off");
1395
+ var UNSUPPORTED = skipped("unsupported");
1396
+ var LONG_RETENTION = "24h";
1397
+ var LONG_OPTIONS = Object.freeze({ ttl: "30m" });
1398
+ var textOfBlocks = (blocks) => blocks.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
1399
+ function createCarrierCache({ carrierPrefix, report, observe = () => {
1400
+ }, responsesBreakpoint = () => false }) {
1401
+ const lastCarrier = (messages, textOf) => messages.findLastIndex((message) => message?.role === "user" && textOf(message).startsWith(carrierPrefix));
1402
+ const blocksText = (content) => typeof content === "string" ? content : Array.isArray(content) ? textOfBlocks(content) : "";
1403
+ const controlText = (message) => blocksText(message.content);
1404
+ const controlled = (parts) => parts.filter((part) => part?.cache_control !== void 0);
1405
+ function controlPoint({ message, marked, pick, model }) {
1406
+ if (marked.length === 0) return NO_NATIVE_POINT;
1407
+ const blocks = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
1408
+ const last = pick(blocks);
1409
+ if (last.cache_control !== void 0) return NATIVE;
1410
+ if (marked.length >= MAX_CONTROL_POINTS) {
1411
+ report(`llm-pi-ai carrier cache: route "${model.provider}/${model.id}" (${model.api}) already sends ${marked.length} cache points, so the last carrier is given none`);
1412
+ return POINTS_FULL;
1413
+ }
1414
+ last.cache_control = { ...marked[0].cache_control };
1415
+ if (typeof message.content === "string") message.content = blocks;
1416
+ return ADDED;
1417
+ }
1418
+ const anthropicMarked = (payload) => controlled([
1419
+ ...Array.isArray(payload.system) ? payload.system : [],
1420
+ ...Array.isArray(payload.tools) ? payload.tools : [],
1421
+ ...(Array.isArray(payload.messages) ? payload.messages : []).flatMap((message) => Array.isArray(message.content) ? message.content : [])
1422
+ ]);
1423
+ function anthropic(payload, model) {
1424
+ if (!Array.isArray(payload.messages)) return UNSUPPORTED;
1425
+ const at = lastCarrier(payload.messages, controlText);
1426
+ if (at < 0) return NO_CARRIER;
1427
+ return controlPoint({ message: payload.messages[at], marked: anthropicMarked(payload), pick: (blocks) => blocks.at(-1), model });
1428
+ }
1429
+ function completions(payload, model) {
1430
+ if (!Array.isArray(payload.messages)) return UNSUPPORTED;
1431
+ const at = lastCarrier(payload.messages, controlText);
1432
+ if (at < 0) return NO_CARRIER;
1433
+ const marked = controlled([
1434
+ ...Array.isArray(payload.tools) ? payload.tools : [],
1435
+ ...payload.messages.flatMap((message) => Array.isArray(message.content) ? message.content : [])
1436
+ ]);
1437
+ return controlPoint({ message: payload.messages[at], marked, pick: (parts) => parts.findLast((part) => part?.type === "text"), model });
1438
+ }
1439
+ const bedrockText = (message) => Array.isArray(message.content) ? message.content.filter((block) => typeof block?.text === "string").map((block) => block.text).join("") : "";
1440
+ function bedrock(payload) {
1441
+ if (!Array.isArray(payload.messages)) return UNSUPPORTED;
1442
+ const at = lastCarrier(payload.messages, bedrockText);
1443
+ if (at < 0) return NO_CARRIER;
1444
+ const blocks = [...Array.isArray(payload.system) ? payload.system : [], ...payload.messages.flatMap((message) => Array.isArray(message.content) ? message.content : [])];
1445
+ const point = blocks.find((block) => block?.cachePoint !== void 0);
1446
+ if (point === void 0) return NO_NATIVE_POINT;
1447
+ const { content } = payload.messages[at];
1448
+ if (content.at(-1)?.cachePoint !== void 0) return NATIVE;
1449
+ content.push({ cachePoint: { ...point.cachePoint } });
1450
+ return ADDED;
1451
+ }
1452
+ const responsesText = (item) => item?.role === "user" && Array.isArray(item.content) ? item.content.filter((part) => part?.type === "input_text" && typeof part.text === "string").map((part) => part.text).join("") : "";
1453
+ const chatGptSignIn = (model, apiKey) => model.provider === "openai" && model.baseUrl === "https://api.openai.com/v1" && apiKey !== void 0 && !apiKey.startsWith("sk-");
1454
+ const switchedOn = () => {
1455
+ try {
1456
+ return responsesBreakpoint() === true;
1457
+ } catch {
1458
+ report("llm-pi-ai carrier cache: the Responses breakpoint setting could not be read, so the request is sent without it");
1459
+ return false;
1460
+ }
1461
+ };
1462
+ const explicitOptions = (payload) => {
1463
+ if (payload.prompt_cache_retention !== LONG_RETENTION) return;
1464
+ delete payload.prompt_cache_retention;
1465
+ payload.prompt_cache_options = { ...LONG_OPTIONS };
1466
+ };
1467
+ function responses(payload, model, options) {
1468
+ if (!switchedOn()) return RESPONSES_OFF;
1469
+ if (!Array.isArray(payload.input) || chatGptSignIn(model, options?.apiKey)) return UNSUPPORTED;
1470
+ if (options?.cacheRetention === "none") return NO_NATIVE_POINT;
1471
+ const at = lastCarrier(payload.input, responsesText);
1472
+ if (at < 0) return NO_CARRIER;
1473
+ if (at === payload.input.length - 1) return NATIVE;
1474
+ const block = payload.input[at].content.findLast((part) => part?.type === "input_text");
1475
+ block.prompt_cache_breakpoint = { mode: "explicit" };
1476
+ explicitOptions(payload);
1477
+ return ADDED;
1478
+ }
1479
+ const WRITERS = { "anthropic-messages": anthropic, "bedrock-converse-stream": bedrock, "openai-responses": responses, "openai-completions": completions };
1480
+ const observed = (outcome) => {
1481
+ try {
1482
+ observe(outcome);
1483
+ } catch {
1484
+ report("llm-pi-ai carrier cache: the cache evidence of a request could not be recorded");
1485
+ }
1486
+ };
1487
+ const hookOf = (earlier, options) => async (payload, model) => {
1488
+ const replaced = await earlier?.(payload, model);
1489
+ const body = replaced ?? payload;
1490
+ const outcome = WRITERS[model.api]?.(body, model, options) ?? UNSUPPORTED;
1491
+ observed(outcome);
1492
+ return outcome === ADDED ? body : replaced;
1493
+ };
1494
+ const wrapProvider = (provider) => Object.create(provider, {
1495
+ streamSimple: {
1496
+ value: (model, context, options) => provider.streamSimple(model, context, { ...options, onPayload: hookOf(options?.onPayload, options) }),
1497
+ enumerable: true,
1498
+ writable: true,
1499
+ configurable: true
1500
+ }
1501
+ });
1502
+ return {
1503
+ /** The resolved profiles with each route's pi-ai provider wrapped; a route that resolved none is left as it is. */
1504
+ decorateProfiles: (profiles) => new Map([...profiles].map(([route, profile2]) => [
1505
+ route,
1506
+ profile2.piProvider === void 0 ? profile2 : { ...profile2, piProvider: wrapProvider(profile2.piProvider) }
1507
+ ]))
1508
+ };
1509
+ }
1510
+
1511
+ // dsh/src/pi-ai-integration.js
1512
+ var PI_AI_SERVICE = "sessionWatcherPiAi";
1513
+ var ORIGINAL_ROW = "include:llm-pi-ai";
1514
+ var CARRIER_EVIDENCE_SERVICE = "sessionWatcherCarrierEvidence";
1515
+
1516
+ // dsh/src/pi-ai-index.js
1517
+ var inject = ["llm", "loader"];
1518
+ var FAILURE_LOGS = {
1519
+ "source-missing": `llm-pi-ai carrier cache: the Loader has no readable row ${ORIGINAL_ROW}, so no route is served`,
1520
+ "source-enabled": `llm-pi-ai carrier cache: the row ${ORIGINAL_ROW} is not switched off, so the original adapter serves and this entry serves no route`,
1521
+ "source-invalid": `llm-pi-ai carrier cache: the configuration of the row ${ORIGINAL_ROW} is not a usable profile dictionary, so no route is served`
1522
+ };
1523
+ function readSource(ctx) {
1524
+ let row;
1525
+ let disabled;
1526
+ try {
1527
+ row = ctx.loader.resolve(ORIGINAL_ROW);
1528
+ ({ disabled } = row);
1529
+ } catch {
1530
+ return { cause: "source-missing" };
1531
+ }
1532
+ if (disabled !== true) return { cause: "source-enabled" };
1533
+ try {
1534
+ const config = Config(structuredClone(row.options.config ?? {}));
1535
+ resolveProfiles(structuredClone(config.providers.get()), "deferred");
1536
+ return { config };
1537
+ } catch {
1538
+ return { cause: "source-invalid" };
1539
+ }
1540
+ }
1541
+ function apply(ctx) {
1542
+ const source = readSource(ctx);
1543
+ if (source.cause !== void 0) {
1544
+ ctx.logger.error(FAILURE_LOGS[source.cause]);
1545
+ ctx.provide(PI_AI_SERVICE, { failure: { cause: source.cause } });
1546
+ return;
1547
+ }
1548
+ const cache = createCarrierCache({
1549
+ carrierPrefix: CARRIER_WORDING.addresses,
1550
+ report: (message) => ctx.logger.warn(message),
1551
+ observe: (result) => ctx.get(CARRIER_EVIDENCE_SERVICE)?.record(result),
1552
+ responsesBreakpoint: () => ctx.get(CARRIER_EVIDENCE_SERVICE)?.responsesBreakpoint?.()
1553
+ });
1554
+ const registration = bootstrap(ctx, source.config, cache.decorateProfiles);
1555
+ ctx.provide(PI_AI_SERVICE, {
1556
+ failure: null,
1557
+ cacheRetention: (route) => source.config.providers.get()[route]?.cacheRetention ?? null,
1558
+ routes: () => registration.registeredRoutes()
1559
+ });
1560
+ }
1561
+ export {
1562
+ apply,
1563
+ inject,
1564
+ name
1565
+ };