@averyyy/pi-coding-agent 0.87.0-piclient.2 → 0.87.1-piclient.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +25 -711
  3. package/dist/bundle/chunks/{anthropic-messages-MYU5ZMRF.js → anthropic-messages-J5WXPPPC.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-6OYWS3W7.js → chunk-BZKWNWMI.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-KEXYQWZW.js → chunk-X2F52Z34.js} +45 -29
  6. package/dist/bundle/chunks/github-copilot.js +1 -1
  7. package/dist/bundle/chunks/{openai-completions-XHML6MTL.js → openai-completions-OBX42CLD.js} +1 -1
  8. package/dist/bundle/chunks/{virtual-modules-5W7KEXM3.js → virtual-modules-WWGGM27U.js} +1 -1
  9. package/dist/bundle/cli-runtime.js +1 -1
  10. package/dist/bundle/index.js +1 -1
  11. package/dist/bundle/rpc-entry.js +1 -1
  12. package/dist/cli/args.d.ts.map +1 -1
  13. package/dist/cli/args.js +14 -4
  14. package/dist/cli/args.js.map +1 -1
  15. package/dist/core/agent-session.d.ts +2 -0
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +73 -3
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/compaction/compaction.d.ts +10 -3
  20. package/dist/core/compaction/compaction.d.ts.map +1 -1
  21. package/dist/core/compaction/compaction.js +82 -23
  22. package/dist/core/compaction/compaction.js.map +1 -1
  23. package/dist/core/model-resolver.d.ts.map +1 -1
  24. package/dist/core/model-resolver.js +1 -1
  25. package/dist/core/model-resolver.js.map +1 -1
  26. package/dist/core/pi-server-client.d.ts +5 -0
  27. package/dist/core/pi-server-client.d.ts.map +1 -1
  28. package/dist/core/pi-server-client.js +3 -0
  29. package/dist/core/pi-server-client.js.map +1 -1
  30. package/dist/core/pi-server-protocol.d.ts +2 -1
  31. package/dist/core/pi-server-protocol.d.ts.map +1 -1
  32. package/dist/core/pi-server-protocol.js +16 -0
  33. package/dist/core/pi-server-protocol.js.map +1 -1
  34. package/docs/cli-integration.md +106 -0
  35. package/docs/cli.md +268 -0
  36. package/docs/compaction.md +22 -22
  37. package/docs/configuration.md +45 -0
  38. package/docs/containerization.md +109 -82
  39. package/docs/custom-provider.md +132 -784
  40. package/docs/docs.json +139 -99
  41. package/docs/environment-variables.md +3 -5
  42. package/docs/extensions.md +134 -3020
  43. package/docs/how-pi-works.md +49 -0
  44. package/docs/images/interactive-mode.png +0 -0
  45. package/docs/index.md +24 -69
  46. package/docs/json.md +193 -65
  47. package/docs/keybindings.md +57 -102
  48. package/docs/llama-cpp.md +3 -3
  49. package/docs/message-types.md +261 -0
  50. package/docs/models.md +55 -565
  51. package/docs/packages.md +66 -167
  52. package/docs/prompt-templates.md +31 -68
  53. package/docs/providers.md +102 -240
  54. package/docs/quickstart.md +61 -106
  55. package/docs/rpc-commands.md +854 -0
  56. package/docs/rpc-extension-ui.md +200 -0
  57. package/docs/rpc.md +129 -1556
  58. package/docs/sdk.md +76 -1171
  59. package/docs/security.md +70 -32
  60. package/docs/session-format.md +10 -214
  61. package/docs/sessions.md +35 -141
  62. package/docs/settings.md +109 -387
  63. package/docs/shell-aliases.md +85 -5
  64. package/docs/skills.md +51 -190
  65. package/docs/slash-commands.md +60 -0
  66. package/docs/terminal-setup.md +105 -78
  67. package/docs/termux.md +74 -83
  68. package/docs/themes.md +68 -280
  69. package/docs/tmux.md +31 -39
  70. package/docs/tui.md +69 -923
  71. package/docs/usage.md +54 -272
  72. package/docs/windows.md +43 -17
  73. package/examples/README.md +13 -2
  74. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  75. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  76. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  77. package/examples/extensions/gondolin/package-lock.json +2 -2
  78. package/examples/extensions/gondolin/package.json +1 -1
  79. package/examples/extensions/sandbox/package-lock.json +2 -2
  80. package/examples/extensions/sandbox/package.json +1 -1
  81. package/examples/extensions/with-deps/package-lock.json +2 -2
  82. package/examples/extensions/with-deps/package.json +1 -1
  83. package/examples/rpc-client.ts +35 -0
  84. package/examples/rpc-extension-ui.ts +25 -5
  85. package/examples/sdk/README.md +1 -1
  86. package/package.json +8 -8
  87. package/docs/development.md +0 -90
