@agimon-ai/po-core 0.0.0-alpha.138 → 0.0.0-alpha.139

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.
@@ -550,6 +550,11 @@ interface PoCustomProviderDefinition {
550
550
  /** `http:` or `https:`, without userinfo or a query string. */
551
551
  readonly baseUrl: string;
552
552
  readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';
553
+ /**
554
+ * `openai-completions` only: send `tools: []` once the conversation holds tool calls but the turn offers
555
+ * no tools, for proxies such as LiteLLM that reject tool history without a tools list.
556
+ */
557
+ readonly requiresToolsWithToolHistory?: boolean;
553
558
  readonly models: readonly {
554
559
  readonly id: string;
555
560
  readonly name?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.d.mts","names":["_0","_0","_0","_0","IoContext","_0","_$__hubChannel0.PoHubSessionUsage","_0"],"sources":["../src/schemas/serverBundle.ts","../src/schemas/brain.ts","../src/schemas/serverScope.ts","../src/schemas/approvalPrompt.ts","../src/schemas/approval.ts","../src/schemas/backgroundWork.ts","../src/schemas/notification.ts","../src/schemas/platform.ts","../src/schemas/workflow.ts","../src/schemas/hubChannel.ts","../src/schemas/packageApi.ts","../src/schemas/apiContracts.ts","../src/services/apiContracts/index.ts","../src/schemas/builtinApiContracts.ts","../src/schemas/httpApiContracts.ts","../src/schemas/sessionProtocol.ts","../src/schemas/sessionApiContracts.ts","../src/schemas/transportApiContracts.ts"],"mappings":";;;;;;;;;;UAKiB;WACN;WACA;;UAGM;WACN;;WAEA;;WAEA,cAAc;;WAEd,iBAAiB;;WAEjB,cAAc;;WAEd;;WAEA;WACA,iBAAiB;WACjB,iBAAiB;WACjB;;;;;UCtBM;EACf;EACA,OAAO;;UAGQ;EACf;EACA;EACA,QAAQ,YAAY;;UAGL;EACf;EACA;EACA,OAAO;EACP,aAAa;EACb,OAAO;EACP;EACA;;UAGe;EACf;EACA;EACA,OAAO;EACP,OAAO;;;UAIQ;EACf;E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AA,qBAAA,KAAA,uBAAA,KAAA,8BAAA,KAAA;;EAOR;IACE,MAAI,KAAA;;;;IACJ,QAAM,KAAA,QAAA,KAAA,sBAAA,KAAA,uBAAA,KAAA,4BAAA,KAAA;;EAOR;EACA;IAAc,QAAM,KAAA;;;;;EACpB;IACE,MAAI,KAAA;;;;;;;IAOJ,QAAM,KAAA;;;;;;;;;;;;;;;;;;;;;;EAkBR;IACE,MAAI,KAAA,QAAA,KAAA;;;;;;;;;;;EAMN;IACE,QAAM,KAAA;;;;;;;;;;;;;;;;;;;;;;;EAoBR;IACE,QAAM,KAAA;;;;;;;;;;;;;;;;;;EAcR;IACE,QAAM,KAAA,OAAA,KAAA;;;;;;;;;;;;;EAiBR;IAAsB,QAAM,KAAA,OAAA,KAAA;;;;;EAC5B;IAA8B,QAAM,KAAA,OAAA,KAAA,QAAA,KAAA,iBAAA,KAAA,qBAAA,KAAA,iBAAA,KAAA,oBAAA,KAAA,kBAAA,KAAA,iBAAA,KAAA;;EACpC;IAAW,MAAI,KAAA;;;IAAuD,QAAM,KAAA,QAAA;;EAC5E;IAAW,MAAI,KAAA;;EACf;IAAa,MAAI,KAAA,OAAA,KAAA;;;;;;;;;qBClQN"}
1
+ {"version":3,"file":"apiContracts.d.mts","names":["_0","_0","_0","_0","IoContext","_0","_$__hubChannel0.PoHubSessionUsage","_0"],"sources":["../src/schemas/serverBundle.ts","../src/schemas/brain.ts","../src/schemas/serverScope.ts","../src/schemas/approvalPrompt.ts","../src/schemas/approval.ts","../src/schemas/backgroundWork.ts","../src/schemas/notification.ts","../src/schemas/platform.ts","../src/schemas/workflow.ts","../src/schemas/hubChannel.ts","../src/schemas/packageApi.ts","../src/schemas/apiContracts.ts","../src/services/apiContracts/index.ts","../src/schemas/builtinApiContracts.ts","../src/schemas/httpApiContracts.ts","../src/schemas/sessionProtocol.ts","../src/schemas/sessionApiContracts.ts","../src/schemas/transportApiContracts.ts"],"mappings":";;;;;;;;;;UAKiB;WACN;WACA;;UAGM;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AA,QAAA,KAAA,iBAAA,KAAA,qBAAA,KAAA,iBAAA,KAAA,oBAAA,KAAA,kBAAA,KAAA,iBAAA,KAAA;;EACnB;IAAe,MAAI,KAAA;;EACnB;IAAgB,MAAI,KAAA;;EACpB;IAAY,MAAI,KAAA;;;;;;;;;;EAChB;IAAoB,MAAI,KAAA;;;;;;;;;IAAW,QAAM,KAAA;;;;EACzC;IACE,MAAI,KAAA;;;IACJ,QAAM,KAAA,QAAA,KAAA,qBAAA,KAAA,uBAAA,KAAA,8BAAA,KAAA;;EAOR;IACE,MAAI,KAAA;;;;IACJ,QAAM,KAAA,QAAA,KAAA,sBAAA,KAAA,uBAAA,KAAA,4BAAA,KAAA;;EAOR;EACA;IAAc,QAAM,KAAA;;;;;EACpB;IACE,MAAI,KAAA;;;;;;;IAOJ,QAAM,KAAA;;;;;;;;;;;;;;;;;;;;;;EAkBR;IACE,MAAI,KAAA,QAAA,KAAA;;;;;;;;;;;EAMN;IACE,QAAM,KAAA;;;;;;;;;;;;;;;;;;;;;;;EAoBR;IACE,QAAM,KAAA;;;;;;;;;;;;;;;;;;EAcR;IACE,QAAM,KAAA,OAAA,KAAA;;;;;;;;;;;;;EAiBR;IAAsB,QAAM,KAAA,OAAA,KAAA;;;;;EAC5B;IAA8B,QAAM,KAAA,OAAA,KAAA,QAAA,KAAA,iBAAA,KAAA,qBAAA,KAAA,iBAAA,KAAA,oBAAA,KAAA,kBAAA,KAAA,iBAAA,KAAA;;EACpC;IAAW,MAAI,KAAA;;;IAAuD,QAAM,KAAA,QAAA;;EAC5E;IAAW,MAAI,KAAA;;EACf;IAAa,MAAI,KAAA,OAAA,KAAA;;;;;;;;;qBClQN"}
@@ -0,0 +1,7 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_protocolContracts = require("./src/schemas/protocolContracts.cjs");
3
+ const require_index = require("./src/services/chordAdapter/index.cjs");
4
+ exports.createProtocolClient = require_index.createProtocolClient;
5
+ exports.createTextLink = require_protocolContracts.createTextLink;
6
+ exports.memoryLinkPair = require_index.memoryLinkPair;
7
+ exports.webSocketLink = require_protocolContracts.webSocketLink;
@@ -0,0 +1,3 @@
1
+ import { ProtocolClient, ProtocolLink, TextLinkOptions, WebSocketLike, createTextLink, webSocketLink } from "./src/schemas/protocolContracts.mjs";
2
+ import { createProtocolClient, memoryLinkPair } from "./src/services/chordAdapter/index.mjs";
3
+ export { type ProtocolClient, type ProtocolLink, type TextLinkOptions, type WebSocketLike, createProtocolClient, createTextLink, memoryLinkPair, webSocketLink };
@@ -0,0 +1,3 @@
1
+ import { createTextLink, webSocketLink } from "./src/schemas/protocolContracts.mjs";
2
+ import { createProtocolClient, memoryLinkPair } from "./src/services/chordAdapter/index.mjs";
3
+ export { createProtocolClient, createTextLink, memoryLinkPair, webSocketLink };
@@ -1 +1 @@
1
- {"version":3,"file":"platform.cjs","names":[],"sources":["../../../src/schemas/platform.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport type { Context as IoContext } from '@earendil-works/chord/context';\nimport type { AuthResult, ModelsStoreEntry, ModelType } from '@earendil-works/pi-ai';\nimport type { Storage } from '@earendil-works/pi-durable';\nimport type { ExecutionEnv, FileSystem, Shell } from '@earendil-works/pi-durable/env';\nimport type { SqliteDatabase } from '@earendil-works/pi-durable/storage/sqlite';\n\nexport const PO_FS_SERVICE = 'po/fs';\nexport const PO_SHELL_SERVICE = 'po/shell';\nexport const PO_SQLITE_SERVICE = 'po/sqlite';\nexport const PO_SESSION_STORAGE_SERVICE = 'po/session-storage';\nexport const PO_ISOLATE_SERVICE = 'po/isolate';\nexport const PO_NPM_SERVICE = 'po/npm';\nexport const PO_ELECTRON_SERVICE = 'po/electron';\nexport const PO_BROWSER_SERVICE = 'po/browser';\nexport const PO_BROWSER_SESSION_SERVICE = 'po/browser-session';\nexport const PO_PROVIDER_AUTH_SERVICE = 'po/provider-auth';\n\n/** Host-owned npm installation and native module loading. */\nexport interface PoNpm {\n import(specifier: string, options: { sessionId: string; signal?: AbortSignal }): Promise<Record<string, unknown>>;\n}\n\n/** One page for the Desktop's Electron to render: a loopback `http:` or a `file:` URL. */\nexport interface PoElectronCaptureRequest {\n readonly url: string;\n readonly width: number;\n readonly height: number;\n readonly fullPage: boolean;\n readonly darkMode: boolean;\n readonly mobile: boolean;\n /** Extra settle time after the story mounted, in milliseconds. */\n readonly waitTime: number;\n}\n\n/** Electron capabilities of Po Desktop's main process; bound only while the server runs under Desktop. */\nexport interface PoElectronService {\n readonly abiVersion: 1;\n /**\n * Renders a story page in a hidden window and returns its PNG as base64. Rejects with\n * `Story failed in the browser: ...` when the page throws, shows Vite's error overlay, or mounts nothing.\n */\n capturePage(request: PoElectronCaptureRequest, signal?: AbortSignal): Promise<{ png: string }>;\n}\n\n/** A page the host rendered: its final URL after the host's checks, and its title. */\nexport interface PoBrowserPageInfo {\n readonly url: string;\n /** HTTP status of the main document, when the browser saw one. */\n readonly status?: number;\n readonly title: string;\n}\n\nexport interface PoBrowserScreenshotRequest {\n readonly url: string;\n /** The whole scrollable page, clipped by the host's height cap, instead of the viewport. */\n readonly fullPage?: boolean;\n}\n\n/**\n * A remote headless browser for one session, bound only on hosts that offer one (Cloudflare Browser\n * Rendering behind `PO_CLOUD_WEB`). The host owns the outbound policy, page timeout, size caps and quota;\n * each call rejects with a message that names the refusal.\n */\nexport interface PoBrowserService {\n readonly abiVersion: 1;\n /** The rendered page's visible text, capped by the host. */\n fetchPage(url: string, signal?: AbortSignal): Promise<PoBrowserPageInfo & { text: string; truncated: boolean }>;\n /** The rendered DOM as HTML plus its links, each capped by the host. */\n snapshot(\n url: string,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { html: string; links: { text: string; href: string }[]; truncated: boolean }>;\n /** A PNG of the rendered page as base64, refused past the host's byte cap. */\n screenshot(\n request: PoBrowserScreenshotRequest,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { data: string; mimeType: 'image/png' }>;\n}\n\n/** What an action aims at: a CSS selector, visible text, or an ARIA role with an optional accessible name. */\nexport type PoBrowserTarget =\n | { readonly selector: string }\n | { readonly text: string }\n | { readonly role: string; readonly name?: string };\n\n/** One open tab of the session's browser. `pageId` is stable for the life of the remote browser. */\nexport interface PoBrowserTab extends PoBrowserPageInfo {\n readonly pageId: string;\n}\n\nexport type PoBrowserHandoffState = 'pending' | 'done' | 'failed' | 'timedOut';\n\n/**\n * One persistent remote browser for one session, bound only on hosts that offer one. Tabs and sign-ins\n * survive between calls until the host's idle window closes the browser. The host owns the outbound\n * policy (every navigation, popups included), deadlines, size caps, quota and reconnect after a restart;\n * every call is JSON in, JSON out. `navigate` reports `reconnected: false` once the previous browser was\n * lost, so its tabs and sign-ins are gone.\n */\nexport interface PoBrowserSessionService {\n readonly abiVersion: 1;\n navigate(\n input: { readonly url: string; readonly pageId?: string; readonly newPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly reconnected?: false; readonly reason?: string }>;\n snapshot(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<\n PoBrowserTab & {\n readonly text: string;\n readonly aria: string;\n readonly links: readonly { readonly text: string; readonly href: string }[];\n readonly truncated: boolean;\n }\n >;\n click(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n /** Refuses password fields: the person types those during a handoff. */\n fill(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget; readonly value: string },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n pressKey(input: { readonly pageId?: string; readonly key: string }, signal?: AbortSignal): Promise<PoBrowserTab>;\n screenshot(\n input: { readonly pageId?: string; readonly fullPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly data: string; readonly mimeType: 'image/png' }>;\n listPages(signal?: AbortSignal): Promise<readonly PoBrowserTab[]>;\n closePage(input: { readonly pageId?: string }, signal?: AbortSignal): Promise<void>;\n /** Closes the remote browser and stops metering. Safe to call when nothing is open. */\n close(): Promise<void>;\n /** A short-lived link that lets a person watch and control one tab. A bearer secret: never log it. */\n liveView(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<{ readonly url: string; readonly expiresAt: string }>;\n /** Asks a person to act on a tab (sign-in, MFA, CAPTCHA) and returns at once; poll `handoffStatus`. */\n handoff(\n input: { readonly instructions: string; readonly pageId?: string; readonly timeoutMs?: number },\n signal?: AbortSignal,\n ): Promise<{ readonly handoffId: string; readonly liveViewUrl: string; readonly expiresAt: string }>;\n handoffStatus(\n input: { readonly handoffId: string },\n signal?: AbortSignal,\n ): Promise<{ readonly state: PoBrowserHandoffState; readonly tab?: PoBrowserTab }>;\n}\n\nexport interface PoSqliteService {\n readonly abiVersion: 1;\n /** Node: the database file at this path. Edge: the owning Durable Object's single database. */\n open(file: string, context: IoContext): Promise<SqliteDatabase>;\n}\n\n/** One agent session's storage, held by a single writer until released. */\nexport interface PoSessionStorage {\n readonly storage: Storage;\n /** Throws once another writer may own the session; checked before every write. */\n assertWritable(): void | Promise<void>;\n /** Closes `storage` and gives the session up, after its harness closed. */\n release(context: IoContext): Promise<void>;\n}\n\nexport interface PoSessionStorageRequest {\n /** Omitted for a new session, which gets a fresh id. */\n readonly sessionId?: string;\n /** Recorded on a new session. */\n readonly parentSessionId?: string;\n /** Resume only: refuse to create a session that was never stored. */\n readonly existing?: boolean;\n}\n\nexport interface PoStoredSession {\n readonly sessionId: string;\n /** Epoch milliseconds of the session's last write. */\n readonly updatedAt: number;\n}\n\n/**\n * Where agent sessions live, keyed by session id: one SQLite file per session on Node, the\n * Durable Object's own SQLite on the edge. Callers never see a file, a path or a database.\n */\nexport interface PoSessionStorageService {\n readonly abiVersion: 1;\n open(request: PoSessionStorageRequest, context: IoContext): Promise<PoSessionStorage>;\n /** A stored session without taking ownership or migrating it. The caller closes the storage. */\n openReadOnly(sessionId: string, context: IoContext): Promise<Storage>;\n list(context: IoContext): Promise<readonly PoStoredSession[]>;\n /**\n * Deletes a stored session behind its ownership lease. `'busy'` while a live owner holds it;\n * an already missing session is `'removed'`. Hosts without teardown leave it out.\n */\n remove?(sessionId: string, context: IoContext): Promise<'removed' | 'busy'>;\n}\n\n/** One script run: the source, the globals it may see, and its limits. */\nexport interface PoIsolateRequest {\n /** TypeScript where the host compiles it (Node), plain JavaScript otherwise (edge). */\n readonly source: string;\n /** Names visible to the script. Live objects on hosts with `liveObjects`, JSON functions otherwise. */\n readonly globals: Readonly<Record<string, unknown>>;\n readonly deadlineMs: number;\n readonly signal: AbortSignal;\n /** Heap cap; only hosts with a separate heap honour it. */\n readonly memoryLimitBytes?: number;\n /** Member names hidden on every live object the script reaches; only hosts with `liveObjects` apply it. */\n readonly deny?: readonly string[];\n /** Problems the script cannot see, such as a throwing callback it passed to a live object. */\n readonly onDiagnostic?: (message: string) => void;\n /**\n * Loads the body behind `await import(specifier)`; `id` names it in errors and caches it per run.\n * Without it, or on hosts that cannot import, `import()` rejects.\n */\n readonly resolveImport?: (\n specifier: string,\n ) => Promise<\n | { readonly kind?: 'script'; readonly id: string; readonly source: string }\n | { readonly kind: 'module'; readonly id: string; readonly exports: Record<string, unknown> }\n >;\n}\n\nexport type PoIsolateErrorKind = 'timeout' | 'aborted' | 'compile' | 'error';\n\nexport type PoIsolateResult =\n | { readonly ok: true; readonly value: unknown }\n | {\n readonly ok: false;\n readonly error: {\n readonly kind: PoIsolateErrorKind;\n readonly name: string;\n readonly message: string;\n /** 1-based line in the submitted source, when known. */\n readonly line?: number;\n readonly stack?: string;\n };\n };\n\n/**\n * Runs model-written code with injected globals. Node binds a main-thread `vm` context that can\n * hold live objects (not a security boundary); the edge binds a QuickJS sandbox limited to JSON.\n */\nexport interface PoIsolateService {\n readonly abiVersion: 1;\n /** True when globals are passed by reference, so live objects work. */\n readonly liveObjects: boolean;\n run(request: PoIsolateRequest): Promise<PoIsolateResult>;\n}\n\n/** An OpenAI- or Anthropic-compatible endpoint added by hand. Holds no secret: its key is a stored credential. */\nexport interface PoCustomProviderDefinition {\n readonly id: string;\n readonly name: string;\n /** `http:` or `https:`, without userinfo or a query string. */\n readonly baseUrl: string;\n readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';\n readonly models: readonly {\n readonly id: string;\n readonly name?: string;\n readonly reasoning?: boolean;\n readonly input?: readonly ('text' | 'image')[];\n readonly contextWindow?: number;\n readonly maxTokens?: number;\n }[];\n}\n\n/** What the credential owner tells sessions: never a key, token, header or URL secret. */\nexport interface PoProviderAuthSnapshot {\n /** Changes whenever anything below changes; compare with `!==`, as an owner restart starts afresh. */\n readonly version: number;\n /** Configured providers only; every other provider is unconfigured. */\n readonly providers: readonly {\n readonly id: string;\n readonly type: 'api_key' | 'oauth';\n readonly source?: string;\n readonly subscription: boolean;\n }[];\n /** Models of every type the deployment target can use, after each provider's credential filter. */\n readonly available: readonly { readonly provider: string; readonly id: string; readonly type: ModelType }[];\n /** Dynamic catalogs by provider id, with headers and URL secrets removed. */\n readonly models: Readonly<Record<string, ModelsStoreEntry>>;\n readonly customProviders: readonly PoCustomProviderDefinition[];\n}\n\n/**\n * Provider credentials held by one owner per deployment target (the org on hosted Po), for hosts\n * whose sessions must never store them. Node leaves it unbound: `auth.json` is the authority there.\n */\nexport interface PoProviderAuth {\n readonly abiVersion: 1;\n /**\n * Provider-level auth for one request, resolved like local `Models.getAuth` (stored OAuth refreshed,\n * then the stored key) and never persisted by the caller. `version` is the owner's snapshot version.\n */\n resolveAuth(provider: string): Promise<{ readonly version: number; readonly auth?: AuthResult }>;\n /** The full snapshot, or just `{ version }` while `sinceVersion` is still current. */\n snapshot(sinceVersion?: number): Promise<PoProviderAuthSnapshot | { readonly version: number }>;\n refresh(options?: {\n readonly allowNetwork?: boolean;\n }): Promise<{ readonly version: number; readonly errors: Readonly<Record<string, string>> }>;\n}\n\n/** Host capabilities one composition root runs on: Node in the CLI, a Durable Object on the edge. */\nexport interface PoPlatform {\n readonly abiVersion: 1;\n readonly homeDirectory: string;\n /** Host-selected base for session output; absent on older embedding platforms. */\n readonly temporaryDirectory?: string;\n /** Files and shell rooted at `cwd`; pi-durable `FileSystem` and `Shell`. */\n env(cwd: string): ExecutionEnv;\n readonly sqlite: PoSqliteService;\n readonly sessions: PoSessionStorageService;\n /** Script runner for code mode; absent on hosts that do not bind one. */\n readonly isolate?: PoIsolateService;\n /** Native npm loader; absent on hosts without Node package support. */\n readonly npm?: PoNpm;\n /** Po Desktop's Electron; absent unless the server runs under Desktop. */\n readonly electron?: PoElectronService;\n /** Remote headless browser; absent unless the host offers one and its operator turned it on. */\n readonly browser?: PoBrowserService;\n /** One persistent remote browser per session; absent unless the host offers one and its operator turned it on. */\n readonly browserSession?: PoBrowserSessionService;\n /** Owner-held provider credentials; absent where the session's own runtime holds them (Node). */\n readonly providerAuth?: PoProviderAuth;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/fs': FileSystem;\n 'po/shell': Shell;\n 'po/sqlite': PoSqliteService;\n 'po/session-storage': PoSessionStorageService;\n 'po/isolate': PoIsolateService;\n 'po/npm': PoNpm;\n 'po/electron': PoElectronService;\n 'po/browser': PoBrowserService;\n 'po/browser-session': PoBrowserSessionService;\n 'po/provider-auth': PoProviderAuth;\n 'po/session-files': { readonly temporaryDirectory: string };\n }\n}\n\nexport function readPoFs(context: Context): FileSystem | undefined {\n return context.get(PO_FS_SERVICE) as FileSystem | undefined;\n}\n\nexport function requirePoFs(context: Context): FileSystem {\n const service = readPoFs(context);\n if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoShell(context: Context): Shell {\n const service = context.get(PO_SHELL_SERVICE) as Shell | undefined;\n if (!service) throw new Error(`The '${PO_SHELL_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoSqlite(context: Context): PoSqliteService {\n const service = context.get(PO_SQLITE_SERVICE) as PoSqliteService | undefined;\n if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function readPoNpm(context: Context): PoNpm | undefined {\n return context.get(PO_NPM_SERVICE) as PoNpm | undefined;\n}\n\nexport function readPoElectron(context: Context): PoElectronService | undefined {\n return context.get(PO_ELECTRON_SERVICE) as PoElectronService | undefined;\n}\n\nexport function readPoBrowser(context: Context): PoBrowserService | undefined {\n return context.get(PO_BROWSER_SERVICE) as PoBrowserService | undefined;\n}\n\nexport function readPoBrowserSession(context: Context): PoBrowserSessionService | undefined {\n return context.get(PO_BROWSER_SESSION_SERVICE) as PoBrowserSessionService | undefined;\n}\n\nexport function readPoProviderAuth(context: Context): PoProviderAuth | undefined {\n return context.get(PO_PROVIDER_AUTH_SERVICE) as PoProviderAuth | undefined;\n}\n\nexport function readPoIsolate(context: Context): PoIsolateService | undefined {\n return context.get(PO_ISOLATE_SERVICE) as PoIsolateService | undefined;\n}\n\nexport function requirePoIsolate(context: Context): PoIsolateService {\n const service = readPoIsolate(context);\n if (!service) throw new Error(`The '${PO_ISOLATE_SERVICE}' service is unavailable on this host.`);\n return service;\n}\n"],"mappings":";AAOA,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;AACjC,MAAa,6BAA6B;AAC1C,MAAa,qBAAqB;AAClC,MAAa,iBAAiB;AAC9B,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAClC,MAAa,6BAA6B;AAC1C,MAAa,2BAA2B;AAwUxC,SAAgB,SAAS,SAA0C;CACjE,OAAO,QAAQ,IAAI,aAAa;AAClC;AAEA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,SAAS,OAAO;CAChC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,cAAc,mDAAmD;CACvG,OAAO;AACT;AAEA,SAAgB,eAAe,SAAyB;CACtD,MAAM,UAAU,QAAQ,IAAI,gBAAgB;CAC5C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,iBAAiB,mDAAmD;CAC1G,OAAO;AACT;AAEA,SAAgB,gBAAgB,SAAmC;CACjE,MAAM,UAAU,QAAQ,IAAI,iBAAiB;CAC7C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,kBAAkB,mDAAmD;CAC3G,OAAO;AACT;AAEA,SAAgB,UAAU,SAAqC;CAC7D,OAAO,QAAQ,IAAI,cAAc;AACnC;AAEA,SAAgB,eAAe,SAAiD;CAC9E,OAAO,QAAQ,IAAI,mBAAmB;AACxC;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,qBAAqB,SAAuD;CAC1F,OAAO,QAAQ,IAAI,0BAA0B;AAC/C;AAEA,SAAgB,mBAAmB,SAA8C;CAC/E,OAAO,QAAQ,IAAI,wBAAwB;AAC7C;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,iBAAiB,SAAoC;CACnE,MAAM,UAAU,cAAc,OAAO;CACrC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,mBAAmB,uCAAuC;CAChG,OAAO;AACT"}
1
+ {"version":3,"file":"platform.cjs","names":[],"sources":["../../../src/schemas/platform.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport type { Context as IoContext } from '@earendil-works/chord/context';\nimport type { AuthResult, ModelsStoreEntry, ModelType } from '@earendil-works/pi-ai';\nimport type { Storage } from '@earendil-works/pi-durable';\nimport type { ExecutionEnv, FileSystem, Shell } from '@earendil-works/pi-durable/env';\nimport type { SqliteDatabase } from '@earendil-works/pi-durable/storage/sqlite';\n\nexport const PO_FS_SERVICE = 'po/fs';\nexport const PO_SHELL_SERVICE = 'po/shell';\nexport const PO_SQLITE_SERVICE = 'po/sqlite';\nexport const PO_SESSION_STORAGE_SERVICE = 'po/session-storage';\nexport const PO_ISOLATE_SERVICE = 'po/isolate';\nexport const PO_NPM_SERVICE = 'po/npm';\nexport const PO_ELECTRON_SERVICE = 'po/electron';\nexport const PO_BROWSER_SERVICE = 'po/browser';\nexport const PO_BROWSER_SESSION_SERVICE = 'po/browser-session';\nexport const PO_PROVIDER_AUTH_SERVICE = 'po/provider-auth';\n\n/** Host-owned npm installation and native module loading. */\nexport interface PoNpm {\n import(specifier: string, options: { sessionId: string; signal?: AbortSignal }): Promise<Record<string, unknown>>;\n}\n\n/** One page for the Desktop's Electron to render: a loopback `http:` or a `file:` URL. */\nexport interface PoElectronCaptureRequest {\n readonly url: string;\n readonly width: number;\n readonly height: number;\n readonly fullPage: boolean;\n readonly darkMode: boolean;\n readonly mobile: boolean;\n /** Extra settle time after the story mounted, in milliseconds. */\n readonly waitTime: number;\n}\n\n/** Electron capabilities of Po Desktop's main process; bound only while the server runs under Desktop. */\nexport interface PoElectronService {\n readonly abiVersion: 1;\n /**\n * Renders a story page in a hidden window and returns its PNG as base64. Rejects with\n * `Story failed in the browser: ...` when the page throws, shows Vite's error overlay, or mounts nothing.\n */\n capturePage(request: PoElectronCaptureRequest, signal?: AbortSignal): Promise<{ png: string }>;\n}\n\n/** A page the host rendered: its final URL after the host's checks, and its title. */\nexport interface PoBrowserPageInfo {\n readonly url: string;\n /** HTTP status of the main document, when the browser saw one. */\n readonly status?: number;\n readonly title: string;\n}\n\nexport interface PoBrowserScreenshotRequest {\n readonly url: string;\n /** The whole scrollable page, clipped by the host's height cap, instead of the viewport. */\n readonly fullPage?: boolean;\n}\n\n/**\n * A remote headless browser for one session, bound only on hosts that offer one (Cloudflare Browser\n * Rendering behind `PO_CLOUD_WEB`). The host owns the outbound policy, page timeout, size caps and quota;\n * each call rejects with a message that names the refusal.\n */\nexport interface PoBrowserService {\n readonly abiVersion: 1;\n /** The rendered page's visible text, capped by the host. */\n fetchPage(url: string, signal?: AbortSignal): Promise<PoBrowserPageInfo & { text: string; truncated: boolean }>;\n /** The rendered DOM as HTML plus its links, each capped by the host. */\n snapshot(\n url: string,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { html: string; links: { text: string; href: string }[]; truncated: boolean }>;\n /** A PNG of the rendered page as base64, refused past the host's byte cap. */\n screenshot(\n request: PoBrowserScreenshotRequest,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { data: string; mimeType: 'image/png' }>;\n}\n\n/** What an action aims at: a CSS selector, visible text, or an ARIA role with an optional accessible name. */\nexport type PoBrowserTarget =\n | { readonly selector: string }\n | { readonly text: string }\n | { readonly role: string; readonly name?: string };\n\n/** One open tab of the session's browser. `pageId` is stable for the life of the remote browser. */\nexport interface PoBrowserTab extends PoBrowserPageInfo {\n readonly pageId: string;\n}\n\nexport type PoBrowserHandoffState = 'pending' | 'done' | 'failed' | 'timedOut';\n\n/**\n * One persistent remote browser for one session, bound only on hosts that offer one. Tabs and sign-ins\n * survive between calls until the host's idle window closes the browser. The host owns the outbound\n * policy (every navigation, popups included), deadlines, size caps, quota and reconnect after a restart;\n * every call is JSON in, JSON out. `navigate` reports `reconnected: false` once the previous browser was\n * lost, so its tabs and sign-ins are gone.\n */\nexport interface PoBrowserSessionService {\n readonly abiVersion: 1;\n navigate(\n input: { readonly url: string; readonly pageId?: string; readonly newPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly reconnected?: false; readonly reason?: string }>;\n snapshot(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<\n PoBrowserTab & {\n readonly text: string;\n readonly aria: string;\n readonly links: readonly { readonly text: string; readonly href: string }[];\n readonly truncated: boolean;\n }\n >;\n click(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n /** Refuses password fields: the person types those during a handoff. */\n fill(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget; readonly value: string },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n pressKey(input: { readonly pageId?: string; readonly key: string }, signal?: AbortSignal): Promise<PoBrowserTab>;\n screenshot(\n input: { readonly pageId?: string; readonly fullPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly data: string; readonly mimeType: 'image/png' }>;\n listPages(signal?: AbortSignal): Promise<readonly PoBrowserTab[]>;\n closePage(input: { readonly pageId?: string }, signal?: AbortSignal): Promise<void>;\n /** Closes the remote browser and stops metering. Safe to call when nothing is open. */\n close(): Promise<void>;\n /** A short-lived link that lets a person watch and control one tab. A bearer secret: never log it. */\n liveView(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<{ readonly url: string; readonly expiresAt: string }>;\n /** Asks a person to act on a tab (sign-in, MFA, CAPTCHA) and returns at once; poll `handoffStatus`. */\n handoff(\n input: { readonly instructions: string; readonly pageId?: string; readonly timeoutMs?: number },\n signal?: AbortSignal,\n ): Promise<{ readonly handoffId: string; readonly liveViewUrl: string; readonly expiresAt: string }>;\n handoffStatus(\n input: { readonly handoffId: string },\n signal?: AbortSignal,\n ): Promise<{ readonly state: PoBrowserHandoffState; readonly tab?: PoBrowserTab }>;\n}\n\nexport interface PoSqliteService {\n readonly abiVersion: 1;\n /** Node: the database file at this path. Edge: the owning Durable Object's single database. */\n open(file: string, context: IoContext): Promise<SqliteDatabase>;\n}\n\n/** One agent session's storage, held by a single writer until released. */\nexport interface PoSessionStorage {\n readonly storage: Storage;\n /** Throws once another writer may own the session; checked before every write. */\n assertWritable(): void | Promise<void>;\n /** Closes `storage` and gives the session up, after its harness closed. */\n release(context: IoContext): Promise<void>;\n}\n\nexport interface PoSessionStorageRequest {\n /** Omitted for a new session, which gets a fresh id. */\n readonly sessionId?: string;\n /** Recorded on a new session. */\n readonly parentSessionId?: string;\n /** Resume only: refuse to create a session that was never stored. */\n readonly existing?: boolean;\n}\n\nexport interface PoStoredSession {\n readonly sessionId: string;\n /** Epoch milliseconds of the session's last write. */\n readonly updatedAt: number;\n}\n\n/**\n * Where agent sessions live, keyed by session id: one SQLite file per session on Node, the\n * Durable Object's own SQLite on the edge. Callers never see a file, a path or a database.\n */\nexport interface PoSessionStorageService {\n readonly abiVersion: 1;\n open(request: PoSessionStorageRequest, context: IoContext): Promise<PoSessionStorage>;\n /** A stored session without taking ownership or migrating it. The caller closes the storage. */\n openReadOnly(sessionId: string, context: IoContext): Promise<Storage>;\n list(context: IoContext): Promise<readonly PoStoredSession[]>;\n /**\n * Deletes a stored session behind its ownership lease. `'busy'` while a live owner holds it;\n * an already missing session is `'removed'`. Hosts without teardown leave it out.\n */\n remove?(sessionId: string, context: IoContext): Promise<'removed' | 'busy'>;\n}\n\n/** One script run: the source, the globals it may see, and its limits. */\nexport interface PoIsolateRequest {\n /** TypeScript where the host compiles it (Node), plain JavaScript otherwise (edge). */\n readonly source: string;\n /** Names visible to the script. Live objects on hosts with `liveObjects`, JSON functions otherwise. */\n readonly globals: Readonly<Record<string, unknown>>;\n readonly deadlineMs: number;\n readonly signal: AbortSignal;\n /** Heap cap; only hosts with a separate heap honour it. */\n readonly memoryLimitBytes?: number;\n /** Member names hidden on every live object the script reaches; only hosts with `liveObjects` apply it. */\n readonly deny?: readonly string[];\n /** Problems the script cannot see, such as a throwing callback it passed to a live object. */\n readonly onDiagnostic?: (message: string) => void;\n /**\n * Loads the body behind `await import(specifier)`; `id` names it in errors and caches it per run.\n * Without it, or on hosts that cannot import, `import()` rejects.\n */\n readonly resolveImport?: (\n specifier: string,\n ) => Promise<\n | { readonly kind?: 'script'; readonly id: string; readonly source: string }\n | { readonly kind: 'module'; readonly id: string; readonly exports: Record<string, unknown> }\n >;\n}\n\nexport type PoIsolateErrorKind = 'timeout' | 'aborted' | 'compile' | 'error';\n\nexport type PoIsolateResult =\n | { readonly ok: true; readonly value: unknown }\n | {\n readonly ok: false;\n readonly error: {\n readonly kind: PoIsolateErrorKind;\n readonly name: string;\n readonly message: string;\n /** 1-based line in the submitted source, when known. */\n readonly line?: number;\n readonly stack?: string;\n };\n };\n\n/**\n * Runs model-written code with injected globals. Node binds a main-thread `vm` context that can\n * hold live objects (not a security boundary); the edge binds a QuickJS sandbox limited to JSON.\n */\nexport interface PoIsolateService {\n readonly abiVersion: 1;\n /** True when globals are passed by reference, so live objects work. */\n readonly liveObjects: boolean;\n run(request: PoIsolateRequest): Promise<PoIsolateResult>;\n}\n\n/** An OpenAI- or Anthropic-compatible endpoint added by hand. Holds no secret: its key is a stored credential. */\nexport interface PoCustomProviderDefinition {\n readonly id: string;\n readonly name: string;\n /** `http:` or `https:`, without userinfo or a query string. */\n readonly baseUrl: string;\n readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';\n /**\n * `openai-completions` only: send `tools: []` once the conversation holds tool calls but the turn offers\n * no tools, for proxies such as LiteLLM that reject tool history without a tools list.\n */\n readonly requiresToolsWithToolHistory?: boolean;\n readonly models: readonly {\n readonly id: string;\n readonly name?: string;\n readonly reasoning?: boolean;\n readonly input?: readonly ('text' | 'image')[];\n readonly contextWindow?: number;\n readonly maxTokens?: number;\n }[];\n}\n\n/** What the credential owner tells sessions: never a key, token, header or URL secret. */\nexport interface PoProviderAuthSnapshot {\n /** Changes whenever anything below changes; compare with `!==`, as an owner restart starts afresh. */\n readonly version: number;\n /** Configured providers only; every other provider is unconfigured. */\n readonly providers: readonly {\n readonly id: string;\n readonly type: 'api_key' | 'oauth';\n readonly source?: string;\n readonly subscription: boolean;\n }[];\n /** Models of every type the deployment target can use, after each provider's credential filter. */\n readonly available: readonly { readonly provider: string; readonly id: string; readonly type: ModelType }[];\n /** Dynamic catalogs by provider id, with headers and URL secrets removed. */\n readonly models: Readonly<Record<string, ModelsStoreEntry>>;\n readonly customProviders: readonly PoCustomProviderDefinition[];\n}\n\n/**\n * Provider credentials held by one owner per deployment target (the org on hosted Po), for hosts\n * whose sessions must never store them. Node leaves it unbound: `auth.json` is the authority there.\n */\nexport interface PoProviderAuth {\n readonly abiVersion: 1;\n /**\n * Provider-level auth for one request, resolved like local `Models.getAuth` (stored OAuth refreshed,\n * then the stored key) and never persisted by the caller. `version` is the owner's snapshot version.\n */\n resolveAuth(provider: string): Promise<{ readonly version: number; readonly auth?: AuthResult }>;\n /** The full snapshot, or just `{ version }` while `sinceVersion` is still current. */\n snapshot(sinceVersion?: number): Promise<PoProviderAuthSnapshot | { readonly version: number }>;\n refresh(options?: {\n readonly allowNetwork?: boolean;\n }): Promise<{ readonly version: number; readonly errors: Readonly<Record<string, string>> }>;\n}\n\n/** Host capabilities one composition root runs on: Node in the CLI, a Durable Object on the edge. */\nexport interface PoPlatform {\n readonly abiVersion: 1;\n readonly homeDirectory: string;\n /** Host-selected base for session output; absent on older embedding platforms. */\n readonly temporaryDirectory?: string;\n /** Files and shell rooted at `cwd`; pi-durable `FileSystem` and `Shell`. */\n env(cwd: string): ExecutionEnv;\n readonly sqlite: PoSqliteService;\n readonly sessions: PoSessionStorageService;\n /** Script runner for code mode; absent on hosts that do not bind one. */\n readonly isolate?: PoIsolateService;\n /** Native npm loader; absent on hosts without Node package support. */\n readonly npm?: PoNpm;\n /** Po Desktop's Electron; absent unless the server runs under Desktop. */\n readonly electron?: PoElectronService;\n /** Remote headless browser; absent unless the host offers one and its operator turned it on. */\n readonly browser?: PoBrowserService;\n /** One persistent remote browser per session; absent unless the host offers one and its operator turned it on. */\n readonly browserSession?: PoBrowserSessionService;\n /** Owner-held provider credentials; absent where the session's own runtime holds them (Node). */\n readonly providerAuth?: PoProviderAuth;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/fs': FileSystem;\n 'po/shell': Shell;\n 'po/sqlite': PoSqliteService;\n 'po/session-storage': PoSessionStorageService;\n 'po/isolate': PoIsolateService;\n 'po/npm': PoNpm;\n 'po/electron': PoElectronService;\n 'po/browser': PoBrowserService;\n 'po/browser-session': PoBrowserSessionService;\n 'po/provider-auth': PoProviderAuth;\n 'po/session-files': { readonly temporaryDirectory: string };\n }\n}\n\nexport function readPoFs(context: Context): FileSystem | undefined {\n return context.get(PO_FS_SERVICE) as FileSystem | undefined;\n}\n\nexport function requirePoFs(context: Context): FileSystem {\n const service = readPoFs(context);\n if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoShell(context: Context): Shell {\n const service = context.get(PO_SHELL_SERVICE) as Shell | undefined;\n if (!service) throw new Error(`The '${PO_SHELL_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoSqlite(context: Context): PoSqliteService {\n const service = context.get(PO_SQLITE_SERVICE) as PoSqliteService | undefined;\n if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function readPoNpm(context: Context): PoNpm | undefined {\n return context.get(PO_NPM_SERVICE) as PoNpm | undefined;\n}\n\nexport function readPoElectron(context: Context): PoElectronService | undefined {\n return context.get(PO_ELECTRON_SERVICE) as PoElectronService | undefined;\n}\n\nexport function readPoBrowser(context: Context): PoBrowserService | undefined {\n return context.get(PO_BROWSER_SERVICE) as PoBrowserService | undefined;\n}\n\nexport function readPoBrowserSession(context: Context): PoBrowserSessionService | undefined {\n return context.get(PO_BROWSER_SESSION_SERVICE) as PoBrowserSessionService | undefined;\n}\n\nexport function readPoProviderAuth(context: Context): PoProviderAuth | undefined {\n return context.get(PO_PROVIDER_AUTH_SERVICE) as PoProviderAuth | undefined;\n}\n\nexport function readPoIsolate(context: Context): PoIsolateService | undefined {\n return context.get(PO_ISOLATE_SERVICE) as PoIsolateService | undefined;\n}\n\nexport function requirePoIsolate(context: Context): PoIsolateService {\n const service = readPoIsolate(context);\n if (!service) throw new Error(`The '${PO_ISOLATE_SERVICE}' service is unavailable on this host.`);\n return service;\n}\n"],"mappings":";AAOA,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;AACjC,MAAa,6BAA6B;AAC1C,MAAa,qBAAqB;AAClC,MAAa,iBAAiB;AAC9B,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAClC,MAAa,6BAA6B;AAC1C,MAAa,2BAA2B;AA6UxC,SAAgB,SAAS,SAA0C;CACjE,OAAO,QAAQ,IAAI,aAAa;AAClC;AAEA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,SAAS,OAAO;CAChC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,cAAc,mDAAmD;CACvG,OAAO;AACT;AAEA,SAAgB,eAAe,SAAyB;CACtD,MAAM,UAAU,QAAQ,IAAI,gBAAgB;CAC5C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,iBAAiB,mDAAmD;CAC1G,OAAO;AACT;AAEA,SAAgB,gBAAgB,SAAmC;CACjE,MAAM,UAAU,QAAQ,IAAI,iBAAiB;CAC7C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,kBAAkB,mDAAmD;CAC3G,OAAO;AACT;AAEA,SAAgB,UAAU,SAAqC;CAC7D,OAAO,QAAQ,IAAI,cAAc;AACnC;AAEA,SAAgB,eAAe,SAAiD;CAC9E,OAAO,QAAQ,IAAI,mBAAmB;AACxC;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,qBAAqB,SAAuD;CAC1F,OAAO,QAAQ,IAAI,0BAA0B;AAC/C;AAEA,SAAgB,mBAAmB,SAA8C;CAC/E,OAAO,QAAQ,IAAI,wBAAwB;AAC7C;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,iBAAiB,SAAoC;CACnE,MAAM,UAAU,cAAc,OAAO;CACrC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,mBAAmB,uCAAuC;CAChG,OAAO;AACT"}
@@ -278,6 +278,11 @@ export interface PoCustomProviderDefinition {
278
278
  /** `http:` or `https:`, without userinfo or a query string. */
279
279
  readonly baseUrl: string;
280
280
  readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';
281
+ /**
282
+ * `openai-completions` only: send `tools: []` once the conversation holds tool calls but the turn offers
283
+ * no tools, for proxies such as LiteLLM that reject tool history without a tools list.
284
+ */
285
+ readonly requiresToolsWithToolHistory?: boolean;
281
286
  readonly models: readonly {
282
287
  readonly id: string;
283
288
  readonly name?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"platform.d.mts","names":["IoContext","Context"],"sources":["../../../src/schemas/platform.ts"],"mappings":";;;;;;;qBAOa;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;;iBAGI;EACf,OAAO,mBAAmB;IAAW;IAAmB,SAAS;MAAgB,QAAQ;;;iBAI1E;WACN;WACA;WACA;WACA;WACA;WACA;;WAEA;;;iBAIM;WACN;;;;;EAKT,YAAY,SAAS,0BAA0B,SAAS,cAAc;IAAU;;;;iBAIjE;WACN;;WAEA;WACA;;iBAGM;WACN;;WAEA;;;;;;;iBAQM;WACN;;EAET,UAAU,aAAa,SAAS,cAAc,QAAQ;IAAsB;IAAc;;;EAE1F,SACE,aACA,SAAS,cACR,QAAQ;IAAsB;IAAc;MAAS;MAAc;;IAAkB;;;EAExF,WACE,SAAS,4BACT,SAAS,cACR,QAAQ;IAAsB;IAAc;;;;YAIrC;WACG;;WACA;;WACA;WAAuB;;;iBAGrB,qBAAqB;WAC3B;;YAGC;;;;;;;;iBASK;WACN;EACT,SACE;aAAkB;aAAsB;aAA0B;KAClE,SAAS,cACR,QAAQ;aAA0B;aAA8B;;EACnE,SACE;aAAkB;KAClB,SAAS,cACR,QACD;aACW;aACA;aACA;eAA2B;eAAuB;;aAClD;;EAGb,MACE;aAAkB;aAA0B,QAAQ;KACpD,SAAS,cACR,QAAQ;;EAEX,KACE;aAAkB;aAA0B,QAAQ;aAA0B;KAC9E,SAAS,cACR,QAAQ;EACX,SAAS;aAAkB;aAA0B;KAAe,SAAS,cAAc,QAAQ;EACnG,WACE;aAAkB;aAA0B;KAC5C,SAAS,cACR,QAAQ;aAA0B;aAAuB;;EAC5D,UAAU,SAAS,cAAc,iBAAiB;EAClD,UAAU;aAAkB;KAAmB,SAAS,cAAc;;EAEtE,S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ACR,UAAU;;WAEV,UAAU;;WAEV,MAAM;;WAEN,WAAW;;WAEX,UAAU;;WAEV,iBAAiB;;WAEjB,eAAe;;;YAId;IACR,SAAS;IACT,YAAY;IACZ,aAAa;IACb,sBAAsB;IACtB,cAAc;IACd,UAAU;IACV,eAAe;IACf,cAAc;IACd,sBAAsB;IACtB,oBAAoB;IACpB;eAA+B;;;;wBAInB,SAAS,SAASC,YAAU;wBAI5B,YAAY,SAASA,YAAU;wBAM/B,eAAe,SAASA,YAAU;wBAMlC,gBAAgB,SAASA,YAAU;wBAMnC,UAAU,SAASA,YAAU;wBAI7B,eAAe,SAASA,YAAU;wBAIlC,cAAc,SAASA,YAAU;wBAIjC,qBAAqB,SAASA,YAAU;wBAIxC,mBAAmB,SAASA,YAAU;wBAItC,cAAc,SAASA,YAAU;wBAIjC,iBAAiB,SAASA,YAAU"}
1
+ {"version":3,"file":"platform.d.mts","names":["IoContext","Context"],"sources":["../../../src/schemas/platform.ts"],"mappings":";;;;;;;qBAOa;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;;iBAGI;EACf,OAAO,mBAAmB;IAAW;IAAmB,SAAS;MAAgB,QAAQ;;;iBAI1E;WACN;WACA;WACA;WACA;WACA;WACA;;WAEA;;;iBAIM;WACN;;;;;EAKT,YAAY,SAAS,0BAA0B,SAAS,cAAc;IAAU;;;;iBAIjE;WACN;;WAEA;WACA;;iBAGM;WACN;;WAEA;;;;;;;iBAQM;WACN;;EAET,UAAU,aAAa,SAAS,cAAc,QAAQ;IAAsB;IAAc;;;EAE1F,SACE,aACA,SAAS,cACR,QAAQ;IAAsB;IAAc;MAAS;MAAc;;IAAkB;;;EAExF,WACE,SAAS,4BACT,SAAS,cACR,QAAQ;IAAsB;IAAc;;;;YAIrC;WACG;;WACA;;WACA;WAAuB;;;iBAGrB,qBAAqB;WAC3B;;YAGC;;;;;;;;iBASK;WACN;EACT,SACE;aAAkB;aAAsB;aAA0B;KAClE,SAAS,cACR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S,mBAAmB,QAAQ;;;iBAIzB;WACN;WACA;;WAEA;WACA;;;;;WAKA;WACA;aACE;aACA;aACA;aACA;aACA;aACA;;;;iBAKI;;WAEN;;WAEA;aACE;aACA;aACA;aACA;;;WAGF;aAA+B;aAA2B;aAAqB,MAAM;;;WAErF,QAAQ,SAAS,eAAe;WAChC,0BAA0B;;;;;;iBAOpB;WACN;;;;;EAKT,YAAY,mBAAmB;aAAmB;aAA0B,OAAO;;;EAEnF,SAAS,wBAAwB,QAAQ;aAAoC;;EAC7E,QAAQ;aACG;MACP;aAAmB;aAA0B,QAAQ,SAAS;;;;iBAInD;WACN;WACA;;WAEA;;EAET,IAAI,cAAc;WACT,QAAQ;WACR,UAAU;;WAEV,UAAU;;WAEV,MAAM;;WAEN,WAAW;;WAEX,UAAU;;WAEV,iBAAiB;;WAEjB,eAAe;;;YAId;IACR,SAAS;IACT,YAAY;IACZ,aAAa;IACb,sBAAsB;IACtB,cAAc;IACd,UAAU;IACV,eAAe;IACf,cAAc;IACd,sBAAsB;IACtB,oBAAoB;IACpB;eAA+B;;;;wBAInB,SAAS,SAASC,YAAU;wBAI5B,YAAY,SAASA,YAAU;wBAM/B,eAAe,SAASA,YAAU;wBAMlC,gBAAgB,SAASA,YAAU;wBAMnC,UAAU,SAASA,YAAU;wBAI7B,eAAe,SAASA,YAAU;wBAIlC,cAAc,SAASA,YAAU;wBAIjC,qBAAqB,SAASA,YAAU;wBAIxC,mBAAmB,SAASA,YAAU;wBAItC,cAAc,SAASA,YAAU;wBAIjC,iBAAiB,SAASA,YAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"platform.mjs","names":[],"sources":["../../../src/schemas/platform.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport type { Context as IoContext } from '@earendil-works/chord/context';\nimport type { AuthResult, ModelsStoreEntry, ModelType } from '@earendil-works/pi-ai';\nimport type { Storage } from '@earendil-works/pi-durable';\nimport type { ExecutionEnv, FileSystem, Shell } from '@earendil-works/pi-durable/env';\nimport type { SqliteDatabase } from '@earendil-works/pi-durable/storage/sqlite';\n\nexport const PO_FS_SERVICE = 'po/fs';\nexport const PO_SHELL_SERVICE = 'po/shell';\nexport const PO_SQLITE_SERVICE = 'po/sqlite';\nexport const PO_SESSION_STORAGE_SERVICE = 'po/session-storage';\nexport const PO_ISOLATE_SERVICE = 'po/isolate';\nexport const PO_NPM_SERVICE = 'po/npm';\nexport const PO_ELECTRON_SERVICE = 'po/electron';\nexport const PO_BROWSER_SERVICE = 'po/browser';\nexport const PO_BROWSER_SESSION_SERVICE = 'po/browser-session';\nexport const PO_PROVIDER_AUTH_SERVICE = 'po/provider-auth';\n\n/** Host-owned npm installation and native module loading. */\nexport interface PoNpm {\n import(specifier: string, options: { sessionId: string; signal?: AbortSignal }): Promise<Record<string, unknown>>;\n}\n\n/** One page for the Desktop's Electron to render: a loopback `http:` or a `file:` URL. */\nexport interface PoElectronCaptureRequest {\n readonly url: string;\n readonly width: number;\n readonly height: number;\n readonly fullPage: boolean;\n readonly darkMode: boolean;\n readonly mobile: boolean;\n /** Extra settle time after the story mounted, in milliseconds. */\n readonly waitTime: number;\n}\n\n/** Electron capabilities of Po Desktop's main process; bound only while the server runs under Desktop. */\nexport interface PoElectronService {\n readonly abiVersion: 1;\n /**\n * Renders a story page in a hidden window and returns its PNG as base64. Rejects with\n * `Story failed in the browser: ...` when the page throws, shows Vite's error overlay, or mounts nothing.\n */\n capturePage(request: PoElectronCaptureRequest, signal?: AbortSignal): Promise<{ png: string }>;\n}\n\n/** A page the host rendered: its final URL after the host's checks, and its title. */\nexport interface PoBrowserPageInfo {\n readonly url: string;\n /** HTTP status of the main document, when the browser saw one. */\n readonly status?: number;\n readonly title: string;\n}\n\nexport interface PoBrowserScreenshotRequest {\n readonly url: string;\n /** The whole scrollable page, clipped by the host's height cap, instead of the viewport. */\n readonly fullPage?: boolean;\n}\n\n/**\n * A remote headless browser for one session, bound only on hosts that offer one (Cloudflare Browser\n * Rendering behind `PO_CLOUD_WEB`). The host owns the outbound policy, page timeout, size caps and quota;\n * each call rejects with a message that names the refusal.\n */\nexport interface PoBrowserService {\n readonly abiVersion: 1;\n /** The rendered page's visible text, capped by the host. */\n fetchPage(url: string, signal?: AbortSignal): Promise<PoBrowserPageInfo & { text: string; truncated: boolean }>;\n /** The rendered DOM as HTML plus its links, each capped by the host. */\n snapshot(\n url: string,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { html: string; links: { text: string; href: string }[]; truncated: boolean }>;\n /** A PNG of the rendered page as base64, refused past the host's byte cap. */\n screenshot(\n request: PoBrowserScreenshotRequest,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { data: string; mimeType: 'image/png' }>;\n}\n\n/** What an action aims at: a CSS selector, visible text, or an ARIA role with an optional accessible name. */\nexport type PoBrowserTarget =\n | { readonly selector: string }\n | { readonly text: string }\n | { readonly role: string; readonly name?: string };\n\n/** One open tab of the session's browser. `pageId` is stable for the life of the remote browser. */\nexport interface PoBrowserTab extends PoBrowserPageInfo {\n readonly pageId: string;\n}\n\nexport type PoBrowserHandoffState = 'pending' | 'done' | 'failed' | 'timedOut';\n\n/**\n * One persistent remote browser for one session, bound only on hosts that offer one. Tabs and sign-ins\n * survive between calls until the host's idle window closes the browser. The host owns the outbound\n * policy (every navigation, popups included), deadlines, size caps, quota and reconnect after a restart;\n * every call is JSON in, JSON out. `navigate` reports `reconnected: false` once the previous browser was\n * lost, so its tabs and sign-ins are gone.\n */\nexport interface PoBrowserSessionService {\n readonly abiVersion: 1;\n navigate(\n input: { readonly url: string; readonly pageId?: string; readonly newPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly reconnected?: false; readonly reason?: string }>;\n snapshot(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<\n PoBrowserTab & {\n readonly text: string;\n readonly aria: string;\n readonly links: readonly { readonly text: string; readonly href: string }[];\n readonly truncated: boolean;\n }\n >;\n click(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n /** Refuses password fields: the person types those during a handoff. */\n fill(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget; readonly value: string },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n pressKey(input: { readonly pageId?: string; readonly key: string }, signal?: AbortSignal): Promise<PoBrowserTab>;\n screenshot(\n input: { readonly pageId?: string; readonly fullPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly data: string; readonly mimeType: 'image/png' }>;\n listPages(signal?: AbortSignal): Promise<readonly PoBrowserTab[]>;\n closePage(input: { readonly pageId?: string }, signal?: AbortSignal): Promise<void>;\n /** Closes the remote browser and stops metering. Safe to call when nothing is open. */\n close(): Promise<void>;\n /** A short-lived link that lets a person watch and control one tab. A bearer secret: never log it. */\n liveView(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<{ readonly url: string; readonly expiresAt: string }>;\n /** Asks a person to act on a tab (sign-in, MFA, CAPTCHA) and returns at once; poll `handoffStatus`. */\n handoff(\n input: { readonly instructions: string; readonly pageId?: string; readonly timeoutMs?: number },\n signal?: AbortSignal,\n ): Promise<{ readonly handoffId: string; readonly liveViewUrl: string; readonly expiresAt: string }>;\n handoffStatus(\n input: { readonly handoffId: string },\n signal?: AbortSignal,\n ): Promise<{ readonly state: PoBrowserHandoffState; readonly tab?: PoBrowserTab }>;\n}\n\nexport interface PoSqliteService {\n readonly abiVersion: 1;\n /** Node: the database file at this path. Edge: the owning Durable Object's single database. */\n open(file: string, context: IoContext): Promise<SqliteDatabase>;\n}\n\n/** One agent session's storage, held by a single writer until released. */\nexport interface PoSessionStorage {\n readonly storage: Storage;\n /** Throws once another writer may own the session; checked before every write. */\n assertWritable(): void | Promise<void>;\n /** Closes `storage` and gives the session up, after its harness closed. */\n release(context: IoContext): Promise<void>;\n}\n\nexport interface PoSessionStorageRequest {\n /** Omitted for a new session, which gets a fresh id. */\n readonly sessionId?: string;\n /** Recorded on a new session. */\n readonly parentSessionId?: string;\n /** Resume only: refuse to create a session that was never stored. */\n readonly existing?: boolean;\n}\n\nexport interface PoStoredSession {\n readonly sessionId: string;\n /** Epoch milliseconds of the session's last write. */\n readonly updatedAt: number;\n}\n\n/**\n * Where agent sessions live, keyed by session id: one SQLite file per session on Node, the\n * Durable Object's own SQLite on the edge. Callers never see a file, a path or a database.\n */\nexport interface PoSessionStorageService {\n readonly abiVersion: 1;\n open(request: PoSessionStorageRequest, context: IoContext): Promise<PoSessionStorage>;\n /** A stored session without taking ownership or migrating it. The caller closes the storage. */\n openReadOnly(sessionId: string, context: IoContext): Promise<Storage>;\n list(context: IoContext): Promise<readonly PoStoredSession[]>;\n /**\n * Deletes a stored session behind its ownership lease. `'busy'` while a live owner holds it;\n * an already missing session is `'removed'`. Hosts without teardown leave it out.\n */\n remove?(sessionId: string, context: IoContext): Promise<'removed' | 'busy'>;\n}\n\n/** One script run: the source, the globals it may see, and its limits. */\nexport interface PoIsolateRequest {\n /** TypeScript where the host compiles it (Node), plain JavaScript otherwise (edge). */\n readonly source: string;\n /** Names visible to the script. Live objects on hosts with `liveObjects`, JSON functions otherwise. */\n readonly globals: Readonly<Record<string, unknown>>;\n readonly deadlineMs: number;\n readonly signal: AbortSignal;\n /** Heap cap; only hosts with a separate heap honour it. */\n readonly memoryLimitBytes?: number;\n /** Member names hidden on every live object the script reaches; only hosts with `liveObjects` apply it. */\n readonly deny?: readonly string[];\n /** Problems the script cannot see, such as a throwing callback it passed to a live object. */\n readonly onDiagnostic?: (message: string) => void;\n /**\n * Loads the body behind `await import(specifier)`; `id` names it in errors and caches it per run.\n * Without it, or on hosts that cannot import, `import()` rejects.\n */\n readonly resolveImport?: (\n specifier: string,\n ) => Promise<\n | { readonly kind?: 'script'; readonly id: string; readonly source: string }\n | { readonly kind: 'module'; readonly id: string; readonly exports: Record<string, unknown> }\n >;\n}\n\nexport type PoIsolateErrorKind = 'timeout' | 'aborted' | 'compile' | 'error';\n\nexport type PoIsolateResult =\n | { readonly ok: true; readonly value: unknown }\n | {\n readonly ok: false;\n readonly error: {\n readonly kind: PoIsolateErrorKind;\n readonly name: string;\n readonly message: string;\n /** 1-based line in the submitted source, when known. */\n readonly line?: number;\n readonly stack?: string;\n };\n };\n\n/**\n * Runs model-written code with injected globals. Node binds a main-thread `vm` context that can\n * hold live objects (not a security boundary); the edge binds a QuickJS sandbox limited to JSON.\n */\nexport interface PoIsolateService {\n readonly abiVersion: 1;\n /** True when globals are passed by reference, so live objects work. */\n readonly liveObjects: boolean;\n run(request: PoIsolateRequest): Promise<PoIsolateResult>;\n}\n\n/** An OpenAI- or Anthropic-compatible endpoint added by hand. Holds no secret: its key is a stored credential. */\nexport interface PoCustomProviderDefinition {\n readonly id: string;\n readonly name: string;\n /** `http:` or `https:`, without userinfo or a query string. */\n readonly baseUrl: string;\n readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';\n readonly models: readonly {\n readonly id: string;\n readonly name?: string;\n readonly reasoning?: boolean;\n readonly input?: readonly ('text' | 'image')[];\n readonly contextWindow?: number;\n readonly maxTokens?: number;\n }[];\n}\n\n/** What the credential owner tells sessions: never a key, token, header or URL secret. */\nexport interface PoProviderAuthSnapshot {\n /** Changes whenever anything below changes; compare with `!==`, as an owner restart starts afresh. */\n readonly version: number;\n /** Configured providers only; every other provider is unconfigured. */\n readonly providers: readonly {\n readonly id: string;\n readonly type: 'api_key' | 'oauth';\n readonly source?: string;\n readonly subscription: boolean;\n }[];\n /** Models of every type the deployment target can use, after each provider's credential filter. */\n readonly available: readonly { readonly provider: string; readonly id: string; readonly type: ModelType }[];\n /** Dynamic catalogs by provider id, with headers and URL secrets removed. */\n readonly models: Readonly<Record<string, ModelsStoreEntry>>;\n readonly customProviders: readonly PoCustomProviderDefinition[];\n}\n\n/**\n * Provider credentials held by one owner per deployment target (the org on hosted Po), for hosts\n * whose sessions must never store them. Node leaves it unbound: `auth.json` is the authority there.\n */\nexport interface PoProviderAuth {\n readonly abiVersion: 1;\n /**\n * Provider-level auth for one request, resolved like local `Models.getAuth` (stored OAuth refreshed,\n * then the stored key) and never persisted by the caller. `version` is the owner's snapshot version.\n */\n resolveAuth(provider: string): Promise<{ readonly version: number; readonly auth?: AuthResult }>;\n /** The full snapshot, or just `{ version }` while `sinceVersion` is still current. */\n snapshot(sinceVersion?: number): Promise<PoProviderAuthSnapshot | { readonly version: number }>;\n refresh(options?: {\n readonly allowNetwork?: boolean;\n }): Promise<{ readonly version: number; readonly errors: Readonly<Record<string, string>> }>;\n}\n\n/** Host capabilities one composition root runs on: Node in the CLI, a Durable Object on the edge. */\nexport interface PoPlatform {\n readonly abiVersion: 1;\n readonly homeDirectory: string;\n /** Host-selected base for session output; absent on older embedding platforms. */\n readonly temporaryDirectory?: string;\n /** Files and shell rooted at `cwd`; pi-durable `FileSystem` and `Shell`. */\n env(cwd: string): ExecutionEnv;\n readonly sqlite: PoSqliteService;\n readonly sessions: PoSessionStorageService;\n /** Script runner for code mode; absent on hosts that do not bind one. */\n readonly isolate?: PoIsolateService;\n /** Native npm loader; absent on hosts without Node package support. */\n readonly npm?: PoNpm;\n /** Po Desktop's Electron; absent unless the server runs under Desktop. */\n readonly electron?: PoElectronService;\n /** Remote headless browser; absent unless the host offers one and its operator turned it on. */\n readonly browser?: PoBrowserService;\n /** One persistent remote browser per session; absent unless the host offers one and its operator turned it on. */\n readonly browserSession?: PoBrowserSessionService;\n /** Owner-held provider credentials; absent where the session's own runtime holds them (Node). */\n readonly providerAuth?: PoProviderAuth;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/fs': FileSystem;\n 'po/shell': Shell;\n 'po/sqlite': PoSqliteService;\n 'po/session-storage': PoSessionStorageService;\n 'po/isolate': PoIsolateService;\n 'po/npm': PoNpm;\n 'po/electron': PoElectronService;\n 'po/browser': PoBrowserService;\n 'po/browser-session': PoBrowserSessionService;\n 'po/provider-auth': PoProviderAuth;\n 'po/session-files': { readonly temporaryDirectory: string };\n }\n}\n\nexport function readPoFs(context: Context): FileSystem | undefined {\n return context.get(PO_FS_SERVICE) as FileSystem | undefined;\n}\n\nexport function requirePoFs(context: Context): FileSystem {\n const service = readPoFs(context);\n if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoShell(context: Context): Shell {\n const service = context.get(PO_SHELL_SERVICE) as Shell | undefined;\n if (!service) throw new Error(`The '${PO_SHELL_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoSqlite(context: Context): PoSqliteService {\n const service = context.get(PO_SQLITE_SERVICE) as PoSqliteService | undefined;\n if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function readPoNpm(context: Context): PoNpm | undefined {\n return context.get(PO_NPM_SERVICE) as PoNpm | undefined;\n}\n\nexport function readPoElectron(context: Context): PoElectronService | undefined {\n return context.get(PO_ELECTRON_SERVICE) as PoElectronService | undefined;\n}\n\nexport function readPoBrowser(context: Context): PoBrowserService | undefined {\n return context.get(PO_BROWSER_SERVICE) as PoBrowserService | undefined;\n}\n\nexport function readPoBrowserSession(context: Context): PoBrowserSessionService | undefined {\n return context.get(PO_BROWSER_SESSION_SERVICE) as PoBrowserSessionService | undefined;\n}\n\nexport function readPoProviderAuth(context: Context): PoProviderAuth | undefined {\n return context.get(PO_PROVIDER_AUTH_SERVICE) as PoProviderAuth | undefined;\n}\n\nexport function readPoIsolate(context: Context): PoIsolateService | undefined {\n return context.get(PO_ISOLATE_SERVICE) as PoIsolateService | undefined;\n}\n\nexport function requirePoIsolate(context: Context): PoIsolateService {\n const service = readPoIsolate(context);\n if (!service) throw new Error(`The '${PO_ISOLATE_SERVICE}' service is unavailable on this host.`);\n return service;\n}\n"],"mappings":";AAOA,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;AACjC,MAAa,6BAA6B;AAC1C,MAAa,qBAAqB;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["import type { Context } from '@deepseek-ai/cordis';\nimport type { Context as IoContext } from '@earendil-works/chord/context';\nimport type { AuthResult, ModelsStoreEntry, ModelType } from '@earendil-works/pi-ai';\nimport type { Storage } from '@earendil-works/pi-durable';\nimport type { ExecutionEnv, FileSystem, Shell } from '@earendil-works/pi-durable/env';\nimport type { SqliteDatabase } from '@earendil-works/pi-durable/storage/sqlite';\n\nexport const PO_FS_SERVICE = 'po/fs';\nexport const PO_SHELL_SERVICE = 'po/shell';\nexport const PO_SQLITE_SERVICE = 'po/sqlite';\nexport const PO_SESSION_STORAGE_SERVICE = 'po/session-storage';\nexport const PO_ISOLATE_SERVICE = 'po/isolate';\nexport const PO_NPM_SERVICE = 'po/npm';\nexport const PO_ELECTRON_SERVICE = 'po/electron';\nexport const PO_BROWSER_SERVICE = 'po/browser';\nexport const PO_BROWSER_SESSION_SERVICE = 'po/browser-session';\nexport const PO_PROVIDER_AUTH_SERVICE = 'po/provider-auth';\n\n/** Host-owned npm installation and native module loading. */\nexport interface PoNpm {\n import(specifier: string, options: { sessionId: string; signal?: AbortSignal }): Promise<Record<string, unknown>>;\n}\n\n/** One page for the Desktop's Electron to render: a loopback `http:` or a `file:` URL. */\nexport interface PoElectronCaptureRequest {\n readonly url: string;\n readonly width: number;\n readonly height: number;\n readonly fullPage: boolean;\n readonly darkMode: boolean;\n readonly mobile: boolean;\n /** Extra settle time after the story mounted, in milliseconds. */\n readonly waitTime: number;\n}\n\n/** Electron capabilities of Po Desktop's main process; bound only while the server runs under Desktop. */\nexport interface PoElectronService {\n readonly abiVersion: 1;\n /**\n * Renders a story page in a hidden window and returns its PNG as base64. Rejects with\n * `Story failed in the browser: ...` when the page throws, shows Vite's error overlay, or mounts nothing.\n */\n capturePage(request: PoElectronCaptureRequest, signal?: AbortSignal): Promise<{ png: string }>;\n}\n\n/** A page the host rendered: its final URL after the host's checks, and its title. */\nexport interface PoBrowserPageInfo {\n readonly url: string;\n /** HTTP status of the main document, when the browser saw one. */\n readonly status?: number;\n readonly title: string;\n}\n\nexport interface PoBrowserScreenshotRequest {\n readonly url: string;\n /** The whole scrollable page, clipped by the host's height cap, instead of the viewport. */\n readonly fullPage?: boolean;\n}\n\n/**\n * A remote headless browser for one session, bound only on hosts that offer one (Cloudflare Browser\n * Rendering behind `PO_CLOUD_WEB`). The host owns the outbound policy, page timeout, size caps and quota;\n * each call rejects with a message that names the refusal.\n */\nexport interface PoBrowserService {\n readonly abiVersion: 1;\n /** The rendered page's visible text, capped by the host. */\n fetchPage(url: string, signal?: AbortSignal): Promise<PoBrowserPageInfo & { text: string; truncated: boolean }>;\n /** The rendered DOM as HTML plus its links, each capped by the host. */\n snapshot(\n url: string,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { html: string; links: { text: string; href: string }[]; truncated: boolean }>;\n /** A PNG of the rendered page as base64, refused past the host's byte cap. */\n screenshot(\n request: PoBrowserScreenshotRequest,\n signal?: AbortSignal,\n ): Promise<PoBrowserPageInfo & { data: string; mimeType: 'image/png' }>;\n}\n\n/** What an action aims at: a CSS selector, visible text, or an ARIA role with an optional accessible name. */\nexport type PoBrowserTarget =\n | { readonly selector: string }\n | { readonly text: string }\n | { readonly role: string; readonly name?: string };\n\n/** One open tab of the session's browser. `pageId` is stable for the life of the remote browser. */\nexport interface PoBrowserTab extends PoBrowserPageInfo {\n readonly pageId: string;\n}\n\nexport type PoBrowserHandoffState = 'pending' | 'done' | 'failed' | 'timedOut';\n\n/**\n * One persistent remote browser for one session, bound only on hosts that offer one. Tabs and sign-ins\n * survive between calls until the host's idle window closes the browser. The host owns the outbound\n * policy (every navigation, popups included), deadlines, size caps, quota and reconnect after a restart;\n * every call is JSON in, JSON out. `navigate` reports `reconnected: false` once the previous browser was\n * lost, so its tabs and sign-ins are gone.\n */\nexport interface PoBrowserSessionService {\n readonly abiVersion: 1;\n navigate(\n input: { readonly url: string; readonly pageId?: string; readonly newPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly reconnected?: false; readonly reason?: string }>;\n snapshot(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<\n PoBrowserTab & {\n readonly text: string;\n readonly aria: string;\n readonly links: readonly { readonly text: string; readonly href: string }[];\n readonly truncated: boolean;\n }\n >;\n click(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n /** Refuses password fields: the person types those during a handoff. */\n fill(\n input: { readonly pageId?: string; readonly target: PoBrowserTarget; readonly value: string },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab>;\n pressKey(input: { readonly pageId?: string; readonly key: string }, signal?: AbortSignal): Promise<PoBrowserTab>;\n screenshot(\n input: { readonly pageId?: string; readonly fullPage?: boolean },\n signal?: AbortSignal,\n ): Promise<PoBrowserTab & { readonly data: string; readonly mimeType: 'image/png' }>;\n listPages(signal?: AbortSignal): Promise<readonly PoBrowserTab[]>;\n closePage(input: { readonly pageId?: string }, signal?: AbortSignal): Promise<void>;\n /** Closes the remote browser and stops metering. Safe to call when nothing is open. */\n close(): Promise<void>;\n /** A short-lived link that lets a person watch and control one tab. A bearer secret: never log it. */\n liveView(\n input: { readonly pageId?: string },\n signal?: AbortSignal,\n ): Promise<{ readonly url: string; readonly expiresAt: string }>;\n /** Asks a person to act on a tab (sign-in, MFA, CAPTCHA) and returns at once; poll `handoffStatus`. */\n handoff(\n input: { readonly instructions: string; readonly pageId?: string; readonly timeoutMs?: number },\n signal?: AbortSignal,\n ): Promise<{ readonly handoffId: string; readonly liveViewUrl: string; readonly expiresAt: string }>;\n handoffStatus(\n input: { readonly handoffId: string },\n signal?: AbortSignal,\n ): Promise<{ readonly state: PoBrowserHandoffState; readonly tab?: PoBrowserTab }>;\n}\n\nexport interface PoSqliteService {\n readonly abiVersion: 1;\n /** Node: the database file at this path. Edge: the owning Durable Object's single database. */\n open(file: string, context: IoContext): Promise<SqliteDatabase>;\n}\n\n/** One agent session's storage, held by a single writer until released. */\nexport interface PoSessionStorage {\n readonly storage: Storage;\n /** Throws once another writer may own the session; checked before every write. */\n assertWritable(): void | Promise<void>;\n /** Closes `storage` and gives the session up, after its harness closed. */\n release(context: IoContext): Promise<void>;\n}\n\nexport interface PoSessionStorageRequest {\n /** Omitted for a new session, which gets a fresh id. */\n readonly sessionId?: string;\n /** Recorded on a new session. */\n readonly parentSessionId?: string;\n /** Resume only: refuse to create a session that was never stored. */\n readonly existing?: boolean;\n}\n\nexport interface PoStoredSession {\n readonly sessionId: string;\n /** Epoch milliseconds of the session's last write. */\n readonly updatedAt: number;\n}\n\n/**\n * Where agent sessions live, keyed by session id: one SQLite file per session on Node, the\n * Durable Object's own SQLite on the edge. Callers never see a file, a path or a database.\n */\nexport interface PoSessionStorageService {\n readonly abiVersion: 1;\n open(request: PoSessionStorageRequest, context: IoContext): Promise<PoSessionStorage>;\n /** A stored session without taking ownership or migrating it. The caller closes the storage. */\n openReadOnly(sessionId: string, context: IoContext): Promise<Storage>;\n list(context: IoContext): Promise<readonly PoStoredSession[]>;\n /**\n * Deletes a stored session behind its ownership lease. `'busy'` while a live owner holds it;\n * an already missing session is `'removed'`. Hosts without teardown leave it out.\n */\n remove?(sessionId: string, context: IoContext): Promise<'removed' | 'busy'>;\n}\n\n/** One script run: the source, the globals it may see, and its limits. */\nexport interface PoIsolateRequest {\n /** TypeScript where the host compiles it (Node), plain JavaScript otherwise (edge). */\n readonly source: string;\n /** Names visible to the script. Live objects on hosts with `liveObjects`, JSON functions otherwise. */\n readonly globals: Readonly<Record<string, unknown>>;\n readonly deadlineMs: number;\n readonly signal: AbortSignal;\n /** Heap cap; only hosts with a separate heap honour it. */\n readonly memoryLimitBytes?: number;\n /** Member names hidden on every live object the script reaches; only hosts with `liveObjects` apply it. */\n readonly deny?: readonly string[];\n /** Problems the script cannot see, such as a throwing callback it passed to a live object. */\n readonly onDiagnostic?: (message: string) => void;\n /**\n * Loads the body behind `await import(specifier)`; `id` names it in errors and caches it per run.\n * Without it, or on hosts that cannot import, `import()` rejects.\n */\n readonly resolveImport?: (\n specifier: string,\n ) => Promise<\n | { readonly kind?: 'script'; readonly id: string; readonly source: string }\n | { readonly kind: 'module'; readonly id: string; readonly exports: Record<string, unknown> }\n >;\n}\n\nexport type PoIsolateErrorKind = 'timeout' | 'aborted' | 'compile' | 'error';\n\nexport type PoIsolateResult =\n | { readonly ok: true; readonly value: unknown }\n | {\n readonly ok: false;\n readonly error: {\n readonly kind: PoIsolateErrorKind;\n readonly name: string;\n readonly message: string;\n /** 1-based line in the submitted source, when known. */\n readonly line?: number;\n readonly stack?: string;\n };\n };\n\n/**\n * Runs model-written code with injected globals. Node binds a main-thread `vm` context that can\n * hold live objects (not a security boundary); the edge binds a QuickJS sandbox limited to JSON.\n */\nexport interface PoIsolateService {\n readonly abiVersion: 1;\n /** True when globals are passed by reference, so live objects work. */\n readonly liveObjects: boolean;\n run(request: PoIsolateRequest): Promise<PoIsolateResult>;\n}\n\n/** An OpenAI- or Anthropic-compatible endpoint added by hand. Holds no secret: its key is a stored credential. */\nexport interface PoCustomProviderDefinition {\n readonly id: string;\n readonly name: string;\n /** `http:` or `https:`, without userinfo or a query string. */\n readonly baseUrl: string;\n readonly api: 'openai-completions' | 'openai-responses' | 'anthropic-messages';\n /**\n * `openai-completions` only: send `tools: []` once the conversation holds tool calls but the turn offers\n * no tools, for proxies such as LiteLLM that reject tool history without a tools list.\n */\n readonly requiresToolsWithToolHistory?: boolean;\n readonly models: readonly {\n readonly id: string;\n readonly name?: string;\n readonly reasoning?: boolean;\n readonly input?: readonly ('text' | 'image')[];\n readonly contextWindow?: number;\n readonly maxTokens?: number;\n }[];\n}\n\n/** What the credential owner tells sessions: never a key, token, header or URL secret. */\nexport interface PoProviderAuthSnapshot {\n /** Changes whenever anything below changes; compare with `!==`, as an owner restart starts afresh. */\n readonly version: number;\n /** Configured providers only; every other provider is unconfigured. */\n readonly providers: readonly {\n readonly id: string;\n readonly type: 'api_key' | 'oauth';\n readonly source?: string;\n readonly subscription: boolean;\n }[];\n /** Models of every type the deployment target can use, after each provider's credential filter. */\n readonly available: readonly { readonly provider: string; readonly id: string; readonly type: ModelType }[];\n /** Dynamic catalogs by provider id, with headers and URL secrets removed. */\n readonly models: Readonly<Record<string, ModelsStoreEntry>>;\n readonly customProviders: readonly PoCustomProviderDefinition[];\n}\n\n/**\n * Provider credentials held by one owner per deployment target (the org on hosted Po), for hosts\n * whose sessions must never store them. Node leaves it unbound: `auth.json` is the authority there.\n */\nexport interface PoProviderAuth {\n readonly abiVersion: 1;\n /**\n * Provider-level auth for one request, resolved like local `Models.getAuth` (stored OAuth refreshed,\n * then the stored key) and never persisted by the caller. `version` is the owner's snapshot version.\n */\n resolveAuth(provider: string): Promise<{ readonly version: number; readonly auth?: AuthResult }>;\n /** The full snapshot, or just `{ version }` while `sinceVersion` is still current. */\n snapshot(sinceVersion?: number): Promise<PoProviderAuthSnapshot | { readonly version: number }>;\n refresh(options?: {\n readonly allowNetwork?: boolean;\n }): Promise<{ readonly version: number; readonly errors: Readonly<Record<string, string>> }>;\n}\n\n/** Host capabilities one composition root runs on: Node in the CLI, a Durable Object on the edge. */\nexport interface PoPlatform {\n readonly abiVersion: 1;\n readonly homeDirectory: string;\n /** Host-selected base for session output; absent on older embedding platforms. */\n readonly temporaryDirectory?: string;\n /** Files and shell rooted at `cwd`; pi-durable `FileSystem` and `Shell`. */\n env(cwd: string): ExecutionEnv;\n readonly sqlite: PoSqliteService;\n readonly sessions: PoSessionStorageService;\n /** Script runner for code mode; absent on hosts that do not bind one. */\n readonly isolate?: PoIsolateService;\n /** Native npm loader; absent on hosts without Node package support. */\n readonly npm?: PoNpm;\n /** Po Desktop's Electron; absent unless the server runs under Desktop. */\n readonly electron?: PoElectronService;\n /** Remote headless browser; absent unless the host offers one and its operator turned it on. */\n readonly browser?: PoBrowserService;\n /** One persistent remote browser per session; absent unless the host offers one and its operator turned it on. */\n readonly browserSession?: PoBrowserSessionService;\n /** Owner-held provider credentials; absent where the session's own runtime holds them (Node). */\n readonly providerAuth?: PoProviderAuth;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/fs': FileSystem;\n 'po/shell': Shell;\n 'po/sqlite': PoSqliteService;\n 'po/session-storage': PoSessionStorageService;\n 'po/isolate': PoIsolateService;\n 'po/npm': PoNpm;\n 'po/electron': PoElectronService;\n 'po/browser': PoBrowserService;\n 'po/browser-session': PoBrowserSessionService;\n 'po/provider-auth': PoProviderAuth;\n 'po/session-files': { readonly temporaryDirectory: string };\n }\n}\n\nexport function readPoFs(context: Context): FileSystem | undefined {\n return context.get(PO_FS_SERVICE) as FileSystem | undefined;\n}\n\nexport function requirePoFs(context: Context): FileSystem {\n const service = readPoFs(context);\n if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoShell(context: Context): Shell {\n const service = context.get(PO_SHELL_SERVICE) as Shell | undefined;\n if (!service) throw new Error(`The '${PO_SHELL_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function requirePoSqlite(context: Context): PoSqliteService {\n const service = context.get(PO_SQLITE_SERVICE) as PoSqliteService | undefined;\n if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);\n return service;\n}\n\nexport function readPoNpm(context: Context): PoNpm | undefined {\n return context.get(PO_NPM_SERVICE) as PoNpm | undefined;\n}\n\nexport function readPoElectron(context: Context): PoElectronService | undefined {\n return context.get(PO_ELECTRON_SERVICE) as PoElectronService | undefined;\n}\n\nexport function readPoBrowser(context: Context): PoBrowserService | undefined {\n return context.get(PO_BROWSER_SERVICE) as PoBrowserService | undefined;\n}\n\nexport function readPoBrowserSession(context: Context): PoBrowserSessionService | undefined {\n return context.get(PO_BROWSER_SESSION_SERVICE) as PoBrowserSessionService | undefined;\n}\n\nexport function readPoProviderAuth(context: Context): PoProviderAuth | undefined {\n return context.get(PO_PROVIDER_AUTH_SERVICE) as PoProviderAuth | undefined;\n}\n\nexport function readPoIsolate(context: Context): PoIsolateService | undefined {\n return context.get(PO_ISOLATE_SERVICE) as PoIsolateService | undefined;\n}\n\nexport function requirePoIsolate(context: Context): PoIsolateService {\n const service = readPoIsolate(context);\n if (!service) throw new Error(`The '${PO_ISOLATE_SERVICE}' service is unavailable on this host.`);\n return service;\n}\n"],"mappings":";AAOA,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;AACjC,MAAa,6BAA6B;AAC1C,MAAa,qBAAqB;AAClC,MAAa,iBAAiB;AAC9B,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAClC,MAAa,6BAA6B;AAC1C,MAAa,2BAA2B;AA6UxC,SAAgB,SAAS,SAA0C;CACjE,OAAO,QAAQ,IAAI,aAAa;AAClC;AAEA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,SAAS,OAAO;CAChC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,cAAc,mDAAmD;CACvG,OAAO;AACT;AAEA,SAAgB,eAAe,SAAyB;CACtD,MAAM,UAAU,QAAQ,IAAI,gBAAgB;CAC5C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,iBAAiB,mDAAmD;CAC1G,OAAO;AACT;AAEA,SAAgB,gBAAgB,SAAmC;CACjE,MAAM,UAAU,QAAQ,IAAI,iBAAiB;CAC7C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,kBAAkB,mDAAmD;CAC3G,OAAO;AACT;AAEA,SAAgB,UAAU,SAAqC;CAC7D,OAAO,QAAQ,IAAI,cAAc;AACnC;AAEA,SAAgB,eAAe,SAAiD;CAC9E,OAAO,QAAQ,IAAI,mBAAmB;AACxC;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,qBAAqB,SAAuD;CAC1F,OAAO,QAAQ,IAAI,0BAA0B;AAC/C;AAEA,SAAgB,mBAAmB,SAA8C;CAC/E,OAAO,QAAQ,IAAI,wBAAwB;AAC7C;AAEA,SAAgB,cAAc,SAAgD;CAC5E,OAAO,QAAQ,IAAI,kBAAkB;AACvC;AAEA,SAAgB,iBAAiB,SAAoC;CACnE,MAAM,UAAU,cAAc,OAAO;CACrC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,QAAQ,mBAAmB,uCAAuC;CAChG,OAAO;AACT"}
@@ -17,6 +17,7 @@ const CUSTOM_API = {
17
17
  };
18
18
  /** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */
19
19
  function customProvider(definition) {
20
+ const compat = definition.api === "openai-completions" && definition.requiresToolsWithToolHistory === true ? { compat: { requiresToolsWithToolHistory: true } } : {};
20
21
  return (0, _earendil_works_pi_ai.createProvider)({
21
22
  id: definition.id,
22
23
  name: definition.name,
@@ -37,7 +38,8 @@ function customProvider(definition) {
37
38
  cacheWrite: 0
38
39
  },
39
40
  contextWindow: model.contextWindow ?? 128e3,
40
- maxTokens: model.maxTokens ?? 16384
41
+ maxTokens: model.maxTokens ?? 16384,
42
+ ...compat
41
43
  })),
42
44
  api: CUSTOM_API[definition.api]()
43
45
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["openAICompletionsApi","openAIResponsesApi","anthropicMessagesApi","createProvider","envApiKeyAuth","createModels","builtinProviders","getModelType","ModelsError"],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"sourcesContent":["import {\n createModels,\n createProvider,\n envApiKeyAuth,\n getModelType,\n ModelsError,\n type AnyModel,\n type AuthContext,\n type AuthInteraction,\n type CredentialStore,\n type ModelsStore,\n type ModelsStoreEntry,\n type Provider,\n} from '@earendil-works/pi-ai';\nimport { anthropicMessagesApi } from '@earendil-works/pi-ai/api/anthropic-messages.lazy';\nimport { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';\nimport { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy';\nimport { builtinProviders } from '@earendil-works/pi-ai/providers/all';\n\nimport type { PoCustomProviderDefinition, PoProviderAuth, PoProviderAuthSnapshot } from '../../schemas/platform';\nimport type { PoModelRuntime } from '../../systems/main/types/headlessSessionHost';\nimport type { AuthRuntime } from '../../types/server/auth';\nimport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nexport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nconst MANAGED_BY_ADMINS = 'Org admins manage providers in Settings → Providers.';\n\n/** No env vars or ambient files: on a shared host they belong to the host, not to the deployment target. */\nconst NO_AMBIENT_AUTH: AuthContext = { env: async () => undefined, fileExists: async () => false };\n\nconst CUSTOM_API = {\n 'openai-completions': openAICompletionsApi,\n 'openai-responses': openAIResponsesApi,\n 'anthropic-messages': anthropicMessagesApi,\n} as const;\n\n/** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */\nexport function customProvider(definition: PoCustomProviderDefinition): Provider {\n return createProvider({\n id: definition.id,\n name: definition.name,\n baseUrl: definition.baseUrl,\n auth: { apiKey: envApiKeyAuth(`${definition.name} API key`, []) },\n models: definition.models.map((model) => ({\n id: model.id,\n name: model.name ?? model.id,\n api: definition.api,\n provider: definition.id,\n baseUrl: definition.baseUrl,\n reasoning: model.reasoning ?? false,\n input: [...(model.input ?? ['text'])],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: model.contextWindow ?? 128000,\n maxTokens: model.maxTokens ?? 16384,\n })),\n api: CUSTOM_API[definition.api](),\n });\n}\n\n/** A URL without userinfo, query or fragment; unchanged when it carries none, so path joins keep working. */\nfunction publicUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return '';\n }\n if (url.username === '' && url.password === '' && url.search === '' && url.hash === '') return value;\n url.username = '';\n url.password = '';\n url.search = '';\n url.hash = '';\n return url.href;\n}\n\n/** A dynamic catalog fit to leave the owner: no headers, no URL secrets, data only. */\nexport function sanitizeModelsEntry(entry: ModelsStoreEntry): ModelsStoreEntry {\n return JSON.parse(\n JSON.stringify({\n ...entry,\n models: entry.models.map(({ headers: _headers, ...model }) => ({ ...model, baseUrl: publicUrl(model.baseUrl) })),\n }),\n ) as ModelsStoreEntry;\n}\n\nconst availableKey = (model: Pick<AnyModel, 'provider' | 'id'> & { type?: string }): string =>\n `${model.type ?? 'chat'}\\0${model.provider}\\0${model.id}`;\n\n/**\n * The owner side: a real pi-ai `Models` over the deployment target's credential store, so login, OAuth\n * refresh and request auth behave exactly as on a local machine. Every change that sessions can see\n * produces a new snapshot version.\n */\nexport function createProviderAuthOwner(options: ProviderAuthOwnerOptions): ProviderAuthOwner {\n // A failed recompute stays in `pending`, so settled() rethrows it to the next caller; the next change retries.\n const report = options.onError ?? ((): void => undefined);\n let pending: Promise<void> = Promise.resolve();\n const changed = (): Promise<void> => {\n pending = pending.then(recompute, recompute);\n return pending;\n };\n const credentials: CredentialStore = {\n read: (providerId, operation) => options.credentials.read(providerId, operation),\n list: (operation) => options.credentials.list(operation),\n modify: async (providerId, fn, operation) => {\n const result = await options.credentials.modify(providerId, fn, operation);\n void changed().catch(report);\n return result;\n },\n delete: async (providerId, operation) => {\n await options.credentials.delete(providerId, operation);\n void changed().catch(report);\n },\n };\n const models = createModels({ credentials, modelsStore: options.modelsStore, authContext: NO_AMBIENT_AUTH });\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(provider);\n\n let customProviders: readonly PoCustomProviderDefinition[] = [];\n const applyCustomProviders = (definitions: readonly PoCustomProviderDefinition[]): void => {\n for (const previous of customProviders)\n if (!definitions.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of definitions) models.setProvider(customProvider(definition));\n customProviders = definitions;\n };\n applyCustomProviders(options.customProviders ?? []);\n\n // Starts from the clock, so a restarted owner never repeats a version a session still holds.\n let version = Date.now();\n let lastBody = '';\n let current: PoProviderAuthSnapshot | undefined;\n async function recompute(): Promise<void> {\n const providers = models.getProviders();\n const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type]));\n const checks = await Promise.all(\n providers.map(async (provider) => ({\n provider,\n check: await models.checkAuth(provider.id).catch(() => undefined),\n })),\n );\n const catalogs: Record<string, ModelsStoreEntry> = {};\n for (const provider of providers) {\n if (provider.refreshModels === undefined) continue;\n const entry = await options.modelsStore.read(provider.id);\n if (entry !== undefined) catalogs[provider.id] = sanitizeModelsEntry(entry);\n }\n const body = {\n providers: checks.flatMap(({ provider, check }) =>\n check === undefined\n ? []\n : [\n {\n id: provider.id,\n type: check.type,\n source: stored.get(provider.id) === check.type ? 'stored' : check.source,\n subscription: check.type === 'oauth' && provider.auth.oauth?.isSubscription === true,\n },\n ],\n ),\n available: (await models.getAllAvailable()).map((model) => ({\n provider: model.provider,\n id: model.id,\n type: getModelType(model),\n })),\n models: catalogs,\n customProviders,\n };\n const serialized = JSON.stringify(body);\n if (serialized === lastBody && current !== undefined) return;\n lastBody = serialized;\n version += 1;\n current = { version, ...(JSON.parse(serialized) as Omit<PoProviderAuthSnapshot, 'version'>) };\n }\n const settled = async (): Promise<PoProviderAuthSnapshot> => {\n await pending;\n if (current === undefined) await changed();\n return current as PoProviderAuthSnapshot;\n };\n void changed().catch(report);\n\n const statusOf = (providerId: string) => current?.providers.find((entry) => entry.id === providerId);\n const refresh: PoProviderAuth['refresh'] = async (refreshOptions) => {\n const result = await models.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n await changed();\n const snapshot = await settled();\n return {\n version: snapshot.version,\n errors: Object.fromEntries([...result.errors].map(([providerId, error]) => [providerId, error.message])),\n };\n };\n\n const service: PoProviderAuth = {\n abiVersion: 1,\n resolveAuth: async (providerId) => {\n const auth = await models.getAuth(providerId);\n return { version: (await settled()).version, ...(auth === undefined ? {} : { auth }) };\n },\n snapshot: async (sinceVersion) => {\n const snapshot = await settled();\n return sinceVersion === snapshot.version ? { version: snapshot.version } : snapshot;\n },\n refresh,\n };\n\n const authRuntime: AuthRuntime = {\n getProviders: () => models.getProviders(),\n getProviderAuthStatus: (providerId) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n getAvailableSnapshot: () => (current?.available ?? []).filter((model) => model.type === 'chat'),\n hasConfiguredAuth: (providerId) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId) => statusOf(providerId)?.type === 'oauth',\n refresh: (refreshOptions) => refresh(refreshOptions),\n login: async (providerId, type, interaction) => {\n await models.login(providerId, type, interaction as AuthInteraction);\n await settled();\n },\n logout: async (providerId, logoutOptions) => {\n await models.logout(providerId, logoutOptions);\n await settled();\n },\n };\n\n return {\n service,\n authRuntime,\n setCustomProviders: async (definitions) => {\n applyCustomProviders(definitions);\n await changed();\n },\n };\n}\n\n/** Session credentials stay empty: every request's auth comes from the owner and is never kept. */\nconst NO_SESSION_CREDENTIALS: CredentialStore = {\n read: async () => undefined,\n list: async () => [],\n modify: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n delete: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n};\n\n/**\n * The session side: pi-ai `Models` with the same providers as the owner, whose auth asks the owner and\n * whose status and availability come from the owner's snapshot. Requests, streaming and header merges\n * run locally, unchanged; the session never holds a credential.\n */\nexport async function createOwnerBackedModelRuntime(options: OwnerBackedModelRuntimeOptions): Promise<PoModelRuntime> {\n const { owner } = options;\n let snapshot: PoProviderAuthSnapshot | undefined;\n let availableKeys = new Set<string>();\n const statusOf = (providerId: string) => snapshot?.providers.find((entry) => entry.id === providerId);\n const isAvailable = (model: AnyModel): boolean =>\n availableKeys.has(availableKey({ provider: model.provider, id: model.id, type: getModelType(model) }));\n\n const modelsStore: ModelsStore = {\n read: async (providerId) => snapshot?.models[providerId],\n // The owner persists catalogs; a session only restores the snapshot's copy.\n write: async () => undefined,\n delete: async () => undefined,\n };\n const models = createModels({\n credentials: NO_SESSION_CREDENTIALS,\n modelsStore,\n authContext: NO_AMBIENT_AUTH,\n });\n\n // A failed sync keeps the last snapshot; the next version the owner reports retries it.\n const report = options.onError ?? ((): void => undefined);\n let syncing: Promise<void> = Promise.resolve();\n const pull = async (): Promise<void> => {\n const next = await owner.snapshot(snapshot?.version);\n if (!('providers' in next)) return;\n const previousCustom = snapshot?.customProviders ?? [];\n snapshot = next;\n availableKeys = new Set(next.available.map(availableKey));\n for (const previous of previousCustom)\n if (!next.customProviders.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of next.customProviders) models.setProvider(ownerBacked(customProvider(definition)));\n await models.refresh({ allowNetwork: false });\n };\n const sync = (): Promise<void> => {\n syncing = syncing.then(pull, pull);\n return syncing;\n };\n const observe = (version: number): void => {\n if (version !== snapshot?.version) void sync().catch(report);\n };\n\n const ownerBacked = (provider: Provider): Provider => {\n const apiKey = provider.auth.apiKey;\n return {\n ...provider,\n auth: {\n ...provider.auth,\n apiKey: {\n name: apiKey?.name ?? provider.name,\n check: async () => {\n const status = statusOf(provider.id);\n return status === undefined\n ? undefined\n : { type: status.type, ...(status.source === undefined ? {} : { source: status.source }) };\n },\n resolve: async ({ credential, signal }) => {\n // A key the caller passed for this request resolves locally, as it would on a machine.\n if (credential?.key !== undefined && apiKey !== undefined)\n return apiKey.resolve({ ctx: NO_AMBIENT_AUTH, credential, signal });\n const result = await owner.resolveAuth(provider.id);\n observe(result.version);\n return result.auth;\n },\n },\n },\n filterModels: (list) => list.filter(isAvailable),\n filterAllModels: (list) => list.filter(isAvailable),\n } as Provider;\n };\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(ownerBacked(provider));\n await sync();\n\n const managedByAdmins = async (): Promise<never> => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n };\n const refused = (): never => {\n throw new ModelsError('provider', MANAGED_BY_ADMINS);\n };\n return {\n getProviders: models.getProviders.bind(models),\n getProvider: models.getProvider.bind(models),\n getModels: models.getModels.bind(models),\n getModel: models.getModel.bind(models),\n getModelsOfType: models.getModelsOfType.bind(models),\n getModelOfType: models.getModelOfType.bind(models),\n getAllModels: models.getAllModels.bind(models),\n checkAuth: models.checkAuth.bind(models),\n getAvailable: models.getAvailable.bind(models),\n getAvailableOfType: models.getAvailableOfType.bind(models),\n getAllAvailable: models.getAllAvailable.bind(models),\n getAuth: models.getAuth.bind(models),\n stream: models.stream.bind(models),\n complete: models.complete.bind(models),\n streamSimple: models.streamSimple.bind(models),\n completeSimple: models.completeSimple.bind(models),\n streamDeferred: models.streamDeferred.bind(models),\n fetchDeferred: models.fetchDeferred.bind(models),\n cancelDeferred: models.cancelDeferred.bind(models),\n generateImages: models.generateImages.bind(models),\n classify: models.classify.bind(models),\n refresh: async (refreshOptions?: { allowNetwork?: boolean }) => {\n const result = await owner.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n if (result.version !== snapshot?.version) await sync();\n return {\n aborted: false,\n errors: new Map(\n Object.entries(result.errors).map(([providerId, message]) => [\n providerId,\n new ModelsError('model_source', message),\n ]),\n ),\n };\n },\n getAvailableSnapshot: () => models.getModels().filter(isAvailable),\n getError: () => undefined,\n hasConfiguredAuth: (providerId: string) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId: string) => statusOf(providerId)?.type === 'oauth',\n isUsingSubscription: (providerId: string) => statusOf(providerId)?.subscription === true,\n getProviderAuthStatus: (providerId: string) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n login: managedByAdmins,\n logout: managedByAdmins,\n setRuntimeApiKey: managedByAdmins,\n removeRuntimeApiKey: managedByAdmins,\n listCredentials: async () => [],\n getRegisteredNativeProvider: () => undefined,\n getRegisteredProviderConfig: () => undefined,\n getRegisteredProviderIds: () => [],\n getCompatibilityRequestConfig: refused,\n registerProvider: refused,\n registerNativeProvider: refused,\n unregisterProvider: refused,\n registerVirtualModel: refused,\n unregisterVirtualModel: refused,\n } as unknown as PoModelRuntime;\n}\n"],"mappings":";;;;;;AA0BA,MAAM,oBAAoB;;AAG1B,MAAM,kBAA+B;CAAE,KAAK,YAAY,KAA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YACA,IAAIA,sBAAAA,YAAY,gBAAgB,OAAO,CACzC,CAAC,CACH;GACF;EACF;EACA,4BAA4B,OAAO,UAAU,CAAC,CAAC,OAAO,WAAW;EACjE,gBAAgB,KAAA;EAChB,oBAAoB,eAAuB,SAAS,UAAU,MAAM,KAAA;EACpE,eAAe,eAAuB,SAAS,UAAU,CAAC,EAAE,SAAS;EACrE,sBAAsB,eAAuB,SAAS,UAAU,CAAC,EAAE,iBAAiB;EACpF,wBAAwB,eAAuB;GAC7C,MAAM,SAAS,SAAS,UAAU;GAClC,OAAO,WAAW,KAAA,IAAY,EAAE,YAAY,MAAM,IAAI;IAAE,YAAY;IAAM,QAAQ,OAAO;GAAO;EAClG;EACA,OAAO;EACP,QAAQ;EACR,kBAAkB;EAClB,qBAAqB;EACrB,iBAAiB,YAAY,CAAC;EAC9B,mCAAmC,KAAA;EACnC,mCAAmC,KAAA;EACnC,gCAAgC,CAAC;EACjC,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,oBAAoB;EACpB,sBAAsB;EACtB,wBAAwB;CAC1B;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["openAICompletionsApi","openAIResponsesApi","anthropicMessagesApi","createProvider","envApiKeyAuth","createModels","builtinProviders","getModelType","ModelsError"],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"sourcesContent":["import {\n createModels,\n createProvider,\n envApiKeyAuth,\n getModelType,\n ModelsError,\n type AnyModel,\n type AuthContext,\n type AuthInteraction,\n type CredentialStore,\n type ModelsStore,\n type ModelsStoreEntry,\n type Provider,\n} from '@earendil-works/pi-ai';\nimport { anthropicMessagesApi } from '@earendil-works/pi-ai/api/anthropic-messages.lazy';\nimport { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';\nimport { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy';\nimport { builtinProviders } from '@earendil-works/pi-ai/providers/all';\n\nimport type { PoCustomProviderDefinition, PoProviderAuth, PoProviderAuthSnapshot } from '../../schemas/platform';\nimport type { PoModelRuntime } from '../../systems/main/types/headlessSessionHost';\nimport type { AuthRuntime } from '../../types/server/auth';\nimport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nexport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nconst MANAGED_BY_ADMINS = 'Org admins manage providers in Settings → Providers.';\n\n/** No env vars or ambient files: on a shared host they belong to the host, not to the deployment target. */\nconst NO_AMBIENT_AUTH: AuthContext = { env: async () => undefined, fileExists: async () => false };\n\nconst CUSTOM_API = {\n 'openai-completions': openAICompletionsApi,\n 'openai-responses': openAIResponsesApi,\n 'anthropic-messages': anthropicMessagesApi,\n} as const;\n\n/** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */\nexport function customProvider(definition: PoCustomProviderDefinition): Provider {\n // Stored definitions are JSON: only a real `true` on a completions endpoint reaches the model.\n const compat =\n definition.api === 'openai-completions' && definition.requiresToolsWithToolHistory === true\n ? { compat: { requiresToolsWithToolHistory: true } }\n : {};\n return createProvider({\n id: definition.id,\n name: definition.name,\n baseUrl: definition.baseUrl,\n auth: { apiKey: envApiKeyAuth(`${definition.name} API key`, []) },\n models: definition.models.map((model) => ({\n id: model.id,\n name: model.name ?? model.id,\n api: definition.api,\n provider: definition.id,\n baseUrl: definition.baseUrl,\n reasoning: model.reasoning ?? false,\n input: [...(model.input ?? ['text'])],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: model.contextWindow ?? 128000,\n maxTokens: model.maxTokens ?? 16384,\n ...compat,\n })),\n api: CUSTOM_API[definition.api](),\n });\n}\n\n/** A URL without userinfo, query or fragment; unchanged when it carries none, so path joins keep working. */\nfunction publicUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return '';\n }\n if (url.username === '' && url.password === '' && url.search === '' && url.hash === '') return value;\n url.username = '';\n url.password = '';\n url.search = '';\n url.hash = '';\n return url.href;\n}\n\n/** A dynamic catalog fit to leave the owner: no headers, no URL secrets, data only. */\nexport function sanitizeModelsEntry(entry: ModelsStoreEntry): ModelsStoreEntry {\n return JSON.parse(\n JSON.stringify({\n ...entry,\n models: entry.models.map(({ headers: _headers, ...model }) => ({ ...model, baseUrl: publicUrl(model.baseUrl) })),\n }),\n ) as ModelsStoreEntry;\n}\n\nconst availableKey = (model: Pick<AnyModel, 'provider' | 'id'> & { type?: string }): string =>\n `${model.type ?? 'chat'}\\0${model.provider}\\0${model.id}`;\n\n/**\n * The owner side: a real pi-ai `Models` over the deployment target's credential store, so login, OAuth\n * refresh and request auth behave exactly as on a local machine. Every change that sessions can see\n * produces a new snapshot version.\n */\nexport function createProviderAuthOwner(options: ProviderAuthOwnerOptions): ProviderAuthOwner {\n // A failed recompute stays in `pending`, so settled() rethrows it to the next caller; the next change retries.\n const report = options.onError ?? ((): void => undefined);\n let pending: Promise<void> = Promise.resolve();\n const changed = (): Promise<void> => {\n pending = pending.then(recompute, recompute);\n return pending;\n };\n const credentials: CredentialStore = {\n read: (providerId, operation) => options.credentials.read(providerId, operation),\n list: (operation) => options.credentials.list(operation),\n modify: async (providerId, fn, operation) => {\n const result = await options.credentials.modify(providerId, fn, operation);\n void changed().catch(report);\n return result;\n },\n delete: async (providerId, operation) => {\n await options.credentials.delete(providerId, operation);\n void changed().catch(report);\n },\n };\n const models = createModels({ credentials, modelsStore: options.modelsStore, authContext: NO_AMBIENT_AUTH });\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(provider);\n\n let customProviders: readonly PoCustomProviderDefinition[] = [];\n const applyCustomProviders = (definitions: readonly PoCustomProviderDefinition[]): void => {\n for (const previous of customProviders)\n if (!definitions.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of definitions) models.setProvider(customProvider(definition));\n customProviders = definitions;\n };\n applyCustomProviders(options.customProviders ?? []);\n\n // Starts from the clock, so a restarted owner never repeats a version a session still holds.\n let version = Date.now();\n let lastBody = '';\n let current: PoProviderAuthSnapshot | undefined;\n async function recompute(): Promise<void> {\n const providers = models.getProviders();\n const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type]));\n const checks = await Promise.all(\n providers.map(async (provider) => ({\n provider,\n check: await models.checkAuth(provider.id).catch(() => undefined),\n })),\n );\n const catalogs: Record<string, ModelsStoreEntry> = {};\n for (const provider of providers) {\n if (provider.refreshModels === undefined) continue;\n const entry = await options.modelsStore.read(provider.id);\n if (entry !== undefined) catalogs[provider.id] = sanitizeModelsEntry(entry);\n }\n const body = {\n providers: checks.flatMap(({ provider, check }) =>\n check === undefined\n ? []\n : [\n {\n id: provider.id,\n type: check.type,\n source: stored.get(provider.id) === check.type ? 'stored' : check.source,\n subscription: check.type === 'oauth' && provider.auth.oauth?.isSubscription === true,\n },\n ],\n ),\n available: (await models.getAllAvailable()).map((model) => ({\n provider: model.provider,\n id: model.id,\n type: getModelType(model),\n })),\n models: catalogs,\n customProviders,\n };\n const serialized = JSON.stringify(body);\n if (serialized === lastBody && current !== undefined) return;\n lastBody = serialized;\n version += 1;\n current = { version, ...(JSON.parse(serialized) as Omit<PoProviderAuthSnapshot, 'version'>) };\n }\n const settled = async (): Promise<PoProviderAuthSnapshot> => {\n await pending;\n if (current === undefined) await changed();\n return current as PoProviderAuthSnapshot;\n };\n void changed().catch(report);\n\n const statusOf = (providerId: string) => current?.providers.find((entry) => entry.id === providerId);\n const refresh: PoProviderAuth['refresh'] = async (refreshOptions) => {\n const result = await models.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n await changed();\n const snapshot = await settled();\n return {\n version: snapshot.version,\n errors: Object.fromEntries([...result.errors].map(([providerId, error]) => [providerId, error.message])),\n };\n };\n\n const service: PoProviderAuth = {\n abiVersion: 1,\n resolveAuth: async (providerId) => {\n const auth = await models.getAuth(providerId);\n return { version: (await settled()).version, ...(auth === undefined ? {} : { auth }) };\n },\n snapshot: async (sinceVersion) => {\n const snapshot = await settled();\n return sinceVersion === snapshot.version ? { version: snapshot.version } : snapshot;\n },\n refresh,\n };\n\n const authRuntime: AuthRuntime = {\n getProviders: () => models.getProviders(),\n getProviderAuthStatus: (providerId) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n getAvailableSnapshot: () => (current?.available ?? []).filter((model) => model.type === 'chat'),\n hasConfiguredAuth: (providerId) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId) => statusOf(providerId)?.type === 'oauth',\n refresh: (refreshOptions) => refresh(refreshOptions),\n login: async (providerId, type, interaction) => {\n await models.login(providerId, type, interaction as AuthInteraction);\n await settled();\n },\n logout: async (providerId, logoutOptions) => {\n await models.logout(providerId, logoutOptions);\n await settled();\n },\n };\n\n return {\n service,\n authRuntime,\n setCustomProviders: async (definitions) => {\n applyCustomProviders(definitions);\n await changed();\n },\n };\n}\n\n/** Session credentials stay empty: every request's auth comes from the owner and is never kept. */\nconst NO_SESSION_CREDENTIALS: CredentialStore = {\n read: async () => undefined,\n list: async () => [],\n modify: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n delete: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n};\n\n/**\n * The session side: pi-ai `Models` with the same providers as the owner, whose auth asks the owner and\n * whose status and availability come from the owner's snapshot. Requests, streaming and header merges\n * run locally, unchanged; the session never holds a credential.\n */\nexport async function createOwnerBackedModelRuntime(options: OwnerBackedModelRuntimeOptions): Promise<PoModelRuntime> {\n const { owner } = options;\n let snapshot: PoProviderAuthSnapshot | undefined;\n let availableKeys = new Set<string>();\n const statusOf = (providerId: string) => snapshot?.providers.find((entry) => entry.id === providerId);\n const isAvailable = (model: AnyModel): boolean =>\n availableKeys.has(availableKey({ provider: model.provider, id: model.id, type: getModelType(model) }));\n\n const modelsStore: ModelsStore = {\n read: async (providerId) => snapshot?.models[providerId],\n // The owner persists catalogs; a session only restores the snapshot's copy.\n write: async () => undefined,\n delete: async () => undefined,\n };\n const models = createModels({\n credentials: NO_SESSION_CREDENTIALS,\n modelsStore,\n authContext: NO_AMBIENT_AUTH,\n });\n\n // A failed sync keeps the last snapshot; the next version the owner reports retries it.\n const report = options.onError ?? ((): void => undefined);\n let syncing: Promise<void> = Promise.resolve();\n const pull = async (): Promise<void> => {\n const next = await owner.snapshot(snapshot?.version);\n if (!('providers' in next)) return;\n const previousCustom = snapshot?.customProviders ?? [];\n snapshot = next;\n availableKeys = new Set(next.available.map(availableKey));\n for (const previous of previousCustom)\n if (!next.customProviders.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of next.customProviders) models.setProvider(ownerBacked(customProvider(definition)));\n await models.refresh({ allowNetwork: false });\n };\n const sync = (): Promise<void> => {\n syncing = syncing.then(pull, pull);\n return syncing;\n };\n const observe = (version: number): void => {\n if (version !== snapshot?.version) void sync().catch(report);\n };\n\n const ownerBacked = (provider: Provider): Provider => {\n const apiKey = provider.auth.apiKey;\n return {\n ...provider,\n auth: {\n ...provider.auth,\n apiKey: {\n name: apiKey?.name ?? provider.name,\n check: async () => {\n const status = statusOf(provider.id);\n return status === undefined\n ? undefined\n : { type: status.type, ...(status.source === undefined ? {} : { source: status.source }) };\n },\n resolve: async ({ credential, signal }) => {\n // A key the caller passed for this request resolves locally, as it would on a machine.\n if (credential?.key !== undefined && apiKey !== undefined)\n return apiKey.resolve({ ctx: NO_AMBIENT_AUTH, credential, signal });\n const result = await owner.resolveAuth(provider.id);\n observe(result.version);\n return result.auth;\n },\n },\n },\n filterModels: (list) => list.filter(isAvailable),\n filterAllModels: (list) => list.filter(isAvailable),\n } as Provider;\n };\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(ownerBacked(provider));\n await sync();\n\n const managedByAdmins = async (): Promise<never> => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n };\n const refused = (): never => {\n throw new ModelsError('provider', MANAGED_BY_ADMINS);\n };\n return {\n getProviders: models.getProviders.bind(models),\n getProvider: models.getProvider.bind(models),\n getModels: models.getModels.bind(models),\n getModel: models.getModel.bind(models),\n getModelsOfType: models.getModelsOfType.bind(models),\n getModelOfType: models.getModelOfType.bind(models),\n getAllModels: models.getAllModels.bind(models),\n checkAuth: models.checkAuth.bind(models),\n getAvailable: models.getAvailable.bind(models),\n getAvailableOfType: models.getAvailableOfType.bind(models),\n getAllAvailable: models.getAllAvailable.bind(models),\n getAuth: models.getAuth.bind(models),\n stream: models.stream.bind(models),\n complete: models.complete.bind(models),\n streamSimple: models.streamSimple.bind(models),\n completeSimple: models.completeSimple.bind(models),\n streamDeferred: models.streamDeferred.bind(models),\n fetchDeferred: models.fetchDeferred.bind(models),\n cancelDeferred: models.cancelDeferred.bind(models),\n generateImages: models.generateImages.bind(models),\n classify: models.classify.bind(models),\n refresh: async (refreshOptions?: { allowNetwork?: boolean }) => {\n const result = await owner.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n if (result.version !== snapshot?.version) await sync();\n return {\n aborted: false,\n errors: new Map(\n Object.entries(result.errors).map(([providerId, message]) => [\n providerId,\n new ModelsError('model_source', message),\n ]),\n ),\n };\n },\n getAvailableSnapshot: () => models.getModels().filter(isAvailable),\n getError: () => undefined,\n hasConfiguredAuth: (providerId: string) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId: string) => statusOf(providerId)?.type === 'oauth',\n isUsingSubscription: (providerId: string) => statusOf(providerId)?.subscription === true,\n getProviderAuthStatus: (providerId: string) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n login: managedByAdmins,\n logout: managedByAdmins,\n setRuntimeApiKey: managedByAdmins,\n removeRuntimeApiKey: managedByAdmins,\n listCredentials: async () => [],\n getRegisteredNativeProvider: () => undefined,\n getRegisteredProviderConfig: () => undefined,\n getRegisteredProviderIds: () => [],\n getCompatibilityRequestConfig: refused,\n registerProvider: refused,\n registerNativeProvider: refused,\n unregisterProvider: refused,\n registerVirtualModel: refused,\n unregisterVirtualModel: refused,\n } as unkn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,MAAM,MAAM,QAAQ,EAAE,cAAc,gBAAgB,gBAAgB,KAAK,CAAC;GACzF,IAAI,OAAO,YAAY,UAAU,SAAS,MAAM,KAAK;GACrD,OAAO;IACL,SAAS;IACT,QAAQ,IAAI,IACV,OAAO,QAAQ,OAAO,MAAM,CAAC,CAAC,KAAK,CAAC,YAAY,aAAa,CAC3D,YACA,IAAIA,sBAAAA,YAAY,gBAAgB,OAAO,CACzC,CAAC,CACH;GACF;EACF;EACA,4BAA4B,OAAO,UAAU,CAAC,CAAC,OAAO,WAAW;EACjE,gBAAgB,KAAA;EAChB,oBAAoB,eAAuB,SAAS,UAAU,MAAM,KAAA;EACpE,eAAe,eAAuB,SAAS,UAAU,CAAC,EAAE,SAAS;EACrE,sBAAsB,eAAuB,SAAS,UAAU,CAAC,EAAE,iBAAiB;EACpF,wBAAwB,eAAuB;GAC7C,MAAM,SAAS,SAAS,UAAU;GAClC,OAAO,WAAW,KAAA,IAAY,EAAE,YAAY,MAAM,IAAI;IAAE,YAAY;IAAM,QAAQ,OAAO;GAAO;EAClG;EACA,OAAO;EACP,QAAQ;EACR,kBAAkB;EAClB,qBAAqB;EACrB,iBAAiB,YAAY,CAAC;EAC9B,mCAAmC,KAAA;EACnC,mCAAmC,KAAA;EACnC,gCAAgC,CAAC;EACjC,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,oBAAoB;EACpB,sBAAsB;EACtB,wBAAwB;CAC1B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"mappings":";;;;;;wBAsCgB,eAAe,YAAY,6BAA6B;;wBAuCxD,oBAAoB,OAAO,mBAAmB;;;;;;wBAiB9C,wBAAwB,SAAS,2BAA2B;;;;;;wBA6JtD,8BAA8B,SAAS,iCAAiC,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"mappings":";;;;;;wBAsCgB,eAAe,YAAY,6BAA6B;;wBA6CxD,oBAAoB,OAAO,mBAAmB;;;;;;wBAiB9C,wBAAwB,SAAS,2BAA2B;;;;;;wBA6JtD,8BAA8B,SAAS,iCAAiC,QAAQ"}
@@ -17,6 +17,7 @@ const CUSTOM_API = {
17
17
  };
18
18
  /** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */
19
19
  function customProvider(definition) {
20
+ const compat = definition.api === "openai-completions" && definition.requiresToolsWithToolHistory === true ? { compat: { requiresToolsWithToolHistory: true } } : {};
20
21
  return createProvider({
21
22
  id: definition.id,
22
23
  name: definition.name,
@@ -37,7 +38,8 @@ function customProvider(definition) {
37
38
  cacheWrite: 0
38
39
  },
39
40
  contextWindow: model.contextWindow ?? 128e3,
40
- maxTokens: model.maxTokens ?? 16384
41
+ maxTokens: model.maxTokens ?? 16384,
42
+ ...compat
41
43
  })),
42
44
  api: CUSTOM_API[definition.api]()
43
45
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"sourcesContent":["import {\n createModels,\n createProvider,\n envApiKeyAuth,\n getModelType,\n ModelsError,\n type AnyModel,\n type AuthContext,\n type AuthInteraction,\n type CredentialStore,\n type ModelsStore,\n type ModelsStoreEntry,\n type Provider,\n} from '@earendil-works/pi-ai';\nimport { anthropicMessagesApi } from '@earendil-works/pi-ai/api/anthropic-messages.lazy';\nimport { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';\nimport { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy';\nimport { builtinProviders } from '@earendil-works/pi-ai/providers/all';\n\nimport type { PoCustomProviderDefinition, PoProviderAuth, PoProviderAuthSnapshot } from '../../schemas/platform';\nimport type { PoModelRuntime } from '../../systems/main/types/headlessSessionHost';\nimport type { AuthRuntime } from '../../types/server/auth';\nimport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nexport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nconst MANAGED_BY_ADMINS = 'Org admins manage providers in Settings → Providers.';\n\n/** No env vars or ambient files: on a shared host they belong to the host, not to the deployment target. */\nconst NO_AMBIENT_AUTH: AuthContext = { env: async () => undefined, fileExists: async () => false };\n\nconst CUSTOM_API = {\n 'openai-completions': openAICompletionsApi,\n 'openai-responses': openAIResponsesApi,\n 'anthropic-messages': anthropicMessagesApi,\n} as const;\n\n/** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */\nexport function customProvider(definition: PoCustomProviderDefinition): Provider {\n return createProvider({\n id: definition.id,\n name: definition.name,\n baseUrl: definition.baseUrl,\n auth: { apiKey: envApiKeyAuth(`${definition.name} API key`, []) },\n models: definition.models.map((model) => ({\n id: model.id,\n name: model.name ?? model.id,\n api: definition.api,\n provider: definition.id,\n baseUrl: definition.baseUrl,\n reasoning: model.reasoning ?? false,\n input: [...(model.input ?? ['text'])],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: model.contextWindow ?? 128000,\n maxTokens: model.maxTokens ?? 16384,\n })),\n api: CUSTOM_API[definition.api](),\n });\n}\n\n/** A URL without userinfo, query or fragment; unchanged when it carries none, so path joins keep working. */\nfunction publicUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return '';\n }\n if (url.username === '' && url.password === '' && url.search === '' && url.hash === '') return value;\n url.username = '';\n url.password = '';\n url.search = '';\n url.hash = '';\n return url.href;\n}\n\n/** A dynamic catalog fit to leave the owner: no headers, no URL secrets, data only. */\nexport function sanitizeModelsEntry(entry: ModelsStoreEntry): ModelsStoreEntry {\n return JSON.parse(\n JSON.stringify({\n ...entry,\n models: entry.models.map(({ headers: _headers, ...model }) => ({ ...model, baseUrl: publicUrl(model.baseUrl) })),\n }),\n ) as ModelsStoreEntry;\n}\n\nconst availableKey = (model: Pick<AnyModel, 'provider' | 'id'> & { type?: string }): string =>\n `${model.type ?? 'chat'}\\0${model.provider}\\0${model.id}`;\n\n/**\n * The owner side: a real pi-ai `Models` over the deployment target's credential store, so login, OAuth\n * refresh and request auth behave exactly as on a local machine. Every change that sessions can see\n * produces a new snapshot version.\n */\nexport function createProviderAuthOwner(options: ProviderAuthOwnerOptions): ProviderAuthOwner {\n // A failed recompute stays in `pending`, so settled() rethrows it to the next caller; the next change retries.\n const report = options.onError ?? ((): void => undefined);\n let pending: Promise<void> = Promise.resolve();\n const changed = (): Promise<void> => {\n pending = pending.then(recompute, recompute);\n return pending;\n };\n const credentials: CredentialStore = {\n read: (providerId, operation) => options.credentials.read(providerId, operation),\n list: (operation) => options.credentials.list(operation),\n modify: async (providerId, fn, operation) => {\n const result = await options.credentials.modify(providerId, fn, operation);\n void changed().catch(report);\n return result;\n },\n delete: async (providerId, operation) => {\n await options.credentials.delete(providerId, operation);\n void changed().catch(report);\n },\n };\n const models = createModels({ credentials, modelsStore: options.modelsStore, authContext: NO_AMBIENT_AUTH });\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(provider);\n\n let customProviders: readonly PoCustomProviderDefinition[] = [];\n const applyCustomProviders = (definitions: readonly PoCustomProviderDefinition[]): void => {\n for (const previous of customProviders)\n if (!definitions.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of definitions) models.setProvider(customProvider(definition));\n customProviders = definitions;\n };\n applyCustomProviders(options.customProviders ?? []);\n\n // Starts from the clock, so a restarted owner never repeats a version a session still holds.\n let version = Date.now();\n let lastBody = '';\n let current: PoProviderAuthSnapshot | undefined;\n async function recompute(): Promise<void> {\n const providers = models.getProviders();\n const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type]));\n const checks = await Promise.all(\n providers.map(async (provider) => ({\n provider,\n check: await models.checkAuth(provider.id).catch(() => undefined),\n })),\n );\n const catalogs: Record<string, ModelsStoreEntry> = {};\n for (const provider of providers) {\n if (provider.refreshModels === undefined) continue;\n const entry = await options.modelsStore.read(provider.id);\n if (entry !== undefined) catalogs[provider.id] = sanitizeModelsEntry(entry);\n }\n const body = {\n providers: checks.flatMap(({ provider, check }) =>\n check === undefined\n ? []\n : [\n {\n id: provider.id,\n type: check.type,\n source: stored.get(provider.id) === check.type ? 'stored' : check.source,\n subscription: check.type === 'oauth' && provider.auth.oauth?.isSubscription === true,\n },\n ],\n ),\n available: (await models.getAllAvailable()).map((model) => ({\n provider: model.provider,\n id: model.id,\n type: getModelType(model),\n })),\n models: catalogs,\n customProviders,\n };\n const serialized = JSON.stringify(body);\n if (serialized === lastBody && current !== undefined) return;\n lastBody = serialized;\n version += 1;\n current = { version, ...(JSON.parse(serialized) as Omit<PoProviderAuthSnapshot, 'version'>) };\n }\n const settled = async (): Promise<PoProviderAuthSnapshot> => {\n await pending;\n if (current === undefined) await changed();\n return current as PoProviderAuthSnapshot;\n };\n void changed().catch(report);\n\n const statusOf = (providerId: string) => current?.providers.find((entry) => entry.id === providerId);\n const refresh: PoProviderAuth['refresh'] = async (refreshOptions) => {\n const result = await models.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n await changed();\n const snapshot = await settled();\n return {\n version: snapshot.version,\n errors: Object.fromEntries([...result.errors].map(([providerId, error]) => [providerId, error.message])),\n };\n };\n\n const service: PoProviderAuth = {\n abiVersion: 1,\n resolveAuth: async (providerId) => {\n const auth = await models.getAuth(providerId);\n return { version: (await settled()).version, ...(auth === undefined ? {} : { auth }) };\n },\n snapshot: async (sinceVersion) => {\n const snapshot = await settled();\n return sinceVersion === snapshot.version ? { version: snapshot.version } : snapshot;\n },\n refresh,\n };\n\n const authRuntime: AuthRuntime = {\n getProviders: () => models.getProviders(),\n getProviderAuthStatus: (providerId) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n getAvailableSnapshot: () => (current?.available ?? []).filter((model) => model.type === 'chat'),\n hasConfiguredAuth: (providerId) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId) => statusOf(providerId)?.type === 'oauth',\n refresh: (refreshOptions) => refresh(refreshOptions),\n login: async (providerId, type, interaction) => {\n await models.login(providerId, type, interaction as AuthInteraction);\n await settled();\n },\n logout: async (providerId, logoutOptions) => {\n await models.logout(providerId, logoutOptions);\n await settled();\n },\n };\n\n return {\n service,\n authRuntime,\n setCustomProviders: async (definitions) => {\n applyCustomProviders(definitions);\n await changed();\n },\n };\n}\n\n/** Session credentials stay empty: every request's auth comes from the owner and is never kept. */\nconst NO_SESSION_CREDENTIALS: CredentialStore = {\n read: async () => undefined,\n list: async () => [],\n modify: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n delete: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n};\n\n/**\n * The session side: pi-ai `Models` with the same providers as the owner, whose auth asks the owner and\n * whose status and availability come from the owner's snapshot. Requests, streaming and header merges\n * run locally, unchanged; the session never holds a credential.\n */\nexport async function createOwnerBackedModelRuntime(options: OwnerBackedModelRuntimeOptions): Promise<PoModelRuntime> {\n const { owner } = options;\n let snapshot: PoProviderAuthSnapshot | undefined;\n let availableKeys = new Set<string>();\n const statusOf = (providerId: string) => snapshot?.providers.find((entry) => entry.id === providerId);\n const isAvailable = (model: AnyModel): boolean =>\n availableKeys.has(availableKey({ provider: model.provider, id: model.id, type: getModelType(model) }));\n\n const modelsStore: ModelsStore = {\n read: async (providerId) => snapshot?.models[providerId],\n // The owner persists catalogs; a session only restores the snapshot's copy.\n write: async () => undefined,\n delete: async () => undefined,\n };\n const models = createModels({\n credentials: NO_SESSION_CREDENTIALS,\n modelsStore,\n authContext: NO_AMBIENT_AUTH,\n });\n\n // A failed sync keeps the last snapshot; the next version the owner reports retries it.\n const report = options.onError ?? ((): void => undefined);\n let syncing: Promise<void> = Promise.resolve();\n const pull = async (): Promise<void> => {\n const next = await owner.snapshot(snapshot?.version);\n if (!('providers' in next)) return;\n const previousCustom = snapshot?.customProviders ?? [];\n snapshot = next;\n availableKeys = new Set(next.available.map(availableKey));\n for (const previous of previousCustom)\n if (!next.customProviders.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of next.customProviders) models.setProvider(ownerBacked(customProvider(definition)));\n await models.refresh({ allowNetwork: false });\n };\n const sync = (): Promise<void> => {\n syncing = syncing.then(pull, pull);\n return syncing;\n };\n const observe = (version: number): void => {\n if (version !== snapshot?.version) void sync().catch(report);\n };\n\n const ownerBacked = (provider: Provider): Provider => {\n const apiKey = provider.auth.apiKey;\n return {\n ...provider,\n auth: {\n ...provider.auth,\n apiKey: {\n name: apiKey?.name ?? provider.name,\n check: async () => {\n const status = statusOf(provider.id);\n return status === undefined\n ? undefined\n : { type: status.type, ...(status.source === undefined ? {} : { source: status.source }) };\n },\n resolve: async ({ credential, signal }) => {\n // A key the caller passed for this request resolves locally, as it would on a machine.\n if (credential?.key !== undefined && apiKey !== undefined)\n return apiKey.resolve({ ctx: NO_AMBIENT_AUTH, credential, signal });\n const result = await owner.resolveAuth(provider.id);\n observe(result.version);\n return result.auth;\n },\n },\n },\n filterModels: (list) => list.filter(isAvailable),\n filterAllModels: (list) => list.filter(isAvailable),\n } as Provider;\n };\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(ownerBacked(provider));\n await sync();\n\n const managedByAdmins = async (): Promise<never> => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n };\n const refused = (): never => {\n throw new ModelsError('provider', MANAGED_BY_ADMINS);\n };\n return {\n getProviders: models.getProviders.bind(models),\n getProvider: models.getProvider.bind(models),\n getModels: models.getModels.bind(models),\n getModel: models.getModel.bind(models),\n getModelsOfType: models.getModelsOfType.bind(models),\n getModelOfType: models.getModelOfType.bind(models),\n getAllModels: models.getAllModels.bind(models),\n checkAuth: models.checkAuth.bind(models),\n getAvailable: models.getAvailable.bind(models),\n getAvailableOfType: models.getAvailableOfType.bind(models),\n getAllAvailable: models.getAllAvailable.bind(models),\n getAuth: models.getAuth.bind(models),\n stream: models.stream.bind(models),\n complete: models.complete.bind(models),\n streamSimple: models.streamSimple.bind(models),\n completeSimple: models.completeSimple.bind(models),\n streamDeferred: models.streamDeferred.bind(models),\n fetchDeferred: models.fetchDeferred.bind(models),\n cancelDeferred: models.cancelDeferred.bind(models),\n generateImages: models.generateImages.bind(models),\n classify: models.classify.bind(models),\n refresh: async (refreshOptions?: { allowNetwork?: boolean }) => {\n const result = await owner.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n if (result.version !== snapshot?.version) await sync();\n return {\n aborted: false,\n errors: new Map(\n Object.entries(result.errors).map(([providerId, message]) => [\n providerId,\n new ModelsError('model_source', message),\n ]),\n ),\n };\n },\n getAvailableSnapshot: () => models.getModels().filter(isAvailable),\n getError: () => undefined,\n hasConfiguredAuth: (providerId: string) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId: string) => statusOf(providerId)?.type === 'oauth',\n isUsingSubscription: (providerId: string) => statusOf(providerId)?.subscription === true,\n getProviderAuthStatus: (providerId: string) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n login: managedByAdmins,\n logout: managedByAdmins,\n setRuntimeApiKey: managedByAdmins,\n removeRuntimeApiKey: managedByAdmins,\n listCredentials: async () => [],\n getRegisteredNativeProvider: () => undefined,\n getRegisteredProviderConfig: () => undefined,\n getRegisteredProviderIds: () => [],\n getCompatibilityRequestConfig: refused,\n registerProvider: refused,\n registerNativeProvider: refused,\n unregisterProvider: refused,\n registerVirtualModel: refused,\n unregisterVirtualModel: refused,\n } as unknown as PoModelRuntime;\n}\n"],"mappings":";;;;;;AA0BA,MAAM,oBAAoB;;AAG1B,MAAM,kBAA+B;CAAE,KAAK,YAAY,KAAA;CAAW,YAAY,YAAY;AAAM;AAEjG,MAAM,aAAa;CACjB,sBAAsB;CACtB,oBAAoB;CACpB,sBAAsB;AACxB;;AAGA,SAAgB,eAAe,YAAkD;CAC/E,OAAO,eAAe;EACpB,IAAI,WAAW;EACf,MAAM,WAAW;EACjB,SAAS,WAAW;EACp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EAClG;EACA,OAAO;EACP,QAAQ;EACR,kBAAkB;EAClB,qBAAqB;EACrB,iBAAiB,YAAY,CAAC;EAC9B,mCAAmC,KAAA;EACnC,mCAAmC,KAAA;EACnC,gCAAgC,CAAC;EACjC,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,oBAAoB;EACpB,sBAAsB;EACtB,wBAAwB;CAC1B;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/edgeModelRuntime/index.ts"],"sourcesContent":["import {\n createModels,\n createProvider,\n envApiKeyAuth,\n getModelType,\n ModelsError,\n type AnyModel,\n type AuthContext,\n type AuthInteraction,\n type CredentialStore,\n type ModelsStore,\n type ModelsStoreEntry,\n type Provider,\n} from '@earendil-works/pi-ai';\nimport { anthropicMessagesApi } from '@earendil-works/pi-ai/api/anthropic-messages.lazy';\nimport { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';\nimport { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy';\nimport { builtinProviders } from '@earendil-works/pi-ai/providers/all';\n\nimport type { PoCustomProviderDefinition, PoProviderAuth, PoProviderAuthSnapshot } from '../../schemas/platform';\nimport type { PoModelRuntime } from '../../systems/main/types/headlessSessionHost';\nimport type { AuthRuntime } from '../../types/server/auth';\nimport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nexport type { OwnerBackedModelRuntimeOptions, ProviderAuthOwner, ProviderAuthOwnerOptions } from './type';\n\nconst MANAGED_BY_ADMINS = 'Org admins manage providers in Settings → Providers.';\n\n/** No env vars or ambient files: on a shared host they belong to the host, not to the deployment target. */\nconst NO_AMBIENT_AUTH: AuthContext = { env: async () => undefined, fileExists: async () => false };\n\nconst CUSTOM_API = {\n 'openai-completions': openAICompletionsApi,\n 'openai-responses': openAIResponsesApi,\n 'anthropic-messages': anthropicMessagesApi,\n} as const;\n\n/** A hand-added endpoint as a provider, with the defaults Pi gives a models.json provider. */\nexport function customProvider(definition: PoCustomProviderDefinition): Provider {\n // Stored definitions are JSON: only a real `true` on a completions endpoint reaches the model.\n const compat =\n definition.api === 'openai-completions' && definition.requiresToolsWithToolHistory === true\n ? { compat: { requiresToolsWithToolHistory: true } }\n : {};\n return createProvider({\n id: definition.id,\n name: definition.name,\n baseUrl: definition.baseUrl,\n auth: { apiKey: envApiKeyAuth(`${definition.name} API key`, []) },\n models: definition.models.map((model) => ({\n id: model.id,\n name: model.name ?? model.id,\n api: definition.api,\n provider: definition.id,\n baseUrl: definition.baseUrl,\n reasoning: model.reasoning ?? false,\n input: [...(model.input ?? ['text'])],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: model.contextWindow ?? 128000,\n maxTokens: model.maxTokens ?? 16384,\n ...compat,\n })),\n api: CUSTOM_API[definition.api](),\n });\n}\n\n/** A URL without userinfo, query or fragment; unchanged when it carries none, so path joins keep working. */\nfunction publicUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return '';\n }\n if (url.username === '' && url.password === '' && url.search === '' && url.hash === '') return value;\n url.username = '';\n url.password = '';\n url.search = '';\n url.hash = '';\n return url.href;\n}\n\n/** A dynamic catalog fit to leave the owner: no headers, no URL secrets, data only. */\nexport function sanitizeModelsEntry(entry: ModelsStoreEntry): ModelsStoreEntry {\n return JSON.parse(\n JSON.stringify({\n ...entry,\n models: entry.models.map(({ headers: _headers, ...model }) => ({ ...model, baseUrl: publicUrl(model.baseUrl) })),\n }),\n ) as ModelsStoreEntry;\n}\n\nconst availableKey = (model: Pick<AnyModel, 'provider' | 'id'> & { type?: string }): string =>\n `${model.type ?? 'chat'}\\0${model.provider}\\0${model.id}`;\n\n/**\n * The owner side: a real pi-ai `Models` over the deployment target's credential store, so login, OAuth\n * refresh and request auth behave exactly as on a local machine. Every change that sessions can see\n * produces a new snapshot version.\n */\nexport function createProviderAuthOwner(options: ProviderAuthOwnerOptions): ProviderAuthOwner {\n // A failed recompute stays in `pending`, so settled() rethrows it to the next caller; the next change retries.\n const report = options.onError ?? ((): void => undefined);\n let pending: Promise<void> = Promise.resolve();\n const changed = (): Promise<void> => {\n pending = pending.then(recompute, recompute);\n return pending;\n };\n const credentials: CredentialStore = {\n read: (providerId, operation) => options.credentials.read(providerId, operation),\n list: (operation) => options.credentials.list(operation),\n modify: async (providerId, fn, operation) => {\n const result = await options.credentials.modify(providerId, fn, operation);\n void changed().catch(report);\n return result;\n },\n delete: async (providerId, operation) => {\n await options.credentials.delete(providerId, operation);\n void changed().catch(report);\n },\n };\n const models = createModels({ credentials, modelsStore: options.modelsStore, authContext: NO_AMBIENT_AUTH });\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(provider);\n\n let customProviders: readonly PoCustomProviderDefinition[] = [];\n const applyCustomProviders = (definitions: readonly PoCustomProviderDefinition[]): void => {\n for (const previous of customProviders)\n if (!definitions.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of definitions) models.setProvider(customProvider(definition));\n customProviders = definitions;\n };\n applyCustomProviders(options.customProviders ?? []);\n\n // Starts from the clock, so a restarted owner never repeats a version a session still holds.\n let version = Date.now();\n let lastBody = '';\n let current: PoProviderAuthSnapshot | undefined;\n async function recompute(): Promise<void> {\n const providers = models.getProviders();\n const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type]));\n const checks = await Promise.all(\n providers.map(async (provider) => ({\n provider,\n check: await models.checkAuth(provider.id).catch(() => undefined),\n })),\n );\n const catalogs: Record<string, ModelsStoreEntry> = {};\n for (const provider of providers) {\n if (provider.refreshModels === undefined) continue;\n const entry = await options.modelsStore.read(provider.id);\n if (entry !== undefined) catalogs[provider.id] = sanitizeModelsEntry(entry);\n }\n const body = {\n providers: checks.flatMap(({ provider, check }) =>\n check === undefined\n ? []\n : [\n {\n id: provider.id,\n type: check.type,\n source: stored.get(provider.id) === check.type ? 'stored' : check.source,\n subscription: check.type === 'oauth' && provider.auth.oauth?.isSubscription === true,\n },\n ],\n ),\n available: (await models.getAllAvailable()).map((model) => ({\n provider: model.provider,\n id: model.id,\n type: getModelType(model),\n })),\n models: catalogs,\n customProviders,\n };\n const serialized = JSON.stringify(body);\n if (serialized === lastBody && current !== undefined) return;\n lastBody = serialized;\n version += 1;\n current = { version, ...(JSON.parse(serialized) as Omit<PoProviderAuthSnapshot, 'version'>) };\n }\n const settled = async (): Promise<PoProviderAuthSnapshot> => {\n await pending;\n if (current === undefined) await changed();\n return current as PoProviderAuthSnapshot;\n };\n void changed().catch(report);\n\n const statusOf = (providerId: string) => current?.providers.find((entry) => entry.id === providerId);\n const refresh: PoProviderAuth['refresh'] = async (refreshOptions) => {\n const result = await models.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n await changed();\n const snapshot = await settled();\n return {\n version: snapshot.version,\n errors: Object.fromEntries([...result.errors].map(([providerId, error]) => [providerId, error.message])),\n };\n };\n\n const service: PoProviderAuth = {\n abiVersion: 1,\n resolveAuth: async (providerId) => {\n const auth = await models.getAuth(providerId);\n return { version: (await settled()).version, ...(auth === undefined ? {} : { auth }) };\n },\n snapshot: async (sinceVersion) => {\n const snapshot = await settled();\n return sinceVersion === snapshot.version ? { version: snapshot.version } : snapshot;\n },\n refresh,\n };\n\n const authRuntime: AuthRuntime = {\n getProviders: () => models.getProviders(),\n getProviderAuthStatus: (providerId) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n getAvailableSnapshot: () => (current?.available ?? []).filter((model) => model.type === 'chat'),\n hasConfiguredAuth: (providerId) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId) => statusOf(providerId)?.type === 'oauth',\n refresh: (refreshOptions) => refresh(refreshOptions),\n login: async (providerId, type, interaction) => {\n await models.login(providerId, type, interaction as AuthInteraction);\n await settled();\n },\n logout: async (providerId, logoutOptions) => {\n await models.logout(providerId, logoutOptions);\n await settled();\n },\n };\n\n return {\n service,\n authRuntime,\n setCustomProviders: async (definitions) => {\n applyCustomProviders(definitions);\n await changed();\n },\n };\n}\n\n/** Session credentials stay empty: every request's auth comes from the owner and is never kept. */\nconst NO_SESSION_CREDENTIALS: CredentialStore = {\n read: async () => undefined,\n list: async () => [],\n modify: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n delete: async () => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n },\n};\n\n/**\n * The session side: pi-ai `Models` with the same providers as the owner, whose auth asks the owner and\n * whose status and availability come from the owner's snapshot. Requests, streaming and header merges\n * run locally, unchanged; the session never holds a credential.\n */\nexport async function createOwnerBackedModelRuntime(options: OwnerBackedModelRuntimeOptions): Promise<PoModelRuntime> {\n const { owner } = options;\n let snapshot: PoProviderAuthSnapshot | undefined;\n let availableKeys = new Set<string>();\n const statusOf = (providerId: string) => snapshot?.providers.find((entry) => entry.id === providerId);\n const isAvailable = (model: AnyModel): boolean =>\n availableKeys.has(availableKey({ provider: model.provider, id: model.id, type: getModelType(model) }));\n\n const modelsStore: ModelsStore = {\n read: async (providerId) => snapshot?.models[providerId],\n // The owner persists catalogs; a session only restores the snapshot's copy.\n write: async () => undefined,\n delete: async () => undefined,\n };\n const models = createModels({\n credentials: NO_SESSION_CREDENTIALS,\n modelsStore,\n authContext: NO_AMBIENT_AUTH,\n });\n\n // A failed sync keeps the last snapshot; the next version the owner reports retries it.\n const report = options.onError ?? ((): void => undefined);\n let syncing: Promise<void> = Promise.resolve();\n const pull = async (): Promise<void> => {\n const next = await owner.snapshot(snapshot?.version);\n if (!('providers' in next)) return;\n const previousCustom = snapshot?.customProviders ?? [];\n snapshot = next;\n availableKeys = new Set(next.available.map(availableKey));\n for (const previous of previousCustom)\n if (!next.customProviders.some((definition) => definition.id === previous.id)) models.deleteProvider(previous.id);\n for (const definition of next.customProviders) models.setProvider(ownerBacked(customProvider(definition)));\n await models.refresh({ allowNetwork: false });\n };\n const sync = (): Promise<void> => {\n syncing = syncing.then(pull, pull);\n return syncing;\n };\n const observe = (version: number): void => {\n if (version !== snapshot?.version) void sync().catch(report);\n };\n\n const ownerBacked = (provider: Provider): Provider => {\n const apiKey = provider.auth.apiKey;\n return {\n ...provider,\n auth: {\n ...provider.auth,\n apiKey: {\n name: apiKey?.name ?? provider.name,\n check: async () => {\n const status = statusOf(provider.id);\n return status === undefined\n ? undefined\n : { type: status.type, ...(status.source === undefined ? {} : { source: status.source }) };\n },\n resolve: async ({ credential, signal }) => {\n // A key the caller passed for this request resolves locally, as it would on a machine.\n if (credential?.key !== undefined && apiKey !== undefined)\n return apiKey.resolve({ ctx: NO_AMBIENT_AUTH, credential, signal });\n const result = await owner.resolveAuth(provider.id);\n observe(result.version);\n return result.auth;\n },\n },\n },\n filterModels: (list) => list.filter(isAvailable),\n filterAllModels: (list) => list.filter(isAvailable),\n } as Provider;\n };\n for (const provider of (options.providers ?? builtinProviders)()) models.setProvider(ownerBacked(provider));\n await sync();\n\n const managedByAdmins = async (): Promise<never> => {\n throw new ModelsError('auth', MANAGED_BY_ADMINS);\n };\n const refused = (): never => {\n throw new ModelsError('provider', MANAGED_BY_ADMINS);\n };\n return {\n getProviders: models.getProviders.bind(models),\n getProvider: models.getProvider.bind(models),\n getModels: models.getModels.bind(models),\n getModel: models.getModel.bind(models),\n getModelsOfType: models.getModelsOfType.bind(models),\n getModelOfType: models.getModelOfType.bind(models),\n getAllModels: models.getAllModels.bind(models),\n checkAuth: models.checkAuth.bind(models),\n getAvailable: models.getAvailable.bind(models),\n getAvailableOfType: models.getAvailableOfType.bind(models),\n getAllAvailable: models.getAllAvailable.bind(models),\n getAuth: models.getAuth.bind(models),\n stream: models.stream.bind(models),\n complete: models.complete.bind(models),\n streamSimple: models.streamSimple.bind(models),\n completeSimple: models.completeSimple.bind(models),\n streamDeferred: models.streamDeferred.bind(models),\n fetchDeferred: models.fetchDeferred.bind(models),\n cancelDeferred: models.cancelDeferred.bind(models),\n generateImages: models.generateImages.bind(models),\n classify: models.classify.bind(models),\n refresh: async (refreshOptions?: { allowNetwork?: boolean }) => {\n const result = await owner.refresh({ allowNetwork: refreshOptions?.allowNetwork ?? true });\n if (result.version !== snapshot?.version) await sync();\n return {\n aborted: false,\n errors: new Map(\n Object.entries(result.errors).map(([providerId, message]) => [\n providerId,\n new ModelsError('model_source', message),\n ]),\n ),\n };\n },\n getAvailableSnapshot: () => models.getModels().filter(isAvailable),\n getError: () => undefined,\n hasConfiguredAuth: (providerId: string) => statusOf(providerId) !== undefined,\n isUsingOAuth: (providerId: string) => statusOf(providerId)?.type === 'oauth',\n isUsingSubscription: (providerId: string) => statusOf(providerId)?.subscription === true,\n getProviderAuthStatus: (providerId: string) => {\n const status = statusOf(providerId);\n return status === undefined ? { configured: false } : { configured: true, source: status.source };\n },\n login: managedByAdmins,\n logout: managedByAdmins,\n setRuntimeApiKey: managedByAdmins,\n removeRuntimeApiKey: managedByAdmins,\n listCredentials: async () => [],\n getRegisteredNativeProvider: () => undefined,\n getRegisteredProviderConfig: () => undefined,\n getRegisteredProviderIds: () => [],\n getCompatibilityRequestConfig: refused,\n registerProvider: refused,\n registerNativeProvider: refused,\n unregisterProvider: refused,\n registerVirtualModel: refused,\n unregisterVirtualModel: refused,\n } as unknown as PoModelRuntime;\n}\n"],"mappings":";;;;;;AA0BA,MAAM,oBAAoB;;AAG1B,MAAM,kBAA+B;CAAE,KAAK,YAAY,KAAA;CAAW,YAAY,YAAY;AAAM;AAEjG,MAAM,aAAa;CACjB,sBAAsB;CACtB,oBAAoB;CACpB,sBAAsB;AACxB;;AAGA,SAAgB,eAAe,YAAkD;CAE/E,MAAM,SACJ,WAAW,QAAQ,wBAAwB,WAAW,iCAAiC,OACnF,EAAE,QAAQ,EAAE,8BAA8B,KAAK,EAAE,IACjD,CAAC;CACP,OAAO,eAAe;EACpB,IAAI,WAAW;EACf,MAAM,WAAW;EACjB,SAAS,WAAW;EACpB,MAAM,EAAE,QAAQ,cAAc,GAAG,WAAW,KAAK,WAAW,CAAC,CAAC,EAAE;EAChE,QAAQ,WAAW,OAAO,KAAK,W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mCAAmC,KAAA;EACnC,mCAAmC,KAAA;EACnC,gCAAgC,CAAC;EACjC,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,oBAAoB;EACpB,sBAAsB;EACtB,wBAAwB;CAC1B;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-core",
3
- "version": "0.0.0-alpha.138",
3
+ "version": "0.0.0-alpha.139",
4
4
  "description": "Po runtime systems and reusable core services.",
5
5
  "keywords": [
6
6
  "ai",
@@ -322,6 +322,11 @@
322
322
  "import": "./dist/protocol.mjs",
323
323
  "require": "./dist/protocol.cjs"
324
324
  },
325
+ "./protocolTransport": {
326
+ "types": "./dist/protocolTransport.d.mts",
327
+ "import": "./dist/protocolTransport.mjs",
328
+ "require": "./dist/protocolTransport.cjs"
329
+ },
325
330
  "./readiness": {
326
331
  "types": "./dist/readiness.d.mts",
327
332
  "import": "./dist/readiness.mjs",
@@ -609,8 +614,8 @@
609
614
  "registry": "https://registry.npmjs.org/"
610
615
  },
611
616
  "dependencies": {
612
- "@agimon-ai/po-logsink": "0.0.1-alpha.120",
613
- "@agimon-ai/po-web-security": "0.0.0-alpha.138",
617
+ "@agimon-ai/po-logsink": "0.0.1-alpha.121",
618
+ "@agimon-ai/po-web-security": "0.0.0-alpha.139",
614
619
  "@deepseek-ai/cordis": "4.0.5",
615
620
  "@earendil-works/chord": "1.5.1",
616
621
  "@earendil-works/pi-agent-core": "1.5.1",
@@ -636,7 +641,7 @@
636
641
  "yaml": "2.9.1"
637
642
  },
638
643
  "devDependencies": {
639
- "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.138",
644
+ "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.139",
640
645
  "@apidevtools/swagger-parser": "^13.1.0",
641
646
  "@asyncapi/parser": "^3.6.4",
642
647
  "@earendil-works/pi-ai": "1.5.1",