@averyyy/pi-coding-agent 0.82.1-piclient.6 → 0.82.1-piclient.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -12
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +1 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +0 -5
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -12
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +89 -317
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/pi-server-client.d.ts +2 -54
- package/dist/core/pi-server-client.d.ts.map +1 -1
- package/dist/core/pi-server-client.js +272 -2320
- package/dist/core/pi-server-client.js.map +1 -1
- package/dist/core/pi-server-protocol.d.ts +0 -2
- package/dist/core/pi-server-protocol.d.ts.map +1 -1
- package/dist/core/pi-server-protocol.js +1 -24
- package/dist/core/pi-server-protocol.js.map +1 -1
- package/dist/core/pi-server-request.d.ts +0 -28
- package/dist/core/pi-server-request.d.ts.map +1 -1
- package/dist/core/pi-server-request.js +75 -492
- package/dist/core/pi-server-request.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +53 -69
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +2 -86
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +144 -737
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +1 -3
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +26 -46
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +0 -13
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +0 -15
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +29 -98
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/package.json +4 -4
- package/dist/cli/tool-effects.d.ts +0 -6
- package/dist/cli/tool-effects.d.ts.map +0 -1
- package/dist/cli/tool-effects.js +0 -164
- package/dist/cli/tool-effects.js.map +0 -1
- package/dist/core/pi-server-compact-state.d.ts +0 -81
- package/dist/core/pi-server-compact-state.d.ts.map +0 -1
- package/dist/core/pi-server-compact-state.js +0 -439
- package/dist/core/pi-server-compact-state.js.map +0 -1
- package/dist/core/pi-server-run-state.d.ts +0 -42
- package/dist/core/pi-server-run-state.d.ts.map +0 -1
- package/dist/core/pi-server-run-state.js +0 -320
- package/dist/core/pi-server-run-state.js.map +0 -1
- package/dist/core/tool-effect-journal.d.ts +0 -103
- package/dist/core/tool-effect-journal.d.ts.map +0 -1
- package/dist/core/tool-effect-journal.js +0 -1442
- package/dist/core/tool-effect-journal.js.map +0 -1
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import type { SessionTreeEntry } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Tool } from "@earendil-works/pi-ai";
|
|
3
|
-
export declare const PI_SERVER_PROTOCOL_VERSION = 2;
|
|
4
3
|
export interface PiServerStaticContext {
|
|
5
4
|
systemPrompt?: string;
|
|
6
5
|
tools?: Tool[];
|
|
7
6
|
}
|
|
8
|
-
export declare function canonicalJsonStringify(value: unknown): string | undefined;
|
|
9
7
|
export declare function hashPiServerStaticContext(context: PiServerStaticContext | undefined): string;
|
|
10
8
|
export declare const PI_SERVER_EMPTY_TREE_HASH: string;
|
|
11
9
|
export declare function hashPiServerTreeEntry(entry: SessionTreeEntry): 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,
|
|
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,22 +1,4 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
export const PI_SERVER_PROTOCOL_VERSION = 2;
|
|
3
|
-
export function canonicalJsonStringify(value) {
|
|
4
|
-
if (Array.isArray(value)) {
|
|
5
|
-
return `[${Array.from(value, (item) => canonicalJsonStringify(item) ?? "null").join(",")}]`;
|
|
6
|
-
}
|
|
7
|
-
if (value !== null && typeof value === "object") {
|
|
8
|
-
const record = value;
|
|
9
|
-
const properties = [];
|
|
10
|
-
for (const key of Object.keys(record).sort()) {
|
|
11
|
-
const serialized = canonicalJsonStringify(record[key]);
|
|
12
|
-
if (serialized !== undefined) {
|
|
13
|
-
properties.push(`${JSON.stringify(key)}:${serialized}`);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
return `{${properties.join(",")}}`;
|
|
17
|
-
}
|
|
18
|
-
return JSON.stringify(value);
|
|
19
|
-
}
|
|
20
2
|
export function hashPiServerStaticContext(context) {
|
|
21
3
|
if (!context)
|
|
22
4
|
return "";
|
|
@@ -26,14 +8,9 @@ export function hashPiServerStaticContext(context) {
|
|
|
26
8
|
name: tool.name,
|
|
27
9
|
description: tool.description,
|
|
28
10
|
parameters: tool.parameters,
|
|
29
|
-
constrainedSampling: tool.constrainedSampling,
|
|
30
11
|
})),
|
|
31
12
|
};
|
|
32
|
-
|
|
33
|
-
if (serialized === undefined) {
|
|
34
|
-
throw new Error("Failed to serialize pi-server static context");
|
|
35
|
-
}
|
|
36
|
-
return createHash("sha256").update(serialized).digest("hex");
|
|
13
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
37
14
|
}
|
|
38
15
|
export const PI_SERVER_EMPTY_TREE_HASH = createHash("sha256").update("pi-tree-v1").digest("hex");
|
|
39
16
|
export function hashPiServerTreeEntry(entry) {
|
|
@@ -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;
|
|
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,42 +1,14 @@
|
|
|
1
|
-
export declare const PI_SERVER_CHUNK_ACK_HEADER = "X-Pi-Chunk-Ack";
|
|
2
|
-
export declare const PI_SERVER_CHUNK_ACK_VALUE = "1";
|
|
3
|
-
export declare const PI_SERVER_CHUNK_FINAL_VALUE = "0";
|
|
4
|
-
export declare const PI_SERVER_CHUNK_SEGMENT_ENCODING = "base64-segment-v1";
|
|
5
|
-
export declare const PI_SERVER_RESPONSE_HEADER_TIMEOUT_MS = 30000;
|
|
6
1
|
export interface PiServerRequestOptions {
|
|
7
2
|
serverUrl: string;
|
|
8
3
|
authToken: string;
|
|
9
4
|
signal?: AbortSignal;
|
|
10
|
-
responseHeaderTimeoutMs?: number;
|
|
11
|
-
maxChunkRequestMemos?: number;
|
|
12
|
-
}
|
|
13
|
-
export declare class PiServerTransportHeaderTimeoutError extends Error {
|
|
14
|
-
readonly code = "PI_SERVER_TRANSPORT_HEADER_TIMEOUT";
|
|
15
|
-
readonly timeoutMs: number;
|
|
16
|
-
constructor(method: string, endpoint: string, timeoutMs: number);
|
|
17
|
-
}
|
|
18
|
-
export declare class PiServerChunkRequestMemoLimitError extends Error {
|
|
19
|
-
readonly code = "PI_SERVER_CHUNK_REQUEST_MEMO_LIMIT";
|
|
20
|
-
readonly limit: number;
|
|
21
|
-
constructor(limit: number);
|
|
22
|
-
}
|
|
23
|
-
export declare class PiServerChunkAckProtocolError extends Error {
|
|
24
|
-
constructor(message: string);
|
|
25
|
-
}
|
|
26
|
-
export declare class PiServerTransportBodyLimitError extends Error {
|
|
27
|
-
readonly code = "PI_SERVER_TRANSPORT_BODY_LIMIT";
|
|
28
|
-
readonly maxBytes: number;
|
|
29
|
-
constructor(maxBytes: number);
|
|
30
5
|
}
|
|
31
6
|
export declare function getMaxRequestBytes(): number;
|
|
32
|
-
export declare function readPiServerResponseText(response: Response, maxBytes?: number): Promise<string>;
|
|
33
|
-
export declare function readPiServerResponseJson(response: Response, maxBytes?: number): Promise<unknown>;
|
|
34
7
|
export declare class ChunkRequest {
|
|
35
8
|
#private;
|
|
36
9
|
options: PiServerRequestOptions;
|
|
37
10
|
constructor(options: PiServerRequestOptions);
|
|
38
11
|
getJson(endpoint: string): Promise<Response>;
|
|
39
|
-
deleteJson(endpoint: string): Promise<Response>;
|
|
40
12
|
postJson(endpoint: string, body: unknown): Promise<Response>;
|
|
41
13
|
}
|
|
42
14
|
//# sourceMappingURL=pi-server-request.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi-server-request.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-request.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAC7C,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,eAAO,MAAM,gCAAgC,sBAAsB,CAAC;AACpE,eAAO,MAAM,oCAAoC,QAAS,CAAC;AAE3D,MAAM,WAAW,sBAAsB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAoCD,qBAAa,mCAAoC,SAAQ,KAAK;IAC7D,QAAQ,CAAC,IAAI,wCAAwC;IACrD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B,YAAY,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAI9D;CACD;AASD,qBAAa,kCAAmC,SAAQ,KAAK;IAC5D,QAAQ,CAAC,IAAI,wCAAwC;IACrD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,YAAY,KAAK,EAAE,MAAM,EAMxB;CACD;AAED,qBAAa,6BAA8B,SAAQ,KAAK;IACvD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAED,qBAAa,+BAAgC,SAAQ,KAAK;IACzD,QAAQ,CAAC,IAAI,oCAAoC;IACjD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAI3B;CACD;AAMD,wBAAgB,kBAAkB,IAAI,MAAM,CAS3C;AAsGD,wBAAsB,wBAAwB,CAC7C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,SAA2B,GACjC,OAAO,CAAC,MAAM,CAAC,CA8BjB;AAED,wBAAsB,wBAAwB,CAC7C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,SAA2B,GACjC,OAAO,CAAC,OAAO,CAAC,CAElB;AAmLD,qBAAa,YAAY;;IACxB,OAAO,EAAE,sBAAsB,CAAC;IAIhC,YAAY,OAAO,EAAE,sBAAsB,EAO1C;IAEK,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAKjD;IAEK,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAKpD;IAEK,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAyKjE;CAyCD","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst DEFAULT_MAX_REQUEST_KB = 512;\nconst CHUNK_ENDPOINT = \"/api/request/chunk\";\nconst CHUNK_UPLOAD_CONCURRENCY = 4;\nconst CHUNK_MAX_TOTAL_CHUNKS = 4096;\nconst CHUNK_UPLOAD_RETRY_DELAYS_MS = [100, 250, 500] as const;\nconst LEGACY_CHUNK_ACK_MAX_BYTES = 4096;\nconst DEFAULT_CHUNK_REQUEST_MEMO_LIMIT = 128;\nconst DEFAULT_RESPONSE_NO_PROGRESS_TIMEOUT_MS = 90_000;\nexport const PI_SERVER_CHUNK_ACK_HEADER = \"X-Pi-Chunk-Ack\";\nexport const PI_SERVER_CHUNK_ACK_VALUE = \"1\";\nexport const PI_SERVER_CHUNK_FINAL_VALUE = \"0\";\nexport const PI_SERVER_CHUNK_SEGMENT_ENCODING = \"base64-segment-v1\";\nexport const PI_SERVER_RESPONSE_HEADER_TIMEOUT_MS = 30_000;\n\nexport interface PiServerRequestOptions {\n\tserverUrl: string;\n\tauthToken: string;\n\tsignal?: AbortSignal;\n\tresponseHeaderTimeoutMs?: number;\n\tmaxChunkRequestMemos?: number;\n}\n\ninterface ChunkBody {\n\trequestId: string;\n\ttarget: string;\n\tchunkIndex: number;\n\ttotalChunks: number;\n\tsha256: string;\n\tchunk: string;\n\tencoding: typeof PI_SERVER_CHUNK_SEGMENT_ENCODING;\n\trawTotalBytes: number;\n\trawChunkBytes: number;\n}\n\ninterface ChunkAckBody {\n\treceived: unknown;\n\trequestId: unknown;\n\tchunkIndex: unknown;\n\ttotalChunks: unknown;\n}\n\ninterface ChunkRequestMemo {\n\trequestId: string;\n\tmaxBytes: number;\n}\n\ninterface ChunkResponseInspection {\n\tacknowledged: boolean;\n\tresponse?: Response;\n}\n\ninterface BodyNoProgressState {\n\treadonly timeoutMs: number;\n\tdeadlineMs: number;\n}\n\nexport class PiServerTransportHeaderTimeoutError extends Error {\n\treadonly code = \"PI_SERVER_TRANSPORT_HEADER_TIMEOUT\";\n\treadonly timeoutMs: number;\n\n\tconstructor(method: string, endpoint: string, timeoutMs: number) {\n\t\tsuper(`pi-server transport header timeout after ${timeoutMs} ms (ETIMEDOUT): ${method} ${endpoint}`);\n\t\tthis.name = \"PiServerTransportHeaderTimeoutError\";\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nclass PiServerTransportBodyNoProgressError extends Error {\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`pi-server response made no progress for ${timeoutMs}ms`);\n\t\tthis.name = \"PiServerTransportBodyNoProgressError\";\n\t}\n}\n\nexport class PiServerChunkRequestMemoLimitError extends Error {\n\treadonly code = \"PI_SERVER_CHUNK_REQUEST_MEMO_LIMIT\";\n\treadonly limit: number;\n\n\tconstructor(limit: number) {\n\t\tsuper(\n\t\t\t`pi-server chunk request identity limit (${limit}) reached; refusing to allocate a new requestId while prior requests remain uncertain`,\n\t\t);\n\t\tthis.name = \"PiServerChunkRequestMemoLimitError\";\n\t\tthis.limit = limit;\n\t}\n}\n\nexport class PiServerChunkAckProtocolError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"PiServerChunkAckProtocolError\";\n\t}\n}\n\nexport class PiServerTransportBodyLimitError extends Error {\n\treadonly code = \"PI_SERVER_TRANSPORT_BODY_LIMIT\";\n\treadonly maxBytes: number;\n\n\tconstructor(maxBytes: number) {\n\t\tsuper(`pi-server response body exceeded ${maxBytes} bytes`);\n\t\tthis.name = \"PiServerTransportBodyLimitError\";\n\t\tthis.maxBytes = maxBytes;\n\t}\n}\n\nfunction jsonByteLength(value: unknown): number {\n\treturn Buffer.byteLength(JSON.stringify(value), \"utf-8\");\n}\n\nexport function getMaxRequestBytes(): number {\n\tconst raw = process.env.PI_CLIENT_MAX_REQUEST_KB;\n\tif (raw === undefined || raw === \"\") return DEFAULT_MAX_REQUEST_KB * 1024;\n\n\tconst value = Number(raw);\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(\"PI_CLIENT_MAX_REQUEST_KB must be a positive number\");\n\t}\n\treturn Math.floor(value * 1024);\n}\n\nfunction makeHeaders(authToken: string): Record<string, string> {\n\treturn {\n\t\t\"Content-Type\": \"application/json\",\n\t\t...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n\t};\n}\n\nfunction sha256(value: string | Uint8Array): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isTransientChunkResponse(status: number): boolean {\n\treturn status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nfunction waitForChunkRetry(delayMs: number, signal?: AbortSignal): Promise<void> {\n\tif (signal?.aborted) return Promise.reject(signal.reason);\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, delayMs);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\treject(signal?.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\"));\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isChunkAckBody(value: unknown): value is ChunkAckBody {\n\treturn (\n\t\tisRecord(value) && \"received\" in value && \"requestId\" in value && \"chunkIndex\" in value && \"totalChunks\" in value\n\t);\n}\n\nfunction getResponseNoProgressTimeoutMs(): number {\n\tconst raw = process.env.PI_SERVER_RESPONSE_NO_PROGRESS_TIMEOUT_MS;\n\tconst value = raw === undefined ? DEFAULT_RESPONSE_NO_PROGRESS_TIMEOUT_MS : Number(raw);\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(\"PI_SERVER_RESPONSE_NO_PROGRESS_TIMEOUT_MS must be positive finite milliseconds\");\n\t}\n\treturn value;\n}\n\nfunction createBodyNoProgressState(): BodyNoProgressState {\n\tconst timeoutMs = getResponseNoProgressTimeoutMs();\n\treturn { timeoutMs, deadlineMs: Date.now() + timeoutMs };\n}\n\nasync function readPiServerBodyChunk(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tstate: BodyNoProgressState,\n): Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>> {\n\twhile (true) {\n\t\tconst remainingMs = state.deadlineMs - Date.now();\n\t\tif (remainingMs <= 0) {\n\t\t\tthrow new PiServerTransportBodyNoProgressError(state.timeoutMs);\n\t\t}\n\t\tconst result = await new Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>>(\n\t\t\t(resolve, reject) => {\n\t\t\t\tlet settled = false;\n\t\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(new PiServerTransportBodyNoProgressError(state.timeoutMs));\n\t\t\t\t}, remainingMs);\n\t\t\t\ttimeout.unref();\n\t\t\t\tvoid reader.read().then(\n\t\t\t\t\t(value) => {\n\t\t\t\t\t\tif (settled) return;\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\tresolve(value);\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tif (settled) return;\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tif (result.done || result.value.byteLength > 0) {\n\t\t\tif (!result.done) state.deadlineMs = Date.now() + state.timeoutMs;\n\t\t\treturn result;\n\t\t}\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tsetTimeout(resolve, 0);\n\t\t});\n\t}\n}\n\nexport async function readPiServerResponseText(\n\tresponse: Response,\n\tmaxBytes = Number.POSITIVE_INFINITY,\n): Promise<string> {\n\tif (\n\t\t(maxBytes !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) ||\n\t\tmaxBytes === Number.NEGATIVE_INFINITY\n\t) {\n\t\tthrow new Error(\"pi-server response body limit must be positive safe-integer bytes or Infinity\");\n\t}\n\tif (!response.body) throw new Error(\"pi-server response body was missing\");\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst noProgress = createBodyNoProgressState();\n\tlet body = \"\";\n\tlet bodyBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await readPiServerBodyChunk(reader, noProgress);\n\t\t\tif (result.done) {\n\t\t\t\tbody += decoder.decode();\n\t\t\t\treturn body;\n\t\t\t}\n\t\t\tbodyBytes += result.value.byteLength;\n\t\t\tif (bodyBytes > maxBytes) {\n\t\t\t\tthrow new PiServerTransportBodyLimitError(maxBytes);\n\t\t\t}\n\t\t\tbody += decoder.decode(result.value, { stream: true });\n\t\t}\n\t} catch (error) {\n\t\tvoid reader.cancel().catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nexport async function readPiServerResponseJson(\n\tresponse: Response,\n\tmaxBytes = Number.POSITIVE_INFINITY,\n): Promise<unknown> {\n\treturn JSON.parse(await readPiServerResponseText(response, maxBytes)) as unknown;\n}\n\nfunction rebuildResponse(response: Response, body: ConstructorParameters<typeof Response>[0]): Response {\n\treturn new Response(body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: response.headers,\n\t});\n}\n\nasync function discardResponse(response: Response | undefined): Promise<void> {\n\tif (!response?.body || response.bodyUsed || response.body.locked) return;\n\ttry {\n\t\tawait response.body.cancel();\n\t} catch {\n\t\t// The response is already unusable and must not replace the selected final response.\n\t}\n}\n\nasync function inspectLegacyChunkAck(\n\tresponse: Response,\n\trequestId: string,\n\tchunkIndex: number,\n\ttotalChunks: number,\n): Promise<ChunkResponseInspection> {\n\tconst contentLength = Number(response.headers.get(\"Content-Length\"));\n\tif (Number.isFinite(contentLength) && contentLength > LEGACY_CHUNK_ACK_MAX_BYTES) {\n\t\treturn { acknowledged: false, response };\n\t}\n\tif (!response.body) return { acknowledged: false, response };\n\tconst reader = response.body.getReader();\n\tconst noProgress = createBodyNoProgressState();\n\tconst chunks: Uint8Array[] = [];\n\tlet bodyBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await readPiServerBodyChunk(reader, noProgress);\n\t\t\tif (result.done) break;\n\t\t\tchunks.push(result.value);\n\t\t\tbodyBytes += result.value.byteLength;\n\t\t\tif (bodyBytes > LEGACY_CHUNK_ACK_MAX_BYTES) {\n\t\t\t\tlet prefixIndex = 0;\n\t\t\t\tconst rebuiltBody = new ReadableStream<Uint8Array>({\n\t\t\t\t\tasync pull(controller) {\n\t\t\t\t\t\tif (prefixIndex < chunks.length) {\n\t\t\t\t\t\t\tconst prefix = chunks[prefixIndex];\n\t\t\t\t\t\t\tchunks[prefixIndex] = new Uint8Array();\n\t\t\t\t\t\t\tprefixIndex++;\n\t\t\t\t\t\t\tcontroller.enqueue(prefix);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst next = await readPiServerBodyChunk(reader, noProgress);\n\t\t\t\t\t\t\tif (next.done) {\n\t\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontroller.enqueue(next.value);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t\t\tvoid reader.cancel(error).catch(() => undefined);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcancel(reason) {\n\t\t\t\t\t\treturn reader.cancel(reason);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn { acknowledged: false, response: rebuildResponse(response, rebuiltBody) };\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tvoid reader.cancel().catch(() => undefined);\n\t\tthrow error;\n\t}\n\n\tconst encoded = Buffer.concat(\n\t\tchunks.map((chunk) => Buffer.from(chunk)),\n\t\tbodyBytes,\n\t);\n\tconst rebuilt = rebuildResponse(response, encoded);\n\ttry {\n\t\tconst body = JSON.parse(encoded.toString(\"utf-8\")) as unknown;\n\t\tconst acknowledged =\n\t\t\tisChunkAckBody(body) &&\n\t\t\tbody.received === true &&\n\t\t\tbody.requestId === requestId &&\n\t\t\tbody.chunkIndex === chunkIndex &&\n\t\t\tbody.totalChunks === totalChunks;\n\t\treturn acknowledged ? { acknowledged: true } : { acknowledged: false, response: rebuilt };\n\t} catch {\n\t\treturn { acknowledged: false, response: rebuilt };\n\t}\n}\n\nasync function inspectChunkResponse(\n\tresponse: Response,\n\trequestId: string,\n\tchunkIndex: number,\n\ttotalChunks: number,\n): Promise<ChunkResponseInspection> {\n\tconst marker = response.headers.get(PI_SERVER_CHUNK_ACK_HEADER);\n\tif (marker === PI_SERVER_CHUNK_FINAL_VALUE) {\n\t\treturn { acknowledged: false, response };\n\t}\n\tif (marker === PI_SERVER_CHUNK_ACK_VALUE) {\n\t\tif (!response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\tawait discardResponse(response);\n\t\t\tthrow new PiServerChunkAckProtocolError(\"pi-server chunk acknowledgement must use application/json\");\n\t\t}\n\t\tconst text = await readPiServerResponseText(response, LEGACY_CHUNK_ACK_MAX_BYTES);\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(text) as unknown;\n\t\t} catch {\n\t\t\tthrow new PiServerChunkAckProtocolError(\"pi-server chunk acknowledgement was not valid JSON\");\n\t\t}\n\t\tif (\n\t\t\t!isChunkAckBody(body) ||\n\t\t\tbody.received !== true ||\n\t\t\tbody.requestId !== requestId ||\n\t\t\tbody.chunkIndex !== chunkIndex ||\n\t\t\tbody.totalChunks !== totalChunks\n\t\t) {\n\t\t\tthrow new PiServerChunkAckProtocolError(\"pi-server chunk acknowledgement did not match its request envelope\");\n\t\t}\n\t\treturn { acknowledged: true };\n\t}\n\tif (marker !== null) {\n\t\tawait discardResponse(response);\n\t\tthrow new PiServerChunkAckProtocolError(\n\t\t\t`pi-server returned unsupported ${PI_SERVER_CHUNK_ACK_HEADER} value: ${marker}`,\n\t\t);\n\t}\n\tif (!response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\treturn { acknowledged: false, response };\n\t}\n\treturn inspectLegacyChunkAck(response, requestId, chunkIndex, totalChunks);\n}\n\nfunction getRawChunkLayout(\n\ttarget: string,\n\trequestId: string,\n\trawBodyBytes: number,\n\tmaxBytes: number,\n): { rawChunkBytes: number; totalChunks: number } {\n\tlet totalChunks = 1;\n\twhile (true) {\n\t\tconst emptyEnvelopeBytes = jsonByteLength({\n\t\t\trequestId,\n\t\t\ttarget,\n\t\t\tchunkIndex: totalChunks - 1,\n\t\t\ttotalChunks,\n\t\t\tsha256: \"0\".repeat(64),\n\t\t\tchunk: \"\",\n\t\t\tencoding: PI_SERVER_CHUNK_SEGMENT_ENCODING,\n\t\t\trawTotalBytes: rawBodyBytes,\n\t\t\t// Using the total body size here is conservative because every\n\t\t\t// derived chunk size is no larger and therefore has no more digits.\n\t\t\trawChunkBytes: rawBodyBytes,\n\t\t} satisfies ChunkBody);\n\t\tconst encodedChunkBytes = Math.floor((maxBytes - emptyEnvelopeBytes) / 4) * 4;\n\t\tconst rawChunkBytes = Math.floor(encodedChunkBytes / 4) * 3;\n\t\tif (rawChunkBytes <= 0) {\n\t\t\tthrow new Error(\"PI_CLIENT_MAX_REQUEST_KB is too small for pi-server chunk envelopes\");\n\t\t}\n\t\tconst nextTotalChunks = Math.ceil(rawBodyBytes / rawChunkBytes);\n\t\tif (nextTotalChunks > CHUNK_MAX_TOTAL_CHUNKS) {\n\t\t\tthrow new Error(`pi-server chunk request exceeds the ${CHUNK_MAX_TOTAL_CHUNKS}-chunk protocol limit`);\n\t\t}\n\t\tif (nextTotalChunks === totalChunks) {\n\t\t\treturn { rawChunkBytes, totalChunks };\n\t\t}\n\t\tif (nextTotalChunks < totalChunks) {\n\t\t\tthrow new Error(\"pi-server chunk layout did not converge monotonically\");\n\t\t}\n\t\ttotalChunks = nextTotalChunks;\n\t}\n}\n\nexport class ChunkRequest {\n\toptions: PiServerRequestOptions;\n\treadonly #chunkRequestMemos = new Map<string, ChunkRequestMemo>();\n\treadonly #maxChunkRequestMemos: number;\n\n\tconstructor(options: PiServerRequestOptions) {\n\t\tconst maxChunkRequestMemos = options.maxChunkRequestMemos ?? DEFAULT_CHUNK_REQUEST_MEMO_LIMIT;\n\t\tif (!Number.isSafeInteger(maxChunkRequestMemos) || maxChunkRequestMemos <= 0) {\n\t\t\tthrow new Error(\"maxChunkRequestMemos must be a positive safe integer\");\n\t\t}\n\t\tthis.options = options;\n\t\tthis.#maxChunkRequestMemos = maxChunkRequestMemos;\n\t}\n\n\tasync getJson(endpoint: string): Promise<Response> {\n\t\treturn this.#fetchWithResponseHeaderTimeout(endpoint, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: makeHeaders(this.options.authToken),\n\t\t});\n\t}\n\n\tasync deleteJson(endpoint: string): Promise<Response> {\n\t\treturn this.#fetchWithResponseHeaderTimeout(endpoint, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: makeHeaders(this.options.authToken),\n\t\t});\n\t}\n\n\tasync postJson(endpoint: string, body: unknown): Promise<Response> {\n\t\tconst rawBody = Buffer.from(JSON.stringify(body), \"utf-8\");\n\t\tconst memoKey = `${endpoint}\\0${sha256(rawBody)}`;\n\t\tlet memo = this.#chunkRequestMemos.get(memoKey);\n\t\tconst maxBytes = memo?.maxBytes ?? getMaxRequestBytes();\n\t\tif (memo === undefined && rawBody.byteLength <= maxBytes) {\n\t\t\treturn this.#postRawJson(endpoint, rawBody.toString(\"utf-8\"));\n\t\t}\n\n\t\tif (memo === undefined) {\n\t\t\tif (this.#chunkRequestMemos.size >= this.#maxChunkRequestMemos) {\n\t\t\t\tthrow new PiServerChunkRequestMemoLimitError(this.#maxChunkRequestMemos);\n\t\t\t}\n\t\t\tmemo = { requestId: randomUUID(), maxBytes };\n\t\t\tthis.#chunkRequestMemos.set(memoKey, memo);\n\t\t}\n\n\t\tconst { requestId } = memo;\n\t\tlet layout: { rawChunkBytes: number; totalChunks: number };\n\t\ttry {\n\t\t\tlayout = getRawChunkLayout(endpoint, requestId, rawBody.byteLength, memo.maxBytes);\n\t\t} catch (error) {\n\t\t\tif (this.#chunkRequestMemos.get(memoKey) === memo) {\n\t\t\t\tthis.#chunkRequestMemos.delete(memoKey);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet nextIndex = 0;\n\t\tlet finalResponse: Response | undefined;\n\t\tlet transientFailureResponse: Response | undefined;\n\t\tlet fatalError: unknown;\n\n\t\tconst stopped = () => finalResponse !== undefined || fatalError !== undefined;\n\t\tconst replaceTransientFailureResponse = async (response: Response): Promise<void> => {\n\t\t\tconst previous = transientFailureResponse;\n\t\t\ttransientFailureResponse = response;\n\t\t\tif (previous !== response) await discardResponse(previous);\n\t\t};\n\n\t\tconst uploadChunk = async (index: number): Promise<void> => {\n\t\t\tconst start = index * layout.rawChunkBytes;\n\t\t\tconst chunk = rawBody\n\t\t\t\t.subarray(start, Math.min(start + layout.rawChunkBytes, rawBody.byteLength))\n\t\t\t\t.toString(\"base64\");\n\t\t\tlet lastError: unknown;\n\t\t\tlet lastTransientResponse: Response | undefined;\n\n\t\t\ttry {\n\t\t\t\tfor (let attempt = 0; attempt <= CHUNK_UPLOAD_RETRY_DELAYS_MS.length; attempt++) {\n\t\t\t\t\tif (stopped()) return;\n\t\t\t\t\tif (attempt > 0) {\n\t\t\t\t\t\tawait waitForChunkRetry(CHUNK_UPLOAD_RETRY_DELAYS_MS[attempt - 1], this.options.signal);\n\t\t\t\t\t\tif (stopped()) return;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst chunkBody: ChunkBody = {\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t\ttarget: endpoint,\n\t\t\t\t\t\tchunkIndex: index,\n\t\t\t\t\t\ttotalChunks: layout.totalChunks,\n\t\t\t\t\t\tsha256: sha256(chunk),\n\t\t\t\t\t\tchunk,\n\t\t\t\t\t\tencoding: PI_SERVER_CHUNK_SEGMENT_ENCODING,\n\t\t\t\t\t\trawTotalBytes: rawBody.byteLength,\n\t\t\t\t\t\trawChunkBytes: layout.rawChunkBytes,\n\t\t\t\t\t};\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet response = await this.#postRawJson(CHUNK_ENDPOINT, JSON.stringify(chunkBody));\n\t\t\t\t\t\tif (stopped()) {\n\t\t\t\t\t\t\tawait discardResponse(response);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\t\tconst inspection = await inspectChunkResponse(response, requestId, index, layout.totalChunks);\n\t\t\t\t\t\t\tif (inspection.acknowledged) return;\n\t\t\t\t\t\t\tif (!inspection.response) {\n\t\t\t\t\t\t\t\tthrow new PiServerChunkAckProtocolError(\n\t\t\t\t\t\t\t\t\t\"pi-server chunk response inspection lost its response\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresponse = inspection.response;\n\t\t\t\t\t\t\tif (stopped()) {\n\t\t\t\t\t\t\t\tawait discardResponse(response);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isTransientChunkResponse(response.status)) {\n\t\t\t\t\t\t\tawait discardResponse(lastTransientResponse);\n\t\t\t\t\t\t\tlastTransientResponse = response;\n\t\t\t\t\t\t\tlastError = new Error(\n\t\t\t\t\t\t\t\t`pi-server chunk ${index + 1}/${layout.totalChunks} returned HTTP ${response.status}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (finalResponse === undefined && fatalError === undefined) {\n\t\t\t\t\t\t\tfinalResponse = response;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait discardResponse(response);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (this.options.signal?.aborted) {\n\t\t\t\t\t\t\tthrow this.options.signal.reason ?? error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\terror instanceof PiServerChunkAckProtocolError ||\n\t\t\t\t\t\t\terror instanceof PiServerTransportBodyLimitError\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tfatalError = error;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastError = error;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (lastTransientResponse !== undefined) {\n\t\t\t\t\tawait replaceTransientFailureResponse(lastTransientResponse);\n\t\t\t\t\tlastTransientResponse = undefined;\n\t\t\t\t}\n\t\t\t\tif (lastError instanceof Error) {\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t\tthrow new Error(`pi-server chunk ${index + 1}/${layout.totalChunks} failed after bounded retries`);\n\t\t\t} finally {\n\t\t\t\tif (stopped()) await discardResponse(lastTransientResponse);\n\t\t\t}\n\t\t};\n\n\t\tconst uploadWorker = async (): Promise<void> => {\n\t\t\twhile (!stopped()) {\n\t\t\t\tconst index = nextIndex;\n\t\t\t\tif (index >= layout.totalChunks) return;\n\t\t\t\tnextIndex++;\n\t\t\t\tawait uploadChunk(index);\n\t\t\t}\n\t\t};\n\n\t\tconst results = await Promise.allSettled(\n\t\t\tArray.from({ length: Math.min(CHUNK_UPLOAD_CONCURRENCY, layout.totalChunks) }, () => uploadWorker()),\n\t\t);\n\n\t\tif (fatalError !== undefined) {\n\t\t\tawait discardResponse(finalResponse);\n\t\t\tawait discardResponse(transientFailureResponse);\n\t\t\tthrow fatalError;\n\t\t}\n\t\tif (this.options.signal?.aborted) {\n\t\t\tawait discardResponse(finalResponse);\n\t\t\tawait discardResponse(transientFailureResponse);\n\t\t\tthrow this.options.signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n\t\t}\n\t\tif (finalResponse !== undefined) {\n\t\t\tawait discardResponse(transientFailureResponse);\n\t\t\tif (this.#chunkRequestMemos.get(memoKey) === memo) {\n\t\t\t\tthis.#chunkRequestMemos.delete(memoKey);\n\t\t\t}\n\t\t\treturn finalResponse;\n\t\t}\n\t\tif (transientFailureResponse !== undefined) {\n\t\t\treturn transientFailureResponse;\n\t\t}\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") {\n\t\t\t\tthrow result.reason;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"No final chunk response received from pi-server\");\n\t}\n\n\tasync #postRawJson(endpoint: string, rawJson: string): Promise<Response> {\n\t\treturn this.#fetchWithResponseHeaderTimeout(endpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: makeHeaders(this.options.authToken),\n\t\t\tbody: rawJson,\n\t\t});\n\t}\n\n\tasync #fetchWithResponseHeaderTimeout(endpoint: string, init: RequestInit): Promise<Response> {\n\t\tconst timeoutMs = this.options.responseHeaderTimeoutMs ?? PI_SERVER_RESPONSE_HEADER_TIMEOUT_MS;\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\t\tthrow new Error(\"responseHeaderTimeoutMs must be a positive finite number\");\n\t\t}\n\n\t\tconst method = init.method ?? \"GET\";\n\t\tconst timeoutError = new PiServerTransportHeaderTimeoutError(method, endpoint, timeoutMs);\n\t\tconst timeoutController = new AbortController();\n\t\tconst signal = this.options.signal\n\t\t\t? AbortSignal.any([this.options.signal, timeoutController.signal])\n\t\t\t: timeoutController.signal;\n\t\tconst timeout = setTimeout(() => {\n\t\t\ttimeoutController.abort(timeoutError);\n\t\t}, timeoutMs);\n\t\ttimeout.unref();\n\n\t\ttry {\n\t\t\treturn await fetch(`${this.options.serverUrl}${endpoint}`, {\n\t\t\t\t...init,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (timeoutController.signal.aborted && !this.options.signal?.aborted) {\n\t\t\t\tthrow timeoutError;\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pi-server-request.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-request.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,sBAAsB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAsBD,wBAAgB,kBAAkB,IAAI,MAAM,CAS3C;AAwFD,qBAAa,YAAY;;IACxB,OAAO,EAAE,sBAAsB,CAAC;IAEhC,YAAY,OAAO,EAAE,sBAAsB,EAE1C;IAEK,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAMjD;IAEK,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgDjE;CAUD","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst DEFAULT_MAX_REQUEST_KB = 512;\nconst CHUNK_ENDPOINT = \"/api/request/chunk\";\nconst CHUNK_UPLOAD_CONCURRENCY = 4;\n\nexport interface PiServerRequestOptions {\n\tserverUrl: string;\n\tauthToken: string;\n\tsignal?: AbortSignal;\n}\n\ninterface ChunkBody {\n\trequestId: string;\n\ttarget: string;\n\tchunkIndex: number;\n\ttotalChunks: number;\n\tsha256: string;\n\tchunk: string;\n}\n\ninterface ChunkAckBody {\n\treceived: unknown;\n\trequestId: unknown;\n\tchunkIndex: unknown;\n\ttotalChunks: unknown;\n}\n\nfunction jsonByteLength(value: unknown): number {\n\treturn Buffer.byteLength(JSON.stringify(value), \"utf-8\");\n}\n\nexport function getMaxRequestBytes(): number {\n\tconst raw = process.env.PI_CLIENT_MAX_REQUEST_KB;\n\tif (raw === undefined || raw === \"\") return DEFAULT_MAX_REQUEST_KB * 1024;\n\n\tconst value = Number(raw);\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(\"PI_CLIENT_MAX_REQUEST_KB must be a positive number\");\n\t}\n\treturn Math.floor(value * 1024);\n}\n\nfunction makeHeaders(authToken: string): Record<string, string> {\n\treturn {\n\t\t\"Content-Type\": \"application/json\",\n\t\t...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n\t};\n}\n\nfunction sha256(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isChunkAckBody(value: unknown): value is ChunkAckBody {\n\treturn (\n\t\tisRecord(value) && \"received\" in value && \"requestId\" in value && \"chunkIndex\" in value && \"totalChunks\" in value\n\t);\n}\n\nasync function isChunkAck(\n\tresponse: Response,\n\trequestId: string,\n\tchunkIndex: number,\n\ttotalChunks: number,\n): Promise<boolean> {\n\tif (!response.headers.get(\"Content-Type\")?.includes(\"application/json\")) return false;\n\ttry {\n\t\tconst body = (await response.clone().json()) as unknown;\n\t\treturn (\n\t\t\tisChunkAckBody(body) &&\n\t\t\tbody.received === true &&\n\t\t\tbody.requestId === requestId &&\n\t\t\tbody.chunkIndex === chunkIndex &&\n\t\t\tbody.totalChunks === totalChunks\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction chunkBodyFits(\n\ttarget: string,\n\trequestId: string,\n\tencodedLength: number,\n\tchunkLength: number,\n\tmaxBytes: number,\n): boolean {\n\tconst total = Math.ceil(encodedLength / chunkLength);\n\tconst body: ChunkBody = {\n\t\trequestId,\n\t\ttarget,\n\t\tchunkIndex: Math.max(0, total - 1),\n\t\ttotalChunks: total,\n\t\tsha256: \"0\".repeat(64),\n\t\tchunk: \"x\".repeat(Math.min(chunkLength, encodedLength)),\n\t};\n\treturn jsonByteLength(body) <= maxBytes;\n}\n\nfunction splitEncodedBody(target: string, requestId: string, encoded: string, maxBytes: number): string[] {\n\tif (!chunkBodyFits(target, requestId, encoded.length, 1, maxBytes)) {\n\t\tthrow new Error(\"PI_CLIENT_MAX_REQUEST_KB is too small for pi-server chunk envelopes\");\n\t}\n\n\tlet low = 1;\n\tlet high = encoded.length;\n\tlet best = 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (chunkBodyFits(target, requestId, encoded.length, mid, maxBytes)) {\n\t\t\tbest = mid;\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid - 1;\n\t\t}\n\t}\n\n\tconst chunks: string[] = [];\n\tfor (let offset = 0; offset < encoded.length; offset += best) {\n\t\tchunks.push(encoded.slice(offset, offset + best));\n\t}\n\treturn chunks;\n}\n\nexport class ChunkRequest {\n\toptions: PiServerRequestOptions;\n\n\tconstructor(options: PiServerRequestOptions) {\n\t\tthis.options = options;\n\t}\n\n\tasync getJson(endpoint: string): Promise<Response> {\n\t\treturn fetch(`${this.options.serverUrl}${endpoint}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: makeHeaders(this.options.authToken),\n\t\t\tsignal: this.options.signal,\n\t\t});\n\t}\n\n\tasync postJson(endpoint: string, body: unknown): Promise<Response> {\n\t\tconst rawJson = JSON.stringify(body);\n\t\tconst maxBytes = getMaxRequestBytes();\n\t\tif (Buffer.byteLength(rawJson, \"utf-8\") <= maxBytes) {\n\t\t\treturn this.#postRawJson(endpoint, rawJson);\n\t\t}\n\n\t\tconst requestId = randomUUID();\n\t\tconst encoded = Buffer.from(rawJson, \"utf-8\").toString(\"base64\");\n\t\tconst chunks = splitEncodedBody(endpoint, requestId, encoded, maxBytes);\n\t\tlet nextIndex = 0;\n\t\tlet finalResponse: Response | undefined;\n\t\tlet failureResponse: Response | undefined;\n\n\t\tconst uploadWorker = async (): Promise<void> => {\n\t\t\twhile (nextIndex < chunks.length && finalResponse === undefined && failureResponse === undefined) {\n\t\t\t\tconst index = nextIndex;\n\t\t\t\tnextIndex++;\n\t\t\t\tconst chunk = chunks[index];\n\t\t\t\tconst chunkBody: ChunkBody = {\n\t\t\t\t\trequestId,\n\t\t\t\t\ttarget: endpoint,\n\t\t\t\t\tchunkIndex: index,\n\t\t\t\t\ttotalChunks: chunks.length,\n\t\t\t\t\tsha256: sha256(chunk),\n\t\t\t\t\tchunk,\n\t\t\t\t};\n\t\t\t\tconst response = await this.#postRawJson(CHUNK_ENDPOINT, JSON.stringify(chunkBody));\n\t\t\t\tif (finalResponse !== undefined || failureResponse !== undefined) return;\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tfailureResponse = response;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!(await isChunkAck(response, requestId, index, chunks.length))) {\n\t\t\t\t\tfinalResponse = response;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tawait Promise.all(\n\t\t\tArray.from({ length: Math.min(CHUNK_UPLOAD_CONCURRENCY, chunks.length) }, () => uploadWorker()),\n\t\t);\n\n\t\tif (failureResponse) return failureResponse;\n\t\tif (finalResponse) return finalResponse;\n\n\t\tthrow new Error(\"No final chunk response received from pi-server\");\n\t}\n\n\tasync #postRawJson(endpoint: string, rawJson: string): Promise<Response> {\n\t\treturn fetch(`${this.options.serverUrl}${endpoint}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: makeHeaders(this.options.authToken),\n\t\t\tbody: rawJson,\n\t\t\tsignal: this.options.signal,\n\t\t});\n\t}\n}\n"]}
|