@@ -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;AAED,SAAS,YAAY,GAAW;IAC/B,OAA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O,EAAE,CAAC;QACtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,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 sessionTreeHashes = new Map<string, string>();\nconst sessionTreeEntryCounts = new Map<string, number>();\nconst sessionTreeLeafIds = new Map<string, string | null>();\nconst sessionHasTemporaryTree = new Set<string>();\ninterface ActivePiServerOperation {\n\townerSessionId: string;\n\tsessionId: string;\n\trunId: string;\n\tsignal?: AbortSignal;\n\tcancelListener?: () => void;\n\tcancelPromise?: Promise<void>;\n\tcancelFailed?: boolean;\n\tcancelConfirmed?: boolean;\n}\n\nconst activePiServerOperations = new Map<string, Map<string, ActivePiServerOperation>>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([500, 502, 503, 504, 524, 530]);\nconst PI_SERVER_RUN_RECOVERY_POLL_MS = 250;\nconst DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS = 10 * 60 * 1000;\n\nclass PiServerRunRecoveryTimeoutError extends Error {\n\tconstructor() {\n\t\tsuper(\"pi-server run recovery timed out; the server may still be processing the request\");\n\t\tthis.name = \"PiServerRunRecoveryTimeoutError\";\n\t}\n}\n\nexport function hashStaticContext(ctx: Context): string {\n\treturn hashPiServerStaticContext(ctx);\n}\n\nfunction hashEntries(entries: SessionTreeEntry[]): string {\n\treturn hashPiServerSessionEntries(entries);\n}\n\nfunction getLinearTreeFromMessages(messages: Message[]): { entries: SessionTreeEntry[]; leafId: string | null } {\n\tlet parentId: string | null = null;\n\tconst entries = messages.map((message, index): SessionTreeEntry => {\n\t\tconst id = `message-${index}`;\n\t\tconst entry: SessionTreeEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid,\n\t\t\tparentId,\n\t\t\ttimestamp: new Date(message.timestamp).toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tparentId = id;\n\t\treturn entry;\n\t});\n\treturn { entries, leafId: parentId };\n}\n\nexport function resetSessionTracking(sessionId: string): void {\n\tsessionStaticContextHashes.delete(sessionId);\n\tsessionTreeHashes.delete(sessionId);\n\tsessionTreeEntryCounts.delete(sessionId);\n\tsessionTreeLeafIds.delete(sessionId);\n\tsessionHasTemporaryTree.delete(sessionId);\n}\n\nexport function resetAllSessionTracking(): void {\n\tsessionStaticContextHashes.clear();\n\tsessionTreeHashes.clear();\n\tsessionTreeEntryCounts.clear();\n\tsessionTreeLeafIds.clear();\n\tsessionHasTemporaryTree.clear();\n\tactivePiServerOperations.clear();\n}\n\nfunction registerPiServerOperation(\n\townerSessionId: string | undefined,\n\tsessionId: string,\n\trunId: string,\n\tsignal?: AbortSignal,\n): ActivePiServerOperation | undefined {\n\tif (!ownerSessionId) return undefined;\n\tlet operations = activePiServerOperations.get(ownerSessionId);\n\tif (!operations) {\n\t\toperations = new Map();\n\t\tactivePiServerOperations.set(ownerSessionId, operations);\n\t}\n\tconst operation: ActivePiServerOperation = { ownerSessionId, sessionId, runId, signal };\n\toperations.set(runId, operation);\n\tif (signal) {\n\t\tconst onAbort = () => {\n\t\t\tvoid cancelPiServerOperation(operation).catch(() => {\n\t\t\t\t// The owner session retries cancellation and reports the failure.\n\t\t\t});\n\t\t};\n\t\toperation.cancelListener = onAbort;\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (signal.aborted) onAbort();\n\t}\n\treturn operation;\n}\n\nfunction removePiServerOperation(operation: ActivePiServerOperation): void {\n\tconst operations = activePiServerOperations.get(operation.ownerSessionId);\n\toperation.cancelConfirmed = true;\n\tif (operation.signal && operation.cancelListener) {\n\t\toperation.signal.removeEventListener(\"abort\", operation.cancelListener);\n\t}\n\toperation.cancelListener = undefined;\n\tif (!operations || operations.get(operation.runId) !== operation) return;\n\toperations.delete(operation.runId);\n\tif (operations.size === 0) activePiServerOperations.delete(operation.ownerSessionId);\n}\n\nasync function finishPiServerOperation(\n\toperation: ActivePiServerOperation | undefined,\n\taborted: boolean,\n): Promise<void> {\n\tif (!operation) return;\n\tif (aborted) {\n\t\tif (operation.cancelPromise) await operation.cancelPromise;\n\t} else {\n\t\tremovePiServerOperation(operation);\n\t}\n}\n\nasync function cancelPiServerOperation(operation: ActivePiServerOperation, retryFailed = false): Promise<void> {\n\tif (operation.cancelConfirmed) return;\n\tif (retryFailed && operation.cancelFailed) {\n\t\toperation.cancelFailed = false;\n\t\toperation.cancelPromise = undefined;\n\t}\n\tif (operation.cancelPromise) return operation.cancelPromise;\n\n\tconst cancellation = (async () => {\n\t\tconst request = createPiServerRequest();\n\t\tconst response = await request.postJson(\n\t\t\t`/api/session/${encodeURIComponent(operation.sessionId)}/runs/${encodeURIComponent(operation.runId)}/abort`,\n\t\t\t{ sessionId: operation.sessionId, runId: operation.runId },\n\t\t);\n\t\tconst result = await readPiServerJson<PiServerAbortResponse>(response, \"Session run cancellation failed\");\n\t\tif (result.sessionId !== operation.sessionId || result.runId !== operation.runId) {\n\t\t\tthrow new Error(\"Session run cancellation failed (response did not echo the cancelled run)\");\n\t\t}\n\t\tif (result.status !== \"aborted\" && result.status !== \"completed\" && result.status !== \"failed\") {\n\t\t\tthrow new Error(\"Session run cancellation failed (response was not terminal)\");\n\t\t}\n\t\tremovePiServerOperation(operation);\n\t})();\n\n\toperation.cancelPromise = cancellation;\n\ttry {\n\t\tawait cancellation;\n\t} catch (error) {\n\t\toperation.cancelFailed = true;\n\t\tthrow error;\n\t}\n}\n\n/** Cancel all provider operations owned by a coding-agent session and wait for terminal acknowledgements. */\nexport async function cancelPiServerOperations(ownerSessionId: string): Promise<void> {\n\tconst operations = [...(activePiServerOperations.get(ownerSessionId)?.values() ?? [])];\n\tconst results = await Promise.allSettled(operations.map((operation) => cancelPiServerOperation(operation, true)));\n\tconst failure = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\tif (failure) throw failure.reason;\n}\n\ninterface SessionInitResponse {\n\tsessionId: string;\n\tstaticContextHash: string;\n\ttreeHash?: string;\n\tmessageCount: number;\n\tentryCount?: number;\n\tleafId?: string | null;\n\trevision?: number;\n\tfromCache?: boolean;\n}\n\nexport interface PiServerTreeSnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\treplace?: boolean;\n}\n\nexport interface PiServerCompactionResult {\n\tcompaction: Omit<LegacyCompactResult, \"retainedTail\">;\n\tcompactionEntry: SessionTreeEntry;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerHistorySnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerStreamOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerErrorResponse {\n\terror: string;\n\tcode?: string;\n\tdetails?: Record<string, unknown>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tcode?: string;\n}\n\nclass PiServerResponseError extends Error {\n\tpublic readonly code?: string;\n\tpublic readonly details?: Record<string, unknown>;\n\n\tconstructor(message: string, code?: string, details?: Record<string, unknown>) {\n\t\tsuper(message);\n\t\tthis.name = \"PiServerResponseError\";\n\t\tthis.code = code;\n\t\tthis.details = details;\n\t}\n}\n\ninterface PiServerHistoryResponse extends Partial<PiServerHistorySnapshot> {\n\tsessionId: string;\n\ttreeHash?: string;\n\tentryCount?: number;\n\tleafId?: string | null;\n\ttreePatch?: PiServerTreePatch;\n}\n\ninterface PiServerTreePatch {\n\tentriesFrom: number;\n\tbaseRevision?: number;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\trevision: number;\n}\n\ninterface PiServerCompactionResponse extends Partial<PiServerCompactionResult> {\n\ttreePatch?: PiServerTreePatch & { baseTreeHash?: string };\n}\n\ninterface ServerSentEvent {\n\tevent: string;\n\tdata: string;\n}\n\nclass ServerSentEventParser {\n\tprivate buffer = \"\";\n\tprivate event = \"message\";\n\tprivate dataLines: string[] = [];\n\n\tfeed(text: string): ServerSentEvent[] {\n\t\tthis.buffer += text;\n\t\tconst lines = this.buffer.split(\"\\n\");\n\t\tthis.buffer = lines.pop() ?? \"\";\n\t\treturn lines.flatMap((line) => this.consumeLine(line));\n\t}\n\n\tfinish(): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tif (this.buffer.length > 0) {\n\t\t\tevents.push(...this.consumeLine(this.buffer));\n\t\t\tthis.buffer = \"\";\n\t\t}\n\t\tconst final = this.flush();\n\t\tif (final) events.push(final);\n\t\treturn events;\n\t}\n\n\tprivate consumeLine(rawLine: string): ServerSentEvent[] {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tconst event = this.flush();\n\t\t\treturn event ? [event] : [];\n\t\t}\n\t\tif (line.startsWith(\":\")) return [];\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tthis.event = getServerSentEventFieldValue(line, \"event\");\n\t\t\treturn [];\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tthis.dataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t\treturn [];\n\t}\n\n\tprivate flush(): ServerSentEvent | undefined {\n\t\tif (this.dataLines.length === 0) return undefined;\n\t\tconst event = { event: this.event, data: this.dataLines.join(\"\\n\") };\n\t\tthis.event = \"message\";\n\t\tthis.dataLines = [];\n\t\treturn event;\n\t}\n}\n\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\" | \"aborted\";\n\tmessage?: AssistantMessage;\n\tcompactResult?: PiServerCompactionResponse;\n\terrorMessage?: string;\n}\n\ninterface PiServerAbortResponse {\n\tsessionId: string;\n\trunId: string;\n\tstatus: \"aborted\" | \"completed\" | \"failed\";\n}\n\ninterface PiServerSyncOptions {\n\tsignal?: AbortSignal;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ntype PiServerFailurePhase = \"session_init\" | \"tree_sync\" | \"provider_stream\" | \"history_reconcile\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction getResponseStatus(response: Response): string {\n\tconst status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);\n\treturn response.status >= 500 ? `${status} (server error)` : status;\n}\n\nfunction getResponseContentType(response: Response): string {\n\treturn response.headers.get(\"content-type\") ?? \"unknown\";\n}\n\nfunction getBodyExcerpt(text: string): string {\n\tconst trimmed = text.trim();\n\tif (!trimmed) return \"<empty>\";\n\tconst excerpt = trimmed.slice(0, RESPONSE_BODY_EXCERPT_CHARS);\n\treturn excerpt.length < trimmed.length ? `${excerpt}...` : excerpt;\n}\n\nfunction getJsonErrorResponse(text: string): PiServerErrorResponse | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed) || typeof parsed.error !== \"string\" || parsed.error.length === 0) return undefined;\n\t\tconst code = parsed.code;\n\t\treturn {\n\t\t\terror: parsed.error,\n\t\t\tcode: typeof code === \"string\" ? code : undefined,\n\t\t\tdetails: isObject(parsed.details) ? parsed.details : undefined,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction getJsonErrorText(text: string): string | undefined {\n\treturn getJsonErrorResponse(text)?.error;\n}\n\nfunction formatResponseDetails(response: Response, bodyText: string): string {\n\tconst body = getJsonErrorText(bodyText) ?? getBodyExcerpt(bodyText);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${body}`;\n}\n\nasync function readPiServerFailure(response: Response): Promise<PiServerResponseFailure> {\n\tconst bodyText = await response.text();\n\tconst errorResponse = getJsonErrorResponse(bodyText);\n\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tcode: errorResponse?.code,\n\t};\n}\n\nasync function readPiServerJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tif (!response.ok) {\n\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\tif (errorResponse) {\n\t\t\tthrow new PiServerResponseError(\n\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\terrorResponse.code,\n\t\t\t\terrorResponse.details,\n\t\t\t);\n\t\t}\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t}\n\ttry {\n\t\treturn JSON.parse(bodyText) as T;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t}\n}\n\nfunction getServerSentEventFieldValue(line: string, field: string): string {\n\tconst prefix = `${field}:`;\n\tconst value = line.slice(prefix.length);\n\treturn value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction parseServerSentEvents(bodyText: string): ServerSentEvent[] {\n\tconst parser = new ServerSentEventParser();\n\treturn [...parser.feed(bodyText), ...parser.finish()];\n}\n\nfunction parseServerSentEventData(event: ServerSentEvent, errorPrefix: string): unknown {\n\ttry {\n\t\treturn JSON.parse(event.data) as unknown;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (invalid event-stream JSON data: ${getBodyExcerpt(event.data)})`);\n\t}\n}\n\nfunction formatServerSentEventError(response: Response, payload: unknown): string {\n\tconst message = isObject(payload) && typeof payload.error === \"string\" ? payload.error : JSON.stringify(payload);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${getBodyExcerpt(message)}`;\n}\n\nasync function readPiServerEventStreamJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tfor (const event of parseServerSentEvents(bodyText)) {\n\t\tif (event.event === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`${errorPrefix} (${formatServerSentEventError(response, parseServerSentEventData(event, errorPrefix))})`,\n\t\t\t);\n\t\t}\n\t\tif (event.event === \"result\") {\n\t\t\treturn parseServerSentEventData(event, errorPrefix) as T;\n\t\t}\n\t}\n\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected result event)`);\n}\n\nasync function readPiServerCompactResponse<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst contentType = getResponseContentType(response).toLowerCase().split(\";\")[0]?.trim();\n\tif (contentType === \"text/event-stream\") {\n\t\treturn readPiServerEventStreamJson<T>(response, errorPrefix);\n\t}\n\treturn readPiServerJson<T>(response, errorPrefix);\n}\n\nfunction isAbortError(error: unknown, signal: AbortSignal | undefined): boolean {\n\treturn signal?.aborted === true || (error instanceof Error && error.name === \"AbortError\");\n}\n\nfunction isTransientPiServerFetchError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /fetch failed|network|socket hang up|terminated|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|CONNECT timeout/i.test(\n\t\tmessage,\n\t);\n}\n\nfunction isTransientPiServerError(error: unknown): boolean {\n\tif (isTransientPiServerFetchError(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t/\\b(?:500|502|503|504|524|530)\\b/.test(message) ||\n\t\t/CONNECT timeout|Bad Gateway|upstream|A timeout occurred/i.test(message)\n\t);\n}\n\nfunction isRetryablePiServerFailure(phase: PiServerFailurePhase, error: unknown): boolean {\n\tif (phase === \"provider_stream\") return true;\n\tif (phase === \"history_reconcile\") return false;\n\treturn isTransientPiServerError(error);\n}\n\nasync function waitForPiServerRetry(attempt: number, signal: AbortSignal | undefined): Promise<void> {\n\tawait sleep(TRANSIENT_PI_SERVER_RETRY_DELAYS_MS[attempt], undefined, { signal });\n}\n\nasync function postPiServerJsonWithTransientRetry<T>(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<T> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await request.postJson(endpoint, body);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!isAbortError(error, request.options.signal) &&\n\t\t\t\tisTransientPiServerFetchError(error)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst bodyText = await response.text();\n\t\tif (!response.ok) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!request.options.signal?.aborted &&\n\t\t\t\tTRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\t\tif (errorResponse) {\n\t\t\t\tthrow new PiServerResponseError(\n\t\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\t\terrorResponse.code,\n\t\t\t\t\terrorResponse.details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(bodyText) as T;\n\t\t} catch {\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t\t}\n\t}\n}\n\nasync function ensurePiServerEventStream(response: Response): Promise<void> {\n\tconst contentType = getResponseContentType(response);\n\tif (contentType.toLowerCase().split(\";\")[0]?.trim() === \"text/event-stream\") {\n\t\treturn;\n\t}\n\tconst bodyText = await response.text();\n\tthrow new Error(`pi-server error: ${formatResponseDetails(response, bodyText)}; expected text/event-stream`);\n}\n\nasync function ensureSessionInit(\n\tsessionId: string,\n\tcontext: Context,\n\trequest: ChunkRequest,\n): Promise<SessionInitResponse> {\n\tconst currentHash = hashStaticContext(context);\n\tconst previousHash = sessionStaticContextHashes.get(sessionId);\n\n\tif (previousHash === currentHash) {\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tstaticContextHash: previousHash,\n\t\t\tmessageCount: 0,\n\t\t\tfromCache: true,\n\t\t};\n\t}\n\n\tconst staticContext = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n\n\tconst endpoint = previousHash === undefined ? \"/api/session/init\" : \"/api/session/update\";\n\n\tconst result = await postPiServerJsonWithTransientRetry<SessionInitResponse>(\n\t\trequest,\n\t\tendpoint,\n\t\t{ sessionId, staticContext },\n\t\t\"Session init failed\",\n\t);\n\tsessionStaticContextHashes.set(sessionId, currentHash);\n\tif (result.treeHash !== undefined) {\n\t\tsessionTreeHashes.set(sessionId, result.treeHash);\n\t\tsessionTreeLeafIds.set(sessionId, result.leafId ?? null);\n\t\tif (result.entryCount !== undefined) {\n\t\t\tsessionTreeEntryCounts.set(sessionId, result.entryCount);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getStaticContext(context: Context) {\n\treturn {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n}\n\nfunction markTreeSynced(sessionId: string, tree: PiServerTreeSnapshot): void {\n\tconst prefixHashes = buildPiServerTreePrefixHashes(tree.entries);\n\tsessionTreeHashes.set(sessionId, prefixHashes[prefixHashes.length - 1]);\n\tsessionTreeEntryCounts.set(sessionId, tree.entries.length);\n\tsessionTreeLeafIds.set(sessionId, tree.leafId);\n\tif (tree.replace) {\n\t\tsessionHasTemporaryTree.add(sessionId);\n\t} else {\n\t\tsessionHasTemporaryTree.delete(sessionId);\n\t}\n}\n\nasync function postTreeJson(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<void> {\n\tawait postPiServerJsonWithTransientRetry<unknown>(request, endpoint, body, errorPrefix);\n}\n\nasync function fetchPiServerHistory(\n\tsessionId: string,\n\trequest: ChunkRequest,\n\tlocalTree?: PiServerTreeSnapshot,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst prefixHashes = localTree ? buildPiServerTreePrefixHashes(localTree.entries) : undefined;\n\tconst historyUrl =\n\t\tlocalTree && prefixHashes\n\t\t\t? `/api/session/${encodeURIComponent(sessionId)}/history?entriesFrom=${localTree.entries.length}&baseTreeHash=${encodeURIComponent(prefixHashes[prefixHashes.length - 1])}`\n\t\t\t: `/api/session/${encodeURIComponent(sessionId)}/history`;\n\tconst response = await request.getJson(historyUrl);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\tconst history = await readPiServerJson<PiServerHistoryResponse>(response, \"Session history reconciliation failed\");\n\tif (history.treePatch && localTree) {\n\t\treturn {\n\t\t\tentries: [...localTree.entries.slice(0, history.treePatch.entriesFrom), ...history.treePatch.entries],\n\t\t\tleafId: history.treePatch.leafId,\n\t\t\tmessages: history.messages ?? [],\n\t\t};\n\t}\n\tif (!history.entries || history.leafId === undefined || !history.messages) {\n\t\tthrow new Error(\"Session history reconciliation failed (response did not include the session tree)\");\n\t}\n\treturn {\n\t\tentries: history.entries,\n\t\tleafId: history.leafId,\n\t\tmessages: history.messages,\n\t};\n}\n\nasync function applyPiServerHistory(\n\tsessionId: string,\n\tsnapshot: PiServerHistorySnapshot,\n\tonHistoryReconciled: ((snapshot: PiServerHistorySnapshot) => void | Promise<void>) | undefined,\n): Promise<void> {\n\tmarkTreeSynced(sessionId, snapshot);\n\tawait onHistoryReconciled?.(snapshot);\n}\n\nasync function fetchPiServerRun(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n): Promise<PiServerRunResponse | undefined> {\n\tconst response = await request.getJson(\n\t\t`/api/session/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`,\n\t);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\treturn readPiServerJson<PiServerRunResponse>(response, \"Session run recovery failed\");\n}\n\nasync function waitForPiServerRunCompletion(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n\toptions: PiServerStreamOptions | undefined,\n): Promise<PiServerRunResponse | undefined> {\n\tconst deadline = Date.now() + DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS;\n\tfor (;;) {\n\t\tconst run = await fetchPiServerRun(sessionId, runId, request);\n\t\tif (!run || run.status !== \"running\") return run;\n\t\tif (Date.now() >= deadline) throw new PiServerRunRecoveryTimeoutError();\n\t\tawait sleep(PI_SERVER_RUN_RECOVERY_POLL_MS, undefined, { signal: options?.signal });\n\t}\n}\n\nfunction getKnownServerPrefixIds(sessionId: string, entries: SessionTreeEntry[]): Set<string> | undefined {\n\tconst entryCount = sessionTreeEntryCounts.get(sessionId);\n\tconst treeHash = sessionTreeHashes.get(sessionId);\n\tif (entryCount === undefined || treeHash === undefined || entryCount > entries.length) {\n\t\treturn undefined;\n\t}\n\tconst prefixHashes = buildPiServerTreePrefixHashes(entries);\n\tif (prefixHashes[entryCount] !== treeHash) {\n\t\treturn undefined;\n\t}\n\treturn new Set(entries.slice(0, entryCount).map((entry) => entry.id));\n}\n\nfunction isRecoverableTreeDivergenceCode(code: string | undefined): boolean {\n\treturn code === \"PARENT_ENTRY_NOT_FOUND\" || code === \"LEAF_ID_NOT_FOUND\" || code === \"ENTRY_ALREADY_EXISTS\";\n}\n\nfunction isRecoverableMissingServerStateCode(code: string | undefined): boolean {\n\treturn code === \"SESSION_NOT_FOUND\" || code === \"SESSION_NO_STATIC_CONTEXT\" || isRecoverableTreeDivergenceCode(code);\n}\n\nfunction isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tif (error instanceof PiServerResponseError) {\n\t\treturn isRecoverableTreeDivergenceCode(error.code);\n\t}\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\treturn isRecoverableTreeDivergenceCode((error as { code?: string }).code);\n\t}\n\treturn false;\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorCode?: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn isRecoverableMissingServerStateCode(errorCode);\n}\n\nasync function syncFullPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n): Promise<void> {\n\tawait postTreeJson(\n\t\trequest,\n\t\t\"/api/session/tree/sync\",\n\t\t{\n\t\t\tsessionId,\n\t\t\tentries: tree.entries,\n\t\t\tleafId: tree.leafId,\n\t\t\tstaticContext: getStaticContext(context),\n\t\t},\n\t\t\"Session tree sync failed\",\n\t);\n\tmarkTreeSynced(sessionId, tree);\n}\n\nfunction shouldUseServerHistory(sessionId: string, tree: PiServerTreeSnapshot): boolean {\n\treturn !tree.replace && !sessionHasTemporaryTree.has(sessionId) && (sessionTreeEntryCounts.get(sessionId) ?? 0) > 0;\n}\n\nasync function recoverPiServerTreeDivergence(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tif (shouldUseServerHistory(sessionId, tree)) {\n\t\tconst snapshot = await fetchPiServerHistory(sessionId, request, tree);\n\t\tif (snapshot && snapshot.entries.length > 0) {\n\t\t\tawait applyPiServerHistory(sessionId, snapshot, onHistoryReconciled);\n\t\t\treturn snapshot;\n\t\t}\n\t}\n\n\tawait syncFullPiServerTree(sessionId, context, tree, request);\n}\n\nexport async function syncPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\toptions?: PiServerSyncOptions,\n): Promise<void> {\n\tconst request = createPiServerRequest(options?.signal);\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\tsessionId,\n\t\tcontext,\n\t\ttree,\n\t\trequest,\n\t\toptions?.onHistoryReconciled,\n\t);\n\tif (reconciled) {\n\t\tthrow new Error(\"pi-server history differed from local history; local session was reconciled to server history\");\n\t}\n}\n\nasync function syncPiServerTreeWithRequest(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst syncTree = tree;\n\tconst currentHash = hashEntries(syncTree.entries);\n\tconst previousHash = sessionTreeHashes.get(sessionId);\n\tconst previousLeafId = sessionTreeLeafIds.get(sessionId);\n\n\tif (!tree.replace && previousHash === currentHash) {\n\t\tif (previousLeafId !== syncTree.leafId) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/switch\",\n\t\t\t\t\t{ sessionId, leafId: syncTree.leafId },\n\t\t\t\t\t\"Session tree switch failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tsessionTreeLeafIds.set(sessionId, syncTree.leafId);\n\t\t}\n\t\tmarkTreeSynced(sessionId, syncTree);\n\t\treturn;\n\t}\n\n\tconst syncedIds =\n\t\t!tree.replace && !sessionHasTemporaryTree.has(sessionId)\n\t\t\t? getKnownServerPrefixIds(sessionId, syncTree.entries)\n\t\t\t: undefined;\n\tif (syncedIds) {\n\t\tconst deltaEntries = syncTree.entries.filter((entry) => !syncedIds.has(entry.id));\n\t\tif (deltaEntries.length > 0) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/append\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tentries: deltaEntries,\n\t\t\t\t\t\tleafId: syncTree.leafId,\n\t\t\t\t\t\tstaticContext: getStaticContext(context),\n\t\t\t\t\t},\n\t\t\t\t\t\"Session tree append failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tmarkTreeSynced(sessionId, syncTree);\n\t\t\treturn;\n\t\t}\n\t}\n\n\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n}\n\nfunction serializeOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\treasoning: options?.reasoning,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tapiKey: options?.apiKey,\n\t\theaders: options?.headers,\n\t\tmetadata: options?.metadata,\n\t\ttransport: options?.transport,\n\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t};\n}\n\nexport interface PiServerCompactOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tcustomInstructions?: string;\n\tsettings?: unknown;\n\tpreparation?: CompactionPreparationOptions;\n\tsessionTree?: PiServerTreeSnapshot;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\nexport async function compactPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerCompactOptions,\n): Promise<PiServerCompactionResult> {\n\tconst sessionId = options?.sessionId ?? \"default\";\n\tconst runId = randomUUID();\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst request = createPiServerRequest(options?.signal);\n\n\ttry {\n\t\tawait ensureSessionInit(sessionId, context, request);\n\t\tlet tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\t\tlet preparation = options?.preparation;\n\t\tconst syncTree = async () => {\n\t\t\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\t\t\tsessionId,\n\t\t\t\tcontext,\n\t\t\t\ttree,\n\t\t\t\trequest,\n\t\t\t\toptions?.onHistoryReconciled,\n\t\t\t);\n\t\t\tif (reconciled) {\n\t\t\t\ttree = reconciled;\n\t\t\t\t// A forced cut point belongs to the old branch. Recompute it on the authoritative tree.\n\t\t\t\tpreparation = undefined;\n\t\t\t}\n\t\t};\n\t\tawait syncTree();\n\n\t\tconst makeBody = () => ({\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\tmodel,\n\t\t\toptions: serializeOptions(options),\n\t\t\tsettings: options?.settings,\n\t\t\tpreparation,\n\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\t\tstreamResponse: true,\n\t\t});\n\t\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\t\tif (!response.ok) {\n\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\tawait syncTree();\n\t\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t} else {\n\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t\t}\n\t\t}\n\t\tlet result: PiServerCompactionResponse;\n\t\ttry {\n\t\t\tresult = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\t\t} catch (error) {\n\t\t\tif (options?.signal?.aborted || !getResponseContentType(response).startsWith(\"text/event-stream\")) throw error;\n\t\t\tconst run = await waitForPiServerRunCompletion(sessionId, runId, request, options);\n\t\t\tif (run?.status !== \"completed\" || !run.compactResult) {\n\t\t\t\tif (run?.errorMessage) throw new Error(`Server compaction failed: ${run.errorMessage}`);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tresult = run.compactResult;\n\t\t}\n\t\tif (!result.compaction) {\n\t\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t\t}\n\t\tconst resultEntries =\n\t\t\tresult.entries ??\n\t\t\t(result.treePatch\n\t\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t\t: undefined);\n\t\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\t\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t\t}\n\t\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\t\treturn {\n\t\t\tcompaction: result.compaction,\n\t\t\tcompactionEntry: result.compactionEntry,\n\t\t\tentries: resultEntries,\n\t\t\tleafId: resultLeafId,\n\t\t\tmessages: result.messages ?? [],\n\t\t};\n\t} finally {\n\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t}\n}\n\nexport async function streamPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerStreamOptions,\n): Promise<PiServerEventStream> {\n\tconst sessionId = options?.sessionId ?? randomUUID();\n\tconst runId = randomUUID();\n\tconst isEphemeralSession = options?.sessionId === undefined;\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst stream = new PiServerEventStream();\n\n\tconst partial: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tstopReason: \"stop\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\ttimestamp: Date.now(),\n\t};\n\n\t(async () => {\n\t\tlet phase: PiServerFailurePhase = \"session_init\";\n\t\tlet streamOpened = false;\n\t\ttry {\n\t\t\tconst request = createPiServerRequest(options?.signal);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\n\t\t\tconst makeBody = () => ({\n\t\t\t\tsessionId,\n\t\t\t\trunId,\n\t\t\t\tmodel,\n\t\t\t\toptions: serializeOptions(options),\n\t\t\t\tcontextOverlay: options?.contextOverlay ?? [\n\t\t\t\t\t...(context.messages as Message[]),\n\t\t\t\t\t...(options?.ephemeralMessages ?? []),\n\t\t\t\t],\n\t\t\t});\n\t\t\tphase = \"provider_stream\";\n\t\t\tlet response = await request.postJson(\"/api/stream\", makeBody());\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\t\tresponse = await request.postJson(\"/api/stream\", makeBody());\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`pi-server error: ${failure.details}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ensurePiServerEventStream(response);\n\t\t\tstreamOpened = true;\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst parser = new ServerSentEventParser();\n\t\t\tlet terminalReceived = false;\n\n\t\t\tconst consumeEvents = (events: ServerSentEvent[]): void => {\n\t\t\t\tfor (const serverEvent of events) {\n\t\t\t\t\tconst proxyEvent = parseServerSentEventData(\n\t\t\t\t\t\tserverEvent,\n\t\t\t\t\t\t\"pi-server stream\",\n\t\t\t\t\t) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (!event) continue;\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalReceived = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tconsumeEvents(parser.feed(decoder.decode(value, { stream: true })));\n\t\t\t}\n\t\t\tconsumeEvents(parser.feed(decoder.decode()));\n\t\t\tconsumeEvents(parser.finish());\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\t\t\tif (!terminalReceived) {\n\t\t\t\tthrow new Error(\"pi-server stream ended before a terminal response event\");\n\t\t\t}\n\n\t\t\tif (isEphemeralSession) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tlet errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t// Same-run recovery only applies to an interrupted event-stream. HTTP/proxy\n\t\t\t// failures before the stream starts (502/504/fetch failed) never opened a run\n\t\t\t// we can poll; attempting recovery against a down proxy reclassifies the error\n\t\t\t// as history_reconcile and blocks session auto-retry.\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\" && streamOpened) {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await waitForPiServerRunCompletion(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tcreatePiServerRequest(options?.signal),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tif (recoveredRun?.status === \"completed\" && recoveredRun.message) {\n\t\t\t\t\t\tswitch (recoveredRun.message.stopReason) {\n\t\t\t\t\t\t\tcase \"stop\":\n\t\t\t\t\t\t\tcase \"length\":\n\t\t\t\t\t\t\tcase \"toolUse\":\n\t\t\t\t\t\t\tcase \"deferred\":\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\treason: recoveredRun.message.stopReason,\n\t\t\t\t\t\t\t\t\tmessage: recoveredRun.message,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"aborted\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"failed\" && recoveredRun.errorMessage) {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"aborted\") {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage ?? \"pi-server run aborted\";\n\t\t\t\t\t}\n\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\tphase = \"history_reconcile\";\n\t\t\t\t\terrorMessage = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options?.signal?.aborted && operation && !operation.cancelConfirmed) {\n\t\t\t\ttry {\n\t\t\t\t\tawait cancelPiServerOperation(operation);\n\t\t\t\t} catch (cancelError) {\n\t\t\t\t\terrorMessage = `${errorMessage}; cancellation failed: ${\n\t\t\t\t\t\tcancelError instanceof Error ? cancelError.message : String(cancelError)\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tpartial.diagnostics = [\n\t\t\t\t...(partial.diagnostics ?? []),\n\t\t\t\t{\n\t\t\t\t\ttype: \"pi_server_failure\",\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\terror: { name: error instanceof Error ? error.name : \"Error\", message: errorMessage },\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tphase,\n\t\t\t\t\t\tsource: \"pi-server\",\n\t\t\t\t\t\tretryable: isRetryablePiServerFailure(phase, error),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t\t\t} catch {\n\t\t\t\t// The owning session's cancellation helper reports the failure and keeps\n\t\t\t\t// this operation registered for a retry.\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn { type: \"text_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"text_end\", contentIndex: proxyEvent.contentIndex, content: content.text, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn { type: \"thinking_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"thinking_end\", contentIndex: proxyEvent.contentIndex, content: content.thinking, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} as any;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content };\n\t\t\t\treturn { type: \"toolcall_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn { type: \"toolcall_end\", contentIndex: proxyEvent.contentIndex, toolCall: content, partial };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nexport { getServerUrl, getAuthToken };\n"]}
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;AAED,SAA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YACjC,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;YACvC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;QACtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,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 sessionTreeHashes = new Map<string, string>();\nconst sessionTreeEntryCounts = new Map<string, number>();\nconst sessionTreeLeafIds = new Map<string, string | null>();\nconst sessionHasTemporaryTree = new Set<string>();\ninterface ActivePiServerOperation {\n\townerSessionId: string;\n\tsessionId: string;\n\trunId: string;\n\tsignal?: AbortSignal;\n\tcancelListener?: () => void;\n\tcancelPromise?: Promise<void>;\n\tcancelFailed?: boolean;\n\tcancelConfirmed?: boolean;\n}\n\nconst activePiServerOperations = new Map<string, Map<string, ActivePiServerOperation>>();\nconst RESPONSE_BODY_EXCERPT_CHARS = 500;\nconst TRANSIENT_PI_SERVER_RETRY_DELAYS_MS = [250, 750, 1500];\nconst TRANSIENT_PI_SERVER_STATUS_CODES = new Set([500, 502, 503, 504, 524, 530]);\nconst PI_SERVER_RUN_RECOVERY_POLL_MS = 250;\nconst DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS = 10 * 60 * 1000;\n\nclass PiServerRunRecoveryTimeoutError extends Error {\n\tconstructor() {\n\t\tsuper(\"pi-server run recovery timed out; the server may still be processing the request\");\n\t\tthis.name = \"PiServerRunRecoveryTimeoutError\";\n\t}\n}\n\nexport function hashStaticContext(ctx: Context): string {\n\treturn hashPiServerStaticContext(ctx);\n}\n\nfunction hashEntries(entries: SessionTreeEntry[]): string {\n\treturn hashPiServerSessionEntries(entries);\n}\n\nfunction getLinearTreeFromMessages(messages: Message[]): { entries: SessionTreeEntry[]; leafId: string | null } {\n\tlet parentId: string | null = null;\n\tconst entries = messages.map((message, index): SessionTreeEntry => {\n\t\tconst id = `message-${index}`;\n\t\tconst entry: SessionTreeEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid,\n\t\t\tparentId,\n\t\t\ttimestamp: new Date(message.timestamp).toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tparentId = id;\n\t\treturn entry;\n\t});\n\treturn { entries, leafId: parentId };\n}\n\nexport function resetSessionTracking(sessionId: string): void {\n\tsessionStaticContextHashes.delete(sessionId);\n\tsessionTreeHashes.delete(sessionId);\n\tsessionTreeEntryCounts.delete(sessionId);\n\tsessionTreeLeafIds.delete(sessionId);\n\tsessionHasTemporaryTree.delete(sessionId);\n}\n\nexport function resetAllSessionTracking(): void {\n\tsessionStaticContextHashes.clear();\n\tsessionTreeHashes.clear();\n\tsessionTreeEntryCounts.clear();\n\tsessionTreeLeafIds.clear();\n\tsessionHasTemporaryTree.clear();\n\tactivePiServerOperations.clear();\n}\n\nfunction registerPiServerOperation(\n\townerSessionId: string | undefined,\n\tsessionId: string,\n\trunId: string,\n\tsignal?: AbortSignal,\n): ActivePiServerOperation | undefined {\n\tif (!ownerSessionId) return undefined;\n\tlet operations = activePiServerOperations.get(ownerSessionId);\n\tif (!operations) {\n\t\toperations = new Map();\n\t\tactivePiServerOperations.set(ownerSessionId, operations);\n\t}\n\tconst operation: ActivePiServerOperation = { ownerSessionId, sessionId, runId, signal };\n\toperations.set(runId, operation);\n\tif (signal) {\n\t\tconst onAbort = () => {\n\t\t\tvoid cancelPiServerOperation(operation).catch(() => {\n\t\t\t\t// The owner session retries cancellation and reports the failure.\n\t\t\t});\n\t\t};\n\t\toperation.cancelListener = onAbort;\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (signal.aborted) onAbort();\n\t}\n\treturn operation;\n}\n\nfunction removePiServerOperation(operation: ActivePiServerOperation): void {\n\tconst operations = activePiServerOperations.get(operation.ownerSessionId);\n\toperation.cancelConfirmed = true;\n\tif (operation.signal && operation.cancelListener) {\n\t\toperation.signal.removeEventListener(\"abort\", operation.cancelListener);\n\t}\n\toperation.cancelListener = undefined;\n\tif (!operations || operations.get(operation.runId) !== operation) return;\n\toperations.delete(operation.runId);\n\tif (operations.size === 0) activePiServerOperations.delete(operation.ownerSessionId);\n}\n\nasync function finishPiServerOperation(\n\toperation: ActivePiServerOperation | undefined,\n\taborted: boolean,\n): Promise<void> {\n\tif (!operation) return;\n\tif (aborted) {\n\t\tif (operation.cancelPromise) await operation.cancelPromise;\n\t} else {\n\t\tremovePiServerOperation(operation);\n\t}\n}\n\nasync function cancelPiServerOperation(operation: ActivePiServerOperation, retryFailed = false): Promise<void> {\n\tif (operation.cancelConfirmed) return;\n\tif (retryFailed && operation.cancelFailed) {\n\t\toperation.cancelFailed = false;\n\t\toperation.cancelPromise = undefined;\n\t}\n\tif (operation.cancelPromise) return operation.cancelPromise;\n\n\tconst cancellation = (async () => {\n\t\tconst request = createPiServerRequest();\n\t\tconst response = await request.postJson(\n\t\t\t`/api/session/${encodeURIComponent(operation.sessionId)}/runs/${encodeURIComponent(operation.runId)}/abort`,\n\t\t\t{ sessionId: operation.sessionId, runId: operation.runId },\n\t\t);\n\t\tconst result = await readPiServerJson<PiServerAbortResponse>(response, \"Session run cancellation failed\");\n\t\tif (result.sessionId !== operation.sessionId || result.runId !== operation.runId) {\n\t\t\tthrow new Error(\"Session run cancellation failed (response did not echo the cancelled run)\");\n\t\t}\n\t\tif (result.status !== \"aborted\" && result.status !== \"completed\" && result.status !== \"failed\") {\n\t\t\tthrow new Error(\"Session run cancellation failed (response was not terminal)\");\n\t\t}\n\t\tremovePiServerOperation(operation);\n\t})();\n\n\toperation.cancelPromise = cancellation;\n\ttry {\n\t\tawait cancellation;\n\t} catch (error) {\n\t\toperation.cancelFailed = true;\n\t\tthrow error;\n\t}\n}\n\n/** Cancel all provider operations owned by a coding-agent session and wait for terminal acknowledgements. */\nexport async function cancelPiServerOperations(ownerSessionId: string): Promise<void> {\n\tconst operations = [...(activePiServerOperations.get(ownerSessionId)?.values() ?? [])];\n\tconst results = await Promise.allSettled(operations.map((operation) => cancelPiServerOperation(operation, true)));\n\tconst failure = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\tif (failure) throw failure.reason;\n}\n\ninterface SessionInitResponse {\n\tsessionId: string;\n\tstaticContextHash: string;\n\ttreeHash?: string;\n\tmessageCount: number;\n\tentryCount?: number;\n\tleafId?: string | null;\n\trevision?: number;\n\tfromCache?: boolean;\n}\n\nexport interface PiServerTreeSnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\treplace?: boolean;\n}\n\nexport interface PiServerCompactionResult {\n\tcompaction: Omit<LegacyCompactResult, \"retainedTail\">;\n\tcompactionEntry: SessionTreeEntry;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerHistorySnapshot {\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\tmessages: Message[];\n}\n\nexport interface PiServerStreamOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tsessionTree?: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ninterface PiServerErrorResponse {\n\terror: string;\n\tcode?: string;\n\tdetails?: Record<string, unknown>;\n}\n\ninterface PiServerResponseFailure {\n\tdetails: string;\n\tcode?: string;\n}\n\nclass PiServerResponseError extends Error {\n\tpublic readonly code?: string;\n\tpublic readonly details?: Record<string, unknown>;\n\n\tconstructor(message: string, code?: string, details?: Record<string, unknown>) {\n\t\tsuper(message);\n\t\tthis.name = \"PiServerResponseError\";\n\t\tthis.code = code;\n\t\tthis.details = details;\n\t}\n}\n\ninterface PiServerHistoryResponse extends Partial<PiServerHistorySnapshot> {\n\tsessionId: string;\n\ttreeHash?: string;\n\tentryCount?: number;\n\tleafId?: string | null;\n\ttreePatch?: PiServerTreePatch;\n}\n\ninterface PiServerTreePatch {\n\tentriesFrom: number;\n\tbaseRevision?: number;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n\trevision: number;\n}\n\ninterface PiServerCompactionResponse extends Partial<PiServerCompactionResult> {\n\ttreePatch?: PiServerTreePatch & { baseTreeHash?: string };\n}\n\ninterface ServerSentEvent {\n\tevent: string;\n\tdata: string;\n}\n\nclass ServerSentEventParser {\n\tprivate buffer = \"\";\n\tprivate event = \"message\";\n\tprivate dataLines: string[] = [];\n\n\tfeed(text: string): ServerSentEvent[] {\n\t\tthis.buffer += text;\n\t\tconst lines = this.buffer.split(\"\\n\");\n\t\tthis.buffer = lines.pop() ?? \"\";\n\t\treturn lines.flatMap((line) => this.consumeLine(line));\n\t}\n\n\tfinish(): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tif (this.buffer.length > 0) {\n\t\t\tevents.push(...this.consumeLine(this.buffer));\n\t\t\tthis.buffer = \"\";\n\t\t}\n\t\tconst final = this.flush();\n\t\tif (final) events.push(final);\n\t\treturn events;\n\t}\n\n\tprivate consumeLine(rawLine: string): ServerSentEvent[] {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tconst event = this.flush();\n\t\t\treturn event ? [event] : [];\n\t\t}\n\t\tif (line.startsWith(\":\")) return [];\n\t\tif (line.startsWith(\"event:\")) {\n\t\t\tthis.event = getServerSentEventFieldValue(line, \"event\");\n\t\t\treturn [];\n\t\t}\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tthis.dataLines.push(getServerSentEventFieldValue(line, \"data\"));\n\t\t}\n\t\treturn [];\n\t}\n\n\tprivate flush(): ServerSentEvent | undefined {\n\t\tif (this.dataLines.length === 0) return undefined;\n\t\tconst event = { event: this.event, data: this.dataLines.join(\"\\n\") };\n\t\tthis.event = \"message\";\n\t\tthis.dataLines = [];\n\t\treturn event;\n\t}\n}\n\ninterface PiServerRunResponse {\n\trunId: string;\n\tstatus: \"running\" | \"completed\" | \"failed\" | \"aborted\";\n\tmessage?: AssistantMessage;\n\tcompactResult?: PiServerCompactionResponse;\n\terrorMessage?: string;\n}\n\ninterface PiServerAbortResponse {\n\tsessionId: string;\n\trunId: string;\n\tstatus: \"aborted\" | \"completed\" | \"failed\";\n}\n\ninterface PiServerSyncOptions {\n\tsignal?: AbortSignal;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\ntype PiServerFailurePhase = \"session_init\" | \"tree_sync\" | \"provider_stream\" | \"history_reconcile\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction getResponseStatus(response: Response): string {\n\tconst status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);\n\treturn response.status >= 500 ? `${status} (server error)` : status;\n}\n\nfunction getResponseContentType(response: Response): string {\n\treturn response.headers.get(\"content-type\") ?? \"unknown\";\n}\n\nfunction getBodyExcerpt(text: string): string {\n\tconst trimmed = text.trim();\n\tif (!trimmed) return \"<empty>\";\n\tconst excerpt = trimmed.slice(0, RESPONSE_BODY_EXCERPT_CHARS);\n\treturn excerpt.length < trimmed.length ? `${excerpt}...` : excerpt;\n}\n\nfunction getJsonErrorResponse(text: string): PiServerErrorResponse | undefined {\n\tif (!text) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (!isObject(parsed) || typeof parsed.error !== \"string\" || parsed.error.length === 0) return undefined;\n\t\tconst code = parsed.code;\n\t\treturn {\n\t\t\terror: parsed.error,\n\t\t\tcode: typeof code === \"string\" ? code : undefined,\n\t\t\tdetails: isObject(parsed.details) ? parsed.details : undefined,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction getJsonErrorText(text: string): string | undefined {\n\treturn getJsonErrorResponse(text)?.error;\n}\n\nfunction formatResponseDetails(response: Response, bodyText: string): string {\n\tconst body = getJsonErrorText(bodyText) ?? getBodyExcerpt(bodyText);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${body}`;\n}\n\nasync function readPiServerFailure(response: Response): Promise<PiServerResponseFailure> {\n\tconst bodyText = await response.text();\n\tconst errorResponse = getJsonErrorResponse(bodyText);\n\treturn {\n\t\tdetails: formatResponseDetails(response, bodyText),\n\t\tcode: errorResponse?.code,\n\t};\n}\n\nasync function readPiServerJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tif (!response.ok) {\n\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\tif (errorResponse) {\n\t\t\tthrow new PiServerResponseError(\n\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\terrorResponse.code,\n\t\t\t\terrorResponse.details,\n\t\t\t);\n\t\t}\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t}\n\ttry {\n\t\treturn JSON.parse(bodyText) as T;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t}\n}\n\nfunction getServerSentEventFieldValue(line: string, field: string): string {\n\tconst prefix = `${field}:`;\n\tconst value = line.slice(prefix.length);\n\treturn value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction parseServerSentEvents(bodyText: string): ServerSentEvent[] {\n\tconst parser = new ServerSentEventParser();\n\treturn [...parser.feed(bodyText), ...parser.finish()];\n}\n\nfunction parseServerSentEventData(event: ServerSentEvent, errorPrefix: string): unknown {\n\ttry {\n\t\treturn JSON.parse(event.data) as unknown;\n\t} catch {\n\t\tthrow new Error(`${errorPrefix} (invalid event-stream JSON data: ${getBodyExcerpt(event.data)})`);\n\t}\n}\n\nfunction formatServerSentEventError(response: Response, payload: unknown): string {\n\tconst message = isObject(payload) && typeof payload.error === \"string\" ? payload.error : JSON.stringify(payload);\n\treturn `${getResponseStatus(response)}; content-type: ${getResponseContentType(response)}; body excerpt: ${getBodyExcerpt(message)}`;\n}\n\nasync function readPiServerEventStreamJson<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst bodyText = await response.text();\n\tfor (const event of parseServerSentEvents(bodyText)) {\n\t\tif (event.event === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`${errorPrefix} (${formatServerSentEventError(response, parseServerSentEventData(event, errorPrefix))})`,\n\t\t\t);\n\t\t}\n\t\tif (event.event === \"result\") {\n\t\t\treturn parseServerSentEventData(event, errorPrefix) as T;\n\t\t}\n\t}\n\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected result event)`);\n}\n\nasync function readPiServerCompactResponse<T>(response: Response, errorPrefix: string): Promise<T> {\n\tconst contentType = getResponseContentType(response).toLowerCase().split(\";\")[0]?.trim();\n\tif (contentType === \"text/event-stream\") {\n\t\treturn readPiServerEventStreamJson<T>(response, errorPrefix);\n\t}\n\treturn readPiServerJson<T>(response, errorPrefix);\n}\n\nfunction isAbortError(error: unknown, signal: AbortSignal | undefined): boolean {\n\treturn signal?.aborted === true || (error instanceof Error && error.name === \"AbortError\");\n}\n\nfunction isTransientPiServerFetchError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /fetch failed|network|socket hang up|terminated|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|CONNECT timeout/i.test(\n\t\tmessage,\n\t);\n}\n\nfunction isTransientPiServerError(error: unknown): boolean {\n\tif (isTransientPiServerFetchError(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t/\\b(?:500|502|503|504|524|530)\\b/.test(message) ||\n\t\t/CONNECT timeout|Bad Gateway|upstream|A timeout occurred/i.test(message)\n\t);\n}\n\nfunction isRetryablePiServerFailure(phase: PiServerFailurePhase, error: unknown): boolean {\n\tif (phase === \"provider_stream\") return true;\n\tif (phase === \"history_reconcile\") return false;\n\treturn isTransientPiServerError(error);\n}\n\nasync function waitForPiServerRetry(attempt: number, signal: AbortSignal | undefined): Promise<void> {\n\tawait sleep(TRANSIENT_PI_SERVER_RETRY_DELAYS_MS[attempt], undefined, { signal });\n}\n\nasync function postPiServerJsonWithTransientRetry<T>(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<T> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await request.postJson(endpoint, body);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!isAbortError(error, request.options.signal) &&\n\t\t\t\tisTransientPiServerFetchError(error)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst bodyText = await response.text();\n\t\tif (!response.ok) {\n\t\t\tif (\n\t\t\t\tattempt < TRANSIENT_PI_SERVER_RETRY_DELAYS_MS.length &&\n\t\t\t\t!request.options.signal?.aborted &&\n\t\t\t\tTRANSIENT_PI_SERVER_STATUS_CODES.has(response.status)\n\t\t\t) {\n\t\t\t\tawait waitForPiServerRetry(attempt, request.options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst errorResponse = getJsonErrorResponse(bodyText);\n\t\t\tif (errorResponse) {\n\t\t\t\tthrow new PiServerResponseError(\n\t\t\t\t\t`${errorPrefix} (${formatResponseDetails(response, bodyText)})`,\n\t\t\t\t\terrorResponse.code,\n\t\t\t\t\terrorResponse.details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)})`);\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(bodyText) as T;\n\t\t} catch {\n\t\t\tthrow new Error(`${errorPrefix} (${formatResponseDetails(response, bodyText)}; expected JSON)`);\n\t\t}\n\t}\n}\n\nasync function ensurePiServerEventStream(response: Response): Promise<void> {\n\tconst contentType = getResponseContentType(response);\n\tif (contentType.toLowerCase().split(\";\")[0]?.trim() === \"text/event-stream\") {\n\t\treturn;\n\t}\n\tconst bodyText = await response.text();\n\tthrow new Error(`pi-server error: ${formatResponseDetails(response, bodyText)}; expected text/event-stream`);\n}\n\nasync function ensureSessionInit(\n\tsessionId: string,\n\tcontext: Context,\n\trequest: ChunkRequest,\n): Promise<SessionInitResponse> {\n\tconst currentHash = hashStaticContext(context);\n\tconst previousHash = sessionStaticContextHashes.get(sessionId);\n\n\tif (previousHash === currentHash) {\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tstaticContextHash: previousHash,\n\t\t\tmessageCount: 0,\n\t\t\tfromCache: true,\n\t\t};\n\t}\n\n\tconst staticContext = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n\n\tconst endpoint = previousHash === undefined ? \"/api/session/init\" : \"/api/session/update\";\n\n\tconst result = await postPiServerJsonWithTransientRetry<SessionInitResponse>(\n\t\trequest,\n\t\tendpoint,\n\t\t{ sessionId, staticContext },\n\t\t\"Session init failed\",\n\t);\n\tsessionStaticContextHashes.set(sessionId, currentHash);\n\tif (result.treeHash !== undefined) {\n\t\tsessionTreeHashes.set(sessionId, result.treeHash);\n\t\tsessionTreeLeafIds.set(sessionId, result.leafId ?? null);\n\t\tif (result.entryCount !== undefined) {\n\t\t\tsessionTreeEntryCounts.set(sessionId, result.entryCount);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getStaticContext(context: Context) {\n\treturn {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools,\n\t};\n}\n\nfunction markTreeSynced(sessionId: string, tree: PiServerTreeSnapshot): void {\n\tconst prefixHashes = buildPiServerTreePrefixHashes(tree.entries);\n\tsessionTreeHashes.set(sessionId, prefixHashes[prefixHashes.length - 1]);\n\tsessionTreeEntryCounts.set(sessionId, tree.entries.length);\n\tsessionTreeLeafIds.set(sessionId, tree.leafId);\n\tif (tree.replace) {\n\t\tsessionHasTemporaryTree.add(sessionId);\n\t} else {\n\t\tsessionHasTemporaryTree.delete(sessionId);\n\t}\n}\n\nasync function postTreeJson(\n\trequest: ChunkRequest,\n\tendpoint: string,\n\tbody: unknown,\n\terrorPrefix: string,\n): Promise<void> {\n\tawait postPiServerJsonWithTransientRetry<unknown>(request, endpoint, body, errorPrefix);\n}\n\nasync function fetchPiServerHistory(\n\tsessionId: string,\n\trequest: ChunkRequest,\n\tlocalTree?: PiServerTreeSnapshot,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst prefixHashes = localTree ? buildPiServerTreePrefixHashes(localTree.entries) : undefined;\n\tconst historyUrl =\n\t\tlocalTree && prefixHashes\n\t\t\t? `/api/session/${encodeURIComponent(sessionId)}/history?entriesFrom=${localTree.entries.length}&baseTreeHash=${encodeURIComponent(prefixHashes[prefixHashes.length - 1])}`\n\t\t\t: `/api/session/${encodeURIComponent(sessionId)}/history`;\n\tconst response = await request.getJson(historyUrl);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\tconst history = await readPiServerJson<PiServerHistoryResponse>(response, \"Session history reconciliation failed\");\n\tif (history.treePatch && localTree) {\n\t\treturn {\n\t\t\tentries: [...localTree.entries.slice(0, history.treePatch.entriesFrom), ...history.treePatch.entries],\n\t\t\tleafId: history.treePatch.leafId,\n\t\t\tmessages: history.messages ?? [],\n\t\t};\n\t}\n\tif (!history.entries || history.leafId === undefined || !history.messages) {\n\t\tthrow new Error(\"Session history reconciliation failed (response did not include the session tree)\");\n\t}\n\treturn {\n\t\tentries: history.entries,\n\t\tleafId: history.leafId,\n\t\tmessages: history.messages,\n\t};\n}\n\nasync function applyPiServerHistory(\n\tsessionId: string,\n\tsnapshot: PiServerHistorySnapshot,\n\tonHistoryReconciled: ((snapshot: PiServerHistorySnapshot) => void | Promise<void>) | undefined,\n): Promise<void> {\n\tmarkTreeSynced(sessionId, snapshot);\n\tawait onHistoryReconciled?.(snapshot);\n}\n\nasync function fetchPiServerRun(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n): Promise<PiServerRunResponse | undefined> {\n\tconst response = await request.getJson(\n\t\t`/api/session/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`,\n\t);\n\tif (response.status === 404) {\n\t\treturn undefined;\n\t}\n\treturn readPiServerJson<PiServerRunResponse>(response, \"Session run recovery failed\");\n}\n\nasync function waitForPiServerRunCompletion(\n\tsessionId: string,\n\trunId: string,\n\trequest: ChunkRequest,\n\toptions: PiServerStreamOptions | undefined,\n): Promise<PiServerRunResponse | undefined> {\n\tconst deadline = Date.now() + DEFAULT_PI_SERVER_RUN_RECOVERY_TIMEOUT_MS;\n\tfor (;;) {\n\t\tconst run = await fetchPiServerRun(sessionId, runId, request);\n\t\tif (!run || run.status !== \"running\") return run;\n\t\tif (Date.now() >= deadline) throw new PiServerRunRecoveryTimeoutError();\n\t\tawait sleep(PI_SERVER_RUN_RECOVERY_POLL_MS, undefined, { signal: options?.signal });\n\t}\n}\n\nfunction getKnownServerPrefixIds(sessionId: string, entries: SessionTreeEntry[]): Set<string> | undefined {\n\tconst entryCount = sessionTreeEntryCounts.get(sessionId);\n\tconst treeHash = sessionTreeHashes.get(sessionId);\n\tif (entryCount === undefined || treeHash === undefined || entryCount > entries.length) {\n\t\treturn undefined;\n\t}\n\tconst prefixHashes = buildPiServerTreePrefixHashes(entries);\n\tif (prefixHashes[entryCount] !== treeHash) {\n\t\treturn undefined;\n\t}\n\treturn new Set(entries.slice(0, entryCount).map((entry) => entry.id));\n}\n\nfunction isRecoverableTreeDivergenceCode(code: string | undefined): boolean {\n\treturn code === \"PARENT_ENTRY_NOT_FOUND\" || code === \"LEAF_ID_NOT_FOUND\" || code === \"ENTRY_ALREADY_EXISTS\";\n}\n\nfunction isRecoverableMissingServerStateCode(code: string | undefined): boolean {\n\treturn code === \"SESSION_NOT_FOUND\" || code === \"SESSION_NO_STATIC_CONTEXT\" || isRecoverableTreeDivergenceCode(code);\n}\n\nfunction isRecoverableTreeDivergenceError(error: unknown): boolean {\n\tif (error instanceof PiServerResponseError) {\n\t\treturn isRecoverableTreeDivergenceCode(error.code);\n\t}\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\treturn isRecoverableTreeDivergenceCode((error as { code?: string }).code);\n\t}\n\treturn false;\n}\n\nfunction isRecoverableMissingServerState(response: Response, errorCode?: string): boolean {\n\tif (response.status !== 400 && response.status !== 404) return false;\n\treturn isRecoverableMissingServerStateCode(errorCode);\n}\n\nasync function syncFullPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n): Promise<void> {\n\tawait postTreeJson(\n\t\trequest,\n\t\t\"/api/session/tree/sync\",\n\t\t{\n\t\t\tsessionId,\n\t\t\tentries: tree.entries,\n\t\t\tleafId: tree.leafId,\n\t\t\tstaticContext: getStaticContext(context),\n\t\t},\n\t\t\"Session tree sync failed\",\n\t);\n\tmarkTreeSynced(sessionId, tree);\n}\n\nfunction shouldUseServerHistory(sessionId: string, tree: PiServerTreeSnapshot): boolean {\n\treturn !tree.replace && !sessionHasTemporaryTree.has(sessionId) && (sessionTreeEntryCounts.get(sessionId) ?? 0) > 0;\n}\n\nasync function recoverPiServerTreeDivergence(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tif (shouldUseServerHistory(sessionId, tree)) {\n\t\tconst snapshot = await fetchPiServerHistory(sessionId, request, tree);\n\t\tif (snapshot && snapshot.entries.length > 0) {\n\t\t\tawait applyPiServerHistory(sessionId, snapshot, onHistoryReconciled);\n\t\t\treturn snapshot;\n\t\t}\n\t}\n\n\tawait syncFullPiServerTree(sessionId, context, tree, request);\n}\n\nexport async function syncPiServerTree(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\toptions?: PiServerSyncOptions,\n): Promise<void> {\n\tconst request = createPiServerRequest(options?.signal);\n\tawait ensureSessionInit(sessionId, context, request);\n\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\tsessionId,\n\t\tcontext,\n\t\ttree,\n\t\trequest,\n\t\toptions?.onHistoryReconciled,\n\t);\n\tif (reconciled) {\n\t\tthrow new Error(\"pi-server history differed from local history; local session was reconciled to server history\");\n\t}\n}\n\nasync function syncPiServerTreeWithRequest(\n\tsessionId: string,\n\tcontext: Context,\n\ttree: PiServerTreeSnapshot,\n\trequest: ChunkRequest,\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>,\n): Promise<PiServerHistorySnapshot | undefined> {\n\tconst syncTree = tree;\n\tconst currentHash = hashEntries(syncTree.entries);\n\tconst previousHash = sessionTreeHashes.get(sessionId);\n\tconst previousLeafId = sessionTreeLeafIds.get(sessionId);\n\n\tif (!tree.replace && previousHash === currentHash) {\n\t\tif (previousLeafId !== syncTree.leafId) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/switch\",\n\t\t\t\t\t{ sessionId, leafId: syncTree.leafId },\n\t\t\t\t\t\"Session tree switch failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tsessionTreeLeafIds.set(sessionId, syncTree.leafId);\n\t\t}\n\t\tmarkTreeSynced(sessionId, syncTree);\n\t\treturn;\n\t}\n\n\tconst syncedIds =\n\t\t!tree.replace && !sessionHasTemporaryTree.has(sessionId)\n\t\t\t? getKnownServerPrefixIds(sessionId, syncTree.entries)\n\t\t\t: undefined;\n\tif (syncedIds) {\n\t\tconst deltaEntries = syncTree.entries.filter((entry) => !syncedIds.has(entry.id));\n\t\tif (deltaEntries.length > 0) {\n\t\t\ttry {\n\t\t\t\tawait postTreeJson(\n\t\t\t\t\trequest,\n\t\t\t\t\t\"/api/session/tree/append\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tentries: deltaEntries,\n\t\t\t\t\t\tleafId: syncTree.leafId,\n\t\t\t\t\t\tstaticContext: getStaticContext(context),\n\t\t\t\t\t},\n\t\t\t\t\t\"Session tree append failed\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isRecoverableTreeDivergenceError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n\t\t\t}\n\t\t\tmarkTreeSynced(sessionId, syncTree);\n\t\t\treturn;\n\t\t}\n\t}\n\n\treturn recoverPiServerTreeDivergence(sessionId, context, syncTree, request, onHistoryReconciled);\n}\n\nfunction serializeOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\treasoning: options?.reasoning,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tapiKey: options?.apiKey,\n\t\theaders: options?.headers,\n\t\tmetadata: options?.metadata,\n\t\ttransport: options?.transport,\n\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t};\n}\n\nexport interface PiServerCompactOptions extends SimpleStreamOptions {\n\townerSessionId?: string;\n\tcustomInstructions?: string;\n\tsettings?: unknown;\n\tpreparation?: CompactionPreparationOptions;\n\t/** Fixed-size digest of the exact provider message overlay for this session. */\n\tcacheContextHash?: string;\n\t/** Fixed-size digest of the synchronized static prompt and tools. */\n\tcacheStaticContextHash?: string;\n\tcacheFallbackReason?: string;\n\tsessionTree?: PiServerTreeSnapshot;\n\tonHistoryReconciled?: (snapshot: PiServerHistorySnapshot) => void | Promise<void>;\n}\n\nexport async function compactPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerCompactOptions,\n): Promise<PiServerCompactionResult> {\n\tconst sessionId = options?.sessionId ?? \"default\";\n\tconst runId = randomUUID();\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst request = createPiServerRequest(options?.signal);\n\n\ttry {\n\t\tawait ensureSessionInit(sessionId, context, request);\n\t\tlet tree = options?.sessionTree ?? getLinearTreeFromMessages(context.messages as Message[]);\n\t\tlet preparation = options?.preparation;\n\t\tconst syncTree = async () => {\n\t\t\tconst reconciled = await syncPiServerTreeWithRequest(\n\t\t\t\tsessionId,\n\t\t\t\tcontext,\n\t\t\t\ttree,\n\t\t\t\trequest,\n\t\t\t\toptions?.onHistoryReconciled,\n\t\t\t);\n\t\t\tif (reconciled) {\n\t\t\t\ttree = reconciled;\n\t\t\t\t// A forced cut point belongs to the old branch. Recompute it on the authoritative tree.\n\t\t\t\tpreparation = undefined;\n\t\t\t}\n\t\t};\n\t\tawait syncTree();\n\n\t\tconst makeBody = () => ({\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\tmodel,\n\t\t\toptions: serializeOptions(options),\n\t\t\tsettings: options?.settings,\n\t\t\tpreparation,\n\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\tcacheContextHash: options?.cacheContextHash,\n\t\t\tcacheStaticContextHash: options?.cacheStaticContextHash,\n\t\t\tcacheFallbackReason: options?.cacheFallbackReason,\n\t\t\tbaseTreeHash: sessionTreeHashes.get(sessionId) ?? hashEntries(tree.entries),\n\t\t\tstreamResponse: true,\n\t\t});\n\t\tlet response = await request.postJson(\"/api/session/compact\", makeBody());\n\t\tif (!response.ok) {\n\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\tawait syncTree();\n\t\t\t\tresponse = await request.postJson(\"/api/session/compact\", makeBody());\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t} else {\n\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Server compaction failed (${failure.details})`);\n\t\t\t}\n\t\t}\n\t\tlet result: PiServerCompactionResponse;\n\t\ttry {\n\t\t\tresult = await readPiServerCompactResponse<PiServerCompactionResponse>(response, \"Server compaction failed\");\n\t\t} catch (error) {\n\t\t\tif (options?.signal?.aborted || !getResponseContentType(response).startsWith(\"text/event-stream\")) throw error;\n\t\t\tconst run = await waitForPiServerRunCompletion(sessionId, runId, request, options);\n\t\t\tif (run?.status !== \"completed\" || !run.compactResult) {\n\t\t\t\tif (run?.errorMessage) throw new Error(`Server compaction failed: ${run.errorMessage}`);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tresult = run.compactResult;\n\t\t}\n\t\tif (!result.compaction) {\n\t\t\tthrow new Error(\"Server compaction response did not include a compaction result\");\n\t\t}\n\t\tconst resultEntries =\n\t\t\tresult.entries ??\n\t\t\t(result.treePatch\n\t\t\t\t? [...tree.entries.slice(0, result.treePatch.entriesFrom), ...result.treePatch.entries]\n\t\t\t\t: undefined);\n\t\tconst resultLeafId = result.leafId ?? result.treePatch?.leafId;\n\t\tif (!result.compactionEntry || !resultEntries || resultLeafId === undefined) {\n\t\t\tthrow new Error(\"Server compaction response did not include the updated session tree\");\n\t\t}\n\t\tmarkTreeSynced(sessionId, { entries: resultEntries, leafId: resultLeafId });\n\t\treturn {\n\t\t\tcompaction: result.compaction,\n\t\t\tcompactionEntry: result.compactionEntry,\n\t\t\tentries: resultEntries,\n\t\t\tleafId: resultLeafId,\n\t\t\tmessages: result.messages ?? [],\n\t\t};\n\t} finally {\n\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t}\n}\n\nexport async function streamPiServer(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions?: PiServerStreamOptions,\n): Promise<PiServerEventStream> {\n\tconst sessionId = options?.sessionId ?? randomUUID();\n\tconst runId = randomUUID();\n\tconst isEphemeralSession = options?.sessionId === undefined;\n\tconst operation = registerPiServerOperation(options?.ownerSessionId ?? sessionId, sessionId, runId, options?.signal);\n\tconst stream = new PiServerEventStream();\n\n\tconst partial: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tstopReason: \"stop\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\ttimestamp: Date.now(),\n\t};\n\n\t(async () => {\n\t\tlet phase: PiServerFailurePhase = \"session_init\";\n\t\tlet streamOpened = false;\n\t\ttry {\n\t\t\tconst request = createPiServerRequest(options?.signal);\n\t\t\tawait ensureSessionInit(sessionId, context, request);\n\n\t\t\tconst makeBody = () => ({\n\t\t\t\tsessionId,\n\t\t\t\trunId,\n\t\t\t\tmodel,\n\t\t\t\toptions: serializeOptions(options),\n\t\t\t\tcontextOverlay: options?.contextOverlay ?? [\n\t\t\t\t\t...(context.messages as Message[]),\n\t\t\t\t\t...(options?.ephemeralMessages ?? []),\n\t\t\t\t],\n\t\t\t});\n\t\t\tphase = \"provider_stream\";\n\t\t\tlet response = await request.postJson(\"/api/stream\", makeBody());\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet failure = await readPiServerFailure(response);\n\t\t\t\tif (!options?.signal?.aborted && isRecoverableMissingServerState(response, failure.code)) {\n\t\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t\t\tawait ensureSessionInit(sessionId, context, request);\n\t\t\t\t\tresponse = await request.postJson(\"/api/stream\", makeBody());\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tfailure = { details: \"\", code: undefined };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailure = await readPiServerFailure(response);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`pi-server error: ${failure.details}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ensurePiServerEventStream(response);\n\t\t\tstreamOpened = true;\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst parser = new ServerSentEventParser();\n\t\t\tlet terminalReceived = false;\n\n\t\t\tconst consumeEvents = (events: ServerSentEvent[]): void => {\n\t\t\t\tfor (const serverEvent of events) {\n\t\t\t\t\tconst proxyEvent = parseServerSentEventData(\n\t\t\t\t\t\tserverEvent,\n\t\t\t\t\t\t\"pi-server stream\",\n\t\t\t\t\t) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (!event) continue;\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalReceived = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tconsumeEvents(parser.feed(decoder.decode(value, { stream: true })));\n\t\t\t}\n\t\t\tconsumeEvents(parser.feed(decoder.decode()));\n\t\t\tconsumeEvents(parser.finish());\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\t\t\tif (!terminalReceived) {\n\t\t\t\tthrow new Error(\"pi-server stream ended before a terminal response event\");\n\t\t\t}\n\n\t\t\tif (isEphemeralSession) {\n\t\t\t\tresetSessionTracking(sessionId);\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tlet errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t// Same-run recovery only applies to an interrupted event-stream. HTTP/proxy\n\t\t\t// failures before the stream starts (502/504/fetch failed) never opened a run\n\t\t\t// we can poll; attempting recovery against a down proxy reclassifies the error\n\t\t\t// as history_reconcile and blocks session auto-retry.\n\t\t\tif (!options?.signal?.aborted && phase === \"provider_stream\" && streamOpened) {\n\t\t\t\ttry {\n\t\t\t\t\tconst recoveredRun = await waitForPiServerRunCompletion(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tcreatePiServerRequest(options?.signal),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tif (recoveredRun?.status === \"completed\" && recoveredRun.message) {\n\t\t\t\t\t\tswitch (recoveredRun.message.stopReason) {\n\t\t\t\t\t\t\tcase \"stop\":\n\t\t\t\t\t\t\tcase \"length\":\n\t\t\t\t\t\t\tcase \"toolUse\":\n\t\t\t\t\t\t\tcase \"deferred\":\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\treason: recoveredRun.message.stopReason,\n\t\t\t\t\t\t\t\t\tmessage: recoveredRun.message,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"aborted\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: recoveredRun.message });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"failed\" && recoveredRun.errorMessage) {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tif (recoveredRun?.status === \"aborted\") {\n\t\t\t\t\t\terrorMessage = recoveredRun.errorMessage ?? \"pi-server run aborted\";\n\t\t\t\t\t}\n\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\tphase = \"history_reconcile\";\n\t\t\t\t\terrorMessage = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options?.signal?.aborted && operation && !operation.cancelConfirmed) {\n\t\t\t\ttry {\n\t\t\t\t\tawait cancelPiServerOperation(operation);\n\t\t\t\t} catch (cancelError) {\n\t\t\t\t\terrorMessage = `${errorMessage}; cancellation failed: ${\n\t\t\t\t\t\tcancelError instanceof Error ? cancelError.message : String(cancelError)\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tpartial.diagnostics = [\n\t\t\t\t...(partial.diagnostics ?? []),\n\t\t\t\t{\n\t\t\t\t\ttype: \"pi_server_failure\",\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\terror: { name: error instanceof Error ? error.name : \"Error\", message: errorMessage },\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tphase,\n\t\t\t\t\t\tsource: \"pi-server\",\n\t\t\t\t\t\tretryable: isRetryablePiServerFailure(phase, error),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait finishPiServerOperation(operation, options?.signal?.aborted === true);\n\t\t\t} catch {\n\t\t\t\t// The owning session's cancellation helper reports the failure and keeps\n\t\t\t\t// this operation registered for a retry.\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn { type: \"text_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"text_end\", contentIndex: proxyEvent.contentIndex, content: content.text, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn { type: \"thinking_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn { type: \"thinking_end\", contentIndex: proxyEvent.contentIndex, content: content.thinking, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} as any;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content };\n\t\t\t\treturn { type: \"toolcall_delta\", contentIndex: proxyEvent.contentIndex, delta: proxyEvent.delta, partial };\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn { type: \"toolcall_end\", contentIndex: proxyEvent.contentIndex, toolCall: content, partial };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nexport { getServerUrl, getAuthToken };\n"]}
@@ -1,10 +1,11 @@
1
1
  import type { SessionTreeEntry } from "@earendil-works/pi-agent-core";
