@humain/humain-code 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bun/sandbox-env-setup.js +8 -0
  3. package/dist/bun/sandbox-env-setup.js.map +1 -1
  4. package/dist/bundle/agent-monitor.js +1 -1
  5. package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
  6. package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +35 -35
  8. package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
  9. package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
  10. package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
  11. package/dist/bundle/chunks/{chunk-FP2SXW5M.js → chunk-GNOKILVU.js} +472 -458
  12. package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
  14. package/dist/bundle/chunks/{chunk-UU4WS4BQ.js → chunk-ILRBME2Y.js} +611 -563
  15. package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
  17. package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-BBBBZ5HY.js → chunk-PYU5BR3Z.js} +3 -3
  20. package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
  25. package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
  26. package/dist/bundle/chunks/{compat-LJ4ZIVJZ.js → compat-J5FTRJ6S.js} +8 -8
  27. package/dist/bundle/chunks/{dist-UAQRGPZO.js → dist-6FQCCUSC.js} +308 -287
  28. package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
  29. package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
  30. package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
  31. package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
  32. package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
  33. package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
  34. package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
  35. package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
  36. package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
  37. package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
  38. package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
  39. package/dist/bundle/chunks/{virtual-modules-LWYOTTHQ.js → virtual-modules-TT2VTOSY.js} +2 -2
  40. package/dist/bundle/cli-runtime.js +2 -2
  41. package/dist/bundle/flow/package.json +1 -1
  42. package/dist/bundle/index.js +5 -5
  43. package/dist/bundle/rpc-entry.js +2 -2
  44. package/dist/core/tools/renderers/write.d.ts +2 -2
  45. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  46. package/dist/core/tools/renderers/write.js +120 -15
  47. package/dist/core/tools/renderers/write.js.map +1 -1
  48. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
  49. package/dist/humain/flow-loader.d.ts.map +1 -1
  50. package/dist/humain/flow-loader.js +30 -2
  51. package/dist/humain/flow-loader.js.map +1 -1
  52. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  53. package/dist/modes/interactive/components/assistant-message.js +2 -0
  54. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  55. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  56. package/dist/modes/interactive/components/mermaid.js +4 -0
  57. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  58. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  59. package/dist/modes/interactive/components/tool-execution.js +4 -0
  60. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  61. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  62. package/dist/modes/interactive/interactive-mode.js +5 -0
  63. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  64. package/dist/utils/child-process.d.ts +8 -0
  65. package/dist/utils/child-process.d.ts.map +1 -1
  66. package/dist/utils/child-process.js +65 -4
  67. package/dist/utils/child-process.js.map +1 -1
  68. package/dist/utils/windows-path.d.ts +9 -0
  69. package/dist/utils/windows-path.d.ts.map +1 -0
  70. package/dist/utils/windows-path.js +31 -0
  71. package/dist/utils/windows-path.js.map +1 -0
  72. package/docs/flow.md +2 -0
  73. package/docs/tui.md +1 -1
  74. package/npm-shrinkwrap.json +6 -6
  75. package/package.json +2 -2
  76. package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{AssistantMessageFrameEncoder,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,StringEnum,createFauxCore,envApiKeyAuth,fauxAssistantMessage,fauxProvider,fauxText,fauxThinking,fauxToolCall,getAssistantRetryDelayMs,getOverflowPatterns,isContextOverflow,isRecoverableLength,isRetryableAssistantError,lazyOAuth,reduceAssistantMessageFrames,retryAssistantCall,retryDelayMs,validateToolArguments,validateToolCall}from"./chunk-KLIRQQH5.js";import{cleanupSessionResources,getOpenAICodexTokenIdentity,registerSessionResourceCleanup}from"./chunk-DBL35X7L.js";
