@averyyy/pi-coding-agent 1.4.0-piclient.16 → 1.4.0-piclient.18
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/dist/bundle/chunks/{anthropic-messages-RTMTRCJD.js → anthropic-messages-QGSJXRQY.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-32IFXADQ.js → azure-openai-responses-KTGSBDCI.js} +1 -1
- package/dist/bundle/chunks/{chunk-7TZ46DX3.js → chunk-4G2HOZFC.js} +1 -1
- package/dist/bundle/chunks/{chunk-PQ65VYIJ.js → chunk-7ZWG2VLP.js} +1 -1
- package/dist/bundle/chunks/{chunk-3W4ECU36.js → chunk-DLIY7H4U.js} +1 -1
- package/dist/bundle/chunks/{chunk-RA32KT4S.js → chunk-F5TPA3TT.js} +1 -1
- package/dist/bundle/chunks/{chunk-ULEDFAAS.js → chunk-MEITEFTF.js} +1 -1
- package/dist/bundle/chunks/{chunk-NIXXKXME.js → chunk-PMRZTEST.js} +1 -1
- package/dist/bundle/chunks/{chunk-RSPBBB2E.js → chunk-WYPX6IZ6.js} +5 -5
- package/dist/bundle/chunks/{chunk-QTBWPXJ6.js → chunk-ZJUPP73W.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-SHFSUL5R.js → cloudflare-workers-ai-system-one-POXEFIVK.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-4X76WNE7.js → google-generative-ai-B5QUNJHX.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-EXVYF56Z.js → google-vertex-FOZO2INS.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-WQWSUHPM.js → mistral-conversations-QF5Y2MYX.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-HUGPPMN4.js → openai-codex-responses-KW7Q2ZLI.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-VKJKJ3X3.js → openai-completions-VYCCVND3.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-D4KWSP7Z.js → openai-decisions-YYEYHJVD.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-SYCUDQZV.js → openai-responses-TYAD6CWK.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-J55G2O6T.js → typesafe-system-one-LC3TLMBU.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-S2BCYRZG.js → virtual-modules-UGFKDWP5.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/pi-server-request.d.ts +1 -1
- package/dist/core/pi-server-request.d.ts.map +1 -1
- package/dist/core/pi-server-request.js +2 -2
- package/dist/core/pi-server-request.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +3 -2
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +30 -15
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/package.json +4 -4
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-
|
|
2
|
+
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-PMRZTEST.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-WYPX6IZ6.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatReadLineRange,formatSize,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-BRYV63PL.js";import{ArminComponent}from"./chunks/chunk-3EGEEHMN.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-H2UJDH5M.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-PG7P2LUM.js";import{readStoredCredential}from"./chunks/chunk-VYYRESZJ.js";import{getShellConfig}from"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-4G2HOZFC.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-ZADMB3XG.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatReadLineRange,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-WYPX6IZ6.js";import"./chunks/chunk-BRYV63PL.js";import"./chunks/chunk-3EGEEHMN.js";import"./chunks/chunk-H2UJDH5M.js";import"./chunks/chunk-PG7P2LUM.js";import"./chunks/chunk-VYYRESZJ.js";import"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-4G2HOZFC.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-ZADMB3XG.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
@@ -8,7 +8,7 @@ export declare class ChunkRequest {
|
|
|
8
8
|
#private;
|
|
9
9
|
options: PiServerRequestOptions;
|
|
10
10
|
constructor(options: PiServerRequestOptions);
|
|
11
|
-
getJson(endpoint: string): Promise<Response>;
|
|
11
|
+
getJson(endpoint: string, headers?: Record<string, string>): Promise<Response>;
|
|
12
12
|
postJson(endpoint: string, body: unknown): Promise<Response>;
|
|
13
13
|
}
|
|
14
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":"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,
|
|
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,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAMnF;IAEK,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgDjE;CAUD"}
|
|
@@ -86,10 +86,10 @@ export class ChunkRequest {
|
|
|
86
86
|
constructor(options) {
|
|
87
87
|
this.options = options;
|
|
88
88
|
}
|
|
89
|
-
async getJson(endpoint) {
|
|
89
|
+
async getJson(endpoint, headers) {
|
|
90
90
|
return fetch(`${this.options.serverUrl}${endpoint}`, {
|
|
91
91
|
method: "GET",
|
|
92
|
-
headers: makeHeaders(this.options.authToken),
|
|
92
|
+
headers: { ...makeHeaders(this.options.authToken), ...headers },
|
|
93
93
|
signal: this.options.signal,
|
|
94
94
|
});
|
|
95
95
|
}
|
|
@@ -1 +1 @@
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AED,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,OAAe;QACnD,OAAO,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,GAAG,QAAQ,EAAE,EAAE;YACpD,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;YAC5C,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM;SAC3B,CAAC,CAAC;IACJ,CAAC;CACD","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"]}
|
|
1
|
+
{"version":3,"file":"pi-server-request.js","sourceRoot":"","sources":["../../src/core/pi-server-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAwBnC,SAAS,cAAc,CAAC,KAAc;IACrC,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,kBAAkB;IACjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC;IACjD,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,EAAE;QAA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;oBAAE,OAAO;gBACzE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;oBAClB,eAAe,GAAG,QAAQ,CAAC;oBAC3B,OAAO;gBACR,CAAC;gBACD,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;oBACpE,aAAa,GAAG,QAAQ,CAAC;oBACzB,OAAO;gBACR,CAAC;YACF,CAAC;QACF,CAAC,CAAC;QAEF,MAAM,OAAO,CAAC,GAAG,CAChB,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,wBAAwB,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,CAC/F,CAAC;QAEF,IAAI,eAAe;YAAE,OAAO,eAAe,CAAC;QAC5C,IAAI,aAAa;YAAE,OAAO,aAAa,CAAC;QAExC,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACpE,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,OAAe;QACnD,OAAO,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,GAAG,QAAQ,EAAE,EAAE;YACpD,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;YAC5C,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM;SAC3B,CAAC,CAAC;IACJ,CAAC;CACD","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, headers?: Record<string, string>): Promise<Response> {\n\t\treturn fetch(`${this.options.serverUrl}${endpoint}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { ...makeHeaders(this.options.authToken), ...headers },\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"]}
|
|
@@ -12,8 +12,9 @@ export type PersonalizeCatalog = (catalog: readonly AnyModel[], context: Refresh
|
|
|
12
12
|
/** Add a persisted pi.dev catalog overlay to a static built-in provider. */
|
|
13
13
|
export declare function withRemoteCatalog(provider: Provider, catalogBaseUrl?: string, localGeneratedAt?: number): Provider;
|
|
14
14
|
/**
|
|
15
|
-
* Like `withRemoteCatalog`, but on each network refresh the catalog
|
|
16
|
-
*
|
|
15
|
+
* Like `withRemoteCatalog`, but on each network refresh the catalog is passed through `personalize`
|
|
16
|
+
* and the result is saved. Server catalogs overlay built-in models regardless of generation time;
|
|
17
|
+
* local Pi applies only newer pi.dev catalogs. The saved entry holds
|
|
17
18
|
* the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.
|
|
18
19
|
* The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an
|
|
19
20
|
* empty catalog saved by an older pi after a failed or missing pi.dev catalog) falls back to the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-catalog-provider.d.ts","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EAIb,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"remote-catalog-provider.d.ts","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EAIb,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,MAAM,uBAAuB,CAAC;AAQ/B,eAAO,MAAM,kCAAkC,QAAqB,CAAC;AACrE;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,SAAS,EAAoC,CAAC;AAqFhG,kEAAkE;AAClE,MAAM,MAAM,kBAAkB,GAAG,CAChC,OAAO,EAAE,SAAS,QAAQ,EAAE,EAC5B,OAAO,EAAE,oBAAoB,KACzB,OAAO,CAAC,SAAS,QAAQ,EAAE,CAAC,CAAC;AAElC,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CAgFV;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CACtC,QAAQ,EAAE,QAAQ,EAClB,WAAW,EAAE,kBAAkB,EAC/B,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CA6CV"}
|
|
@@ -2,6 +2,7 @@ import { getModelType, isModelType, } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import { VERSION } from "../config.js";
|
|
3
3
|
import { fetchWithRetry } from "../utils/management-http.js";
|
|
4
4
|
import { getPiUserAgent } from "../utils/pi-user-agent.js";
|
|
5
|
+
import { ChunkRequest } from "./pi-server-request.js";
|
|
5
6
|
const DEFAULT_CATALOG_BASE_URL = "https://pi.dev";
|
|
6
7
|
const REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;
|
|
7
8
|
export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
|
@@ -53,7 +54,14 @@ function isNewer(lastModified, localGeneratedAt) {
|
|
|
53
54
|
function remoteModels(entry, localGeneratedAt) {
|
|
54
55
|
return entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];
|
|
55
56
|
}
|
|
56
|
-
function requestCatalog(providerId, catalogBaseUrl, signal, validator) {
|
|
57
|
+
function requestCatalog(providerId, catalogBaseUrl, signal, validator, force) {
|
|
58
|
+
if (process.env.PI_SERVER_MODE === "true") {
|
|
59
|
+
return new ChunkRequest({
|
|
60
|
+
serverUrl: process.env.PI_SERVER_URL ?? "http://127.0.0.1:4217",
|
|
61
|
+
authToken: process.env.PI_SERVER_AUTH_TOKEN ?? "",
|
|
62
|
+
signal,
|
|
63
|
+
}).getJson(`/api/model-catalog/providers/${encodeURIComponent(providerId)}?pi-version=${encodeURIComponent(VERSION)}${force ? "&force=true" : ""}`, validator ? { "if-none-match": validator } : undefined);
|
|
64
|
+
}
|
|
57
65
|
const url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);
|
|
58
66
|
url.searchParams.set("types", REMOTE_CATALOG_MODEL_TYPES.join(","));
|
|
59
67
|
return fetchWithRetry(url, {
|
|
@@ -67,6 +75,7 @@ function requestCatalog(providerId, catalogBaseUrl, signal, validator) {
|
|
|
67
75
|
}
|
|
68
76
|
/** Add a persisted pi.dev catalog overlay to a static built-in provider. */
|
|
69
77
|
export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
|
|
78
|
+
const catalogGeneratedAt = process.env.PI_SERVER_MODE === "true" ? undefined : localGeneratedAt;
|
|
70
79
|
let dynamicModels = [];
|
|
71
80
|
return {
|
|
72
81
|
...provider,
|
|
@@ -75,7 +84,7 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
75
84
|
getAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),
|
|
76
85
|
refreshModels: async (context) => {
|
|
77
86
|
const stored = context.stored;
|
|
78
|
-
const restored = remoteModels(stored,
|
|
87
|
+
const restored = remoteModels(stored, catalogGeneratedAt).filter((model) => model.provider === provider.id);
|
|
79
88
|
if (!(await context.publish({
|
|
80
89
|
update: () => {
|
|
81
90
|
dynamicModels = restored;
|
|
@@ -88,7 +97,8 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
88
97
|
// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.
|
|
89
98
|
// An entry without lastModified (saved by an older pi, or after a failed first request) is
|
|
90
99
|
// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.
|
|
91
|
-
if (
|
|
100
|
+
if (process.env.PI_SERVER_MODE !== "true" &&
|
|
101
|
+
!context.force &&
|
|
92
102
|
stored?.checkedAt !== undefined &&
|
|
93
103
|
stored.lastModified !== undefined &&
|
|
94
104
|
Date.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS) {
|
|
@@ -97,7 +107,7 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
97
107
|
// Only revalidate when a cached body backs the validator, so a 304 can never
|
|
98
108
|
// leave the overlay empty.
|
|
99
109
|
const validator = stored && stored.models.length > 0 ? stored.etag : undefined;
|
|
100
|
-
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);
|
|
110
|
+
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator, context.force);
|
|
101
111
|
if (context.signal.aborted)
|
|
102
112
|
return;
|
|
103
113
|
const checkedAt = Date.now();
|
|
@@ -107,7 +117,7 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
107
117
|
await context.publish({ persist: { ...stored, checkedAt } });
|
|
108
118
|
return;
|
|
109
119
|
}
|
|
110
|
-
if (response.status === 404 || response.status === 501) {
|
|
120
|
+
if (process.env.PI_SERVER_MODE !== "true" && (response.status === 404 || response.status === 501)) {
|
|
111
121
|
await context.publish({
|
|
112
122
|
persist: {
|
|
113
123
|
...(stored ?? { models: [] }),
|
|
@@ -118,16 +128,17 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
118
128
|
});
|
|
119
129
|
return;
|
|
120
130
|
}
|
|
121
|
-
if (!response.ok) {
|
|
131
|
+
if (!response.ok || (process.env.PI_SERVER_MODE === "true" && response.status !== 200)) {
|
|
122
132
|
// Transient failure: the cached body and its validator stay valid, so keep the
|
|
123
133
|
// etag and let the next refresh revalidate instead of downloading the catalog.
|
|
124
|
-
|
|
134
|
+
const source = process.env.PI_SERVER_MODE === "true" ? "pi-server model catalog" : "Model catalog";
|
|
135
|
+
throw new Error(`${source} request failed for ${provider.id}: ${response.status}`);
|
|
125
136
|
}
|
|
126
137
|
const catalog = await readCatalog(provider.id, response);
|
|
127
138
|
if (context.signal.aborted)
|
|
128
139
|
return;
|
|
129
140
|
const entry = { ...catalog, checkedAt };
|
|
130
|
-
const published = remoteModels(entry,
|
|
141
|
+
const published = remoteModels(entry, catalogGeneratedAt);
|
|
131
142
|
await context.publish({
|
|
132
143
|
persist: entry,
|
|
133
144
|
update: () => {
|
|
@@ -138,14 +149,16 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
138
149
|
};
|
|
139
150
|
}
|
|
140
151
|
/**
|
|
141
|
-
* Like `withRemoteCatalog`, but on each network refresh the catalog
|
|
142
|
-
*
|
|
152
|
+
* Like `withRemoteCatalog`, but on each network refresh the catalog is passed through `personalize`
|
|
153
|
+
* and the result is saved. Server catalogs overlay built-in models regardless of generation time;
|
|
154
|
+
* local Pi applies only newer pi.dev catalogs. The saved entry holds
|
|
143
155
|
* the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.
|
|
144
156
|
* The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an
|
|
145
157
|
* empty catalog saved by an older pi after a failed or missing pi.dev catalog) falls back to the
|
|
146
158
|
* built-in models.
|
|
147
159
|
*/
|
|
148
160
|
export function withPersonalizedCatalog(provider, personalize, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
|
|
161
|
+
const catalogGeneratedAt = process.env.PI_SERVER_MODE === "true" ? undefined : localGeneratedAt;
|
|
149
162
|
let personalModels = [];
|
|
150
163
|
const builtinModels = () => provider.getAllModels?.() ?? provider.getModels();
|
|
151
164
|
const getAllModels = () => (personalModels.length > 0 ? personalModels : builtinModels());
|
|
@@ -165,15 +178,17 @@ export function withPersonalizedCatalog(provider, personalize, catalogBaseUrl =
|
|
|
165
178
|
}
|
|
166
179
|
if (!context.allowNetwork || context.signal.aborted)
|
|
167
180
|
return;
|
|
168
|
-
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);
|
|
181
|
+
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, undefined, context.force);
|
|
169
182
|
if (context.signal.aborted)
|
|
170
183
|
return;
|
|
171
184
|
let remote = [];
|
|
172
|
-
if (response.status !== 404 && response.status !== 501) {
|
|
173
|
-
if (!response.ok)
|
|
174
|
-
|
|
185
|
+
if (process.env.PI_SERVER_MODE === "true" || (response.status !== 404 && response.status !== 501)) {
|
|
186
|
+
if (!response.ok || (process.env.PI_SERVER_MODE === "true" && response.status !== 200)) {
|
|
187
|
+
const source = process.env.PI_SERVER_MODE === "true" ? "pi-server model catalog" : "Model catalog";
|
|
188
|
+
throw new Error(`${source} request failed for ${provider.id}: ${response.status}`);
|
|
189
|
+
}
|
|
175
190
|
const catalog = await readCatalog(provider.id, response);
|
|
176
|
-
if (isNewer(catalog.lastModified,
|
|
191
|
+
if (isNewer(catalog.lastModified, catalogGeneratedAt))
|
|
177
192
|
remote = catalog.models;
|
|
178
193
|
}
|
|
179
194
|
const personalized = await personalize(mergeModels(builtinModels(), remote), context);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,EACZ,WAAW,GAKX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AA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EAAE,CAAC;gBACxD,IAAI,CAAC,QAAQ,CAAC,EAAE;oBAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,QAAQ,CAAC,EAAE,KAAK,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBACzG,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;gBACzD,IAAI,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,gBAAgB,CAAC;oBAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;YAC9E,CAAC;YACD,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,WAAW,CAAC,aAAa,EAAE,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;YACtF,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;gBACxD,MAAM,EAAE,GAAG,EAAE;oBACZ,cAAc,GAAG,YAAY,CAAC;gBAC/B,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\tgetModelType,\n\tisModelType,\n\ttype ModelsStoreEntry,\n\ttype ModelType,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { VERSION } from \"../config.ts\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\n/** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */\nasync function readCatalog(\n\tproviderId: string,\n\tresponse: Response,\n): Promise<{ models: AnyModel[]; lastModified: number; etag: string | undefined }> {\n\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\treturn {\n\t\tmodels: parseCatalog(providerId, await response.json()),\n\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t};\n}\n\n/** Whether a pi.dev catalog is newer than the model data shipped with pi. */\nfunction isNewer(lastModified: number | undefined, localGeneratedAt: number | undefined): boolean {\n\treturn localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\treturn entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];\n}\n\nfunction requestCatalog(\n\tproviderId: string,\n\tcatalogBaseUrl: string,\n\tsignal: AbortSignal,\n\tvalidator?: string,\n): Promise<Response> {\n\tconst url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);\n\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\treturn fetchWithRetry(\n\t\turl,\n\t\t{\n\t\t\theaders: {\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t},\n\t\t\tsignal,\n\t\t},\n\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t);\n}\n\n/** Replaces the catalog with a credential-specific model list. */\nexport type PersonalizeCatalog = (\n\tcatalog: readonly AnyModel[],\n\tcontext: RefreshModelsContext,\n) => Promise<readonly AnyModel[]>;\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tmodelCatalogAuth: \"none\",\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, localGeneratedAt).filter((model) => model.provider === provider.id);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.\n\t\t\t// An entry without lastModified (saved by an older pi, or after a failed first request) is\n\t\t\t// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.\n\t\t\tif (\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = { ...catalog, checkedAt };\n\t\t\tconst published = remoteModels(entry, localGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer\n * pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds\n * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.\n * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an\n * empty catalog saved by an older pi after a failed or missing pi.dev catalog) falls back to the\n * built-in models.\n */\nexport function withPersonalizedCatalog(\n\tprovider: Provider,\n\tpersonalize: PersonalizeCatalog,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet personalModels: readonly AnyModel[] = [];\n\tconst builtinModels = (): readonly AnyModel[] => provider.getAllModels?.() ?? provider.getModels();\n\tconst getAllModels = (): readonly AnyModel[] => (personalModels.length > 0 ? personalModels : builtinModels());\n\n\treturn {\n\t\t...provider,\n\t\tmodelCatalogAuth: \"provider\",\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels: async (context) => {\n\t\t\tconst restored = (context.stored?.models ?? []).filter((model) => model.provider === provider.id);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tpersonalModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tlet remote: readonly AnyModel[] = [];\n\t\t\tif (response.status !== 404 && response.status !== 501) {\n\t\t\t\tif (!response.ok) throw new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\t\tif (isNewer(catalog.lastModified, localGeneratedAt)) remote = catalog.models;\n\t\t\t}\n\t\t\tconst personalized = await personalize(mergeModels(builtinModels(), remote), context);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: personalized, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tpersonalModels = personalized;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,EACZ,WAAW,GAKX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACrE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAyB,CAAC,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;AAEhG,SAAS,oBAAoB,CAAC,KAAyB;IACtD,OAAO,CAC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C,CAAC,yBAAyB,CAAC,CAAC,CAAC,eAAe,CAAC;oBACnG,MAAM,IAAI,KAAK,CAAC,GAAG,MAAM,uBAAuB,QAAQ,CAAC,EAAE,KAAK,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBACpF,CAAC;gBACD,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;gBACzD,IAAI,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,kBAAkB,CAAC;oBAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;YAChF,CAAC;YACD,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,WAAW,CAAC,aAAa,EAAE,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;YACtF,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;gBACxD,MAAM,EAAE,GAAG,EAAE;oBACZ,cAAc,GAAG,YAAY,CAAC;gBAC/B,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\tgetModelType,\n\tisModelType,\n\ttype ModelsStoreEntry,\n\ttype ModelType,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { VERSION } from \"../config.ts\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { ChunkRequest } from \"./pi-server-request.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\n/** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */\nasync function readCatalog(\n\tproviderId: string,\n\tresponse: Response,\n): Promise<{ models: AnyModel[]; lastModified: number; etag: string | undefined }> {\n\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\treturn {\n\t\tmodels: parseCatalog(providerId, await response.json()),\n\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t};\n}\n\n/** Whether a pi.dev catalog is newer than the model data shipped with pi. */\nfunction isNewer(lastModified: number | undefined, localGeneratedAt: number | undefined): boolean {\n\treturn localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\treturn entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];\n}\n\nfunction requestCatalog(\n\tproviderId: string,\n\tcatalogBaseUrl: string,\n\tsignal: AbortSignal,\n\tvalidator?: string,\n\tforce?: boolean,\n): Promise<Response> {\n\tif (process.env.PI_SERVER_MODE === \"true\") {\n\t\treturn new ChunkRequest({\n\t\t\tserverUrl: process.env.PI_SERVER_URL ?? \"http://127.0.0.1:4217\",\n\t\t\tauthToken: process.env.PI_SERVER_AUTH_TOKEN ?? \"\",\n\t\t\tsignal,\n\t\t}).getJson(\n\t\t\t`/api/model-catalog/providers/${encodeURIComponent(providerId)}?pi-version=${encodeURIComponent(VERSION)}${force ? \"&force=true\" : \"\"}`,\n\t\t\tvalidator ? { \"if-none-match\": validator } : undefined,\n\t\t);\n\t}\n\tconst url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);\n\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\treturn fetchWithRetry(\n\t\turl,\n\t\t{\n\t\t\theaders: {\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t},\n\t\t\tsignal,\n\t\t},\n\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t);\n}\n\n/** Replaces the catalog with a credential-specific model list. */\nexport type PersonalizeCatalog = (\n\tcatalog: readonly AnyModel[],\n\tcontext: RefreshModelsContext,\n) => Promise<readonly AnyModel[]>;\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst catalogGeneratedAt = process.env.PI_SERVER_MODE === \"true\" ? undefined : localGeneratedAt;\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tmodelCatalogAuth: \"none\",\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, catalogGeneratedAt).filter((model) => model.provider === provider.id);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.\n\t\t\t// An entry without lastModified (saved by an older pi, or after a failed first request) is\n\t\t\t// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.\n\t\t\tif (\n\t\t\t\tprocess.env.PI_SERVER_MODE !== \"true\" &&\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator, context.force);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (process.env.PI_SERVER_MODE !== \"true\" && (response.status === 404 || response.status === 501)) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok || (process.env.PI_SERVER_MODE === \"true\" && response.status !== 200)) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tconst source = process.env.PI_SERVER_MODE === \"true\" ? \"pi-server model catalog\" : \"Model catalog\";\n\t\t\t\tthrow new Error(`${source} request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = { ...catalog, checkedAt };\n\t\t\tconst published = remoteModels(entry, catalogGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * Like `withRemoteCatalog`, but on each network refresh the catalog is passed through `personalize`\n * and the result is saved. Server catalogs overlay built-in models regardless of generation time;\n * local Pi applies only newer pi.dev catalogs. The saved entry holds\n * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.\n * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an\n * empty catalog saved by an older pi after a failed or missing pi.dev catalog) falls back to the\n * built-in models.\n */\nexport function withPersonalizedCatalog(\n\tprovider: Provider,\n\tpersonalize: PersonalizeCatalog,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst catalogGeneratedAt = process.env.PI_SERVER_MODE === \"true\" ? undefined : localGeneratedAt;\n\tlet personalModels: readonly AnyModel[] = [];\n\tconst builtinModels = (): readonly AnyModel[] => provider.getAllModels?.() ?? provider.getModels();\n\tconst getAllModels = (): readonly AnyModel[] => (personalModels.length > 0 ? personalModels : builtinModels());\n\n\treturn {\n\t\t...provider,\n\t\tmodelCatalogAuth: \"provider\",\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels: async (context) => {\n\t\t\tconst restored = (context.stored?.models ?? []).filter((model) => model.provider === provider.id);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tpersonalModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, undefined, context.force);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tlet remote: readonly AnyModel[] = [];\n\t\t\tif (process.env.PI_SERVER_MODE === \"true\" || (response.status !== 404 && response.status !== 501)) {\n\t\t\t\tif (!response.ok || (process.env.PI_SERVER_MODE === \"true\" && response.status !== 200)) {\n\t\t\t\t\tconst source = process.env.PI_SERVER_MODE === \"true\" ? \"pi-server model catalog\" : \"Model catalog\";\n\t\t\t\t\tthrow new Error(`${source} request failed for ${provider.id}: ${response.status}`);\n\t\t\t\t}\n\t\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\t\tif (isNewer(catalog.lastModified, catalogGeneratedAt)) remote = catalog.models;\n\t\t\t}\n\t\t\tconst personalized = await personalize(mergeModels(builtinModels(), remote), context);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: personalized, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tpersonalModels = personalized;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@averyyy/pi-coding-agent",
|
|
3
|
-
"version": "1.4.0-piclient.
|
|
3
|
+
"version": "1.4.0-piclient.18",
|
|
4
4
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"piConfig": {
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"prepublishOnly": "npm run clean && npm run build"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@1.4.0-piclient.
|
|
52
|
-
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.4.0-piclient.
|
|
51
|
+
"@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@1.4.0-piclient.18",
|
|
52
|
+
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.4.0-piclient.18",
|
|
53
53
|
"@earendil-works/pi-codemode": "1.4.0",
|
|
54
54
|
"@earendil-works/pi-mcp": "1.4.0",
|
|
55
|
-
"@earendil-works/pi-tui": "npm:@averyyy/pi-tui@1.4.0-piclient.
|
|
55
|
+
"@earendil-works/pi-tui": "npm:@averyyy/pi-tui@1.4.0-piclient.18",
|
|
56
56
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
57
57
|
"brace-expansion": "5.0.12",
|
|
58
58
|
"chalk": "6.0.0",
|