2
- import type { Tool } from "@earendil-works/pi-ai";
2
+ import type { Message, Tool } from "@earendil-works/pi-ai";
3
3
  export interface PiServerStaticContext {
4
4
  systemPrompt?: string;
5
5
  tools?: Tool[];
6
6
  }
7
7
  export declare function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string;
8
+ export declare function hashPiServerProviderMessages(messages: readonly Message[]): string;
8
9
  export declare const PI_SERVER_EMPTY_TREE_HASH: string;
9
10
  export declare function hashPiServerTreeEntry(entry: SessionTreeEntry): string;
10
11
  export declare function appendPiServerTreeHash(previousHash: string, entryHash: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-protocol.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-protocol.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAElD,MAAM,WAAW,qBAAqB;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC;CACf;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,qBAAqB,GAAG,SAAS,GAAG,MAAM,CAW5F;AAED,eAAO,MAAM,yBAAyB,QAA0D,CAAC;AAEjG,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAErE;AAED,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAEtF;AAED,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,MAAM,EAAE,CAMnF;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,MAAM,CAE9E","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SessionTreeEntry } from \"@earendil-works/pi-agent-core\";\nimport type { Tool } from \"@earendil-works/pi-ai\";\n\nexport interface PiServerStaticContext {\n\tsystemPrompt?: string;\n\ttools?: Tool[];\n}\n\nexport function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string {\n\tif (!context) return \"\";\n\tconst canonical = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools?.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t})),\n\t};\n\treturn createHash(\"sha256\").update(JSON.stringify(canonical)).digest(\"hex\");\n}\n\nexport const PI_SERVER_EMPTY_TREE_HASH = createHash(\"sha256\").update(\"pi-tree-v1\").digest(\"hex\");\n\nexport function hashPiServerTreeEntry(entry: SessionTreeEntry): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(entry)).digest(\"hex\");\n}\n\nexport function appendPiServerTreeHash(previousHash: string, entryHash: string): string {\n\treturn createHash(\"sha256\").update(`${previousHash}:${entryHash}`).digest(\"hex\");\n}\n\nexport function buildPiServerTreePrefixHashes(entries: SessionTreeEntry[]): string[] {\n\tconst hashes = [PI_SERVER_EMPTY_TREE_HASH];\n\tfor (const entry of entries) {\n\t\thashes.push(appendPiServerTreeHash(hashes[hashes.length - 1], hashPiServerTreeEntry(entry)));\n\t}\n\treturn hashes;\n}\n\nexport function hashPiServerSessionEntries(entries: SessionTreeEntry[]): string {\n\treturn buildPiServerTreePrefixHashes(entries)[entries.length];\n}\n"]}