3
- import{parseJsonWithRepair,parseStreamingJson,repairJson}from"./chunk-4X774RBJ.js";import{InMemoryCredentialStore,InMemoryModelsStore,ModelsError,calculateCost,clampThinkingLevel,collapseSystemMessages,commitLoginCredential,contentText,createInitialSystemMessage,createModels,createProvider,declarationsEqual,defaultProviderAuthContext,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getDeclaredTools,getInitialSystemMessage,getModelType,getSupportedThinkingLevels,getSystemMessageText,
4
- getToolStateChanges,hasApi,hasNonAdditiveToolChanges,hasToolRedefinitions,isModelType,lazyApi,lazyStream,modelsAreEqual,normalizeContext,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,toToolDeclaration,withoutInitialSystemMessage}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream,EventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,createAssistantMessageEventStream,extractDiagnosticError,formatThrownValue}from"./chunk-YURQPD6Y.js";
2
+ import{AssistantMessageFrameEncoder,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,StringEnum,createFauxCore,envApiKeyAuth,fauxAssistantMessage,fauxProvider,fauxText,fauxThinking,fauxToolCall,getAssistantRetryDelayMs,getOverflowPatterns,isContextOverflow,isRecoverableLength,isRetryableAssistantError,lazyOAuth,reduceAssistantMessageFrames,retryAssistantCall,retryDelayMs,validateToolArguments,validateToolCall}from"./chunk-OTXURGIO.js";import{cleanupSessionResources,getOpenAICodexTokenIdentity,registerSessionResourceCleanup}from"./chunk-DBL35X7L.js";
3
+ import{parseJsonWithRepair,parseStreamingJson,parseStreamingJsonWhileStreaming,repairJson}from"./chunk-GVVRXZHN.js";import{InMemoryCredentialStore,InMemoryModelsStore,ModelsError,calculateCost,clampThinkingLevel,collapseSystemMessages,commitLoginCredential,contentText,createInitialSystemMessage,createModels,createProvider,declarationsEqual,defaultProviderAuthContext,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getDeclaredTools,getInitialSystemMessage,getModelType,getSupportedThinkingLevels,
4
+ getSystemMessageText,getToolStateChanges,hasApi,hasNonAdditiveToolChanges,hasToolRedefinitions,isModelType,lazyApi,lazyStream,modelsAreEqual,normalizeContext,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,toToolDeclaration,withoutInitialSystemMessage}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream,EventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,createAssistantMessageEventStream,extractDiagnosticError,formatThrownValue}from"./chunk-YURQPD6Y.js";
5
5
  import{uuidv7}from"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";export{AssistantMessageEventStream,AssistantMessageFrameEncoder,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,EventStream,InMemoryCredentialStore,InMemoryModelsStore,ModelsError,StringEnum,typebox_exports as Type,appendAssistantMessageDiagnostic,calculateCost,clampThinkingLevel,cleanupSessionResources,collapseSystemMessages,commitLoginCredential,contentText,createAssistantMessageDiagnostic,createAssistantMessageEventStream,createFauxCore,createInitialSystemMessage,createModels,createProvider,declarationsEqual,
6
6
  defaultProviderAuthContext,envApiKeyAuth,extractDiagnosticError,fauxAssistantMessage,fauxProvider,fauxText,fauxThinking,fauxToolCall,formatThrownValue,getAssistantRetryDelayMs,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getDeclaredTools,getInitialSystemMessage,getModelType,getOpenAICodexTokenIdentity,getOverflowPatterns,getSupportedThinkingLevels,getSystemMessageText,getToolStateChanges,hasApi,hasNonAdditiveToolChanges,hasToolRedefinitions,isContextOverflow,isModelType,isRecoverableLength,
7
- isRetryableAssistantError,lazyApi,lazyOAuth,lazyStream,modelsAreEqual,normalizeContext,parseJsonWithRepair,parseStreamingJson,reduceAssistantMessageFrames,registerSessionResourceCleanup,renderSystemMessageUpdate,repairJson,resolveTranscript,resolveTranscriptTools,retryAssistantCall,retryDelayMs,toToolDeclaration,uuidv7,validateToolArguments,validateToolCall,withoutInitialSystemMessage};
7
+ isRetryableAssistantError,lazyApi,lazyOAuth,lazyStream,modelsAreEqual,normalizeContext,parseJsonWithRepair,parseStreamingJson,parseStreamingJsonWhileStreaming,reduceAssistantMessageFrames,registerSessionResourceCleanup,renderSystemMessageUpdate,repairJson,resolveTranscript,resolveTranscriptTools,retryAssistantCall,retryDelayMs,toToolDeclaration,uuidv7,validateToolArguments,validateToolCall,withoutInitialSystemMessage};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-E7WGCXWK.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-ICLZNV4V.js";import"./chunk-SCIGZFN5.js";import"./chunk-DUZY4PDA.js";import"./chunk-JXWJOIH4.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[
2
+ import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-GUUAEK6G.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-LQ4S7CRR.js";import"./chunk-SCIGZFN5.js";import"./chunk-3E4SMILM.js";import"./chunk-JXWJOIH4.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[
3
3
  228,138,122],BLUE=[79,142,179],YELLOW=[234,182,93],PI_LOGO_PIXELS=["ccc.","b.c.","bb.y","b..y"],PI_LOGO_COLORS={c:CORAL,b:BLUE,y:YELLOW};function piLogoModel(origin){return createModel(4,4,(column,row)=>PI_LOGO_COLORS[PI_LOGO_PIXELS[row][column]],{cameraDistance:10,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.
4
4
  round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),
5
5
  key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-2NX3BVH6.js";import{formatSize,writeOutputFile}from"./chunk-OXJXKCLB.js";import"./chunk-ICLZNV4V.js";import"./chunk-SCIGZFN5.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-DUZY4PDA.js";import"./chunk-BHM75BJJ.js";
2
+ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-Z5LYSSTY.js";import{formatSize,writeOutputFile}from"./chunk-PMISFIBM.js";import"./chunk-LQ4S7CRR.js";import"./chunk-SCIGZFN5.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-3E4SMILM.js";import"./chunk-BHM75BJJ.js";
3
3
  import"./chunk-JXWJOIH4.js";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}var BridgeError=class extends Error{};function parseBridgeJson(json,what){
4
4
  try{return JSON.parse(json)}catch{throw new BridgeError(`${what} is not valid JSON`)}}function parseStoreWrites(json){let entries=parseBridgeJson(json,"store writes");if(!Array.isArray(entries))throw new BridgeError("store writes are not an array");let writes={set:{},delete:[]};for(let entry of entries){if(!Array.isArray(entry)||typeof entry[0]!="string"||(entry.length===2?typeof entry[1]!="string":entry.length!==1))throw new BridgeError("store writes contain a malformed entry");let[key,value]=entry;
5
5
  value===void 0?writes.delete.push(key):writes.set[key]=parseBridgeJson(value,`store value for ${JSON.stringify(key)}`)}return writes}function parseScriptError(json){let parsed=parseBridgeJson(json,"script error");if(typeof parsed!="object"||parsed===null)throw new BridgeError("script error is not an object");let{name,message,stack}=parsed;if(typeof message!="string"||name!==void 0&&typeof name!="string"||stack!==void 0&&typeof stack!="string")throw new BridgeError("script error is malformed");return{
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
2
  import{CredentialResolutionError,DEFAULT_MODEL,activityMonitor,askPerplexity,assertAuthFetchUrl,authFetchRedirectGuard,checkGhAvailable,extractGitHub,extractWithFirecrawl,extractWithKagi,extractWithOllama,extractWithParallel,extractWithParallelMcp,extractWithQuerit,extractWithSearch1API,extractWithTinyFish,fetchGeminiApi,fetchRemoteUrl,formatSeconds,getApiKey,getBrowserCookiesForHosts,getLastBrowserCookieDiagnostic,getUploadBase,getVersionedApiBase,getWebSearchConfigPath,hasCredentialSource,isFirecrawlAvailable,
3
3
  isGatewayConfigured,isGeminiAdcAvailable,isGeminiApiAvailable,isGeminiApiAvailableWithVideo,isGeminiWebAvailable,isKagiExtractAvailable,isLoopbackHostname,isOllamaFetchAvailable,isParallelAvailable,isPerplexityAvailable,isQueritAvailable,isSearch1APIAvailable,isTimeoutError,isTinyFishAvailable,loadFetchContentDomainPolicy,loadSsrfConfig,mapFfmpegError,pLimit,queryGeminiApiWithInlineData,queryGeminiApiWithVideo,queryWithCookies,readExecError,redactCredential,redactGeminiApiResponse,resolveCredential,
4
- showGhHint,trimErrorText,validateRemoteUrl}from"./chunk-3ZI2TEVB.js";import"./chunk-LFXFQLII.js";import"./chunk-DUZY4PDA.js";import"./chunk-KLIRQQH5.js";import"./chunk-DBL35X7L.js";import"./chunk-4X774RBJ.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";import{existsSync as existsSync9,readFileSync as readFileSync9}from"node:fs";function extractRSCContent(html){if(!html.includes("self.__next_f.push"))return null;let chunkMap=new Map,scriptRegex=/<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;for(let match of html.matchAll(scriptRegex)){let content2;try{content2=JSON.parse('"'+match[1]+'"')}catch{continue}for(let line of content2.split(`
4
+ showGhHint,trimErrorText,validateRemoteUrl}from"./chunk-UZ5FVVCP.js";import"./chunk-ROSZII6E.js";import"./chunk-3E4SMILM.js";import"./chunk-OTXURGIO.js";import"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";import{existsSync as existsSync9,readFileSync as readFileSync9}from"node:fs";function extractRSCContent(html){if(!html.includes("self.__next_f.push"))return null;let chunkMap=new Map,scriptRegex=/<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;for(let match of html.matchAll(scriptRegex)){let content2;try{content2=JSON.parse('"'+match[1]+'"')}catch{continue}for(let line of content2.split(`
5
5
  `)){if(!line.trim())continue;let colonIdx=line.indexOf(":");if(colonIdx<=0||colonIdx>4)continue;let id=line.slice(0,colonIdx);if(!/^[0-9a-f]+$/i.test(id))continue;let payload=line.slice(colonIdx+1);if(!payload)continue;let existing=chunkMap.get(id);(!existing||payload.length>existing.length)&&chunkMap.set(id,payload)}}if(chunkMap.size===0)return null;let title=html.match(/<title[^>]*>([^<]+)<\/title>/)?.[1]?.split("|")[0]?.trim()||"",parsedCache=new Map;function getParsedChunk(id){if(parsedCache.
6
6
  has(id))return parsedCache.get(id);let chunk=chunkMap.get(id);if(!chunk||!chunk.startsWith("["))return parsedCache.set(id,null),null;try{let parsed=JSON.parse(chunk);return parsedCache.set(id,parsed),parsed}catch{return parsedCache.set(id,null),null}}let visitedRefs=new Set;function extractNode(node,ctx={inTable:!1,inCode:!1}){if(node==null)return"";if(typeof node=="string"){let refMatch=node.match(/^\$L([0-9a-f]+)$/i);if(refMatch){let refId=refMatch[1];if(visitedRefs.has(refId))return"";visitedRefs.
7
7
  add(refId);let refNode=getParsedChunk(refId),result=refNode?extractNode(refNode,ctx):"";return visitedRefs.delete(refId),result}return!ctx.inCode&&(node==="$undefined"||node==="$"||/^\$[A-Z]/.test(node))?"":node.trim()?node:""}if(typeof node=="number")return String(node);if(typeof node=="boolean"||!Array.isArray(node))return"";if(node[0]==="$"&&typeof node[1]=="string"){let tag=node[1],props=node[3]||{};if(["script","style","svg","path","circle","link","meta","template","button","input","nav","f\
@@ -334,7 +334,7 @@ mode!=="raw")return activityMonitor.logComplete(activityId,response.status),{url
334
334
  logComplete(activityId,response.status),{url,title:"",content:"",error:"PDF extraction is disabled by pdf.enabled",mimeType,status:response.status};let maxResponseSize=(pdfConfig?.maxSizeMB??5)*1024*1024;if(contentLengthHeader){let contentLength=Number.parseInt(contentLengthHeader,10);if(Number.isFinite(contentLength)&&contentLength>maxResponseSize)return activityMonitor.logComplete(activityId,response.status),{url,title:"",content:"",error:pdfConfig?pdfSizeLimitError(pdfConfig.maxSizeMB).message:
335
335
  `Response too large (${Math.round(contentLength/1024/1024)}MB)`}}if(options?.mode==="raw"){if(!isTextContentType(contentType))return activityMonitor.logComplete(activityId,response.status),{url,title:"",content:"",error:`Unsupported content type in raw mode: ${mimeType||"missing"}`,mimeType,status:response.status};let text2=await readTextResponseWithLimit(response,maxResponseSize);return activityMonitor.logComplete(activityId,response.status),{url,title:extractTextTitle(text2,url),content:text2,
336
336
  error:null,mimeType,status:response.status}}if(SUPPORTED_IMAGE_TYPES.has(mimeType)){let disabled=imageGateError();if(disabled)return activityMonitor.logComplete(activityId,response.status),{url,title:"",content:"",error:disabled,mimeType,status:response.status};if(options?.rejectDirectImages)return activityMonitor.logComplete(activityId,response.status),{url,title:"",content:"",error:options.rejectDirectImages,mimeType,status:response.status};try{let buffer=await readResponseBufferWithLimit(response,
337
- maxResponseSize,()=>responseSizeLimitError(maxResponseSize)),{resizeImage}=await import("./host-3OGMFGBY.js"),resized=await resizeImage(new Uint8Array(buffer),mimeType,{maxWidth:2e3,maxHeight:2e3});if(activityMonitor.logComplete(activityId,response.status),!resized)return{url,title:"",content:"",error:`Could not decode image: ${mimeType}`,mimeType,status:response.status};let title=new URL(response.url||url).pathname.split("/").pop()||url;return{url,title,content:`Image fetched (${resized.
337
+ maxResponseSize,()=>responseSizeLimitError(maxResponseSize)),{resizeImage}=await import("./host-2ARI7PQ5.js"),resized=await resizeImage(new Uint8Array(buffer),mimeType,{maxWidth:2e3,maxHeight:2e3});if(activityMonitor.logComplete(activityId,response.status),!resized)return{url,title:"",content:"",error:`Could not decode image: ${mimeType}`,mimeType,status:response.status};let title=new URL(response.url||url).pathname.split("/").pop()||url;return{url,title,content:`Image fetched (${resized.
338
338
  width}\xD7${resized.height}, ${resized.mimeType})`,error:null,thumbnail:{data:resized.data,mimeType:resized.mimeType},mimeType:resized.mimeType,status:response.status}}catch(err){let message=errorMessage5(err);return activityMonitor.logError(activityId,message),{url,title:"",content:"",error:message,mimeType,status:response.status}}}if(isPDFContent&&pdfConfig)try{let buffer=await readPDFResponseBuffer(response,pdfConfig.maxSizeMB);if(signal?.aborted)return abortedResult(url);let result=await extractPDFToMarkdown(
339
339
  buffer,url,{signal});return activityMonitor.logComplete(activityId,response.status),{url,title:result.title,content:options?.mode==="answer"?result.content:`PDF extracted and saved to: ${result.outputPath}
340
340
 
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{buildSessionContext,resizeImage}from"./chunk-LFXFQLII.js";import{getAgentDir}from"./chunk-DUZY4PDA.js";import"./chunk-KLIRQQH5.js";import"./chunk-DBL35X7L.js";import"./chunk-4X774RBJ.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";export{buildSessionContext,getAgentDir,resizeImage};
2
+ import{buildSessionContext,resizeImage}from"./chunk-ROSZII6E.js";import{getAgentDir}from"./chunk-3E4SMILM.js";import"./chunk-OTXURGIO.js";import"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";export{buildSessionContext,getAgentDir,resizeImage};
@@ -0,0 +1,43 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord}from"./chunk-II2442A2.js";import{parseStreamingJson,parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{calculateCost,
3
+ clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(normalizedContext.
4
+ messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborte\
5
+ d");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content){let partialArgs=block.partialArgs;block.type==="toolCall"&&partialArgs!==void 0&&(block.arguments=parseStreamingJson(partialArgs)),delete block.
6
+ partialArgs}output.usage.usageIncomplete=!0,output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.
7
+ reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.
8
+ id,usage:{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.
9
+ set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode==
10
+ "number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars}\
11
+ chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?
12
+ AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,body=JSON.stringify(toMistralWirePayload(payload));await createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"chat"})(body);let response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body,signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body2=await response.text();throw new MistralHttpError(
13
+ response.status,body2,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{statusCode;body;constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"\
14
+ text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)
15
+ for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence\
16
+ _penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(
17
+ wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,
18
+ "toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){
19
+ source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.
20
+ read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{
21
+ signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
22
+ `).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(
23
+ currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),payload}function shouldUsePromptCaching(options){return options?.
24
+ cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,cacheCounters=[rawUsage.promptTokensDetails?.cachedTokens,rawUsage.prompt_tokens_details?.cached_tokens,rawUsage.promptTokenDetails?.cachedTokens,rawUsage.prompt_token_details?.cached_tokens,rawUsage.numCachedTokens,rawUsage.num_cached_tokens],rawCachedTokens=cacheCounters.find(value=>value!=null),cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?
25
+ rawCachedTokens:0;return{count:Math.min(promptTokens,Math.max(0,cachedTokens)),incomplete:hasIncompleteUsage([promptTokens-cachedTokens],cacheCounters)}}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}
26
+ block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cached=getMistralCachedPromptTokens(chunk.usage,promptTokens),cachedPromptTokens=cached.count;output.usage.usageIncomplete=cached.incomplete||hasIncompleteUsage([chunk.usage.prompt_tokens,
27
+ chunk.usage.completion_tokens],[chunk.usage.total_tokens]),output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens]),calculateCost(model,output.usage)}let choice=chunk.
28
+ choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(
29
+ item);if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(
30
+ deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;
31
+ currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!==
32
+ "null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.
33
+ length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJsonWhileStreaming(block,block.partialArgs,block.arguments),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.
34
+ content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),
35
+ strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.
36
+ push({role:"system",content:sanitizeSurrogates(text)});continue}if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.
37
+ push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(
38
+ block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.
39
+ type==="text"?sanitizeSurrogates(part.text):"").join(`
40
+ `),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){
41
+ let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
42
+ [tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.
43
+ name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-UTMYL2YO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-IMR3ZJM5.js";import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord}from"./chunk-II2442A2.js";
3
- import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{getOpenAICodexTokenIdentity,registerSessionResourceCleanup}from"./chunk-DBL35X7L.js";import"./chunk-4X774RBJ.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-YURQPD6Y.js";
2
+ import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-2W5PWUPO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-IMR3ZJM5.js";import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord}from"./chunk-II2442A2.js";
3
+ import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{getOpenAICodexTokenIdentity,registerSessionResourceCleanup}from"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-YURQPD6Y.js";
4
4
  import{uuidv7}from"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);if(activeSignals.length===0)return{cleanup:()=>{}};if(activeSignals.length===1)return{signal:activeSignals[0],cleanup:()=>{}};let controller=new AbortController,listeners=[],abort=signal=>{controller.signal.aborted||controller.abort(signal.reason)};for(let signal of activeSignals){if(signal.aborted){abort(signal);break}let listener=()=>abort(signal);signal.addEventListener("abort",listener,{once:!0}),
5
5
  listeners.push({signal,listener})}return{signal:controller.signal,cleanup:()=>{for(let{signal,listener}of listeners)signal.removeEventListener("abort",listener)}}}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.
6
6
  slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
2
  import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-UW4GMZL3.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import{retryProviderRequest}from"./chunk-MEIYGK5O.js";import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,
3
- getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseStreamingJson}from"./chunk-4X774RBJ.js";
4
- import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)
3
+ getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseStreamingJson,
4
+ parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)
5
5
  if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){
6
6
  return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.\
7
7
  text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&
@@ -22,10 +22,10 @@ typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=
22
22
  finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}let reasoningFields=["reasoning_content","reaso\
23
23
  ning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.
24
24
  thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=
25
- (block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(
26
- detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail))}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.
27
- errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.usage.usageIncomplete=
28
- !0,output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
25
+ (block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJsonWhileStreaming(block,block.partialArgs,block.arguments);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)
26
+ isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail))}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")
27
+ throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content){block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index;let partialArgs=block.partialArgs;block.type==="toolCall"&&partialArgs!==void 0&&
28
+ (block.arguments=parseStreamingJson(partialArgs)),delete block.partialArgs,delete block.customInput,delete block.streamIndex}output.usage.usageIncomplete=!0,output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
29
29
  ${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,
30
30
  thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat===
31
31
  "openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-UTMYL2YO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-UW4GMZL3.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import{retryProviderRequest}from"./chunk-MEIYGK5O.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,
3
- createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-IMR3ZJM5.js";import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import"./chunk-4X774RBJ.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";
2
+ import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-2W5PWUPO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-UW4GMZL3.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import{retryProviderRequest}from"./chunk-MEIYGK5O.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,
3
+ createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-IMR3ZJM5.js";import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import"./chunk-GVVRXZHN.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";
4
4
  import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var OPENAI_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16,CHATGPT_USAGE_URL="https://chatgpt.com/settings/usage";function isChatGPTSignIn(model,apiKey){return model.provider==="openai"&&model.baseUrl==="https://api.openai.com/v1"&&apiKey!==void 0&&!apiKey.startsWith("sk-")}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==
5
5
  null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function detectSessionAffinityFormat(model){return model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue(
6
6
  "HUMAIN_TERMINAL_CACHE_RETENTION",env)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCompat(model){return{supportsDeveloperRole:model.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:model.compat?.sessionAffinityFormat??detectSessionAffinityFormat(model),supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,supportsStrictMode:model.compat?.supportsStrictMode??
@@ -1,13 +1,14 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{createRequestObserver,headersToRecord,providerHeadersToRecord}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseStreamingJson}from"./chunk-4X774RBJ.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var PiMessagesResponseError=class extends Error{code;diagnosticDetails;constructor(message,code,diagnosticDetails){super(message),this.name="PiMessagesResponseError",this.code=code,this.diagnosticDetails=diagnosticDetails}};function parsePiMessagesErrorBody(body){try{let parsed=JSON.parse(body),error=parsed?.error;return parsed&&typeof error=="object"&&error!==null&&!Array.isArray(error)?parsed:void 0}catch{return}}function truncateDiagnosticString(value){return value.length>8192?`${value.slice(
2
+ import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{createRequestObserver,headersToRecord,providerHeadersToRecord}from"./chunk-II2442A2.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseStreamingJson,parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var PiMessagesResponseError=class extends Error{code;diagnosticDetails;constructor(message,code,diagnosticDetails){super(message),this.name="PiMessagesResponseError",this.code=code,this.diagnosticDetails=diagnosticDetails}};function parsePiMessagesErrorBody(body){try{let parsed=JSON.parse(body),error=parsed?.error;return parsed&&typeof error=="object"&&error!==null&&!Array.isArray(error)?parsed:void 0}catch{return}}function truncateDiagnosticString(value){return value.length>8192?`${value.slice(
3
3
  0,8192)}\u2026`:value}function formatPiMessagesResponseError(response,body,errorBody){let message=typeof errorBody?.error?.message=="string"?errorBody.error.message:void 0,code=typeof errorBody?.error?.code=="string"?errorBody.error.code:void 0,suffix=message??body,codeSuffix=code?` (${code})`:"";return`${response.status} ${response.statusText}: ${suffix}${codeSuffix}`}function createPiMessagesResponseError(model,url,response,body){let errorBody=parsePiMessagesErrorBody(body),code=typeof errorBody?.
4
4
  error?.code=="string"?errorBody.error.code:void 0;return new PiMessagesResponseError(formatPiMessagesResponseError(response,body,errorBody),code,{version:1,provider:model.provider,model:model.id,url:url.toString(),status:response.status,statusText:response.statusText,...errorBody?.error===void 0?{}:{error:errorBody.error},...errorBody?{}:{body:truncateDiagnosticString(body)},timestampMs:Date.now()})}function createEmptyUsage(){return{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,
5
5
  cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function appendRewriteDiagnostic(message,rewrite){rewrite&&appendAssistantMessageDiagnostic(message,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...rewrite}})}function createEventConverter(model){let partial={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:createEmptyUsage(),stopReason:"pending",timestamp:Date.now()},toolJson=new Map;return event=>{let terminalUsage;switch((event.type===
6
- "done"||event.type==="error")&&(terminalUsage=event.usage?{...event.usage,usageIncomplete:event.usage.usageIncomplete===!0||hasIncompleteUsage([event.usage.input,event.usage.output,event.usage.cacheRead,event.usage.cacheWrite,event.usage.totalTokens],[event.usage.reasoning,event.usage.cacheWrite1h])}:createEmptyUsage()),event.type){case"done":return Object.assign(partial,{stopReason:event.reason,usage:terminalUsage,responseId:event.responseId}),event.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=
7
- event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"done",reason:event.reason,message:partial};case"error":return Object.assign(partial,{stopReason:event.reason,usage:terminalUsage,errorMessage:event.errorMessage,responseId:event.responseId}),event.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"error",reason:event.reason,error:partial};case"start":break;case"text_star\
8
- t":partial.content[event.contentIndex]={type:"text",text:""};break;case"text_delta":partial.content[event.contentIndex].text+=event.delta;break;case"text_end":Object.assign(partial.content[event.contentIndex],{text:event.content,textSignature:event.contentSignature});break;case"thinking_start":partial.content[event.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":partial.content[event.contentIndex].thinking+=event.delta;break;case"thinking_end":Object.assign(partial.content[event.
9
- contentIndex],{thinking:event.content,thinkingSignature:event.contentSignature,redacted:event.redacted});break;case"toolcall_start":partial.content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}},toolJson.set(event.contentIndex,"");break;case"toolcall_delta":{let json=`${toolJson.get(event.contentIndex)??""}${event.delta}`;toolJson.set(event.contentIndex,json),partial.content[event.contentIndex].arguments=parseStreamingJson(json);break}case"toolcall_end":return Object.
10
- assign(partial.content[event.contentIndex],event.toolCall),toolJson.delete(event.contentIndex),{type:"toolcall_end",contentIndex:event.contentIndex,toolCall:partial.content[event.contentIndex],partial}}return{...event,partial}}}async function*readPiMessagesEvents(stream2){let decoder=new TextDecoder,reader=stream2.getReader(),buffer="";try{for(;;){let{done,value}=await reader.read();buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),buffer=buffer.replace(/\r\n/g,`
6
+ "done"||event.type==="error")&&(terminalUsage=event.usage?{...event.usage,usageIncomplete:event.usage.usageIncomplete===!0||hasIncompleteUsage([event.usage.input,event.usage.output,event.usage.cacheRead,event.usage.cacheWrite,event.usage.totalTokens],[event.usage.reasoning,event.usage.cacheWrite1h])}:createEmptyUsage()),event.type){case"done":for(let[contentIndex,json]of toolJson)partial.content[contentIndex].arguments=parseStreamingJson(json);return Object.assign(partial,{stopReason:event.reason,
7
+ usage:terminalUsage,responseId:event.responseId}),event.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"done",reason:event.reason,message:partial};case"error":for(let[contentIndex,json]of toolJson)partial.content[contentIndex].arguments=parseStreamingJson(json);return Object.assign(partial,{stopReason:event.reason,usage:terminalUsage,errorMessage:event.errorMessage,responseId:event.responseId}),event.
8
+ providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"error",reason:event.reason,error:partial};case"start":break;case"text_start":partial.content[event.contentIndex]={type:"text",text:""};break;case"text_delta":partial.content[event.contentIndex].text+=event.delta;break;case"text_end":Object.assign(partial.content[event.contentIndex],{text:event.content,textSignature:event.contentSignature});break;case"t\
9
+ hinking_start":partial.content[event.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":partial.content[event.contentIndex].thinking+=event.delta;break;case"thinking_end":Object.assign(partial.content[event.contentIndex],{thinking:event.content,thinkingSignature:event.contentSignature,redacted:event.redacted});break;case"toolcall_start":partial.content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}},toolJson.set(event.contentIndex,"");break;case"\
10
+ toolcall_delta":{let json=`${toolJson.get(event.contentIndex)??""}${event.delta}`;toolJson.set(event.contentIndex,json);let block=partial.content[event.contentIndex];block.arguments=parseStreamingJsonWhileStreaming(block,json,block.arguments);break}case"toolcall_end":return Object.assign(partial.content[event.contentIndex],event.toolCall),toolJson.delete(event.contentIndex),{type:"toolcall_end",contentIndex:event.contentIndex,toolCall:partial.content[event.contentIndex],partial}}return{...event,
11
+ partial}}}async function*readPiMessagesEvents(stream2){let decoder=new TextDecoder,reader=stream2.getReader(),buffer="";try{for(;;){let{done,value}=await reader.read();buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),buffer=buffer.replace(/\r\n/g,`
11
12
  `);let split=buffer.indexOf(`
12
13
 
13
14
  `);for(;split!==-1;){let event=parsePiMessagesEvent(buffer.slice(0,split));event&&(yield event),buffer=buffer.slice(split+2),split=buffer.indexOf(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-E22S6D55.js";import"./chunk-JQZ7BIAI.js";import"./chunk-OXJXKCLB.js";import"./chunk-ICLZNV4V.js";import"./chunk-SCIGZFN5.js";import"./chunk-DUZY4PDA.js";import"./chunk-JXWJOIH4.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-SWRU4BOC.js";import"./chunk-F7UMX5BV.js";import"./chunk-PMISFIBM.js";import"./chunk-LQ4S7CRR.js";import"./chunk-SCIGZFN5.js";import"./chunk-3E4SMILM.js";import"./chunk-JXWJOIH4.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{dist_exports as dist_exports3}from"./chunk-BBBBZ5HY.js";import{dist_exports as dist_exports2}from"./chunk-FP2SXW5M.js";import"./chunk-3ZI2TEVB.js";import"./chunk-H5CZL7M5.js";import"./chunk-UBQSONVR.js";import"./chunk-LFXFQLII.js";import{all_exports,compat_exports}from"./chunk-UU4WS4BQ.js";import"./chunk-2NX3BVH6.js";import"./chunk-JQZ7BIAI.js";import"./chunk-OXJXKCLB.js";import"./chunk-E7WGCXWK.js";import{dist_exports}from"./chunk-ICLZNV4V.js";
3
- import"./chunk-SCIGZFN5.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";import"./chunk-VQTXF23B.js";import"./chunk-DUZY4PDA.js";import"./chunk-BRXQUQSC.js";import"./chunk-KLIRQQH5.js";import"./chunk-DBL35X7L.js";import"./chunk-4X774RBJ.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import{compile_exports,value_exports2 as value_exports}from"./chunk-QMUIATLD.js";
2
+ import{dist_exports as dist_exports3}from"./chunk-PYU5BR3Z.js";import{dist_exports as dist_exports2}from"./chunk-GNOKILVU.js";import"./chunk-UZ5FVVCP.js";import"./chunk-KRMTBTWU.js";import"./chunk-UBQSONVR.js";import"./chunk-ROSZII6E.js";import{all_exports,compat_exports}from"./chunk-ILRBME2Y.js";import"./chunk-Z5LYSSTY.js";import"./chunk-F7UMX5BV.js";import"./chunk-PMISFIBM.js";import"./chunk-GUUAEK6G.js";import{dist_exports}from"./chunk-LQ4S7CRR.js";
3
+ import"./chunk-SCIGZFN5.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";import"./chunk-TIAXGIMN.js";import"./chunk-3E4SMILM.js";import"./chunk-BRXQUQSC.js";import"./chunk-OTXURGIO.js";import"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import{compile_exports,value_exports2 as value_exports}from"./chunk-QMUIATLD.js";
4
4
  import{build_exports}from"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-w\
5
5
  orks/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
@@ -1,5 +1,5 @@
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,warnIfDeprecatedCommand}from"./chunks/chunk-FP2SXW5M.js";import"./chunks/chunk-3ZI2TEVB.js";import"./chunks/chunk-H5CZL7M5.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-LFXFQLII.js";import"./chunks/chunk-UU4WS4BQ.js";import"./chunks/chunk-2NX3BVH6.js";import"./chunks/chunk-JQZ7BIAI.js";import"./chunks/chunk-OXJXKCLB.js";import"./chunks/chunk-E7WGCXWK.js";import"./chunks/chunk-ICLZNV4V.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";
4
- import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-VQTXF23B.js";import{APP_COMMAND,ENV_PREFIX}from"./chunks/chunk-DUZY4PDA.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-KLIRQQH5.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-4X774RBJ.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";
3
+ import{configureHttpDispatcher,main,warnIfDeprecatedCommand}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import"./chunks/chunk-F7UMX5BV.js";import"./chunks/chunk-PMISFIBM.js";import"./chunks/chunk-GUUAEK6G.js";import"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";
4
+ import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-TIAXGIMN.js";import{APP_COMMAND,ENV_PREFIX}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";
5
5
  import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_COMMAND,process.env.PI_CODING_AGENT="true",process.env[`${ENV_PREFIX}_CODING_AGENT`]="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();warnIfDeprecatedCommand(process.argv.slice(2));main(process.argv.slice(2));
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@earendil-works/pi-tui": "1.1.0",
31
- "@humain/humain-code-contracts": "0.4.6",
31
+ "@humain/humain-code-contracts": "0.4.8",
32
32
  "typebox": "1.3.35"
33
33
  },
34
34
  "devDependencies": {
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-BBBBZ5HY.js";import{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
2
+ import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-PYU5BR3Z.js";import{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
3
3
  ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,OAuthSelectorComponent,RpcClient,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,calculateContextTokens,collectEntriesForBranchSummary,
4
4
  compact,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,
5
5
  createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,
6
6
  getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,
7
- serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-FP2SXW5M.js";import"./chunks/chunk-3ZI2TEVB.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-H5CZL7M5.js";import"./chunks/chunk-UBQSONVR.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,
8
- resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-LFXFQLII.js";import"./chunks/chunk-UU4WS4BQ.js";import"./chunks/chunk-2NX3BVH6.js";import{readStoredCredential}from"./chunks/chunk-JQZ7BIAI.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-OXJXKCLB.js";import{ArminComponent}from"./chunks/chunk-E7WGCXWK.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,
9
- getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-ICLZNV4V.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,
10
- HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunks/chunk-VQTXF23B.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-DUZY4PDA.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-KLIRQQH5.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-4X774RBJ.js";import"./chunks/chunk-WPLW452J.js";
7
+ serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,
8
+ resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import{readStoredCredential}from"./chunks/chunk-F7UMX5BV.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-PMISFIBM.js";import{ArminComponent}from"./chunks/chunk-GUUAEK6G.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,
9
+ getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,
10
+ HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunks/chunk-TIAXGIMN.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";
11
11
  import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";export{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,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,
12
12
  ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,
13
13
  OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UPSTREAM_PI_VERSION,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,
@@ -1,4 +1,4 @@
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-FP2SXW5M.js";import"./chunks/chunk-3ZI2TEVB.js";import"./chunks/chunk-H5CZL7M5.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-LFXFQLII.js";import"./chunks/chunk-UU4WS4BQ.js";import"./chunks/chunk-2NX3BVH6.js";import"./chunks/chunk-JQZ7BIAI.js";import"./chunks/chunk-OXJXKCLB.js";import"./chunks/chunk-E7WGCXWK.js";import"./chunks/chunk-ICLZNV4V.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";
4
- import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-VQTXF23B.js";import{APP_COMMAND}from"./chunks/chunk-DUZY4PDA.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-KLIRQQH5.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-4X774RBJ.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_COMMAND}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import"./chunks/chunk-F7UMX5BV.js";import"./chunks/chunk-PMISFIBM.js";import"./chunks/chunk-GUUAEK6G.js";import"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";
4
+ import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-TIAXGIMN.js";import{APP_COMMAND}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_COMMAND}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -5,6 +5,6 @@
5
5
  * load the execution path or its typebox parameter schema. `write.ts` spreads these into its
6
6
  * definition, so the tool's public shape is unchanged.
7
7
  */
8
- import type { ToolDefinition } from "../../extensions/types.ts";
9
- export declare const writeRenderers: Pick<ToolDefinition<any, any>, "renderCall" | "renderResult">;
8
+ import type { ToolRenderers } from "../../extensions/types.ts";
9
+ export declare const writeRenderers: Pick<ToolRenderers, "renderCall" | "renderResult">;
10
10
  //# sourceMappingURL=write.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/write.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,2BAA2B,CAAC;AAqIzF,eAAO,MAAM,cAAc,EAAE,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,YAAY,GAAG,cAAc,CAoCxF,CAAC"}
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/write.ts"],"names":[],"mappings":"AACA;;;;;;GAMG;AAKH,OAAO,KAAK,EAAE,aAAa,EAA2B,MAAM,2BAA2B,CAAC;AAuOxF,eAAO,MAAM,cAAc,EAAE,IAAI,CAAC,aAAa,EAAE,YAAY,GAAG,cAAc,CA0D7E,CAAC"}