@averyyy/pi-coding-agent 0.84.2-piclient.1 → 0.84.2-piclient.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
- Fixed compaction rendering to preserve the full active transcript, avoid duplicate compaction summaries, and keep the working indicator visible until the agent run settles.
|
|
9
9
|
- Fixed long compacted sessions blocking the terminal by rendering the latest compaction context first and lazy-loading earlier transcript entries in bounded batches.
|
|
10
10
|
- Fixed pi-server provider requests to send only the projected, compaction-aware LLM context instead of synchronizing the full durable session tree.
|
|
11
|
+
- Fixed pi-server tree recovery to use structured error codes and preserve authoritative tool-call namespaces.
|
|
12
|
+
- Fixed disconnected pi-server streams to recover the same run before allowing an outer provider retry, preventing duplicate concurrent provider requests.
|
|
13
|
+
|
|
11
14
|
## [0.84.2] - 2026-08-14
|
|
12
15
|
|
|
13
16
|
### New Features
|
|
@@ -44,7 +44,6 @@ export interface PiServerCompactOptions extends SimpleStreamOptions {
|
|
|
44
44
|
onHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;
|
|
45
45
|
}
|
|
46
46
|
export declare function compactPiServer(model: Model<any>, context: Context, options?: PiServerCompactOptions): Promise<PiServerCompactionResult>;
|
|
47
|
-
export declare function dropLastPiServerAssistantError(sessionId: string): Promise<void>;
|
|
48
47
|
export declare function streamPiServer(model: Model<any>, context: Context, options?: PiServerStreamOptions): Promise<PiServerEventStream>;
|
|
49
48
|
export { getServerUrl, getAuthToken };
|
|
50
49
|
//# sourceMappingURL=pi-server-client.d.ts.map
|
|
@@ -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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AK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClF;AAuCD,UAAU,mBAAmB;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,mBAAmB,CAAC,EAAE,CAAC,QAAQ,EAAE,uBAAuB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClF;AAkZD,wBAAsB,gBAAgB,CACrC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,oBAAoB,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAIf;AAyFD,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IAClE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,4BAA4B,CAAC;IAC3C,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,mBAAmB,CAAC,EAAE,CAAC,QAAQ,EAAE,uBAAuB,KAAK,IAAI,GAAG,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,CAyDnC;AAED,wBAAsB,8BAA8B,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAIrF;AAED,wBAAsB,cAAc,CACnC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,OAAO,CAAC,mBAAmB,CAAC,CAwJ9B;AA4FD,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>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([502, 503, 504, 530]);\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}\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\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tmatchText: string;\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\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\";\n\tmessage?: AssistantMessage;\n\terrorMessage?: string;\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 getJsonErrorText(text: string): string | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed)) return undefined;\n\t\tconst error = parsed.error;\n\t\treturn typeof error === \"string\" && error.length > 0 ? error : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\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\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tmatchText: getJsonErrorText(bodyText) ?? bodyText,\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\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 events: ServerSentEvent[] = [];\n\tlet event = \"message\";\n\tlet dataLines: string[] = [];\n\n\tconst flush = () => {\n\t\tif (dataLines.length === 0) return;\n\t\tevents.push({ event, data: dataLines.join(\"\\n\") });\n\t\tevent = \"message\";\n\t\tdataLines = [];\n\t};\n\n\tfor (const line of bodyText.split(/\\r?\\n/)) {\n\t\tif (line === \"\") {\n\t\t\tflush();\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\":\")) continue;\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tevent = getServerSentEventFieldValue(line, \"event\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tdataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t}\n\tflush();\n\treturn events;\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 isTransientPiServerResponse(response: Response, bodyText: string): boolean {\n\tif (!TRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)) return false;\n\tif (response.status === 530) return true;\n\treturn /CONNECT timeout|Bad Gateway|upstream|timeout/i.test(`${response.statusText}\\n${bodyText}`);\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\tisTransientPiServerResponse(response, bodyText)\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 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\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 isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /parent entry .* does not exist|leafId .* does not exist|entry .* already exists/i.test(message);\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorBody: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn /Session has no static context|session not found|parent entry .* does not exist|leafId .* does not exist|entry .* already exists/i.test(\n\t\terrorBody,\n\t);\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\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 request = createPiServerRequest(options?.signal);\n\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\n\tconst makeBody = () => ({\n\t\tsessionId,\n\t\tmodel,\n\t\toptions: serializeOptions(options),\n\t\tsettings: options?.settings,\n\t\tpreparation: options?.preparation,\n\t\tcustomInstructions: options?.customInstructions,\n\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\tstreamResponse: true,\n\t});\n\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\tif (!response.ok) {\n\t\tlet failure = await readPiServerFailure(response);\n\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.matchText)) {\n\t\t\tresetSessionTracking(sessionId);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\tif (response.ok) {\n\t\t\t\tfailure = { details: \"\", matchText: \"\" };\n\t\t\t} else {\n\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t}\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t}\n\t}\n\tconst result = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\tif (!result.compaction) {\n\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t}\n\tconst resultEntries =\n\t\tresult.entries ??\n\t\t(result.treePatch\n\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t: undefined);\n\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t}\n\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\treturn {\n\t\tcompaction: result.compaction,\n\t\tcompactionEntry: result.compactionEntry,\n\t\tentries: resultEntries,\n\t\tleafId: resultLeafId,\n\t\tmessages: result.messages ?? [],\n\t};\n}\n\nexport async function dropLastPiServerAssistantError(sessionId: string): Promise<void> {\n\tconst request = createPiServerRequest();\n\tconst response = await request.postJson(\"/api/session/drop-last-assistant-error\", { sessionId });\n\tawait readPiServerJson<unknown>(response, \"Dropping server assistant error failed\");\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 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\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.matchText)) {\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: \"\", matchText: \"\" };\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\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\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\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (!data) continue;\n\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\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\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await fetchPiServerRun(sessionId, runId, createPiServerRequest());\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} catch {\n\t\t\t\t\t// Keep the original stream error authoritative.\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: { phase, source: \"pi-server\", retryable: phase === \"provider_stream\" },\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}\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\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\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,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;AA6BD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAEtD;AAuBD,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAO5D;AAED,wBAAgB,uBAAuB,IAAI,IAAI,CAO9C;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,CAAC;IAClC,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,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,OAAO,CAAC,wBAAwB,CAAC,CAyDnC;AAED,wBAAsB,cAAc,CACnC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,OAAO,CAAC,mBAAmB,CAAC,CAsK9B;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>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([502, 503, 504, 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}\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\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\";\n\tmessage?: AssistantMessage;\n\terrorMessage?: string;\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 isTransientPiServerResponse(response: Response, bodyText: string): boolean {\n\tif (!TRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)) return false;\n\tif (response.status === 530) return true;\n\treturn /CONNECT timeout|Bad Gateway|upstream|timeout/i.test(`${response.statusText}\\n${bodyText}`);\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\tisTransientPiServerResponse(response, bodyText)\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\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 request = createPiServerRequest(options?.signal);\n\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\n\tconst makeBody = () => ({\n\t\tsessionId,\n\t\tmodel,\n\t\toptions: serializeOptions(options),\n\t\tsettings: options?.settings,\n\t\tpreparation: options?.preparation,\n\t\tcustomInstructions: options?.customInstructions,\n\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\tstreamResponse: true,\n\t});\n\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\tif (!response.ok) {\n\t\tlet failure = await readPiServerFailure(response);\n\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\tresetSessionTracking(sessionId);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\tif (response.ok) {\n\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t} else {\n\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t}\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t}\n\t}\n\tconst result = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\tif (!result.compaction) {\n\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t}\n\tconst resultEntries =\n\t\tresult.entries ??\n\t\t(result.treePatch\n\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t: undefined);\n\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t}\n\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\treturn {\n\t\tcompaction: result.compaction,\n\t\tcompactionEntry: result.compactionEntry,\n\t\tentries: resultEntries,\n\t\tleafId: resultLeafId,\n\t\tmessages: result.messages ?? [],\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 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\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\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\tif (!options?.signal?.aborted && phase === \"provider_stream\") {\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} 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\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: { phase, source: \"pi-server\", retryable: phase === \"provider_stream\" },\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}\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"]}
|
|
@@ -36,6 +36,14 @@ const sessionHasTemporaryTree = new Set();
|
|
|
36
36
|
const RESPONSE_BODY_EXCERPT_CHARS = 500;
|
|
37
37
|
const TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];
|
|
38
38
|
const TRANSIENT_PI_SERVER_STATUS_CODES = new Set([502, 503, 504, 530]);
|
|
39
|
+
const PI_SERVER_RUN_RECOVERY_POLL_MS = 250;
|
|
40
|
+
const DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS = 10 * 60 * 1000;
|
|
41
|
+
class PiServerRunRecoveryTimeoutError extends Error {
|
|
42
|
+
constructor() {
|
|
43
|
+
super("pi-server run recovery timed out; the server may still be processing the request");
|
|
44
|
+
this.name = "PiServerRunRecoveryTimeoutError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
39
47
|
export function hashStaticContext(ctx) {
|
|
40
48
|
return hashPiServerStaticContext(ctx);
|
|
41
49
|
}
|
|
@@ -74,6 +82,63 @@ export function resetAllSessionTracking() {
|
|
|
74
82
|
sessionTreeLeafIds.clear();
|
|
75
83
|
sessionHasTemporaryTree.clear();
|
|
76
84
|
}
|
|
85
|
+
class PiServerResponseError extends Error {
|
|
86
|
+
code;
|
|
87
|
+
details;
|
|
88
|
+
constructor(message, code, details) {
|
|
89
|
+
super(message);
|
|
90
|
+
this.name = "PiServerResponseError";
|
|
91
|
+
this.code = code;
|
|
92
|
+
this.details = details;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
class ServerSentEventParser {
|
|
96
|
+
buffer = "";
|
|
97
|
+
event = "message";
|
|
98
|
+
dataLines = [];
|
|
99
|
+
feed(text) {
|
|
100
|
+
this.buffer += text;
|
|
101
|
+
const lines = this.buffer.split("\n");
|
|
102
|
+
this.buffer = lines.pop() ?? "";
|
|
103
|
+
return lines.flatMap((line) => this.consumeLine(line));
|
|
104
|
+
}
|
|
105
|
+
finish() {
|
|
106
|
+
const events = [];
|
|
107
|
+
if (this.buffer.length > 0) {
|
|
108
|
+
events.push(...this.consumeLine(this.buffer));
|
|
109
|
+
this.buffer = "";
|
|
110
|
+
}
|
|
111
|
+
const final = this.flush();
|
|
112
|
+
if (final)
|
|
113
|
+
events.push(final);
|
|
114
|
+
return events;
|
|
115
|
+
}
|
|
116
|
+
consumeLine(rawLine) {
|
|
117
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
118
|
+
if (line === "") {
|
|
119
|
+
const event = this.flush();
|
|
120
|
+
return event ? [event] : [];
|
|
121
|
+
}
|
|
122
|
+
if (line.startsWith(":"))
|
|
123
|
+
return [];
|
|
124
|
+
if (line.startsWith("event:")) {
|
|
125
|
+
this.event = getServerSentEventFieldValue(line, "event");
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
if (line.startsWith("data:")) {
|
|
129
|
+
this.dataLines.push(getServerSentEventFieldValue(line, "data"));
|
|
130
|
+
}
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
flush() {
|
|
134
|
+
if (this.dataLines.length === 0)
|
|
135
|
+
return undefined;
|
|
136
|
+
const event = { event: this.event, data: this.dataLines.join("\n") };
|
|
137
|
+
this.event = "message";
|
|
138
|
+
this.dataLines = [];
|
|
139
|
+
return event;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
77
142
|
function isObject(value) {
|
|
78
143
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
79
144
|
}
|
|
@@ -91,34 +156,46 @@ function getBodyExcerpt(text) {
|
|
|
91
156
|
const excerpt = trimmed.slice(0, RESPONSE_BODY_EXCERPT_CHARS);
|
|
92
157
|
return excerpt.length < trimmed.length ? `${excerpt}...` : excerpt;
|
|
93
158
|
}
|
|
94
|
-
function
|
|
159
|
+
function getJsonErrorResponse(text) {
|
|
95
160
|
if (!text)
|
|
96
161
|
return undefined;
|
|
97
162
|
try {
|
|
98
163
|
const parsed = JSON.parse(text);
|
|
99
|
-
if (!isObject(parsed))
|
|
164
|
+
if (!isObject(parsed) || typeof parsed.error !== "string" || parsed.error.length === 0)
|
|
100
165
|
return undefined;
|
|
101
|
-
const
|
|
102
|
-
return
|
|
166
|
+
const code = parsed.code;
|
|
167
|
+
return {
|
|
168
|
+
error: parsed.error,
|
|
169
|
+
code: typeof code === "string" ? code : undefined,
|
|
170
|
+
details: isObject(parsed.details) ? parsed.details : undefined,
|
|
171
|
+
};
|
|
103
172
|
}
|
|
104
173
|
catch {
|
|
105
174
|
return undefined;
|
|
106
175
|
}
|
|
107
176
|
}
|
|
177
|
+
function getJsonErrorText(text) {
|
|
178
|
+
return getJsonErrorResponse(text)?.error;
|
|
179
|
+
}
|
|
108
180
|
function formatResponseDetails(response, bodyText) {
|
|
109
181
|
const body = getJsonErrorText(bodyText) ?? getBodyExcerpt(bodyText);
|
|
110
182
|
return `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${body}`;
|
|
111
183
|
}
|
|
112
184
|
async function readPiServerFailure(response) {
|
|
113
185
|
const bodyText = await response.text();
|
|
186
|
+
const errorResponse = getJsonErrorResponse(bodyText);
|
|
114
187
|
return {
|
|
115
188
|
details: formatResponseDetails(response, bodyText),
|
|
116
|
-
|
|
189
|
+
code: errorResponse?.code,
|
|
117
190
|
};
|
|
118
191
|
}
|
|
119
192
|
async function readPiServerJson(response, errorPrefix) {
|
|
120
193
|
const bodyText = await response.text();
|
|
121
194
|
if (!response.ok) {
|
|
195
|
+
const errorResponse = getJsonErrorResponse(bodyText);
|
|
196
|
+
if (errorResponse) {
|
|
197
|
+
throw new PiServerResponseError(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`, errorResponse.code, errorResponse.details);
|
|
198
|
+
}
|
|
122
199
|
throw new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);
|
|
123
200
|
}
|
|
124
201
|
try {
|
|
@@ -134,33 +211,8 @@ function getServerSentEventFieldValue(line, field) {
|
|
|
134
211
|
return value.startsWith(" ") ? value.slice(1) : value;
|
|
135
212
|
}
|
|
136
213
|
function parseServerSentEvents(bodyText) {
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
let dataLines = [];
|
|
140
|
-
const flush = () => {
|
|
141
|
-
if (dataLines.length === 0)
|
|
142
|
-
return;
|
|
143
|
-
events.push({ event, data: dataLines.join("\n") });
|
|
144
|
-
event = "message";
|
|
145
|
-
dataLines = [];
|
|
146
|
-
};
|
|
147
|
-
for (const line of bodyText.split(/\r?\n/)) {
|
|
148
|
-
if (line === "") {
|
|
149
|
-
flush();
|
|
150
|
-
continue;
|
|
151
|
-
}
|
|
152
|
-
if (line.startsWith(":"))
|
|
153
|
-
continue;
|
|
154
|
-
if (line.startsWith("event:")) {
|
|
155
|
-
event = getServerSentEventFieldValue(line, "event");
|
|
156
|
-
continue;
|
|
157
|
-
}
|
|
158
|
-
if (line.startsWith("data:")) {
|
|
159
|
-
dataLines.push(getServerSentEventFieldValue(line, "data"));
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
flush();
|
|
163
|
-
return events;
|
|
214
|
+
const parser = new ServerSentEventParser();
|
|
215
|
+
return [...parser.feed(bodyText), ...parser.finish()];
|
|
164
216
|
}
|
|
165
217
|
function parseServerSentEventData(event, errorPrefix) {
|
|
166
218
|
try {
|
|
@@ -233,6 +285,10 @@ async function postPiServerJsonWithTransientRetry(request, endpoint, body, error
|
|
|
233
285
|
await waitForPiServerRetry(attempt, request.options.signal);
|
|
234
286
|
continue;
|
|
235
287
|
}
|
|
288
|
+
const errorResponse = getJsonErrorResponse(bodyText);
|
|
289
|
+
if (errorResponse) {
|
|
290
|
+
throw new PiServerResponseError(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`, errorResponse.code, errorResponse.details);
|
|
291
|
+
}
|
|
236
292
|
throw new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);
|
|
237
293
|
}
|
|
238
294
|
try {
|
|
@@ -337,6 +393,17 @@ async function fetchPiServerRun(sessionId, runId, request) {
|
|
|
337
393
|
}
|
|
338
394
|
return readPiServerJson(response, "Session run recovery failed");
|
|
339
395
|
}
|
|
396
|
+
async function waitForPiServerRunCompletion(sessionId, runId, request, options) {
|
|
397
|
+
const deadline = Date.now() + DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS;
|
|
398
|
+
for (;;) {
|
|
399
|
+
const run = await fetchPiServerRun(sessionId, runId, request);
|
|
400
|
+
if (!run || run.status !== "running")
|
|
401
|
+
return run;
|
|
402
|
+
if (Date.now() >= deadline)
|
|
403
|
+
throw new PiServerRunRecoveryTimeoutError();
|
|
404
|
+
await sleep(PI_SERVER_RUN_RECOVERY_POLL_MS, undefined, { signal: options?.signal });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
340
407
|
function getKnownServerPrefixIds(sessionId, entries) {
|
|
341
408
|
const entryCount = sessionTreeEntryCounts.get(sessionId);
|
|
342
409
|
const treeHash = sessionTreeHashes.get(sessionId);
|
|
@@ -351,14 +418,25 @@ function getKnownServerPrefixIds(sessionId, entries) {
|
|
|
351
418
|
sessionSyncedEntryIds.set(sessionId, ids);
|
|
352
419
|
return ids;
|
|
353
420
|
}
|
|
421
|
+
function isRecoverableTreeDivergenceCode(code) {
|
|
422
|
+
return code === "PARENT_ENTRY_NOT_FOUND" || code === "LEAF_ID_NOT_FOUND" || code === "ENTRY_ALREADY_EXISTS";
|
|
423
|
+
}
|
|
424
|
+
function isRecoverableMissingServerStateCode(code) {
|
|
425
|
+
return code === "SESSION_NOT_FOUND" || code === "SESSION_NO_STATIC_CONTEXT" || isRecoverableTreeDivergenceCode(code);
|
|
426
|
+
}
|
|
354
427
|
function isRecoverableTreeDivergenceError(error) {
|
|
355
|
-
|
|
356
|
-
|
|
428
|
+
if (error instanceof PiServerResponseError) {
|
|
429
|
+
return isRecoverableTreeDivergenceCode(error.code);
|
|
430
|
+
}
|
|
431
|
+
if (error && typeof error === "object" && "code" in error) {
|
|
432
|
+
return isRecoverableTreeDivergenceCode(error.code);
|
|
433
|
+
}
|
|
434
|
+
return false;
|
|
357
435
|
}
|
|
358
|
-
function isRecoverableMissingServerState(response,
|
|
436
|
+
function isRecoverableMissingServerState(response, errorCode) {
|
|
359
437
|
if (response.status !== 400 && response.status !== 404)
|
|
360
438
|
return false;
|
|
361
|
-
return
|
|
439
|
+
return isRecoverableMissingServerStateCode(errorCode);
|
|
362
440
|
}
|
|
363
441
|
async function syncFullPiServerTree(sessionId, context, tree, request) {
|
|
364
442
|
await postTreeJson(request, "/api/session/tree/sync", {
|
|
@@ -473,13 +551,13 @@ export async function compactPiServer(model, context, options) {
|
|
|
473
551
|
let response = await request.postJson("/api/session/compact", makeBody());
|
|
474
552
|
if (!response.ok) {
|
|
475
553
|
let failure = await readPiServerFailure(response);
|
|
476
|
-
if (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.
|
|
554
|
+
if (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {
|
|
477
555
|
resetSessionTracking(sessionId);
|
|
478
556
|
await ensureSessionInit(sessionId, context, request);
|
|
479
557
|
await syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);
|
|
480
558
|
response = await request.postJson("/api/session/compact", makeBody());
|
|
481
559
|
if (response.ok) {
|
|
482
|
-
failure = { details: "",
|
|
560
|
+
failure = { details: "", code: undefined };
|
|
483
561
|
}
|
|
484
562
|
else {
|
|
485
563
|
failure = await readPiServerFailure(response);
|
|
@@ -510,11 +588,6 @@ export async function compactPiServer(model, context, options) {
|
|
|
510
588
|
messages: result.messages ?? [],
|
|
511
589
|
};
|
|
512
590
|
}
|
|
513
|
-
export async function dropLastPiServerAssistantError(sessionId) {
|
|
514
|
-
const request = createPiServerRequest();
|
|
515
|
-
const response = await request.postJson("/api/session/drop-last-assistant-error", { sessionId });
|
|
516
|
-
await readPiServerJson(response, "Dropping server assistant error failed");
|
|
517
|
-
}
|
|
518
591
|
export async function streamPiServer(model, context, options) {
|
|
519
592
|
const sessionId = options?.sessionId ?? randomUUID();
|
|
520
593
|
const runId = randomUUID();
|
|
@@ -556,12 +629,12 @@ export async function streamPiServer(model, context, options) {
|
|
|
556
629
|
let response = await request.postJson("/api/stream", makeBody());
|
|
557
630
|
if (!response.ok) {
|
|
558
631
|
let failure = await readPiServerFailure(response);
|
|
559
|
-
if (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.
|
|
632
|
+
if (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {
|
|
560
633
|
resetSessionTracking(sessionId);
|
|
561
634
|
await ensureSessionInit(sessionId, context, request);
|
|
562
635
|
response = await request.postJson("/api/stream", makeBody());
|
|
563
636
|
if (response.ok) {
|
|
564
|
-
failure = { details: "",
|
|
637
|
+
failure = { details: "", code: undefined };
|
|
565
638
|
}
|
|
566
639
|
else {
|
|
567
640
|
failure = await readPiServerFailure(response);
|
|
@@ -574,7 +647,19 @@ export async function streamPiServer(model, context, options) {
|
|
|
574
647
|
await ensurePiServerEventStream(response);
|
|
575
648
|
const reader = response.body.getReader();
|
|
576
649
|
const decoder = new TextDecoder();
|
|
577
|
-
|
|
650
|
+
const parser = new ServerSentEventParser();
|
|
651
|
+
let terminalReceived = false;
|
|
652
|
+
const consumeEvents = (events) => {
|
|
653
|
+
for (const serverEvent of events) {
|
|
654
|
+
const proxyEvent = parseServerSentEventData(serverEvent, "pi-server stream");
|
|
655
|
+
const event = processProxyEvent(proxyEvent, partial);
|
|
656
|
+
if (!event)
|
|
657
|
+
continue;
|
|
658
|
+
if (event.type === "done" || event.type === "error")
|
|
659
|
+
terminalReceived = true;
|
|
660
|
+
stream.push(event);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
578
663
|
while (true) {
|
|
579
664
|
const { done, value } = await reader.read();
|
|
580
665
|
if (done)
|
|
@@ -582,35 +667,26 @@ export async function streamPiServer(model, context, options) {
|
|
|
582
667
|
if (options?.signal?.aborted) {
|
|
583
668
|
throw new Error("Request aborted by user");
|
|
584
669
|
}
|
|
585
|
-
|
|
586
|
-
const lines = buffer.split("\n");
|
|
587
|
-
buffer = lines.pop() || "";
|
|
588
|
-
for (const line of lines) {
|
|
589
|
-
if (line.startsWith("data: ")) {
|
|
590
|
-
const data = line.slice(6).trim();
|
|
591
|
-
if (!data)
|
|
592
|
-
continue;
|
|
593
|
-
const proxyEvent = JSON.parse(data);
|
|
594
|
-
const event = processProxyEvent(proxyEvent, partial);
|
|
595
|
-
if (event) {
|
|
596
|
-
stream.push(event);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
}
|
|
670
|
+
consumeEvents(parser.feed(decoder.decode(value, { stream: true })));
|
|
600
671
|
}
|
|
672
|
+
consumeEvents(parser.feed(decoder.decode()));
|
|
673
|
+
consumeEvents(parser.finish());
|
|
601
674
|
if (options?.signal?.aborted) {
|
|
602
675
|
throw new Error("Request aborted by user");
|
|
603
676
|
}
|
|
677
|
+
if (!terminalReceived) {
|
|
678
|
+
throw new Error("pi-server stream ended before a terminal response event");
|
|
679
|
+
}
|
|
604
680
|
if (isEphemeralSession) {
|
|
605
681
|
resetSessionTracking(sessionId);
|
|
606
682
|
}
|
|
607
683
|
stream.end();
|
|
608
684
|
}
|
|
609
685
|
catch (error) {
|
|
610
|
-
|
|
686
|
+
let errorMessage = error instanceof Error ? error.message : String(error);
|
|
611
687
|
if (!options?.signal?.aborted && phase === "provider_stream") {
|
|
612
688
|
try {
|
|
613
|
-
const recoveredRun = await
|
|
689
|
+
const recoveredRun = await waitForPiServerRunCompletion(sessionId, runId, createPiServerRequest(options?.signal), options);
|
|
614
690
|
if (recoveredRun?.status === "completed" && recoveredRun.message) {
|
|
615
691
|
switch (recoveredRun.message.stopReason) {
|
|
616
692
|
case "stop":
|
|
@@ -633,9 +709,13 @@ export async function streamPiServer(model, context, options) {
|
|
|
633
709
|
stream.end();
|
|
634
710
|
return;
|
|
635
711
|
}
|
|
712
|
+
if (recoveredRun?.status === "failed" && recoveredRun.errorMessage) {
|
|
713
|
+
errorMessage = recoveredRun.errorMessage;
|
|
714
|
+
}
|
|
636
715
|
}
|
|
637
|
-
catch {
|
|
638
|
-
|
|
716
|
+
catch (recoveryError) {
|
|
717
|
+
phase = "history_reconcile";
|
|
718
|
+
errorMessage = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);
|
|
639
719
|
}
|
|
640
720
|
}
|
|
641
721
|
const reason = options?.signal?.aborted ? "aborted" : "error";
|
|
@@ -724,12 +804,15 @@ function processProxyEvent(proxyEvent, partial) {
|
|
|
724
804
|
case "toolcall_end": {
|
|
725
805
|
const content = partial.content[proxyEvent.contentIndex];
|
|
726
806
|
if (content?.type === "toolCall") {
|
|
807
|
+
Object.assign(content, proxyEvent.toolCall);
|
|
727
808
|
delete content.partialJson;
|
|
728
809
|
return { type: "toolcall_end", contentIndex: proxyEvent.contentIndex, toolCall: content, partial };
|
|
729
810
|
}
|
|
730
811
|
return undefined;
|
|
731
812
|
}
|
|
732
813
|
case "done":
|
|
814
|
+
if (proxyEvent.message)
|
|
815
|
+
return { type: "done", reason: proxyEvent.reason, message: proxyEvent.message };
|
|
733
816
|
partial.stopReason = proxyEvent.reason;
|
|
734
817
|
partial.usage = proxyEvent.usage;
|
|
735
818
|
partial.deferred = proxyEvent.deferred;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi-server-client.js","sourceRoot":"","sources":["../../src/core/pi-server-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAO3D,OAAO,EAIN,WAAW,EAGX,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,6BAA6B,EAC7B,0BAA0B,EAC1B,yBAAyB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,MAAM,mBAAoB,SAAQ,WAAoD;IACrF,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;gBAAE,OAAO,KAAK,CAAC,OAAO,CAAC;YAChD,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;gBAAE,OAAO,KAAK,CAAC,KAAK,CAAC;YAC/C,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAAA,CACzC,CACD,CAAC;IAAA,CACF;CACD;AAED,SAAS,YAAY,GAAW;IAC/B,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,uBAAuB,CAAC;AAAA,CAC5D;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,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QACrE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AAAA,CACD;AAED,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>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([502, 503, 504, 530]);\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}\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\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tmatchText: string;\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\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\";\n\tmessage?: AssistantMessage;\n\terrorMessage?: string;\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 getJsonErrorText(text: string): string | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed)) return undefined;\n\t\tconst error = parsed.error;\n\t\treturn typeof error === \"string\" && error.length > 0 ? error : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\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\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tmatchText: getJsonErrorText(bodyText) ?? bodyText,\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\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 events: ServerSentEvent[] = [];\n\tlet event = \"message\";\n\tlet dataLines: string[] = [];\n\n\tconst flush = () => {\n\t\tif (dataLines.length === 0) return;\n\t\tevents.push({ event, data: dataLines.join(\"\\n\") });\n\t\tevent = \"message\";\n\t\tdataLines = [];\n\t};\n\n\tfor (const line of bodyText.split(/\\r?\\n/)) {\n\t\tif (line === \"\") {\n\t\t\tflush();\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\":\")) continue;\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tevent = getServerSentEventFieldValue(line, \"event\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tdataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t}\n\tflush();\n\treturn events;\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 isTransientPiServerResponse(response: Response, bodyText: string): boolean {\n\tif (!TRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)) return false;\n\tif (response.status === 530) return true;\n\treturn /CONNECT timeout|Bad Gateway|upstream|timeout/i.test(`${response.statusText}\\n${bodyText}`);\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\tisTransientPiServerResponse(response, bodyText)\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 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\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 isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /parent entry .* does not exist|leafId .* does not exist|entry .* already exists/i.test(message);\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorBody: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn /Session has no static context|session not found|parent entry .* does not exist|leafId .* does not exist|entry .* already exists/i.test(\n\t\terrorBody,\n\t);\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\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 request = createPiServerRequest(options?.signal);\n\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\n\tconst makeBody = () => ({\n\t\tsessionId,\n\t\tmodel,\n\t\toptions: serializeOptions(options),\n\t\tsettings: options?.settings,\n\t\tpreparation: options?.preparation,\n\t\tcustomInstructions: options?.customInstructions,\n\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\tstreamResponse: true,\n\t});\n\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\tif (!response.ok) {\n\t\tlet failure = await readPiServerFailure(response);\n\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.matchText)) {\n\t\t\tresetSessionTracking(sessionId);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\tif (response.ok) {\n\t\t\t\tfailure = { details: \"\", matchText: \"\" };\n\t\t\t} else {\n\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t}\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t}\n\t}\n\tconst result = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\tif (!result.compaction) {\n\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t}\n\tconst resultEntries =\n\t\tresult.entries ??\n\t\t(result.treePatch\n\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t: undefined);\n\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t}\n\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\treturn {\n\t\tcompaction: result.compaction,\n\t\tcompactionEntry: result.compactionEntry,\n\t\tentries: resultEntries,\n\t\tleafId: resultLeafId,\n\t\tmessages: result.messages ?? [],\n\t};\n}\n\nexport async function dropLastPiServerAssistantError(sessionId: string): Promise<void> {\n\tconst request = createPiServerRequest();\n\tconst response = await request.postJson(\"/api/session/drop-last-assistant-error\", { sessionId });\n\tawait readPiServerJson<unknown>(response, \"Dropping server assistant error failed\");\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 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\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.matchText)) {\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: \"\", matchText: \"\" };\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\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\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\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (!data) continue;\n\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\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\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await fetchPiServerRun(sessionId, runId, createPiServerRequest());\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} catch {\n\t\t\t\t\t// Keep the original stream error authoritative.\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: { phase, source: \"pi-server\", retryable: phase === \"provider_stream\" },\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}\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\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\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.js","sourceRoot":"","sources":["../../src/core/pi-server-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAO3D,OAAO,EAIN,WAAW,EAGX,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,6BAA6B,EAC7B,0BAA0B,EAC1B,yBAAyB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,MAAM,mBAAoB,SAAQ,WAAoD;IACrF,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KA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cesContent":["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>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([502, 503, 504, 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}\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\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\";\n\tmessage?: AssistantMessage;\n\terrorMessage?: string;\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 isTransientPiServerResponse(response: Response, bodyText: string): boolean {\n\tif (!TRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)) return false;\n\tif (response.status === 530) return true;\n\treturn /CONNECT timeout|Bad Gateway|upstream|timeout/i.test(`${response.statusText}\\n${bodyText}`);\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\tisTransientPiServerResponse(response, bodyText)\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\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 request = createPiServerRequest(options?.signal);\n\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\n\tconst makeBody = () => ({\n\t\tsessionId,\n\t\tmodel,\n\t\toptions: serializeOptions(options),\n\t\tsettings: options?.settings,\n\t\tpreparation: options?.preparation,\n\t\tcustomInstructions: options?.customInstructions,\n\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\tstreamResponse: true,\n\t});\n\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\tif (!response.ok) {\n\t\tlet failure = await readPiServerFailure(response);\n\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\tresetSessionTracking(sessionId);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\tawait syncPiServerTreeWithRequest(sessionId, context, tree, request, options?.onHistoryReconciled);\n\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\tif (response.ok) {\n\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t} else {\n\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t}\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t}\n\t}\n\tconst result = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\tif (!result.compaction) {\n\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t}\n\tconst resultEntries =\n\t\tresult.entries ??\n\t\t(result.treePatch\n\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t: undefined);\n\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t}\n\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\treturn {\n\t\tcompaction: result.compaction,\n\t\tcompactionEntry: result.compactionEntry,\n\t\tentries: resultEntries,\n\t\tleafId: resultLeafId,\n\t\tmessages: result.messages ?? [],\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 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\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\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\tif (!options?.signal?.aborted && phase === \"provider_stream\") {\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} 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\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: { phase, source: \"pi-server\", retryable: phase === \"provider_stream\" },\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}\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@averyyy/pi-coding-agent",
|
|
3
|
-
"version": "0.84.2-piclient.
|
|
3
|
+
"version": "0.84.2-piclient.3",
|
|
4
4
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"piConfig": {
|
|
@@ -50,11 +50,11 @@
|
|
|
50
50
|
"prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@0.84.2-piclient.
|
|
54
|
-
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@0.84.2-piclient.
|
|
53
|
+
"@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@0.84.2-piclient.3",
|
|
54
|
+
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@0.84.2-piclient.3",
|
|
55
55
|
"@earendil-works/pi-client": "^0.84.2",
|
|
56
56
|
"@earendil-works/pi-protocol": "^0.84.2",
|
|
57
|
-
"@earendil-works/pi-tui": "npm:@averyyy/pi-tui@0.84.2-piclient.
|
|
57
|
+
"@earendil-works/pi-tui": "npm:@averyyy/pi-tui@0.84.2-piclient.3",
|
|
58
58
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
59
59
|
"chalk": "5.6.2",
|
|
60
60
|
"cross-spawn": "7.0.6",
|