1
+ {"version":3,"file":"pi-server-protocol.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-protocol.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAE3D,MAAM,WAAW,qBAAqB;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC;CACf;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,qBAAqB,GAAG,SAAS,GAAG,MAAM,CAW5F;AAeD,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,CAIjF;AAED,eAAO,MAAM,yBAAyB,QAA0D,CAAC;AAEjG,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAErE;AAED,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAEtF;AAED,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,MAAM,EAAE,CAMnF;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,MAAM,CAE9E","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SessionTreeEntry } from \"@earendil-works/pi-agent-core\";\nimport type { Message, Tool } from \"@earendil-works/pi-ai\";\n\nexport interface PiServerStaticContext {\n\tsystemPrompt?: string;\n\ttools?: Tool[];\n}\n\nexport function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string {\n\tif (!context) return \"\";\n\tconst canonical = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools?.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t})),\n\t};\n\treturn createHash(\"sha256\").update(JSON.stringify(canonical)).digest(\"hex\");\n}\n\nfunction canonicalizeJson(value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map(canonicalizeJson);\n\tif (value && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(record)\n\t\t\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t\t\t.map(([key, item]) => [key, canonicalizeJson(item)]),\n\t\t);\n\t}\n\treturn value;\n}\n\nexport function hashPiServerProviderMessages(messages: readonly Message[]): string {\n\treturn createHash(\"sha256\")\n\t\t.update(JSON.stringify(canonicalizeJson(messages)))\n\t\t.digest(\"hex\");\n}\n\nexport const PI_SERVER_EMPTY_TREE_HASH = createHash(\"sha256\").update(\"pi-tree-v1\").digest(\"hex\");\n\nexport function hashPiServerTreeEntry(entry: SessionTreeEntry): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(entry)).digest(\"hex\");\n}\n\nexport function appendPiServerTreeHash(previousHash: string, entryHash: string): string {\n\treturn createHash(\"sha256\").update(`${previousHash}:${entryHash}`).digest(\"hex\");\n}\n\nexport function buildPiServerTreePrefixHashes(entries: SessionTreeEntry[]): string[] {\n\tconst hashes = [PI_SERVER_EMPTY_TREE_HASH];\n\tfor (const entry of entries) {\n\t\thashes.push(appendPiServerTreeHash(hashes[hashes.length - 1], hashPiServerTreeEntry(entry)));\n\t}\n\treturn hashes;\n}\n\nexport function hashPiServerSessionEntries(entries: SessionTreeEntry[]): string {\n\treturn buildPiServerTreePrefixHashes(entries)[entries.length];\n}\n"]}
@@ -12,6 +12,22 @@ export function hashPiServerStaticContext(context) {
12
12
  };
