@averyyy/pi-coding-agent 0.85.1-piclient.4 → 0.85.1-piclient.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAcN,YAAY,EAIZ,UAAU,EAMV,WAAW,GAYX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAGN,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAqC9D,qGAAqG;AACrG,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAC/C,UAAU,CAAS;IACnB,SAAS,CAAqC;IAC9C,UAAU,CAAyB;IAE5C,YACC,UAAkB,EAClB,SAA6C,EAC7C,UAAkC,EAClC,OAAqB,EACpB;QACD,KAAK,CAAC,cAAc,SAAS,kBAAkB,UAAU,oCAAoC,EAAE,OAAO,CAAC,CAAC;QACxG,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;QAC7C,IA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AI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YACzC,sFAAsF;YACtF,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE;oBACpB,IAAI,EAAE,SAAS,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;oBAChE,MAAM,EAAE,qBAAqB;iBAC7B,CAAC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG;gBACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
1
+ {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAcN,YAAY,EAIZ,UAAU,EAMV,WAAW,GAYX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,mBAAm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KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.refreshModels !== undefined\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
@@ -16,7 +16,7 @@ export interface PiServerTreeSnapshot {
16
16
  replace?: boolean;
17
17
  }
18
18
  export interface PiServerCompactionResult {
19
- compaction: LegacyCompactResult;
19
+ compaction: Omit<LegacyCompactResult, "retainedTail">;
20
20
  compactionEntry: SessionTreeEntry;
21
21
  entries: SessionTreeEntry[];
22
22
  leafId: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-client.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,4BAA4B,EAC5B,mBAAmB,EAEnB,gBAAgB,EAChB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAAW,EACX,KAAK,OAAO,EACZ,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,MAAM,uBAAuB,CAAC;AAQ/B,cAAM,mBAAoB,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACrF,cASC;CACD;AAED,iBAAS,YAAY,IAAI,MAAM,CAE9B;AAED,iBAAS,YAAY,IAAI,MAAM,CAE9B;AAyCD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAEtD;AAuBD,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAO5D;AAED,wBAAgB,uBAAuB,IAAI,IAAI,CAQ9C;AAsFD,6GAA6G;AAC7G,wBAAsB,wBAAwB,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKpF;AAaD,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,wBAAwB;IACxC,UAAU,EAAE,mBAAmB,CAAC;IAChC,eAAe,EAAE,gBAAgB,C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AAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClF;AAED,wBAAsB,eAAe,CACpC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,sBAAsB,GAC9B,OAAO,CAAC,wBAAwB,CAAC,CAmEnC;AAED,wBAAsB,cAAc,CACnC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,OAAO,CAAC,mBAAmB,CAAC,CAoM9B;AA8FD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport type {\n\tCompactionPreparationOptions,\n\tLegacyCompactResult,\n\tProxyAssistantMessageEvent,\n\tSessionTreeEntry,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Message,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport {\n\tbuildPiServerTreePrefixHashes,\n\thashPiServerSessionEntries,\n\thashPiServerStaticContext,\n} from \"./pi-server-protocol.ts\";\nimport { ChunkRequest } from \"./pi-server-request.ts\";\n\nclass PiServerEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nfunction getServerUrl(): string {\n\treturn process.env.PI_SERVER_URL ?? \"http://127.0.0.1:4217\";\n}\n\nfunction getAuthToken(): string {\n\treturn process.env.PI_SERVER_AUTH_TOKEN ?? \"\";\n}\n\nfunction createPiServerRequest(signal?: AbortSignal): ChunkRequest {\n\treturn new ChunkRequest({\n\t\tserverUrl: getServerUrl(),\n\t\tauthToken: getAuthToken(),\n\t\tsignal,\n\t});\n}\n\nconst sessionStaticContextHashes = new Map<string, string>();\nconst sessionSyncedEntryIds = new Map<string, Set<string>>();\nconst sessionTreeHashes = new Map<string, string>();\nconst sessionTreeEntryCounts = new Map<string, number>();\nconst sessionTreeLeafIds = new Map<string, string | null>();\nconst sessionHasTemporaryTree = new Set<string>();\ninterface ActivePiServerOperation {\n\townerSessionId: string;\n\tsessionId: string;\n\trunId: string;\n\tsignal?: AbortSignal;\n\tcancelListener?: () => void;\n\tcancelPromise?: Promise<void>;\n\tcancelFailed?: boolean;\n\tcancelConfirmed?: boolean;\n}\n\nconst activePiServerOperations = new Map<string, Map<string, ActivePiServerOperation>>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([500, 502, 503, 504, 524, 530]);\nconst PI_SERVER_RUN_RECOVERY_POLL_MS = 250;\nconst DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS = 10 * 60 * 1000;\n\nclass PiServerRunRecoveryTimeoutError extends Error {\n\tconstructor() {\n\t\tsuper(\"pi-server run recovery timed out; the server may still be processing the request\");\n\t\tthis.name = \"PiServerRunRecoveryTimeoutError\";\n\t}\n}\n\nexport function hashStaticContext(ctx: Context): string {\n\treturn hashPiServerStaticContext(ctx);\n}\n\nfunction hashEntries(entries: SessionTreeEntry[]): string {\n\treturn hashPiServerSessionEntries(entries);\n}\n\nfunction getLinearTreeFromMessages(messages: Message[]): { entries: SessionTreeEntry[]; leafId: string | null } {\n\tlet parentId: string | null = null;\n\tconst entries = messages.map((message, index): SessionTreeEntry => {\n\t\tconst id = `message-${index}`;\n\t\tconst entry: SessionTreeEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid,\n\t\t\tparentId,\n\t\t\ttimestamp: new Date(message.timestamp).toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tparentId = id;\n\t\treturn entry;\n\t});\n\treturn { entries, leafId: parentId };\n}\n\nexport function resetSessionTracking(sessionId: string): void {\n\tsessionStaticContextHashes.delete(sessionId);\n\tsessionSyncedEntryIds.delete(sessionId);\n\tsessionTreeHashes.delete(sessionId);\n\tsessionTreeEntryCounts.delete(sessionId);\n\tsessionTreeLeafIds.delete(sessionId);\n\tsessionHasTemporaryTree.delete(sessionId);\n}\n\nexport function resetAllSessionTracking(): void {\n\tsessionStaticContextHashes.clear();\n\tsessionSyncedEntryIds.clear();\n\tsessionTreeHashes.clear();\n\tsessionTreeEntryCounts.clear();\n\tsessionTreeLeafIds.clear();\n\tsessionHasTemporaryTree.clear();\n\tactivePiServerOperations.clear();\n}\n\nfunction registerPiServerOperation(\n\townerSessionId: string | undefined,\n\tsessionId: string,\n\trunId: string,\n\tsignal?: AbortSignal,\n): ActivePiServerOperation | undefined {\n\tif (!ownerSessionId) return undefined;\n\tlet operations = activePiServerOperations.get(ownerSessionId);\n\tif (!operations) {\n\t\toperations = new Map();\n\t\tactivePiServerOperations.set(ownerSessionId, operations);\n\t}\n\tconst operation: ActivePiServerOperation = { ownerSessionId, sessionId, runId, signal };\n\toperations.set(runId, operation);\n\tif (signal) {\n\t\tconst onAbort = () => {\n\t\t\tvoid cancelPiServerOperation(operation).catch(() => {\n\t\t\t\t// The owner session retries cancellation and reports the failure.\n\t\t\t});\n\t\t};\n\t\toperation.cancelListener = onAbort;\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (signal.aborted) onAbort();\n\t}\n\treturn operation;\n}\n\nfunction removePiServerOperation(operation: ActivePiServerOperation): void {\n\tconst operations = activePiServerOperations.get(operation.ownerSessionId);\n\toperation.cancelConfirmed = true;\n\tif (operation.signal && operation.cancelListener) {\n\t\toperation.signal.removeEventListener(\"abort\", operation.cancelListener);\n\t}\n\toperation.cancelListener = undefined;\n\tif (!operations || operations.get(operation.runId) !== operation) return;\n\toperations.delete(operation.runId);\n\tif (operations.size === 0) activePiServerOperations.delete(operation.ownerSessionId);\n}\n\nasync function finishPiServerOperation(\n\toperation: ActivePiServerOperation | undefined,\n\taborted: boolean,\n): Promise<void> {\n\tif (!operation) return;\n\tif (aborted) {\n\t\tif (operation.cancelPromise) await operation.cancelPromise;\n\t} else {\n\t\tremovePiServerOperation(operation);\n\t}\n}\n\nasync function cancelPiServerOperation(operation: ActivePiServerOperation, retryFailed = false): Promise<void> {\n\tif (operation.cancelConfirmed) return;\n\tif (retryFailed && operation.cancelFailed) {\n\t\toperation.cancelFailed = false;\n\t\toperation.cancelPromise = undefined;\n\t}\n\tif (operation.cancelPromise) return operation.cancelPromise;\n\n\tconst cancellation = (async () => {\n\t\tconst request = createPiServerRequest();\n\t\tconst response = await request.postJson(\n\t\t\t`/api/session/${encodeURIComponent(operation.sessionId)}/runs/${encodeURIComponent(operation.runId)}/abort`,\n\t\t\t{ sessionId: operation.sessionId, runId: operation.runId },\n\t\t);\n\t\tconst result = await readPiServerJson<PiServerAbortResponse>(response, \"Session run cancellation failed\");\n\t\tif (result.sessionId !== operation.sessionId || result.runId !== operation.runId) {\n\t\t\tthrow new Error(\"Session run cancellation failed (response did not echo the cancelled run)\");\n\t\t}\n\t\tif (result.status !== \"aborted\" && result.status !== \"completed\" && result.status !== \"failed\") {\n\t\t\tthrow new Error(\"Session run cancellation failed (response was not terminal)\");\n\t\t}\n\t\tremovePiServerOperation(operation);\n\t})();\n\n\toperation.cancelPromise = cancellation;\n\ttry {\n\t\tawait cancellation;\n\t} catch (error) {\n\t\toperation.cancelFailed = true;\n\t\tthrow error;\n\t}\n}\n\n/** Cancel all provider operations owned by a coding-agent session and wait for terminal acknowledgements. */\nexport async function cancelPiServerOperations(ownerSessionId: string): Promise<void> {\n\tconst operations = [...(activePiServerOperations.get(ownerSessionId)?.values() ?? [])];\n\tconst results = await Promise.allSettled(operations.map((operation) => cancelPiServerOperation(operation, true)));\n\tconst failure = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\tif (failure) throw failure.reason;\n}\n\ninterface SessionInitResponse {\n\tsessionId: string;\n\tstaticContextHash: string;\n\ttreeHash?: string;\n\tmessageCount: number;\n\tentryCount?: number;\n\tleafId?: string | null;\n\trevision?: number;\n\tfromCache?: boolean;\n}\n\nexport interface PiServerTreeSnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\treplace?: boolean;\n}\n\nexport interface PiServerCompactionResult {\n\tcompaction: LegacyCompactResult;\n\tcompactionEntry: SessionTreeEntry;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerHistorySnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerStreamOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerErrorResponse {\n\terror: string;\n\tcode?: string;\n\tdetails?: Record<string, unknown>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tcode?: string;\n}\n\nclass PiServerResponseError extends Error {\n\tpublic readonly code?: string;\n\tpublic readonly details?: Record<string, unknown>;\n\n\tconstructor(message: string, code?: string, details?: Record<string, unknown>) {\n\t\tsuper(message);\n\t\tthis.name = \"PiServerResponseError\";\n\t\tthis.code = code;\n\t\tthis.details = details;\n\t}\n}\n\ninterface PiServerHistoryResponse extends Partial<PiServerHistorySnapshot> {\n\tsessionId: string;\n\ttreeHash?: string;\n\tentryCount?: number;\n\tleafId?: string | null;\n\ttreePatch?: PiServerTreePatch;\n}\n\ninterface PiServerTreePatch {\n\tentriesFrom: number;\n\tbaseRevision?: number;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\trevision: number;\n}\n\ninterface PiServerCompactionResponse extends Partial<PiServerCompactionResult> {\n\ttreePatch?: PiServerTreePatch & { baseTreeHash?: string };\n}\n\ninterface ServerSentEvent {\n\tevent: string;\n\tdata: string;\n}\n\nclass ServerSentEventParser {\n\tprivate buffer = \"\";\n\tprivate event = \"message\";\n\tprivate dataLines: string[] = [];\n\n\tfeed(text: string): ServerSentEvent[] {\n\t\tthis.buffer += text;\n\t\tconst lines = this.buffer.split(\"\\n\");\n\t\tthis.buffer = lines.pop() ?? \"\";\n\t\treturn lines.flatMap((line) => this.consumeLine(line));\n\t}\n\n\tfinish(): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tif (this.buffer.length > 0) {\n\t\t\tevents.push(...this.consumeLine(this.buffer));\n\t\t\tthis.buffer = \"\";\n\t\t}\n\t\tconst final = this.flush();\n\t\tif (final) events.push(final);\n\t\treturn events;\n\t}\n\n\tprivate consumeLine(rawLine: string): ServerSentEvent[] {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tconst event = this.flush();\n\t\t\treturn event ? [event] : [];\n\t\t}\n\t\tif (line.startsWith(\":\")) return [];\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tthis.event = getServerSentEventFieldValue(line, \"event\");\n\t\t\treturn [];\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tthis.dataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t\treturn [];\n\t}\n\n\tprivate flush(): ServerSentEvent | undefined {\n\t\tif (this.dataLines.length === 0) return undefined;\n\t\tconst event = { event: this.event, data: this.dataLines.join(\"\\n\") };\n\t\tthis.event = \"message\";\n\t\tthis.dataLines = [];\n\t\treturn event;\n\t}\n}\n\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\" | \"aborted\";\n\tmessage?: AssistantMessage;\n\terrorMessage?: string;\n}\n\ninterface PiServerAbortResponse {\n\tsessionId: string;\n\trunId: string;\n\tstatus: \"aborted\" | \"completed\" | \"failed\";\n}\n\ninterface PiServerSyncOptions {\n\tsignal?: AbortSignal;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ntype PiServerFailurePhase = \"session_init\" | \"tree_sync\" | \"provider_stream\" | \"history_reconcile\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction getResponseStatus(response: Response): string {\n\tconst status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);\n\treturn response.status >= 500 ? `${status} (server error)` : status;\n}\n\nfunction getResponseContentType(response: Response): string {\n\treturn response.headers.get(\"content-type\") ?? \"unknown\";\n}\n\nfunction getBodyExcerpt(text: string): string {\n\tconst trimmed = text.trim();\n\tif (!trimmed) return \"<empty>\";\n\tconst excerpt = trimmed.slice(0, RESPONSE_BODY_EXCERPT_CHARS);\n\treturn excerpt.length < trimmed.length ? `${excerpt}...` : excerpt;\n}\n\nfunction getJsonErrorResponse(text: string): PiServerErrorResponse | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed) || typeof parsed.error !== \"string\" || parsed.error.length === 0) return undefined;\n\t\tconst code = parsed.code;\n\t\treturn {\n\t\t\terror: parsed.error,\n\t\t\tcode: typeof code === \"string\" ? code : undefined,\n\t\t\tdetails: isObject(parsed.details) ? parsed.details : undefined,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction getJsonErrorText(text: string): string | undefined {\n\treturn getJsonErrorResponse(text)?.error;\n}\n\nfunction formatResponseDetails(response: Response, bodyText: string): string {\n\tconst body = getJsonErrorText(bodyText) ?? getBodyExcerpt(bodyText);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${body}`;\n}\n\nasync function readPiServerFailure(response: Response): Promise<PiServerResponseFailure> {\n\tconst bodyText = await response.text();\n\tconst errorResponse = getJsonErrorResponse(bodyText);\n\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tcode: errorResponse?.code,\n\t};\n}\n\nasync function readPiServerJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tif (!response.ok) {\n\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\tif (errorResponse) {\n\t\t\tthrow new PiServerResponseError(\n\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\terrorResponse.code,\n\t\t\t\terrorResponse.details,\n\t\t\t);\n\t\t}\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t}\n\ttry {\n\t\treturn JSON.parse(bodyText) as T;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t}\n}\n\nfunction getServerSentEventFieldValue(line: string, field: string): string {\n\tconst prefix = `${field}:`;\n\tconst value = line.slice(prefix.length);\n\treturn value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction parseServerSentEvents(bodyText: string): ServerSentEvent[] {\n\tconst parser = new ServerSentEventParser();\n\treturn [...parser.feed(bodyText), ...parser.finish()];\n}\n\nfunction parseServerSentEventData(event: ServerSentEvent, errorPrefix: string): unknown {\n\ttry {\n\t\treturn JSON.parse(event.data) as unknown;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (invalid event-stream JSON data: ${getBodyExcerpt(event.data)})`);\n\t}\n}\n\nfunction formatServerSentEventError(response: Response, payload: unknown): string {\n\tconst message = isObject(payload) && typeof payload.error === \"string\" ? payload.error : JSON.stringify(payload);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${getBodyExcerpt(message)}`;\n}\n\nasync function readPiServerEventStreamJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tfor (const event of parseServerSentEvents(bodyText)) {\n\t\tif (event.event === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`${errorPrefix} (${formatServerSentEventError(response, parseServerSentEventData(event, errorPrefix))})`,\n\t\t\t);\n\t\t}\n\t\tif (event.event === \"result\") {\n\t\t\treturn parseServerSentEventData(event, errorPrefix) as T;\n\t\t}\n\t}\n\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected result event)`);\n}\n\nasync function readPiServerCompactResponse<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst contentType = getResponseContentType(response).toLowerCase().split(\";\")[0]?.trim();\n\tif (contentType === \"text/event-stream\") {\n\t\treturn readPiServerEventStreamJson<T>(response, errorPrefix);\n\t}\n\treturn readPiServerJson<T>(response, errorPrefix);\n}\n\nfunction isAbortError(error: unknown, signal: AbortSignal | undefined): boolean {\n\treturn signal?.aborted === true || (error instanceof Error && error.name === \"AbortError\");\n}\n\nfunction isTransientPiServerFetchError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /fetch failed|network|socket hang up|terminated|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|CONNECT timeout/i.test(\n\t\tmessage,\n\t);\n}\n\nfunction isTransientPiServerError(error: unknown): boolean {\n\tif (isTransientPiServerFetchError(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t/\\b(?:500|502|503|504|524|530)\\b/.test(message) ||\n\t\t/CONNECT timeout|Bad Gateway|upstream|A timeout occurred/i.test(message)\n\t);\n}\n\nfunction isRetryablePiServerFailure(phase: PiServerFailurePhase, error: unknown): boolean {\n\tif (phase === \"provider_stream\") return true;\n\tif (phase === \"history_reconcile\") return false;\n\treturn isTransientPiServerError(error);\n}\n\nasync function waitForPiServerRetry(attempt: number, signal: AbortSignal | undefined): Promise<void> {\n\tawait sleep(TRANSIENT_PI_SERVER_RETRY_DELAYS_MS[attempt], undefined, { signal });\n}\n\nasync function postPiServerJsonWithTransientRetry<T>(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<T> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await request.postJson(endpoint, body);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!isAbortError(error, request.options.signal) &&\n\t\t\t\tisTransientPiServerFetchError(error)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst bodyText = await response.text();\n\t\tif (!response.ok) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!request.options.signal?.aborted &&\n\t\t\t\tTRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\t\tif (errorResponse) {\n\t\t\t\tthrow new PiServerResponseError(\n\t\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\t\terrorResponse.code,\n\t\t\t\t\terrorResponse.details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(bodyText) as T;\n\t\t} catch {\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t\t}\n\t}\n}\n\nasync function ensurePiServerEventStream(response: Response): Promise<void> {\n\tconst contentType = getResponseContentType(response);\n\tif (contentType.toLowerCase().split(\";\")[0]?.trim() === \"text/event-stream\") {\n\t\treturn;\n\t}\n\tconst bodyText = await response.text();\n\tthrow new Error(`pi-server error: ${formatResponseDetails(response, bodyText)}; expected text/event-stream`);\n}\n\nasync function ensureSessionInit(\n\tsessionId: string,\n\tcontext: Context,\n\trequest: ChunkRequest,\n): Promise<SessionInitResponse> {\n\tconst currentHash = hashStaticContext(context);\n\tconst previousHash = sessionStaticContextHashes.get(sessionId);\n\n\tif (previousHash === currentHash) {\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tstaticContextHash: previousHash,\n\t\t\tmessageCount: 0,\n\t\t\tfromCache: true,\n\t\t};\n\t}\n\n\tconst staticContext = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n\n\tconst endpoint = previousHash === undefined ? \"/api/session/init\" : \"/api/session/update\";\n\n\tconst result = await postPiServerJsonWithTransientRetry<SessionInitResponse>(\n\t\trequest,\n\t\tendpoint,\n\t\t{ sessionId, staticContext },\n\t\t\"Session init failed\",\n\t);\n\tsessionStaticContextHashes.set(sessionId, currentHash);\n\tif (result.treeHash !== undefined) {\n\t\tsessionTreeHashes.set(sessionId, result.treeHash);\n\t\tsessionTreeLeafIds.set(sessionId, result.leafId ?? null);\n\t\tif (result.entryCount !== undefined) {\n\t\t\tsessionTreeEntryCounts.set(sessionId, result.entryCount);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getStaticContext(context: Context) {\n\treturn {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n}\n\nfunction markTreeSynced(sessionId: string, tree: PiServerTreeSnapshot): void {\n\tsessionSyncedEntryIds.set(sessionId, new Set(tree.entries.map((entry) => entry.id)));\n\tconst prefixHashes = buildPiServerTreePrefixHashes(tree.entries);\n\tsessionTreeHashes.set(sessionId, prefixHashes[prefixHashes.length - 1]);\n\tsessionTreeEntryCounts.set(sessionId, tree.entries.length);\n\tsessionTreeLeafIds.set(sessionId, tree.leafId);\n\tif (tree.replace) {\n\t\tsessionHasTemporaryTree.add(sessionId);\n\t} else {\n\t\tsessionHasTemporaryTree.delete(sessionId);\n\t}\n}\n\nasync function postTreeJson(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<void> {\n\tawait postPiServerJsonWithTransientRetry<unknown>(request, endpoint, body, errorPrefix);\n}\n\nasync function fetchPiServerHistory(\n\tsessionId: string,\n\trequest: ChunkRequest,\n\tlocalTree?: PiServerTreeSnapshot,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst prefixHashes = localTree ? buildPiServerTreePrefixHashes(localTree.entries) : undefined;\n\tconst historyUrl =\n\t\tlocalTree && prefixHashes\n\t\t\t? `/api/session/${encodeURIComponent(sessionId)}/history?entriesFrom=${localTree.entries.length}&baseTreeHash=${encodeURIComponent(prefixHashes[prefixHashes.length - 1])}`\n\t\t\t: `/api/session/${encodeURIComponent(sessionId)}/history`;\n\tconst response = await request.getJson(historyUrl);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\tconst history = await readPiServerJson<PiServerHistoryResponse>(response, \"Session history reconciliation failed\");\n\tif (history.treePatch && localTree) {\n\t\treturn {\n\t\t\tentries: [...localTree.entries.slice(0, history.treePatch.entriesFrom), ...history.treePatch.entries],\n\t\t\tleafId: history.treePatch.leafId,\n\t\t\tmessages: history.messages ?? [],\n\t\t};\n\t}\n\tif (!history.entries || history.leafId === undefined || !history.messages) {\n\t\tthrow new Error(\"Session history reconciliation failed (response did not include the session tree)\");\n\t}\n\treturn {\n\t\tentries: history.entries,\n\t\tleafId: history.leafId,\n\t\tmessages: history.messages,\n\t};\n}\n\nasync function applyPiServerHistory(\n\tsessionId: string,\n\tsnapshot: PiServerHistorySnapshot,\n\tonHistoryReconciled: ((snapshot: PiServerHistorySnapshot) => void | Promise<void>) | undefined,\n): Promise<void> {\n\tmarkTreeSynced(sessionId, snapshot);\n\tawait onHistoryReconciled?.(snapshot);\n}\n\nasync function fetchPiServerRun(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n): Promise<PiServerRunResponse | undefined> {\n\tconst response = await request.getJson(\n\t\t`/api/session/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`,\n\t);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\treturn readPiServerJson<PiServerRunResponse>(response, \"Session run recovery failed\");\n}\n\nasync function waitForPiServerRunCompletion(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n\toptions: PiServerStreamOptions | undefined,\n): Promise<PiServerRunResponse | undefined> {\n\tconst deadline = Date.now() + DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS;\n\tfor (;;) {\n\t\tconst run = await fetchPiServerRun(sessionId, runId, request);\n\t\tif (!run || run.status !== \"running\") return run;\n\t\tif (Date.now() >= deadline) throw new PiServerRunRecoveryTimeoutError();\n\t\tawait sleep(PI_SERVER_RUN_RECOVERY_POLL_MS, undefined, { signal: options?.signal });\n\t}\n}\n\nfunction getKnownServerPrefixIds(sessionId: string, entries: SessionTreeEntry[]): Set<string> | undefined {\n\tconst entryCount = sessionTreeEntryCounts.get(sessionId);\n\tconst treeHash = sessionTreeHashes.get(sessionId);\n\tif (entryCount === undefined || treeHash === undefined || entryCount > entries.length) {\n\t\treturn undefined;\n\t}\n\tconst prefixHashes = buildPiServerTreePrefixHashes(entries);\n\tif (prefixHashes[entryCount] !== treeHash) {\n\t\treturn undefined;\n\t}\n\tconst ids = new Set(entries.slice(0, entryCount).map((entry) => entry.id));\n\tsessionSyncedEntryIds.set(sessionId, ids);\n\treturn ids;\n}\n\nfunction isRecoverableTreeDivergenceCode(code: string | undefined): boolean {\n\treturn code === \"PARENT_ENTRY_NOT_FOUND\" || code === \"LEAF_ID_NOT_FOUND\" || code === \"ENTRY_ALREADY_EXISTS\";\n}\n\nfunction isRecoverableMissingServerStateCode(code: string | undefined): boolean {\n\treturn code === \"SESSION_NOT_FOUND\" || code === \"SESSION_NO_STATIC_CONTEXT\" || isRecoverableTreeDivergenceCode(code);\n}\n\nfunction isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tif (error instanceof PiServerResponseError) {\n\t\treturn isRecoverableTreeDivergenceCode(error.code);\n\t}\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\treturn isRecoverableTreeDivergenceCode((error as { code?: string }).code);\n\t}\n\treturn false;\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorCode?: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn isRecoverableMissingServerStateCode(errorCode);\n}\n\nasync function syncFullPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n): Promise<void> {\n\tawait postTreeJson(\n\t\trequest,\n\t\t\"/api/session/tree/sync\",\n\t\t{\n\t\t\tsessionId,\n\t\t\tentries: tree.entries,\n\t\t\tleafId: tree.leafId,\n\t\t\tstaticContext: getStaticContext(context),\n\t\t},\n\t\t\"Session tree sync failed\",\n\t);\n\tmarkTreeSynced(sessionId, tree);\n}\n\nfunction shouldUseServerHistory(sessionId: string, tree: PiServerTreeSnapshot): boolean {\n\treturn !tree.replace && !sessionHasTemporaryTree.has(sessionId) && (sessionTreeEntryCounts.get(sessionId) ?? 0) > 0;\n}\n\nasync function recoverPiServerTreeDivergence(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<void> {\n\tif (shouldUseServerHistory(sessionId, tree)) {\n\t\tconst snapshot = await fetchPiServerHistory(sessionId, request, tree);\n\t\tif (snapshot && snapshot.entries.length > 0) {\n\t\t\tawait applyPiServerHistory(sessionId, snapshot, onHistoryReconciled);\n\t\t\tthrow new Error(\n\t\t\t\t\"pi-server history differed from local history; local session was reconciled to server history\",\n\t\t\t);\n\t\t}\n\t}\n\n\tawait syncFullPiServerTree(sessionId, context, tree, request);\n}\n\nexport async function syncPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\toptions?: PiServerSyncOptions,\n): Promise<void> {\n\tconst request = createPiServerRequest(options?.signal);\n\tawait ensureSessionInit(sessionId, context, request);\n\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n}\n\nasync function syncPiServerTreeWithRequest(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<void> {\n\tconst syncTree = tree;\n\tconst currentHash = hashEntries(syncTree.entries);\n\tconst previousHash = sessionTreeHashes.get(sessionId);\n\tconst previousLeafId = sessionTreeLeafIds.get(sessionId);\n\n\tif (!tree.replace && previousHash === currentHash) {\n\t\tif (previousLeafId !== syncTree.leafId) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/switch\",\n\t\t\t\t\t{ sessionId, leafId: syncTree.leafId },\n\t\t\t\t\t\"Session tree switch failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tawait recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsessionTreeLeafIds.set(sessionId, syncTree.leafId);\n\t\t}\n\t\tmarkTreeSynced(sessionId, syncTree);\n\t\treturn;\n\t}\n\n\tconst syncedIds =\n\t\t!tree.replace && !sessionHasTemporaryTree.has(sessionId)\n\t\t\t? (sessionSyncedEntryIds.get(sessionId) ?? getKnownServerPrefixIds(sessionId, syncTree.entries))\n\t\t\t: undefined;\n\tif (syncedIds) {\n\t\tconst deltaEntries = syncTree.entries.filter((entry) => !syncedIds.has(entry.id));\n\t\tif (deltaEntries.length > 0) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/append\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tentries: deltaEntries,\n\t\t\t\t\t\tleafId: syncTree.leafId,\n\t\t\t\t\t\tstaticContext: getStaticContext(context),\n\t\t\t\t\t},\n\t\t\t\t\t\"Session tree append failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tawait recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmarkTreeSynced(sessionId, syncTree);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tawait recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n}\n\nfunction serializeOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\treasoning: options?.reasoning,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tapiKey: options?.apiKey,\n\t\theaders: options?.headers,\n\t\tmetadata: options?.metadata,\n\t\ttransport: options?.transport,\n\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t};\n}\n\nexport interface PiServerCompactOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tcustomInstructions?: string;\n\tsettings?: unknown;\n\tpreparation?: CompactionPreparationOptions;\n\tsessionTree?: PiServerTreeSnapshot;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\nexport async function compactPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerCompactOptions,\n): Promise<PiServerCompactionResult> {\n\tconst sessionId = options?.sessionId ?? \"default\";\n\tconst runId = randomUUID();\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst request = createPiServerRequest(options?.signal);\n\n\ttry {\n\t\tawait ensureSessionInit(sessionId, context, request);\n\t\tconst tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\n\t\tconst makeBody = () => ({\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\tmodel,\n\t\t\toptions: serializeOptions(options),\n\t\t\tsettings: options?.settings,\n\t\t\tpreparation: options?.preparation,\n\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\t\tstreamResponse: true,\n\t\t});\n\t\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\t\tif (!response.ok) {\n\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\t\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t} else {\n\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t\t}\n\t\t}\n\t\tconst result = await readPiServerCompactResponse<PiServerCompactionResponse>(\n\t\t\tresponse,\n\t\t\t\"Server compaction failed\",\n\t\t);\n\t\tif (!result.compaction) {\n\t\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t\t}\n\t\tconst resultEntries =\n\t\t\tresult.entries ??\n\t\t\t(result.treePatch\n\t\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t\t: undefined);\n\t\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\t\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t\t}\n\t\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\t\treturn {\n\t\t\tcompaction: result.compaction,\n\t\t\tcompactionEntry: result.compactionEntry,\n\t\t\tentries: resultEntries,\n\t\t\tleafId: resultLeafId,\n\t\t\tmessages: result.messages ?? [],\n\t\t};\n\t} finally {\n\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t}\n}\n\nexport async function streamPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerStreamOptions,\n): Promise<PiServerEventStream> {\n\tconst sessionId = options?.sessionId ?? randomUUID();\n\tconst runId = randomUUID();\n\tconst isEphemeralSession = options?.sessionId === undefined;\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst stream = new PiServerEventStream();\n\n\tconst partial: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tstopReason: \"stop\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\ttimestamp: Date.now(),\n\t};\n\n\t(async () => {\n\t\tlet phase: PiServerFailurePhase = \"session_init\";\n\t\tlet streamOpened = false;\n\t\ttry {\n\t\t\tconst request = createPiServerRequest(options?.signal);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\n\t\t\tconst makeBody = () => ({\n\t\t\t\tsessionId,\n\t\t\t\trunId,\n\t\t\t\tmodel,\n\t\t\t\toptions: serializeOptions(options),\n\t\t\t\tcontextOverlay: options?.contextOverlay ?? [\n\t\t\t\t\t...(context.messages as Message[]),\n\t\t\t\t\t...(options?.ephemeralMessages ?? []),\n\t\t\t\t],\n\t\t\t});\n\t\t\tphase = \"provider_stream\";\n\t\t\tlet response = await request.postJson(\"/api/stream\", makeBody());\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\t\tresponse = await request.postJson(\"/api/stream\", makeBody());\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`pi-server error: ${failure.details}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ensurePiServerEventStream(response);\n\t\t\tstreamOpened = true;\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst parser = new ServerSentEventParser();\n\t\t\tlet terminalReceived = false;\n\n\t\t\tconst consumeEvents = (events: ServerSentEvent[]): void => {\n\t\t\t\tfor (const serverEvent of events) {\n\t\t\t\t\tconst proxyEvent = parseServerSentEventData(\n\t\t\t\t\t\tserverEvent,\n\t\t\t\t\t\t\"pi-server stream\",\n\t\t\t\t\t) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (!event) continue;\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalReceived = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tconsumeEvents(parser.feed(decoder.decode(value, { stream: true })));\n\t\t\t}\n\t\t\tconsumeEvents(parser.feed(decoder.decode()));\n\t\t\tconsumeEvents(parser.finish());\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\t\t\tif (!terminalReceived) {\n\t\t\t\tthrow new Error(\"pi-server stream ended before a terminal response event\");\n\t\t\t}\n\n\t\t\tif (isEphemeralSession) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tlet errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t// Same-run recovery only applies to an interrupted event-stream. HTTP/proxy\n\t\t\t// failures before the stream starts (502/504/fetch failed) never opened a run\n\t\t\t// we can poll; attempting recovery against a down proxy reclassifies the error\n\t\t\t// as history_reconcile and blocks session auto-retry.\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\" && streamOpened) {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await waitForPiServerRunCompletion(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tcreatePiServerRequest(options?.signal),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tif (recoveredRun?.status === \"completed\" && recoveredRun.message) {\n\t\t\t\t\t\tswitch (recoveredRun.message.stopReason) {\n\t\t\t\t\t\t\tcase \"stop\":\n\t\t\t\t\t\t\tcase \"length\":\n\t\t\t\t\t\t\tcase \"toolUse\":\n\t\t\t\t\t\t\tcase \"deferred\":\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\treason: recoveredRun.message.stopReason,\n\t\t\t\t\t\t\t\t\tmessage: recoveredRun.message,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"aborted\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"failed\" && recoveredRun.errorMessage) {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"aborted\") {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage ?? \"pi-server run aborted\";\n\t\t\t\t\t}\n\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\tphase = \"history_reconcile\";\n\t\t\t\t\terrorMessage = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options?.signal?.aborted && operation && !operation.cancelConfirmed) {\n\t\t\t\ttry {\n\t\t\t\t\tawait cancelPiServerOperation(operation);\n\t\t\t\t} catch (cancelError) {\n\t\t\t\t\terrorMessage = `${errorMessage}; cancellation failed: ${\n\t\t\t\t\t\tcancelError instanceof Error ? cancelError.message : String(cancelError)\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tpartial.diagnostics = [\n\t\t\t\t...(partial.diagnostics ?? []),\n\t\t\t\t{\n\t\t\t\t\ttype: \"pi_server_failure\",\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\terror: { name: error instanceof Error ? error.name : \"Error\", message: errorMessage },\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tphase,\n\t\t\t\t\t\tsource: \"pi-server\",\n\t\t\t\t\t\tretryable: isRetryablePiServerFailure(phase, error),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t\t\t} catch {\n\t\t\t\t// The owning session's cancellation helper reports the failure and keeps\n\t\t\t\t// this operation registered for a retry.\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn { type: \"text_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"text_end\", contentIndex: proxyEvent.contentIndex, content: content.text, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn { type: \"thinking_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"thinking_end\", contentIndex: proxyEvent.contentIndex, content: content.thinking, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} as any;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content };\n\t\t\t\treturn { type: \"toolcall_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn { type: \"toolcall_end\", contentIndex: proxyEvent.contentIndex, toolCall: content, partial };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nexport { getServerUrl, getAuthToken };\n"]}
1
+ {"version":3,"file":"pi-server-client.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,4BAA4B,EAC5B,mBAAmB,EAEnB,gBAAgB,EAChB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAA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import { setTimeout as sleep } from \"node:timers/promises\";\nimport type {\n\tCompactionPreparationOptions,\n\tLegacyCompactResult,\n\tProxyAssistantMessageEvent,\n\tSessionTreeEntry,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Message,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport {\n\tbuildPiServerTreePrefixHashes,\n\thashPiServerSessionEntries,\n\thashPiServerStaticContext,\n} from \"./pi-server-protocol.ts\";\nimport { ChunkRequest } from \"./pi-server-request.ts\";\n\nclass PiServerEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nfunction getServerUrl(): string {\n\treturn process.env.PI_SERVER_URL ?? \"http://127.0.0.1:4217\";\n}\n\nfunction getAuthToken(): string {\n\treturn process.env.PI_SERVER_AUTH_TOKEN ?? \"\";\n}\n\nfunction createPiServerRequest(signal?: AbortSignal): ChunkRequest {\n\treturn new ChunkRequest({\n\t\tserverUrl: getServerUrl(),\n\t\tauthToken: getAuthToken(),\n\t\tsignal,\n\t});\n}\n\nconst sessionStaticContextHashes = new Map<string, string>();\nconst sessionTreeHashes = new Map<string, string>();\nconst sessionTreeEntryCounts = new Map<string, number>();\nconst sessionTreeLeafIds = new Map<string, string | null>();\nconst sessionHasTemporaryTree = new Set<string>();\ninterface ActivePiServerOperation {\n\townerSessionId: string;\n\tsessionId: string;\n\trunId: string;\n\tsignal?: AbortSignal;\n\tcancelListener?: () => void;\n\tcancelPromise?: Promise<void>;\n\tcancelFailed?: boolean;\n\tcancelConfirmed?: boolean;\n}\n\nconst activePiServerOperations = new Map<string, Map<string, ActivePiServerOperation>>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([500, 502, 503, 504, 524, 530]);\nconst PI_SERVER_RUN_RECOVERY_POLL_MS = 250;\nconst DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS = 10 * 60 * 1000;\n\nclass PiServerRunRecoveryTimeoutError extends Error {\n\tconstructor() {\n\t\tsuper(\"pi-server run recovery timed out; the server may still be processing the request\");\n\t\tthis.name = \"PiServerRunRecoveryTimeoutError\";\n\t}\n}\n\nexport function hashStaticContext(ctx: Context): string {\n\treturn hashPiServerStaticContext(ctx);\n}\n\nfunction hashEntries(entries: SessionTreeEntry[]): string {\n\treturn hashPiServerSessionEntries(entries);\n}\n\nfunction getLinearTreeFromMessages(messages: Message[]): { entries: SessionTreeEntry[]; leafId: string | null } {\n\tlet parentId: string | null = null;\n\tconst entries = messages.map((message, index): SessionTreeEntry => {\n\t\tconst id = `message-${index}`;\n\t\tconst entry: SessionTreeEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid,\n\t\t\tparentId,\n\t\t\ttimestamp: new Date(message.timestamp).toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tparentId = id;\n\t\treturn entry;\n\t});\n\treturn { entries, leafId: parentId };\n}\n\nexport function resetSessionTracking(sessionId: string): void {\n\tsessionStaticContextHashes.delete(sessionId);\n\tsessionTreeHashes.delete(sessionId);\n\tsessionTreeEntryCounts.delete(sessionId);\n\tsessionTreeLeafIds.delete(sessionId);\n\tsessionHasTemporaryTree.delete(sessionId);\n}\n\nexport function resetAllSessionTracking(): void {\n\tsessionStaticContextHashes.clear();\n\tsessionTreeHashes.clear();\n\tsessionTreeEntryCounts.clear();\n\tsessionTreeLeafIds.clear();\n\tsessionHasTemporaryTree.clear();\n\tactivePiServerOperations.clear();\n}\n\nfunction registerPiServerOperation(\n\townerSessionId: string | undefined,\n\tsessionId: string,\n\trunId: string,\n\tsignal?: AbortSignal,\n): ActivePiServerOperation | undefined {\n\tif (!ownerSessionId) return undefined;\n\tlet operations = activePiServerOperations.get(ownerSessionId);\n\tif (!operations) {\n\t\toperations = new Map();\n\t\tactivePiServerOperations.set(ownerSessionId, operations);\n\t}\n\tconst operation: ActivePiServerOperation = { ownerSessionId, sessionId, runId, signal };\n\toperations.set(runId, operation);\n\tif (signal) {\n\t\tconst onAbort = () => {\n\t\t\tvoid cancelPiServerOperation(operation).catch(() => {\n\t\t\t\t// The owner session retries cancellation and reports the failure.\n\t\t\t});\n\t\t};\n\t\toperation.cancelListener = onAbort;\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (signal.aborted) onAbort();\n\t}\n\treturn operation;\n}\n\nfunction removePiServerOperation(operation: ActivePiServerOperation): void {\n\tconst operations = activePiServerOperations.get(operation.ownerSessionId);\n\toperation.cancelConfirmed = true;\n\tif (operation.signal && operation.cancelListener) {\n\t\toperation.signal.removeEventListener(\"abort\", operation.cancelListener);\n\t}\n\toperation.cancelListener = undefined;\n\tif (!operations || operations.get(operation.runId) !== operation) return;\n\toperations.delete(operation.runId);\n\tif (operations.size === 0) activePiServerOperations.delete(operation.ownerSessionId);\n}\n\nasync function finishPiServerOperation(\n\toperation: ActivePiServerOperation | undefined,\n\taborted: boolean,\n): Promise<void> {\n\tif (!operation) return;\n\tif (aborted) {\n\t\tif (operation.cancelPromise) await operation.cancelPromise;\n\t} else {\n\t\tremovePiServerOperation(operation);\n\t}\n}\n\nasync function cancelPiServerOperation(operation: ActivePiServerOperation, retryFailed = false): Promise<void> {\n\tif (operation.cancelConfirmed) return;\n\tif (retryFailed && operation.cancelFailed) {\n\t\toperation.cancelFailed = false;\n\t\toperation.cancelPromise = undefined;\n\t}\n\tif (operation.cancelPromise) return operation.cancelPromise;\n\n\tconst cancellation = (async () => {\n\t\tconst request = createPiServerRequest();\n\t\tconst response = await request.postJson(\n\t\t\t`/api/session/${encodeURIComponent(operation.sessionId)}/runs/${encodeURIComponent(operation.runId)}/abort`,\n\t\t\t{ sessionId: operation.sessionId, runId: operation.runId },\n\t\t);\n\t\tconst result = await readPiServerJson<PiServerAbortResponse>(response, \"Session run cancellation failed\");\n\t\tif (result.sessionId !== operation.sessionId || result.runId !== operation.runId) {\n\t\t\tthrow new Error(\"Session run cancellation failed (response did not echo the cancelled run)\");\n\t\t}\n\t\tif (result.status !== \"aborted\" && result.status !== \"completed\" && result.status !== \"failed\") {\n\t\t\tthrow new Error(\"Session run cancellation failed (response was not terminal)\");\n\t\t}\n\t\tremovePiServerOperation(operation);\n\t})();\n\n\toperation.cancelPromise = cancellation;\n\ttry {\n\t\tawait cancellation;\n\t} catch (error) {\n\t\toperation.cancelFailed = true;\n\t\tthrow error;\n\t}\n}\n\n/** Cancel all provider operations owned by a coding-agent session and wait for terminal acknowledgements. */\nexport async function cancelPiServerOperations(ownerSessionId: string): Promise<void> {\n\tconst operations = [...(activePiServerOperations.get(ownerSessionId)?.values() ?? [])];\n\tconst results = await Promise.allSettled(operations.map((operation) => cancelPiServerOperation(operation, true)));\n\tconst failure = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\tif (failure) throw failure.reason;\n}\n\ninterface SessionInitResponse {\n\tsessionId: string;\n\tstaticContextHash: string;\n\ttreeHash?: string;\n\tmessageCount: number;\n\tentryCount?: number;\n\tleafId?: string | null;\n\trevision?: number;\n\tfromCache?: boolean;\n}\n\nexport interface PiServerTreeSnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\treplace?: boolean;\n}\n\nexport interface PiServerCompactionResult {\n\tcompaction: Omit<LegacyCompactResult, \"retainedTail\">;\n\tcompactionEntry: SessionTreeEntry;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerHistorySnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerStreamOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerErrorResponse {\n\terror: string;\n\tcode?: string;\n\tdetails?: Record<string, unknown>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tcode?: string;\n}\n\nclass PiServerResponseError extends Error {\n\tpublic readonly code?: string;\n\tpublic readonly details?: Record<string, unknown>;\n\n\tconstructor(message: string, code?: string, details?: Record<string, unknown>) {\n\t\tsuper(message);\n\t\tthis.name = \"PiServerResponseError\";\n\t\tthis.code = code;\n\t\tthis.details = details;\n\t}\n}\n\ninterface PiServerHistoryResponse extends Partial<PiServerHistorySnapshot> {\n\tsessionId: string;\n\ttreeHash?: string;\n\tentryCount?: number;\n\tleafId?: string | null;\n\ttreePatch?: PiServerTreePatch;\n}\n\ninterface PiServerTreePatch {\n\tentriesFrom: number;\n\tbaseRevision?: number;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\trevision: number;\n}\n\ninterface PiServerCompactionResponse extends Partial<PiServerCompactionResult> {\n\ttreePatch?: PiServerTreePatch & { baseTreeHash?: string };\n}\n\ninterface ServerSentEvent {\n\tevent: string;\n\tdata: string;\n}\n\nclass ServerSentEventParser {\n\tprivate buffer = \"\";\n\tprivate event = \"message\";\n\tprivate dataLines: string[] = [];\n\n\tfeed(text: string): ServerSentEvent[] {\n\t\tthis.buffer += text;\n\t\tconst lines = this.buffer.split(\"\\n\");\n\t\tthis.buffer = lines.pop() ?? \"\";\n\t\treturn lines.flatMap((line) => this.consumeLine(line));\n\t}\n\n\tfinish(): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tif (this.buffer.length > 0) {\n\t\t\tevents.push(...this.consumeLine(this.buffer));\n\t\t\tthis.buffer = \"\";\n\t\t}\n\t\tconst final = this.flush();\n\t\tif (final) events.push(final);\n\t\treturn events;\n\t}\n\n\tprivate consumeLine(rawLine: string): ServerSentEvent[] {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tconst event = this.flush();\n\t\t\treturn event ? [event] : [];\n\t\t}\n\t\tif (line.startsWith(\":\")) return [];\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tthis.event = getServerSentEventFieldValue(line, \"event\");\n\t\t\treturn [];\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tthis.dataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t\treturn [];\n\t}\n\n\tprivate flush(): ServerSentEvent | undefined {\n\t\tif (this.dataLines.length === 0) return undefined;\n\t\tconst event = { event: this.event, data: this.dataLines.join(\"\\n\") };\n\t\tthis.event = \"message\";\n\t\tthis.dataLines = [];\n\t\treturn event;\n\t}\n}\n\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\" | \"aborted\";\n\tmessage?: AssistantMessage;\n\tcompactResult?: PiServerCompactionResponse;\n\terrorMessage?: string;\n}\n\ninterface PiServerAbortResponse {\n\tsessionId: string;\n\trunId: string;\n\tstatus: \"aborted\" | \"completed\" | \"failed\";\n}\n\ninterface PiServerSyncOptions {\n\tsignal?: AbortSignal;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ntype PiServerFailurePhase = \"session_init\" | \"tree_sync\" | \"provider_stream\" | \"history_reconcile\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction getResponseStatus(response: Response): string {\n\tconst status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);\n\treturn response.status >= 500 ? `${status} (server error)` : status;\n}\n\nfunction getResponseContentType(response: Response): string {\n\treturn response.headers.get(\"content-type\") ?? \"unknown\";\n}\n\nfunction getBodyExcerpt(text: string): string {\n\tconst trimmed = text.trim();\n\tif (!trimmed) return \"<empty>\";\n\tconst excerpt = trimmed.slice(0, RESPONSE_BODY_EXCERPT_CHARS);\n\treturn excerpt.length < trimmed.length ? `${excerpt}...` : excerpt;\n}\n\nfunction getJsonErrorResponse(text: string): PiServerErrorResponse | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed) || typeof parsed.error !== \"string\" || parsed.error.length === 0) return undefined;\n\t\tconst code = parsed.code;\n\t\treturn {\n\t\t\terror: parsed.error,\n\t\t\tcode: typeof code === \"string\" ? code : undefined,\n\t\t\tdetails: isObject(parsed.details) ? parsed.details : undefined,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction getJsonErrorText(text: string): string | undefined {\n\treturn getJsonErrorResponse(text)?.error;\n}\n\nfunction formatResponseDetails(response: Response, bodyText: string): string {\n\tconst body = getJsonErrorText(bodyText) ?? getBodyExcerpt(bodyText);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${body}`;\n}\n\nasync function readPiServerFailure(response: Response): Promise<PiServerResponseFailure> {\n\tconst bodyText = await response.text();\n\tconst errorResponse = getJsonErrorResponse(bodyText);\n\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tcode: errorResponse?.code,\n\t};\n}\n\nasync function readPiServerJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tif (!response.ok) {\n\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\tif (errorResponse) {\n\t\t\tthrow new PiServerResponseError(\n\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\terrorResponse.code,\n\t\t\t\terrorResponse.details,\n\t\t\t);\n\t\t}\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t}\n\ttry {\n\t\treturn JSON.parse(bodyText) as T;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t}\n}\n\nfunction getServerSentEventFieldValue(line: string, field: string): string {\n\tconst prefix = `${field}:`;\n\tconst value = line.slice(prefix.length);\n\treturn value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction parseServerSentEvents(bodyText: string): ServerSentEvent[] {\n\tconst parser = new ServerSentEventParser();\n\treturn [...parser.feed(bodyText), ...parser.finish()];\n}\n\nfunction parseServerSentEventData(event: ServerSentEvent, errorPrefix: string): unknown {\n\ttry {\n\t\treturn JSON.parse(event.data) as unknown;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (invalid event-stream JSON data: ${getBodyExcerpt(event.data)})`);\n\t}\n}\n\nfunction formatServerSentEventError(response: Response, payload: unknown): string {\n\tconst message = isObject(payload) && typeof payload.error === \"string\" ? payload.error : JSON.stringify(payload);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${getBodyExcerpt(message)}`;\n}\n\nasync function readPiServerEventStreamJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tfor (const event of parseServerSentEvents(bodyText)) {\n\t\tif (event.event === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`${errorPrefix} (${formatServerSentEventError(response, parseServerSentEventData(event, errorPrefix))})`,\n\t\t\t);\n\t\t}\n\t\tif (event.event === \"result\") {\n\t\t\treturn parseServerSentEventData(event, errorPrefix) as T;\n\t\t}\n\t}\n\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected result event)`);\n}\n\nasync function readPiServerCompactResponse<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst contentType = getResponseContentType(response).toLowerCase().split(\";\")[0]?.trim();\n\tif (contentType === \"text/event-stream\") {\n\t\treturn readPiServerEventStreamJson<T>(response, errorPrefix);\n\t}\n\treturn readPiServerJson<T>(response, errorPrefix);\n}\n\nfunction isAbortError(error: unknown, signal: AbortSignal | undefined): boolean {\n\treturn signal?.aborted === true || (error instanceof Error && error.name === \"AbortError\");\n}\n\nfunction isTransientPiServerFetchError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /fetch failed|network|socket hang up|terminated|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|CONNECT timeout/i.test(\n\t\tmessage,\n\t);\n}\n\nfunction isTransientPiServerError(error: unknown): boolean {\n\tif (isTransientPiServerFetchError(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t/\\b(?:500|502|503|504|524|530)\\b/.test(message) ||\n\t\t/CONNECT timeout|Bad Gateway|upstream|A timeout occurred/i.test(message)\n\t);\n}\n\nfunction isRetryablePiServerFailure(phase: PiServerFailurePhase, error: unknown): boolean {\n\tif (phase === \"provider_stream\") return true;\n\tif (phase === \"history_reconcile\") return false;\n\treturn isTransientPiServerError(error);\n}\n\nasync function waitForPiServerRetry(attempt: number, signal: AbortSignal | undefined): Promise<void> {\n\tawait sleep(TRANSIENT_PI_SERVER_RETRY_DELAYS_MS[attempt], undefined, { signal });\n}\n\nasync function postPiServerJsonWithTransientRetry<T>(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<T> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await request.postJson(endpoint, body);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!isAbortError(error, request.options.signal) &&\n\t\t\t\tisTransientPiServerFetchError(error)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst bodyText = await response.text();\n\t\tif (!response.ok) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!request.options.signal?.aborted &&\n\t\t\t\tTRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\t\tif (errorResponse) {\n\t\t\t\tthrow new PiServerResponseError(\n\t\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\t\terrorResponse.code,\n\t\t\t\t\terrorResponse.details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(bodyText) as T;\n\t\t} catch {\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t\t}\n\t}\n}\n\nasync function ensurePiServerEventStream(response: Response): Promise<void> {\n\tconst contentType = getResponseContentType(response);\n\tif (contentType.toLowerCase().split(\";\")[0]?.trim() === \"text/event-stream\") {\n\t\treturn;\n\t}\n\tconst bodyText = await response.text();\n\tthrow new Error(`pi-server error: ${formatResponseDetails(response, bodyText)}; expected text/event-stream`);\n}\n\nasync function ensureSessionInit(\n\tsessionId: string,\n\tcontext: Context,\n\trequest: ChunkRequest,\n): Promise<SessionInitResponse> {\n\tconst currentHash = hashStaticContext(context);\n\tconst previousHash = sessionStaticContextHashes.get(sessionId);\n\n\tif (previousHash === currentHash) {\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tstaticContextHash: previousHash,\n\t\t\tmessageCount: 0,\n\t\t\tfromCache: true,\n\t\t};\n\t}\n\n\tconst staticContext = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n\n\tconst endpoint = previousHash === undefined ? \"/api/session/init\" : \"/api/session/update\";\n\n\tconst result = await postPiServerJsonWithTransientRetry<SessionInitResponse>(\n\t\trequest,\n\t\tendpoint,\n\t\t{ sessionId, staticContext },\n\t\t\"Session init failed\",\n\t);\n\tsessionStaticContextHashes.set(sessionId, currentHash);\n\tif (result.treeHash !== undefined) {\n\t\tsessionTreeHashes.set(sessionId, result.treeHash);\n\t\tsessionTreeLeafIds.set(sessionId, result.leafId ?? null);\n\t\tif (result.entryCount !== undefined) {\n\t\t\tsessionTreeEntryCounts.set(sessionId, result.entryCount);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getStaticContext(context: Context) {\n\treturn {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n}\n\nfunction markTreeSynced(sessionId: string, tree: PiServerTreeSnapshot): void {\n\tconst prefixHashes = buildPiServerTreePrefixHashes(tree.entries);\n\tsessionTreeHashes.set(sessionId, prefixHashes[prefixHashes.length - 1]);\n\tsessionTreeEntryCounts.set(sessionId, tree.entries.length);\n\tsessionTreeLeafIds.set(sessionId, tree.leafId);\n\tif (tree.replace) {\n\t\tsessionHasTemporaryTree.add(sessionId);\n\t} else {\n\t\tsessionHasTemporaryTree.delete(sessionId);\n\t}\n}\n\nasync function postTreeJson(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<void> {\n\tawait postPiServerJsonWithTransientRetry<unknown>(request, endpoint, body, errorPrefix);\n}\n\nasync function fetchPiServerHistory(\n\tsessionId: string,\n\trequest: ChunkRequest,\n\tlocalTree?: PiServerTreeSnapshot,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst prefixHashes = localTree ? buildPiServerTreePrefixHashes(localTree.entries) : undefined;\n\tconst historyUrl =\n\t\tlocalTree && prefixHashes\n\t\t\t? `/api/session/${encodeURIComponent(sessionId)}/history?entriesFrom=${localTree.entries.length}&baseTreeHash=${encodeURIComponent(prefixHashes[prefixHashes.length - 1])}`\n\t\t\t: `/api/session/${encodeURIComponent(sessionId)}/history`;\n\tconst response = await request.getJson(historyUrl);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\tconst history = await readPiServerJson<PiServerHistoryResponse>(response, \"Session history reconciliation failed\");\n\tif (history.treePatch && localTree) {\n\t\treturn {\n\t\t\tentries: [...localTree.entries.slice(0, history.treePatch.entriesFrom), ...history.treePatch.entries],\n\t\t\tleafId: history.treePatch.leafId,\n\t\t\tmessages: history.messages ?? [],\n\t\t};\n\t}\n\tif (!history.entries || history.leafId === undefined || !history.messages) {\n\t\tthrow new Error(\"Session history reconciliation failed (response did not include the session tree)\");\n\t}\n\treturn {\n\t\tentries: history.entries,\n\t\tleafId: history.leafId,\n\t\tmessages: history.messages,\n\t};\n}\n\nasync function applyPiServerHistory(\n\tsessionId: string,\n\tsnapshot: PiServerHistorySnapshot,\n\tonHistoryReconciled: ((snapshot: PiServerHistorySnapshot) => void | Promise<void>) | undefined,\n): Promise<void> {\n\tmarkTreeSynced(sessionId, snapshot);\n\tawait onHistoryReconciled?.(snapshot);\n}\n\nasync function fetchPiServerRun(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n): Promise<PiServerRunResponse | undefined> {\n\tconst response = await request.getJson(\n\t\t`/api/session/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`,\n\t);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\treturn readPiServerJson<PiServerRunResponse>(response, \"Session run recovery failed\");\n}\n\nasync function waitForPiServerRunCompletion(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n\toptions: PiServerStreamOptions | undefined,\n): Promise<PiServerRunResponse | undefined> {\n\tconst deadline = Date.now() + DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS;\n\tfor (;;) {\n\t\tconst run = await fetchPiServerRun(sessionId, runId, request);\n\t\tif (!run || run.status !== \"running\") return run;\n\t\tif (Date.now() >= deadline) throw new PiServerRunRecoveryTimeoutError();\n\t\tawait sleep(PI_SERVER_RUN_RECOVERY_POLL_MS, undefined, { signal: options?.signal });\n\t}\n}\n\nfunction getKnownServerPrefixIds(sessionId: string, entries: SessionTreeEntry[]): Set<string> | undefined {\n\tconst entryCount = sessionTreeEntryCounts.get(sessionId);\n\tconst treeHash = sessionTreeHashes.get(sessionId);\n\tif (entryCount === undefined || treeHash === undefined || entryCount > entries.length) {\n\t\treturn undefined;\n\t}\n\tconst prefixHashes = buildPiServerTreePrefixHashes(entries);\n\tif (prefixHashes[entryCount] !== treeHash) {\n\t\treturn undefined;\n\t}\n\treturn new Set(entries.slice(0, entryCount).map((entry) => entry.id));\n}\n\nfunction isRecoverableTreeDivergenceCode(code: string | undefined): boolean {\n\treturn code === \"PARENT_ENTRY_NOT_FOUND\" || code === \"LEAF_ID_NOT_FOUND\" || code === \"ENTRY_ALREADY_EXISTS\";\n}\n\nfunction isRecoverableMissingServerStateCode(code: string | undefined): boolean {\n\treturn code === \"SESSION_NOT_FOUND\" || code === \"SESSION_NO_STATIC_CONTEXT\" || isRecoverableTreeDivergenceCode(code);\n}\n\nfunction isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tif (error instanceof PiServerResponseError) {\n\t\treturn isRecoverableTreeDivergenceCode(error.code);\n\t}\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\treturn isRecoverableTreeDivergenceCode((error as { code?: string }).code);\n\t}\n\treturn false;\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorCode?: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn isRecoverableMissingServerStateCode(errorCode);\n}\n\nasync function syncFullPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n): Promise<void> {\n\tawait postTreeJson(\n\t\trequest,\n\t\t\"/api/session/tree/sync\",\n\t\t{\n\t\t\tsessionId,\n\t\t\tentries: tree.entries,\n\t\t\tleafId: tree.leafId,\n\t\t\tstaticContext: getStaticContext(context),\n\t\t},\n\t\t\"Session tree sync failed\",\n\t);\n\tmarkTreeSynced(sessionId, tree);\n}\n\nfunction shouldUseServerHistory(sessionId: string, tree: PiServerTreeSnapshot): boolean {\n\treturn !tree.replace && !sessionHasTemporaryTree.has(sessionId) && (sessionTreeEntryCounts.get(sessionId) ?? 0) > 0;\n}\n\nasync function recoverPiServerTreeDivergence(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tif (shouldUseServerHistory(sessionId, tree)) {\n\t\tconst snapshot = await fetchPiServerHistory(sessionId, request, tree);\n\t\tif (snapshot && snapshot.entries.length > 0) {\n\t\t\tawait applyPiServerHistory(sessionId, snapshot, onHistoryReconciled);\n\t\t\treturn snapshot;\n\t\t}\n\t}\n\n\tawait syncFullPiServerTree(sessionId, context, tree, request);\n}\n\nexport async function syncPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\toptions?: PiServerSyncOptions,\n): Promise<void> {\n\tconst request = createPiServerRequest(options?.signal);\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\tsessionId,\n\t\tcontext,\n\t\ttree,\n\t\trequest,\n\t\toptions?.onHistoryReconciled,\n\t);\n\tif (reconciled) {\n\t\tthrow new Error(\"pi-server history differed from local history; local session was reconciled to server history\");\n\t}\n}\n\nasync function syncPiServerTreeWithRequest(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst syncTree = tree;\n\tconst currentHash = hashEntries(syncTree.entries);\n\tconst previousHash = sessionTreeHashes.get(sessionId);\n\tconst previousLeafId = sessionTreeLeafIds.get(sessionId);\n\n\tif (!tree.replace && previousHash === currentHash) {\n\t\tif (previousLeafId !== syncTree.leafId) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/switch\",\n\t\t\t\t\t{ sessionId, leafId: syncTree.leafId },\n\t\t\t\t\t\"Session tree switch failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tsessionTreeLeafIds.set(sessionId, syncTree.leafId);\n\t\t}\n\t\tmarkTreeSynced(sessionId, syncTree);\n\t\treturn;\n\t}\n\n\tconst syncedIds =\n\t\t!tree.replace && !sessionHasTemporaryTree.has(sessionId)\n\t\t\t? getKnownServerPrefixIds(sessionId, syncTree.entries)\n\t\t\t: undefined;\n\tif (syncedIds) {\n\t\tconst deltaEntries = syncTree.entries.filter((entry) => !syncedIds.has(entry.id));\n\t\tif (deltaEntries.length > 0) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/append\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tentries: deltaEntries,\n\t\t\t\t\t\tleafId: syncTree.leafId,\n\t\t\t\t\t\tstaticContext: getStaticContext(context),\n\t\t\t\t\t},\n\t\t\t\t\t\"Session tree append failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tmarkTreeSynced(sessionId, syncTree);\n\t\t\treturn;\n\t\t}\n\t}\n\n\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n}\n\nfunction serializeOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\treasoning: options?.reasoning,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tapiKey: options?.apiKey,\n\t\theaders: options?.headers,\n\t\tmetadata: options?.metadata,\n\t\ttransport: options?.transport,\n\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t};\n}\n\nexport interface PiServerCompactOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tcustomInstructions?: string;\n\tsettings?: unknown;\n\tpreparation?: CompactionPreparationOptions;\n\tsessionTree?: PiServerTreeSnapshot;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\nexport async function compactPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerCompactOptions,\n): Promise<PiServerCompactionResult> {\n\tconst sessionId = options?.sessionId ?? \"default\";\n\tconst runId = randomUUID();\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst request = createPiServerRequest(options?.signal);\n\n\ttry {\n\t\tawait ensureSessionInit(sessionId, context, request);\n\t\tlet tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\t\tlet preparation = options?.preparation;\n\t\tconst syncTree = async () => {\n\t\t\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\t\t\tsessionId,\n\t\t\t\tcontext,\n\t\t\t\ttree,\n\t\t\t\trequest,\n\t\t\t\toptions?.onHistoryReconciled,\n\t\t\t);\n\t\t\tif (reconciled) {\n\t\t\t\ttree = reconciled;\n\t\t\t\t// A forced cut point belongs to the old branch. Recompute it on the authoritative tree.\n\t\t\t\tpreparation = undefined;\n\t\t\t}\n\t\t};\n\t\tawait syncTree();\n\n\t\tconst makeBody = () => ({\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\tmodel,\n\t\t\toptions: serializeOptions(options),\n\t\t\tsettings: options?.settings,\n\t\t\tpreparation,\n\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\t\tstreamResponse: true,\n\t\t});\n\t\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\t\tif (!response.ok) {\n\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\tawait syncTree();\n\t\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t} else {\n\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t\t}\n\t\t}\n\t\tlet result: PiServerCompactionResponse;\n\t\ttry {\n\t\t\tresult = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\t\t} catch (error) {\n\t\t\tif (options?.signal?.aborted || !getResponseContentType(response).startsWith(\"text/event-stream\")) throw error;\n\t\t\tconst run = await waitForPiServerRunCompletion(sessionId, runId, request, options);\n\t\t\tif (run?.status !== \"completed\" || !run.compactResult) {\n\t\t\t\tif (run?.errorMessage) throw new Error(`Server compaction failed: ${run.errorMessage}`);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tresult = run.compactResult;\n\t\t}\n\t\tif (!result.compaction) {\n\t\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t\t}\n\t\tconst resultEntries =\n\t\t\tresult.entries ??\n\t\t\t(result.treePatch\n\t\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t\t: undefined);\n\t\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\t\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t\t}\n\t\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\t\treturn {\n\t\t\tcompaction: result.compaction,\n\t\t\tcompactionEntry: result.compactionEntry,\n\t\t\tentries: resultEntries,\n\t\t\tleafId: resultLeafId,\n\t\t\tmessages: result.messages ?? [],\n\t\t};\n\t} finally {\n\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t}\n}\n\nexport async function streamPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerStreamOptions,\n): Promise<PiServerEventStream> {\n\tconst sessionId = options?.sessionId ?? randomUUID();\n\tconst runId = randomUUID();\n\tconst isEphemeralSession = options?.sessionId === undefined;\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst stream = new PiServerEventStream();\n\n\tconst partial: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tstopReason: \"stop\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\ttimestamp: Date.now(),\n\t};\n\n\t(async () => {\n\t\tlet phase: PiServerFailurePhase = \"session_init\";\n\t\tlet streamOpened = false;\n\t\ttry {\n\t\t\tconst request = createPiServerRequest(options?.signal);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\n\t\t\tconst makeBody = () => ({\n\t\t\t\tsessionId,\n\t\t\t\trunId,\n\t\t\t\tmodel,\n\t\t\t\toptions: serializeOptions(options),\n\t\t\t\tcontextOverlay: options?.contextOverlay ?? [\n\t\t\t\t\t...(context.messages as Message[]),\n\t\t\t\t\t...(options?.ephemeralMessages ?? []),\n\t\t\t\t],\n\t\t\t});\n\t\t\tphase = \"provider_stream\";\n\t\t\tlet response = await request.postJson(\"/api/stream\", makeBody());\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\t\tresponse = await request.postJson(\"/api/stream\", makeBody());\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`pi-server error: ${failure.details}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ensurePiServerEventStream(response);\n\t\t\tstreamOpened = true;\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst parser = new ServerSentEventParser();\n\t\t\tlet terminalReceived = false;\n\n\t\t\tconst consumeEvents = (events: ServerSentEvent[]): void => {\n\t\t\t\tfor (const serverEvent of events) {\n\t\t\t\t\tconst proxyEvent = parseServerSentEventData(\n\t\t\t\t\t\tserverEvent,\n\t\t\t\t\t\t\"pi-server stream\",\n\t\t\t\t\t) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (!event) continue;\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalReceived = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tconsumeEvents(parser.feed(decoder.decode(value, { stream: true })));\n\t\t\t}\n\t\t\tconsumeEvents(parser.feed(decoder.decode()));\n\t\t\tconsumeEvents(parser.finish());\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\t\t\tif (!terminalReceived) {\n\t\t\t\tthrow new Error(\"pi-server stream ended before a terminal response event\");\n\t\t\t}\n\n\t\t\tif (isEphemeralSession) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tlet errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t// Same-run recovery only applies to an interrupted event-stream. HTTP/proxy\n\t\t\t// failures before the stream starts (502/504/fetch failed) never opened a run\n\t\t\t// we can poll; attempting recovery against a down proxy reclassifies the error\n\t\t\t// as history_reconcile and blocks session auto-retry.\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\" && streamOpened) {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await waitForPiServerRunCompletion(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tcreatePiServerRequest(options?.signal),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tif (recoveredRun?.status === \"completed\" && recoveredRun.message) {\n\t\t\t\t\t\tswitch (recoveredRun.message.stopReason) {\n\t\t\t\t\t\t\tcase \"stop\":\n\t\t\t\t\t\t\tcase \"length\":\n\t\t\t\t\t\t\tcase \"toolUse\":\n\t\t\t\t\t\t\tcase \"deferred\":\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\treason: recoveredRun.message.stopReason,\n\t\t\t\t\t\t\t\t\tmessage: recoveredRun.message,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"aborted\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"failed\" && recoveredRun.errorMessage) {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"aborted\") {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage ?? \"pi-server run aborted\";\n\t\t\t\t\t}\n\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\tphase = \"history_reconcile\";\n\t\t\t\t\terrorMessage = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options?.signal?.aborted && operation && !operation.cancelConfirmed) {\n\t\t\t\ttry {\n\t\t\t\t\tawait cancelPiServerOperation(operation);\n\t\t\t\t} catch (cancelError) {\n\t\t\t\t\terrorMessage = `${errorMessage}; cancellation failed: ${\n\t\t\t\t\t\tcancelError instanceof Error ? cancelError.message : String(cancelError)\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tpartial.diagnostics = [\n\t\t\t\t...(partial.diagnostics ?? []),\n\t\t\t\t{\n\t\t\t\t\ttype: \"pi_server_failure\",\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\terror: { name: error instanceof Error ? error.name : \"Error\", message: errorMessage },\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tphase,\n\t\t\t\t\t\tsource: \"pi-server\",\n\t\t\t\t\t\tretryable: isRetryablePiServerFailure(phase, error),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t\t\t} catch {\n\t\t\t\t// The owning session's cancellation helper reports the failure and keeps\n\t\t\t\t// this operation registered for a retry.\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn { type: \"text_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"text_end\", contentIndex: proxyEvent.contentIndex, content: content.text, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn { type: \"thinking_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"thinking_end\", contentIndex: proxyEvent.contentIndex, content: content.thinking, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} as any;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content };\n\t\t\t\treturn { type: \"toolcall_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn { type: \"toolcall_end\", contentIndex: proxyEvent.contentIndex, toolCall: content, partial };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nexport { getServerUrl, getAuthToken };\n"]}