dsh-magpie-connect 0.7.0 → 0.7.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.
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/adapter/catalog.ts", "../src/homeDir.ts", "../src/adapter/magpie-adapter.ts", "../src/adapter/events.ts", "../src/adapter/messages.ts", "../src/adapter/watchdog.ts", "../src/config.ts", "../src/settings.ts", "../src/trace.ts"],
4
- "sourcesContent": ["import { join } from 'node:path'\nimport { writeFile } from 'node:fs/promises'\n\nimport {\n ModelCatalog,\n defaultCachePath,\n fetchMagpieModels,\n type CatalogSnapshot,\n type MagpieModelEntry,\n} from './adapter/catalog.ts'\nimport { legacyDataDir } from './homeDir.ts'\nimport { MagpieAdapter } from './adapter/magpie-adapter.ts'\nimport type { AttachmentStore } from './adapter/messages.ts'\nimport { resolveConfig, type DshMagpieConnectConfig } from './config.ts'\nimport { deriveGatewayBase, fetchTraceView, fetchWebIcon, TRACE_TIMEOUT_MS } from './trace.ts'\nimport {\n SettingsStore,\n defaultSettingsPath,\n isConfigured,\n normalizeBaseUrl,\n normalizePageSettings,\n resolveEffectiveEndpoint,\n type MagpieSettingsView,\n} from './settings.ts'\n\n/**\n * dsh-magpie-connect DSH cordis plugin entry.\n *\n * Registers a DSH LlmAdapter streaming directly from the Magpie gateway\n * (marketplace shape: no child process, no binary, no proxy). The model\n * catalog warms up in the background (live gateway list with disk cache +\n * static snapshot fallback).\n *\n * The Settings sidebar page (client half) talks to the REST routes below:\n * connection endpoint (baseUrl/apiKey) applies live without restart, and the\n * hidden-model list filters the picker immediately.\n *\n * dispose(): stop the catalog refresh loop. The cordis fiber disposal\n * guarantees this runs on plugin reload/unload and on DSH shutdown.\n */\n\n// Minimal structural typing against the host ctx; keeps the plugin independent\n// of the exact @deepseek-ai/cordis version DSH ships.\nexport interface PluginContext {\n logger: { info(...args: unknown[]): void; warn(...args: unknown[]): void; error(...args: unknown[]): void }\n llm?: { registerAdapter(providers: string[], adapter: unknown): unknown }\n get?(key: string): unknown\n inject?(deps: string[], fn: (ctx: Record<string, unknown>) => unknown): unknown\n effect?(fn: () => () => void): unknown\n on?(event: string, listener: (...args: never[]) => unknown): () => void\n /**\n * Cordis `ctx.emit` (mixed in from the events service). Used to publish\n * `llm/adapters-updated` when this plugin's own catalog moves, without\n * touching the adapter registry.\n */\n emit?(event: string, ...args: unknown[]): unknown\n}\n\nexport const name = 'dsh-magpie-connect'\nexport const inject = ['llm'] as const\n\n/** Browser-facing REST root for the settings page (served under the shared /api channel). */\nexport const SETTINGS_API = '/api/magpie-settings'\nexport const MODELS_API = '/api/magpie-models'\nexport const TEST_API = '/api/magpie-test'\n/**\n * Candidate discovery: asks the endpoint the form currently shows (including a\n * key typed but not yet saved) what it serves. The reply is candidates the\n * user picks from \u2014 never configuration written behind them.\n */\nexport const DISCOVER_API = '/api/magpie-discover'\n/**\n * Routing-trace read for the composer button's popover (`/api/magpie-trace`).\n * The host reads the gateway's own ledger (`/v1/magpie/usage/requests`) and\n * quotas (`/v1/magpie/quotas`) with the stored key and serves the compressed\n * view \u2014 the browser never sees the key nor talks to the gateway cross-origin.\n */\nexport const TRACE_API = '/api/magpie-trace'\n/** Same-origin proxy for Magpie Web provider icons; the Web Key stays on the Host. */\nexport const ICON_API = '/api/magpie-icon'\n\n/**\n * How long a settings save waits for the catalog re-read it triggered.\n *\n * The page re-reads rows right after the response, so the save must not answer\n * before a fast gateway has been read; but the credential write is already\n * durable, so a slow gateway must not hold the request open either.\n */\nconst SAVE_REFRESH_WAIT_MS = 5000\n\n/** Backend generation behind the shared settings routes (newest wins). */\nexport interface SettingsBackend {\n store: SettingsStore\n catalog: ModelCatalog\n patchEndpoint: { baseUrl: string; apiKey: string }\n effective: () => { baseUrl: string; apiKey: string }\n applyPageSettings: () => void\n}\n\ntype FetchRegister = (route: {\n path: string\n methods: string[]\n requestBody: string\n fetch: (request: Request) => Promise<Response>\n}) => () => void | Promise<void>\n\ninterface ModelRow {\n /** Route id, used by the allowlist, requests and session history. */\n id: string\n /** `<group>/<display_name>` label the settings list and picker show. */\n displayName: string\n contextWindow?: number\n maxTokens?: number\n image: boolean\n responsesOnly: boolean\n reasoning: boolean\n efforts: string[]\n /** Whether the allowlist currently offers this model in the picker. */\n enabled: boolean\n /**\n * What lists this id right now: `'gateway'` (the live directory), `'static'`\n * (only the built-in snapshot) or `'none'` (nothing does \u2014 a hidden id the\n * gateway has dropped). The page labels the last two so a stale row cannot be\n * mistaken for a model the gateway still serves. Candidates from the discover\n * route leave it unset: they come from the gateway by construction.\n */\n source?: 'gateway' | 'static' | 'none'\n}\n\n/** One discovered candidate: a {@link ModelRow} without this plugin's own allowlist flag. */\nexport type CandidateRow = Omit<ModelRow, 'enabled'>\n\n/** True when the endpoints advertise responses but not chat completions. */\nfunction responsesOnlyFor(nativeEndpoints: readonly string[]): boolean {\n if (nativeEndpoints.length === 0) return false\n const hasCompletions = nativeEndpoints.some((endpoint) => endpoint.includes('/chat/completions'))\n return !hasCompletions && nativeEndpoints.some((endpoint) => endpoint.includes('/responses'))\n}\n\n/**\n * Both model lists are sorted by the label the user sees. Grouping models by\n * `<group>/<display_name>` keeps one gateway lane's models together; the id is a\n * tie-break so two models with the same label still have a stable order.\n */\nfunction compareModelRows(left: CandidateRow, right: CandidateRow): number {\n return left.displayName.localeCompare(right.displayName, 'zh') || left.id.localeCompare(right.id)\n}\n\n/** Project one catalog entry (or a bare id) into the wire row the page renders. */\nfunction toRow(id: string, entry: MagpieModelEntry | undefined): CandidateRow {\n return {\n id,\n displayName: entry?.displayName ?? id,\n ...(entry?.contextWindow !== undefined ? { contextWindow: entry.contextWindow } : {}),\n ...(entry?.maxTokens !== undefined ? { maxTokens: entry.maxTokens } : {}),\n image: entry?.image ?? false,\n responsesOnly: responsesOnlyFor(entry?.nativeEndpoints ?? []),\n reasoning: entry?.reasoning ?? false,\n efforts: entry?.efforts ?? [],\n }\n}\n\nlet currentBackend: SettingsBackend | null = null\nlet liveRouteSets = 0\nlet routeDisposers: Array<() => void | Promise<void>> | null = null\n\n/** @internal Test hook: forget installed routes so the next apply reinstalls. */\nexport function __resetSettingsRoutes(): void {\n currentBackend = null\n liveRouteSets = 0\n routeDisposers = null\n}\n\nfunction jsonResponse(status: number, payload: unknown): Response {\n return new Response(JSON.stringify(payload), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },\n })\n}\n\nconst routeOk = (value: unknown): Response => jsonResponse(200, { ok: true, value })\nconst routeFail = (error: unknown): Response =>\n jsonResponse(500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n\nasync function readRouteBody(request: Request): Promise<unknown> {\n try {\n return await request.json()\n } catch {\n return {}\n }\n}\n\n/**\n * The rows the settings page renders.\n *\n * One row per id the gateway directory holds, each flagged with whether the\n * allowlist offers it. Unlike the old blacklist shape there are no extra rows\n * for ids outside the directory: an allowlist entry the gateway no longer\n * serves is simply not a model any more, and surfacing it would offer the user\n * a checkbox that can never take effect.\n */\nfunction buildModelRows(backend: SettingsBackend): ModelRow[] {\n const { store, catalog } = backend\n const allowlist = store.get().enabledModels\n const allowed = allowlist === undefined ? undefined : new Set(allowlist)\n return catalog.directory()\n .map((id) => ({\n ...toRow(id, catalog.getEntry(id)),\n enabled: allowed === undefined || allowed.has(id),\n source: catalog.sourceFor(id),\n }))\n .sort(compareModelRows)\n}\n\nfunction backendOrThrow(): SettingsBackend {\n if (!currentBackend) throw new Error('dsh-magpie-connect: settings backend not ready')\n return currentBackend\n}\n\n/**\n * One registered route: the connection registry keys routes by PATH and\n * rejects a second registration of the same path, so every method of one\n * endpoint must share a single entry and dispatch inside its handler. Two\n * entries on `SETTINGS_API` (GET + POST) silently lose the second one \u2014 the\n * save button then answers `404 not found` forever.\n */\ninterface RouteDefinition {\n path: string\n methods: string[]\n requestBody: string\n fetch: (request: Request) => Promise<Response>\n}\n\n/**\n * The only settings shape the browser may see. The credential is represented\n * by its presence, never by its value; `fromPage`/`fromPatch` are gone for the\n * same reason \u2014 both carried the gateway key.\n */\nfunction settingsView(backend: SettingsBackend): MagpieSettingsView {\n const page = backend.store.get()\n const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, page)\n return {\n baseUrl: endpoint.baseUrl,\n hasApiKey: endpoint.apiKey !== '',\n hasWebKey: (page.webKey ?? '').trim() !== '',\n enabledModels: page.enabledModels,\n inheritedModels: page.enabledModels === undefined,\n showComposerIcon: page.showComposerIcon !== false,\n }\n}\n\n/**\n * Accept an older client's payload that still includes the credential field\n * but left it blank (\"keep the saved key\"). The field is dropped so the save\n * merges instead of failing validation. A blank key with nothing stored is\n * still an error: there is no credential to keep.\n */\nfunction stripBlankApiKey(backend: SettingsBackend, body: unknown): unknown {\n if (!body || typeof body !== 'object') return body\n const record = body as Record<string, unknown>\n const rest = { ...record }\n if (typeof record.apiKey === 'string' && record.apiKey.trim() === '') {\n if (resolveEffectiveEndpoint(backend.patchEndpoint, backend.store.get()).apiKey === '') {\n throw new Error('dsh-magpie-connect: apiKey is required and must not be empty')\n }\n delete rest.apiKey\n }\n // An empty Web Key field means \"keep the saved Web Key\", just like the API\n // Key field. It may also be omitted entirely by older clients.\n if (typeof record.webKey === 'string' && record.webKey.trim() === '') delete rest.webKey\n return rest\n}\n\nasync function handleSettingsGet(): Promise<Response> {\n try {\n return routeOk(settingsView(backendOrThrow()))\n } catch (error) {\n return routeFail(error)\n }\n}\n\nasync function handleSettingsPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = await readRouteBody(request)\n const normalized = normalizePageSettings(stripBlankApiKey(backend, body))\n // The submitted allowlist is stored **as submitted**. Dropping ids the\n // current directory does not list would silently undo a delete: a lane's\n // models come and go between refreshes, so the ids removed while the\n // gateway happened to be un-listing them would be forgotten, then reappear\n // in the picker on the next refresh that listed them again.\n await backend.store.save(normalized)\n backend.applyPageSettings()\n // A save can move the endpoint (or just the key), so re-read the directory\n // before answering: the page re-reads rows right after this response, and a\n // key-guarded gateway would otherwise still be serving the old, empty\n // snapshot when that read lands.\n //\n // Bounded: the write is already durable, so a gateway that answers slowly\n // (or not at all) must not turn a successful save into a client-side\n // timeout. Losing the race only costs a stale row, never the setting.\n if (normalized.baseUrl !== undefined || normalized.apiKey !== undefined) {\n await Promise.race([\n backend.catalog.refreshOnce(),\n new Promise((resolve) => setTimeout(resolve, SAVE_REFRESH_WAIT_MS)),\n ])\n }\n return routeOk(settingsView(backend))\n } catch (error) {\n return routeFail(error)\n }\n}\n\nasync function handleModelsGet(): Promise<Response> {\n try {\n const backend = backendOrThrow()\n return routeOk({ models: buildModelRows(backend), snapshot: backend.catalog.snapshot() })\n } catch (error) {\n return routeFail(error)\n }\n}\n\n/** Resolve the endpoint one probe should ask: form values first, effective config as fallback. */\nfunction probeTarget(\n backend: SettingsBackend,\n body: { baseUrl?: unknown; apiKey?: unknown },\n): { origin: string; key: string } {\n const effective = backend.effective()\n const origin = normalizeBaseUrl(body.baseUrl ?? effective.baseUrl)\n // A blank field means \"use the saved key\": older pages echoed the\n // credential into the form, and a blank submit must keep working now that\n // the server no longer sends it back.\n const typed = typeof body.apiKey === 'string' ? body.apiKey.trim() : ''\n const key = typed === '' ? effective.apiKey.trim() : typed\n if (key === '') throw new Error('dsh-magpie-connect: apiKey is required \u2014 fill it in before asking the gateway')\n return { origin, key }\n}\n\n/**\n * Turn a gateway failure into copy the page can show. A 404 from the gateway\n * almost always means the origin path is wrong or the key is unknown or\n * unauthorized (many gateways hide existence behind 404 instead of 401).\n */\nfunction hintGatewayFailure(error: unknown): Response {\n const message = error instanceof Error ? error.message : String(error)\n const hinted =\n /HTTP 404/.test(message) && !/\u7F51\u5173\u8FD4\u56DE 404/.test(message)\n ? `${message}\uFF08\u7F51\u5173\u8FD4\u56DE 404\uFF1A\u591A\u4E3A API \u5730\u5740\u8DEF\u5F84\u4E0D\u5BF9\uFF0C\u6216\u8BE5 Key \u65E0\u6548/\u65E0\u6743\u8BBF\u95EE\uFF09`\n : message\n return routeFail(hinted)\n}\n\nasync function handleTestPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = (await readRouteBody(request)) as { baseUrl?: unknown; apiKey?: unknown }\n const { origin, key } = probeTarget(backend, body)\n const models = await fetchMagpieModels(origin, fetch, { headers: { authorization: `Bearer ${key}` } })\n return routeOk({ count: models.size, models: [...models.keys()].sort().slice(0, 50) })\n } catch (error) {\n return hintGatewayFailure(error)\n }\n}\n\n/**\n * Candidate discovery for the fetch-available-models dialog.\n *\n * Unlike {@link handleTestPost} (a count for the connection check) this returns\n * full rows so the picker can show the same chips the list does, and it caps\n * nothing: the dialog filters client-side. The origin and key come from the\n * form, so a provider can be filled in one pass instead of save-then-return.\n */\nasync function handleDiscoverPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = (await readRouteBody(request)) as { baseUrl?: unknown; apiKey?: unknown }\n const { origin, key } = probeTarget(backend, body)\n const models = await fetchMagpieModels(origin, fetch, { headers: { authorization: `Bearer ${key}` } })\n // The reply is the gateway's whole catalog as of now, so the local\n // directory adopts it wholesale. Without this, a model the gateway dropped\n // lingers in the list (and the picker) until a *successful* background\n // refresh \u2014 which on a key-guarded gateway may never come. That is how a\n // model already gone from the dialog kept showing in the settings list.\n backend.catalog.adoptDirectory(models)\n const candidates = [...models.entries()]\n .map(([id, entry]) => toRow(id, entry))\n .sort(compareModelRows)\n return routeOk({ count: candidates.length, models: candidates })\n } catch (error) {\n return hintGatewayFailure(error)\n }\n}\n\n/**\n * The composer popover's routing view: the gateway's request ledger plus the\n * accounts' allowances, compressed by {@link fetchTraceView} into the shape\n * `trace-contract.ts` declares. `?session=<id>` (the DSH session the composer\n * popover belongs to) adds the session's own latest route. Errors resolve\n * into a status kind the popover renders as one localized hint row \u2014 never\n * a throw.\n */\nasync function handleTraceGet(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const session = new URL(request.url).searchParams.get('session') ?? undefined\n const pageSettings = backend.store.get()\n const view = await fetchTraceView(backend.effective(), AbortSignal.timeout(TRACE_TIMEOUT_MS), session ?? undefined, pageSettings.webKey)\n return routeOk(view)\n } catch (error) {\n return routeFail(error)\n }\n}\n\n/**\n * Serve one Magpie Web provider icon through DSH's same-origin API so the\n * browser does not need a Web Key cookie for `api.lan:3430/icons/...`.\n */\nasync function handleIconGet(request: Request): Promise<Response> {\n const name = new URL(request.url).searchParams.get('name') ?? ''\n if (name === '') return jsonResponse(404, { ok: false, error: 'icon name is required' })\n try {\n const backend = backendOrThrow()\n const webKey = backend.store.get().webKey\n if (webKey === undefined || webKey.trim() === '') {\n return jsonResponse(404, { ok: false, error: 'Magpie Web Key is not configured' })\n }\n const base = deriveGatewayBase(normalizeBaseUrl(backend.effective().baseUrl))\n if (base === undefined || base === '') return jsonResponse(404, { ok: false, error: 'gateway base is invalid' })\n const icon = await fetchWebIcon(base, webKey.trim(), name, AbortSignal.timeout(TRACE_TIMEOUT_MS))\n return new Response(icon.body, {\n status: 200,\n headers: { 'content-type': icon.contentType, 'cache-control': 'public, max-age=3600' },\n })\n } catch (error) {\n return jsonResponse(404, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n}\n\nfunction routeDefinitions(): RouteDefinition[] {\n return [\n {\n path: SETTINGS_API,\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => (request.method === 'POST' ? handleSettingsPost(request) : handleSettingsGet()),\n },\n {\n path: MODELS_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: () => handleModelsGet(),\n },\n {\n path: TEST_API,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleTestPost(request),\n },\n {\n path: DISCOVER_API,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleDiscoverPost(request),\n },\n {\n path: TRACE_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleTraceGet(request),\n },\n {\n path: ICON_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleIconGet(request),\n },\n ]\n}\n\n/**\n * Install the settings-page routes on the authenticated /api channel.\n *\n * Process-wide singleton semantics: hot reload can run overlapping\n * generations of this plugin in one process, and the connection registry\n * rejects duplicate paths. The routes install once and are shared; the last\n * generation out uninstalls. Handlers resolve through `currentBackend`, so\n * they always serve the newest generation.\n */\nfunction installSettingsRoutes(\n ctx: PluginContext,\n logger: PluginContext['logger'],\n): void {\n try {\n if (typeof ctx.inject !== 'function') return\n ctx.inject(['connection'], (cctx: Record<string, unknown>) => {\n const connection = cctx.connection as { fetch?: { register?: FetchRegister } } | undefined\n const register = connection?.fetch?.register\n if (typeof register !== 'function') {\n logger.warn('dsh-magpie-connect: connection fetch registry unavailable; settings page API disabled')\n return\n }\n liveRouteSets += 1\n try {\n if (routeDisposers === null) {\n const installed: Array<() => void | Promise<void>> = []\n try {\n for (const definition of routeDefinitions()) {\n try {\n installed.push(register(definition))\n } catch (error) {\n // A live sibling generation already owns this path; share it.\n // Only ever expected for a whole path we also declare \u2014 since\n // every method of one path shares one entry, losing one here\n // means the sibling serves it identically.\n if (error instanceof Error && /already registered/.test(error.message)) {\n logger.warn(`dsh-magpie-connect: ${definition.path} already registered by another generation; sharing it`)\n continue\n }\n throw error\n }\n }\n } catch (error) {\n for (const dispose of installed.reverse()) {\n try {\n const result = dispose()\n if (result instanceof Promise) result.catch(() => {})\n } catch {\n // roll back best-effort\n }\n }\n throw error\n }\n routeDisposers = installed\n }\n } catch (error) {\n liveRouteSets -= 1\n logger.warn(`dsh-magpie-connect: settings API unavailable: ${error instanceof Error ? error.message : String(error)}`)\n throw error\n }\n return async () => {\n liveRouteSets -= 1\n if (liveRouteSets <= 0) {\n liveRouteSets = 0\n const owned = routeDisposers\n routeDisposers = null\n if (owned) {\n for (const dispose of owned.reverse()) await dispose()\n }\n }\n }\n })\n } catch (error) {\n logger.warn(`dsh-magpie-connect: settings API unavailable: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function apply(\n ctx: PluginContext,\n config: DshMagpieConnectConfig = {},\n): { ready: Promise<{ version: string }> } {\n const logger = ctx.logger\n const cfg = resolveConfig(config)\n const ready = Promise.resolve({ version: 'adapter' })\n\n if (!ctx.llm || typeof ctx.llm.registerAdapter !== 'function') {\n logger.error('dsh-magpie-connect: llm service unavailable; adapter cannot register')\n return { ready }\n }\n\n const dataDir = cfg.dataDir\n const statusPath = join(dataDir, 'adapter-status.json')\n const writeStatus = (status: CatalogSnapshot, lastError: string): void => {\n void writeFile(\n statusPath,\n JSON.stringify({ ...status, lastError, writtenAt: new Date().toISOString() }, null, 2),\n 'utf8',\n ).catch(() => {})\n }\n\n // An explicit `dataDir` means the user owns the path: never read the pre-0.5\n // file and never delete anything. Otherwise the store falls back read-only to\n // `~/.dsh-magpie-connect/settings.json` and migrates it on the first save.\n const store = new SettingsStore({\n path: defaultSettingsPath(dataDir),\n legacyPath: config.dataDir === undefined ? join(legacyDataDir(), 'settings.json') : undefined,\n // Only the plugin-owned default directory is chmod-ed; an explicit\n // `dataDir` belongs to the user and is left as they set it.\n privateDir: config.dataDir === undefined,\n })\n const patchEndpoint = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey }\n const effective = () => resolveEffectiveEndpoint(patchEndpoint, store.get())\n\n /**\n * Publish `llm/adapters-updated`, the one notification DSH's model\n * directory listens to.\n *\n * The browser caches one `modelCatalog()` read per Host generation and\n * re-reads only on this event. Registering an adapter fires it once, but\n * nothing does for a pure in-memory change, so hiding models, switching\n * the gateway origin, or a refresh that moved the list all left the picker\n * on the stale snapshot until restart. `dsh-workbuddy-connect` solves the\n * same problem identically for its visibility toggles.\n */\n const announceTopology = (): void => {\n if (typeof ctx.emit !== 'function') return\n try {\n ctx.emit('llm/adapters-updated')\n } catch (error) {\n logger.warn(`dsh-magpie-connect: llm/adapters-updated emit failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const catalog = new ModelCatalog({\n baseUrl: effective().baseUrl,\n apiKey: effective().apiKey,\n refreshSeconds: cfg.refreshSeconds,\n cachePath: defaultCachePath(dataDir),\n onRefresh: (status, lastError) => {\n writeStatus(status, lastError)\n if (lastError) logger.warn(`dsh-magpie-connect: catalog refresh issue: ${lastError}`)\n },\n onInvalidate: announceTopology,\n })\n /**\n * Apply page settings to the live catalog + adapter (no restart needed).\n *\n * The endpoint is a pair: the gateway guards `GET /models` with the same key\n * as inference, so the key is part of the catalog's identity, not just the\n * URL. A key-only edit therefore re-points the catalog too \u2014 otherwise the\n * refresh keeps 401ing and the picker keeps serving the static snapshot,\n * which is why a model just ticked in the fetch dialog never appeared.\n */\n const applyPageSettings = (): void => {\n const page = store.get()\n const endpoint = resolveEffectiveEndpoint(patchEndpoint, page)\n // The gate: URL and key are both required. Anything missing clears the\n // catalog API root, which empties the picker and calls fail fast.\n // The value is the versioned root (`\u2026/v1`), passed through untouched.\n const configured = isConfigured(endpoint)\n catalog.setEndpoint(configured ? endpoint.baseUrl.replace(/\\/+$/, '') : '', configured ? endpoint.apiKey : '')\n catalog.setEnabled(page.enabledModels ?? null)\n }\n const adapter = new MagpieAdapter(catalog, {\n providerId: cfg.providerId,\n displayName: cfg.displayName,\n magpieBaseUrl: cfg.baseUrl,\n apiKey: cfg.apiKey,\n maxRetries: cfg.maxRetries,\n timeoutMs: cfg.timeoutMs,\n firstEventTimeoutMs: cfg.firstEventTimeoutMs,\n idleTimeoutMs: cfg.idleTimeoutMs,\n runtime: {\n baseUrl: () => {\n const endpoint = effective()\n return isConfigured(endpoint) ? endpoint.baseUrl.replace(/\\/+$/, '') : ''\n },\n apiKey: () => effective().apiKey,\n },\n resolveAttachments: () => {\n try {\n const attachments = typeof ctx.get === 'function' ? (ctx.get('attachments') as AttachmentStore | undefined) : undefined\n return attachments && typeof attachments.readImageRequest === 'function' ? attachments : undefined\n } catch {\n return undefined\n }\n },\n })\n store.onChange(applyPageSettings)\n\n // Register immediately: the provider must appear in the selector right\n // away, even while the catalog is still warming up (listModels is read\n // live at selector time, so models appear as refreshes land).\n ctx.llm.registerAdapter([cfg.providerId], adapter)\n logger.info(`dsh-magpie-connect: adapter registered for \"${cfg.providerId}\" (catalog warms up in background)`)\n void (async () => {\n // Startup order is load-bearing in both directions:\n //\n // 1. read the document first \u2014 until it is applied, the catalog is pointed\n // at the patch/default endpoint, not the user's, so any fetch it does\n // now fails and leaves the directory empty;\n // 2. apply it, so the catalog knows the real endpoint before it warms up;\n // 3. warm the directory;\n // 4. only then run the legacy conversion, which needs the ids the gateway\n // actually serves.\n //\n // Doing 3 before 2 was a regression: the warm-up hit the default endpoint,\n // failed, and the settings page fell back to the built-in snapshot.\n const persisted = await store.read()\n await store.hydrate(persisted, undefined)\n applyPageSettings()\n await catalog.start().catch((err) => {\n logger.error(`dsh-magpie-connect: catalog start failed: ${err instanceof Error ? err.message : String(err)}`)\n })\n await store.hydrate(persisted, catalog.directory())\n applyPageSettings()\n })().catch((err) => {\n logger.error(`dsh-magpie-connect: startup failed: ${err instanceof Error ? err.message : String(err)}`)\n })\n\n // Suppress the auto-generated config form: this plugin owns a dedicated\n // settings page (client half). Guarded \u2014 compositions without the settings\n // service simply skip it.\n try {\n if (typeof ctx.inject === 'function') {\n ctx.inject(['settings'], (settingsCtx: Record<string, unknown>) => {\n try {\n const scoped = settingsCtx as {\n effect?: (fn: () => unknown, label?: string) => unknown\n settings?: { configure?: (policy: unknown, fiber: unknown) => unknown }\n }\n const fiber = (ctx as unknown as Record<string, unknown>).fiber\n scoped.effect?.(() => scoped.settings?.configure?.({ auto: false }, fiber), 'dsh-magpie-connect: custom settings page')\n } catch {\n // presentation policy is best-effort\n }\n })\n }\n } catch {\n // presentation policy is best-effort\n }\n\n // Newest generation wins: shared route handlers below always resolve through\n // here, so the settings page talks to the latest store/catalog/adapter even\n // when an older generation installed the routes.\n currentBackend = { store, catalog, patchEndpoint, effective, applyPageSettings }\n\n installSettingsRoutes(ctx, logger)\n\n const maybeEffect = (ctx as { effect?: PluginContext['effect'] }).effect\n if (typeof maybeEffect === 'function') {\n maybeEffect.call(ctx, () => () => {\n catalog.stop()\n })\n }\n return { ready }\n}\n\nexport { MagpieAdapter } from './adapter/magpie-adapter.ts'\nexport { ModelCatalog } from './adapter/catalog.ts'\nexport { SettingsStore, isConfigured, resolveEffectiveEndpoint } from './settings.ts'\nexport {\n resolveConfig,\n type DshMagpieConnectConfig,\n} from './config.ts'\n", "import { randomBytes } from 'node:crypto'\nimport { readFile, rename, rm, writeFile, mkdir } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\n/**\n * Model directory for the Magpie gateway.\n *\n * Single source: `GET {baseUrl}/models` already curates the servable set\n * with full per-model metadata (modalities, native endpoints, reasoning\n * ladders, context limits). There is no paid/free filter \u2014 everything listed\n * is exposed. A disk cache plus a compile-time static snapshot covers gateway\n * outages (the plugin still registers, the picker still lists).\n *\n * The gateway guards that endpoint with the same Bearer key as inference, so\n * every fetch here carries it: a keyless refresh is answered 401 and the\n * picker silently keeps the static snapshot instead of the live directory.\n *\n * `baseUrl` is the versioned API root (default `http://127.0.0.1:3425/v1`),\n * never an origin: the gateway may move to `/v2`, and the plugin must not know\n * that version.\n */\n\nexport interface MagpieModelEntry {\n id: string\n displayName: string\n contextWindow?: number\n maxTokens?: number\n /** Whether the gateway accepts image input for this model. */\n image: boolean\n /** Raw gateway `native_endpoints` (may be empty when undisclosed). */\n nativeEndpoints: string[]\n /** Whether the gateway reports thinking support. */\n reasoning: boolean\n /** Effort allowlist from `supported_reasoning_levels` (canonical order). */\n efforts?: string[]\n}\n\n/**\n * Thinking levels the gateway uses. pi-ai natively understands the minimal\u2192max\n * ladder; `none` (thinking disabled) and `ultra` (beyond max, e.g. Terra) are\n * gateway extensions the adapter forwards verbatim on the Responses /\n * completions wire instead of clamping.\n */\nexport const KNOWN_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const\nexport const EXTENDED_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const\n\nexport type KnownEffort = (typeof KNOWN_EFFORTS)[number]\nexport type ExtendedEffort = (typeof EXTENDED_EFFORTS)[number]\n\n/** Picker display order: `none` (disable) first, then increasing strength. */\nconst EFFORT_ORDER: readonly string[] = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']\n\nconst EFFORT_LABELS: Record<string, { name: string; description: string }> = {\n none: { name: 'None', description: '\u5173\u95ED\u601D\u8003\uFF0C\u76F4\u63A5\u56DE\u7B54' },\n minimal: { name: 'Minimal', description: '\u6700\u5C11\u601D\u8003\uFF0C\u6700\u5FEB' },\n low: { name: 'Low', description: '\u8F7B\u91CF\u601D\u8003\uFF0C\u9002\u5408\u7B80\u5355\u95EE\u7B54' },\n medium: { name: 'Medium', description: '\u9ED8\u8BA4\u6863\u4F4D\uFF0C\u5747\u8861\u8D28\u91CF\u4E0E\u901F\u5EA6' },\n high: { name: 'High', description: '\u6DF1\u5EA6\u601D\u8003\uFF0C\u9002\u5408\u590D\u6742\u7F16\u7801' },\n xhigh: { name: 'Extra high', description: '\u8D85\u9AD8\u601D\u8003\u5F3A\u5EA6' },\n max: { name: 'Max', description: '\u6700\u5F3A\u601D\u8003\uFF08pi-ai \u6863\u4F4D\uFF09\uFF0C\u6700\u6162' },\n ultra: { name: 'Ultra', description: '\u6781\u9650\u601D\u8003\uFF08\u7F51\u5173\u76F4\u901A\uFF09\uFF0C\u6700\u6162\u6700\u8D35' },\n}\n\nexport interface ReasoningEffortChoice {\n id: string\n name: string\n description?: string\n}\n\n/** Normalize one gateway effort spelling; unknown spellings are dropped. */\nexport function normalizeEffort(raw: unknown): string | undefined {\n if (typeof raw !== 'string') return undefined\n const level = raw.trim().toLowerCase()\n return (EFFORT_ORDER as readonly string[]).includes(level) ? level : undefined\n}\n\n/** Canonicalize an effort list: keep known spellings, dedupe, order canonically. */\nexport function canonicalEfforts(values: readonly unknown[] | undefined): string[] | undefined {\n if (!Array.isArray(values)) return undefined\n const out: string[] = []\n for (const value of values) {\n const level = normalizeEffort(typeof value === 'object' && value !== null ? (value as { effort?: unknown }).effort ?? value : value)\n if (level !== undefined && !out.includes(level)) out.push(level)\n }\n if (out.length === 0) return undefined\n return EFFORT_ORDER.filter((level) => out.includes(level))\n}\n\n/** Build picker efforts for an allowlist (display order = none\u2192minimal\u2192\u2026\u2192ultra). */\nexport function effortsFor(efforts: readonly string[] | undefined): ReasoningEffortChoice[] {\n const allowed = new Set(efforts ?? [])\n return EFFORT_ORDER.filter((level) => allowed.has(level)).map((level) => {\n const label = EFFORT_LABELS[level] ?? { name: level, description: '' }\n return { id: level, name: label.name, description: label.description }\n })\n}\n\n/**\n * pi-ai `thinkingLevelMap` for an effort allowlist. `off: null` is\n * load-bearing: without it pi-ai falls back to `reasoning.effort: 'none'`\n * on the Responses lane, which the gateway rejects with 400. Every\n * non-listed known level maps to null so `getSupportedThinkingLevels` hides\n * it and `clampThinkingLevel` folds stale values to the nearest listed one.\n * Gateway extensions (`none`/`ultra`) never enter the map \u2014 the adapter\n * forwards them via `provider.stream` instead of `streamSimple`.\n */\nexport function thinkingLevelMapFor(efforts: readonly string[] | undefined): Record<string, string | null> {\n const allowed = new Set(efforts ?? [])\n const map: Record<string, string | null> = { off: null }\n for (const level of KNOWN_EFFORTS) map[level] = allowed.has(level) ? level : null\n return map\n}\n\n/**\n * True when the model must go through `/v1/responses` instead of chat\n * completions: the gateway lists responses as the only native endpoint\n * (Muse Spark, Codex/Grok lanes). Anything advertising\n * `/v1/chat/completions` \u2014 including multi-endpoint models \u2014 rides the\n * completions lane for better tool support.\n */\nexport function requiresResponsesApiEntry(nativeEndpoints: readonly string[]): boolean {\n const hasCompletions = nativeEndpoints.some((endpoint) => endpoint.includes('/chat/completions'))\n if (hasCompletions) return false\n return nativeEndpoints.some((endpoint) => endpoint.includes('/responses'))\n}\n\n/** pi-ai `model.api` value for the given native endpoints. */\nexport function modelApiForEntry(nativeEndpoints: readonly string[]): 'openai-completions' | 'openai-responses' {\n return requiresResponsesApiEntry(nativeEndpoints) ? 'openai-responses' : 'openai-completions'\n}\n\n/** The gateway separates a model name from its group with a middle dot. */\nconst LABEL_GROUP_SEPARATOR = '\\u00B7'\n\n/** Capitalize only the first character; preserve the rest of a gateway/id group. */\nfunction capitalizeGroup(group: string): string {\n return group.length === 0 ? '' : group[0]!.toLocaleUpperCase() + group.slice(1)\n}\n\n/** Derive a fallback group from the id's first slash-delimited segment. */\nfunction groupFromId(id: string): string {\n const prefix = id.split('/', 1)[0]?.trim() ?? ''\n return capitalizeGroup(prefix)\n}\n\n/**\n * The one label both the DSH model picker and this plugin's settings page show.\n * The model name is exactly `display_name`. Prefer the group after the last\n * middle dot in `magpie_label`; if it is absent or empty, capitalize the first\n * character of the id's first path segment as the fallback group.\n */\nexport function displayNameFor(raw: Record<string, unknown>): string {\n const id = typeof raw.id === 'string' ? raw.id : ''\n const name = typeof raw.display_name === 'string' ? raw.display_name.trim() : ''\n if (name === '') return id\n const label = typeof raw.magpie_label === 'string' ? raw.magpie_label.trim() : ''\n const at = label.lastIndexOf(LABEL_GROUP_SEPARATOR)\n const parsedGroup = at >= 0 ? label.slice(at + 1).trim() : ''\n const idGroup = groupFromId(id)\n // Routing ids are the source of truth for these two lanes; their gateway\n // label group is generic and must not replace the explicit route prefix.\n const routingPrefix = id.startsWith('auto/') || id.startsWith('group/')\n const group = routingPrefix ? idGroup : parsedGroup || idGroup\n if (group === '') return id\n return `${group}/${name}`\n}\n\n/** Decode one gateway model object into a catalog entry. */\nexport function decodeModel(raw: unknown): MagpieModelEntry | undefined {\n if (!raw || typeof raw !== 'object') return undefined\n const record = raw as Record<string, unknown>\n const id = record.id\n if (typeof id !== 'string' || id.length === 0) return undefined\n const num = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined\n const displayName = displayNameFor(record)\n const contextWindow = num(record.context_window) ?? num(record.context_length) ?? num(record.max_input_tokens)\n const maxTokens = num(record.max_output_tokens)\n const modalities = record.modalities as { input?: unknown } | undefined\n const inputModalities = Array.isArray(modalities?.input) ? modalities.input.map(String).map((s) => s.toLowerCase()) : []\n const image = inputModalities.includes('image')\n const nativeEndpoints = Array.isArray(record.native_endpoints)\n ? (record.native_endpoints as unknown[]).filter((e): e is string => typeof e === 'string')\n : []\n const reasoning = record.reasoning === true\n const levels = record.supported_reasoning_levels\n const efforts = Array.isArray(levels)\n ? canonicalEfforts(levels.map((entry) => (entry as { effort?: unknown })?.effort ?? entry))\n : undefined\n return { id, displayName, ...(contextWindow !== undefined ? { contextWindow } : {}), ...(maxTokens !== undefined ? { maxTokens } : {}), image, nativeEndpoints, reasoning, ...(efforts !== undefined ? { efforts } : {}) }\n}\n\n/** Decode the full gateway `/v1/models` payload into entries keyed by id. */\nexport function decodeMagpieModels(data: unknown): Map<string, MagpieModelEntry> {\n const result = new Map<string, MagpieModelEntry>()\n if (!data || typeof data !== 'object') return result\n const payload = data as { data?: unknown }\n if (!Array.isArray(payload.data)) return result\n for (const raw of payload.data) {\n const entry = decodeModel(raw)\n if (entry && !result.has(entry.id)) result.set(entry.id, entry)\n }\n return result\n}\n\n/**\n * Compile-time static snapshot (observed 2026-10-02, 22 models): last-resort\n * bootstrap while the gateway is unreachable. Refreshed by hand when the\n * gateway catalog changes shape; live data always wins when reachable.\n *\n * These rows have no `magpie_label`, so their group comes from the id prefix\n * and their curated model name is retained. Live data still uses the same\n * `displayNameFor` rule.\n */\nconst staticMagpieModelSeeds: MagpieModelEntry[] = [\n { id: 'group/auto-gpt-4-1', displayName: 'GPT-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: [], reasoning: false },\n { id: 'group/auto-gpt-6-luna', displayName: 'GPT-6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: [], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'vercel/xiaomi/mimo-v2.6-flash', displayName: 'xiaomi/mimo-v2.6-flash', contextWindow: 1048576, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true },\n { id: 'vercel/alibaba/qwen3.8-omni-flash', displayName: 'alibaba/qwen3.8-omni-flash', contextWindow: 1000000, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['none', 'low', 'medium', 'xhigh'] },\n { id: 'vercel/openai/gpt-5.4-nano', displayName: 'openai/gpt-5.4-nano', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['none', 'low', 'medium', 'high', 'xhigh'] },\n { id: 'vercel/openai/gpt-4.1', displayName: 'openai/gpt-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: false },\n { id: 'vercel/google/gemini-2.5-flash-lite', displayName: 'google/gemini-2.5-flash-lite', contextWindow: 1048576, maxTokens: 65536, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'medium', 'high'] },\n { id: 'opencode-zen/muse-spark-1.3-contributor-free', displayName: 'Muse Spark 1.3 Free', contextWindow: 1048576, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'] },\n { id: 'opencode-zen/jev-1.13-free', displayName: 'jev-1.13-free', image: false, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: false },\n { id: 'opencode-zen/mimo-v2.6-flash-free', displayName: 'MiMo-V2.6-Flash Free', contextWindow: 200000, maxTokens: 32000, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: true },\n { id: 'opencode-zen/space-bunny-free', displayName: 'Space Bunny Free', contextWindow: 524288, maxTokens: 524288, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-6-luna', displayName: 'GPT-6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-5.6-terra', displayName: 'GPT-5.6-Terra', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] },\n { id: 'codex/gpt-5.6-luna', displayName: 'GPT-5.6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-5.5', displayName: 'GPT-5.5', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh'] },\n { id: 'copilot/gemini-3.8-flash', displayName: 'Gemini 3.8 Flash', contextWindow: 1048576, maxTokens: 65536, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'medium', 'high'] },\n { id: 'copilot/grok-4.7', displayName: 'grok-4.7', contextWindow: 500000, maxTokens: 500000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh'] },\n { id: 'copilot/gpt-4.1', displayName: 'gpt-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: false },\n { id: 'copilot/gpt-6-luna', displayName: 'gpt-6-luna', contextWindow: 922000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'copilot/claude-sonnet-5.5', displayName: 'claude-sonnet-5.5', contextWindow: 1000000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/messages'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'workbuddy-ai/hy4-preview-f', displayName: 'hy4-preview-f', contextWindow: 1000000, maxTokens: 64000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['high'] },\n { id: 'workbuddy-ai/deepseek-v4.1-flash', displayName: 'deepseek-v4.1-flash', contextWindow: 1000000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'high', 'max'] },\n]\n\n/** The exported snapshot, with each label derived by the one display-name rule. */\nexport const staticMagpieModels: MagpieModelEntry[] = staticMagpieModelSeeds.map((entry) => ({\n ...entry,\n displayName: displayNameFor({ id: entry.id, display_name: entry.displayName }),\n}))\n\nexport interface CatalogSnapshot {\n status: 'pending' | 'ready' | 'stale' | 'error'\n total: number\n exposed: number\n lastRefresh?: string\n}\n\nexport interface CatalogOptions {\n /** Refresh cadence (seconds). */\n refreshSeconds?: number\n /** Where the gateway snapshot cache lives (plugin data dir). */\n cachePath?: string\n /** Versioned API root override for tests. */\n baseUrl?: string\n /**\n * Gateway credential, sent as `Authorization: Bearer \u2026` on every catalog\n * fetch. The gateway guards `GET /models` with the same key it guards\n * inference with, so a refresh that omits it is answered 401 and the picker\n * silently stays on the static snapshot.\n */\n apiKey?: string\n fetchImpl?: typeof fetch\n now?: () => number\n /** Observability hook: fired after every refresh round. */\n onRefresh?: (status: CatalogSnapshot, lastError: string) => void\n /**\n * Fired when the exposed model set actually changes. DSH's picker caches\n * one `modelCatalog()` read per Host generation and only re-reads it on\n * `llm/adapters-updated`, so a pure in-memory change (hidden models, a\n * refresh that added or dropped models) is invisible without this.\n */\n onInvalidate?: () => void\n /** Delay between startup retries while the live catalog is empty (default 15s). */\n startupRetryMs?: number\n}\n\nconst FETCH_TIMEOUT_MS = 30_000\n\n/** Live model directory with refresh loop. All state in-memory; only the gateway snapshot persists. */\nexport class ModelCatalog {\n #entries: Map<string, MagpieModelEntry> = new Map()\n /**\n * Allowlist of model ids the picker offers. `null` = inherit the whole\n * directory (the default, and what a fresh install gets); a Set (possibly\n * empty) = exactly these ids. Mirrors DSH's own Models settings, where a\n * provider's `models` array replaces the catalog instead of filtering it.\n */\n #enabled: Set<string> | null = null\n #updatedAt = 0\n #lastError = ''\n #refreshSeconds: number\n #cachePath?: string\n #baseUrl: string\n #apiKey: string\n #fetch: typeof fetch\n #now: () => number\n #timer: NodeJS.Timeout | null = null\n #stopped = false\n #onRefresh?: (status: CatalogSnapshot, lastError: string) => void\n #onInvalidate?: () => void\n #startupRetryMs: number\n /**\n * Last announced exposed set. The picker caches its catalog read, so an\n * invalidation is only worth a Host event when the exposed ids really\n * moved \u2014 otherwise the refresh loop would emit every 5 minutes.\n */\n #announced = ''\n\n constructor(options: CatalogOptions = {}) {\n this.#refreshSeconds = options.refreshSeconds ?? 300\n this.#cachePath = options.cachePath\n this.#baseUrl = (options.baseUrl ?? '').replace(/\\/+$/, '')\n this.#apiKey = options.apiKey ?? ''\n this.#fetch = options.fetchImpl ?? fetch\n this.#now = options.now ?? Date.now\n this.#onRefresh = options.onRefresh\n this.#onInvalidate = options.onInvalidate\n this.#startupRetryMs = options.startupRetryMs ?? 15_000\n }\n\n /**\n * Start the refresh loop: immediate fetch, fast retries while the live\n * catalog is still empty (the first fetch often races the machine's\n * network coming up), then the normal cadence.\n */\n async start(): Promise<void> {\n await this.refreshOnce()\n let attempts = 0\n while (this.#entries.size === 0 && attempts < 4 && !this.#stopped) {\n attempts += 1\n await new Promise((resolve) => setTimeout(resolve, this.#startupRetryMs))\n if (this.#stopped) return\n await this.refreshOnce()\n }\n if (this.#stopped) return\n this.#timer = setInterval(() => {\n void this.refreshOnce()\n }, this.#refreshSeconds * 1000)\n this.#timer.unref?.()\n }\n\n stop(): void {\n this.#stopped = true\n if (this.#timer) {\n clearInterval(this.#timer)\n this.#timer = null\n }\n }\n\n async refreshOnce(): Promise<void> {\n await this.refreshModels()\n if (this.#onRefresh) {\n try {\n this.#onRefresh(this.snapshot(), this.#lastError)\n } catch {\n // observers must never break the refresh loop\n }\n }\n // A refresh can add or drop models: tell the picker to re-read.\n this.#announce()\n }\n\n /**\n * Announce the exposed set when it changed.\n *\n * DSH's browser-side model directory caches one `modelCatalog()` read per\n * Host generation and only re-reads it on `llm/adapters-updated`, so\n * in-memory catalog mutations (hidden models, a refresh that moved the\n * list) are otherwise invisible until restart. Firing the event on every\n * refresh would also work but wakes the whole picker every 5 minutes, so\n * the exposed ids are fingerprinted and only a real change is announced.\n */\n #announce(): void {\n const fingerprint = this.#fingerprint()\n if (fingerprint === this.#announced) return\n this.#announced = fingerprint\n if (!this.#onInvalidate) return\n try {\n this.#onInvalidate()\n } catch {\n // observers must never break the refresh loop\n }\n }\n\n /** Stable fingerprint of the exposed set (ids + their capabilities). */\n #fingerprint(): string {\n const rows = this.list().map((id) => {\n const entry = this.#entryFor(id)\n return [\n id,\n entry?.displayName ?? '',\n entry?.image === true ? 'img' : '-',\n entry?.reasoning === true ? 'think' : '-',\n (entry?.efforts ?? []).join(','),\n String(entry?.contextWindow ?? 0),\n String(entry?.maxTokens ?? 0),\n ].join('|')\n })\n return rows.join('\\n')\n }\n\n /** Whether a gateway API root is configured (empty baseUrl = not configured). */\n get configured(): boolean {\n return this.#baseUrl !== ''\n }\n\n /**\n * Auth header for every catalog fetch. The gateway guards `GET /models` with\n * the same Bearer key as inference, so omitting it is answered 401 \u2014 which\n * the refresh loop then reports as a \"catalog issue\" while the picker keeps\n * serving whatever it already had.\n */\n #authHeaders(): Record<string, string> {\n return this.#apiKey === '' ? {} : { authorization: `Bearer ${this.#apiKey}` }\n }\n\n /**\n * Adopt a directory the settings page just read from the gateway.\n *\n * The fetch dialog asks the endpoint the form shows and gets the freshest\n * answer the session will see; the background refresh loop may be minutes\n * behind, or silently failing on a 401. Without this, a model the gateway has\n * dropped stays in the local directory \u2014 and therefore in the picker and the\n * settings list \u2014 until the next *successful* refresh, which may never come.\n *\n * Whole-set replacement, never a merge: the reply is the gateway's entire\n * catalog, so anything it no longer lists is gone. Empty input is refused\n * rather than treated as \"nothing served\", because a bad endpoint or a\n * transient failure must not blank the picker.\n * @param entries - the decoded gateway directory just fetched.\n * @returns whether the directory was adopted.\n */\n adoptDirectory(entries: Map<string, MagpieModelEntry>): boolean {\n if (entries.size === 0) return false\n this.#entries = new Map(entries)\n this.#updatedAt = this.#now()\n this.#lastError = ''\n if (this.#cachePath) void saveModelsCache(this.#cachePath, entries, this.#now()).catch(() => {})\n this.#announce()\n return true\n }\n\n async refreshModels(): Promise<void> {\n if (!this.configured) {\n this.#lastError = 'magpie gateway API URL or key is not configured \u2014 set both on the Magpie settings page'\n return\n }\n try {\n const entries = await fetchMagpieModels(this.#baseUrl, this.#fetch, { headers: this.#authHeaders() })\n this.#entries = entries\n this.#updatedAt = this.#now()\n this.#lastError = ''\n if (this.#cachePath) await saveModelsCache(this.#cachePath, entries, this.#now()).catch(() => {})\n } catch (err) {\n // Network failure with a cached copy is not fatal: load the cache.\n if (this.#cachePath && this.#entries.size === 0) {\n const cached = await loadModelsCache(this.#cachePath).catch(() => null)\n if (cached && cached.size > 0) {\n this.#entries = cached\n this.#updatedAt = this.#updatedAt === 0 ? this.#now() : this.#updatedAt\n return\n }\n }\n this.#lastError = err instanceof Error ? err.message : String(err)\n }\n }\n\n getEntry(model: string): MagpieModelEntry | undefined {\n return this.#entries.get(model)\n }\n\n /**\n * Replace the settings-page allowlist (`null` = inherit the whole directory).\n * Announces: the exposed set changes, and DSH's picker only re-reads it on\n * `llm/adapters-updated`.\n * @param ids - the allowed model ids, or `null` to inherit.\n */\n setEnabled(ids: readonly string[] | null): void {\n const next = ids === null ? null : new Set(ids)\n if (this.#sameSet(next)) return\n this.#enabled = next\n this.#announce()\n }\n\n /** The allowlist as stored: `null` when inheriting. */\n enabled(): string[] | null {\n return this.#enabled === null ? null : [...this.#enabled]\n }\n\n #sameSet(next: Set<string> | null): boolean {\n const current = this.#enabled\n if (next === null || current === null) return next === current\n return next.size === current.size && [...next].every((id) => current.has(id))\n }\n\n /** Whether the picker offers one id under the current allowlist. */\n #offers(model: string): boolean {\n return this.#enabled === null || this.#enabled.has(model)\n }\n\n /**\n * Where one model id comes from right now: the live directory, the built-in\n * snapshot, or nothing. The settings page labels its rows with this so a\n * model the gateway stopped listing is not mistaken for one it still serves.\n * @param model - the id to classify.\n * @returns `'gateway'`, `'static'`, or `'none'`.\n */\n sourceFor(model: string): 'gateway' | 'static' | 'none' {\n if (this.#entries.has(model)) return 'gateway'\n if (this.configured && staticMagpieModels.some((entry) => entry.id === model)) return 'static'\n return 'none'\n }\n\n isEnabled(model: string): boolean {\n return this.#offers(model)\n }\n\n /**\n * Point the refresh loop at another API root or credential (settings page\n * change).\n *\n * The key is part of the identity here, not just the URL: the gateway's\n * `GET /models` is key-guarded, so a key-only edit \u2014 the common case of\n * pasting a fresh key \u2014 must re-read the directory too. When only the key\n * moves the live entries are kept and merely re-fetched; when the root\n * moves they are dropped, because they describe a different gateway.\n * @param baseUrl - the versioned API root ('' = unconfigured).\n * @param apiKey - the gateway credential sent as a Bearer header.\n */\n setEndpoint(baseUrl: string, apiKey: string): void {\n const root = baseUrl.replace(/\\/+$/, '')\n const key = apiKey\n if (root === this.#baseUrl && key === this.#apiKey) return\n const rootChanged = root !== this.#baseUrl\n this.#baseUrl = root\n this.#apiKey = key\n if (rootChanged) {\n // Drop entries from the previous root: the picker must not serve a\n // stale directory, and clearing unconfigured state must empty it.\n this.#entries = new Map()\n this.#updatedAt = 0\n }\n this.#lastError = root === '' ? 'magpie gateway API URL or key is not configured \u2014 set both on the Magpie settings page' : ''\n // The picker must not keep serving the previous endpoint's directory.\n this.#announce()\n }\n\n /** Point the refresh loop at another API root (keeps the current key). */\n setBaseUrl(baseUrl: string): void {\n this.setEndpoint(baseUrl, this.#apiKey)\n }\n\n get baseUrl(): string {\n return this.#baseUrl\n }\n\n get apiKey(): string {\n return this.#apiKey\n }\n\n decision(model: string): { allowed: boolean; source: string; known: boolean } {\n if (!this.configured) return { allowed: false, source: 'unconfigured', known: false }\n if (!this.#offers(model)) return { allowed: false, source: 'not_enabled_by_settings', known: true }\n if (this.#entries.has(model)) return { allowed: true, source: 'gateway', known: true }\n const fallback = staticMagpieModels.find((entry) => entry.id === model)\n if (fallback) return { allowed: true, source: 'static_verified', known: false }\n return { allowed: false, source: this.#entries.size === 0 ? 'gateway_pending' : 'gateway_unknown', known: false }\n }\n\n /** Entry lookup: live map first, static snapshot while configured (never unconfigured). */\n #entryFor(model: string): MagpieModelEntry | undefined {\n if (!this.configured) return undefined\n return this.#entries.get(model) ?? staticMagpieModels.find((candidate) => candidate.id === model)\n }\n\n /**\n * Reasoning capability for one model id (DSH `resolveModel().reasoning`\n * + pi-ai `thinkingLevelMap` source of truth). Ladder-less thinking models\n * (reasoning without an effort list) think with upstream defaults \u2014 see\n * `thinks()` \u2014 and expose no picker.\n */\n reasoningFor(model: string): { efforts: ReasoningEffortChoice[]; defaultEffort: string } | undefined {\n const entry = this.#entryFor(model)\n const efforts = entry?.efforts\n if (!entry?.reasoning) return undefined\n if (efforts !== undefined && efforts.length > 0) {\n const mid = efforts[Math.floor(efforts.length / 2)] ?? 'medium'\n return { efforts: effortsFor(efforts), defaultEffort: efforts.includes('medium') ? 'medium' : mid }\n }\n return undefined\n }\n\n /** Whether the wire model may think (pi-ai `reasoning: true`). */\n thinks(model: string): boolean {\n const entry = this.#entryFor(model)\n return entry?.reasoning ?? false\n }\n\n /** Whether the model accepts image input. */\n supportsImage(model: string): boolean {\n const entry = this.#entryFor(model)\n return entry?.image ?? false\n }\n\n /** Whether one effort id is selectable for the model. */\n supportsEffort(model: string, effort: string): boolean {\n const entry = this.#entryFor(model)\n if (!entry?.reasoning) return false\n if (!entry.efforts || entry.efforts.length === 0) return true // ladder-less: upstream accepts, picker hidden\n return entry.efforts.includes(effort)\n }\n\n requiresResponsesApi(model: string): boolean {\n const entry = this.#entryFor(model)\n if (!entry) return /muse-spark|codex\\/|grok/i.test(model)\n return requiresResponsesApiEntry(entry.nativeEndpoints)\n }\n\n contextWindowFor(model: string): number {\n return this.#entryFor(model)?.contextWindow ?? 262144\n }\n\n maxTokensFor(model: string): number {\n return this.#entryFor(model)?.maxTokens ?? 32768\n }\n\n /**\n * Every id the directory knows right now, ignoring the allowlist: the live\n * gateway list, else the cached copy, else the built-in snapshot.\n *\n * This is what the settings page renders (each row then says whether the\n * allowlist offers it) and what the one-time migration intersects against.\n */\n directory(): string[] {\n if (!this.configured) return []\n if (this.#entries.size === 0) return staticMagpieModels.map((entry) => entry.id)\n return [...this.#entries.keys()].sort()\n }\n\n /** ids exposed to DSH: the directory filtered by the allowlist (empty while unconfigured). */\n list(): string[] {\n if (!this.configured) return []\n if (this.#entries.size === 0) return staticMagpieModels.map((entry) => entry.id).filter((id) => this.#offers(id))\n return [...this.#entries.keys()].filter((id) => this.#offers(id)).sort()\n }\n\n /** Catalog health snapshot (pending/ready/stale + counts). */\n snapshot(): CatalogSnapshot {\n const age = this.#updatedAt === 0 ? Infinity : this.#now() - this.#updatedAt\n const stale = this.#updatedAt !== 0 && age > 10 * 60 * 1000\n return {\n status: this.#updatedAt === 0 ? 'pending' : stale ? 'stale' : 'ready',\n total: this.#entries.size,\n exposed: this.list().length,\n ...(this.#updatedAt !== 0 ? { lastRefresh: new Date(this.#updatedAt).toISOString() } : {}),\n }\n }\n\n get lastError(): string {\n return this.#lastError\n }\n}\n\nasync function withTimeout(\n run: (signal: AbortSignal) => Promise<Response>,\n timeoutMs = FETCH_TIMEOUT_MS,\n): Promise<Response> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n return await run(controller.signal)\n } catch (error) {\n if (controller.signal.aborted) throw new Error(`models endpoint timed out after ${timeoutMs}ms`)\n throw error\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Fetch the live gateway model list.\n *\n * `baseUrl` is the versioned API root (`http://127.0.0.1:3425/v1`) exactly as the user\n * configured it; only the resource is appended. Never synthesize a version\n * here \u2014 a gateway on `/v2` would otherwise be asked for `/v2/v1/models`.\n */\nexport async function fetchMagpieModels(\n baseUrl: string,\n fetchImpl: typeof fetch,\n options: { timeoutMs?: number; headers?: Record<string, string> } = {},\n): Promise<Map<string, MagpieModelEntry>> {\n const response = await withTimeout(\n (signal) =>\n fetchImpl(`${baseUrl.replace(/\\/+$/, '')}/models`, {\n headers: { accept: 'application/json', ...(options.headers ?? {}) },\n signal,\n }),\n options.timeoutMs ?? FETCH_TIMEOUT_MS,\n )\n if (!response.ok) throw new Error(`models endpoint returned HTTP ${response.status}`)\n const payload = (await response.json()) as unknown\n const models = decodeMagpieModels(payload)\n if (models.size === 0) throw new Error('models endpoint returned an empty list')\n return models\n}\n\n/** Cache schema v3: labels now use display_name plus parsed/id-derived group. */\nconst MODELS_CACHE_VERSION = 3\n\ninterface ModelsCache {\n version: number\n updatedAt: number\n entries: MagpieModelEntry[]\n}\n\nasync function saveModelsCache(path: string, entries: Map<string, MagpieModelEntry>, now: number): Promise<void> {\n const cache: ModelsCache = { version: MODELS_CACHE_VERSION, updatedAt: now, entries: [...entries.values()] }\n // Same atomic-replace discipline as SettingsStore: random-suffix sibling,\n // rename over the target, no `rm` window. The cache is reproducible, so a\n // lost write is harmless \u2014 but a half-written file is not worth risking.\n const tmp = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n await mkdir(dirname(path), { recursive: true })\n try {\n await writeFile(tmp, JSON.stringify(cache), { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n await rename(tmp, path)\n } finally {\n await rm(tmp, { force: true }).catch(() => {})\n }\n}\n\nasync function loadModelsCache(path: string): Promise<Map<string, MagpieModelEntry>> {\n const raw = JSON.parse(await readFile(path, 'utf8')) as ModelsCache\n if (Date.now() - raw.updatedAt > 7 * 24 * 60 * 60 * 1000) {\n throw new Error('gateway cache too old')\n }\n const legacy = raw.version !== MODELS_CACHE_VERSION\n return new Map(raw.entries.map((entry) => {\n // A legacy cache has no raw gateway fields to recompute the new label\n // from. Preserve ids and capabilities, and use id as the label until a\n // successful refresh replaces them. This avoids falling back to the stale\n // compile-time snapshot offline.\n const relabeled = legacy ? { ...entry, displayName: entry.id } : entry\n return [entry.id, relabeled]\n }))\n}\n\n/** Default cache location next to the plugin data dir (index.ts convention). */\nexport function defaultCachePath(dataDir: string): string {\n return join(dataDir, 'magpie-models.json')\n}\n", "/**\n * Harness-home path helpers.\n *\n * Mirrors `@deepseek-ai/dsh-home-paths` closely enough to keep this plugin\n * independent of that package (the repo's `node_modules` carries no\n * `@deepseek-ai/*`, so importing it would break offline `typecheck`). The\n * resolution order is the documented one: an explicit path wins, then\n * `$DSH_HOME`, then `~/.dsh`; a blank override is treated as unset so a stray\n * empty variable never resolves the home to the current working directory.\n *\n * `legacyDataDir()` is deliberately NOT derived from the resolved home: the\n * 0.4.x line computed its state dir as `join(homedir(), '.dsh-magpie-connect')`\n * and never looked at `DSH_HOME`. Reading the old file through the new helper\n * would miss it for anyone who sets `DSH_HOME`, which is exactly the user who\n * must not silently lose their configuration.\n */\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\n/** Resolve the Harness home: explicit override > $DSH_HOME > ~/.dsh. */\nexport function resolveDshHome(configured?: string, env: NodeJS.ProcessEnv = process.env): string {\n if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured)\n const fromEnv = env.DSH_HOME\n if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return resolve(fromEnv)\n return join(homedir(), '.dsh')\n}\n\n/** Join path segments onto the resolved Harness home. */\nexport function dshHomePath(...segments: string[]): string {\n return join(resolveDshHome(), ...segments)\n}\n\n/**\n * State directory used by dsh-magpie-connect 0.4.x and earlier.\n *\n * `homedir`-based on purpose \u2014 see the module note. Used only to read/write the\n * pre-0.5 settings file during the one-time, save-triggered migration.\n */\nexport function legacyDataDir(): string {\n return join(homedir(), '.dsh-magpie-connect')\n}\n", "import { createProvider, type Api, type Context, type Model } from '@earendil-works/pi-ai'\nimport * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions'\nimport * as openaiResponses from '@earendil-works/pi-ai/api/openai-responses'\n\nimport {\n ModelCatalog,\n modelApiForEntry,\n thinkingLevelMapFor,\n} from './catalog.ts'\nimport { toStreamChunks, type HarnessChunk, type PiEvent } from './events.ts'\nimport {\n contentHasImage,\n toPiContext,\n toPiContextWithImages,\n type AttachmentStore,\n type HarnessGenerateOptions,\n} from './messages.ts'\nimport { withStallTimeout } from './watchdog.ts'\n\n/**\n * Magpie gateway adapter: registers as a DSH LlmAdapter and streams\n * directly from the configured API root (e.g. `\u2026/v1`) \u2014 chat completions for most models plus the\n * Responses API for responses-only models (Muse Spark / Codex / Grok lanes).\n *\n * Adapter contract: dsh-llm LlmAdapter (providerInfo/providerRetryPolicy/\n * imageRequestPricing/listModels/resolveModel/prepareCall/stream) \u2014\n * structural, no host import.\n *\n * Images resolve through the harness attachment service; thinking levels come\n * from the gateway catalog and forward verbatim (including the `none`/`ultra`\n * extensions pi-ai does not model).\n */\n\n/** Structural pi-ai provider surface the adapter consumes. */\nexport interface PiProviderLike {\n stream(model: unknown, context: unknown, options: unknown): AsyncIterable<PiEvent>\n streamSimple(model: unknown, context: unknown, options: unknown): AsyncIterable<PiEvent>\n}\n\n/** Live endpoint read per request so the settings page applies without restart. */\nexport interface RuntimeEndpoint {\n /** Versioned API root, e.g. `http://127.0.0.1:3425/v1` (no trailing slash). */\n baseUrl(): string\n /** Bearer key sent to the gateway. */\n apiKey(): string\n}\n\nexport const PROVIDER_ID = 'dsh-magpie-connect'\n\n/** Default picker label for the default route id. */\nexport const DEFAULT_DISPLAY_NAME = 'Magpie'\n\nexport interface MagpieModelInfo {\n id: string\n name: string\n contextWindow: number\n maxTokens: number\n}\n\nexport interface CatalogLike {\n list(): string[]\n decision(model: string): { allowed: boolean; source: string; known: boolean }\n getEntry?(model: string): { nativeEndpoints: string[]; displayName?: string } | undefined\n reasoningFor?(model: string): { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort: string } | undefined\n thinks?(model: string): boolean\n supportsImage?(model: string): boolean\n supportsEffort?(model: string, effort: string): boolean\n requiresResponsesApi?(model: string): boolean\n contextWindowFor?(model: string): number\n maxTokensFor?(model: string): number\n}\n\nconst DEFAULT_CONTEXT_WINDOW = 262144\nconst DEFAULT_MAX_TOKENS = 32768\n\n/** Match Magpie's DSH defaults: reserve reply space without exhausting the compaction budget. */\nfunction requestDefaultMaxTokens(contextWindow: number, outputLimit: number): number {\n const room = Math.max(1, Math.floor(contextWindow / 4), Math.floor(contextWindow / 2) - 65536)\n return Math.min(outputLimit, room)\n}\n\n/** Credential sent to the Magpie gateway (it needs none; pi-ai requires a value). */\nconst DEFAULT_API_KEY = 'not-needed'\n\n/** Connection-setup retries (429/5xx with backoff, interruptible by abort). */\nexport const DEFAULT_MAX_RETRIES = 2\n/** Overall SDK request cap (replaces the OpenAI SDK 10 min default). */\nexport const DEFAULT_TIMEOUT_MS = 300_000\n/** Max wait for the first upstream event (queueing happens here). */\nexport const DEFAULT_FIRST_EVENT_TIMEOUT_MS = 90_000\n/** Max silence between upstream events once streaming. */\nexport const DEFAULT_IDLE_TIMEOUT_MS = 60_000\n\nconst STRENGTH_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const\n\n/**\n * The attribution header dsh-llm's own adapters send on every provider\n * request (`attributionHeaders()`, its APP_IDENTITY rendered as\n * `product/version (+url)`). Sent verbatim: a newer host's version string\n * changes nothing for the gateway, which matches the `deepseek-harness`\n * prefix alone.\n */\nconst DSH_USER_AGENT = 'deepseek-harness/0.2.2-rc.1 (+https://github.com/deepseek-ai/deepseek-harness)'\n\n/**\n * Plan the wire `reasoning_effort` for one request. Returns the effort to\n * send via `provider.stream`, or undefined to omit the field (gateway\n * default applies).\n *\n * - `off` aliases `none` (explicitly disable thinking).\n * - `none` sends only when the model lists it; otherwise omitted.\n * - `ultra` sends when listed; otherwise degrades to the highest listed\n * strength level (`max` \u2192 \u2026 \u2192 `minimal`).\n * - Known strength levels send verbatim when listed or when the model thinks\n * without a ladder (gateway decides); otherwise clamped up-then-down to\n * the nearest listed level so a stale remembered value never 400s.\n * - Unknown values and non-reasoning models omit.\n */\nexport function planReasoningEffort(\n requested: unknown,\n model: string,\n catalog: Pick<CatalogLike, 'thinks' | 'supportsEffort' | 'reasoningFor'>,\n): string | undefined {\n if (typeof requested !== 'string') return undefined\n const level = requested.trim().toLowerCase()\n if (level === '') return undefined\n const thinks = catalog.thinks?.(model) ?? false\n if (!thinks) return undefined\n const normalized = level === 'off' ? 'none' : level\n const supports = (effort: string): boolean => catalog.supportsEffort?.(model, effort) ?? false\n const ladder = catalog.reasoningFor?.(model)?.efforts.map((effort) => effort.id)\n const ladderLess = ladder === undefined\n\n if (normalized === 'none') {\n return supports('none') ? 'none' : undefined\n }\n if (!(STRENGTH_ORDER as readonly string[]).includes(normalized)) return undefined\n if (supports(normalized) || ladderLess) return normalized\n // Clamp a stale/foreign level up-then-down (pi-ai clamp order).\n const order = STRENGTH_ORDER as readonly string[]\n const index = order.indexOf(normalized as (typeof STRENGTH_ORDER)[number])\n if (index !== -1) {\n for (let i = index + 1; i < order.length; i++) {\n const candidate = order[i] as string\n if (supports(candidate)) return candidate\n }\n for (let i = index - 1; i >= 0; i--) {\n const candidate = order[i] as string\n if (supports(candidate)) return candidate\n }\n }\n return undefined\n}\n\nfunction toPiModel(\n providerId: string,\n baseUrl: string,\n id: string,\n catalog: CatalogLike,\n contextWindow = DEFAULT_CONTEXT_WINDOW,\n maxTokens = DEFAULT_MAX_TOKENS,\n): Model<Api> {\n const endpoints = catalog.getEntry?.(id)?.nativeEndpoints ?? []\n const api = modelApiForEntry(endpoints)\n const entryThinks = catalog.thinks?.(id) ?? api === 'openai-responses'\n const ladder = catalog.reasoningFor?.(id)\n const ladderIds = ladder?.efforts.map((effort) => effort.id)\n const resolvedContext = catalog.contextWindowFor?.(id) ?? contextWindow\n const resolvedMax = catalog.maxTokensFor?.(id) ?? maxTokens\n if (api === 'openai-responses') {\n return {\n id,\n name: id,\n api,\n provider: providerId,\n baseUrl,\n reasoning: true,\n thinkingLevelMap: thinkingLevelMapFor(ladderIds),\n input: catalog.supportsImage?.(id) ?? true ? ['text', 'image'] : ['text'],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: resolvedContext,\n maxTokens: resolvedMax,\n }\n }\n const wire: Model<Api> = {\n id,\n name: id,\n api,\n provider: providerId,\n baseUrl,\n reasoning: entryThinks,\n input: catalog.supportsImage?.(id) ?? false ? ['text', 'image'] : ['text'],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: resolvedContext,\n maxTokens: resolvedMax,\n }\n if (entryThinks) wire.thinkingLevelMap = thinkingLevelMapFor(ladderIds)\n return wire\n}\n\nexport class MagpieAdapter {\n readonly #catalog: CatalogLike\n readonly #provider: PiProviderLike\n readonly #providerId: string\n readonly #displayName: string\n /** Static fallback API root; the live settings page overrides per request. */\n readonly #fallbackBaseUrl: string\n readonly #fallbackApiKey: string\n readonly #runtime?: RuntimeEndpoint\n readonly #maxRetries: number\n readonly #timeoutMs: number\n readonly #firstEventTimeoutMs: number\n readonly #idleTimeoutMs: number\n readonly #resolveAttachments?: () => AttachmentStore | undefined\n\n constructor(\n catalog: CatalogLike,\n options: {\n magpieBaseUrl?: string\n baseUrl?: string\n providerOverride?: unknown\n /** Route id registered into DSH (model `provider` field + pi-ai provider tag). */\n providerId?: string\n /** Display name reported via providerInfo (model picker grouping label). */\n displayName?: string\n /** Gateway credential (the gateway needs none). */\n apiKey?: string\n /**\n * Live endpoint read per request (settings page). Falls back to the\n * static `magpieBaseUrl`/`apiKey` options when absent.\n */\n runtime?: RuntimeEndpoint\n /** Connection-setup retries for 429/5xx (default 2). */\n maxRetries?: number\n /** Overall SDK request cap in ms (default 300000). */\n timeoutMs?: number\n /** Stall watchdog: max wait for the first upstream event in ms (default 90000; <=0 disables). */\n firstEventTimeoutMs?: number\n /** Stall watchdog: max silence between upstream events in ms (default 60000; <=0 disables). */\n idleTimeoutMs?: number\n /** Harness attachment service for image bytes (wired in index.ts). */\n resolveAttachments?: () => AttachmentStore | undefined\n } = {},\n ) {\n this.#catalog = catalog\n this.#providerId = options.providerId ?? PROVIDER_ID\n this.#displayName = options.displayName ?? (options.providerId ?? DEFAULT_DISPLAY_NAME)\n // The configured value is already the versioned API root (`\u2026/v1`), which is\n // exactly what pi-ai's `baseUrl` expects: it appends `/chat/completions`\n // and `/responses` itself. Synthesizing a version here would double it and\n // would hard-code `/v1` against a gateway that later moves to `/v2`.\n this.#fallbackBaseUrl = (options.magpieBaseUrl ?? options.baseUrl ?? '').replace(/\\/+$/, '')\n this.#fallbackApiKey = options.apiKey ?? DEFAULT_API_KEY\n this.#runtime = options.runtime\n this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n this.#firstEventTimeoutMs = options.firstEventTimeoutMs ?? DEFAULT_FIRST_EVENT_TIMEOUT_MS\n this.#idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS\n this.#resolveAttachments = options.resolveAttachments\n if (options.providerOverride !== undefined) {\n this.#provider = options.providerOverride as never\n return\n }\n this.#provider = createProvider<Api>({\n id: this.#providerId,\n name: this.#displayName,\n baseUrl: this.#fallbackBaseUrl,\n auth: {\n apiKey: {\n name: 'Magpie gateway',\n resolve: async () => ({ auth: { apiKey: this.#runtime?.apiKey() ?? this.#fallbackApiKey } }),\n },\n },\n models: [],\n // Mixed-API provider: pi-ai dispatches on `model.api`, so completions\n // models ride /v1/chat/completions while responses-only models ride\n // /v1/responses through the same provider instance.\n api: {\n 'openai-completions': openaiCompletions,\n 'openai-responses': openaiResponses,\n },\n }) as unknown as PiProviderLike\n }\n\n providerInfo(provider: string): { id: string; name: string } {\n return { id: provider, name: this.#displayName }\n }\n\n /**\n * dsh-llm calls this unconditionally at registration.\n * undefined = the host default retry policy.\n */\n providerRetryPolicy(_provider: string): undefined {\n return undefined\n }\n\n /**\n * Per-route visual-token pricing for the token meter (`/compact` calls\n * this unconditionally via `ctx.llm.imageRequestPricing`). The gateway\n * charges no separate visual tokens (pi-ai cost is 0), so like the host\n * base-class default we declare no per-route pricing.\n */\n imageRequestPricing(_provider: string, _model: string): undefined {\n return undefined\n }\n\n /**\n * Picker label: the catalog's `<group>/<display_name>` label\n * (e.g. \"Codex/GPT-6-Luna\"); the group comes from `magpie_label` or falls\n * back to the capitalized first id segment. The id itself stays the route id\n * (`codex/gpt-6-luna`) for requests and session history.\n */\n #labelFor(id: string): string {\n const label = this.#catalog.getEntry?.(id)?.displayName\n return typeof label === 'string' && label.trim() !== '' ? label : id\n }\n\n /** Advisory catalog for the DSH model picker (deduped; dsh-llm rejects duplicates). */\n listModels(provider: string): Array<{ provider: string; id: string; name: string; inputModalities: string[] }> {\n const seen = new Set<string>()\n const models: Array<{ provider: string; id: string; name: string; inputModalities: string[] }> = []\n for (const id of this.#catalog.list()) {\n if (seen.has(id)) continue\n seen.add(id)\n const image = this.#catalog.supportsImage?.(id) ?? false\n models.push({ provider, id, name: this.#labelFor(id), inputModalities: image ? ['text', 'image'] : ['text'] })\n }\n return models\n }\n\n resolveModel(\n provider: string,\n model: string,\n ): {\n provider: string\n id: string\n name: string\n inputModalities: string[]\n context: { contextWindow: number }\n defaultMaxTokens: number\n reasoning?: {\n efforts: ReadonlyArray<{ id: string; name: string; description?: string }>\n defaultEffort?: string\n }\n } {\n // DSH capability seam: exposing efforts lights up the session model\n // selector's reasoning picker; ids flow back as\n // GenerateOptions.reasoningEffort and are forwarded verbatim by\n // planReasoningEffort (gateway extensions `none`/`ultra` included).\n // No `off` entry: omission keeps the gateway default (= defaultEffort).\n const image = this.#catalog.supportsImage?.(model) ?? this.#catalog.requiresResponsesApi?.(model) ?? false\n const ladder = this.#catalog.reasoningFor?.(model)\n const contextWindow = this.#catalog.contextWindowFor?.(model) ?? DEFAULT_CONTEXT_WINDOW\n return {\n provider,\n id: model,\n name: this.#labelFor(model),\n inputModalities: image ? ['text', 'image'] : ['text'],\n context: { contextWindow },\n defaultMaxTokens: requestDefaultMaxTokens(contextWindow, this.#catalog.maxTokensFor?.(model) ?? DEFAULT_MAX_TOKENS),\n ...(ladder !== undefined ? { reasoning: ladder } : {}),\n }\n }\n\n async prepareCall(\n provider: string,\n model: string,\n _signal?: AbortSignal,\n ): Promise<{\n model: ReturnType<MagpieAdapter['resolveModel']>\n stream: (options: HarnessGenerateOptions) => AsyncGenerator<HarnessChunk>\n }> {\n return {\n model: this.resolveModel(provider, model),\n stream: (options) => this.stream(options),\n }\n }\n\n /**\n * Fail fast when no gateway API URL is configured (picker stays empty too).\n * @returns the versioned API root, trailing slash stripped.\n */\n #requireBaseUrl(): string {\n const raw = this.#runtime?.baseUrl() ?? this.#fallbackBaseUrl\n const baseUrl = raw.replace(/\\/+$/, '')\n if (baseUrl === '') {\n throw new Error('dsh-magpie-connect: Magpie gateway API URL or key is not configured \u2014 open Settings \u2192 Magpie and fill in both')\n }\n return baseUrl\n }\n\n /** Effective bearer key for this request. */\n #wireApiKey(): string {\n return this.#runtime?.apiKey() ?? this.#fallbackApiKey\n }\n\n /**\n * Stream one chat turn from the Magpie gateway: a single pi-ai stream,\n * translated to harness chunks verbatim. Upstream failures (rate limit,\n * auth, timeout, transport) arrive as classified finish reasons, and\n * turn-level retries stay owned by DSH.\n *\n * A stall watchdog races every upstream event against a timer: on expiry\n * the upstream is aborted and the turn ends fast with a TIMEOUT error\n * instead of hanging to the SDK/harness timeout.\n */\n async *stream(options: HarnessGenerateOptions): AsyncGenerator<HarnessChunk> {\n const baseUrl = this.#requireBaseUrl()\n const endpoints = this.#catalog.getEntry?.(options.model)?.nativeEndpoints ?? []\n const hasImage = contentHasImage(options.messages)\n if (hasImage && !(this.#catalog.supportsImage?.(options.model) ?? false)) {\n throw new Error(`dsh-magpie-connect: model \"${options.model}\" does not accept image input`)\n }\n const context = hasImage\n ? await this.#imageContext(options, endpoints)\n : toPiContext(options, endpoints)\n const model = toPiModel(this.#providerId, baseUrl, options.model, this.#catalog)\n // Linked controller: the watchdog aborts the upstream on stall, while a\n // harness abort (user stop / host timeout) still propagates through.\n const controller = new AbortController()\n const harnessSignal = options.signal\n const onHarnessAbort = (): void => controller.abort()\n if (harnessSignal) {\n if (harnessSignal.aborted) controller.abort()\n else harnessSignal.addEventListener('abort', onHarnessAbort, { once: true })\n }\n try {\n const events = withStallTimeout(\n this.#eventsFor(options, context, model, controller.signal) as AsyncIterable<PiEvent>,\n { firstEventTimeoutMs: this.#firstEventTimeoutMs, idleTimeoutMs: this.#idleTimeoutMs },\n { model: options.model, onTimeout: () => controller.abort() },\n )\n yield* toStreamChunks(events, model.contextWindow)\n } finally {\n harnessSignal?.removeEventListener('abort', onHarnessAbort)\n }\n }\n\n async #imageContext(options: HarnessGenerateOptions, endpoints: readonly string[]): Promise<ReturnType<typeof toPiContext>> {\n const attachments = this.#resolveAttachments?.()\n if (!attachments) {\n throw new Error('dsh-magpie-connect: image input requires the attachment service')\n }\n return toPiContextWithImages(options, attachments, endpoints)\n }\n\n #eventsFor(\n options: HarnessGenerateOptions,\n context: ReturnType<typeof toPiContext>,\n model: ReturnType<typeof toPiModel>,\n signal: AbortSignal,\n ): unknown {\n // Single dispatch through `provider.stream` with our own clamped effort:\n // gateway extensions (`none`/`ultra`) ride verbatim, known levels ride\n // the ladder, and omission keeps the gateway default.\n const reasoningEffort = planReasoningEffort(options.reasoningEffort, options.model, this.#catalog)\n // Attribution rides dsh-llm's own shape (`user-agent`:\n // `deepseek-harness/<version> (+url)`, the value `attributionHeaders()`\n // sends on the official adapters). Magpie names a client by its\n // User-Agent alone \u2014 the gateway key it accepts is anonymous \u2014 so\n // without this the plugin's turns read as the OpenAI SDK's\n // (\"OpenAI/JS 6.26.0\"), and the gateway's DSH-specific views\n // (the `agent == \"dsh\"` ones) never see them as DSH's.\n const sessionId = typeof options.sessionId === 'string' ? options.sessionId : undefined\n return this.#provider.stream(model, context as unknown as Context, {\n apiKey: this.#wireApiKey(),\n signal,\n maxRetries: this.#maxRetries,\n timeoutMs: this.#timeoutMs,\n temperature: options.temperature,\n maxTokens: options.maxTokens ?? requestDefaultMaxTokens(model.contextWindow, model.maxTokens),\n ...(reasoningEffort !== undefined ? { reasoningEffort } : {}),\n headers: {\n 'user-agent': DSH_USER_AGENT,\n // The session id rides the same header Magpie's `/v1/magpie/route`\n // reads (`x-session-id`, one of its recognized session headers): with\n // it the gateway tags each request's routing with the DSH session, so\n // the composer's routing popover can show this session's latest route.\n // Official dsh-llm adapters do the same (`x-deepseek-harness-session-id`,\n // which Magpie also reads; the generic name keeps third-party gateways\n // out of DSH's private namespace).\n ...(sessionId !== undefined ? { 'x-session-id': sessionId } : {}),\n // DSH marks compaction requests with a header, not its prompt\n // (`dshCompacts` in magpie): \"only the mark says so\". The official\n // adapters send it when `purpose` is compaction.\n ...(options.purpose === 'compaction' ? { 'x-deepseek-harness-compact': '1' } : {}),\n },\n })\n }\n\n /** Expose the live catalog snapshot for diagnostics. */\n catalogStatus(): { total: number; exposed: number } {\n const list = this.#catalog.list()\n return { total: list.length, exposed: list.length }\n }\n\n decisionFor(model: string): { allowed: boolean; source: string } {\n const decision = this.#catalog.decision(model)\n return { allowed: decision.allowed, source: decision.source }\n }\n}\n\n/** Build the adapter over a live catalog. */\nexport function createMagpieAdapter(catalog: ModelCatalog): MagpieAdapter {\n return new MagpieAdapter(catalog)\n}\n", "/**\n * pi-ai AssistantMessageEvent -> harness StreamChunks.\n * The chunk stream must end with `usage` then `finish`.\n */\n\nexport type HarnessChunk =\n | { type: 'block-start'; index: number; blockType: 'text' | 'reasoning' | 'tool-call' }\n | { type: 'text-delta'; index: number; text: string }\n | { type: 'block-end'; index: number; block: { type: 'text'; text: string } | { type: 'reasoning'; text: string } | { type: 'tool-call'; id: string; name: string; arguments: string } }\n | { type: 'reasoning-delta'; index: number; text: string }\n | { type: 'tool-call-delta'; index: number; id: string; name?: string; argumentsDelta: string }\n | { type: 'usage'; usage: { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number } }\n | { type: 'finish'; reason: FinishReason; replayState?: unknown }\n\nexport type FinishReason =\n | { kind: 'stop' }\n | { kind: 'max-tokens' }\n | { kind: 'tool-calls' }\n | { kind: 'aborted'; failure: { message: string; code: string } }\n | { kind: 'error'; failure: { message: string; code: string } }\n\n/** pi-ai AssistantMessageEvent vocabulary (subset we consume). */\nexport type PiEvent =\n | { type: 'start'; partial: PiAssistantPartial }\n | { type: 'text_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'text_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'text_end'; contentIndex: number; content: string; partial: PiAssistantPartial }\n | { type: 'thinking_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'thinking_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'thinking_end'; contentIndex: number; content: string; partial: PiAssistantPartial }\n | { type: 'toolcall_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'toolcall_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'toolcall_end'; contentIndex: number; toolCall: { id: string; name: string; arguments: Record<string, unknown> }; partial: PiAssistantPartial }\n | { type: 'done'; message: PiDoneMessage }\n | { type: 'error'; error: PiDoneMessage }\n\nexport interface PiAssistantPartial {\n content: Array<{ type: string; id?: string; name?: string; [key: string]: unknown }>\n [key: string]: unknown\n}\n\n/** pi-ai AssistantMessage content block (done/error messages carry these). */\nexport type PiAssistantBlock = { type: string; [key: string]: unknown }\n\nexport interface PiDoneMessage {\n api: string\n provider: string\n model: string\n responseModel?: string\n responseId?: string\n content: PiAssistantBlock[]\n usage: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens: number }\n stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted'\n errorMessage?: string\n [key: string]: unknown\n}\n\nconst CONTEXT_WINDOW_EXCEEDED = 'CONTEXT_WINDOW_EXCEEDED'\nconst EMPTY_RESPONSE = 'EMPTY_RESPONSE'\nconst QUOTA_EXCEEDED = 'QUOTA_EXCEEDED'\n\nfunction classifyError(text: string): string {\n if (/\\b(?:401|403)\\b/.test(text)) return 'AUTH'\n if (/insufficient|quota|billing/i.test(text)) return QUOTA_EXCEEDED\n if (/\\b429\\b|rate.?limit/i.test(text)) return 'RATE_LIMIT'\n if (/\\b413\\b|payload too large|request body too large/i.test(text)) return 'INVALID_REQUEST'\n if (/\\b400\\b|invalid.?request/i.test(text)) return 'INVALID_REQUEST'\n if (/\\b5\\d\\d\\b/.test(text)) return 'SERVER'\n if (/\\btime(?:d)?\\s*out\\b|timeout/i.test(text)) return 'TIMEOUT'\n if (/\\b(?:network|connection|socket|fetch)\\b|\\bECONN[A-Z]+\\b|terminated|premature close/i.test(text)) return 'TRANSPORT'\n return 'UPSTREAM'\n}\n\nfunction isContextOverflow(message: PiDoneMessage, contextWindow: number): boolean {\n // pi-ai isContextOverflow equivalent: error-free finish whose input usage\n // alone exceeds the resolved window.\n return message.stopReason === 'stop' && message.usage.input > contextWindow\n}\n\n/** Map a pi-ai terminal message to a harness finish reason. */\nfunction mapStopReason(message: PiDoneMessage, contextWindow: number): FinishReason {\n if (isContextOverflow(message, contextWindow) || (message.stopReason === 'error' && message.errorMessage !== undefined && /context/i.test(message.errorMessage) && /exceed|window|length|token/i.test(message.errorMessage))) {\n return {\n kind: 'error',\n failure: {\n message: message.errorMessage ?? `pi-ai detected context overflow for model \"${message.model}\"`,\n code: CONTEXT_WINDOW_EXCEEDED,\n },\n }\n }\n switch (message.stopReason) {\n case 'stop':\n if (message.content.length === 0) {\n return {\n kind: 'error',\n failure: { message: `model \"${message.model}\" returned a completed response with no content`, code: EMPTY_RESPONSE },\n }\n }\n return { kind: 'stop' }\n case 'length':\n return { kind: 'max-tokens' }\n case 'toolUse':\n return { kind: 'tool-calls' }\n case 'aborted':\n return { kind: 'aborted', failure: { message: message.errorMessage ?? 'pi-ai stream aborted', code: 'ABORTED' } }\n case 'error':\n return {\n kind: 'error',\n failure: { message: message.errorMessage ?? 'pi-ai stream error', code: classifyError(message.errorMessage ?? '') },\n }\n }\n}\n\nfunction mapUsage(usage: PiDoneMessage['usage']): Extract<HarnessChunk, { type: 'usage' }>['usage'] {\n return {\n inputTokens: usage.input,\n outputTokens: usage.output,\n ...(usage.cacheRead > 0 ? { cacheReadTokens: usage.cacheRead } : {}),\n ...(usage.cacheWrite > 0 ? { cacheWriteTokens: usage.cacheWrite } : {}),\n }\n}\n\n/**\n * Translate one pi-ai event stream into harness chunks. pi-ai never throws\n * mid-stream: failures arrive as `error` events and become error/aborted\n * finish chunks.\n */\nexport async function* toStreamChunks(events: AsyncIterable<PiEvent>, contextWindow: number): AsyncGenerator<HarnessChunk> {\n const toolIds = new Map<number, { id: string; name: string }>()\n for await (const event of events) {\n switch (event.type) {\n case 'start':\n break\n case 'text_start':\n yield { type: 'block-start', index: event.contentIndex, blockType: 'text' }\n break\n case 'text_delta':\n yield { type: 'text-delta', index: event.contentIndex, text: event.delta }\n break\n case 'text_end':\n yield { type: 'block-end', index: event.contentIndex, block: { type: 'text', text: event.content } }\n break\n case 'thinking_start':\n yield { type: 'block-start', index: event.contentIndex, blockType: 'reasoning' }\n break\n case 'thinking_delta':\n yield { type: 'reasoning-delta', index: event.contentIndex, text: event.delta }\n break\n case 'thinking_end':\n yield { type: 'block-end', index: event.contentIndex, block: { type: 'reasoning', text: event.content } }\n break\n case 'toolcall_start': {\n const partial = event.partial.content[event.contentIndex]\n const id = partial?.type === 'toolCall' ? (partial.id ?? '') : ''\n const name = partial?.type === 'toolCall' ? (partial.name ?? '') : ''\n toolIds.set(event.contentIndex, { id, name })\n yield { type: 'block-start', index: event.contentIndex, blockType: 'tool-call' }\n break\n }\n case 'toolcall_delta': {\n const known = toolIds.get(event.contentIndex)\n yield {\n type: 'tool-call-delta',\n index: event.contentIndex,\n id: known?.id ?? '',\n ...(known?.name !== undefined && known.name.length > 0 ? { name: known.name } : {}),\n argumentsDelta: event.delta,\n }\n break\n }\n case 'toolcall_end':\n yield {\n type: 'block-end',\n index: event.contentIndex,\n block: {\n type: 'tool-call',\n id: event.toolCall.id,\n name: event.toolCall.name,\n arguments: JSON.stringify(event.toolCall.arguments),\n },\n }\n break\n case 'done':\n yield { type: 'usage', usage: mapUsage(event.message.usage) }\n yield { type: 'finish', reason: mapStopReason(event.message, contextWindow) }\n return\n case 'error':\n yield { type: 'usage', usage: mapUsage(event.error.usage) }\n yield { type: 'finish', reason: mapStopReason(event.error, contextWindow) }\n return\n }\n }\n throw new Error('dsh-magpie-connect: pi-ai event stream ended without done/error')\n}\n", "/**\n * Harness GenerateOptions -> pi-ai Context conversion, with image support.\n *\n * Text-only requests convert synchronously (`toPiContext`); requests carrying\n * durable image blocks resolve bytes through the harness attachment service\n * (`toPiContextWithImages`, async). pi-ai then encodes images as OpenAI\n * `image_url` (completions) or `input_image` (responses) parts.\n */\n\nimport { modelApiForEntry } from './catalog.ts'\n\nexport interface ImageAttachmentRef {\n attachmentId: string\n mediaType: string\n bytes: number\n width: number\n height: number\n name?: string\n}\n\nexport interface FileAttachmentRef {\n attachmentId: string\n name: string\n bytes: number\n}\n\nexport interface HarnessTool {\n name: string\n description: string\n parameters: unknown\n}\n\nexport type HarnessBlock =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'tool-call'; id: string; name: string; arguments: string }\n | { type: 'image'; attachment: ImageAttachmentRef; offloaded?: true; [key: string]: unknown }\n | { type: 'file'; attachment: FileAttachmentRef; [key: string]: unknown }\n | { type: 'tool-result'; toolCallId: string; content: HarnessBlock[]; isError?: boolean; [key: string]: unknown }\n | { type: string; [key: string]: unknown }\n\nexport interface HarnessMessage {\n role: 'system' | 'user' | 'assistant' | 'tool' | 'developer'\n content: HarnessBlock[]\n source?: { kind: string; provider?: string; model?: string; callId?: string; [key: string]: unknown }\n toolCallId?: string\n isError?: boolean\n [key: string]: unknown\n}\n\nexport interface HarnessGenerateOptions {\n provider: string\n model: string\n messages: HarnessMessage[]\n system?: string\n tools?: HarnessTool[]\n maxTokens?: number\n temperature?: number\n reasoningEffort?: string\n signal?: AbortSignal\n /** Declared auxiliary request purpose (e.g. `compaction`); absent for ordinary turns. */\n purpose?: string\n [key: string]: unknown\n}\n\n/** pi-ai message vocabulary (subset we emit). */\nexport type PiMessage =\n | { role: 'user'; content: string | PiContentBlock[]; timestamp: number }\n | {\n role: 'assistant'\n content: PiAssistantBlock[]\n api: 'openai-completions' | 'openai-responses'\n provider: string\n model: string\n usage: PiUsage\n stopReason: 'stop' | 'toolUse'\n timestamp: number\n }\n | { role: 'toolResult'; toolCallId: string; toolName: string; content: PiContentBlock[]; isError: boolean; timestamp: number }\n\nexport type PiAssistantBlock =\n | { type: 'text'; text: string }\n | { type: 'thinking'; thinking: string }\n | { type: 'toolCall'; id: string; name: string; arguments: Record<string, unknown> }\n\nexport type PiContentBlock = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }\n\nexport interface PiUsage {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n totalTokens: number\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number }\n}\n\nexport interface PiTool {\n name: string\n description: string\n parameters: unknown\n}\n\nexport interface PiContext {\n systemPrompt?: string\n messages: PiMessage[]\n tools?: PiTool[]\n}\n\n/** Attachment service surface we consume (structural subset of dsh-attachment). */\nexport interface AttachmentStore {\n readImageRequest(\n ref: ImageAttachmentRef,\n target: { width: number; height: number; maxBytes: number },\n signal?: AbortSignal,\n ): Promise<{ data: Uint8Array; mediaType: string; bytes: number; width: number; height: number }>\n}\n\nexport interface RequestImageVersion {\n data: Uint8Array\n mediaType: string\n bytes: number\n width: number\n height: number\n}\n\nconst REQUEST_MAX_PIXELS = 2048 * 2048\nconst REQUEST_MAX_BYTES = 1024 * 1024\n\nexport function zeroUsage(): PiUsage {\n return {\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}\n\nfunction parseArguments(raw: string): Record<string, unknown> {\n if (typeof raw !== 'string' || raw.length === 0) return {}\n try {\n const parsed = JSON.parse(raw) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : { value: parsed }\n } catch {\n return { raw }\n }\n}\n\n/** True when any message carries a retained (non-offloaded) image block. */\nexport function contentHasImage(messages: readonly HarnessMessage[]): boolean {\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type === 'image' && (block as { offloaded?: unknown }).offloaded !== true) return true\n }\n }\n return false\n}\n\n/** Request target for one attachment: fit within the pixel budget, cap bytes. */\nexport function requestImageTarget(ref: ImageAttachmentRef): { width: number; height: number; maxBytes: number } {\n const pixels = ref.width * ref.height\n if (!(pixels > REQUEST_MAX_PIXELS) || !(ref.width > 0 && ref.height > 0)) {\n return { width: ref.width, height: ref.height, maxBytes: REQUEST_MAX_BYTES }\n }\n const scale = Math.sqrt(REQUEST_MAX_PIXELS / pixels)\n return { width: Math.max(1, Math.floor(ref.width * scale)), height: Math.max(1, Math.floor(ref.height * scale)), maxBytes: REQUEST_MAX_BYTES }\n}\n\nfunction imageHandleText(ref: ImageAttachmentRef, version: RequestImageVersion): string {\n const name = ref.name ?? `attachment ${String(ref.attachmentId).slice(0, 12)}`\n return `Image ${name}; request preview ${version.width}x${version.height}px.`\n}\n\nfunction offloadedImageText(ref: ImageAttachmentRef): string {\n const name = ref.name ?? `attachment ${String(ref.attachmentId).slice(0, 12)}`\n return `[image omitted (offloaded); ${name}]`\n}\n\nfunction toBase64(data: Uint8Array): string {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('base64')\n}\n\n/**\n * Resolve every retained image to request bytes. Offloaded occurrences need\n * no bytes (placeholder text only) and are skipped here.\n */\nexport async function prepareRequestImages(\n messages: readonly HarnessMessage[],\n attachments: AttachmentStore,\n signal?: AbortSignal,\n): Promise<Map<string, RequestImageVersion>> {\n const refs = new Map<string, ImageAttachmentRef>()\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type !== 'image') continue\n const image = block as Extract<HarnessBlock, { type: 'image' }>\n if (image.offloaded === true) continue\n if (!refs.has(image.attachment.attachmentId)) refs.set(image.attachment.attachmentId, image.attachment)\n }\n }\n const versions = new Map<string, RequestImageVersion>()\n await Promise.all(\n [...refs.values()].map(async (ref) => {\n const prepared = await attachments.readImageRequest(ref, requestImageTarget(ref), signal)\n versions.set(ref.attachmentId, {\n data: prepared.data,\n mediaType: prepared.mediaType,\n bytes: prepared.bytes,\n width: prepared.width,\n height: prepared.height,\n })\n }),\n )\n return versions\n}\n\n/** User/tool-result content with images resolved to handle text + bytes. */\nexport function userContentWithImages(\n blocks: HarnessBlock[],\n requestImages: Map<string, RequestImageVersion>,\n): string | PiContentBlock[] {\n const content: PiContentBlock[] = []\n for (const block of blocks) {\n switch (block.type) {\n case 'text':\n if ((block as { text: string }).text.length > 0) content.push({ type: 'text', text: (block as { text: string }).text })\n break\n case 'image': {\n const image = block as Extract<HarnessBlock, { type: 'image' }>\n if (image.offloaded === true) {\n content.push({ type: 'text', text: offloadedImageText(image.attachment) })\n break\n }\n const version = requestImages.get(image.attachment.attachmentId)\n if (!version) {\n content.push({ type: 'text', text: offloadedImageText(image.attachment) })\n break\n }\n content.push({ type: 'text', text: imageHandleText(image.attachment, version) })\n content.push({ type: 'image', data: toBase64(version.data), mimeType: version.mediaType })\n break\n }\n case 'file': {\n const file = block as Extract<HarnessBlock, { type: 'file' }>\n content.push({ type: 'text', text: `[file: ${file.attachment.name} (${file.attachment.bytes} bytes)]` })\n break\n }\n case 'tool-result':\n content.push({ type: 'text', text: toolResultText((block as { content: HarnessBlock[] }).content) || '(no output)' })\n break\n default:\n break\n }\n }\n if (content.every((block) => block.type === 'text')) return content.map((block) => (block as { text: string }).text).join('')\n return content\n}\n\nfunction toPiAssistant(\n message: HarnessMessage,\n providerId: string,\n api: 'openai-completions' | 'openai-responses' = 'openai-completions',\n): Extract<PiMessage, { role: 'assistant' }> {\n const content: PiAssistantBlock[] = []\n for (const block of message.content) {\n switch (block.type) {\n case 'text':\n content.push({ type: 'text', text: (block as { text: string }).text })\n break\n case 'reasoning':\n content.push({ type: 'thinking', thinking: (block as { text: string }).text })\n break\n case 'tool-call': {\n const call = block as { id: string; name: string; arguments: string }\n content.push({ type: 'toolCall', id: call.id, name: call.name, arguments: parseArguments(call.arguments) })\n break\n }\n case 'image':\n throw new Error('dsh-magpie-connect: assistant image output cannot be replayed to the model')\n default:\n break\n }\n }\n const source = message.source\n return {\n role: 'assistant',\n content,\n api,\n provider: source?.kind === 'model' && typeof source.provider === 'string' ? source.provider : providerId,\n model: source?.kind === 'model' && typeof source.model === 'string' ? source.model : providerId,\n usage: zeroUsage(),\n stopReason: content.some((block) => block.type === 'toolCall') ? 'toolUse' : 'stop',\n timestamp: 0,\n }\n}\n\nfunction flattenText(message: HarnessMessage): string {\n return message.content\n .filter((block) => block.type === 'text')\n .map((block) => (block as { text: string }).text)\n .join('')\n}\n\nfunction toolResultText(blocks: HarnessBlock[]): string {\n return blocks\n .map((block) => (block.type === 'text' ? (block as { text: string }).text : block.type === 'tool-result' ? toolResultText((block as { content: HarnessBlock[] }).content) : ''))\n .join('')\n}\n\nfunction toolsOf(options: HarnessGenerateOptions): PiTool[] | undefined {\n const tools = options.tools?.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters }))\n return tools && tools.length > 0 ? tools : undefined\n}\n\nfunction assistantApiFor(options: HarnessGenerateOptions, entryEndpoints: readonly string[]): 'openai-completions' | 'openai-responses' {\n void options\n return modelApiForEntry(entryEndpoints)\n}\n\n/**\n * Text-only conversion (no image bytes needed). Images without resolved\n * bytes cannot be sent \u2014 callers must route image-bearing requests through\n * `toPiContextWithImages` instead.\n */\nexport function toPiContext(options: HarnessGenerateOptions, entryEndpoints: readonly string[] = []): PiContext {\n const providerId = options.provider\n const assistantApi = assistantApiFor(options, entryEndpoints)\n const toolNames = new Map<string, string>()\n const messages: PiMessage[] = []\n for (const message of options.messages) {\n if (message.role === 'system') {\n const text = flattenText(message)\n if (text.length > 0) messages.push({ role: 'user', content: text, timestamp: 0 })\n continue\n }\n if (message.role === 'assistant') {\n const assistant = toPiAssistant(message, providerId, assistantApi)\n for (const block of assistant.content) {\n if (block.type === 'toolCall') toolNames.set(block.id, block.name)\n }\n messages.push(assistant)\n continue\n }\n if (message.role === 'developer') continue\n if (message.role === 'tool') {\n const text = flattenText(message)\n messages.push({\n role: 'toolResult',\n toolCallId: message.toolCallId ?? '',\n toolName: message.toolCallId ? (toolNames.get(message.toolCallId) ?? 'unknown') : 'unknown',\n content: [{ type: 'text', text: text || '(no output)' }],\n isError: message.isError ?? false,\n timestamp: 0,\n })\n continue\n }\n for (const block of message.content) {\n if (block.type === 'image') {\n throw new Error('dsh-magpie-connect: image input requires the attachment service (use toPiContextWithImages)')\n }\n if (block.type === 'file') {\n // Files are projected to handle text by the harness; keep a stable\n // placeholder when one arrives unprojected.\n continue\n }\n }\n const text = flattenText(message)\n const fileText = message.content\n .filter((block) => block.type === 'file')\n .map((block) => `[file: ${(block as Extract<HarnessBlock, { type: 'file' }>).attachment.name}]`)\n .join('\\n')\n const combined = [text, fileText].filter((part) => part.length > 0).join('\\n')\n const results = message.content.filter((block) => block.type === 'tool-result') as Array<\n Extract<HarnessBlock, { type: 'tool-result' }>\n >\n if (combined.length > 0 || results.length === 0) {\n messages.push({ role: 'user', content: combined, timestamp: 0 })\n }\n for (const result of results) {\n messages.push({\n role: 'toolResult',\n toolCallId: result.toolCallId,\n toolName: toolNames.get(result.toolCallId) ?? 'unknown',\n content: [{ type: 'text', text: toolResultText(result.content) || '(no output)' }],\n isError: result.isError ?? false,\n timestamp: 0,\n })\n }\n }\n const context: PiContext = { messages }\n if (typeof options.system === 'string' && options.system.length > 0) context.systemPrompt = options.system\n const tools = toolsOf(options)\n if (tools) context.tools = tools\n return context\n}\n\n/**\n * Image-aware conversion: retained images resolve to request bytes via the\n * attachment service; offloaded images become placeholder text.\n */\nexport async function toPiContextWithImages(\n options: HarnessGenerateOptions,\n attachments: AttachmentStore,\n entryEndpoints: readonly string[] = [],\n): Promise<PiContext> {\n const providerId = options.provider\n const assistantApi = assistantApiFor(options, entryEndpoints)\n const requestImages = await prepareRequestImages(options.messages, attachments, options.signal)\n const toolNames = new Map<string, string>()\n const messages: PiMessage[] = []\n for (const message of options.messages) {\n if (message.role === 'system') {\n const text = flattenText(message)\n if (text.length > 0) messages.push({ role: 'user', content: text, timestamp: 0 })\n continue\n }\n if (message.role === 'assistant') {\n const assistant = toPiAssistant(message, providerId, assistantApi)\n for (const block of assistant.content) {\n if (block.type === 'toolCall') toolNames.set(block.id, block.name)\n }\n messages.push(assistant)\n continue\n }\n if (message.role === 'developer') continue\n if (message.role === 'tool') {\n messages.push({\n role: 'toolResult',\n toolCallId: message.toolCallId ?? '',\n toolName: message.toolCallId ? (toolNames.get(message.toolCallId) ?? 'unknown') : 'unknown',\n content: userContentToBlocks(message.content, requestImages),\n isError: message.isError ?? false,\n timestamp: 0,\n })\n continue\n }\n const content = userContentWithImages(message.content, requestImages)\n const results = message.content.filter((block) => block.type === 'tool-result') as Array<\n Extract<HarnessBlock, { type: 'tool-result' }>\n >\n // userContentWithImages already folds nested tool-results to text; emit\n // first-class toolResult messages for pi-ai tool continuity.\n if (typeof content === 'string' ? content.length > 0 || results.length === 0 : true) {\n messages.push({ role: 'user', content, timestamp: 0 })\n } else if (typeof content === 'string' && content.length === 0 && results.length === 0) {\n messages.push({ role: 'user', content, timestamp: 0 })\n }\n for (const result of results) {\n messages.push({\n role: 'toolResult',\n toolCallId: result.toolCallId,\n toolName: toolNames.get(result.toolCallId) ?? 'unknown',\n content: userContentToBlocks(result.content, requestImages),\n isError: result.isError ?? false,\n timestamp: 0,\n })\n }\n }\n const context: PiContext = { messages }\n if (typeof options.system === 'string' && options.system.length > 0) context.systemPrompt = options.system\n const tools = toolsOf(options)\n if (tools) context.tools = tools\n return context\n}\n\nfunction userContentToBlocks(blocks: HarnessBlock[], requestImages: Map<string, RequestImageVersion>): PiContentBlock[] {\n const converted = userContentWithImages(blocks, requestImages)\n if (typeof converted === 'string') return [{ type: 'text', text: converted || '(no output)' }]\n return converted.length > 0 ? converted : [{ type: 'text', text: '(no output)' }]\n}\n", "/**\n * Stall watchdog for upstream event streams.\n *\n * pi-ai surfaces transport failures as `error` events, but a silently\n * stalled SSE connection (headers sent, then no bytes ever again) produces\n * *no* event at all: the consumer's `for await` blocks until the SDK-level\n * overall timeout or the harness timeout. This wrapper races every `next()`\n * against a timer and, on expiry, aborts the upstream (best effort, via\n * `onTimeout`) and yields a synthetic `error` event so the normal chunk\n * translation turns the stall into a fast `TIMEOUT` finish instead of a\n * minutes-long hang.\n *\n * Two phases: time-to-first-event (queueing happens here) and idle-between-\n * events (a healthy stream emits frequently). Either phase accepts a\n * non-positive value to disable its timer (wait forever, the old behavior).\n */\n\nimport type { PiEvent } from './events.ts'\n\nexport interface StallTimeouts {\n /** Max wait for the first upstream event (connection + queueing). */\n firstEventTimeoutMs: number\n /** Max silence between two upstream events once streaming. */\n idleTimeoutMs: number\n}\n\nconst TIMED_OUT: unique symbol = Symbol('watchdog-timed-out')\n\nfunction raceTimeout<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer!: ReturnType<typeof setTimeout>\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), ms)\n const t = timer as unknown as { unref?: () => void }\n t.unref?.()\n })\n const cleanup = (): void => clearTimeout(timer)\n return Promise.race([promise.then((value) => {\n cleanup()\n return value\n }, (err: unknown) => {\n cleanup()\n throw err\n }), timeout])\n}\n\nfunction stallErrorEvent(model: string, waitMs: number, first: boolean): PiEvent {\n const phase = first ? 'waiting for the first upstream event' : 'waiting for the next upstream event'\n return {\n type: 'error',\n error: {\n api: 'openai-completions',\n provider: 'dsh-magpie-connect',\n model,\n content: [],\n usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 },\n stopReason: 'error',\n // Must read as a timeout (events.ts classifies on /timeout/i -> TIMEOUT).\n errorMessage: `upstream stream timeout: no upstream events for ${Math.round(waitMs / 1000)}s while ${phase} (model \"${model}\") \u2014 the stalled stream was aborted`,\n timestamp: Date.now(),\n },\n } as PiEvent\n}\n\nexport async function* withStallTimeout(\n events: AsyncIterable<PiEvent>,\n timeouts: StallTimeouts,\n options: { model?: string; onTimeout?: () => void } = {},\n): AsyncGenerator<PiEvent> {\n const iterator = events[Symbol.asyncIterator]()\n try {\n let first = true\n for (;;) {\n const waitMs = first ? timeouts.firstEventTimeoutMs : timeouts.idleTimeoutMs\n if (!(waitMs > 0 && Number.isFinite(waitMs))) {\n const next = await iterator.next()\n if (next.done) return\n first = false\n yield next.value\n continue\n }\n const next = await raceTimeout(iterator.next(), waitMs)\n if (next === TIMED_OUT) {\n try {\n options.onTimeout?.()\n } catch {\n // Teardown must never mask the stall itself.\n }\n yield stallErrorEvent(options.model ?? 'unknown', waitMs, first)\n return\n }\n if (next.done) return\n first = false\n yield next.value\n }\n } finally {\n // Best-effort detach without awaiting: the upstream may be the very thing\n // that is stuck, so waiting for its return() could hang teardown too.\n void Promise.resolve(iterator.return?.()).catch(() => {})\n }\n}\n", "/**\n * Plugin configuration (cordis config object, injected via cordis.patch.yml).\n *\n * The adapter registers a DSH LlmAdapter streaming directly from the Magpie\n * Magpie gateway (the configured API root): chat completions for most models plus the\n * Responses API for responses-only models. No child process, no proxy/pool.\n * The gateway needs no credential \u2014 `apiKey` defaults to a sentinel that\n * satisfies the pi-ai client without changing the wire.\n *\n * The settings sidebar page can override `baseUrl`/`apiKey` at runtime (saved\n * to `<dataDir>/settings.json`, applied without restart) and hides models\n * from the picker. Page values win per-field; patch config is the fallback.\n */\nimport { dshHomePath } from './homeDir.ts'\nexport interface DshMagpieConnectConfig {\n /**\n * Provider route id registered into DSH (the grouping key in the model\n * picker). Changing it after sessions already reference the old id will\n * orphan those model selections \u2014 prefer `displayName` for a cosmetic\n * rename.\n */\n providerId?: string\n /**\n * Display name shown in the model picker for this provider.\n * Defaults to the explicit `providerId` when one is given,\n * otherwise to `'Magpie'`.\n */\n displayName?: string\n /**\n * Versioned API root, e.g. `http://127.0.0.1:3425/v1`. The version is part of\n * the value, not something this plugin adds: a gateway that later serves\n * `/v2` or `/v3` is reached by changing this one string. Trailing slashes are\n * stripped; the path is kept.\n */\n baseUrl?: string\n /**\n * Gateway credential. Required: an empty key leaves the plugin unconfigured\n * even though `baseUrl` has a default, so the picker stays empty until it is\n * set (both are required by `isConfigured`).\n */\n apiKey?: string\n /**\n * Plugin state directory (status snapshot, settings file, catalog cache).\n * Defaults to `$DSH_HOME/storages/magpie-connect`\n * (`~/.dsh/storages/magpie-connect`).\n */\n dataDir?: string\n /** Model list refresh interval in seconds. */\n refreshSeconds?: number\n /**\n * Connection-setup retries for transient upstream failures (429/5xx with\n * backoff). Turn-level retries stay owned by DSH.\n */\n maxRetries?: number\n /** Overall upstream request cap in milliseconds. */\n timeoutMs?: number\n /**\n * Stall watchdog: max wait for the first upstream event in milliseconds\n * (queueing happens here). Non-positive disables that phase.\n */\n firstEventTimeoutMs?: number\n /**\n * Stall watchdog: max silence between upstream events in milliseconds.\n * Non-positive disables that phase.\n */\n idleTimeoutMs?: number\n}\n\nexport const defaults = {\n providerId: 'dsh-magpie-connect',\n displayName: 'Magpie',\n baseUrl: 'http://127.0.0.1:3425/v1',\n apiKey: '',\n refreshSeconds: 300,\n maxRetries: 2,\n timeoutMs: 300_000,\n firstEventTimeoutMs: 90_000,\n idleTimeoutMs: 60_000,\n} as const\n\nexport type ResolvedConfig = Required<\n Pick<DshMagpieConnectConfig, 'providerId' | 'refreshSeconds'>\n> &\n DshMagpieConnectConfig & { displayName: string; baseUrl: string; apiKey: string; dataDir: string }\n\nexport function resolveConfig(config: DshMagpieConnectConfig = {}): ResolvedConfig {\n const providerId = config.providerId ?? defaults.providerId\n return {\n ...defaults,\n ...config,\n providerId,\n displayName: config.displayName ?? (config.providerId ?? defaults.displayName),\n baseUrl: config.baseUrl ?? defaults.baseUrl,\n apiKey: config.apiKey ?? defaults.apiKey,\n dataDir: config.dataDir ?? dshHomePath('storages', 'magpie-connect'),\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { chmod, readFile, writeFile, mkdir, rename, rm } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\n/**\n * Page-owned runtime settings, persisted to a local JSON file.\n *\n * Precedence for the effective endpoint: settings page (this file, only the\n * fields the user actually saved) > cordis patch config > built-in defaults.\n *\n * `enabledModels` is an **allowlist**, matching DSH's own Models settings: the\n * picker offers the intersection of the gateway directory and this list. `null`\n * (absent) means \"inherit the whole directory\", `[]` means \"offer nothing\", and\n * a populated array means exactly those ids. The old blacklist\n * (`hiddenModels`) could not express \"the gateway added a model I don't want\n * yet\"; an allowlist can, and it is why a model the gateway re-lists never\n * comes back on its own.\n */\n\nexport interface MagpiePageSettings {\n baseUrl?: string\n apiKey?: string\n /** Magpie Web Key; never returned to the browser, only its presence is. */\n webKey?: string\n /**\n * Allowlist of model ids the picker offers. `undefined` = inherit every model\n * the gateway serves; `[]` = offer none; otherwise exactly these ids.\n */\n enabledModels?: string[] | undefined\n /**\n * Whether the composer's routing-trace icon shows in the input box's right\n * tool row. Absent reads as shown (the pre-toggle behavior); `false` hides\n * it. The settings page's switch writes `true`/`false` explicitly.\n */\n showComposerIcon?: boolean\n /**\n * Set once the `hiddenModels` (blacklist) document has been converted to\n * `enabledModels`. Its presence stops the migration from running twice \u2014 a\n * second run would read an already-allowlisted document as if it were a\n * blacklist and invert it into nonsense.\n */\n migratedFromHiddenModels?: true\n}\n\nexport interface EffectiveEndpoint {\n baseUrl: string\n apiKey: string\n}\n\n/**\n * What the settings page is allowed to see. The credential never travels to\n * the browser: the page only learns whether one is stored, so a page that\n * loads (or reloads) cannot leak it through the DOM, devtools, or an XSS in\n * the host UI.\n */\nexport interface MagpieSettingsView {\n baseUrl: string\n hasApiKey: boolean\n hasWebKey: boolean\n enabledModels?: string[]\n inheritedModels: boolean\n /** Whether the composer's routing icon shows (absent reads as true). */\n showComposerIcon: boolean\n}\n\nexport const SETTINGS_FILE = 'settings.json'\n\nexport function defaultSettingsPath(dataDir: string): string {\n return join(dataDir, SETTINGS_FILE)\n}\n\n/**\n * Normalize an API base URL: must be http(s), no trailing slash, path kept.\n *\n * The path is load-bearing, not a mistake to be trimmed: the gateway versions\n * its API (`/v1`, and later `/v2`, `/v3`), so this value *is* the prefix every\n * request is built on. The plugin appends only the resource (`/models`,\n * `/chat/completions`), never a version of its own \u2014 an origin-only value\n * would make a future `/v2` unreachable.\n */\nexport function normalizeBaseUrl(raw: unknown): string {\n if (typeof raw !== 'string' || raw.trim() === '') throw new Error('dsh-magpie-connect: baseUrl must be a non-empty http(s) URL')\n const trimmed = raw.trim()\n let url: URL\n try {\n url = new URL(trimmed)\n } catch {\n throw new Error(`dsh-magpie-connect: baseUrl is not a valid URL: ${trimmed}`)\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error(`dsh-magpie-connect: baseUrl must use http(s): ${trimmed}`)\n }\n // Query and fragment are never part of a base URL and would corrupt every\n // appended path; drop them rather than storing a value the wire ignores.\n return `${url.origin}${url.pathname.replace(/\\/+$/, '')}`\n}\n\n/** Normalize an enabled-model allowlist: strings only, deduped, order kept. */\nexport function normalizeEnabledModels(raw: unknown): string[] {\n if (raw === undefined) return []\n if (!Array.isArray(raw)) throw new Error('dsh-magpie-connect: enabledModels must be an array of model ids')\n const out: string[] = []\n for (const entry of raw) {\n if (typeof entry !== 'string') throw new Error('dsh-magpie-connect: enabledModels must be an array of model ids')\n const id = entry.trim()\n if (id !== '' && !out.includes(id)) out.push(id)\n }\n return out\n}\n\n/** Validate + normalize a page payload (full or partial). Unknown keys are dropped. */\nexport function normalizePageSettings(raw: unknown): MagpiePageSettings {\n if (!raw || typeof raw !== 'object') throw new Error('dsh-magpie-connect: settings payload must be an object')\n const record = raw as Record<string, unknown>\n const out: MagpiePageSettings = {}\n if (record.baseUrl !== undefined) out.baseUrl = normalizeBaseUrl(record.baseUrl)\n if (record.apiKey !== undefined) {\n if (typeof record.apiKey !== 'string' || record.apiKey.trim() === '') {\n throw new Error('dsh-magpie-connect: apiKey is required and must not be empty')\n }\n // Surrounding whitespace is always a paste artifact in Bearer keys.\n out.apiKey = record.apiKey.trim()\n }\n if (record.webKey !== undefined) {\n if (typeof record.webKey !== 'string' || record.webKey.trim() === '') {\n throw new Error('dsh-magpie-connect: webKey must be a non-empty string when supplied')\n }\n out.webKey = record.webKey.trim()\n }\n if (record.enabledModels !== undefined) out.enabledModels = normalizeEnabledModels(record.enabledModels)\n if (record.showComposerIcon !== undefined) {\n if (typeof record.showComposerIcon !== 'boolean') {\n throw new Error('dsh-magpie-connect: showComposerIcon must be a boolean')\n }\n out.showComposerIcon = record.showComposerIcon\n }\n if (record.migratedFromHiddenModels === true) out.migratedFromHiddenModels = true\n return out\n}\n\n/** Deep copy so a caller cannot mutate the store through a returned object. */\nfunction cloneSettings(source: MagpiePageSettings): MagpiePageSettings {\n return {\n ...source,\n ...(source.enabledModels === undefined ? {} : { enabledModels: [...source.enabledModels] }),\n }\n}\n\n/**\n * One-time conversion from the old blacklist document to the allowlist.\n *\n * The legacy file stored `hiddenModels` (ids to *exclude*). The new shape stores\n * `enabledModels` (ids to *include*), so the two are not interchangeable: an\n * unconverted file would be read as \"offer exactly the models I had hidden\",\n * which is the precise inverse of what the user asked for.\n *\n * `known` is the ids the picker would have offered under the old rules \u2014 the\n * gateway directory (live, else cached, else the built-in snapshot) minus the\n * hidden set. The conversion can only be computed from it, so the caller passes\n * whatever directory it has; when nothing is known yet (unconfigured, cold\n * cache), `enabledModels` is left absent, which means \"inherit everything\" \u2014\n * the only reading that cannot silently drop models the user can still use.\n *\n * The marker `migratedFromHiddenModels` is written even when the list could not\n * be computed: the blacklist is gone either way, and re-running the conversion\n * later would invert an already-converted document.\n * @param raw - the parsed settings document.\n * @param known - ids the old rules would have offered, or `undefined` when unknown.\n * @returns the converted document and whether anything changed.\n */\nexport function migrateLegacySettings(\n raw: unknown,\n known?: readonly string[],\n): { settings: MagpiePageSettings; migrated: boolean } {\n if (!raw || typeof raw !== 'object') return { settings: {}, migrated: false }\n const record = raw as Record<string, unknown>\n const legacy = record.hiddenModels\n if (record.migratedFromHiddenModels === true || !Array.isArray(legacy)) {\n return { settings: normalizePageSettings(raw), migrated: false }\n }\n const hidden = new Set(legacy.filter((entry): entry is string => typeof entry === 'string').map((entry) => entry.trim()).filter((entry) => entry !== ''))\n const base: Record<string, unknown> = { ...record, migratedFromHiddenModels: true }\n delete base.hiddenModels\n if (known !== undefined) base.enabledModels = known.filter((id) => !hidden.has(id))\n const settings = normalizePageSettings(base)\n return { settings, migrated: true }\n}\n\n/**\n * Merge patch config with page settings: page wins per-field, but only for\n * fields it actually saved (absent page fields fall back to patch/defaults).\n */\nexport function resolveEffectiveEndpoint(\n patch: { baseUrl: string; apiKey: string },\n page: MagpiePageSettings,\n): EffectiveEndpoint {\n return {\n baseUrl: page.baseUrl ?? patch.baseUrl,\n apiKey: page.apiKey ?? patch.apiKey,\n }\n}\n\n/** Fully configured only when both URL and key are present. Either missing gates everything. */\nexport function isConfigured(endpoint: EffectiveEndpoint): boolean {\n return endpoint.baseUrl !== '' && endpoint.apiKey !== ''\n}\n\n/** In-memory settings with file persistence. Synchronous reads for the hot path. */\nexport class SettingsStore {\n #path?: string\n /**\n * Pre-0.5 settings file (`~/.dsh-magpie-connect/settings.json`), or\n * `undefined` when no read-through-and-migrate is wanted (an explicit\n * `dataDir` means the user owns the path \u2014 never fall back, never delete).\n *\n * Read-only until the first successful write: settings are only moved to the\n * new location when the user saves something, so an upgrade that changes no\n * setting touches no file at all.\n */\n #legacyPath?: string\n /** True while the live state came from {@link #legacyPath}, not {@link #path}. */\n #legacySource = false\n /**\n * Set when the settings file exists but could not be read/parsed at startup.\n * Blocks a partial save (e.g. the model-list autosave that posts only\n * `enabledModels`) from writing the empty in-memory state over a file whose\n * credentials we simply failed to load \u2014 that is how a key silently vanished.\n */\n #loadFailed = false\n #settings: MagpiePageSettings = {}\n /** Serializes writes: one persist in flight, so two generations cannot interleave. */\n #writeChain: Promise<void> = Promise.resolve()\n #listeners = new Set<() => void>()\n /**\n * Whether the state directory is the plugin's own (`$DSH_HOME/storages/\u2026`),\n * in which case its permissions are tightened to `0700`. An explicit\n * `dataDir` belongs to the user, so it is never chmod-ed behind their back.\n * The settings file itself is repaired to `0600` either way: it holds a\n * credential.\n */\n #privateDir: boolean\n\n constructor(options: { path?: string; legacyPath?: string; privateDir?: boolean } = {}) {\n this.#path = options.path\n this.#legacyPath = options.legacyPath\n this.#privateDir = options.privateDir ?? false\n }\n\n /**\n * Tighten permissions on a file this store owns, best-effort.\n *\n * Never throws: the file may live on a read-only mount, a non-POSIX\n * filesystem, or a platform where `chmod` is a no-op. A permission repair\n * must never make otherwise-readable settings unreadable.\n */\n async #chmodQuietly(path: string, mode: number): Promise<void> {\n await chmod(path, mode).catch(() => {})\n }\n\n /**\n * Read one settings file, distinguishing \"absent\" from \"unreadable\".\n *\n * Returns the raw parsed document (`raw`) untouched so the legacy\n * `hiddenModels` conversion can still see that field; validation happens in\n * {@link read}. `exists: true` with `raw: undefined` means the file is there\n * but could not be read or parsed \u2014 callers must not mistake that for \"no\n * configuration\", or a later save would persist the blank state over a\n * perfectly good file.\n * @param path - file to read; `undefined` yields `{ exists: false }`.\n */\n async #readFile(path?: string): Promise<{ exists: boolean; raw?: unknown; error?: unknown }> {\n if (!path) return { exists: false }\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { exists: false }\n return { exists: true, error }\n }\n // Repair a pre-existing credential file (old versions wrote it with the\n // process umask). Best-effort: never turn a readable file into an error.\n await this.#chmodQuietly(path, 0o600)\n if (this.#privateDir) await this.#chmodQuietly(dirname(path), 0o700)\n try {\n return { exists: true, raw: JSON.parse(text) as unknown }\n } catch (error) {\n return { exists: true, error }\n }\n }\n\n /**\n * Locate the document to use: new location first, then the pre-0.5 file.\n *\n * A file that exists but is unreadable is returned as-is (`exists: true`,\n * `raw: undefined`) so callers can flag it instead of mistaking it for\n * \"no configuration\". A present-but-corrupt NEW file is authoritative and\n * does not fall back to the legacy one \u2014 that could resurrect stale\n * credentials over a deliberately replaced file.\n */\n async #resolveRaw(): Promise<{ exists: boolean; raw?: unknown; error?: unknown }> {\n const fromNew = await this.#readFile(this.#path)\n if (fromNew.raw !== undefined) return fromNew\n if (fromNew.exists) return fromNew\n const fromOld = await this.#readFile(this.#legacyPath)\n if (fromOld.raw !== undefined) {\n this.#legacySource = true\n return fromOld\n }\n return fromOld\n }\n\n /**\n * Read and normalize the persisted document without touching memory or disk.\n *\n * New location first; when it is absent, fall back **read-only** to the\n * pre-0.5 file so an upgrade shows the user's saved endpoint immediately.\n *\n * A file that is *present but unreadable* is NOT treated as \"no\n * configuration\": it sets {@link #loadFailed} (blocking a later partial save\n * from overwriting it with the blank state) and still returns `{}` so callers\n * have something to render.\n */\n async read(): Promise<MagpiePageSettings> {\n const resolved = await this.#resolveRaw()\n if (resolved.raw !== undefined) {\n try {\n return normalizePageSettings(resolved.raw)\n } catch {\n this.#loadFailed = true\n return {}\n }\n }\n if (resolved.exists) this.#loadFailed = true\n return {}\n }\n\n /**\n * Load persisted settings, running the one-time `hiddenModels` ->\n * `enabledModels` conversion.\n *\n * The rewrite is attempted at startup rather than lazily so the file on disk\n * matches what the running process believes; a failed write is not fatal\n * (the in-memory result is still correct), and the migration marker makes a\n * retry idempotent.\n * @param known - ids the old blacklist rules would have offered, used to\n * compute the allowlist; omitted when the directory is not known yet.\n */\n async load(known?: readonly string[]): Promise<MagpiePageSettings> {\n if (!this.#path) return this.get()\n // Use the RAW document, not the normalized one: the legacy `hiddenModels`\n // conversion needs the field `normalizePageSettings` would drop.\n const resolved = await this.#resolveRaw()\n if (resolved.raw === undefined) {\n if (resolved.exists) this.#loadFailed = true\n this.#settings = {}\n return this.get()\n }\n const { settings, migrated } = migrateLegacySettings(resolved.raw, known)\n this.#settings = settings\n if (migrated) await this.persist().catch(() => {})\n return this.get()\n }\n\n /**\n * Adopt a document already read and normalized by {@link read}, then run the\n * legacy conversion against the directory that is now warm.\n *\n * This is the startup path: `read` -> `applyPageSettings` (so the catalog\n * knows the user's endpoint) -> `catalog.start` (so the directory is real) ->\n * `hydrate` (so a legacy file converts against the live gateway).\n * @param raw - the normalized document from {@link read}.\n * @param known - ids the old blacklist rules would have offered.\n */\n async hydrate(raw: MagpiePageSettings, known?: readonly string[]): Promise<MagpiePageSettings> {\n const { settings, migrated } = migrateLegacySettings(raw, known)\n this.#settings = settings\n if (migrated) await this.persist().catch(() => {})\n this.#emit()\n return this.get()\n }\n\n get(): MagpiePageSettings {\n return cloneSettings(this.#settings)\n }\n\n /** Merge a partial payload, persist, and notify listeners. */\n async save(partial: unknown): Promise<MagpiePageSettings> {\n const normalized = normalizePageSettings(partial)\n // Guard: after a failed startup read, refuse a partial save (the model-list\n // autosave posts only `enabledModels`) \u2014 persisting the blank in-memory\n // state would erase credentials we merely failed to load.\n if (this.#loadFailed && normalized.baseUrl === undefined && normalized.apiKey === undefined) {\n throw new Error(\n 'dsh-magpie-connect: settings file was unreadable; refusing to overwrite it with a partial save \u2014 reload the settings page or restore settings.json',\n )\n }\n this.#settings = { ...this.#settings, ...normalized }\n await this.persist()\n // A complete save (both credentials present) proves the state is trustworthy again.\n if (normalized.baseUrl !== undefined && normalized.apiKey !== undefined) this.#loadFailed = false\n this.#emit()\n return this.get()\n }\n\n /** Replace the whole document (used at startup after load). */\n replace(next: MagpiePageSettings): void {\n this.#settings = cloneSettings(next)\n this.#emit()\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener)\n return () => {\n this.#listeners.delete(listener)\n }\n }\n\n async persist(): Promise<void> {\n if (!this.#path) return\n // Serialize: one write in flight, so overlapping generations cannot\n // interleave a read-modify-write or clobber each other's temp file.\n this.#writeChain = this.#writeChain.then(\n () => this.#writeNow(),\n () => this.#writeNow(),\n )\n await this.#writeChain\n }\n\n /**\n * Write the current state to {@link #path} atomically, then clean up the\n * pre-0.5 file if this generation had read from it.\n *\n * The temp file is a random-suffixed sibling opened with `wx` and renamed\n * over the target \u2014 no `rm` beforehand (that opened a window where the file\n * did not exist and a concurrent read saw an empty document), and a random\n * suffix so two generations in one process cannot share a temp name.\n */\n async #writeNow(): Promise<void> {\n const target = this.#path\n if (!target) return\n const dir = dirname(target)\n await mkdir(dir, { recursive: true, ...(this.#privateDir ? { mode: 0o700 } : {}) })\n if (this.#privateDir) await this.#chmodQuietly(dir, 0o700)\n const tmp = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n await writeFile(tmp, JSON.stringify(this.#settings, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n await rename(tmp, target)\n } finally {\n await rm(tmp, { force: true }).catch(() => {})\n }\n // The new file is durable now; only then drop the legacy one. A failed\n // delete is harmless (the new file is authoritative) and is retried on the\n // next save because `#legacySource` stays true.\n if (this.#legacySource && this.#legacyPath) {\n await rm(this.#legacyPath, { force: true })\n .then(() => {\n this.#legacySource = false\n })\n .catch(() => {\n // keep #legacySource so a later save retries the cleanup\n })\n }\n }\n\n #emit(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener()\n } catch {\n // listeners must never break the save path\n }\n }\n }\n}\n", "/**\n * The routing-trace fetcher: reads the gateway's own view of its routing \u2014\n * the request ledger (`/v1/magpie/usage/requests`) and the accounts'\n * allowances (`/v1/magpie/quotas`) \u2014 and compresses both into the small\n * {@link TraceView} the composer popover shows.\n *\n * Both endpoints answer this machine and, while Magpie shares on the local\n * network, another machine too \u2014 but always with the gateway key, so the\n * fetch runs on the host, never in the browser (CORS would refuse the page,\n * and the key must not cross to it).\n *\n * `{gateway}` is the configured API base with its version segment removed:\n * `http://api.lan/v1` \u2192 `http://api.lan` \u2014 the popover contract's \"base_url\".\n */\n\nimport {\n isConfigured,\n normalizeBaseUrl,\n type EffectiveEndpoint,\n} from './settings.ts'\nimport type {\n ActiveRequestRow,\n SessionRouteTry,\n SessionRouteView,\n SessionTraceView,\n TraceAccountRow,\n TraceCandidate,\n TraceGroup,\n TraceRequestRow,\n TraceRest,\n TraceRoutingSection,\n TraceStatus,\n TraceSubGroup,\n TraceTotals,\n TraceView,\n} from './trace-contract.ts'\n\n/** Request rows one popover shows; the gateway returns newest first. */\nexport const TRACE_REQUEST_ROWS = 8\n\n/** Account rows one popover shows; the list scrolls past the cap. */\nexport const TRACE_ACCOUNT_ROWS = 14\n\n/** In-flight rows one popover shows; the own session's row is kept first. */\nexport const TRACE_ACTIVE_ROWS = 5\n\n/** How long one fetch may take before the popover shows \"unreachable\". */\nexport const TRACE_TIMEOUT_MS = 8_000\n\n/** The `period` the ledger is read for; today keeps the header counts current. */\nconst LEDGER_PERIOD = 'today'\n\n/** Path the signed-in Magpie Web console serves beside its HTML. */\nconst WEB_TRACE_PATH = '/api/gateway/trace'\n\n/** Allowed set so a raw value maps onto the wire status without widening it. */\nconst STATUS_KINDS: readonly TraceStatus[] = ['ok', 'unconfigured', 'unauthorized', 'forbidden', 'network', 'unknown']\n\n/**\n * The gateway base the trace endpoints hang off: the configured API base\n * with its trailing version segment (`/v1`, `/v1/`, `/v2`) removed. The\n * version is part of the API root, not of the gateway address, and the\n * `/v1/magpie/*` namespace lives on the address alone.\n * @param baseUrl - the configured versioned API root (`http://host:port/v1`).\n * @returns the base for `/v1/magpie/*` (origin plus any non-version prefix path), or `undefined` for values that never were URLs.\n */\nexport function deriveGatewayBase(baseUrl: string): string | undefined {\n let url: URL\n try {\n url = new URL(baseUrl)\n } catch {\n return undefined\n }\n const trimmed = url.pathname.replace(/\\/+$/, '').replace(/\\/v\\d+$/i, '')\n return `${url.origin}${trimmed}`\n}\n\n/** One response of the two gateway endpoints, decoded loosely (fields optional). */\ntype LooseRecord = Record<string, unknown>\n\n/** Read one finite number field. */\nfunction num(record: LooseRecord, key: string): number | undefined {\n const value = record[key]\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\n/** Read one non-empty string field. */\nfunction str(record: LooseRecord, key: string): string | undefined {\n const value = record[key]\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/** Round a 0\u2013100 share into whole percents, clamped. */\nfunction pctOf(used: unknown): number | undefined {\n if (typeof used !== 'number' || !Number.isFinite(used)) return undefined\n return Math.min(100, Math.max(0, Math.round(used)))\n}\n\n/** Percent from an explicit amount/limit pair (windows the vendor counts by units). */\nfunction pctOfParts(record: LooseRecord): number | undefined {\n const amount = num(record, 'amount')\n const limit = num(record, 'limit')\n if (amount === undefined || limit === undefined || limit <= 0) return undefined\n return pctOf((amount / limit) * 100)\n}\n\n/**\n * Classify one fetch failure. The gateway's 403 wording names the share\n * setting (\"told to another machine only when magpie is shared\u2026\"), so the\n * popover's hint can say exactly what to turn on.\n */\nfunction statusForStatusCode(code: number): TraceStatus {\n if (code === 401) return 'unauthorized'\n if (code === 403) return 'forbidden'\n if (code >= 500) return 'network'\n return 'unknown'\n}\n\n/** Fetch one Magpie Web endpoint, carrying its port-scoped web cookie. */\nasync function fetchWebJson(base: string, webKey: string, path: string, signal: AbortSignal): Promise<LooseRecord> {\n const url = new URL(base)\n const port = url.port || (url.protocol === 'https:' ? '443' : '80')\n const response = await fetch(`${base}${path}`, {\n headers: { cookie: `magpie_web_${port}=${webKey}`, accept: 'application/json' },\n cache: 'no-store',\n signal,\n })\n if (!response.ok) {\n const error = new Error(`Magpie Web HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return (await response.json()) as LooseRecord\n}\n\n/**\n * Magpie's normal Web UI port is 3430. Some installs reverse-proxy the Web\n * routes onto the API root; try that first, then the default Web port on the\n * same host. This keeps the setting to one Web Key while supporting the\n * split API (:80/:3425) + Web (:3430) layout too.\n */\nfunction webBases(base: string): string[] {\n // In Magpie's split layout, the API endpoint (e.g. :80 or :3425) and Web\n // console (:3430) share a hostname. If the configured endpoint is already\n // on :3430, use it; otherwise try the supplied root first, then Web's port.\n const candidates: string[] = []\n try {\n const url = new URL(base)\n if (url.port === '3430') return [base]\n url.port = '3430'\n candidates.push(`${url.origin}${url.pathname.replace(/\\/+$/, '')}`)\n candidates.push(base)\n } catch {\n return [base]\n }\n return [...new Set(candidates)]\n}\n\n/** Read full trace from the same API host, trying its Web port if split. */\nasync function fetchFullWebTrace(base: string, webKey: string, signal: AbortSignal): Promise<{ trace: LooseRecord; base: string }> {\n let lastError: unknown\n for (const candidate of webBases(base)) {\n try {\n const trace = await fetchWebJson(candidate, webKey, `${WEB_TRACE_PATH}?after=0`, signal)\n // The Web Console's traceJSON has no `object` field (unlike the\n // gateway's loopback /v1/magpie/trace); routes[] is the reliable shape.\n if (!Array.isArray(trace.routes)) {\n throw new Error('Magpie Web returned an unexpected trace shape')\n }\n return { trace, base: candidate }\n } catch (error) {\n if (isAbort(error)) throw error\n lastError = error\n }\n }\n throw lastError instanceof Error ? lastError : new Error('Magpie Web trace is unavailable')\n}\n\n/** The Routing page URL from the configured API root; no Web Key in the link. */\nfunction routingUrlFor(base: string): string {\n return `${base.replace(/\\/+$/, '')}/?view=routing`\n}\n\n/** Fetch one binary asset from Magpie Web, carrying its port-scoped Web cookie. */\nasync function fetchWebBinary(base: string, webKey: string, path: string, signal: AbortSignal): Promise<{ body: ArrayBuffer; contentType: string }> {\n const url = new URL(base)\n const port = url.port || (url.protocol === 'https:' ? '443' : '80')\n const response = await fetch(`${base}${path}`, {\n headers: { cookie: `magpie_web_${port}=${webKey}`, accept: 'image/svg+xml,image/png,*/*' },\n cache: 'no-store',\n signal,\n })\n if (!response.ok) {\n const error = new Error(`Magpie Web HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return {\n body: await response.arrayBuffer(),\n contentType: response.headers.get('content-type') ?? 'image/svg+xml',\n }\n}\n\n/** Magpie's png icon names; all other built-in icons are SVG. */\nconst PNG_ICONS = new Set([\n 'crush', 'zcode', 'alma', 'hanako', 'cindy', 'lody', 'typesafe', 'atomcode',\n 'snow', 'mlx-serve', 'mothx', 'zoo-code', 'kimi-code-desktop',\n])\n\n/**\n * Read one provider icon from Magpie Web through the stored Web Key. The\n * browser asks the plugin's same-origin `/api/magpie-icon` route instead of\n * loading a cross-origin image that would miss the Web cookie.\n */\nexport async function fetchWebIcon(\n base: string,\n webKey: string,\n name: string,\n signal: AbortSignal,\n): Promise<{ body: ArrayBuffer; contentType: string }> {\n const safe = /^[A-Za-z0-9._~-]+$/.test(name) && !name.includes('..') ? name : 'generic'\n if (safe === 'generic') throw new Error('Magpie Web icon name is invalid')\n const ext = PNG_ICONS.has(safe) ? 'png' : 'svg'\n const path = `/icons/${safe}.${ext}`\n let lastError: unknown\n for (const candidate of webBases(base)) {\n try {\n return await fetchWebBinary(candidate, webKey, path, signal)\n } catch (error) {\n if (isAbort(error)) throw error\n lastError = error\n }\n }\n throw lastError instanceof Error ? lastError : new Error('Magpie Web icon is unavailable')\n}\n\n/** Fetch one gateway endpoint, mapping failures onto the shared status kind. */\nasync function fetchJson(base: string, apiKey: string, path: string, signal: AbortSignal): Promise<LooseRecord> {\n const response = await fetch(`${base}${path}`, {\n headers: { authorization: `Bearer ${apiKey}`, accept: 'application/json' },\n cache: 'no-store',\n signal,\n })\n if (!response.ok) {\n const error = new Error(`HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return (await response.json()) as LooseRecord\n}\n\n/**\n * Project one ledger row onto the wire shape. `req` is the routing group or\n * model the agent asked for (`auto/gpt-6-luna`), `served` the model that\n * answered; when they agree one name is enough, so the row stays one line.\n */\nfunction toRequestRow(row: LooseRecord): TraceRequestRow | undefined {\n const id = num(row, 'route_id')\n const time = str(row, 't')\n if (id === undefined || time === undefined) return undefined\n const requested = str(row, 'req')\n const served = str(row, 'served')\n const provider = str(row, 'providerName')\n const account = str(row, 'providerAccount')\n const ms = num(row, 'ms')\n const ttftMs = num(row, 'ttft_ms')\n const status = num(row, 'status')\n const cost = num(row, 'cost')\n return {\n id,\n time,\n agent: str(row, 'agentName') ?? str(row, 'agent') ?? '?',\n ...(requested !== undefined ? { requested } : {}),\n ...(served !== undefined && served !== requested ? { served } : {}),\n ...(provider !== undefined ? { provider } : {}),\n ...(account !== undefined ? { account } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(row.canceled === true ? { canceled: true } : {}),\n ...(cost !== undefined && cost !== 0 ? { cost } : {}),\n }\n}\n\n/**\n * Mask one account holder for the wire: keep the name's head, drop anything\n * mail- or phone-shaped. The gateway's own masking already runs when the\n * user turned it on; this is the popover's second line of defense, so a\n * full address never reaches the browser's DOM.\n */\nfunction maskHolder(user: string | undefined): string | undefined {\n if (user === undefined) return undefined\n const at = user.indexOf('@')\n if (at <= 0) return user\n const head = user.slice(0, Math.max(1, Math.min(at, 4)))\n return `${head}\u2026`\n}\n\n/**\n * The quota window the popover shows for one account: the first window with\n * a usable share (a `used` percent, or an amount/limit pair), falling back\n * to the first one that names its reset date.\n */\nfunction pickWindow(windows: LooseRecord[]): LooseRecord | undefined {\n return (\n windows.find((entry) => num(entry, 'used') !== undefined || pctOfParts(entry) !== undefined) ??\n windows.find((entry) => str(entry, 'resetsAt') !== undefined) ??\n windows[0]\n )\n}\n\n/** Project one quota account onto the wire shape. */\nfunction toAccountRow(account: LooseRecord): TraceAccountRow | undefined {\n const provider = str(account, 'name') ?? str(account, 'provider')\n if (provider === undefined) return undefined\n const user = maskHolder(str(account, 'user'))\n const base: TraceAccountRow = {\n provider,\n ...(str(account, 'provider') !== undefined ? { providerId: str(account, 'provider') } : {}),\n ...(str(account, 'plan') !== undefined ? { plan: str(account, 'plan') } : {}),\n ...(user !== undefined ? { user } : {}),\n ...(str(account, 'error') !== undefined ? { error: str(account, 'error') } : {}),\n }\n const windows = Array.isArray(account.windows) ? (account.windows as LooseRecord[]) : []\n const window = pickWindow(windows)\n if (window === undefined) return base\n const usedPct = pctOf(window.used) ?? pctOfParts(window)\n const windowName = str(window, 'name')\n const display = str(window, 'display')\n const resetsAt = str(window, 'resetsAt')\n const amount = num(window, 'amount')\n const limit = num(window, 'limit')\n const unit = str(window, 'unit')\n return {\n ...base,\n ...(windowName !== undefined ? { windowName } : {}),\n ...(usedPct !== undefined ? { usedPct } : {}),\n ...(display !== undefined ? { display } : {}),\n ...(amount !== undefined ? { amount } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(unit !== undefined ? { unit } : {}),\n ...(resetsAt !== undefined ? { resetsAt } : {}),\n }\n}\n\n/**\n * Project one in-flight request (`/v1/magpie/concurrency`'s `active`) onto\n * the wire shape, and mark the popover's own session's row so the client can\n * pin it to the top.\n */\nfunction toActiveRow(entry: LooseRecord, session: string | undefined): ActiveRequestRow | undefined {\n const ms = num(entry, 'ms')\n if (ms === undefined) return undefined\n const rowSession = str(entry, 'session')\n const agent = str(entry, 'agent')\n const model = str(entry, 'model')\n const provider = str(entry, 'provider')\n const phase = str(entry, 'phase')\n return {\n ...(agent !== undefined ? { agent } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(provider !== undefined ? { provider } : {}),\n ...(rowSession !== undefined ? { session: rowSession } : {}),\n ms,\n ...(phase !== undefined ? { phase } : {}),\n ...(session !== undefined && rowSession !== undefined && rowSession === session ? { own: true } : {}),\n }\n}\n\n/** The whole-gateway concurrency summary, for the header line. */\nfunction toConcurrency(data: LooseRecord): { requests: number; waiting: number; tools: number } {\n return {\n requests: num(data, 'requests') ?? 0,\n waiting: num(data, 'waiting') ?? 0,\n tools: num(data, 'tools') ?? 0,\n }\n}\n\n/** Project Magpie's Weighed or Try record onto a compact candidate. */\nfunction toTraceCandidate(\n entry: LooseRecord,\n outcome: TraceCandidate['outcome'],\n restOverride?: TraceRest,\n): TraceCandidate | undefined {\n const id = str(entry, 'id')\n const provider = str(entry, 'provider')\n if (id === undefined || provider === undefined) return undefined\n const used = num(entry, 'used')\n const renews = Array.isArray(entry.renews)\n ? (entry.renews as unknown[]).filter((value): value is string => typeof value === 'string')\n : []\n const via = Array.isArray(entry.via)\n ? (entry.via as unknown[]).filter((value): value is string => typeof value === 'string' && value !== '')\n : []\n const amount = num(entry, 'amount')\n const limit = num(entry, 'limit')\n const restRaw = restOverride ?? (entry.rest && typeof entry.rest === 'object' ? entry.rest as TraceRest : undefined)\n const status = num(entry, 'status')\n const ms = num(entry, 'ms')\n return {\n id,\n provider,\n ...(str(entry, 'kind') !== undefined ? { kind: str(entry, 'kind') } : {}),\n ...(str(entry, 'name') !== undefined ? { name: str(entry, 'name') } : {}),\n ...(str(entry, 'who') !== undefined ? { who: maskHolder(str(entry, 'who')) } : {}),\n ...(str(entry, 'icon') !== undefined ? { icon: str(entry, 'icon') } : {}),\n ...(str(entry, 'preset') !== undefined ? { preset: str(entry, 'preset') } : {}),\n ...(str(entry, 'plan') !== undefined ? { plan: str(entry, 'plan') } : {}),\n ...(str(entry, 'model') !== undefined ? { model: str(entry, 'model') } : {}),\n ...(str(entry, 'fixed') !== undefined ? { fixed: str(entry, 'fixed') } : {}),\n ...(via.length > 0 ? { via } : {}),\n ...(used !== undefined ? { usedPct: pctOf(used) } : {}),\n ...(amount !== undefined ? { amount } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(str(entry, 'unit') !== undefined ? { unit: str(entry, 'unit') } : {}),\n ...(renews.length > 0 ? { renews } : {}),\n ...(restRaw !== undefined ? { rest: restRaw } : {}),\n outcome,\n ...(status !== undefined ? { status } : {}),\n ...(str(entry, 'fail') !== undefined ? { fail: str(entry, 'fail') } : {}),\n ...(str(entry, 'error') !== undefined ? { error: str(entry, 'error') } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(str(entry, 'leftWhy') !== undefined ? { skipReason: str(entry, 'leftWhy') } : {}),\n ...(entry.fallback === true ? { fallback: true } : {}),\n ...(entry.free === true ? { free: true } : {}),\n ...(num(entry, 'capped') !== undefined ? { capped: num(entry, 'capped') } : {}),\n ...(entry.held === true ? { held: true } : {}),\n ...(str(entry, 'heldBy') !== undefined ? { heldBy: str(entry, 'heldBy') } : {}),\n ...(entry.unlisted === true ? { unlisted: true } : {}),\n ...(entry.barred === true ? { barred: true } : {}),\n ...(entry.noCredits === true ? { noCredits: true } : {}),\n ...(str(entry, 'unread') !== undefined ? { unread: str(entry, 'unread') } : {}),\n ...(str(entry, 'noURL') !== undefined ? { noURL: str(entry, 'noURL') } : {}),\n ...(num(entry, 'window') !== undefined ? { window: num(entry, 'window') } : {}),\n }\n}\n\n/**\n * Compress the session's full route row from `/api/gateway/trace` and enrich\n * its candidates with quota errors where possible. The route itself carries\n * `Rest`, provider/account identity, order/left and each try's failure.\n */\nfunction toSessionTrace(route: LooseRecord, accounts: readonly TraceAccountRow[]): SessionTraceView | undefined {\n const id = num(route, 'id')\n const model = str(route, 'model')\n if (id === undefined || model === undefined) return undefined\n const orderRaw = Array.isArray(route.order) ? route.order as LooseRecord[] : []\n const leftRaw = Array.isArray(route.left) ? route.left as LooseRecord[] : []\n const triesRaw = Array.isArray(route.tries) ? route.tries as LooseRecord[] : []\n const groupRaw = route.group !== null && typeof route.group === 'object' ? route.group as LooseRecord : undefined\n const groupMembers = groupRaw !== undefined && Array.isArray(groupRaw.members)\n ? (groupRaw.members as unknown[]).filter((x): x is string => typeof x === 'string')\n : []\n const groupVia = groupRaw !== undefined && Array.isArray(groupRaw.via)\n ? (groupRaw.via as unknown[]).map((x) => typeof x === 'string' ? x : '')\n : []\n const subsRaw = groupRaw !== undefined && Array.isArray(groupRaw.subs)\n ? groupRaw.subs as LooseRecord[]\n : []\n const subs: TraceSubGroup[] = subsRaw\n .filter((entry) => str(entry, 'id') !== undefined)\n .map((entry) => ({\n id: str(entry, 'id') ?? '',\n name: str(entry, 'name') ?? str(entry, 'id') ?? '',\n ...(str(entry, 'ref') !== undefined ? { ref: str(entry, 'ref') } : {}),\n ...(str(entry, 'routing') !== undefined ? { routing: str(entry, 'routing') } : {}),\n }))\n const group: TraceGroup | undefined = groupRaw !== undefined && str(groupRaw, 'id') !== undefined\n ? {\n id: str(groupRaw, 'id') ?? '',\n name: str(groupRaw, 'name') ?? str(groupRaw, 'id') ?? '',\n ...(str(groupRaw, 'ref') !== undefined ? { ref: str(groupRaw, 'ref') } : {}),\n ...(str(groupRaw, 'routing') !== undefined ? { routing: str(groupRaw, 'routing') } : {}),\n ...(groupMembers.length > 0 ? { members: groupMembers } : {}),\n ...(subs.length > 0 ? { subs } : {}),\n ...(groupVia.length > 0 ? { via: groupVia } : {}),\n }\n : undefined\n /**\n * The inner subgroup a candidate belongs to. Magpie puts the path on\n * `Weighed.via`, and also supplies `GroupRef.via` parallel to `members`.\n * A blank via is a direct member of the parent group \u2014 it must stay a\n * sibling of the nested routing groups, not inherit a previous subgroup.\n */\n const subgroupFor = (entry: LooseRecord): string => {\n const own = Array.isArray(entry.via)\n ? (entry.via as unknown[]).filter((x): x is string => typeof x === 'string' && x !== '')\n : []\n if (own.length > 0) return own[own.length - 1] ?? ''\n const provider = str(entry, 'provider') ?? ''\n const member = str(entry, 'model') ?? ''\n const fixed = str(entry, 'fixed')\n if (provider === '' || member === '') return ''\n const ref = `${provider}/${member}${fixed !== undefined ? `:${fixed}` : ''}`\n const idx = groupMembers.findIndex((x) => x === ref || x === `${provider}/${member}`)\n if (idx < 0) return ''\n const path = (groupVia[idx] ?? '').split('>').filter(Boolean)\n return path[path.length - 1] ?? ''\n }\n const seatKey = (entry: LooseRecord): string =>\n `${str(entry, 'id') ?? ''}\\u0000${str(entry, 'model') ?? ''}\\u0000${str(entry, 'fixed') ?? ''}`\n const triesBySeat = new Map<string, LooseRecord>()\n for (const tried of triesRaw) if (str(tried, 'id') !== undefined) triesBySeat.set(seatKey(tried), tried)\n const candidate = (entry: LooseRecord, kind: TraceCandidate['outcome']): TraceCandidate | undefined => {\n const tried = triesBySeat.get(seatKey(entry))\n const quota = accounts.find((account) =>\n account.providerId === str(entry, 'provider') &&\n ((account.user ?? '').toLowerCase() === maskHolder(str(entry, 'who'))?.toLowerCase() || account.user === undefined),\n )\n const quotaEnrichment: LooseRecord = {\n ...(quota?.usedPct !== undefined && num(entry, 'used') === undefined ? { used: quota.usedPct } : {}),\n ...(quota?.resetsAt !== undefined && !Array.isArray(entry.renews) ? { renews: [quota.resetsAt] } : {}),\n ...(quota?.amount !== undefined ? { amount: quota.amount } : {}),\n ...(quota?.limit !== undefined ? { limit: quota.limit } : {}),\n ...(quota?.unit !== undefined ? { unit: quota.unit } : {}),\n }\n const row = toTraceCandidate({ ...entry, ...quotaEnrichment }, kind, tried?.rest as TraceRest | undefined)\n if (row === undefined) return undefined\n const rest = tried?.rest ?? entry.rest\n const restValue = rest !== null && typeof rest === 'object' ? rest as LooseRecord : undefined\n const outcome: TraceCandidate['outcome'] = restValue !== undefined ? 'resting' : kind\n return {\n ...row,\n outcome,\n subgroup: subgroupFor(entry),\n ...(quota?.error !== undefined && row.error === undefined ? { error: quota.error } : {}),\n ...(restValue !== undefined ? { rest: {\n ...(str(restValue, 'why') !== undefined ? { why: str(restValue, 'why') } : {}),\n ...(num(restValue, 'status') !== undefined ? { status: num(restValue, 'status') } : {}),\n ...(str(restValue, 'until') !== undefined ? { until: str(restValue, 'until') } : {}),\n ...(str(restValue, 'by') !== undefined ? { by: str(restValue, 'by') } : {}),\n ...(num(restValue, 'failures') !== undefined ? { failures: num(restValue, 'failures') } : {}),\n ...(str(restValue, 'model') !== undefined ? { model: str(restValue, 'model') } : {}),\n ...(str(restValue, 'error') !== undefined ? { error: str(restValue, 'error') } : {}),\n ...(restValue.rate === true ? { rate: true } : {}),\n } } : {}),\n }\n }\n const orderSeats = new Set(orderRaw.map(seatKey))\n const orderCandidates = orderRaw.map((entry) => {\n const tried = triesBySeat.get(seatKey(entry))\n const done = tried?.done === true\n const status = num(tried ?? entry, 'status')\n const rest = tried?.rest ?? entry.rest\n const outcome: TraceCandidate['outcome'] = rest !== undefined && rest !== null ? 'resting'\n : tried === undefined ? 'available'\n : done ? (status !== undefined && status >= 200 && status < 400 ? 'answered' : 'failed')\n : 'processing'\n return candidate({ ...entry, ...(tried ?? {}), ...(status !== undefined ? { status } : {}) }, outcome)\n }).filter((value): value is TraceCandidate => value !== undefined)\n const tries = triesRaw.map((entry) => {\n const ordered = orderRaw.find((candidate) => seatKey(candidate) === seatKey(entry))\n const enriched = ordered !== undefined ? { ...ordered, ...entry } : entry\n const done = entry.done === true\n const status = num(entry, 'status')\n const rest = entry.rest ?? ordered?.rest\n const outcome: TraceCandidate['outcome'] = rest !== undefined && rest !== null ? 'resting'\n : done ? (status !== undefined && status >= 200 && status < 400 ? 'answered' : 'failed')\n : 'processing'\n return candidate(enriched, outcome)\n }).filter((value): value is TraceCandidate => value !== undefined)\n const left = leftRaw\n .filter((entry) => !orderSeats.has(seatKey(entry)))\n .map((entry) => {\n const skipReason = str(entry, 'leftWhy') ?? str(entry, 'heldBy')\n ?? (entry.held === true ? 'held' : entry.noCredits === true ? 'credits' : entry.unlisted === true ? 'unlisted' : entry.barred === true ? 'barred' : '')\n return candidate({ ...entry, ...(skipReason !== '' ? { leftWhy: skipReason } : {}) }, 'skipped')\n })\n .filter((value): value is TraceCandidate => value !== undefined)\n const allCandidates = [...orderCandidates, ...left]\n const bySubgroup = new Map<string, TraceCandidate[]>()\n const orderedKeys: string[] = []\n for (const row of allCandidates) {\n const key = row.subgroup ?? ''\n if (!bySubgroup.has(key)) orderedKeys.push(key)\n const list = bySubgroup.get(key) ?? []\n list.push(row)\n bySubgroup.set(key, list)\n }\n const sections: TraceRoutingSection[] = []\n for (const key of orderedKeys) {\n const rows = bySubgroup.get(key) ?? []\n if (rows.length === 0) continue\n if (key === '') {\n // Direct members of the parent routing group are siblings of nested\n // routing-group headings. Never fold them into the previous auto/* group.\n sections.push({\n name: group?.name ?? model,\n ref: group?.ref ?? model,\n ...(group?.routing !== undefined ? { routing: group.routing } : {}),\n depth: 0,\n hideHeader: subs.length > 0,\n candidates: rows.slice(0, 8),\n })\n continue\n }\n const sub = subs.find((entry) => entry.id === key)\n sections.push({\n name: sub?.name ?? key,\n ref: sub?.ref ?? `group/${key}`,\n ...(sub?.routing !== undefined ? { routing: sub.routing } : {}),\n depth: 1,\n candidates: rows.slice(0, 8),\n })\n }\n if (sections.length === 0) {\n sections.push({\n name: group?.name ?? model,\n ref: group?.ref ?? model,\n ...(group?.routing !== undefined ? { routing: group.routing } : {}),\n depth: 0,\n candidates: allCandidates.slice(0, 8),\n })\n }\n const ms = num(route, 'ms')\n const ttftMs = num(route, 'ttft')\n const status = num(route, 'status')\n return {\n id,\n ...(str(route, 'time') !== undefined ? { time: str(route, 'time') } : {}),\n model,\n ...(group !== undefined ? { group } : {}),\n ...(sections.length > 0 ? { sections } : {}),\n order: orderCandidates,\n left,\n tries,\n done: route.done === true,\n ...(status !== undefined ? { status } : {}),\n ...(str(route, 'error') !== undefined ? { error: str(route, 'error') } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n }\n}\n\n/** Whether one of the two fetches failed with a fetch-level error record. */\nfunction isAbort(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError'\n}\n\n/**\n * Project one session route (`/v1/magpie/route`) onto the wire shape. The\n * gateway returns `{\"route\":null}` for a session it has not routed yet, so\n * absence maps to `undefined`, not an empty object.\n */\nfunction toSessionRoute(data: LooseRecord): SessionRouteView | undefined {\n const route = data.route\n if (route === null || route === undefined || typeof route !== 'object') return undefined\n const record = route as LooseRecord\n const triesRaw = Array.isArray(record.tries) ? (record.tries as LooseRecord[]) : []\n const tries: SessionRouteTry[] = triesRaw.map((entry) => {\n const ms = num(entry, 'ms')\n const status = num(entry, 'status')\n return {\n ...(str(entry, 'model') !== undefined ? { model: str(entry, 'model') } : {}),\n ...(entry.done === true ? { done: true } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(str(entry, 'fail') !== undefined ? { fail: str(entry, 'fail') } : {}),\n }\n })\n const ms = num(record, 'ms')\n const ttftMs = num(record, 'ttft_ms')\n const status = num(record, 'status')\n const seq = num(data, 'seq')\n return {\n ...(str(record, 'time') !== undefined ? { time: str(record, 'time') } : {}),\n ...(str(record, 'asked') !== undefined ? { asked: str(record, 'asked') } : {}),\n ...(str(record, 'model') !== undefined ? { model: str(record, 'model') } : {}),\n ...(str(record, 'served') !== undefined ? { served: str(record, 'served') } : {}),\n ...(str(record, 'group') !== undefined ? { group: str(record, 'group') } : {}),\n ...(tries.length > 0 ? { tries } : {}),\n ...(record.done === true ? { done: true } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n ...(str(record, 'error') !== undefined ? { error: str(record, 'error') } : {}),\n ...(seq !== undefined ? { seq } : {}),\n }\n}\n\n/**\n * Fetch the full Web trace when a Web Key is configured, then add quotas;\n * otherwise fall back to the gateway-key-only ledger/concurrency view. The\n * session route is a final fallback if the full trace is unavailable.\n * A full-trace auth failure is shown beside the fallback data rather than\n * hiding the gateway-key view: the Web Key is optional and can be stale.\n * @param endpoint - effective API endpoint (page settings over patch config).\n * @param signal - caller lifetime; the popover aborts on close.\n * @param session - DSH session id to find its route in the full trace.\n * @param webKey - optional Magpie Web Key, stored server-side only.\n * @returns the compressed view, always with a status.\n */\nexport async function fetchTraceView(endpoint: EffectiveEndpoint, signal: AbortSignal, session?: string, webKey?: string): Promise<TraceView> {\n const fetchedAt = new Date().toISOString()\n let base: string | undefined\n try {\n base = deriveGatewayBase(normalizeBaseUrl(endpoint.baseUrl))\n } catch {\n base = undefined\n }\n const defaultRoutingUrl = base !== undefined && base !== '' ? routingUrlFor(base) : undefined\n if (!isConfigured(endpoint)) return { status: 'unconfigured', fetchedAt, ...(defaultRoutingUrl !== undefined ? { routingUrl: defaultRoutingUrl } : {}) }\n if (base === undefined || base === '') return { status: 'unconfigured', fetchedAt, ...(defaultRoutingUrl !== undefined ? { routingUrl: defaultRoutingUrl } : {}) }\n const key = endpoint.apiKey\n const fullWebTrace = webKey !== undefined && webKey.trim() !== ''\n ? fetchFullWebTrace(base, webKey.trim(), signal)\n .then((out) => ({ data: out.trace, base: out.base }))\n .catch((error: unknown) => ({ error }))\n : Promise.resolve(undefined)\n\n const usage = fetchJson(base, key, `/v1/magpie/usage/requests?limit=${TRACE_REQUEST_ROWS}&period=${LEDGER_PERIOD}`, signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const quotas = fetchJson(base, key, '/v1/magpie/quotas', signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const concurrency = fetchJson(base, key, '/v1/magpie/concurrency', signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const sessionRoute = session !== undefined && session !== ''\n ? fetchJson(base, key, `/v1/magpie/route?session=${encodeURIComponent(session)}`, signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n : Promise.resolve(undefined)\n const [usageOut, quotasOut, concurrencyOut, routeOut, fullTraceOut] = await Promise.all([usage, quotas, concurrency, sessionRoute, fullWebTrace])\n\n const usageFailed = 'error' in usageOut\n const quotasFailed = 'error' in quotasOut\n if (usageFailed && quotasFailed) {\n // Both halves failed: one status kind, never a throw. An aborted popover\n // is not a failure worth a message \u2014 the caller is gone.\n const errors: unknown[] = [usageOut.error, quotasOut.error]\n if (errors.some(isAbort)) return { status: 'network', message: 'aborted', fetchedAt }\n const first = errors[0] as (Error & { statusCode?: number }) | undefined\n const kind = first !== undefined && typeof first.statusCode === 'number'\n ? statusForStatusCode(first.statusCode)\n : (first instanceof TypeError ? 'network' : 'unknown')\n return { status: kind, message: first instanceof Error ? first.message : undefined, fetchedAt }\n }\n\n const usageData = usageFailed ? {} : (usageOut.data as LooseRecord)\n const quotasData = quotasFailed ? {} : (quotasOut.data as LooseRecord)\n const concurrencyData = 'error' in concurrencyOut ? undefined : (concurrencyOut.data as LooseRecord)\n\n const totals: TraceTotals = {\n requests: num(usageData, 'calls') ?? 0,\n errors: num(usageData, 'errors') ?? 0,\n retried: num(usageData, 'retried') ?? 0,\n canceled: num(usageData, 'canceled') ?? 0,\n ...(num(usageData, 'credits') !== undefined ? { credits: num(usageData, 'credits') } : {}),\n }\n const rows = Array.isArray(usageData.rows) ? (usageData.rows as LooseRecord[]) : []\n const requests = rows.map(toRequestRow).filter((row): row is TraceRequestRow => row !== undefined)\n const accountsRaw = Array.isArray(quotasData.data) ? (quotasData.data as LooseRecord[]) : []\n const accounts = accountsRaw\n .map(toAccountRow)\n .filter((row): row is TraceAccountRow => row !== undefined)\n .slice(0, TRACE_ACCOUNT_ROWS)\n const activeRaw = concurrencyData !== undefined && Array.isArray(concurrencyData.active)\n ? (concurrencyData.active as LooseRecord[])\n : []\n // The popover's own session's request first, then the longest-running.\n const active = activeRaw\n .map((entry) => toActiveRow(entry, session))\n .filter((row): row is ActiveRequestRow => row !== undefined)\n .sort((a, b) => (b.own === true ? 1 : 0) - (a.own === true ? 1 : 0) || b.ms - a.ms)\n .slice(0, TRACE_ACTIVE_ROWS)\n\n const fullTraceData = fullTraceOut !== undefined && 'data' in fullTraceOut\n ? fullTraceOut.data as LooseRecord\n : undefined\n const routingUrl = defaultRoutingUrl\n const fullRoutes = fullTraceData !== undefined && Array.isArray(fullTraceData.routes)\n ? fullTraceData.routes as LooseRecord[]\n : []\n // Prefer the addressed session's own latest route. With no session \u2014 or a\n // session the gateway never routed \u2014 fall back to the newest route in the\n // whole trace, so the popover still shows the latest overall routing.\n const matched = session !== undefined\n ? [...fullRoutes].reverse().find((route) => str(route, 'session') === session)\n : undefined\n const matchedRoute = matched ?? (fullRoutes.length > 0 ? fullRoutes[fullRoutes.length - 1] : undefined)\n const sessionTrace = matchedRoute !== undefined ? toSessionTrace(matchedRoute, accounts) : undefined\n const traceFailure = fullTraceOut !== undefined && 'error' in fullTraceOut ? fullTraceOut.error : undefined\n const webTraceError: TraceView['webTraceError'] = webKey === undefined || webKey.trim() === ''\n ? 'missing-key'\n : traceFailure !== undefined\n ? (Number((traceFailure as Error & { statusCode?: number })?.statusCode) === 401 ? 'unauthorized'\n : Number((traceFailure as Error & { statusCode?: number })?.statusCode) === 403 ? 'forbidden' : 'unavailable')\n : undefined\n\n return {\n status: 'ok',\n fetchedAt,\n routingUrl,\n totals,\n ...(webTraceError !== undefined ? { webTraceError } : {}),\n ...(traceFailure instanceof Error ? { webTraceMessage: traceFailure.message } : {}),\n ...(requests.length > 0 ? { requests } : {}),\n ...(accounts.length > 0 ? { accounts } : {}),\n ...(concurrencyData !== undefined ? { concurrency: toConcurrency(concurrencyData) } : {}),\n ...(active.length > 0 ? { active } : {}),\n ...((routeOut !== undefined && 'data' in routeOut)\n ? { sessionRoute: toSessionRoute((routeOut as { data: LooseRecord }).data) }\n : {}),\n ...(sessionTrace !== undefined ? { sessionTrace } : {}),\n }\n}\n\n/** Narrow an unknown value onto the wire status list (client decode). */\nexport function asTraceStatus(value: unknown): TraceStatus {\n return STATUS_KINDS.includes(value as TraceStatus) ? (value as TraceStatus) : 'unknown'\n}\n"],
5
- "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,aAAAC,kBAAiB;;;ACD1B,SAAS,mBAAmB;AAC5B,SAAS,UAAU,QAAQ,IAAI,WAAW,aAAa;AACvD,SAAS,SAAS,YAAY;AAyCvB,IAAM,gBAAgB,CAAC,WAAW,OAAO,UAAU,QAAQ,SAAS,KAAK;AAOhF,IAAM,eAAkC,CAAC,QAAQ,WAAW,OAAO,UAAU,QAAQ,SAAS,OAAO,OAAO;AAE5G,IAAM,gBAAuE;AAAA,EAC3E,MAAM,EAAE,MAAM,QAAQ,aAAa,yDAAY;AAAA,EAC/C,SAAS,EAAE,MAAM,WAAW,aAAa,6CAAU;AAAA,EACnD,KAAK,EAAE,MAAM,OAAO,aAAa,qEAAc;AAAA,EAC/C,QAAQ,EAAE,MAAM,UAAU,aAAa,2EAAe;AAAA,EACtD,MAAM,EAAE,MAAM,QAAQ,aAAa,qEAAc;AAAA,EACjD,OAAO,EAAE,MAAM,cAAc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;AAIf,gBAAM,QAAS,IAA2C;AAC1D,iBAAO,SAAS,MAAM,OAAO,UAAU,YAAY,EAAE,MAAM,MAAM,GAAG,KAAK,GAAG,0CAA0C;AAAA,QACxH,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,QAAQ;AAAA,EAER;AAKA,mBAAiB,EAAE,OAAO,SAAS,eAAe,WAAW,kBAAkB;AAE/E,wBAAsB,KAAK,MAAM;AAEjC,QAAM,cAAe,IAA6C;AAClE,MAAI,OAAO,gBAAgB,YAAY;AACrC,gBAAY,KAAK,KAAK,MAAM,MAAM;AAChC,cAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO,EAAE,MAAM;AACjB;",
4
+ "sourcesContent": ["import { join } from 'node:path'\nimport { writeFile } from 'node:fs/promises'\n\nimport {\n ModelCatalog,\n defaultCachePath,\n fetchMagpieModels,\n type CatalogSnapshot,\n type MagpieModelEntry,\n} from './adapter/catalog.ts'\nimport { legacyDataDir } from './homeDir.ts'\nimport { MagpieAdapter } from './adapter/magpie-adapter.ts'\nimport type { AttachmentStore } from './adapter/messages.ts'\nimport { resolveConfig, type DshMagpieConnectConfig } from './config.ts'\nimport { deriveGatewayBase, fetchTraceView, fetchWebIcon, TRACE_TIMEOUT_MS } from './trace.ts'\nimport {\n SettingsStore,\n defaultSettingsPath,\n isConfigured,\n normalizeBaseUrl,\n normalizePageSettings,\n resolveEffectiveEndpoint,\n type MagpieSettingsView,\n} from './settings.ts'\n\n/**\n * dsh-magpie-connect DSH cordis plugin entry.\n *\n * Registers a DSH LlmAdapter streaming directly from the Magpie gateway\n * (marketplace shape: no child process, no binary, no proxy). The model\n * catalog warms up in the background (live gateway list with disk cache +\n * static snapshot fallback).\n *\n * The Settings sidebar page (client half) talks to the REST routes below:\n * connection endpoint (baseUrl/apiKey) applies live without restart, and the\n * hidden-model list filters the picker immediately.\n *\n * dispose(): stop the catalog refresh loop. The cordis fiber disposal\n * guarantees this runs on plugin reload/unload and on DSH shutdown.\n */\n\n// Minimal structural typing against the host ctx; keeps the plugin independent\n// of the exact @deepseek-ai/cordis version DSH ships.\nexport interface PluginContext {\n logger: { info(...args: unknown[]): void; warn(...args: unknown[]): void; error(...args: unknown[]): void }\n llm?: { registerAdapter(providers: string[], adapter: unknown): unknown }\n get?(key: string): unknown\n inject?(deps: string[], fn: (ctx: Record<string, unknown>) => unknown): unknown\n effect?(fn: () => () => void): unknown\n on?(event: string, listener: (...args: never[]) => unknown): () => void\n /**\n * Cordis `ctx.emit` (mixed in from the events service). Used to publish\n * `llm/adapters-updated` when this plugin's own catalog moves, without\n * touching the adapter registry.\n */\n emit?(event: string, ...args: unknown[]): unknown\n}\n\nexport const name = 'dsh-magpie-connect'\nexport const inject = ['llm'] as const\n\n/** Browser-facing REST root for the settings page (served under the shared /api channel). */\nexport const SETTINGS_API = '/api/magpie-settings'\nexport const MODELS_API = '/api/magpie-models'\nexport const TEST_API = '/api/magpie-test'\n/**\n * Candidate discovery: asks the endpoint the form currently shows (including a\n * key typed but not yet saved) what it serves. The reply is candidates the\n * user picks from \u2014 never configuration written behind them.\n */\nexport const DISCOVER_API = '/api/magpie-discover'\n/**\n * Routing-trace read for the composer button's popover (`/api/magpie-trace`).\n * The host reads the gateway's own ledger (`/v1/magpie/usage/requests`) and\n * quotas (`/v1/magpie/quotas`) with the stored key and serves the compressed\n * view \u2014 the browser never sees the key nor talks to the gateway cross-origin.\n */\nexport const TRACE_API = '/api/magpie-trace'\n/** Same-origin proxy for Magpie Web provider icons; the Web Key stays on the Host. */\nexport const ICON_API = '/api/magpie-icon'\n\n/**\n * How long a settings save waits for the catalog re-read it triggered.\n *\n * The page re-reads rows right after the response, so the save must not answer\n * before a fast gateway has been read; but the credential write is already\n * durable, so a slow gateway must not hold the request open either.\n */\nconst SAVE_REFRESH_WAIT_MS = 5000\n\n/** Backend generation behind the shared settings routes (newest wins). */\nexport interface SettingsBackend {\n store: SettingsStore\n catalog: ModelCatalog\n patchEndpoint: { baseUrl: string; apiKey: string }\n effective: () => { baseUrl: string; apiKey: string }\n applyPageSettings: () => void\n}\n\ntype FetchRegister = (route: {\n path: string\n methods: string[]\n requestBody: string\n fetch: (request: Request) => Promise<Response>\n}) => () => void | Promise<void>\n\ninterface ModelRow {\n /** Route id, used by the allowlist, requests and session history. */\n id: string\n /** `<group>/<display_name>` label the settings list and picker show. */\n displayName: string\n contextWindow?: number\n maxTokens?: number\n image: boolean\n responsesOnly: boolean\n reasoning: boolean\n efforts: string[]\n /** Whether the allowlist currently offers this model in the picker. */\n enabled: boolean\n /**\n * What lists this id right now: `'gateway'` (the live directory), `'static'`\n * (only the built-in snapshot) or `'none'` (nothing does \u2014 a hidden id the\n * gateway has dropped). The page labels the last two so a stale row cannot be\n * mistaken for a model the gateway still serves. Candidates from the discover\n * route leave it unset: they come from the gateway by construction.\n */\n source?: 'gateway' | 'static' | 'none'\n}\n\n/** One discovered candidate: a {@link ModelRow} without this plugin's own allowlist flag. */\nexport type CandidateRow = Omit<ModelRow, 'enabled'>\n\n/** True when the endpoints advertise responses but not chat completions. */\nfunction responsesOnlyFor(nativeEndpoints: readonly string[]): boolean {\n if (nativeEndpoints.length === 0) return false\n const hasCompletions = nativeEndpoints.some((endpoint) => endpoint.includes('/chat/completions'))\n return !hasCompletions && nativeEndpoints.some((endpoint) => endpoint.includes('/responses'))\n}\n\n/**\n * Both model lists are sorted by the label the user sees. Grouping models by\n * `<group>/<display_name>` keeps one gateway lane's models together; the id is a\n * tie-break so two models with the same label still have a stable order.\n */\nfunction compareModelRows(left: CandidateRow, right: CandidateRow): number {\n return left.displayName.localeCompare(right.displayName, 'zh') || left.id.localeCompare(right.id)\n}\n\n/** Project one catalog entry (or a bare id) into the wire row the page renders. */\nfunction toRow(id: string, entry: MagpieModelEntry | undefined): CandidateRow {\n return {\n id,\n displayName: entry?.displayName ?? id,\n ...(entry?.contextWindow !== undefined ? { contextWindow: entry.contextWindow } : {}),\n ...(entry?.maxTokens !== undefined ? { maxTokens: entry.maxTokens } : {}),\n image: entry?.image ?? false,\n responsesOnly: responsesOnlyFor(entry?.nativeEndpoints ?? []),\n reasoning: entry?.reasoning ?? false,\n efforts: entry?.efforts ?? [],\n }\n}\n\nlet currentBackend: SettingsBackend | null = null\nlet liveRouteSets = 0\nlet routeDisposers: Array<() => void | Promise<void>> | null = null\n\n/** @internal Test hook: forget installed routes so the next apply reinstalls. */\nexport function __resetSettingsRoutes(): void {\n currentBackend = null\n liveRouteSets = 0\n routeDisposers = null\n}\n\nfunction jsonResponse(status: number, payload: unknown): Response {\n return new Response(JSON.stringify(payload), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },\n })\n}\n\nconst routeOk = (value: unknown): Response => jsonResponse(200, { ok: true, value })\nconst routeFail = (error: unknown): Response =>\n jsonResponse(500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n\nasync function readRouteBody(request: Request): Promise<unknown> {\n try {\n return await request.json()\n } catch {\n return {}\n }\n}\n\n/**\n * The rows the settings page renders.\n *\n * One row per id the gateway directory holds, each flagged with whether the\n * allowlist offers it. Unlike the old blacklist shape there are no extra rows\n * for ids outside the directory: an allowlist entry the gateway no longer\n * serves is simply not a model any more, and surfacing it would offer the user\n * a checkbox that can never take effect.\n */\nfunction buildModelRows(backend: SettingsBackend): ModelRow[] {\n const { store, catalog } = backend\n const allowlist = store.get().enabledModels\n const allowed = allowlist === undefined ? undefined : new Set(allowlist)\n return catalog.directory()\n .map((id) => ({\n ...toRow(id, catalog.getEntry(id)),\n enabled: allowed === undefined || allowed.has(id),\n source: catalog.sourceFor(id),\n }))\n .sort(compareModelRows)\n}\n\nfunction backendOrThrow(): SettingsBackend {\n if (!currentBackend) throw new Error('dsh-magpie-connect: settings backend not ready')\n return currentBackend\n}\n\n/**\n * One registered route: the connection registry keys routes by PATH and\n * rejects a second registration of the same path, so every method of one\n * endpoint must share a single entry and dispatch inside its handler. Two\n * entries on `SETTINGS_API` (GET + POST) silently lose the second one \u2014 the\n * save button then answers `404 not found` forever.\n */\ninterface RouteDefinition {\n path: string\n methods: string[]\n requestBody: string\n fetch: (request: Request) => Promise<Response>\n}\n\n/**\n * The only settings shape the browser may see. The credential is represented\n * by its presence, never by its value; `fromPage`/`fromPatch` are gone for the\n * same reason \u2014 both carried the gateway key.\n */\nfunction settingsView(backend: SettingsBackend): MagpieSettingsView {\n const page = backend.store.get()\n const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, page)\n return {\n baseUrl: endpoint.baseUrl,\n hasApiKey: endpoint.apiKey !== '',\n hasWebKey: (page.webKey ?? '').trim() !== '',\n enabledModels: page.enabledModels,\n inheritedModels: page.enabledModels === undefined,\n showComposerIcon: page.showComposerIcon !== false,\n }\n}\n\n/**\n * Accept an older client's payload that still includes the credential field\n * but left it blank (\"keep the saved key\"). The field is dropped so the save\n * merges instead of failing validation. A blank key with nothing stored is\n * still an error: there is no credential to keep.\n */\nfunction stripBlankApiKey(backend: SettingsBackend, body: unknown): unknown {\n if (!body || typeof body !== 'object') return body\n const record = body as Record<string, unknown>\n const rest = { ...record }\n if (typeof record.apiKey === 'string' && record.apiKey.trim() === '') {\n if (resolveEffectiveEndpoint(backend.patchEndpoint, backend.store.get()).apiKey === '') {\n throw new Error('dsh-magpie-connect: apiKey is required and must not be empty')\n }\n delete rest.apiKey\n }\n // An empty Web Key field means \"keep the saved Web Key\", just like the API\n // Key field. It may also be omitted entirely by older clients.\n if (typeof record.webKey === 'string' && record.webKey.trim() === '') delete rest.webKey\n return rest\n}\n\nasync function handleSettingsGet(): Promise<Response> {\n try {\n return routeOk(settingsView(backendOrThrow()))\n } catch (error) {\n return routeFail(error)\n }\n}\n\nasync function handleSettingsPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = await readRouteBody(request)\n const normalized = normalizePageSettings(stripBlankApiKey(backend, body))\n // The submitted allowlist is stored **as submitted**. Dropping ids the\n // current directory does not list would silently undo a delete: a lane's\n // models come and go between refreshes, so the ids removed while the\n // gateway happened to be un-listing them would be forgotten, then reappear\n // in the picker on the next refresh that listed them again.\n await backend.store.save(normalized)\n backend.applyPageSettings()\n // A save can move the endpoint (or just the key), so re-read the directory\n // before answering: the page re-reads rows right after this response, and a\n // key-guarded gateway would otherwise still be serving the old, empty\n // snapshot when that read lands.\n //\n // Bounded: the write is already durable, so a gateway that answers slowly\n // (or not at all) must not turn a successful save into a client-side\n // timeout. Losing the race only costs a stale row, never the setting.\n if (normalized.baseUrl !== undefined || normalized.apiKey !== undefined) {\n await Promise.race([\n backend.catalog.refreshOnce(),\n new Promise((resolve) => setTimeout(resolve, SAVE_REFRESH_WAIT_MS)),\n ])\n }\n return routeOk(settingsView(backend))\n } catch (error) {\n return routeFail(error)\n }\n}\n\nasync function handleModelsGet(): Promise<Response> {\n try {\n const backend = backendOrThrow()\n return routeOk({ models: buildModelRows(backend), snapshot: backend.catalog.snapshot() })\n } catch (error) {\n return routeFail(error)\n }\n}\n\n/** Resolve the endpoint one probe should ask: form values first, effective config as fallback. */\nfunction probeTarget(\n backend: SettingsBackend,\n body: { baseUrl?: unknown; apiKey?: unknown },\n): { origin: string; key: string } {\n const effective = backend.effective()\n const origin = normalizeBaseUrl(body.baseUrl ?? effective.baseUrl)\n // A blank field means \"use the saved key\": older pages echoed the\n // credential into the form, and a blank submit must keep working now that\n // the server no longer sends it back.\n const typed = typeof body.apiKey === 'string' ? body.apiKey.trim() : ''\n const key = typed === '' ? effective.apiKey.trim() : typed\n if (key === '') throw new Error('dsh-magpie-connect: apiKey is required \u2014 fill it in before asking the gateway')\n return { origin, key }\n}\n\n/**\n * Turn a gateway failure into copy the page can show. A 404 from the gateway\n * almost always means the origin path is wrong or the key is unknown or\n * unauthorized (many gateways hide existence behind 404 instead of 401).\n */\nfunction hintGatewayFailure(error: unknown): Response {\n const message = error instanceof Error ? error.message : String(error)\n const hinted =\n /HTTP 404/.test(message) && !/\u7F51\u5173\u8FD4\u56DE 404/.test(message)\n ? `${message}\uFF08\u7F51\u5173\u8FD4\u56DE 404\uFF1A\u591A\u4E3A API \u5730\u5740\u8DEF\u5F84\u4E0D\u5BF9\uFF0C\u6216\u8BE5 Key \u65E0\u6548/\u65E0\u6743\u8BBF\u95EE\uFF09`\n : message\n return routeFail(hinted)\n}\n\nasync function handleTestPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = (await readRouteBody(request)) as { baseUrl?: unknown; apiKey?: unknown }\n const { origin, key } = probeTarget(backend, body)\n const models = await fetchMagpieModels(origin, fetch, { headers: { authorization: `Bearer ${key}` } })\n return routeOk({ count: models.size, models: [...models.keys()].sort().slice(0, 50) })\n } catch (error) {\n return hintGatewayFailure(error)\n }\n}\n\n/**\n * Candidate discovery for the fetch-available-models dialog.\n *\n * Unlike {@link handleTestPost} (a count for the connection check) this returns\n * full rows so the picker can show the same chips the list does, and it caps\n * nothing: the dialog filters client-side. The origin and key come from the\n * form, so a provider can be filled in one pass instead of save-then-return.\n */\nasync function handleDiscoverPost(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const body = (await readRouteBody(request)) as { baseUrl?: unknown; apiKey?: unknown }\n const { origin, key } = probeTarget(backend, body)\n const models = await fetchMagpieModels(origin, fetch, { headers: { authorization: `Bearer ${key}` } })\n // The reply is the gateway's whole catalog as of now, so the local\n // directory adopts it wholesale. Without this, a model the gateway dropped\n // lingers in the list (and the picker) until a *successful* background\n // refresh \u2014 which on a key-guarded gateway may never come. That is how a\n // model already gone from the dialog kept showing in the settings list.\n backend.catalog.adoptDirectory(models)\n const candidates = [...models.entries()]\n .map(([id, entry]) => toRow(id, entry))\n .sort(compareModelRows)\n return routeOk({ count: candidates.length, models: candidates })\n } catch (error) {\n return hintGatewayFailure(error)\n }\n}\n\n/**\n * The composer popover's routing view: the gateway's request ledger plus the\n * accounts' allowances, compressed by {@link fetchTraceView} into the shape\n * `trace-contract.ts` declares. `?session=<id>` (the DSH session the composer\n * popover belongs to) adds the session's own latest route. Errors resolve\n * into a status kind the popover renders as one localized hint row \u2014 never\n * a throw.\n */\nasync function handleTraceGet(request: Request): Promise<Response> {\n try {\n const backend = backendOrThrow()\n const session = new URL(request.url).searchParams.get('session') ?? undefined\n const pageSettings = backend.store.get()\n const view = await fetchTraceView(backend.effective(), AbortSignal.timeout(TRACE_TIMEOUT_MS), session ?? undefined, pageSettings.webKey)\n return routeOk(view)\n } catch (error) {\n return routeFail(error)\n }\n}\n\n/**\n * Serve one Magpie Web provider icon through DSH's same-origin API so the\n * browser does not need a Web Key cookie for `api.lan:3430/icons/...`.\n */\nasync function handleIconGet(request: Request): Promise<Response> {\n const name = new URL(request.url).searchParams.get('name') ?? ''\n if (name === '') return jsonResponse(404, { ok: false, error: 'icon name is required' })\n try {\n const backend = backendOrThrow()\n const webKey = backend.store.get().webKey\n if (webKey === undefined || webKey.trim() === '') {\n return jsonResponse(404, { ok: false, error: 'Magpie Web Key is not configured' })\n }\n const base = deriveGatewayBase(normalizeBaseUrl(backend.effective().baseUrl))\n if (base === undefined || base === '') return jsonResponse(404, { ok: false, error: 'gateway base is invalid' })\n const icon = await fetchWebIcon(base, webKey.trim(), name, AbortSignal.timeout(TRACE_TIMEOUT_MS))\n return new Response(icon.body, {\n status: 200,\n headers: { 'content-type': icon.contentType, 'cache-control': 'public, max-age=3600' },\n })\n } catch (error) {\n return jsonResponse(404, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n}\n\nfunction routeDefinitions(): RouteDefinition[] {\n return [\n {\n path: SETTINGS_API,\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => (request.method === 'POST' ? handleSettingsPost(request) : handleSettingsGet()),\n },\n {\n path: MODELS_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: () => handleModelsGet(),\n },\n {\n path: TEST_API,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleTestPost(request),\n },\n {\n path: DISCOVER_API,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleDiscoverPost(request),\n },\n {\n path: TRACE_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleTraceGet(request),\n },\n {\n path: ICON_API,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: (request: Request) => handleIconGet(request),\n },\n ]\n}\n\n/**\n * Install the settings-page routes on the authenticated /api channel.\n *\n * Process-wide singleton semantics: hot reload can run overlapping\n * generations of this plugin in one process, and the connection registry\n * rejects duplicate paths. The routes install once and are shared; the last\n * generation out uninstalls. Handlers resolve through `currentBackend`, so\n * they always serve the newest generation.\n */\nfunction installSettingsRoutes(\n ctx: PluginContext,\n logger: PluginContext['logger'],\n): void {\n try {\n if (typeof ctx.inject !== 'function') return\n ctx.inject(['connection'], (cctx: Record<string, unknown>) => {\n const connection = cctx.connection as { fetch?: { register?: FetchRegister } } | undefined\n const register = connection?.fetch?.register\n if (typeof register !== 'function') {\n logger.warn('dsh-magpie-connect: connection fetch registry unavailable; settings page API disabled')\n return\n }\n liveRouteSets += 1\n try {\n if (routeDisposers === null) {\n const installed: Array<() => void | Promise<void>> = []\n try {\n for (const definition of routeDefinitions()) {\n try {\n installed.push(register(definition))\n } catch (error) {\n // A live sibling generation already owns this path; share it.\n // Only ever expected for a whole path we also declare \u2014 since\n // every method of one path shares one entry, losing one here\n // means the sibling serves it identically.\n if (error instanceof Error && /already registered/.test(error.message)) {\n logger.warn(`dsh-magpie-connect: ${definition.path} already registered by another generation; sharing it`)\n continue\n }\n throw error\n }\n }\n } catch (error) {\n for (const dispose of installed.reverse()) {\n try {\n const result = dispose()\n if (result instanceof Promise) result.catch(() => {})\n } catch {\n // roll back best-effort\n }\n }\n throw error\n }\n routeDisposers = installed\n }\n } catch (error) {\n liveRouteSets -= 1\n logger.warn(`dsh-magpie-connect: settings API unavailable: ${error instanceof Error ? error.message : String(error)}`)\n throw error\n }\n return async () => {\n liveRouteSets -= 1\n if (liveRouteSets <= 0) {\n liveRouteSets = 0\n const owned = routeDisposers\n routeDisposers = null\n if (owned) {\n for (const dispose of owned.reverse()) await dispose()\n }\n }\n }\n })\n } catch (error) {\n logger.warn(`dsh-magpie-connect: settings API unavailable: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function apply(\n ctx: PluginContext,\n config: DshMagpieConnectConfig = {},\n): { ready: Promise<{ version: string }> } {\n const logger = ctx.logger\n const cfg = resolveConfig(config)\n const ready = Promise.resolve({ version: 'adapter' })\n\n if (!ctx.llm || typeof ctx.llm.registerAdapter !== 'function') {\n logger.error('dsh-magpie-connect: llm service unavailable; adapter cannot register')\n return { ready }\n }\n\n const dataDir = cfg.dataDir\n const statusPath = join(dataDir, 'adapter-status.json')\n const writeStatus = (status: CatalogSnapshot, lastError: string): void => {\n void writeFile(\n statusPath,\n JSON.stringify({ ...status, lastError, writtenAt: new Date().toISOString() }, null, 2),\n 'utf8',\n ).catch(() => {})\n }\n\n // An explicit `dataDir` means the user owns the path: never read the pre-0.5\n // file and never delete anything. Otherwise the store falls back read-only to\n // `~/.dsh-magpie-connect/settings.json` and migrates it on the first save.\n const store = new SettingsStore({\n path: defaultSettingsPath(dataDir),\n legacyPath: config.dataDir === undefined ? join(legacyDataDir(), 'settings.json') : undefined,\n // Only the plugin-owned default directory is chmod-ed; an explicit\n // `dataDir` belongs to the user and is left as they set it.\n privateDir: config.dataDir === undefined,\n })\n const patchEndpoint = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey }\n const effective = () => resolveEffectiveEndpoint(patchEndpoint, store.get())\n\n /**\n * Publish `llm/adapters-updated`, the one notification DSH's model\n * directory listens to.\n *\n * The browser caches one `modelCatalog()` read per Host generation and\n * re-reads only on this event. Registering an adapter fires it once, but\n * nothing does for a pure in-memory change, so hiding models, switching\n * the gateway origin, or a refresh that moved the list all left the picker\n * on the stale snapshot until restart. `dsh-workbuddy-connect` solves the\n * same problem identically for its visibility toggles.\n */\n const announceTopology = (): void => {\n if (typeof ctx.emit !== 'function') return\n try {\n ctx.emit('llm/adapters-updated')\n } catch (error) {\n logger.warn(`dsh-magpie-connect: llm/adapters-updated emit failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const catalog = new ModelCatalog({\n baseUrl: effective().baseUrl,\n apiKey: effective().apiKey,\n refreshSeconds: cfg.refreshSeconds,\n cachePath: defaultCachePath(dataDir),\n onRefresh: (status, lastError) => {\n writeStatus(status, lastError)\n if (lastError) logger.warn(`dsh-magpie-connect: catalog refresh issue: ${lastError}`)\n },\n onInvalidate: announceTopology,\n })\n /**\n * Apply page settings to the live catalog + adapter (no restart needed).\n *\n * The endpoint is a pair: the gateway guards `GET /models` with the same key\n * as inference, so the key is part of the catalog's identity, not just the\n * URL. A key-only edit therefore re-points the catalog too \u2014 otherwise the\n * refresh keeps 401ing and the picker keeps serving the static snapshot,\n * which is why a model just ticked in the fetch dialog never appeared.\n */\n const applyPageSettings = (): void => {\n const page = store.get()\n const endpoint = resolveEffectiveEndpoint(patchEndpoint, page)\n // The gate: URL and key are both required. Anything missing clears the\n // catalog API root, which empties the picker and calls fail fast.\n // The value is the versioned root (`\u2026/v1`), passed through untouched.\n const configured = isConfigured(endpoint)\n catalog.setEndpoint(configured ? endpoint.baseUrl.replace(/\\/+$/, '') : '', configured ? endpoint.apiKey : '')\n catalog.setEnabled(page.enabledModels ?? null)\n }\n const adapter = new MagpieAdapter(catalog, {\n providerId: cfg.providerId,\n displayName: cfg.displayName,\n magpieBaseUrl: cfg.baseUrl,\n apiKey: cfg.apiKey,\n maxRetries: cfg.maxRetries,\n timeoutMs: cfg.timeoutMs,\n firstEventTimeoutMs: cfg.firstEventTimeoutMs,\n idleTimeoutMs: cfg.idleTimeoutMs,\n runtime: {\n baseUrl: () => {\n const endpoint = effective()\n return isConfigured(endpoint) ? endpoint.baseUrl.replace(/\\/+$/, '') : ''\n },\n apiKey: () => effective().apiKey,\n },\n resolveAttachments: () => {\n try {\n const attachments = typeof ctx.get === 'function' ? (ctx.get('attachments') as AttachmentStore | undefined) : undefined\n return attachments && typeof attachments.readImageRequest === 'function' ? attachments : undefined\n } catch {\n return undefined\n }\n },\n })\n store.onChange(applyPageSettings)\n\n // Register immediately: the provider must appear in the selector right\n // away, even while the catalog is still warming up (listModels is read\n // live at selector time, so models appear as refreshes land).\n ctx.llm.registerAdapter([cfg.providerId], adapter)\n logger.info(`dsh-magpie-connect: adapter registered for \"${cfg.providerId}\" (catalog warms up in background)`)\n void (async () => {\n // Startup order is load-bearing in both directions:\n //\n // 1. read the document first \u2014 until it is applied, the catalog is pointed\n // at the patch/default endpoint, not the user's, so any fetch it does\n // now fails and leaves the directory empty;\n // 2. apply it, so the catalog knows the real endpoint before it warms up;\n // 3. warm the directory;\n // 4. only then run the legacy conversion, which needs the ids the gateway\n // actually serves.\n //\n // Doing 3 before 2 was a regression: the warm-up hit the default endpoint,\n // failed, and the settings page fell back to the built-in snapshot.\n const persisted = await store.read()\n await store.hydrate(persisted, undefined)\n applyPageSettings()\n await catalog.start().catch((err) => {\n logger.error(`dsh-magpie-connect: catalog start failed: ${err instanceof Error ? err.message : String(err)}`)\n })\n await store.hydrate(persisted, catalog.directory())\n applyPageSettings()\n })().catch((err) => {\n logger.error(`dsh-magpie-connect: startup failed: ${err instanceof Error ? err.message : String(err)}`)\n })\n\n // Suppress the auto-generated config form: this plugin owns a dedicated\n // settings page (client half). Guarded \u2014 compositions without the settings\n // service simply skip it.\n try {\n if (typeof ctx.inject === 'function') {\n ctx.inject(['settings'], (settingsCtx: Record<string, unknown>) => {\n try {\n const scoped = settingsCtx as {\n effect?: (fn: () => unknown, label?: string) => unknown\n settings?: { configure?: (policy: unknown, fiber: unknown) => unknown }\n }\n const fiber = (ctx as unknown as Record<string, unknown>).fiber\n scoped.effect?.(() => scoped.settings?.configure?.({ auto: false }, fiber), 'dsh-magpie-connect: custom settings page')\n } catch {\n // presentation policy is best-effort\n }\n })\n }\n } catch {\n // presentation policy is best-effort\n }\n\n // Newest generation wins: shared route handlers below always resolve through\n // here, so the settings page talks to the latest store/catalog/adapter even\n // when an older generation installed the routes.\n currentBackend = { store, catalog, patchEndpoint, effective, applyPageSettings }\n\n installSettingsRoutes(ctx, logger)\n\n const maybeEffect = (ctx as { effect?: PluginContext['effect'] }).effect\n if (typeof maybeEffect === 'function') {\n maybeEffect.call(ctx, () => () => {\n catalog.stop()\n })\n }\n return { ready }\n}\n\nexport { MagpieAdapter } from './adapter/magpie-adapter.ts'\nexport { ModelCatalog } from './adapter/catalog.ts'\nexport { SettingsStore, isConfigured, resolveEffectiveEndpoint } from './settings.ts'\nexport {\n resolveConfig,\n type DshMagpieConnectConfig,\n} from './config.ts'\n", "import { randomBytes } from 'node:crypto'\nimport { readFile, rename, rm, writeFile, mkdir } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\n/**\n * Model directory for the Magpie gateway.\n *\n * Single source: `GET {baseUrl}/models` already curates the servable set\n * with full per-model metadata (modalities, native endpoints, reasoning\n * ladders, context limits). There is no paid/free filter \u2014 everything listed\n * is exposed. A disk cache plus a compile-time static snapshot covers gateway\n * outages (the plugin still registers, the picker still lists).\n *\n * The gateway guards that endpoint with the same Bearer key as inference, so\n * every fetch here carries it: a keyless refresh is answered 401 and the\n * picker silently keeps the static snapshot instead of the live directory.\n *\n * `baseUrl` is the versioned API root (default `http://127.0.0.1:3425/v1`),\n * never an origin: the gateway may move to `/v2`, and the plugin must not know\n * that version.\n */\n\nexport interface MagpieModelEntry {\n id: string\n displayName: string\n contextWindow?: number\n maxTokens?: number\n /** Whether the gateway accepts image input for this model. */\n image: boolean\n /** Raw gateway `native_endpoints` (may be empty when undisclosed). */\n nativeEndpoints: string[]\n /** Whether the gateway reports thinking support. */\n reasoning: boolean\n /** Effort allowlist from `supported_reasoning_levels` (canonical order). */\n efforts?: string[]\n}\n\n/**\n * Thinking levels the gateway uses. pi-ai natively understands the minimal\u2192max\n * ladder; `none` (thinking disabled) and `ultra` (beyond max, e.g. Terra) are\n * gateway extensions the adapter forwards verbatim on the Responses /\n * completions wire instead of clamping.\n */\nexport const KNOWN_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const\nexport const EXTENDED_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const\n\nexport type KnownEffort = (typeof KNOWN_EFFORTS)[number]\nexport type ExtendedEffort = (typeof EXTENDED_EFFORTS)[number]\n\n/** Picker display order: `none` (disable) first, then increasing strength. */\nconst EFFORT_ORDER: readonly string[] = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']\n\nconst EFFORT_LABELS: Record<string, { name: string; description: string }> = {\n none: { name: 'None', description: '\u5173\u95ED\u601D\u8003\uFF0C\u76F4\u63A5\u56DE\u7B54' },\n minimal: { name: 'Minimal', description: '\u6700\u5C11\u601D\u8003\uFF0C\u6700\u5FEB' },\n low: { name: 'Low', description: '\u8F7B\u91CF\u601D\u8003\uFF0C\u9002\u5408\u7B80\u5355\u95EE\u7B54' },\n medium: { name: 'Medium', description: '\u9ED8\u8BA4\u6863\u4F4D\uFF0C\u5747\u8861\u8D28\u91CF\u4E0E\u901F\u5EA6' },\n high: { name: 'High', description: '\u6DF1\u5EA6\u601D\u8003\uFF0C\u9002\u5408\u590D\u6742\u7F16\u7801' },\n xhigh: { name: 'Extra high', description: '\u8D85\u9AD8\u601D\u8003\u5F3A\u5EA6' },\n max: { name: 'Max', description: '\u6700\u5F3A\u601D\u8003\uFF08pi-ai \u6863\u4F4D\uFF09\uFF0C\u6700\u6162' },\n ultra: { name: 'Ultra', description: '\u6781\u9650\u601D\u8003\uFF08\u7F51\u5173\u76F4\u901A\uFF09\uFF0C\u6700\u6162\u6700\u8D35' },\n}\n\nexport interface ReasoningEffortChoice {\n id: string\n name: string\n description?: string\n}\n\n/** Normalize one gateway effort spelling; unknown spellings are dropped. */\nexport function normalizeEffort(raw: unknown): string | undefined {\n if (typeof raw !== 'string') return undefined\n const level = raw.trim().toLowerCase()\n return (EFFORT_ORDER as readonly string[]).includes(level) ? level : undefined\n}\n\n/** Canonicalize an effort list: keep known spellings, dedupe, order canonically. */\nexport function canonicalEfforts(values: readonly unknown[] | undefined): string[] | undefined {\n if (!Array.isArray(values)) return undefined\n const out: string[] = []\n for (const value of values) {\n const level = normalizeEffort(typeof value === 'object' && value !== null ? (value as { effort?: unknown }).effort ?? value : value)\n if (level !== undefined && !out.includes(level)) out.push(level)\n }\n if (out.length === 0) return undefined\n return EFFORT_ORDER.filter((level) => out.includes(level))\n}\n\n/** Build picker efforts for an allowlist (display order = none\u2192minimal\u2192\u2026\u2192ultra). */\nexport function effortsFor(efforts: readonly string[] | undefined): ReasoningEffortChoice[] {\n const allowed = new Set(efforts ?? [])\n return EFFORT_ORDER.filter((level) => allowed.has(level)).map((level) => {\n const label = EFFORT_LABELS[level] ?? { name: level, description: '' }\n return { id: level, name: label.name, description: label.description }\n })\n}\n\n/**\n * pi-ai `thinkingLevelMap` for an effort allowlist. `off: null` is\n * load-bearing: without it pi-ai falls back to `reasoning.effort: 'none'`\n * on the Responses lane, which the gateway rejects with 400. Every\n * non-listed known level maps to null so `getSupportedThinkingLevels` hides\n * it and `clampThinkingLevel` folds stale values to the nearest listed one.\n * Gateway extensions (`none`/`ultra`) never enter the map \u2014 the adapter\n * forwards them via `provider.stream` instead of `streamSimple`.\n */\nexport function thinkingLevelMapFor(efforts: readonly string[] | undefined): Record<string, string | null> {\n const allowed = new Set(efforts ?? [])\n const map: Record<string, string | null> = { off: null }\n for (const level of KNOWN_EFFORTS) map[level] = allowed.has(level) ? level : null\n return map\n}\n\n/**\n * True when the model must go through `/v1/responses` instead of chat\n * completions: the gateway lists responses as the only native endpoint\n * (Muse Spark, Codex/Grok lanes). Anything advertising\n * `/v1/chat/completions` \u2014 including multi-endpoint models \u2014 rides the\n * completions lane for better tool support.\n */\nexport function requiresResponsesApiEntry(nativeEndpoints: readonly string[]): boolean {\n const hasCompletions = nativeEndpoints.some((endpoint) => endpoint.includes('/chat/completions'))\n if (hasCompletions) return false\n return nativeEndpoints.some((endpoint) => endpoint.includes('/responses'))\n}\n\n/** pi-ai `model.api` value for the given native endpoints. */\nexport function modelApiForEntry(nativeEndpoints: readonly string[]): 'openai-completions' | 'openai-responses' {\n return requiresResponsesApiEntry(nativeEndpoints) ? 'openai-responses' : 'openai-completions'\n}\n\n/** The gateway separates a model name from its group with a middle dot. */\nconst LABEL_GROUP_SEPARATOR = '\\u00B7'\n\n/** Capitalize only the first character; preserve the rest of a gateway/id group. */\nfunction capitalizeGroup(group: string): string {\n return group.length === 0 ? '' : group[0]!.toLocaleUpperCase() + group.slice(1)\n}\n\n/** Derive a fallback group from the id's first slash-delimited segment. */\nfunction groupFromId(id: string): string {\n const prefix = id.split('/', 1)[0]?.trim() ?? ''\n return capitalizeGroup(prefix)\n}\n\n/**\n * The one label both the DSH model picker and this plugin's settings page show.\n * The model name is exactly `display_name`. Prefer the group after the last\n * middle dot in `magpie_label`; if it is absent or empty, capitalize the first\n * character of the id's first path segment as the fallback group.\n */\nexport function displayNameFor(raw: Record<string, unknown>): string {\n const id = typeof raw.id === 'string' ? raw.id : ''\n const name = typeof raw.display_name === 'string' ? raw.display_name.trim() : ''\n if (name === '') return id\n const label = typeof raw.magpie_label === 'string' ? raw.magpie_label.trim() : ''\n const at = label.lastIndexOf(LABEL_GROUP_SEPARATOR)\n const parsedGroup = at >= 0 ? label.slice(at + 1).trim() : ''\n const idGroup = groupFromId(id)\n // Routing ids are the source of truth for these two lanes; their gateway\n // label group is generic and must not replace the explicit route prefix.\n const routingPrefix = id.startsWith('auto/') || id.startsWith('group/')\n const group = routingPrefix ? idGroup : parsedGroup || idGroup\n if (group === '') return id\n return `${group}/${name}`\n}\n\n/** Decode one gateway model object into a catalog entry. */\nexport function decodeModel(raw: unknown): MagpieModelEntry | undefined {\n if (!raw || typeof raw !== 'object') return undefined\n const record = raw as Record<string, unknown>\n const id = record.id\n if (typeof id !== 'string' || id.length === 0) return undefined\n const num = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined\n const displayName = displayNameFor(record)\n const contextWindow = num(record.context_window) ?? num(record.context_length) ?? num(record.max_input_tokens)\n const maxTokens = num(record.max_output_tokens)\n const modalities = record.modalities as { input?: unknown } | undefined\n const inputModalities = Array.isArray(modalities?.input) ? modalities.input.map(String).map((s) => s.toLowerCase()) : []\n const image = inputModalities.includes('image')\n const nativeEndpoints = Array.isArray(record.native_endpoints)\n ? (record.native_endpoints as unknown[]).filter((e): e is string => typeof e === 'string')\n : []\n const reasoning = record.reasoning === true\n const levels = record.supported_reasoning_levels\n const efforts = Array.isArray(levels)\n ? canonicalEfforts(levels.map((entry) => (entry as { effort?: unknown })?.effort ?? entry))\n : undefined\n return { id, displayName, ...(contextWindow !== undefined ? { contextWindow } : {}), ...(maxTokens !== undefined ? { maxTokens } : {}), image, nativeEndpoints, reasoning, ...(efforts !== undefined ? { efforts } : {}) }\n}\n\n/** Decode the full gateway `/v1/models` payload into entries keyed by id. */\nexport function decodeMagpieModels(data: unknown): Map<string, MagpieModelEntry> {\n const result = new Map<string, MagpieModelEntry>()\n if (!data || typeof data !== 'object') return result\n const payload = data as { data?: unknown }\n if (!Array.isArray(payload.data)) return result\n for (const raw of payload.data) {\n const entry = decodeModel(raw)\n if (entry && !result.has(entry.id)) result.set(entry.id, entry)\n }\n return result\n}\n\n/**\n * Compile-time static snapshot (observed 2026-10-02, 22 models): last-resort\n * bootstrap while the gateway is unreachable. Refreshed by hand when the\n * gateway catalog changes shape; live data always wins when reachable.\n *\n * These rows have no `magpie_label`, so their group comes from the id prefix\n * and their curated model name is retained. Live data still uses the same\n * `displayNameFor` rule.\n */\nconst staticMagpieModelSeeds: MagpieModelEntry[] = [\n { id: 'group/auto-gpt-4-1', displayName: 'GPT-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: [], reasoning: false },\n { id: 'group/auto-gpt-6-luna', displayName: 'GPT-6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: [], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'vercel/xiaomi/mimo-v2.6-flash', displayName: 'xiaomi/mimo-v2.6-flash', contextWindow: 1048576, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true },\n { id: 'vercel/alibaba/qwen3.8-omni-flash', displayName: 'alibaba/qwen3.8-omni-flash', contextWindow: 1000000, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['none', 'low', 'medium', 'xhigh'] },\n { id: 'vercel/openai/gpt-5.4-nano', displayName: 'openai/gpt-5.4-nano', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['none', 'low', 'medium', 'high', 'xhigh'] },\n { id: 'vercel/openai/gpt-4.1', displayName: 'openai/gpt-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: false },\n { id: 'vercel/google/gemini-2.5-flash-lite', displayName: 'google/gemini-2.5-flash-lite', contextWindow: 1048576, maxTokens: 65536, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'medium', 'high'] },\n { id: 'opencode-zen/muse-spark-1.3-contributor-free', displayName: 'Muse Spark 1.3 Free', contextWindow: 1048576, maxTokens: 131072, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'] },\n { id: 'opencode-zen/jev-1.13-free', displayName: 'jev-1.13-free', image: false, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: false },\n { id: 'opencode-zen/mimo-v2.6-flash-free', displayName: 'MiMo-V2.6-Flash Free', contextWindow: 200000, maxTokens: 32000, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: true },\n { id: 'opencode-zen/space-bunny-free', displayName: 'Space Bunny Free', contextWindow: 524288, maxTokens: 524288, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-6-luna', displayName: 'GPT-6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-5.6-terra', displayName: 'GPT-5.6-Terra', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] },\n { id: 'codex/gpt-5.6-luna', displayName: 'GPT-5.6-Luna', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'codex/gpt-5.5', displayName: 'GPT-5.5', contextWindow: 272000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh'] },\n { id: 'copilot/gemini-3.8-flash', displayName: 'Gemini 3.8 Flash', contextWindow: 1048576, maxTokens: 65536, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'medium', 'high'] },\n { id: 'copilot/grok-4.7', displayName: 'grok-4.7', contextWindow: 500000, maxTokens: 500000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh'] },\n { id: 'copilot/gpt-4.1', displayName: 'gpt-4.1', contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/responses', '/v1/messages'], reasoning: false },\n { id: 'copilot/gpt-6-luna', displayName: 'gpt-6-luna', contextWindow: 922000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/responses'], reasoning: true, efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'copilot/claude-sonnet-5.5', displayName: 'claude-sonnet-5.5', contextWindow: 1000000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions', '/v1/messages'], reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },\n { id: 'workbuddy-ai/hy4-preview-f', displayName: 'hy4-preview-f', contextWindow: 1000000, maxTokens: 64000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['high'] },\n { id: 'workbuddy-ai/deepseek-v4.1-flash', displayName: 'deepseek-v4.1-flash', contextWindow: 1000000, maxTokens: 128000, image: true, nativeEndpoints: ['/v1/chat/completions'], reasoning: true, efforts: ['low', 'high', 'max'] },\n]\n\n/** The exported snapshot, with each label derived by the one display-name rule. */\nexport const staticMagpieModels: MagpieModelEntry[] = staticMagpieModelSeeds.map((entry) => ({\n ...entry,\n displayName: displayNameFor({ id: entry.id, display_name: entry.displayName }),\n}))\n\nexport interface CatalogSnapshot {\n status: 'pending' | 'ready' | 'stale' | 'error'\n total: number\n exposed: number\n lastRefresh?: string\n}\n\nexport interface CatalogOptions {\n /** Refresh cadence (seconds). */\n refreshSeconds?: number\n /** Where the gateway snapshot cache lives (plugin data dir). */\n cachePath?: string\n /** Versioned API root override for tests. */\n baseUrl?: string\n /**\n * Gateway credential, sent as `Authorization: Bearer \u2026` on every catalog\n * fetch. The gateway guards `GET /models` with the same key it guards\n * inference with, so a refresh that omits it is answered 401 and the picker\n * silently stays on the static snapshot.\n */\n apiKey?: string\n fetchImpl?: typeof fetch\n now?: () => number\n /** Observability hook: fired after every refresh round. */\n onRefresh?: (status: CatalogSnapshot, lastError: string) => void\n /**\n * Fired when the exposed model set actually changes. DSH's picker caches\n * one `modelCatalog()` read per Host generation and only re-reads it on\n * `llm/adapters-updated`, so a pure in-memory change (hidden models, a\n * refresh that added or dropped models) is invisible without this.\n */\n onInvalidate?: () => void\n /** Delay between startup retries while the live catalog is empty (default 15s). */\n startupRetryMs?: number\n}\n\nconst FETCH_TIMEOUT_MS = 30_000\n\n/** Live model directory with refresh loop. All state in-memory; only the gateway snapshot persists. */\nexport class ModelCatalog {\n #entries: Map<string, MagpieModelEntry> = new Map()\n /**\n * Allowlist of model ids the picker offers. `null` = inherit the whole\n * directory (the default, and what a fresh install gets); a Set (possibly\n * empty) = exactly these ids. Mirrors DSH's own Models settings, where a\n * provider's `models` array replaces the catalog instead of filtering it.\n */\n #enabled: Set<string> | null = null\n #updatedAt = 0\n #lastError = ''\n #refreshSeconds: number\n #cachePath?: string\n #baseUrl: string\n #apiKey: string\n #fetch: typeof fetch\n #now: () => number\n #timer: NodeJS.Timeout | null = null\n #stopped = false\n #onRefresh?: (status: CatalogSnapshot, lastError: string) => void\n #onInvalidate?: () => void\n #startupRetryMs: number\n /**\n * Last announced exposed set. The picker caches its catalog read, so an\n * invalidation is only worth a Host event when the exposed ids really\n * moved \u2014 otherwise the refresh loop would emit every 5 minutes.\n */\n #announced = ''\n\n constructor(options: CatalogOptions = {}) {\n this.#refreshSeconds = options.refreshSeconds ?? 300\n this.#cachePath = options.cachePath\n this.#baseUrl = (options.baseUrl ?? '').replace(/\\/+$/, '')\n this.#apiKey = options.apiKey ?? ''\n this.#fetch = options.fetchImpl ?? fetch\n this.#now = options.now ?? Date.now\n this.#onRefresh = options.onRefresh\n this.#onInvalidate = options.onInvalidate\n this.#startupRetryMs = options.startupRetryMs ?? 15_000\n }\n\n /**\n * Start the refresh loop: immediate fetch, fast retries while the live\n * catalog is still empty (the first fetch often races the machine's\n * network coming up), then the normal cadence.\n */\n async start(): Promise<void> {\n await this.refreshOnce()\n let attempts = 0\n while (this.#entries.size === 0 && attempts < 4 && !this.#stopped) {\n attempts += 1\n await new Promise((resolve) => setTimeout(resolve, this.#startupRetryMs))\n if (this.#stopped) return\n await this.refreshOnce()\n }\n if (this.#stopped) return\n this.#timer = setInterval(() => {\n void this.refreshOnce()\n }, this.#refreshSeconds * 1000)\n this.#timer.unref?.()\n }\n\n stop(): void {\n this.#stopped = true\n if (this.#timer) {\n clearInterval(this.#timer)\n this.#timer = null\n }\n }\n\n async refreshOnce(): Promise<void> {\n await this.refreshModels()\n if (this.#onRefresh) {\n try {\n this.#onRefresh(this.snapshot(), this.#lastError)\n } catch {\n // observers must never break the refresh loop\n }\n }\n // A refresh can add or drop models: tell the picker to re-read.\n this.#announce()\n }\n\n /**\n * Announce the exposed set when it changed.\n *\n * DSH's browser-side model directory caches one `modelCatalog()` read per\n * Host generation and only re-reads it on `llm/adapters-updated`, so\n * in-memory catalog mutations (hidden models, a refresh that moved the\n * list) are otherwise invisible until restart. Firing the event on every\n * refresh would also work but wakes the whole picker every 5 minutes, so\n * the exposed ids are fingerprinted and only a real change is announced.\n */\n #announce(): void {\n const fingerprint = this.#fingerprint()\n if (fingerprint === this.#announced) return\n this.#announced = fingerprint\n if (!this.#onInvalidate) return\n try {\n this.#onInvalidate()\n } catch {\n // observers must never break the refresh loop\n }\n }\n\n /** Stable fingerprint of the exposed set (ids + their capabilities). */\n #fingerprint(): string {\n const rows = this.list().map((id) => {\n const entry = this.#entryFor(id)\n return [\n id,\n entry?.displayName ?? '',\n entry?.image === true ? 'img' : '-',\n entry?.reasoning === true ? 'think' : '-',\n (entry?.efforts ?? []).join(','),\n String(entry?.contextWindow ?? 0),\n String(entry?.maxTokens ?? 0),\n ].join('|')\n })\n return rows.join('\\n')\n }\n\n /** Whether a gateway API root is configured (empty baseUrl = not configured). */\n get configured(): boolean {\n return this.#baseUrl !== ''\n }\n\n /**\n * Auth header for every catalog fetch. The gateway guards `GET /models` with\n * the same Bearer key as inference, so omitting it is answered 401 \u2014 which\n * the refresh loop then reports as a \"catalog issue\" while the picker keeps\n * serving whatever it already had.\n */\n #authHeaders(): Record<string, string> {\n return this.#apiKey === '' ? {} : { authorization: `Bearer ${this.#apiKey}` }\n }\n\n /**\n * Adopt a directory the settings page just read from the gateway.\n *\n * The fetch dialog asks the endpoint the form shows and gets the freshest\n * answer the session will see; the background refresh loop may be minutes\n * behind, or silently failing on a 401. Without this, a model the gateway has\n * dropped stays in the local directory \u2014 and therefore in the picker and the\n * settings list \u2014 until the next *successful* refresh, which may never come.\n *\n * Whole-set replacement, never a merge: the reply is the gateway's entire\n * catalog, so anything it no longer lists is gone. Empty input is refused\n * rather than treated as \"nothing served\", because a bad endpoint or a\n * transient failure must not blank the picker.\n * @param entries - the decoded gateway directory just fetched.\n * @returns whether the directory was adopted.\n */\n adoptDirectory(entries: Map<string, MagpieModelEntry>): boolean {\n if (entries.size === 0) return false\n this.#entries = new Map(entries)\n this.#updatedAt = this.#now()\n this.#lastError = ''\n if (this.#cachePath) void saveModelsCache(this.#cachePath, entries, this.#now()).catch(() => {})\n this.#announce()\n return true\n }\n\n async refreshModels(): Promise<void> {\n if (!this.configured) {\n this.#lastError = 'magpie gateway API URL or key is not configured \u2014 set both on the Magpie settings page'\n return\n }\n try {\n const entries = await fetchMagpieModels(this.#baseUrl, this.#fetch, { headers: this.#authHeaders() })\n this.#entries = entries\n this.#updatedAt = this.#now()\n this.#lastError = ''\n if (this.#cachePath) await saveModelsCache(this.#cachePath, entries, this.#now()).catch(() => {})\n } catch (err) {\n // Network failure with a cached copy is not fatal: load the cache.\n if (this.#cachePath && this.#entries.size === 0) {\n const cached = await loadModelsCache(this.#cachePath).catch(() => null)\n if (cached && cached.size > 0) {\n this.#entries = cached\n this.#updatedAt = this.#updatedAt === 0 ? this.#now() : this.#updatedAt\n return\n }\n }\n this.#lastError = err instanceof Error ? err.message : String(err)\n }\n }\n\n getEntry(model: string): MagpieModelEntry | undefined {\n return this.#entries.get(model)\n }\n\n /**\n * Replace the settings-page allowlist (`null` = inherit the whole directory).\n * Announces: the exposed set changes, and DSH's picker only re-reads it on\n * `llm/adapters-updated`.\n * @param ids - the allowed model ids, or `null` to inherit.\n */\n setEnabled(ids: readonly string[] | null): void {\n const next = ids === null ? null : new Set(ids)\n if (this.#sameSet(next)) return\n this.#enabled = next\n this.#announce()\n }\n\n /** The allowlist as stored: `null` when inheriting. */\n enabled(): string[] | null {\n return this.#enabled === null ? null : [...this.#enabled]\n }\n\n #sameSet(next: Set<string> | null): boolean {\n const current = this.#enabled\n if (next === null || current === null) return next === current\n return next.size === current.size && [...next].every((id) => current.has(id))\n }\n\n /** Whether the picker offers one id under the current allowlist. */\n #offers(model: string): boolean {\n return this.#enabled === null || this.#enabled.has(model)\n }\n\n /**\n * Where one model id comes from right now: the live directory, the built-in\n * snapshot, or nothing. The settings page labels its rows with this so a\n * model the gateway stopped listing is not mistaken for one it still serves.\n * @param model - the id to classify.\n * @returns `'gateway'`, `'static'`, or `'none'`.\n */\n sourceFor(model: string): 'gateway' | 'static' | 'none' {\n if (this.#entries.has(model)) return 'gateway'\n if (this.configured && staticMagpieModels.some((entry) => entry.id === model)) return 'static'\n return 'none'\n }\n\n isEnabled(model: string): boolean {\n return this.#offers(model)\n }\n\n /**\n * Point the refresh loop at another API root or credential (settings page\n * change).\n *\n * The key is part of the identity here, not just the URL: the gateway's\n * `GET /models` is key-guarded, so a key-only edit \u2014 the common case of\n * pasting a fresh key \u2014 must re-read the directory too. When only the key\n * moves the live entries are kept and merely re-fetched; when the root\n * moves they are dropped, because they describe a different gateway.\n * @param baseUrl - the versioned API root ('' = unconfigured).\n * @param apiKey - the gateway credential sent as a Bearer header.\n */\n setEndpoint(baseUrl: string, apiKey: string): void {\n const root = baseUrl.replace(/\\/+$/, '')\n const key = apiKey\n if (root === this.#baseUrl && key === this.#apiKey) return\n const rootChanged = root !== this.#baseUrl\n this.#baseUrl = root\n this.#apiKey = key\n if (rootChanged) {\n // Drop entries from the previous root: the picker must not serve a\n // stale directory, and clearing unconfigured state must empty it.\n this.#entries = new Map()\n this.#updatedAt = 0\n }\n this.#lastError = root === '' ? 'magpie gateway API URL or key is not configured \u2014 set both on the Magpie settings page' : ''\n // The picker must not keep serving the previous endpoint's directory.\n this.#announce()\n }\n\n /** Point the refresh loop at another API root (keeps the current key). */\n setBaseUrl(baseUrl: string): void {\n this.setEndpoint(baseUrl, this.#apiKey)\n }\n\n get baseUrl(): string {\n return this.#baseUrl\n }\n\n get apiKey(): string {\n return this.#apiKey\n }\n\n decision(model: string): { allowed: boolean; source: string; known: boolean } {\n if (!this.configured) return { allowed: false, source: 'unconfigured', known: false }\n if (!this.#offers(model)) return { allowed: false, source: 'not_enabled_by_settings', known: true }\n if (this.#entries.has(model)) return { allowed: true, source: 'gateway', known: true }\n const fallback = staticMagpieModels.find((entry) => entry.id === model)\n if (fallback) return { allowed: true, source: 'static_verified', known: false }\n return { allowed: false, source: this.#entries.size === 0 ? 'gateway_pending' : 'gateway_unknown', known: false }\n }\n\n /** Entry lookup: live map first, static snapshot while configured (never unconfigured). */\n #entryFor(model: string): MagpieModelEntry | undefined {\n if (!this.configured) return undefined\n return this.#entries.get(model) ?? staticMagpieModels.find((candidate) => candidate.id === model)\n }\n\n /**\n * Reasoning capability for one model id (DSH `resolveModel().reasoning`\n * + pi-ai `thinkingLevelMap` source of truth). Ladder-less thinking models\n * (reasoning without an effort list) think with upstream defaults \u2014 see\n * `thinks()` \u2014 and expose no picker.\n */\n reasoningFor(model: string): { efforts: ReasoningEffortChoice[]; defaultEffort: string } | undefined {\n const entry = this.#entryFor(model)\n const efforts = entry?.efforts\n if (!entry?.reasoning) return undefined\n if (efforts !== undefined && efforts.length > 0) {\n const mid = efforts[Math.floor(efforts.length / 2)] ?? 'medium'\n return { efforts: effortsFor(efforts), defaultEffort: efforts.includes('medium') ? 'medium' : mid }\n }\n return undefined\n }\n\n /** Whether the wire model may think (pi-ai `reasoning: true`). */\n thinks(model: string): boolean {\n const entry = this.#entryFor(model)\n return entry?.reasoning ?? false\n }\n\n /** Whether the model accepts image input. */\n supportsImage(model: string): boolean {\n const entry = this.#entryFor(model)\n return entry?.image ?? false\n }\n\n /** Whether one effort id is selectable for the model. */\n supportsEffort(model: string, effort: string): boolean {\n const entry = this.#entryFor(model)\n if (!entry?.reasoning) return false\n if (!entry.efforts || entry.efforts.length === 0) return true // ladder-less: upstream accepts, picker hidden\n return entry.efforts.includes(effort)\n }\n\n requiresResponsesApi(model: string): boolean {\n const entry = this.#entryFor(model)\n if (!entry) return /muse-spark|codex\\/|grok/i.test(model)\n return requiresResponsesApiEntry(entry.nativeEndpoints)\n }\n\n contextWindowFor(model: string): number {\n return this.#entryFor(model)?.contextWindow ?? 262144\n }\n\n maxTokensFor(model: string): number {\n return this.#entryFor(model)?.maxTokens ?? 32768\n }\n\n /**\n * Every id the directory knows right now, ignoring the allowlist: the live\n * gateway list, else the cached copy, else the built-in snapshot.\n *\n * This is what the settings page renders (each row then says whether the\n * allowlist offers it) and what the one-time migration intersects against.\n */\n directory(): string[] {\n if (!this.configured) return []\n if (this.#entries.size === 0) return staticMagpieModels.map((entry) => entry.id)\n return [...this.#entries.keys()].sort()\n }\n\n /** ids exposed to DSH: the directory filtered by the allowlist (empty while unconfigured). */\n list(): string[] {\n if (!this.configured) return []\n if (this.#entries.size === 0) return staticMagpieModels.map((entry) => entry.id).filter((id) => this.#offers(id))\n return [...this.#entries.keys()].filter((id) => this.#offers(id)).sort()\n }\n\n /** Catalog health snapshot (pending/ready/stale + counts). */\n snapshot(): CatalogSnapshot {\n const age = this.#updatedAt === 0 ? Infinity : this.#now() - this.#updatedAt\n const stale = this.#updatedAt !== 0 && age > 10 * 60 * 1000\n return {\n status: this.#updatedAt === 0 ? 'pending' : stale ? 'stale' : 'ready',\n total: this.#entries.size,\n exposed: this.list().length,\n ...(this.#updatedAt !== 0 ? { lastRefresh: new Date(this.#updatedAt).toISOString() } : {}),\n }\n }\n\n get lastError(): string {\n return this.#lastError\n }\n}\n\nasync function withTimeout(\n run: (signal: AbortSignal) => Promise<Response>,\n timeoutMs = FETCH_TIMEOUT_MS,\n): Promise<Response> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n return await run(controller.signal)\n } catch (error) {\n if (controller.signal.aborted) throw new Error(`models endpoint timed out after ${timeoutMs}ms`)\n throw error\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Fetch the live gateway model list.\n *\n * `baseUrl` is the versioned API root (`http://127.0.0.1:3425/v1`) exactly as the user\n * configured it; only the resource is appended. Never synthesize a version\n * here \u2014 a gateway on `/v2` would otherwise be asked for `/v2/v1/models`.\n */\nexport async function fetchMagpieModels(\n baseUrl: string,\n fetchImpl: typeof fetch,\n options: { timeoutMs?: number; headers?: Record<string, string> } = {},\n): Promise<Map<string, MagpieModelEntry>> {\n const response = await withTimeout(\n (signal) =>\n fetchImpl(`${baseUrl.replace(/\\/+$/, '')}/models`, {\n headers: { accept: 'application/json', ...(options.headers ?? {}) },\n signal,\n }),\n options.timeoutMs ?? FETCH_TIMEOUT_MS,\n )\n if (!response.ok) throw new Error(`models endpoint returned HTTP ${response.status}`)\n const payload = (await response.json()) as unknown\n const models = decodeMagpieModels(payload)\n if (models.size === 0) throw new Error('models endpoint returned an empty list')\n return models\n}\n\n/** Cache schema v3: labels now use display_name plus parsed/id-derived group. */\nconst MODELS_CACHE_VERSION = 3\n\ninterface ModelsCache {\n version: number\n updatedAt: number\n entries: MagpieModelEntry[]\n}\n\nasync function saveModelsCache(path: string, entries: Map<string, MagpieModelEntry>, now: number): Promise<void> {\n const cache: ModelsCache = { version: MODELS_CACHE_VERSION, updatedAt: now, entries: [...entries.values()] }\n // Same atomic-replace discipline as SettingsStore: random-suffix sibling,\n // rename over the target, no `rm` window. The cache is reproducible, so a\n // lost write is harmless \u2014 but a half-written file is not worth risking.\n const tmp = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n await mkdir(dirname(path), { recursive: true })\n try {\n await writeFile(tmp, JSON.stringify(cache), { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n await rename(tmp, path)\n } finally {\n await rm(tmp, { force: true }).catch(() => {})\n }\n}\n\nasync function loadModelsCache(path: string): Promise<Map<string, MagpieModelEntry>> {\n const raw = JSON.parse(await readFile(path, 'utf8')) as ModelsCache\n if (Date.now() - raw.updatedAt > 7 * 24 * 60 * 60 * 1000) {\n throw new Error('gateway cache too old')\n }\n const legacy = raw.version !== MODELS_CACHE_VERSION\n return new Map(raw.entries.map((entry) => {\n // A legacy cache has no raw gateway fields to recompute the new label\n // from. Preserve ids and capabilities, and use id as the label until a\n // successful refresh replaces them. This avoids falling back to the stale\n // compile-time snapshot offline.\n const relabeled = legacy ? { ...entry, displayName: entry.id } : entry\n return [entry.id, relabeled]\n }))\n}\n\n/** Default cache location next to the plugin data dir (index.ts convention). */\nexport function defaultCachePath(dataDir: string): string {\n return join(dataDir, 'magpie-models.json')\n}\n", "/**\n * Harness-home path helpers.\n *\n * Mirrors `@deepseek-ai/dsh-home-paths` closely enough to keep this plugin\n * independent of that package (the repo's `node_modules` carries no\n * `@deepseek-ai/*`, so importing it would break offline `typecheck`). The\n * resolution order is the documented one: an explicit path wins, then\n * `$DSH_HOME`, then `~/.dsh`; a blank override is treated as unset so a stray\n * empty variable never resolves the home to the current working directory.\n *\n * `legacyDataDir()` is deliberately NOT derived from the resolved home: the\n * 0.4.x line computed its state dir as `join(homedir(), '.dsh-magpie-connect')`\n * and never looked at `DSH_HOME`. Reading the old file through the new helper\n * would miss it for anyone who sets `DSH_HOME`, which is exactly the user who\n * must not silently lose their configuration.\n */\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\n/** Resolve the Harness home: explicit override > $DSH_HOME > ~/.dsh. */\nexport function resolveDshHome(configured?: string, env: NodeJS.ProcessEnv = process.env): string {\n if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured)\n const fromEnv = env.DSH_HOME\n if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return resolve(fromEnv)\n return join(homedir(), '.dsh')\n}\n\n/** Join path segments onto the resolved Harness home. */\nexport function dshHomePath(...segments: string[]): string {\n return join(resolveDshHome(), ...segments)\n}\n\n/**\n * State directory used by dsh-magpie-connect 0.4.x and earlier.\n *\n * `homedir`-based on purpose \u2014 see the module note. Used only to read/write the\n * pre-0.5 settings file during the one-time, save-triggered migration.\n */\nexport function legacyDataDir(): string {\n return join(homedir(), '.dsh-magpie-connect')\n}\n", "import { createProvider, type Api, type Context, type Model } from '@earendil-works/pi-ai'\nimport * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions'\nimport * as openaiResponses from '@earendil-works/pi-ai/api/openai-responses'\n\nimport {\n ModelCatalog,\n modelApiForEntry,\n thinkingLevelMapFor,\n} from './catalog.ts'\nimport { toStreamChunks, type HarnessChunk, type PiEvent } from './events.ts'\nimport {\n contentHasImage,\n toPiContext,\n toPiContextWithImages,\n type AttachmentStore,\n type HarnessGenerateOptions,\n} from './messages.ts'\nimport { withStallTimeout } from './watchdog.ts'\n\n/**\n * Magpie gateway adapter: registers as a DSH LlmAdapter and streams\n * directly from the configured API root (e.g. `\u2026/v1`) \u2014 chat completions for most models plus the\n * Responses API for responses-only models (Muse Spark / Codex / Grok lanes).\n *\n * Adapter contract: dsh-llm LlmAdapter (providerInfo/providerRetryPolicy/\n * imageRequestPricing/listModels/resolveModel/prepareCall/stream) \u2014\n * structural, no host import.\n *\n * Images resolve through the harness attachment service; thinking levels come\n * from the gateway catalog and forward verbatim (including the `none`/`ultra`\n * extensions pi-ai does not model).\n */\n\n/** Structural pi-ai provider surface the adapter consumes. */\nexport interface PiProviderLike {\n stream(model: unknown, context: unknown, options: unknown): AsyncIterable<PiEvent>\n streamSimple(model: unknown, context: unknown, options: unknown): AsyncIterable<PiEvent>\n}\n\n/** Live endpoint read per request so the settings page applies without restart. */\nexport interface RuntimeEndpoint {\n /** Versioned API root, e.g. `http://127.0.0.1:3425/v1` (no trailing slash). */\n baseUrl(): string\n /** Bearer key sent to the gateway. */\n apiKey(): string\n}\n\nexport const PROVIDER_ID = 'dsh-magpie-connect'\n\n/** Default picker label for the default route id. */\nexport const DEFAULT_DISPLAY_NAME = 'Magpie'\n\nexport interface MagpieModelInfo {\n id: string\n name: string\n contextWindow: number\n maxTokens: number\n}\n\nexport interface CatalogLike {\n list(): string[]\n decision(model: string): { allowed: boolean; source: string; known: boolean }\n getEntry?(model: string): { nativeEndpoints: string[]; displayName?: string } | undefined\n reasoningFor?(model: string): { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort: string } | undefined\n thinks?(model: string): boolean\n supportsImage?(model: string): boolean\n supportsEffort?(model: string, effort: string): boolean\n requiresResponsesApi?(model: string): boolean\n contextWindowFor?(model: string): number\n maxTokensFor?(model: string): number\n}\n\nconst DEFAULT_CONTEXT_WINDOW = 262144\nconst DEFAULT_MAX_TOKENS = 32768\n\n/** Match Magpie's DSH defaults: reserve reply space without exhausting the compaction budget. */\nfunction requestDefaultMaxTokens(contextWindow: number, outputLimit: number): number {\n const room = Math.max(1, Math.floor(contextWindow / 4), Math.floor(contextWindow / 2) - 65536)\n return Math.min(outputLimit, room)\n}\n\n/** Credential sent to the Magpie gateway (it needs none; pi-ai requires a value). */\nconst DEFAULT_API_KEY = 'not-needed'\n\n/** Connection-setup retries (429/5xx with backoff, interruptible by abort). */\nexport const DEFAULT_MAX_RETRIES = 2\n/** Overall SDK request cap (replaces the OpenAI SDK 10 min default). */\nexport const DEFAULT_TIMEOUT_MS = 300_000\n/** Max wait for the first upstream event (queueing happens here). */\nexport const DEFAULT_FIRST_EVENT_TIMEOUT_MS = 90_000\n/** Max silence between upstream events once streaming. */\nexport const DEFAULT_IDLE_TIMEOUT_MS = 60_000\n\nconst STRENGTH_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const\n\n/**\n * The attribution header dsh-llm's own adapters send on every provider\n * request (`attributionHeaders()`, its APP_IDENTITY rendered as\n * `product/version (+url)`). Sent verbatim: a newer host's version string\n * changes nothing for the gateway, which matches the `deepseek-harness`\n * prefix alone.\n */\nconst DSH_USER_AGENT = 'deepseek-harness/0.2.2-rc.1 (+https://github.com/deepseek-ai/deepseek-harness)'\n\n/**\n * Plan the wire `reasoning_effort` for one request. Returns the effort to\n * send via `provider.stream`, or undefined to omit the field (gateway\n * default applies).\n *\n * - `off` aliases `none` (explicitly disable thinking).\n * - `none` sends only when the model lists it; otherwise omitted.\n * - `ultra` sends when listed; otherwise degrades to the highest listed\n * strength level (`max` \u2192 \u2026 \u2192 `minimal`).\n * - Known strength levels send verbatim when listed or when the model thinks\n * without a ladder (gateway decides); otherwise clamped up-then-down to\n * the nearest listed level so a stale remembered value never 400s.\n * - Unknown values and non-reasoning models omit.\n */\nexport function planReasoningEffort(\n requested: unknown,\n model: string,\n catalog: Pick<CatalogLike, 'thinks' | 'supportsEffort' | 'reasoningFor'>,\n): string | undefined {\n if (typeof requested !== 'string') return undefined\n const level = requested.trim().toLowerCase()\n if (level === '') return undefined\n const thinks = catalog.thinks?.(model) ?? false\n if (!thinks) return undefined\n const normalized = level === 'off' ? 'none' : level\n const supports = (effort: string): boolean => catalog.supportsEffort?.(model, effort) ?? false\n const ladder = catalog.reasoningFor?.(model)?.efforts.map((effort) => effort.id)\n const ladderLess = ladder === undefined\n\n if (normalized === 'none') {\n return supports('none') ? 'none' : undefined\n }\n if (!(STRENGTH_ORDER as readonly string[]).includes(normalized)) return undefined\n if (supports(normalized) || ladderLess) return normalized\n // Clamp a stale/foreign level up-then-down (pi-ai clamp order).\n const order = STRENGTH_ORDER as readonly string[]\n const index = order.indexOf(normalized as (typeof STRENGTH_ORDER)[number])\n if (index !== -1) {\n for (let i = index + 1; i < order.length; i++) {\n const candidate = order[i] as string\n if (supports(candidate)) return candidate\n }\n for (let i = index - 1; i >= 0; i--) {\n const candidate = order[i] as string\n if (supports(candidate)) return candidate\n }\n }\n return undefined\n}\n\nfunction toPiModel(\n providerId: string,\n baseUrl: string,\n id: string,\n catalog: CatalogLike,\n contextWindow = DEFAULT_CONTEXT_WINDOW,\n maxTokens = DEFAULT_MAX_TOKENS,\n): Model<Api> {\n const endpoints = catalog.getEntry?.(id)?.nativeEndpoints ?? []\n const api = modelApiForEntry(endpoints)\n const entryThinks = catalog.thinks?.(id) ?? api === 'openai-responses'\n const ladder = catalog.reasoningFor?.(id)\n const ladderIds = ladder?.efforts.map((effort) => effort.id)\n const resolvedContext = catalog.contextWindowFor?.(id) ?? contextWindow\n const resolvedMax = catalog.maxTokensFor?.(id) ?? maxTokens\n if (api === 'openai-responses') {\n return {\n id,\n name: id,\n api,\n provider: providerId,\n baseUrl,\n reasoning: true,\n thinkingLevelMap: thinkingLevelMapFor(ladderIds),\n input: catalog.supportsImage?.(id) ?? true ? ['text', 'image'] : ['text'],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: resolvedContext,\n maxTokens: resolvedMax,\n }\n }\n const wire: Model<Api> = {\n id,\n name: id,\n api,\n provider: providerId,\n baseUrl,\n reasoning: entryThinks,\n input: catalog.supportsImage?.(id) ?? false ? ['text', 'image'] : ['text'],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: resolvedContext,\n maxTokens: resolvedMax,\n }\n if (entryThinks) wire.thinkingLevelMap = thinkingLevelMapFor(ladderIds)\n return wire\n}\n\nexport class MagpieAdapter {\n readonly #catalog: CatalogLike\n readonly #provider: PiProviderLike\n readonly #providerId: string\n readonly #displayName: string\n /** Static fallback API root; the live settings page overrides per request. */\n readonly #fallbackBaseUrl: string\n readonly #fallbackApiKey: string\n readonly #runtime?: RuntimeEndpoint\n readonly #maxRetries: number\n readonly #timeoutMs: number\n readonly #firstEventTimeoutMs: number\n readonly #idleTimeoutMs: number\n readonly #resolveAttachments?: () => AttachmentStore | undefined\n\n constructor(\n catalog: CatalogLike,\n options: {\n magpieBaseUrl?: string\n baseUrl?: string\n providerOverride?: unknown\n /** Route id registered into DSH (model `provider` field + pi-ai provider tag). */\n providerId?: string\n /** Display name reported via providerInfo (model picker grouping label). */\n displayName?: string\n /** Gateway credential (the gateway needs none). */\n apiKey?: string\n /**\n * Live endpoint read per request (settings page). Falls back to the\n * static `magpieBaseUrl`/`apiKey` options when absent.\n */\n runtime?: RuntimeEndpoint\n /** Connection-setup retries for 429/5xx (default 2). */\n maxRetries?: number\n /** Overall SDK request cap in ms (default 300000). */\n timeoutMs?: number\n /** Stall watchdog: max wait for the first upstream event in ms (default 90000; <=0 disables). */\n firstEventTimeoutMs?: number\n /** Stall watchdog: max silence between upstream events in ms (default 60000; <=0 disables). */\n idleTimeoutMs?: number\n /** Harness attachment service for image bytes (wired in index.ts). */\n resolveAttachments?: () => AttachmentStore | undefined\n } = {},\n ) {\n this.#catalog = catalog\n this.#providerId = options.providerId ?? PROVIDER_ID\n this.#displayName = options.displayName ?? (options.providerId ?? DEFAULT_DISPLAY_NAME)\n // The configured value is already the versioned API root (`\u2026/v1`), which is\n // exactly what pi-ai's `baseUrl` expects: it appends `/chat/completions`\n // and `/responses` itself. Synthesizing a version here would double it and\n // would hard-code `/v1` against a gateway that later moves to `/v2`.\n this.#fallbackBaseUrl = (options.magpieBaseUrl ?? options.baseUrl ?? '').replace(/\\/+$/, '')\n this.#fallbackApiKey = options.apiKey ?? DEFAULT_API_KEY\n this.#runtime = options.runtime\n this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n this.#firstEventTimeoutMs = options.firstEventTimeoutMs ?? DEFAULT_FIRST_EVENT_TIMEOUT_MS\n this.#idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS\n this.#resolveAttachments = options.resolveAttachments\n if (options.providerOverride !== undefined) {\n this.#provider = options.providerOverride as never\n return\n }\n this.#provider = createProvider<Api>({\n id: this.#providerId,\n name: this.#displayName,\n baseUrl: this.#fallbackBaseUrl,\n auth: {\n apiKey: {\n name: 'Magpie gateway',\n resolve: async () => ({ auth: { apiKey: this.#runtime?.apiKey() ?? this.#fallbackApiKey } }),\n },\n },\n models: [],\n // Mixed-API provider: pi-ai dispatches on `model.api`, so completions\n // models ride /v1/chat/completions while responses-only models ride\n // /v1/responses through the same provider instance.\n api: {\n 'openai-completions': openaiCompletions,\n 'openai-responses': openaiResponses,\n },\n }) as unknown as PiProviderLike\n }\n\n providerInfo(provider: string): { id: string; name: string } {\n return { id: provider, name: this.#displayName }\n }\n\n /**\n * dsh-llm calls this unconditionally at registration.\n * undefined = the host default retry policy.\n */\n providerRetryPolicy(_provider: string): undefined {\n return undefined\n }\n\n /**\n * Per-route visual-token pricing for the token meter (`/compact` calls\n * this unconditionally via `ctx.llm.imageRequestPricing`). The gateway\n * charges no separate visual tokens (pi-ai cost is 0), so like the host\n * base-class default we declare no per-route pricing.\n */\n imageRequestPricing(_provider: string, _model: string): undefined {\n return undefined\n }\n\n /**\n * Picker label: the catalog's `<group>/<display_name>` label\n * (e.g. \"Codex/GPT-6-Luna\"); the group comes from `magpie_label` or falls\n * back to the capitalized first id segment. The id itself stays the route id\n * (`codex/gpt-6-luna`) for requests and session history.\n */\n #labelFor(id: string): string {\n const label = this.#catalog.getEntry?.(id)?.displayName\n return typeof label === 'string' && label.trim() !== '' ? label : id\n }\n\n /** Advisory catalog for the DSH model picker (deduped; dsh-llm rejects duplicates). */\n listModels(provider: string): Array<{ provider: string; id: string; name: string; inputModalities: string[] }> {\n const seen = new Set<string>()\n const models: Array<{ provider: string; id: string; name: string; inputModalities: string[] }> = []\n for (const id of this.#catalog.list()) {\n if (seen.has(id)) continue\n seen.add(id)\n const image = this.#catalog.supportsImage?.(id) ?? false\n models.push({ provider, id, name: this.#labelFor(id), inputModalities: image ? ['text', 'image'] : ['text'] })\n }\n return models\n }\n\n resolveModel(\n provider: string,\n model: string,\n ): {\n provider: string\n id: string\n name: string\n inputModalities: string[]\n context: { contextWindow: number }\n defaultMaxTokens: number\n reasoning?: {\n efforts: ReadonlyArray<{ id: string; name: string; description?: string }>\n defaultEffort?: string\n }\n } {\n // DSH capability seam: exposing efforts lights up the session model\n // selector's reasoning picker; ids flow back as\n // GenerateOptions.reasoningEffort and are forwarded verbatim by\n // planReasoningEffort (gateway extensions `none`/`ultra` included).\n // No `off` entry: omission keeps the gateway default (= defaultEffort).\n const image = this.#catalog.supportsImage?.(model) ?? this.#catalog.requiresResponsesApi?.(model) ?? false\n const ladder = this.#catalog.reasoningFor?.(model)\n const contextWindow = this.#catalog.contextWindowFor?.(model) ?? DEFAULT_CONTEXT_WINDOW\n return {\n provider,\n id: model,\n name: this.#labelFor(model),\n inputModalities: image ? ['text', 'image'] : ['text'],\n context: { contextWindow },\n defaultMaxTokens: requestDefaultMaxTokens(contextWindow, this.#catalog.maxTokensFor?.(model) ?? DEFAULT_MAX_TOKENS),\n ...(ladder !== undefined ? { reasoning: ladder } : {}),\n }\n }\n\n async prepareCall(\n provider: string,\n model: string,\n _signal?: AbortSignal,\n ): Promise<{\n model: ReturnType<MagpieAdapter['resolveModel']>\n stream: (options: HarnessGenerateOptions) => AsyncGenerator<HarnessChunk>\n }> {\n return {\n model: this.resolveModel(provider, model),\n stream: (options) => this.stream(options),\n }\n }\n\n /**\n * Fail fast when no gateway API URL is configured (picker stays empty too).\n * @returns the versioned API root, trailing slash stripped.\n */\n #requireBaseUrl(): string {\n const raw = this.#runtime?.baseUrl() ?? this.#fallbackBaseUrl\n const baseUrl = raw.replace(/\\/+$/, '')\n if (baseUrl === '') {\n throw new Error('dsh-magpie-connect: Magpie gateway API URL or key is not configured \u2014 open Settings \u2192 Magpie and fill in both')\n }\n return baseUrl\n }\n\n /** Effective bearer key for this request. */\n #wireApiKey(): string {\n return this.#runtime?.apiKey() ?? this.#fallbackApiKey\n }\n\n /**\n * Stream one chat turn from the Magpie gateway: a single pi-ai stream,\n * translated to harness chunks verbatim. Upstream failures (rate limit,\n * auth, timeout, transport) arrive as classified finish reasons, and\n * turn-level retries stay owned by DSH.\n *\n * A stall watchdog races every upstream event against a timer: on expiry\n * the upstream is aborted and the turn ends fast with a TIMEOUT error\n * instead of hanging to the SDK/harness timeout.\n */\n async *stream(options: HarnessGenerateOptions): AsyncGenerator<HarnessChunk> {\n const baseUrl = this.#requireBaseUrl()\n const endpoints = this.#catalog.getEntry?.(options.model)?.nativeEndpoints ?? []\n const hasImage = contentHasImage(options.messages)\n if (hasImage && !(this.#catalog.supportsImage?.(options.model) ?? false)) {\n throw new Error(`dsh-magpie-connect: model \"${options.model}\" does not accept image input`)\n }\n const context = hasImage\n ? await this.#imageContext(options, endpoints)\n : toPiContext(options, endpoints)\n const model = toPiModel(this.#providerId, baseUrl, options.model, this.#catalog)\n // Linked controller: the watchdog aborts the upstream on stall, while a\n // harness abort (user stop / host timeout) still propagates through.\n const controller = new AbortController()\n const harnessSignal = options.signal\n const onHarnessAbort = (): void => controller.abort()\n if (harnessSignal) {\n if (harnessSignal.aborted) controller.abort()\n else harnessSignal.addEventListener('abort', onHarnessAbort, { once: true })\n }\n try {\n const events = withStallTimeout(\n this.#eventsFor(options, context, model, controller.signal) as AsyncIterable<PiEvent>,\n { firstEventTimeoutMs: this.#firstEventTimeoutMs, idleTimeoutMs: this.#idleTimeoutMs },\n { model: options.model, onTimeout: () => controller.abort() },\n )\n yield* toStreamChunks(events, model.contextWindow)\n } finally {\n harnessSignal?.removeEventListener('abort', onHarnessAbort)\n }\n }\n\n async #imageContext(options: HarnessGenerateOptions, endpoints: readonly string[]): Promise<ReturnType<typeof toPiContext>> {\n const attachments = this.#resolveAttachments?.()\n if (!attachments) {\n throw new Error('dsh-magpie-connect: image input requires the attachment service')\n }\n return toPiContextWithImages(options, attachments, endpoints)\n }\n\n #eventsFor(\n options: HarnessGenerateOptions,\n context: ReturnType<typeof toPiContext>,\n model: ReturnType<typeof toPiModel>,\n signal: AbortSignal,\n ): unknown {\n // Single dispatch through `provider.stream` with our own clamped effort:\n // gateway extensions (`none`/`ultra`) ride verbatim, known levels ride\n // the ladder, and omission keeps the gateway default.\n const reasoningEffort = planReasoningEffort(options.reasoningEffort, options.model, this.#catalog)\n // Attribution rides dsh-llm's own shape (`user-agent`:\n // `deepseek-harness/<version> (+url)`, the value `attributionHeaders()`\n // sends on the official adapters). Magpie names a client by its\n // User-Agent alone \u2014 the gateway key it accepts is anonymous \u2014 so\n // without this the plugin's turns read as the OpenAI SDK's\n // (\"OpenAI/JS 6.26.0\"), and the gateway's DSH-specific views\n // (the `agent == \"dsh\"` ones) never see them as DSH's.\n const sessionId = typeof options.sessionId === 'string' ? options.sessionId : undefined\n return this.#provider.stream(model, context as unknown as Context, {\n apiKey: this.#wireApiKey(),\n signal,\n maxRetries: this.#maxRetries,\n timeoutMs: this.#timeoutMs,\n temperature: options.temperature,\n maxTokens: options.maxTokens ?? requestDefaultMaxTokens(model.contextWindow, model.maxTokens),\n ...(reasoningEffort !== undefined ? { reasoningEffort } : {}),\n headers: {\n 'user-agent': DSH_USER_AGENT,\n // The session id rides the same header Magpie's `/v1/magpie/route`\n // reads (`x-session-id`, one of its recognized session headers): with\n // it the gateway tags each request's routing with the DSH session, so\n // the composer's routing popover can show this session's latest route.\n // Official dsh-llm adapters do the same (`x-deepseek-harness-session-id`,\n // which Magpie also reads; the generic name keeps third-party gateways\n // out of DSH's private namespace).\n ...(sessionId !== undefined ? { 'x-session-id': sessionId } : {}),\n // DSH marks compaction requests with a header, not its prompt\n // (`dshCompacts` in magpie): \"only the mark says so\". The official\n // adapters send it when `purpose` is compaction.\n ...(options.purpose === 'compaction' ? { 'x-deepseek-harness-compact': '1' } : {}),\n },\n })\n }\n\n /** Expose the live catalog snapshot for diagnostics. */\n catalogStatus(): { total: number; exposed: number } {\n const list = this.#catalog.list()\n return { total: list.length, exposed: list.length }\n }\n\n decisionFor(model: string): { allowed: boolean; source: string } {\n const decision = this.#catalog.decision(model)\n return { allowed: decision.allowed, source: decision.source }\n }\n}\n\n/** Build the adapter over a live catalog. */\nexport function createMagpieAdapter(catalog: ModelCatalog): MagpieAdapter {\n return new MagpieAdapter(catalog)\n}\n", "/**\n * pi-ai AssistantMessageEvent -> harness StreamChunks.\n * The chunk stream must end with `usage` then `finish`.\n */\n\nexport type HarnessChunk =\n | { type: 'block-start'; index: number; blockType: 'text' | 'reasoning' | 'tool-call' }\n | { type: 'text-delta'; index: number; text: string }\n | { type: 'block-end'; index: number; block: { type: 'text'; text: string } | { type: 'reasoning'; text: string } | { type: 'tool-call'; id: string; name: string; arguments: string } }\n | { type: 'reasoning-delta'; index: number; text: string }\n | { type: 'tool-call-delta'; index: number; id: string; name?: string; argumentsDelta: string }\n | { type: 'usage'; usage: { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number } }\n | { type: 'finish'; reason: FinishReason; replayState?: unknown }\n\nexport type FinishReason =\n | { kind: 'stop' }\n | { kind: 'max-tokens' }\n | { kind: 'tool-calls' }\n | { kind: 'aborted'; failure: { message: string; code: string } }\n | { kind: 'error'; failure: { message: string; code: string } }\n\n/** pi-ai AssistantMessageEvent vocabulary (subset we consume). */\nexport type PiEvent =\n | { type: 'start'; partial: PiAssistantPartial }\n | { type: 'text_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'text_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'text_end'; contentIndex: number; content: string; partial: PiAssistantPartial }\n | { type: 'thinking_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'thinking_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'thinking_end'; contentIndex: number; content: string; partial: PiAssistantPartial }\n | { type: 'toolcall_start'; contentIndex: number; partial: PiAssistantPartial }\n | { type: 'toolcall_delta'; contentIndex: number; delta: string; partial: PiAssistantPartial }\n | { type: 'toolcall_end'; contentIndex: number; toolCall: { id: string; name: string; arguments: Record<string, unknown> }; partial: PiAssistantPartial }\n | { type: 'done'; message: PiDoneMessage }\n | { type: 'error'; error: PiDoneMessage }\n\nexport interface PiAssistantPartial {\n content: Array<{ type: string; id?: string; name?: string; [key: string]: unknown }>\n [key: string]: unknown\n}\n\n/** pi-ai AssistantMessage content block (done/error messages carry these). */\nexport type PiAssistantBlock = { type: string; [key: string]: unknown }\n\nexport interface PiDoneMessage {\n api: string\n provider: string\n model: string\n responseModel?: string\n responseId?: string\n content: PiAssistantBlock[]\n usage: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens: number }\n stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted'\n errorMessage?: string\n [key: string]: unknown\n}\n\nconst CONTEXT_WINDOW_EXCEEDED = 'CONTEXT_WINDOW_EXCEEDED'\nconst EMPTY_RESPONSE = 'EMPTY_RESPONSE'\nconst QUOTA_EXCEEDED = 'QUOTA_EXCEEDED'\n\nfunction classifyError(text: string): string {\n if (/\\b(?:401|403)\\b/.test(text)) return 'AUTH'\n if (/insufficient|quota|billing/i.test(text)) return QUOTA_EXCEEDED\n if (/\\b429\\b|rate.?limit/i.test(text)) return 'RATE_LIMIT'\n if (/\\b413\\b|payload too large|request body too large/i.test(text)) return 'INVALID_REQUEST'\n if (/\\b400\\b|invalid.?request/i.test(text)) return 'INVALID_REQUEST'\n if (/\\b5\\d\\d\\b/.test(text)) return 'SERVER'\n if (/\\btime(?:d)?\\s*out\\b|timeout/i.test(text)) return 'TIMEOUT'\n if (/\\b(?:network|connection|socket|fetch)\\b|\\bECONN[A-Z]+\\b|terminated|premature close/i.test(text)) return 'TRANSPORT'\n return 'UPSTREAM'\n}\n\nfunction isContextOverflow(message: PiDoneMessage, contextWindow: number): boolean {\n // pi-ai isContextOverflow equivalent: error-free finish whose input usage\n // alone exceeds the resolved window.\n return message.stopReason === 'stop' && message.usage.input > contextWindow\n}\n\n/** Map a pi-ai terminal message to a harness finish reason. */\nfunction mapStopReason(message: PiDoneMessage, contextWindow: number): FinishReason {\n if (isContextOverflow(message, contextWindow) || (message.stopReason === 'error' && message.errorMessage !== undefined && /context/i.test(message.errorMessage) && /exceed|window|length|token/i.test(message.errorMessage))) {\n return {\n kind: 'error',\n failure: {\n message: message.errorMessage ?? `pi-ai detected context overflow for model \"${message.model}\"`,\n code: CONTEXT_WINDOW_EXCEEDED,\n },\n }\n }\n switch (message.stopReason) {\n case 'stop':\n if (message.content.length === 0) {\n return {\n kind: 'error',\n failure: { message: `model \"${message.model}\" returned a completed response with no content`, code: EMPTY_RESPONSE },\n }\n }\n return { kind: 'stop' }\n case 'length':\n return { kind: 'max-tokens' }\n case 'toolUse':\n return { kind: 'tool-calls' }\n case 'aborted':\n return { kind: 'aborted', failure: { message: message.errorMessage ?? 'pi-ai stream aborted', code: 'ABORTED' } }\n case 'error':\n return {\n kind: 'error',\n failure: { message: message.errorMessage ?? 'pi-ai stream error', code: classifyError(message.errorMessage ?? '') },\n }\n }\n}\n\nfunction mapUsage(usage: PiDoneMessage['usage']): Extract<HarnessChunk, { type: 'usage' }>['usage'] {\n return {\n inputTokens: usage.input,\n outputTokens: usage.output,\n ...(usage.cacheRead > 0 ? { cacheReadTokens: usage.cacheRead } : {}),\n ...(usage.cacheWrite > 0 ? { cacheWriteTokens: usage.cacheWrite } : {}),\n }\n}\n\n/**\n * Translate one pi-ai event stream into harness chunks. pi-ai never throws\n * mid-stream: failures arrive as `error` events and become error/aborted\n * finish chunks.\n */\nexport async function* toStreamChunks(events: AsyncIterable<PiEvent>, contextWindow: number): AsyncGenerator<HarnessChunk> {\n const toolIds = new Map<number, { id: string; name: string }>()\n for await (const event of events) {\n switch (event.type) {\n case 'start':\n break\n case 'text_start':\n yield { type: 'block-start', index: event.contentIndex, blockType: 'text' }\n break\n case 'text_delta':\n yield { type: 'text-delta', index: event.contentIndex, text: event.delta }\n break\n case 'text_end':\n yield { type: 'block-end', index: event.contentIndex, block: { type: 'text', text: event.content } }\n break\n case 'thinking_start':\n yield { type: 'block-start', index: event.contentIndex, blockType: 'reasoning' }\n break\n case 'thinking_delta':\n yield { type: 'reasoning-delta', index: event.contentIndex, text: event.delta }\n break\n case 'thinking_end':\n yield { type: 'block-end', index: event.contentIndex, block: { type: 'reasoning', text: event.content } }\n break\n case 'toolcall_start': {\n const partial = event.partial.content[event.contentIndex]\n const id = partial?.type === 'toolCall' ? (partial.id ?? '') : ''\n const name = partial?.type === 'toolCall' ? (partial.name ?? '') : ''\n toolIds.set(event.contentIndex, { id, name })\n yield { type: 'block-start', index: event.contentIndex, blockType: 'tool-call' }\n break\n }\n case 'toolcall_delta': {\n const known = toolIds.get(event.contentIndex)\n yield {\n type: 'tool-call-delta',\n index: event.contentIndex,\n id: known?.id ?? '',\n ...(known?.name !== undefined && known.name.length > 0 ? { name: known.name } : {}),\n argumentsDelta: event.delta,\n }\n break\n }\n case 'toolcall_end':\n yield {\n type: 'block-end',\n index: event.contentIndex,\n block: {\n type: 'tool-call',\n id: event.toolCall.id,\n name: event.toolCall.name,\n arguments: JSON.stringify(event.toolCall.arguments),\n },\n }\n break\n case 'done':\n yield { type: 'usage', usage: mapUsage(event.message.usage) }\n yield { type: 'finish', reason: mapStopReason(event.message, contextWindow) }\n return\n case 'error':\n yield { type: 'usage', usage: mapUsage(event.error.usage) }\n yield { type: 'finish', reason: mapStopReason(event.error, contextWindow) }\n return\n }\n }\n throw new Error('dsh-magpie-connect: pi-ai event stream ended without done/error')\n}\n", "/**\n * Harness GenerateOptions -> pi-ai Context conversion, with image support.\n *\n * Text-only requests convert synchronously (`toPiContext`); requests carrying\n * durable image blocks resolve bytes through the harness attachment service\n * (`toPiContextWithImages`, async). pi-ai then encodes images as OpenAI\n * `image_url` (completions) or `input_image` (responses) parts.\n */\n\nimport { modelApiForEntry } from './catalog.ts'\n\nexport interface ImageAttachmentRef {\n attachmentId: string\n mediaType: string\n bytes: number\n width: number\n height: number\n name?: string\n}\n\nexport interface FileAttachmentRef {\n attachmentId: string\n name: string\n bytes: number\n}\n\nexport interface HarnessTool {\n name: string\n description: string\n parameters: unknown\n}\n\nexport type HarnessBlock =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'tool-call'; id: string; name: string; arguments: string }\n | { type: 'image'; attachment: ImageAttachmentRef; offloaded?: true; [key: string]: unknown }\n | { type: 'file'; attachment: FileAttachmentRef; [key: string]: unknown }\n | { type: 'tool-result'; toolCallId: string; content: HarnessBlock[]; isError?: boolean; [key: string]: unknown }\n | { type: string; [key: string]: unknown }\n\nexport interface HarnessMessage {\n role: 'system' | 'user' | 'assistant' | 'tool' | 'developer'\n content: HarnessBlock[]\n source?: { kind: string; provider?: string; model?: string; callId?: string; [key: string]: unknown }\n toolCallId?: string\n isError?: boolean\n [key: string]: unknown\n}\n\nexport interface HarnessGenerateOptions {\n provider: string\n model: string\n messages: HarnessMessage[]\n system?: string\n tools?: HarnessTool[]\n maxTokens?: number\n temperature?: number\n reasoningEffort?: string\n signal?: AbortSignal\n /** Declared auxiliary request purpose (e.g. `compaction`); absent for ordinary turns. */\n purpose?: string\n [key: string]: unknown\n}\n\n/** pi-ai message vocabulary (subset we emit). */\nexport type PiMessage =\n | { role: 'user'; content: string | PiContentBlock[]; timestamp: number }\n | {\n role: 'assistant'\n content: PiAssistantBlock[]\n api: 'openai-completions' | 'openai-responses'\n provider: string\n model: string\n usage: PiUsage\n stopReason: 'stop' | 'toolUse'\n timestamp: number\n }\n | { role: 'toolResult'; toolCallId: string; toolName: string; content: PiContentBlock[]; isError: boolean; timestamp: number }\n\nexport type PiAssistantBlock =\n | { type: 'text'; text: string }\n | { type: 'thinking'; thinking: string }\n | { type: 'toolCall'; id: string; name: string; arguments: Record<string, unknown> }\n\nexport type PiContentBlock = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }\n\nexport interface PiUsage {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n totalTokens: number\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number }\n}\n\nexport interface PiTool {\n name: string\n description: string\n parameters: unknown\n}\n\nexport interface PiContext {\n systemPrompt?: string\n messages: PiMessage[]\n tools?: PiTool[]\n}\n\n/** Attachment service surface we consume (structural subset of dsh-attachment). */\nexport interface AttachmentStore {\n readImageRequest(\n ref: ImageAttachmentRef,\n target: { width: number; height: number; maxBytes: number },\n signal?: AbortSignal,\n ): Promise<{ data: Uint8Array; mediaType: string; bytes: number; width: number; height: number }>\n}\n\nexport interface RequestImageVersion {\n data: Uint8Array\n mediaType: string\n bytes: number\n width: number\n height: number\n}\n\nconst REQUEST_MAX_PIXELS = 2048 * 2048\nconst REQUEST_MAX_BYTES = 1024 * 1024\n\nexport function zeroUsage(): PiUsage {\n return {\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}\n\nfunction parseArguments(raw: string): Record<string, unknown> {\n if (typeof raw !== 'string' || raw.length === 0) return {}\n try {\n const parsed = JSON.parse(raw) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : { value: parsed }\n } catch {\n return { raw }\n }\n}\n\n/** True when any message carries a retained (non-offloaded) image block. */\nexport function contentHasImage(messages: readonly HarnessMessage[]): boolean {\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type === 'image' && (block as { offloaded?: unknown }).offloaded !== true) return true\n }\n }\n return false\n}\n\n/** Request target for one attachment: fit within the pixel budget, cap bytes. */\nexport function requestImageTarget(ref: ImageAttachmentRef): { width: number; height: number; maxBytes: number } {\n const pixels = ref.width * ref.height\n if (!(pixels > REQUEST_MAX_PIXELS) || !(ref.width > 0 && ref.height > 0)) {\n return { width: ref.width, height: ref.height, maxBytes: REQUEST_MAX_BYTES }\n }\n const scale = Math.sqrt(REQUEST_MAX_PIXELS / pixels)\n return { width: Math.max(1, Math.floor(ref.width * scale)), height: Math.max(1, Math.floor(ref.height * scale)), maxBytes: REQUEST_MAX_BYTES }\n}\n\nfunction imageHandleText(ref: ImageAttachmentRef, version: RequestImageVersion): string {\n const name = ref.name ?? `attachment ${String(ref.attachmentId).slice(0, 12)}`\n return `Image ${name}; request preview ${version.width}x${version.height}px.`\n}\n\nfunction offloadedImageText(ref: ImageAttachmentRef): string {\n const name = ref.name ?? `attachment ${String(ref.attachmentId).slice(0, 12)}`\n return `[image omitted (offloaded); ${name}]`\n}\n\nfunction toBase64(data: Uint8Array): string {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('base64')\n}\n\n/**\n * Resolve every retained image to request bytes. Offloaded occurrences need\n * no bytes (placeholder text only) and are skipped here.\n */\nexport async function prepareRequestImages(\n messages: readonly HarnessMessage[],\n attachments: AttachmentStore,\n signal?: AbortSignal,\n): Promise<Map<string, RequestImageVersion>> {\n const refs = new Map<string, ImageAttachmentRef>()\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type !== 'image') continue\n const image = block as Extract<HarnessBlock, { type: 'image' }>\n if (image.offloaded === true) continue\n if (!refs.has(image.attachment.attachmentId)) refs.set(image.attachment.attachmentId, image.attachment)\n }\n }\n const versions = new Map<string, RequestImageVersion>()\n await Promise.all(\n [...refs.values()].map(async (ref) => {\n const prepared = await attachments.readImageRequest(ref, requestImageTarget(ref), signal)\n versions.set(ref.attachmentId, {\n data: prepared.data,\n mediaType: prepared.mediaType,\n bytes: prepared.bytes,\n width: prepared.width,\n height: prepared.height,\n })\n }),\n )\n return versions\n}\n\n/** User/tool-result content with images resolved to handle text + bytes. */\nexport function userContentWithImages(\n blocks: HarnessBlock[],\n requestImages: Map<string, RequestImageVersion>,\n): string | PiContentBlock[] {\n const content: PiContentBlock[] = []\n for (const block of blocks) {\n switch (block.type) {\n case 'text':\n if ((block as { text: string }).text.length > 0) content.push({ type: 'text', text: (block as { text: string }).text })\n break\n case 'image': {\n const image = block as Extract<HarnessBlock, { type: 'image' }>\n if (image.offloaded === true) {\n content.push({ type: 'text', text: offloadedImageText(image.attachment) })\n break\n }\n const version = requestImages.get(image.attachment.attachmentId)\n if (!version) {\n content.push({ type: 'text', text: offloadedImageText(image.attachment) })\n break\n }\n content.push({ type: 'text', text: imageHandleText(image.attachment, version) })\n content.push({ type: 'image', data: toBase64(version.data), mimeType: version.mediaType })\n break\n }\n case 'file': {\n const file = block as Extract<HarnessBlock, { type: 'file' }>\n content.push({ type: 'text', text: `[file: ${file.attachment.name} (${file.attachment.bytes} bytes)]` })\n break\n }\n case 'tool-result':\n content.push({ type: 'text', text: toolResultText((block as { content: HarnessBlock[] }).content) || '(no output)' })\n break\n default:\n break\n }\n }\n if (content.every((block) => block.type === 'text')) return content.map((block) => (block as { text: string }).text).join('')\n return content\n}\n\nfunction toPiAssistant(\n message: HarnessMessage,\n providerId: string,\n api: 'openai-completions' | 'openai-responses' = 'openai-completions',\n): Extract<PiMessage, { role: 'assistant' }> {\n const content: PiAssistantBlock[] = []\n for (const block of message.content) {\n switch (block.type) {\n case 'text':\n content.push({ type: 'text', text: (block as { text: string }).text })\n break\n case 'reasoning':\n content.push({ type: 'thinking', thinking: (block as { text: string }).text })\n break\n case 'tool-call': {\n const call = block as { id: string; name: string; arguments: string }\n content.push({ type: 'toolCall', id: call.id, name: call.name, arguments: parseArguments(call.arguments) })\n break\n }\n case 'image':\n throw new Error('dsh-magpie-connect: assistant image output cannot be replayed to the model')\n default:\n break\n }\n }\n const source = message.source\n return {\n role: 'assistant',\n content,\n api,\n provider: source?.kind === 'model' && typeof source.provider === 'string' ? source.provider : providerId,\n model: source?.kind === 'model' && typeof source.model === 'string' ? source.model : providerId,\n usage: zeroUsage(),\n stopReason: content.some((block) => block.type === 'toolCall') ? 'toolUse' : 'stop',\n timestamp: 0,\n }\n}\n\nfunction flattenText(message: HarnessMessage): string {\n return message.content\n .filter((block) => block.type === 'text')\n .map((block) => (block as { text: string }).text)\n .join('')\n}\n\nfunction toolResultText(blocks: HarnessBlock[]): string {\n return blocks\n .map((block) => (block.type === 'text' ? (block as { text: string }).text : block.type === 'tool-result' ? toolResultText((block as { content: HarnessBlock[] }).content) : ''))\n .join('')\n}\n\nfunction toolsOf(options: HarnessGenerateOptions): PiTool[] | undefined {\n const tools = options.tools?.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters }))\n return tools && tools.length > 0 ? tools : undefined\n}\n\nfunction assistantApiFor(options: HarnessGenerateOptions, entryEndpoints: readonly string[]): 'openai-completions' | 'openai-responses' {\n void options\n return modelApiForEntry(entryEndpoints)\n}\n\n/**\n * Text-only conversion (no image bytes needed). Images without resolved\n * bytes cannot be sent \u2014 callers must route image-bearing requests through\n * `toPiContextWithImages` instead.\n */\nexport function toPiContext(options: HarnessGenerateOptions, entryEndpoints: readonly string[] = []): PiContext {\n const providerId = options.provider\n const assistantApi = assistantApiFor(options, entryEndpoints)\n const toolNames = new Map<string, string>()\n const messages: PiMessage[] = []\n for (const message of options.messages) {\n if (message.role === 'system') {\n const text = flattenText(message)\n if (text.length > 0) messages.push({ role: 'user', content: text, timestamp: 0 })\n continue\n }\n if (message.role === 'assistant') {\n const assistant = toPiAssistant(message, providerId, assistantApi)\n for (const block of assistant.content) {\n if (block.type === 'toolCall') toolNames.set(block.id, block.name)\n }\n messages.push(assistant)\n continue\n }\n if (message.role === 'developer') continue\n if (message.role === 'tool') {\n const text = flattenText(message)\n messages.push({\n role: 'toolResult',\n toolCallId: message.toolCallId ?? '',\n toolName: message.toolCallId ? (toolNames.get(message.toolCallId) ?? 'unknown') : 'unknown',\n content: [{ type: 'text', text: text || '(no output)' }],\n isError: message.isError ?? false,\n timestamp: 0,\n })\n continue\n }\n for (const block of message.content) {\n if (block.type === 'image') {\n throw new Error('dsh-magpie-connect: image input requires the attachment service (use toPiContextWithImages)')\n }\n if (block.type === 'file') {\n // Files are projected to handle text by the harness; keep a stable\n // placeholder when one arrives unprojected.\n continue\n }\n }\n const text = flattenText(message)\n const fileText = message.content\n .filter((block) => block.type === 'file')\n .map((block) => `[file: ${(block as Extract<HarnessBlock, { type: 'file' }>).attachment.name}]`)\n .join('\\n')\n const combined = [text, fileText].filter((part) => part.length > 0).join('\\n')\n const results = message.content.filter((block) => block.type === 'tool-result') as Array<\n Extract<HarnessBlock, { type: 'tool-result' }>\n >\n if (combined.length > 0 || results.length === 0) {\n messages.push({ role: 'user', content: combined, timestamp: 0 })\n }\n for (const result of results) {\n messages.push({\n role: 'toolResult',\n toolCallId: result.toolCallId,\n toolName: toolNames.get(result.toolCallId) ?? 'unknown',\n content: [{ type: 'text', text: toolResultText(result.content) || '(no output)' }],\n isError: result.isError ?? false,\n timestamp: 0,\n })\n }\n }\n const context: PiContext = { messages }\n if (typeof options.system === 'string' && options.system.length > 0) context.systemPrompt = options.system\n const tools = toolsOf(options)\n if (tools) context.tools = tools\n return context\n}\n\n/**\n * Image-aware conversion: retained images resolve to request bytes via the\n * attachment service; offloaded images become placeholder text.\n */\nexport async function toPiContextWithImages(\n options: HarnessGenerateOptions,\n attachments: AttachmentStore,\n entryEndpoints: readonly string[] = [],\n): Promise<PiContext> {\n const providerId = options.provider\n const assistantApi = assistantApiFor(options, entryEndpoints)\n const requestImages = await prepareRequestImages(options.messages, attachments, options.signal)\n const toolNames = new Map<string, string>()\n const messages: PiMessage[] = []\n for (const message of options.messages) {\n if (message.role === 'system') {\n const text = flattenText(message)\n if (text.length > 0) messages.push({ role: 'user', content: text, timestamp: 0 })\n continue\n }\n if (message.role === 'assistant') {\n const assistant = toPiAssistant(message, providerId, assistantApi)\n for (const block of assistant.content) {\n if (block.type === 'toolCall') toolNames.set(block.id, block.name)\n }\n messages.push(assistant)\n continue\n }\n if (message.role === 'developer') continue\n if (message.role === 'tool') {\n messages.push({\n role: 'toolResult',\n toolCallId: message.toolCallId ?? '',\n toolName: message.toolCallId ? (toolNames.get(message.toolCallId) ?? 'unknown') : 'unknown',\n content: userContentToBlocks(message.content, requestImages),\n isError: message.isError ?? false,\n timestamp: 0,\n })\n continue\n }\n const content = userContentWithImages(message.content, requestImages)\n const results = message.content.filter((block) => block.type === 'tool-result') as Array<\n Extract<HarnessBlock, { type: 'tool-result' }>\n >\n // userContentWithImages already folds nested tool-results to text; emit\n // first-class toolResult messages for pi-ai tool continuity.\n if (typeof content === 'string' ? content.length > 0 || results.length === 0 : true) {\n messages.push({ role: 'user', content, timestamp: 0 })\n } else if (typeof content === 'string' && content.length === 0 && results.length === 0) {\n messages.push({ role: 'user', content, timestamp: 0 })\n }\n for (const result of results) {\n messages.push({\n role: 'toolResult',\n toolCallId: result.toolCallId,\n toolName: toolNames.get(result.toolCallId) ?? 'unknown',\n content: userContentToBlocks(result.content, requestImages),\n isError: result.isError ?? false,\n timestamp: 0,\n })\n }\n }\n const context: PiContext = { messages }\n if (typeof options.system === 'string' && options.system.length > 0) context.systemPrompt = options.system\n const tools = toolsOf(options)\n if (tools) context.tools = tools\n return context\n}\n\nfunction userContentToBlocks(blocks: HarnessBlock[], requestImages: Map<string, RequestImageVersion>): PiContentBlock[] {\n const converted = userContentWithImages(blocks, requestImages)\n if (typeof converted === 'string') return [{ type: 'text', text: converted || '(no output)' }]\n return converted.length > 0 ? converted : [{ type: 'text', text: '(no output)' }]\n}\n", "/**\n * Stall watchdog for upstream event streams.\n *\n * pi-ai surfaces transport failures as `error` events, but a silently\n * stalled SSE connection (headers sent, then no bytes ever again) produces\n * *no* event at all: the consumer's `for await` blocks until the SDK-level\n * overall timeout or the harness timeout. This wrapper races every `next()`\n * against a timer and, on expiry, aborts the upstream (best effort, via\n * `onTimeout`) and yields a synthetic `error` event so the normal chunk\n * translation turns the stall into a fast `TIMEOUT` finish instead of a\n * minutes-long hang.\n *\n * Two phases: time-to-first-event (queueing happens here) and idle-between-\n * events (a healthy stream emits frequently). Either phase accepts a\n * non-positive value to disable its timer (wait forever, the old behavior).\n */\n\nimport type { PiEvent } from './events.ts'\n\nexport interface StallTimeouts {\n /** Max wait for the first upstream event (connection + queueing). */\n firstEventTimeoutMs: number\n /** Max silence between two upstream events once streaming. */\n idleTimeoutMs: number\n}\n\nconst TIMED_OUT: unique symbol = Symbol('watchdog-timed-out')\n\nfunction raceTimeout<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer!: ReturnType<typeof setTimeout>\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), ms)\n const t = timer as unknown as { unref?: () => void }\n t.unref?.()\n })\n const cleanup = (): void => clearTimeout(timer)\n return Promise.race([promise.then((value) => {\n cleanup()\n return value\n }, (err: unknown) => {\n cleanup()\n throw err\n }), timeout])\n}\n\nfunction stallErrorEvent(model: string, waitMs: number, first: boolean): PiEvent {\n const phase = first ? 'waiting for the first upstream event' : 'waiting for the next upstream event'\n return {\n type: 'error',\n error: {\n api: 'openai-completions',\n provider: 'dsh-magpie-connect',\n model,\n content: [],\n usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 },\n stopReason: 'error',\n // Must read as a timeout (events.ts classifies on /timeout/i -> TIMEOUT).\n errorMessage: `upstream stream timeout: no upstream events for ${Math.round(waitMs / 1000)}s while ${phase} (model \"${model}\") \u2014 the stalled stream was aborted`,\n timestamp: Date.now(),\n },\n } as PiEvent\n}\n\nexport async function* withStallTimeout(\n events: AsyncIterable<PiEvent>,\n timeouts: StallTimeouts,\n options: { model?: string; onTimeout?: () => void } = {},\n): AsyncGenerator<PiEvent> {\n const iterator = events[Symbol.asyncIterator]()\n try {\n let first = true\n for (;;) {\n const waitMs = first ? timeouts.firstEventTimeoutMs : timeouts.idleTimeoutMs\n if (!(waitMs > 0 && Number.isFinite(waitMs))) {\n const next = await iterator.next()\n if (next.done) return\n first = false\n yield next.value\n continue\n }\n const next = await raceTimeout(iterator.next(), waitMs)\n if (next === TIMED_OUT) {\n try {\n options.onTimeout?.()\n } catch {\n // Teardown must never mask the stall itself.\n }\n yield stallErrorEvent(options.model ?? 'unknown', waitMs, first)\n return\n }\n if (next.done) return\n first = false\n yield next.value\n }\n } finally {\n // Best-effort detach without awaiting: the upstream may be the very thing\n // that is stuck, so waiting for its return() could hang teardown too.\n void Promise.resolve(iterator.return?.()).catch(() => {})\n }\n}\n", "/**\n * Plugin configuration (cordis config object, injected via cordis.patch.yml).\n *\n * The adapter registers a DSH LlmAdapter streaming directly from the Magpie\n * Magpie gateway (the configured API root): chat completions for most models plus the\n * Responses API for responses-only models. No child process, no proxy/pool.\n * The gateway needs no credential \u2014 `apiKey` defaults to a sentinel that\n * satisfies the pi-ai client without changing the wire.\n *\n * The settings sidebar page can override `baseUrl`/`apiKey` at runtime (saved\n * to `<dataDir>/settings.json`, applied without restart) and hides models\n * from the picker. Page values win per-field; patch config is the fallback.\n */\nimport { dshHomePath } from './homeDir.ts'\nexport interface DshMagpieConnectConfig {\n /**\n * Provider route id registered into DSH (the grouping key in the model\n * picker). Changing it after sessions already reference the old id will\n * orphan those model selections \u2014 prefer `displayName` for a cosmetic\n * rename.\n */\n providerId?: string\n /**\n * Display name shown in the model picker for this provider.\n * Defaults to the explicit `providerId` when one is given,\n * otherwise to `'Magpie'`.\n */\n displayName?: string\n /**\n * Versioned API root, e.g. `http://127.0.0.1:3425/v1`. The version is part of\n * the value, not something this plugin adds: a gateway that later serves\n * `/v2` or `/v3` is reached by changing this one string. Trailing slashes are\n * stripped; the path is kept.\n */\n baseUrl?: string\n /**\n * Gateway credential. Required: an empty key leaves the plugin unconfigured\n * even though `baseUrl` has a default, so the picker stays empty until it is\n * set (both are required by `isConfigured`).\n */\n apiKey?: string\n /**\n * Plugin state directory (status snapshot, settings file, catalog cache).\n * Defaults to `$DSH_HOME/storages/magpie-connect`\n * (`~/.dsh/storages/magpie-connect`).\n */\n dataDir?: string\n /** Model list refresh interval in seconds. */\n refreshSeconds?: number\n /**\n * Connection-setup retries for transient upstream failures (429/5xx with\n * backoff). Turn-level retries stay owned by DSH.\n */\n maxRetries?: number\n /** Overall upstream request cap in milliseconds. */\n timeoutMs?: number\n /**\n * Stall watchdog: max wait for the first upstream event in milliseconds\n * (queueing happens here). Non-positive disables that phase.\n */\n firstEventTimeoutMs?: number\n /**\n * Stall watchdog: max silence between upstream events in milliseconds.\n * Non-positive disables that phase.\n */\n idleTimeoutMs?: number\n}\n\nexport const defaults = {\n providerId: 'dsh-magpie-connect',\n displayName: 'Magpie',\n baseUrl: 'http://127.0.0.1:3425/v1',\n apiKey: '',\n refreshSeconds: 300,\n maxRetries: 2,\n timeoutMs: 300_000,\n firstEventTimeoutMs: 90_000,\n idleTimeoutMs: 60_000,\n} as const\n\nexport type ResolvedConfig = Required<\n Pick<DshMagpieConnectConfig, 'providerId' | 'refreshSeconds'>\n> &\n DshMagpieConnectConfig & { displayName: string; baseUrl: string; apiKey: string; dataDir: string }\n\nexport function resolveConfig(config: DshMagpieConnectConfig = {}): ResolvedConfig {\n const providerId = config.providerId ?? defaults.providerId\n return {\n ...defaults,\n ...config,\n providerId,\n displayName: config.displayName ?? (config.providerId ?? defaults.displayName),\n baseUrl: config.baseUrl ?? defaults.baseUrl,\n apiKey: config.apiKey ?? defaults.apiKey,\n dataDir: config.dataDir ?? dshHomePath('storages', 'magpie-connect'),\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { chmod, readFile, writeFile, mkdir, rename, rm } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\n/**\n * Page-owned runtime settings, persisted to a local JSON file.\n *\n * Precedence for the effective endpoint: settings page (this file, only the\n * fields the user actually saved) > cordis patch config > built-in defaults.\n *\n * `enabledModels` is an **allowlist**, matching DSH's own Models settings: the\n * picker offers the intersection of the gateway directory and this list. `null`\n * (absent) means \"inherit the whole directory\", `[]` means \"offer nothing\", and\n * a populated array means exactly those ids. The old blacklist\n * (`hiddenModels`) could not express \"the gateway added a model I don't want\n * yet\"; an allowlist can, and it is why a model the gateway re-lists never\n * comes back on its own.\n */\n\nexport interface MagpiePageSettings {\n baseUrl?: string\n apiKey?: string\n /** Magpie Web Key; never returned to the browser, only its presence is. */\n webKey?: string\n /**\n * Allowlist of model ids the picker offers. `undefined` = inherit every model\n * the gateway serves; `[]` = offer none; otherwise exactly these ids.\n */\n enabledModels?: string[] | undefined\n /**\n * Whether the composer's routing-trace icon shows in the input box's right\n * tool row. Absent reads as shown (the pre-toggle behavior); `false` hides\n * it. The settings page's switch writes `true`/`false` explicitly.\n */\n showComposerIcon?: boolean\n /**\n * Set once the `hiddenModels` (blacklist) document has been converted to\n * `enabledModels`. Its presence stops the migration from running twice \u2014 a\n * second run would read an already-allowlisted document as if it were a\n * blacklist and invert it into nonsense.\n */\n migratedFromHiddenModels?: true\n}\n\nexport interface EffectiveEndpoint {\n baseUrl: string\n apiKey: string\n}\n\n/**\n * What the settings page is allowed to see. The credential never travels to\n * the browser: the page only learns whether one is stored, so a page that\n * loads (or reloads) cannot leak it through the DOM, devtools, or an XSS in\n * the host UI.\n */\nexport interface MagpieSettingsView {\n baseUrl: string\n hasApiKey: boolean\n hasWebKey: boolean\n enabledModels?: string[]\n inheritedModels: boolean\n /** Whether the composer's routing icon shows (absent reads as true). */\n showComposerIcon: boolean\n}\n\nexport const SETTINGS_FILE = 'settings.json'\n\nexport function defaultSettingsPath(dataDir: string): string {\n return join(dataDir, SETTINGS_FILE)\n}\n\n/**\n * Normalize an API base URL: must be http(s), no trailing slash, path kept.\n *\n * The path is load-bearing, not a mistake to be trimmed: the gateway versions\n * its API (`/v1`, and later `/v2`, `/v3`), so this value *is* the prefix every\n * request is built on. The plugin appends only the resource (`/models`,\n * `/chat/completions`), never a version of its own \u2014 an origin-only value\n * would make a future `/v2` unreachable.\n */\nexport function normalizeBaseUrl(raw: unknown): string {\n if (typeof raw !== 'string' || raw.trim() === '') throw new Error('dsh-magpie-connect: baseUrl must be a non-empty http(s) URL')\n const trimmed = raw.trim()\n let url: URL\n try {\n url = new URL(trimmed)\n } catch {\n throw new Error(`dsh-magpie-connect: baseUrl is not a valid URL: ${trimmed}`)\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error(`dsh-magpie-connect: baseUrl must use http(s): ${trimmed}`)\n }\n // Query and fragment are never part of a base URL and would corrupt every\n // appended path; drop them rather than storing a value the wire ignores.\n return `${url.origin}${url.pathname.replace(/\\/+$/, '')}`\n}\n\n/** Normalize an enabled-model allowlist: strings only, deduped, order kept. */\nexport function normalizeEnabledModels(raw: unknown): string[] {\n if (raw === undefined) return []\n if (!Array.isArray(raw)) throw new Error('dsh-magpie-connect: enabledModels must be an array of model ids')\n const out: string[] = []\n for (const entry of raw) {\n if (typeof entry !== 'string') throw new Error('dsh-magpie-connect: enabledModels must be an array of model ids')\n const id = entry.trim()\n if (id !== '' && !out.includes(id)) out.push(id)\n }\n return out\n}\n\n/** Validate + normalize a page payload (full or partial). Unknown keys are dropped. */\nexport function normalizePageSettings(raw: unknown): MagpiePageSettings {\n if (!raw || typeof raw !== 'object') throw new Error('dsh-magpie-connect: settings payload must be an object')\n const record = raw as Record<string, unknown>\n const out: MagpiePageSettings = {}\n if (record.baseUrl !== undefined) out.baseUrl = normalizeBaseUrl(record.baseUrl)\n if (record.apiKey !== undefined) {\n if (typeof record.apiKey !== 'string' || record.apiKey.trim() === '') {\n throw new Error('dsh-magpie-connect: apiKey is required and must not be empty')\n }\n // Surrounding whitespace is always a paste artifact in Bearer keys.\n out.apiKey = record.apiKey.trim()\n }\n if (record.webKey !== undefined) {\n if (typeof record.webKey !== 'string' || record.webKey.trim() === '') {\n throw new Error('dsh-magpie-connect: webKey must be a non-empty string when supplied')\n }\n out.webKey = record.webKey.trim()\n }\n if (record.enabledModels !== undefined) out.enabledModels = normalizeEnabledModels(record.enabledModels)\n if (record.showComposerIcon !== undefined) {\n if (typeof record.showComposerIcon !== 'boolean') {\n throw new Error('dsh-magpie-connect: showComposerIcon must be a boolean')\n }\n out.showComposerIcon = record.showComposerIcon\n }\n if (record.migratedFromHiddenModels === true) out.migratedFromHiddenModels = true\n return out\n}\n\n/** Deep copy so a caller cannot mutate the store through a returned object. */\nfunction cloneSettings(source: MagpiePageSettings): MagpiePageSettings {\n return {\n ...source,\n ...(source.enabledModels === undefined ? {} : { enabledModels: [...source.enabledModels] }),\n }\n}\n\n/**\n * One-time conversion from the old blacklist document to the allowlist.\n *\n * The legacy file stored `hiddenModels` (ids to *exclude*). The new shape stores\n * `enabledModels` (ids to *include*), so the two are not interchangeable: an\n * unconverted file would be read as \"offer exactly the models I had hidden\",\n * which is the precise inverse of what the user asked for.\n *\n * `known` is the ids the picker would have offered under the old rules \u2014 the\n * gateway directory (live, else cached, else the built-in snapshot) minus the\n * hidden set. The conversion can only be computed from it, so the caller passes\n * whatever directory it has; when nothing is known yet (unconfigured, cold\n * cache), `enabledModels` is left absent, which means \"inherit everything\" \u2014\n * the only reading that cannot silently drop models the user can still use.\n *\n * The marker `migratedFromHiddenModels` is written even when the list could not\n * be computed: the blacklist is gone either way, and re-running the conversion\n * later would invert an already-converted document.\n * @param raw - the parsed settings document.\n * @param known - ids the old rules would have offered, or `undefined` when unknown.\n * @returns the converted document and whether anything changed.\n */\nexport function migrateLegacySettings(\n raw: unknown,\n known?: readonly string[],\n): { settings: MagpiePageSettings; migrated: boolean } {\n if (!raw || typeof raw !== 'object') return { settings: {}, migrated: false }\n const record = raw as Record<string, unknown>\n const legacy = record.hiddenModels\n if (record.migratedFromHiddenModels === true || !Array.isArray(legacy)) {\n return { settings: normalizePageSettings(raw), migrated: false }\n }\n const hidden = new Set(legacy.filter((entry): entry is string => typeof entry === 'string').map((entry) => entry.trim()).filter((entry) => entry !== ''))\n const base: Record<string, unknown> = { ...record, migratedFromHiddenModels: true }\n delete base.hiddenModels\n if (known !== undefined) base.enabledModels = known.filter((id) => !hidden.has(id))\n const settings = normalizePageSettings(base)\n return { settings, migrated: true }\n}\n\n/**\n * Merge patch config with page settings: page wins per-field, but only for\n * fields it actually saved (absent page fields fall back to patch/defaults).\n */\nexport function resolveEffectiveEndpoint(\n patch: { baseUrl: string; apiKey: string },\n page: MagpiePageSettings,\n): EffectiveEndpoint {\n return {\n baseUrl: page.baseUrl ?? patch.baseUrl,\n apiKey: page.apiKey ?? patch.apiKey,\n }\n}\n\n/** Fully configured only when both URL and key are present. Either missing gates everything. */\nexport function isConfigured(endpoint: EffectiveEndpoint): boolean {\n return endpoint.baseUrl !== '' && endpoint.apiKey !== ''\n}\n\n/** In-memory settings with file persistence. Synchronous reads for the hot path. */\nexport class SettingsStore {\n #path?: string\n /**\n * Pre-0.5 settings file (`~/.dsh-magpie-connect/settings.json`), or\n * `undefined` when no read-through-and-migrate is wanted (an explicit\n * `dataDir` means the user owns the path \u2014 never fall back, never delete).\n *\n * Read-only until the first successful write: settings are only moved to the\n * new location when the user saves something, so an upgrade that changes no\n * setting touches no file at all.\n */\n #legacyPath?: string\n /** True while the live state came from {@link #legacyPath}, not {@link #path}. */\n #legacySource = false\n /**\n * Set when the settings file exists but could not be read/parsed at startup.\n * Blocks a partial save (e.g. the model-list autosave that posts only\n * `enabledModels`) from writing the empty in-memory state over a file whose\n * credentials we simply failed to load \u2014 that is how a key silently vanished.\n */\n #loadFailed = false\n #settings: MagpiePageSettings = {}\n /** Serializes writes: one persist in flight, so two generations cannot interleave. */\n #writeChain: Promise<void> = Promise.resolve()\n #listeners = new Set<() => void>()\n /**\n * Whether the state directory is the plugin's own (`$DSH_HOME/storages/\u2026`),\n * in which case its permissions are tightened to `0700`. An explicit\n * `dataDir` belongs to the user, so it is never chmod-ed behind their back.\n * The settings file itself is repaired to `0600` either way: it holds a\n * credential.\n */\n #privateDir: boolean\n\n constructor(options: { path?: string; legacyPath?: string; privateDir?: boolean } = {}) {\n this.#path = options.path\n this.#legacyPath = options.legacyPath\n this.#privateDir = options.privateDir ?? false\n }\n\n /**\n * Tighten permissions on a file this store owns, best-effort.\n *\n * Never throws: the file may live on a read-only mount, a non-POSIX\n * filesystem, or a platform where `chmod` is a no-op. A permission repair\n * must never make otherwise-readable settings unreadable.\n */\n async #chmodQuietly(path: string, mode: number): Promise<void> {\n await chmod(path, mode).catch(() => {})\n }\n\n /**\n * Read one settings file, distinguishing \"absent\" from \"unreadable\".\n *\n * Returns the raw parsed document (`raw`) untouched so the legacy\n * `hiddenModels` conversion can still see that field; validation happens in\n * {@link read}. `exists: true` with `raw: undefined` means the file is there\n * but could not be read or parsed \u2014 callers must not mistake that for \"no\n * configuration\", or a later save would persist the blank state over a\n * perfectly good file.\n * @param path - file to read; `undefined` yields `{ exists: false }`.\n */\n async #readFile(path?: string): Promise<{ exists: boolean; raw?: unknown; error?: unknown }> {\n if (!path) return { exists: false }\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { exists: false }\n return { exists: true, error }\n }\n // Repair a pre-existing credential file (old versions wrote it with the\n // process umask). Best-effort: never turn a readable file into an error.\n await this.#chmodQuietly(path, 0o600)\n if (this.#privateDir) await this.#chmodQuietly(dirname(path), 0o700)\n try {\n return { exists: true, raw: JSON.parse(text) as unknown }\n } catch (error) {\n return { exists: true, error }\n }\n }\n\n /**\n * Locate the document to use: new location first, then the pre-0.5 file.\n *\n * A file that exists but is unreadable is returned as-is (`exists: true`,\n * `raw: undefined`) so callers can flag it instead of mistaking it for\n * \"no configuration\". A present-but-corrupt NEW file is authoritative and\n * does not fall back to the legacy one \u2014 that could resurrect stale\n * credentials over a deliberately replaced file.\n */\n async #resolveRaw(): Promise<{ exists: boolean; raw?: unknown; error?: unknown }> {\n const fromNew = await this.#readFile(this.#path)\n if (fromNew.raw !== undefined) return fromNew\n if (fromNew.exists) return fromNew\n const fromOld = await this.#readFile(this.#legacyPath)\n if (fromOld.raw !== undefined) {\n this.#legacySource = true\n return fromOld\n }\n return fromOld\n }\n\n /**\n * Read and normalize the persisted document without touching memory or disk.\n *\n * New location first; when it is absent, fall back **read-only** to the\n * pre-0.5 file so an upgrade shows the user's saved endpoint immediately.\n *\n * A file that is *present but unreadable* is NOT treated as \"no\n * configuration\": it sets {@link #loadFailed} (blocking a later partial save\n * from overwriting it with the blank state) and still returns `{}` so callers\n * have something to render.\n */\n async read(): Promise<MagpiePageSettings> {\n const resolved = await this.#resolveRaw()\n if (resolved.raw !== undefined) {\n try {\n return normalizePageSettings(resolved.raw)\n } catch {\n this.#loadFailed = true\n return {}\n }\n }\n if (resolved.exists) this.#loadFailed = true\n return {}\n }\n\n /**\n * Load persisted settings, running the one-time `hiddenModels` ->\n * `enabledModels` conversion.\n *\n * The rewrite is attempted at startup rather than lazily so the file on disk\n * matches what the running process believes; a failed write is not fatal\n * (the in-memory result is still correct), and the migration marker makes a\n * retry idempotent.\n * @param known - ids the old blacklist rules would have offered, used to\n * compute the allowlist; omitted when the directory is not known yet.\n */\n async load(known?: readonly string[]): Promise<MagpiePageSettings> {\n if (!this.#path) return this.get()\n // Use the RAW document, not the normalized one: the legacy `hiddenModels`\n // conversion needs the field `normalizePageSettings` would drop.\n const resolved = await this.#resolveRaw()\n if (resolved.raw === undefined) {\n if (resolved.exists) this.#loadFailed = true\n this.#settings = {}\n return this.get()\n }\n const { settings, migrated } = migrateLegacySettings(resolved.raw, known)\n this.#settings = settings\n if (migrated) await this.persist().catch(() => {})\n return this.get()\n }\n\n /**\n * Adopt a document already read and normalized by {@link read}, then run the\n * legacy conversion against the directory that is now warm.\n *\n * This is the startup path: `read` -> `applyPageSettings` (so the catalog\n * knows the user's endpoint) -> `catalog.start` (so the directory is real) ->\n * `hydrate` (so a legacy file converts against the live gateway).\n * @param raw - the normalized document from {@link read}.\n * @param known - ids the old blacklist rules would have offered.\n */\n async hydrate(raw: MagpiePageSettings, known?: readonly string[]): Promise<MagpiePageSettings> {\n const { settings, migrated } = migrateLegacySettings(raw, known)\n this.#settings = settings\n if (migrated) await this.persist().catch(() => {})\n this.#emit()\n return this.get()\n }\n\n get(): MagpiePageSettings {\n return cloneSettings(this.#settings)\n }\n\n /** Merge a partial payload, persist, and notify listeners. */\n async save(partial: unknown): Promise<MagpiePageSettings> {\n const normalized = normalizePageSettings(partial)\n // Guard: after a failed startup read, refuse a partial save (the model-list\n // autosave posts only `enabledModels`) \u2014 persisting the blank in-memory\n // state would erase credentials we merely failed to load.\n if (this.#loadFailed && normalized.baseUrl === undefined && normalized.apiKey === undefined) {\n throw new Error(\n 'dsh-magpie-connect: settings file was unreadable; refusing to overwrite it with a partial save \u2014 reload the settings page or restore settings.json',\n )\n }\n this.#settings = { ...this.#settings, ...normalized }\n await this.persist()\n // A complete save (both credentials present) proves the state is trustworthy again.\n if (normalized.baseUrl !== undefined && normalized.apiKey !== undefined) this.#loadFailed = false\n this.#emit()\n return this.get()\n }\n\n /** Replace the whole document (used at startup after load). */\n replace(next: MagpiePageSettings): void {\n this.#settings = cloneSettings(next)\n this.#emit()\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener)\n return () => {\n this.#listeners.delete(listener)\n }\n }\n\n async persist(): Promise<void> {\n if (!this.#path) return\n // Serialize: one write in flight, so overlapping generations cannot\n // interleave a read-modify-write or clobber each other's temp file.\n this.#writeChain = this.#writeChain.then(\n () => this.#writeNow(),\n () => this.#writeNow(),\n )\n await this.#writeChain\n }\n\n /**\n * Write the current state to {@link #path} atomically, then clean up the\n * pre-0.5 file if this generation had read from it.\n *\n * The temp file is a random-suffixed sibling opened with `wx` and renamed\n * over the target \u2014 no `rm` beforehand (that opened a window where the file\n * did not exist and a concurrent read saw an empty document), and a random\n * suffix so two generations in one process cannot share a temp name.\n */\n async #writeNow(): Promise<void> {\n const target = this.#path\n if (!target) return\n const dir = dirname(target)\n await mkdir(dir, { recursive: true, ...(this.#privateDir ? { mode: 0o700 } : {}) })\n if (this.#privateDir) await this.#chmodQuietly(dir, 0o700)\n const tmp = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n await writeFile(tmp, JSON.stringify(this.#settings, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n await rename(tmp, target)\n } finally {\n await rm(tmp, { force: true }).catch(() => {})\n }\n // The new file is durable now; only then drop the legacy one. A failed\n // delete is harmless (the new file is authoritative) and is retried on the\n // next save because `#legacySource` stays true.\n if (this.#legacySource && this.#legacyPath) {\n await rm(this.#legacyPath, { force: true })\n .then(() => {\n this.#legacySource = false\n })\n .catch(() => {\n // keep #legacySource so a later save retries the cleanup\n })\n }\n }\n\n #emit(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener()\n } catch {\n // listeners must never break the save path\n }\n }\n }\n}\n", "/**\n * The routing-trace fetcher: reads the gateway's own view of its routing \u2014\n * the request ledger (`/v1/magpie/usage/requests`) and the accounts'\n * allowances (`/v1/magpie/quotas`) \u2014 and compresses both into the small\n * {@link TraceView} the composer popover shows.\n *\n * Both endpoints answer this machine and, while Magpie shares on the local\n * network, another machine too \u2014 but always with the gateway key, so the\n * fetch runs on the host, never in the browser (CORS would refuse the page,\n * and the key must not cross to it).\n *\n * `{gateway}` is the configured API base with its version segment removed:\n * `http://api.lan/v1` \u2192 `http://api.lan` \u2014 the popover contract's \"base_url\".\n */\n\nimport {\n isConfigured,\n normalizeBaseUrl,\n type EffectiveEndpoint,\n} from './settings.ts'\nimport type {\n ActiveRequestRow,\n SessionRouteTry,\n SessionRouteView,\n SessionTraceView,\n TraceAccountRow,\n TraceCandidate,\n TraceGroup,\n TraceRequestRow,\n TraceRest,\n TraceRoutingSection,\n TraceStatus,\n TraceSubGroup,\n TraceTotals,\n TraceView,\n} from './trace-contract.ts'\n\n/** Request rows one popover shows; the gateway returns newest first. */\nexport const TRACE_REQUEST_ROWS = 8\n\n/** Account rows one popover shows; the list scrolls past the cap. */\nexport const TRACE_ACCOUNT_ROWS = 14\n\n/** In-flight rows one popover shows; the own session's row is kept first. */\nexport const TRACE_ACTIVE_ROWS = 5\n\n/** How long one fetch may take before the popover shows \"unreachable\". */\nexport const TRACE_TIMEOUT_MS = 8_000\n\n/** The `period` the ledger is read for; today keeps the header counts current. */\nconst LEDGER_PERIOD = 'today'\n\n/** Path the signed-in Magpie Web console serves beside its HTML. */\nconst WEB_TRACE_PATH = '/api/gateway/trace'\n\n/** Allowed set so a raw value maps onto the wire status without widening it. */\nconst STATUS_KINDS: readonly TraceStatus[] = ['ok', 'unconfigured', 'unauthorized', 'forbidden', 'network', 'unknown']\n\n/**\n * The gateway base the trace endpoints hang off: the configured API base\n * with its trailing version segment (`/v1`, `/v1/`, `/v2`) removed. The\n * version is part of the API root, not of the gateway address, and the\n * `/v1/magpie/*` namespace lives on the address alone.\n * @param baseUrl - the configured versioned API root (`http://host:port/v1`).\n * @returns the base for `/v1/magpie/*` (origin plus any non-version prefix path), or `undefined` for values that never were URLs.\n */\nexport function deriveGatewayBase(baseUrl: string): string | undefined {\n let url: URL\n try {\n url = new URL(baseUrl)\n } catch {\n return undefined\n }\n const trimmed = url.pathname.replace(/\\/+$/, '').replace(/\\/v\\d+$/i, '')\n return `${url.origin}${trimmed}`\n}\n\n/** One response of the two gateway endpoints, decoded loosely (fields optional). */\ntype LooseRecord = Record<string, unknown>\n\n/** Read one finite number field. */\nfunction num(record: LooseRecord, key: string): number | undefined {\n const value = record[key]\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\n/** Read one non-empty string field. */\nfunction str(record: LooseRecord, key: string): string | undefined {\n const value = record[key]\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/** Round a 0\u2013100 share into whole percents, clamped. */\nfunction pctOf(used: unknown): number | undefined {\n if (typeof used !== 'number' || !Number.isFinite(used)) return undefined\n return Math.min(100, Math.max(0, Math.round(used)))\n}\n\n/** Percent from an explicit amount/limit pair (windows the vendor counts by units). */\nfunction pctOfParts(record: LooseRecord): number | undefined {\n const amount = num(record, 'amount')\n const limit = num(record, 'limit')\n if (amount === undefined || limit === undefined || limit <= 0) return undefined\n return pctOf((amount / limit) * 100)\n}\n\n/**\n * Classify one fetch failure. The gateway's 403 wording names the share\n * setting (\"told to another machine only when magpie is shared\u2026\"), so the\n * popover's hint can say exactly what to turn on.\n */\nfunction statusForStatusCode(code: number): TraceStatus {\n if (code === 401) return 'unauthorized'\n if (code === 403) return 'forbidden'\n if (code >= 500) return 'network'\n return 'unknown'\n}\n\n/**\n * Budget for probing an alternate Web port. Kept well under\n * {@link TRACE_TIMEOUT_MS}: a black-holed port must not eat the trace's own\n * timeout, which is shared with the gateway reads.\n */\nconst WEB_PROBE_TIMEOUT_MS = 1_500\n\n/** Magpie Web's usual listen ports, tried as a last-resort cookie name, commonest first. */\nconst WEB_COOKIE_FALLBACK_PORTS = ['3430', '443', '80'] as const\n\n/**\n * The cookie name Magpie Web most likely expects for a base: it names the\n * cookie after the port it listens on (`magpie_web_3430`). A direct connection\n * matches this guess; behind a reverse proxy the external port differs, so it\n * is only a starting point {@link discoverWebCookieName} corrects.\n */\nfunction guessedWebCookie(base: string): string {\n try {\n const url = new URL(base)\n return `magpie_web_${url.port || (url.protocol === 'https:' ? '443' : '80')}`\n } catch {\n return 'magpie_web_3430'\n }\n}\n\n/** Base -> the cookie name Magpie Web answered with, so later reads skip the 401 probe. */\nconst webCookieNames = new Map<string, string>()\n\n/** Base -> the Web root that answered, so a split layout probes its Web port only once. */\nconst webBasesResolved = new Map<string, string>()\n\n/** Test hook: forget learned cookie names and Web roots between cases. */\nexport function __resetTraceCaches(): void {\n webCookieNames.clear()\n webBasesResolved.clear()\n}\n\n/**\n * Learn Magpie Web's cookie name from its own sign-in link. The name is\n * `magpie_web_<its listen port>`, and a reverse proxy hides that port, so the\n * external URL cannot tell us. `GET /?k=<webKey>` makes Magpie set the cookie\n * (its normal sign-in); the redirect is not followed \u2014 only the Set-Cookie\n * name is read. Returns `undefined` when the response carries no such cookie.\n */\nasync function discoverWebCookieName(base: string, webKey: string, signal: AbortSignal): Promise<string | undefined> {\n try {\n const response = await fetch(`${base.replace(/\\/+$/, '')}/?k=${encodeURIComponent(webKey)}`, {\n redirect: 'manual',\n cache: 'no-store',\n signal,\n })\n const match = /magpie_web_[A-Za-z0-9._-]+/.exec(response.headers.get('set-cookie') ?? '')\n return match?.[0]\n } catch {\n return undefined\n }\n}\n\n/**\n * GET one Magpie Web path carrying the Web Key. Magpie names the cookie after\n * its listen port; when a reverse proxy hides that port the URL-derived name is\n * refused with 401. On a 401 this asks the sign-in link for the real name and\n * retries once, then falls back to the common Web ports, caching whichever name\n * won so the next read is a single request. A missing cookie and a wrong cookie\n * both answer 401, so trying a few names is cheap.\n */\nasync function fetchWebResponse(base: string, webKey: string, path: string, accept: string, signal: AbortSignal): Promise<Response> {\n const tried: string[] = []\n const attempt = (name: string): Promise<Response> => {\n tried.push(name)\n return fetch(`${base}${path}`, {\n headers: { cookie: `${name}=${webKey}`, accept },\n cache: 'no-store',\n signal,\n })\n }\n const cached = webCookieNames.get(base)\n let response = await attempt(cached ?? guessedWebCookie(base))\n if (response.status === 401) {\n const discovered = await discoverWebCookieName(base, webKey, signal)\n if (discovered !== undefined && !tried.includes(discovered)) {\n response = await attempt(discovered)\n }\n if (response.status === 401) {\n for (const port of WEB_COOKIE_FALLBACK_PORTS) {\n const name = `magpie_web_${port}`\n if (tried.includes(name)) continue\n response = await attempt(name)\n if (response.status !== 401) break\n }\n }\n }\n if (response.ok) {\n const winner = tried[tried.length - 1]\n if (winner !== undefined) webCookieNames.set(base, winner)\n }\n return response\n}\n\n/** Fetch one Magpie Web endpoint, carrying the Web Key in Magpie's own cookie name. */\nasync function fetchWebJson(base: string, webKey: string, path: string, signal: AbortSignal): Promise<LooseRecord> {\n const response = await fetchWebResponse(base, webKey, path, 'application/json', signal)\n if (!response.ok) {\n const error = new Error(`Magpie Web HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return (await response.json()) as LooseRecord\n}\n\n/**\n * Web roots to try: the configured base first, then Magpie's usual Web port\n * (:3430) on the same host as a fallback. This keeps the setting to one Web Key\n * while still supporting the split API (:80/:3425) + Web (:3430) layout. The\n * configured base leads on purpose: a base that already answers must not be\n * preceded by a probe, or a black-holed :3430 would cost every read its timeout\n * before the real address is ever tried.\n */\nfunction webBases(base: string): string[] {\n const candidates: string[] = [base]\n try {\n const url = new URL(base)\n if (url.port !== '3430') {\n url.port = '3430'\n candidates.push(`${url.origin}${url.pathname.replace(/\\/+$/, '')}`)\n }\n } catch {\n return [base]\n }\n return [...new Set(candidates)]\n}\n\n/** {@link webBases}, but a Web root that already answered leads, so its port probe happens once. */\nfunction orderedWebBases(base: string): string[] {\n const bases = webBases(base)\n const known = webBasesResolved.get(base)\n return known !== undefined && bases.includes(known) ? [known, ...bases.filter((b) => b !== known)] : bases\n}\n\n/** The signal for one Web try: the configured base gets the full budget, a probe is cut short. */\nfunction webTrySignal(signal: AbortSignal, index: number): AbortSignal {\n if (index === 0) return signal\n const budget = AbortSignal.timeout(WEB_PROBE_TIMEOUT_MS)\n return typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, budget]) : budget\n}\n\n/** Read full trace from the same API host, trying its Web port if split. */\nasync function fetchFullWebTrace(base: string, webKey: string, signal: AbortSignal): Promise<{ trace: LooseRecord; base: string }> {\n let lastError: unknown\n for (const [index, candidate] of orderedWebBases(base).entries()) {\n try {\n const trace = await fetchWebJson(candidate, webKey, `${WEB_TRACE_PATH}?after=0`, webTrySignal(signal, index))\n // The Web Console's traceJSON has no `object` field (unlike the\n // gateway's loopback /v1/magpie/trace); routes[] is the reliable shape.\n if (!Array.isArray(trace.routes)) {\n throw new Error('Magpie Web returned an unexpected trace shape')\n }\n webBasesResolved.set(base, candidate)\n return { trace, base: candidate }\n } catch (error) {\n // Only the caller's own abort ends the walk; a probe's short budget\n // timing out on one candidate must let the next base be tried.\n if (signal.aborted) throw error\n lastError = error\n }\n }\n throw lastError instanceof Error ? lastError : new Error('Magpie Web trace is unavailable')\n}\n\n/** The Routing page URL from the configured API root; no Web Key in the link. */\nfunction routingUrlFor(base: string): string {\n return `${base.replace(/\\/+$/, '')}/?view=routing`\n}\n\n/** Fetch one binary asset from Magpie Web, carrying the Web Key in Magpie's own cookie name. */\nasync function fetchWebBinary(base: string, webKey: string, path: string, signal: AbortSignal): Promise<{ body: ArrayBuffer; contentType: string }> {\n const response = await fetchWebResponse(base, webKey, path, 'image/svg+xml,image/png,*/*', signal)\n if (!response.ok) {\n const error = new Error(`Magpie Web HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return {\n body: await response.arrayBuffer(),\n contentType: response.headers.get('content-type') ?? 'image/svg+xml',\n }\n}\n\n/** Magpie's png icon names; all other built-in icons are SVG. */\nconst PNG_ICONS = new Set([\n 'crush', 'zcode', 'alma', 'hanako', 'cindy', 'lody', 'typesafe', 'atomcode',\n 'snow', 'mlx-serve', 'mothx', 'zoo-code', 'kimi-code-desktop',\n])\n\n/**\n * Read one provider icon from Magpie Web through the stored Web Key. The\n * browser asks the plugin's same-origin `/api/magpie-icon` route instead of\n * loading a cross-origin image that would miss the Web cookie.\n */\nexport async function fetchWebIcon(\n base: string,\n webKey: string,\n name: string,\n signal: AbortSignal,\n): Promise<{ body: ArrayBuffer; contentType: string }> {\n const safe = /^[A-Za-z0-9._~-]+$/.test(name) && !name.includes('..') ? name : 'generic'\n if (safe === 'generic') throw new Error('Magpie Web icon name is invalid')\n const ext = PNG_ICONS.has(safe) ? 'png' : 'svg'\n const path = `/icons/${safe}.${ext}`\n let lastError: unknown\n for (const [index, candidate] of orderedWebBases(base).entries()) {\n try {\n const icon = await fetchWebBinary(candidate, webKey, path, webTrySignal(signal, index))\n webBasesResolved.set(base, candidate)\n return icon\n } catch (error) {\n // As in fetchFullWebTrace: a probe's own timeout is not the caller's abort.\n if (signal.aborted) throw error\n lastError = error\n }\n }\n throw lastError instanceof Error ? lastError : new Error('Magpie Web icon is unavailable')\n}\n\n/** Fetch one gateway endpoint, mapping failures onto the shared status kind. */\nasync function fetchJson(base: string, apiKey: string, path: string, signal: AbortSignal): Promise<LooseRecord> {\n const response = await fetch(`${base}${path}`, {\n headers: { authorization: `Bearer ${apiKey}`, accept: 'application/json' },\n cache: 'no-store',\n signal,\n })\n if (!response.ok) {\n const error = new Error(`HTTP ${response.status} ${path}`) as Error & { statusCode?: number }\n error.statusCode = response.status\n throw error\n }\n return (await response.json()) as LooseRecord\n}\n\n/**\n * Project one ledger row onto the wire shape. `req` is the routing group or\n * model the agent asked for (`auto/gpt-6-luna`), `served` the model that\n * answered; when they agree one name is enough, so the row stays one line.\n */\nfunction toRequestRow(row: LooseRecord): TraceRequestRow | undefined {\n const id = num(row, 'route_id')\n const time = str(row, 't')\n if (id === undefined || time === undefined) return undefined\n const requested = str(row, 'req')\n const served = str(row, 'served')\n const provider = str(row, 'providerName')\n const account = str(row, 'providerAccount')\n const ms = num(row, 'ms')\n const ttftMs = num(row, 'ttft_ms')\n const status = num(row, 'status')\n const cost = num(row, 'cost')\n return {\n id,\n time,\n agent: str(row, 'agentName') ?? str(row, 'agent') ?? '?',\n ...(requested !== undefined ? { requested } : {}),\n ...(served !== undefined && served !== requested ? { served } : {}),\n ...(provider !== undefined ? { provider } : {}),\n ...(account !== undefined ? { account } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(row.canceled === true ? { canceled: true } : {}),\n ...(cost !== undefined && cost !== 0 ? { cost } : {}),\n }\n}\n\n/**\n * Mask one account holder for the wire: keep the name's head, drop anything\n * mail- or phone-shaped. The gateway's own masking already runs when the\n * user turned it on; this is the popover's second line of defense, so a\n * full address never reaches the browser's DOM.\n */\nfunction maskHolder(user: string | undefined): string | undefined {\n if (user === undefined) return undefined\n const at = user.indexOf('@')\n if (at <= 0) return user\n const head = user.slice(0, Math.max(1, Math.min(at, 4)))\n return `${head}\u2026`\n}\n\n/**\n * Whether one window is the account's aggregate. Vendors that meter a base\n * allowance plus an extra one publish three windows \u2014 \"Credits\", \"Extra\n * credits\" and \"Total credits\" \u2014 and only the total covers what routing\n * actually weighs; showing the base one alone makes the gauge disagree with\n * the numbers beside it.\n */\nfunction isTotalWindow(entry: LooseRecord): boolean {\n return /^(grand\\s+)?total\\b/i.test((str(entry, 'name') ?? '').trim())\n}\n\n/** Whether one window carries a share the popover can draw. */\nfunction hasShare(entry: LooseRecord): boolean {\n return num(entry, 'used') !== undefined || pctOfParts(entry) !== undefined\n}\n\n/**\n * The quota window the popover shows for one account: the aggregate window\n * when the vendor publishes one, else the first window with a usable share\n * (a `used` percent, or an amount/limit pair), falling back to the first one\n * that names its reset date. Windows the vendor marks unlimited never win \u2014\n * their 0% would read as \"nothing used\" beside an allowance that is not\n * counted at all.\n */\nfunction pickWindow(windows: LooseRecord[]): LooseRecord | undefined {\n const usable = windows.filter((entry) => entry.unlimited !== true && hasShare(entry))\n const counted = windows.filter((entry) => entry.unlimited !== true)\n return (\n usable.find(isTotalWindow) ??\n usable[0] ??\n counted.find((entry) => str(entry, 'resetsAt') !== undefined) ??\n counted[0] ??\n windows[0]\n )\n}\n\n/** Project one quota account onto the wire shape. */\nfunction toAccountRow(account: LooseRecord): TraceAccountRow | undefined {\n const provider = str(account, 'name') ?? str(account, 'provider')\n if (provider === undefined) return undefined\n const user = maskHolder(str(account, 'user'))\n const base: TraceAccountRow = {\n provider,\n ...(str(account, 'provider') !== undefined ? { providerId: str(account, 'provider') } : {}),\n ...(str(account, 'plan') !== undefined ? { plan: str(account, 'plan') } : {}),\n ...(user !== undefined ? { user } : {}),\n ...(str(account, 'error') !== undefined ? { error: str(account, 'error') } : {}),\n }\n const windows = Array.isArray(account.windows) ? (account.windows as LooseRecord[]) : []\n const window = pickWindow(windows)\n if (window === undefined) return base\n const usedPct = pctOf(window.used) ?? pctOfParts(window)\n const windowName = str(window, 'name')\n const display = str(window, 'display')\n const resetsAt = str(window, 'resetsAt')\n const amount = num(window, 'amount')\n const limit = num(window, 'limit')\n const unit = str(window, 'unit')\n return {\n ...base,\n ...(windowName !== undefined ? { windowName } : {}),\n ...(usedPct !== undefined ? { usedPct } : {}),\n ...(display !== undefined ? { display } : {}),\n ...(amount !== undefined ? { amount } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(unit !== undefined ? { unit } : {}),\n ...(resetsAt !== undefined ? { resetsAt } : {}),\n }\n}\n\n/**\n * Project one in-flight request (`/v1/magpie/concurrency`'s `active`) onto\n * the wire shape, and mark the popover's own session's row so the client can\n * pin it to the top.\n */\nfunction toActiveRow(entry: LooseRecord, session: string | undefined): ActiveRequestRow | undefined {\n const ms = num(entry, 'ms')\n if (ms === undefined) return undefined\n const rowSession = str(entry, 'session')\n const agent = str(entry, 'agent')\n const model = str(entry, 'model')\n const provider = str(entry, 'provider')\n const phase = str(entry, 'phase')\n return {\n ...(agent !== undefined ? { agent } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(provider !== undefined ? { provider } : {}),\n ...(rowSession !== undefined ? { session: rowSession } : {}),\n ms,\n ...(phase !== undefined ? { phase } : {}),\n ...(session !== undefined && rowSession !== undefined && rowSession === session ? { own: true } : {}),\n }\n}\n\n/** The whole-gateway concurrency summary, for the header line. */\nfunction toConcurrency(data: LooseRecord): { requests: number; waiting: number; tools: number } {\n return {\n requests: num(data, 'requests') ?? 0,\n waiting: num(data, 'waiting') ?? 0,\n tools: num(data, 'tools') ?? 0,\n }\n}\n\n/** Project Magpie's Weighed or Try record onto a compact candidate. */\nfunction toTraceCandidate(\n entry: LooseRecord,\n outcome: TraceCandidate['outcome'],\n restOverride?: TraceRest,\n): TraceCandidate | undefined {\n const id = str(entry, 'id')\n const provider = str(entry, 'provider')\n if (id === undefined || provider === undefined) return undefined\n const used = num(entry, 'used')\n const renews = Array.isArray(entry.renews)\n ? (entry.renews as unknown[]).filter((value): value is string => typeof value === 'string')\n : []\n const via = Array.isArray(entry.via)\n ? (entry.via as unknown[]).filter((value): value is string => typeof value === 'string' && value !== '')\n : []\n const amount = num(entry, 'amount')\n const limit = num(entry, 'limit')\n /**\n * The share the gauge draws. It must describe the same window as the\n * amount/limit beside it: when the row carries an amount/limit pair, that\n * pair is the source, and a `used` percent that disagrees with it belongs\n * to another window. Otherwise the vendor's own `used` stands.\n */\n const partsPct = pctOfParts(entry)\n const usedPct = amount !== undefined && limit !== undefined && limit > 0\n ? (partsPct ?? pctOf(used))\n : pctOf(used)\n const restRaw = restOverride ?? (entry.rest && typeof entry.rest === 'object' ? entry.rest as TraceRest : undefined)\n const status = num(entry, 'status')\n const ms = num(entry, 'ms')\n return {\n id,\n provider,\n ...(str(entry, 'kind') !== undefined ? { kind: str(entry, 'kind') } : {}),\n ...(str(entry, 'name') !== undefined ? { name: str(entry, 'name') } : {}),\n ...(str(entry, 'who') !== undefined ? { who: maskHolder(str(entry, 'who')) } : {}),\n ...(str(entry, 'icon') !== undefined ? { icon: str(entry, 'icon') } : {}),\n ...(str(entry, 'preset') !== undefined ? { preset: str(entry, 'preset') } : {}),\n ...(str(entry, 'plan') !== undefined ? { plan: str(entry, 'plan') } : {}),\n ...(str(entry, 'model') !== undefined ? { model: str(entry, 'model') } : {}),\n ...(str(entry, 'fixed') !== undefined ? { fixed: str(entry, 'fixed') } : {}),\n ...(via.length > 0 ? { via } : {}),\n ...(usedPct !== undefined ? { usedPct } : {}),\n ...(amount !== undefined ? { amount } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(str(entry, 'unit') !== undefined ? { unit: str(entry, 'unit') } : {}),\n ...(str(entry, 'windowName') !== undefined ? { windowName: str(entry, 'windowName') } : {}),\n ...(renews.length > 0 ? { renews } : {}),\n ...(restRaw !== undefined ? { rest: restRaw } : {}),\n outcome,\n ...(status !== undefined ? { status } : {}),\n ...(str(entry, 'fail') !== undefined ? { fail: str(entry, 'fail') } : {}),\n ...(str(entry, 'error') !== undefined ? { error: str(entry, 'error') } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(str(entry, 'leftWhy') !== undefined ? { skipReason: str(entry, 'leftWhy') } : {}),\n ...(entry.fallback === true ? { fallback: true } : {}),\n ...(entry.free === true ? { free: true } : {}),\n ...(num(entry, 'capped') !== undefined ? { capped: num(entry, 'capped') } : {}),\n ...(entry.held === true ? { held: true } : {}),\n ...(str(entry, 'heldBy') !== undefined ? { heldBy: str(entry, 'heldBy') } : {}),\n ...(entry.unlisted === true ? { unlisted: true } : {}),\n ...(entry.barred === true ? { barred: true } : {}),\n ...(entry.noCredits === true ? { noCredits: true } : {}),\n ...(str(entry, 'unread') !== undefined ? { unread: str(entry, 'unread') } : {}),\n ...(str(entry, 'noURL') !== undefined ? { noURL: str(entry, 'noURL') } : {}),\n ...(num(entry, 'window') !== undefined ? { window: num(entry, 'window') } : {}),\n }\n}\n\n/**\n * Compress the session's full route row from `/api/gateway/trace` and enrich\n * its candidates with quota errors where possible. The route itself carries\n * `Rest`, provider/account identity, order/left and each try's failure.\n */\nfunction toSessionTrace(route: LooseRecord, accounts: readonly TraceAccountRow[]): SessionTraceView | undefined {\n const id = num(route, 'id')\n const model = str(route, 'model')\n if (id === undefined || model === undefined) return undefined\n const orderRaw = Array.isArray(route.order) ? route.order as LooseRecord[] : []\n const leftRaw = Array.isArray(route.left) ? route.left as LooseRecord[] : []\n const triesRaw = Array.isArray(route.tries) ? route.tries as LooseRecord[] : []\n const groupRaw = route.group !== null && typeof route.group === 'object' ? route.group as LooseRecord : undefined\n const groupMembers = groupRaw !== undefined && Array.isArray(groupRaw.members)\n ? (groupRaw.members as unknown[]).filter((x): x is string => typeof x === 'string')\n : []\n const groupVia = groupRaw !== undefined && Array.isArray(groupRaw.via)\n ? (groupRaw.via as unknown[]).map((x) => typeof x === 'string' ? x : '')\n : []\n const subsRaw = groupRaw !== undefined && Array.isArray(groupRaw.subs)\n ? groupRaw.subs as LooseRecord[]\n : []\n const subs: TraceSubGroup[] = subsRaw\n .filter((entry) => str(entry, 'id') !== undefined)\n .map((entry) => ({\n id: str(entry, 'id') ?? '',\n name: str(entry, 'name') ?? str(entry, 'id') ?? '',\n ...(str(entry, 'ref') !== undefined ? { ref: str(entry, 'ref') } : {}),\n ...(str(entry, 'routing') !== undefined ? { routing: str(entry, 'routing') } : {}),\n }))\n const group: TraceGroup | undefined = groupRaw !== undefined && str(groupRaw, 'id') !== undefined\n ? {\n id: str(groupRaw, 'id') ?? '',\n name: str(groupRaw, 'name') ?? str(groupRaw, 'id') ?? '',\n ...(str(groupRaw, 'ref') !== undefined ? { ref: str(groupRaw, 'ref') } : {}),\n ...(str(groupRaw, 'routing') !== undefined ? { routing: str(groupRaw, 'routing') } : {}),\n ...(groupMembers.length > 0 ? { members: groupMembers } : {}),\n ...(subs.length > 0 ? { subs } : {}),\n ...(groupVia.length > 0 ? { via: groupVia } : {}),\n }\n : undefined\n /**\n * The inner subgroup a candidate belongs to. Magpie puts the path on\n * `Weighed.via`, and also supplies `GroupRef.via` parallel to `members`.\n * A blank via is a direct member of the parent group \u2014 it must stay a\n * sibling of the nested routing groups, not inherit a previous subgroup.\n */\n const subgroupFor = (entry: LooseRecord): string => {\n const own = Array.isArray(entry.via)\n ? (entry.via as unknown[]).filter((x): x is string => typeof x === 'string' && x !== '')\n : []\n if (own.length > 0) return own[own.length - 1] ?? ''\n const provider = str(entry, 'provider') ?? ''\n const member = str(entry, 'model') ?? ''\n const fixed = str(entry, 'fixed')\n if (provider === '' || member === '') return ''\n const ref = `${provider}/${member}${fixed !== undefined ? `:${fixed}` : ''}`\n const idx = groupMembers.findIndex((x) => x === ref || x === `${provider}/${member}`)\n if (idx < 0) return ''\n const path = (groupVia[idx] ?? '').split('>').filter(Boolean)\n return path[path.length - 1] ?? ''\n }\n const seatKey = (entry: LooseRecord): string =>\n `${str(entry, 'id') ?? ''}\\u0000${str(entry, 'model') ?? ''}\\u0000${str(entry, 'fixed') ?? ''}`\n const triesBySeat = new Map<string, LooseRecord>()\n for (const tried of triesRaw) if (str(tried, 'id') !== undefined) triesBySeat.set(seatKey(tried), tried)\n const candidate = (entry: LooseRecord, kind: TraceCandidate['outcome']): TraceCandidate | undefined => {\n const tried = triesBySeat.get(seatKey(entry))\n const quota = accounts.find((account) =>\n account.providerId === str(entry, 'provider') &&\n ((account.user ?? '').toLowerCase() === maskHolder(str(entry, 'who'))?.toLowerCase() || account.user === undefined),\n )\n /**\n * The window the row's numbers belong to, when that is knowable. The\n * quota window names itself; the trace row does not. It shares the name\n * while it counts that same window \u2014 the limit is the window's size, so\n * an equal limit means the same allowance even though the two reads\n * happened minutes apart \u2014 or while the row carries no numbers of its own\n * and the quota filled them. A row counting another window must not wear\n * the aggregate's label.\n */\n const entryAmount = num(entry, 'amount')\n const entryLimit = num(entry, 'limit')\n const namesPickedWindow = quota?.windowName !== undefined && (\n (entryAmount === undefined && entryLimit === undefined) ||\n (entryLimit !== undefined && quota.limit !== undefined && Math.abs(entryLimit - quota.limit) < 0.01)\n )\n const quotaEnrichment: LooseRecord = {\n // The trace row's own counters are what routing weighed, so they win;\n // the quota windows only fill what the row left out. Filling `used` from\n // one window while `amount`/`limit` came from another is exactly the\n // mismatch this guard prevents.\n ...(num(entry, 'used') === undefined && quota?.usedPct !== undefined ? { used: quota.usedPct } : {}),\n ...(entryAmount === undefined && quota?.amount !== undefined ? { amount: quota.amount } : {}),\n ...(entryLimit === undefined && quota?.limit !== undefined ? { limit: quota.limit } : {}),\n ...(str(entry, 'unit') === undefined && quota?.unit !== undefined ? { unit: quota.unit } : {}),\n ...(str(entry, 'windowName') === undefined && namesPickedWindow ? { windowName: quota!.windowName } : {}),\n ...(!Array.isArray(entry.renews) && quota?.resetsAt !== undefined ? { renews: [quota.resetsAt] } : {}),\n }\n const row = toTraceCandidate({ ...entry, ...quotaEnrichment }, kind, tried?.rest as TraceRest | undefined)\n if (row === undefined) return undefined\n const rest = tried?.rest ?? entry.rest\n const restValue = rest !== null && typeof rest === 'object' ? rest as LooseRecord : undefined\n const outcome: TraceCandidate['outcome'] = restValue !== undefined ? 'resting' : kind\n return {\n ...row,\n outcome,\n subgroup: subgroupFor(entry),\n ...(quota?.error !== undefined && row.error === undefined ? { error: quota.error } : {}),\n ...(restValue !== undefined ? { rest: {\n ...(str(restValue, 'why') !== undefined ? { why: str(restValue, 'why') } : {}),\n ...(num(restValue, 'status') !== undefined ? { status: num(restValue, 'status') } : {}),\n ...(str(restValue, 'until') !== undefined ? { until: str(restValue, 'until') } : {}),\n ...(str(restValue, 'by') !== undefined ? { by: str(restValue, 'by') } : {}),\n ...(num(restValue, 'failures') !== undefined ? { failures: num(restValue, 'failures') } : {}),\n ...(str(restValue, 'model') !== undefined ? { model: str(restValue, 'model') } : {}),\n ...(str(restValue, 'error') !== undefined ? { error: str(restValue, 'error') } : {}),\n ...(restValue.rate === true ? { rate: true } : {}),\n } } : {}),\n }\n }\n const orderSeats = new Set(orderRaw.map(seatKey))\n const orderCandidates = orderRaw.map((entry) => {\n const tried = triesBySeat.get(seatKey(entry))\n const done = tried?.done === true\n const status = num(tried ?? entry, 'status')\n const rest = tried?.rest ?? entry.rest\n const outcome: TraceCandidate['outcome'] = rest !== undefined && rest !== null ? 'resting'\n : tried === undefined ? 'available'\n : done ? (status !== undefined && status >= 200 && status < 400 ? 'answered' : 'failed')\n : 'processing'\n return candidate({ ...entry, ...(tried ?? {}), ...(status !== undefined ? { status } : {}) }, outcome)\n }).filter((value): value is TraceCandidate => value !== undefined)\n const tries = triesRaw.map((entry) => {\n const ordered = orderRaw.find((candidate) => seatKey(candidate) === seatKey(entry))\n const enriched = ordered !== undefined ? { ...ordered, ...entry } : entry\n const done = entry.done === true\n const status = num(entry, 'status')\n const rest = entry.rest ?? ordered?.rest\n const outcome: TraceCandidate['outcome'] = rest !== undefined && rest !== null ? 'resting'\n : done ? (status !== undefined && status >= 200 && status < 400 ? 'answered' : 'failed')\n : 'processing'\n return candidate(enriched, outcome)\n }).filter((value): value is TraceCandidate => value !== undefined)\n const left = leftRaw\n .filter((entry) => !orderSeats.has(seatKey(entry)))\n .map((entry) => {\n const skipReason = str(entry, 'leftWhy') ?? str(entry, 'heldBy')\n ?? (entry.held === true ? 'held' : entry.noCredits === true ? 'credits' : entry.unlisted === true ? 'unlisted' : entry.barred === true ? 'barred' : '')\n return candidate({ ...entry, ...(skipReason !== '' ? { leftWhy: skipReason } : {}) }, 'skipped')\n })\n .filter((value): value is TraceCandidate => value !== undefined)\n const allCandidates = [...orderCandidates, ...left]\n const bySubgroup = new Map<string, TraceCandidate[]>()\n const orderedKeys: string[] = []\n for (const row of allCandidates) {\n const key = row.subgroup ?? ''\n if (!bySubgroup.has(key)) orderedKeys.push(key)\n const list = bySubgroup.get(key) ?? []\n list.push(row)\n bySubgroup.set(key, list)\n }\n const sections: TraceRoutingSection[] = []\n for (const key of orderedKeys) {\n const rows = bySubgroup.get(key) ?? []\n if (rows.length === 0) continue\n if (key === '') {\n // Direct members of the parent routing group are siblings of nested\n // routing-group headings. Never fold them into the previous auto/* group.\n sections.push({\n name: group?.name ?? model,\n ref: group?.ref ?? model,\n ...(group?.routing !== undefined ? { routing: group.routing } : {}),\n depth: 0,\n hideHeader: subs.length > 0,\n candidates: rows.slice(0, 8),\n })\n continue\n }\n const sub = subs.find((entry) => entry.id === key)\n sections.push({\n name: sub?.name ?? key,\n ref: sub?.ref ?? `group/${key}`,\n ...(sub?.routing !== undefined ? { routing: sub.routing } : {}),\n depth: 1,\n candidates: rows.slice(0, 8),\n })\n }\n if (sections.length === 0) {\n sections.push({\n name: group?.name ?? model,\n ref: group?.ref ?? model,\n ...(group?.routing !== undefined ? { routing: group.routing } : {}),\n depth: 0,\n candidates: allCandidates.slice(0, 8),\n })\n }\n const ms = num(route, 'ms')\n const ttftMs = num(route, 'ttft')\n const status = num(route, 'status')\n return {\n id,\n ...(str(route, 'time') !== undefined ? { time: str(route, 'time') } : {}),\n model,\n ...(group !== undefined ? { group } : {}),\n ...(sections.length > 0 ? { sections } : {}),\n order: orderCandidates,\n left,\n tries,\n done: route.done === true,\n ...(status !== undefined ? { status } : {}),\n ...(str(route, 'error') !== undefined ? { error: str(route, 'error') } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n }\n}\n\n/** Whether one of the two fetches failed with a fetch-level error record. */\nfunction isAbort(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError'\n}\n\n/**\n * Project one session route (`/v1/magpie/route`) onto the wire shape. The\n * gateway returns `{\"route\":null}` for a session it has not routed yet, so\n * absence maps to `undefined`, not an empty object.\n */\nfunction toSessionRoute(data: LooseRecord): SessionRouteView | undefined {\n const route = data.route\n if (route === null || route === undefined || typeof route !== 'object') return undefined\n const record = route as LooseRecord\n const triesRaw = Array.isArray(record.tries) ? (record.tries as LooseRecord[]) : []\n const tries: SessionRouteTry[] = triesRaw.map((entry) => {\n const ms = num(entry, 'ms')\n const status = num(entry, 'status')\n return {\n ...(str(entry, 'model') !== undefined ? { model: str(entry, 'model') } : {}),\n ...(entry.done === true ? { done: true } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(str(entry, 'fail') !== undefined ? { fail: str(entry, 'fail') } : {}),\n }\n })\n const ms = num(record, 'ms')\n const ttftMs = num(record, 'ttft_ms')\n const status = num(record, 'status')\n const seq = num(data, 'seq')\n return {\n ...(str(record, 'time') !== undefined ? { time: str(record, 'time') } : {}),\n ...(str(record, 'asked') !== undefined ? { asked: str(record, 'asked') } : {}),\n ...(str(record, 'model') !== undefined ? { model: str(record, 'model') } : {}),\n ...(str(record, 'served') !== undefined ? { served: str(record, 'served') } : {}),\n ...(str(record, 'group') !== undefined ? { group: str(record, 'group') } : {}),\n ...(tries.length > 0 ? { tries } : {}),\n ...(record.done === true ? { done: true } : {}),\n ...(status !== undefined ? { status } : {}),\n ...(ms !== undefined ? { ms } : {}),\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n ...(str(record, 'error') !== undefined ? { error: str(record, 'error') } : {}),\n ...(seq !== undefined ? { seq } : {}),\n }\n}\n\n/**\n * Fetch the full Web trace when a Web Key is configured, then add quotas;\n * otherwise fall back to the gateway-key-only ledger/concurrency view. The\n * session route is a final fallback if the full trace is unavailable.\n * A full-trace auth failure is shown beside the fallback data rather than\n * hiding the gateway-key view: the Web Key is optional and can be stale.\n * @param endpoint - effective API endpoint (page settings over patch config).\n * @param signal - caller lifetime; the popover aborts on close.\n * @param session - DSH session id to find its route in the full trace.\n * @param webKey - optional Magpie Web Key, stored server-side only.\n * @returns the compressed view, always with a status.\n */\nexport async function fetchTraceView(endpoint: EffectiveEndpoint, signal: AbortSignal, session?: string, webKey?: string): Promise<TraceView> {\n const fetchedAt = new Date().toISOString()\n let base: string | undefined\n try {\n base = deriveGatewayBase(normalizeBaseUrl(endpoint.baseUrl))\n } catch {\n base = undefined\n }\n const defaultRoutingUrl = base !== undefined && base !== '' ? routingUrlFor(base) : undefined\n if (!isConfigured(endpoint)) return { status: 'unconfigured', fetchedAt, ...(defaultRoutingUrl !== undefined ? { routingUrl: defaultRoutingUrl } : {}) }\n if (base === undefined || base === '') return { status: 'unconfigured', fetchedAt, ...(defaultRoutingUrl !== undefined ? { routingUrl: defaultRoutingUrl } : {}) }\n const key = endpoint.apiKey\n const fullWebTrace = webKey !== undefined && webKey.trim() !== ''\n ? fetchFullWebTrace(base, webKey.trim(), signal)\n .then((out) => ({ data: out.trace, base: out.base }))\n .catch((error: unknown) => ({ error }))\n : Promise.resolve(undefined)\n\n const usage = fetchJson(base, key, `/v1/magpie/usage/requests?limit=${TRACE_REQUEST_ROWS}&period=${LEDGER_PERIOD}`, signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const quotas = fetchJson(base, key, '/v1/magpie/quotas', signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const concurrency = fetchJson(base, key, '/v1/magpie/concurrency', signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n const sessionRoute = session !== undefined && session !== ''\n ? fetchJson(base, key, `/v1/magpie/route?session=${encodeURIComponent(session)}`, signal)\n .then((data) => ({ data }))\n .catch((error: unknown) => ({ error }))\n : Promise.resolve(undefined)\n const [usageOut, quotasOut, concurrencyOut, routeOut, fullTraceOut] = await Promise.all([usage, quotas, concurrency, sessionRoute, fullWebTrace])\n\n const usageFailed = 'error' in usageOut\n const quotasFailed = 'error' in quotasOut\n if (usageFailed && quotasFailed) {\n // Both halves failed: one status kind, never a throw. An aborted popover\n // is not a failure worth a message \u2014 the caller is gone.\n const errors: unknown[] = [usageOut.error, quotasOut.error]\n if (errors.some(isAbort)) return { status: 'network', message: 'aborted', fetchedAt }\n const first = errors[0] as (Error & { statusCode?: number }) | undefined\n const kind = first !== undefined && typeof first.statusCode === 'number'\n ? statusForStatusCode(first.statusCode)\n : (first instanceof TypeError ? 'network' : 'unknown')\n return { status: kind, message: first instanceof Error ? first.message : undefined, fetchedAt }\n }\n\n const usageData = usageFailed ? {} : (usageOut.data as LooseRecord)\n const quotasData = quotasFailed ? {} : (quotasOut.data as LooseRecord)\n const concurrencyData = 'error' in concurrencyOut ? undefined : (concurrencyOut.data as LooseRecord)\n\n const totals: TraceTotals = {\n requests: num(usageData, 'calls') ?? 0,\n errors: num(usageData, 'errors') ?? 0,\n retried: num(usageData, 'retried') ?? 0,\n canceled: num(usageData, 'canceled') ?? 0,\n ...(num(usageData, 'credits') !== undefined ? { credits: num(usageData, 'credits') } : {}),\n }\n const rows = Array.isArray(usageData.rows) ? (usageData.rows as LooseRecord[]) : []\n const requests = rows.map(toRequestRow).filter((row): row is TraceRequestRow => row !== undefined)\n const accountsRaw = Array.isArray(quotasData.data) ? (quotasData.data as LooseRecord[]) : []\n const accounts = accountsRaw\n .map(toAccountRow)\n .filter((row): row is TraceAccountRow => row !== undefined)\n .slice(0, TRACE_ACCOUNT_ROWS)\n const activeRaw = concurrencyData !== undefined && Array.isArray(concurrencyData.active)\n ? (concurrencyData.active as LooseRecord[])\n : []\n // The popover's own session's request first, then the longest-running.\n const active = activeRaw\n .map((entry) => toActiveRow(entry, session))\n .filter((row): row is ActiveRequestRow => row !== undefined)\n .sort((a, b) => (b.own === true ? 1 : 0) - (a.own === true ? 1 : 0) || b.ms - a.ms)\n .slice(0, TRACE_ACTIVE_ROWS)\n\n const fullTraceData = fullTraceOut !== undefined && 'data' in fullTraceOut\n ? fullTraceOut.data as LooseRecord\n : undefined\n const routingUrl = defaultRoutingUrl\n const fullRoutes = fullTraceData !== undefined && Array.isArray(fullTraceData.routes)\n ? fullTraceData.routes as LooseRecord[]\n : []\n // Prefer the addressed session's own latest route. With no session \u2014 or a\n // session the gateway never routed \u2014 fall back to the newest route in the\n // whole trace, so the popover still shows the latest overall routing.\n const matched = session !== undefined\n ? [...fullRoutes].reverse().find((route) => str(route, 'session') === session)\n : undefined\n const matchedRoute = matched ?? (fullRoutes.length > 0 ? fullRoutes[fullRoutes.length - 1] : undefined)\n const sessionTrace = matchedRoute !== undefined ? toSessionTrace(matchedRoute, accounts) : undefined\n const traceFailure = fullTraceOut !== undefined && 'error' in fullTraceOut ? fullTraceOut.error : undefined\n const webTraceError: TraceView['webTraceError'] = webKey === undefined || webKey.trim() === ''\n ? 'missing-key'\n : traceFailure !== undefined\n ? (Number((traceFailure as Error & { statusCode?: number })?.statusCode) === 401 ? 'unauthorized'\n : Number((traceFailure as Error & { statusCode?: number })?.statusCode) === 403 ? 'forbidden' : 'unavailable')\n : undefined\n\n return {\n status: 'ok',\n fetchedAt,\n routingUrl,\n totals,\n ...(webTraceError !== undefined ? { webTraceError } : {}),\n ...(traceFailure instanceof Error ? { webTraceMessage: traceFailure.message } : {}),\n ...(requests.length > 0 ? { requests } : {}),\n ...(accounts.length > 0 ? { accounts } : {}),\n ...(concurrencyData !== undefined ? { concurrency: toConcurrency(concurrencyData) } : {}),\n ...(active.length > 0 ? { active } : {}),\n ...((routeOut !== undefined && 'data' in routeOut)\n ? { sessionRoute: toSessionRoute((routeOut as { data: LooseRecord }).data) }\n : {}),\n ...(sessionTrace !== undefined ? { sessionTrace } : {}),\n }\n}\n\n/** Narrow an unknown value onto the wire status list (client decode). */\nexport function asTraceStatus(value: unknown): TraceStatus {\n return STATUS_KINDS.includes(value as TraceStatus) ? (value as TraceStatus) : 'unknown'\n}\n"],
5
+ "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,aAAAC,kBAAiB;;;ACD1B,SAAS,mBAAmB;AAC5B,SAAS,UAAU,QAAQ,IAAI,WAAW,aAAa;AACvD,SAAS,SAAS,YAAY;AAyCvB,IAAM,gBAAgB,CAAC,WAAW,OAAO,UAAU,QAAQ,SAAS,KAAK;AAOhF,IAAM,eAAkC,CAAC,QAAQ,WAAW,OAAO,UAAU,QAAQ,SAAS,OAAO,OAAO;AAE5G,IAAM,gBAAuE;AAAA,EAC3E,MAAM,EAAE,MAAM,QAAQ,aAAa,yDAAY;AAAA,EAC/C,SAAS,EAAE,MAAM,WAAW,aAAa,6CAAU;AAAA,EACnD,KAAK,EAAE,MAAM,OAAO,aAAa,qEAAc;AAAA,EAC/C,QAAQ,EAAE,MAAM,UAAU,aAAa,2EAAe;AAAA,EACtD,MAAM,EAAE,MAAM,QAAQ,aAAa,qEAAc;AAAA,EACjD,OAAO,EAAE,MAAM,cAAc,aAAa,uCAAS;AAAA,EACnD,KAAK,EAAE,MAAM,O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CAAC,EAAE;AAAA,EACxG,CAAC;AAKD,MAAI;AACF,QAAI,OAAO,IAAI,WAAW,YAAY;AACpC,UAAI,OAAO,CAAC,UAAU,GAAG,CAAC,gBAAyC;AACjE,YAAI;AACF,gBAAM,SAAS;AAIf,gBAAM,QAAS,IAA2C;AAC1D,iBAAO,SAAS,MAAM,OAAO,UAAU,YAAY,EAAE,MAAM,MAAM,GAAG,KAAK,GAAG,0CAA0C;AAAA,QACxH,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,QAAQ;AAAA,EAER;AAKA,mBAAiB,EAAE,OAAO,SAAS,eAAe,WAAW,kBAAkB;AAE/E,wBAAsB,KAAK,MAAM;AAEjC,QAAM,cAAe,IAA6C;AAClE,MAAI,OAAO,gBAAgB,YAAY;AACrC,gBAAY,KAAK,KAAK,MAAM,MAAM;AAChC,cAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO,EAAE,MAAM;AACjB;",
6
6
  "names": ["join", "writeFile", "name", "num", "resolve", "join", "name", "name", "text", "resolve", "next", "randomBytes", "readFile", "writeFile", "mkdir", "rename", "rm", "dirname", "join", "name", "status", "candidate", "ms", "resolve", "name", "join", "writeFile"]
7
7
  }