13
13
  return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
14
14
  }
15
+ function canonicalizeJson(value) {
16
+ if (Array.isArray(value))
17
+ return value.map(canonicalizeJson);
18
+ if (value && typeof value === "object") {
19
+ const record = value;
20
+ return Object.fromEntries(Object.entries(record)
21
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
22
+ .map(([key, item]) => [key, canonicalizeJson(item)]));
23
+ }
24
+ return value;
25
+ }
26
+ export function hashPiServerProviderMessages(messages) {
27
+ return createHash("sha256")
28
+ .update(JSON.stringify(canonicalizeJson(messages)))
29
+ .digest("hex");
30
+ }
15
31
  export const PI_SERVER_EMPTY_TREE_HASH = createHash("sha256").update("pi-tree-v1").digest("hex");
16
32
  export function hashPiServerTreeEntry(entry) {
17
33
  return createHash("sha256").update(JSON.stringify(entry)).digest("hex");
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-protocol.js","sourceRoot":"","sources":["../../src/core/pi-server-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AASzC,MAAM,UAAU,yBAAyB,CAAC,OAA0C,EAAU;IAC7F,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IACxB,MAAM,SAAS,GAAG;QACjB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACpC,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,UAAU,EAAE,IAAI,CAAC,UAAU;SAC3B,CAAC,CAAC;KACH,CAAC;IACF,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,MAAM,CAAC,MAAM,yBAAyB,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEjG,MAAM,UAAU,qBAAqB,CAAC,KAAuB,EAAU;IACtE,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CACxE;AAED,MAAM,UAAU,sBAAsB,CAAC,YAAoB,EAAE,SAAiB,EAAU;IACvF,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,YAAY,IAAI,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CACjF;AAED,MAAM,UAAU,6BAA6B,CAAC,OAA2B,EAAY;IACpF,MAAM,MAAM,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAC3C,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd;AAED,MAAM,UAAU,0BAA0B,CAAC,OAA2B,EAAU;IAC/E,OAAO,6BAA6B,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAAA,CAC9D","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SessionTreeEntry } from \"@earendil-works/pi-agent-core\";\nimport type { Tool } from \"@earendil-works/pi-ai\";\n\nexport interface PiServerStaticContext {\n\tsystemPrompt?: string;\n\ttools?: Tool[];\n}\n\nexport function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string {\n\tif (!context) return \"\";\n\tconst canonical = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools?.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t})),\n\t};\n\treturn createHash(\"sha256\").update(JSON.stringify(canonical)).digest(\"hex\");\n}\n\nexport const PI_SERVER_EMPTY_TREE_HASH = createHash(\"sha256\").update(\"pi-tree-v1\").digest(\"hex\");\n\nexport function hashPiServerTreeEntry(entry: SessionTreeEntry): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(entry)).digest(\"hex\");\n}\n\nexport function appendPiServerTreeHash(previousHash: string, entryHash: string): string {\n\treturn createHash(\"sha256\").update(`${previousHash}:${entryHash}`).digest(\"hex\");\n}\n\nexport function buildPiServerTreePrefixHashes(entries: SessionTreeEntry[]): string[] {\n\tconst hashes = [PI_SERVER_EMPTY_TREE_HASH];\n\tfor (const entry of entries) {\n\t\thashes.push(appendPiServerTreeHash(hashes[hashes.length - 1], hashPiServerTreeEntry(entry)));\n\t}\n\treturn hashes;\n}\n\nexport function hashPiServerSessionEntries(entries: SessionTreeEntry[]): string {\n\treturn buildPiServerTreePrefixHashes(entries)[entries.length];\n}\n"]}
1
+ {"version":3,"file":"pi-server-protocol.js","sourceRoot":"","sources":["../../src/core/pi-server-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AASzC,MAAM,UAAU,yBAAyB,CAAC,OAA0C,EAAU;IAC7F,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IACxB,MAAM,SAAS,GAAG;QACjB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC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AED,MAAM,CAAC,MAAM,yBAAyB,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEjG,MAAM,UAAU,qBAAqB,CAAC,KAAuB,EAAU;IACtE,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CACxE;AAED,MAAM,UAAU,sBAAsB,CAAC,YAAoB,EAAE,SAAiB,EAAU;IACvF,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,YAAY,IAAI,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CACjF;AAED,MAAM,UAAU,6BAA6B,CAAC,OAA2B,EAAY;IACpF,MAAM,MAAM,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAC3C,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd;AAED,MAAM,UAAU,0BAA0B,CAAC,OAA2B,EAAU;IAC/E,OAAO,6BAA6B,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAAA,CAC9D","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SessionTreeEntry } from \"@earendil-works/pi-agent-core\";\nimport type { Message, Tool } from \"@earendil-works/pi-ai\";\n\nexport interface PiServerStaticContext {\n\tsystemPrompt?: string;\n\ttools?: Tool[];\n}\n\nexport function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string {\n\tif (!context) return \"\";\n\tconst canonical = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\ttools: context.tools?.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t})),\n\t};\n\treturn createHash(\"sha256\").update(JSON.stringify(canonical)).digest(\"hex\");\n}\n\nfunction canonicalizeJson(value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map(canonicalizeJson);\n\tif (value && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(record)\n\t\t\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t\t\t.map(([key, item]) => [key, canonicalizeJson(item)]),\n\t\t);\n\t}\n\treturn value;\n}\n\nexport function hashPiServerProviderMessages(messages: readonly Message[]): string {\n\treturn createHash(\"sha256\")\n\t\t.update(JSON.stringify(canonicalizeJson(messages)))\n\t\t.digest(\"hex\");\n}\n\nexport const PI_SERVER_EMPTY_TREE_HASH = createHash(\"sha256\").update(\"pi-tree-v1\").digest(\"hex\");\n\nexport function hashPiServerTreeEntry(entry: SessionTreeEntry): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(entry)).digest(\"hex\");\n}\n\nexport function appendPiServerTreeHash(previousHash: string, entryHash: string): string {\n\treturn createHash(\"sha256\").update(`${previousHash}:${entryHash}`).digest(\"hex\");\n}\n\nexport function buildPiServerTreePrefixHashes(entries: SessionTreeEntry[]): string[] {\n\tconst hashes = [PI_SERVER_EMPTY_TREE_HASH];\n\tfor (const entry of entries) {\n\t\thashes.push(appendPiServerTreeHash(hashes[hashes.length - 1], hashPiServerTreeEntry(entry)));\n\t}\n\treturn hashes;\n}\n\nexport function hashPiServerSessionEntries(entries: SessionTreeEntry[]): string {\n\treturn buildPiServerTreePrefixHashes(entries)[entries.length];\n}\n"]}
@@ -0,0 +1,106 @@
1
+ # CLI Integration
2
+
3
+ By default, running `pi` opens the interactive terminal interface. When input or output is piped or redirected, Pi uses print mode instead. You can also select print, JSON, or RPC mode explicitly for scripts and applications.
4
+
5
+ All four modes use the same agent, sessions, resources, and tools. The mode determines how input enters Pi, how output is exposed, and whether the process remains available for more commands.
6
+
7
+ The SDK is not a CLI mode. It embeds the agent directly in a Node.js or Bun process. See the [SDK](sdk.md) when direct TypeScript access is preferable to a process boundary.
8
+
9
+ ## Choose a mode
10
+
11
+ | Mode | Interface | Lifetime | Use it when |
12
+ |---|---|---|---|
13
+ | Interactive | Terminal UI | Until the user exits | A person is working with Pi directly |
14
+ | Print | Final text on stdout | One invocation | A script needs the final assistant response |
15
+ | JSON | JSONL events on stdout | One invocation | A process needs structured progress from a run |
16
+ | RPC | JSONL commands, responses, and events | Long-lived | A process needs bidirectional control |
17
+
18
+ CLI options still select the working directory, model, tools, resources, and session persistence independently of the mode. See [Command Line](cli.md) for the complete startup options.
19
+
20
+ ## Print to stdout
21
+
22
+ Print mode runs the supplied prompts, writes the final assistant text to stdout, and exits:
23
+
24
+ ```bash
25
+ pi --print "Summarize the changes in this repository"
26
+ ```
27
+
28
+ Use print mode when only the final text is needed, including command substitution, pipelines, and one-shot jobs. Intermediate events are not exposed.
29
+
30
+ Print mode writes errors to stderr. A final assistant response with an `error` or `aborted` stop reason produces a nonzero exit status.
31
+
32
+ When no mode is selected explicitly, non-TTY stdin or stdout also selects print mode. This allows piped input and output without adding `--print`.
33
+
34
+ ## Stream JSON events
35
+
36
+ JSON mode writes a session header followed by agent and session events as newline-delimited JSON:
37
+
38
+ ```bash
39
+ pi --mode json "Review this repository" > events.jsonl
40
+ ```
41
+
42
+ This is structured event output, not a single JSON result or a constraint on the format of the model’s response.
43
+
44
+ All prompts are supplied when the process starts. The process streams events for that run and then exits; it does not accept later commands.
45
+
46
+ A failed or aborted assistant response appears in the event stream but does not by itself produce a nonzero exit status. Inspect the events when success or failure matters. Pi still exits nonzero if the invocation throws an error.
47
+
48
+ Streaming `message_update` records contain deltas rather than a growing message snapshot. Assemble live output from the delta events, then replace it with the authoritative message from `message_end`.
49
+
50
+ `agent_end` can be followed by automatic recovery or queued work. `agent_settled` marks the end of automatic work for the current run.
51
+
52
+ Stdout is reserved for JSONL. Diagnostics and application logging are written to stderr. See [JSON Event Stream](json.md) for framing, event shapes, and reconstruction rules.
53
+
54
+ ## Control Pi with RPC
55
+
56
+ RPC mode keeps Pi running while another process sends commands and receives responses and events:
57
+
58
+ ```bash
59
+ pi --mode rpc --no-session
60
+ ```
61
+
62
+ Commands are JSON objects written to stdin. Responses and events are JSON objects written to stdout. Every record occupies one line.
63
+
64
+ Add an `id` to commands that need correlation. The matching response repeats that ID. Events generally have no command ID because they describe session activity rather than one request.
65
+
66
+ A successful `prompt` response means the prompt was accepted, queued, or handled. It does not mean the run completed. Continue consuming events through `agent_settled` when completion matters.
67
+
68
+ RPC commands can change models, inspect state, manage sessions, run shell commands, and answer extension UI requests.
69
+
70
+ Extension dialogs form a request-response subprotocol. Other extension UI updates are notifications that a client may display or ignore. TUI-only extension capabilities are unavailable or degraded outside interactive mode.
71
+
72
+ For Node.js or TypeScript integrations, prefer `RpcClient` from `@earendil-works/pi-coding-agent`. It starts a Pi RPC child process, correlates requests, exposes typed command methods, and delivers session events to listeners.
73
+
74
+ The [RPC client example](../examples/rpc-client.ts) sends one prompt, streams text and tool activity, waits for `agent_settled`, and shuts down the child process. It is included in the repository’s TypeScript checks.
75
+
76
+ `RpcClient.promptAndWait()` installs its event listener before sending the prompt, avoiding a race with fast completions. For separate operations, subscribe before calling `prompt()` and call `waitForIdle()` only while a run is active.
77
+
78
+ The client requires a path to a runnable Pi CLI. The repository example points at `dist/cli.js`, so the package must be built before that example runs from a checkout.
79
+
80
+ If you are building a client without `RpcClient`, start with [RPC Protocol](rpc.md), then use [RPC Commands](rpc-commands.md) and [JSON Event Stream](json.md) as the wire references.
81
+
82
+ ## Fork and rebrand Pi
83
+
84
+ A source fork can change the CLI name and configuration directory through `package.json`:
85
+
86
+ ```json
87
+ {
88
+ "piConfig": {
89
+ "name": "my-agent",
90
+ "configDir": ".my-agent"
91
+ }
92
+ }
93
+ ```
94
+
95
+ Change the top-level `bin` field to set the executable name. These settings affect the CLI banner, configuration paths, and derived environment variable names.
96
+
97
+ ## Examples and references
98
+
99
+ - [RPC client](../examples/rpc-client.ts): typed Node.js integration
100
+ - [RPC extension UI](../examples/rpc-extension-ui.ts): custom terminal client with extension dialogs
101
+ - [Command Line](cli.md): startup options and mode selection
102
+ - [JSON Event Stream](json.md): JSON event reference
103
+ - [RPC Protocol](rpc.md): RPC lifecycle, framing, errors, and shutdown
104
+ - [RPC Commands](rpc-commands.md): command and response reference
105
+ - [RPC Extension UI](rpc-extension-ui.md): extension interaction subprotocol
106
+ - [SDK examples](../examples/sdk/): in-process TypeScript integrations