@code-yeongyu/senpi 2026.11.13 → 2026.11.15

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 (95) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundle/chunks/{args-H56W53X6.js → args-JWBI5LNO.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-MNN2TINI.js → azure-openai-responses-PEMLRPJ5.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-HZQHA4PA.js → chunk-3RILB2OD.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-Y4PFEXFN.js → chunk-5IXYN6DK.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-BKDXY6EM.js → chunk-5NECOJNK.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-NI2AOYP6.js → chunk-6MRUNB3Z.js} +1 -1
  8. package/dist/bundle/chunks/chunk-6QQL3SKM.js +2 -0
  9. package/dist/bundle/chunks/{chunk-I4N2OIY4.js → chunk-6QXAYNO7.js} +17 -17
  10. package/dist/bundle/chunks/{chunk-7T2LAWZ4.js → chunk-73HGQTJN.js} +1 -1
  11. package/dist/bundle/chunks/chunk-75O3CWR5.js +2 -0
  12. package/dist/bundle/chunks/{chunk-AZ27TE3H.js → chunk-7BX3JQ7F.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-NDI6N4NJ.js → chunk-7CXLNKEH.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-E6ZBTSC6.js → chunk-A3LGSX7Z.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-7GD2EO6T.js → chunk-FYVQEZYN.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-U4FAWC6C.js → chunk-GXPH7RN6.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-SFACYIB6.js → chunk-IK3S2NDB.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-V4VDIV3U.js → chunk-PWA75RQU.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-IREUIMFE.js → chunk-PWTXZXHH.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-KKB3K5CV.js → chunk-Q4RJ4WLE.js} +1 -1
  21. package/dist/bundle/chunks/chunk-QVG5SUSV.js +2 -0
  22. package/dist/bundle/chunks/chunk-RLIY3AUC.js +2 -0
  23. package/dist/bundle/chunks/{chunk-EQT4WNCW.js → chunk-TACOXP5H.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-NXGSYUMV.js → chunk-TB6LIKVR.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-JLCZIEBC.js → chunk-THYIV26N.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-6FE42M54.js → chunk-VGHGM5PR.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CU6HUYL7.js → chunk-WAGFTIT4.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-UYPH6RHY.js → chunk-Z4PN2MDA.js} +2 -2
  29. package/dist/bundle/chunks/{chunk-JJYN347Z.js → chunk-ZJUL5ODW.js} +1 -1
  30. package/dist/bundle/chunks/{cli-main-MY53RXU3.js → cli-main-MM2XCVYE.js} +1 -1
  31. package/dist/bundle/chunks/credential-accounts-RXZIUKFM.js +2 -0
  32. package/dist/bundle/chunks/github-copilot.js +1 -1
  33. package/dist/bundle/chunks/{hand-entry-AXTVMVJK.js → hand-entry-MBOPYO6I.js} +1 -1
  34. package/dist/bundle/chunks/{headless-host-SU5O2KZ2.js → headless-host-OEK6W65T.js} +1 -1
  35. package/dist/bundle/chunks/{health-write-TN7EXGLI.js → health-write-44JERGEJ.js} +1 -1
  36. package/dist/bundle/chunks/{help-fast-path-TFQ4HJNO.js → help-fast-path-JWHUCE4E.js} +1 -1
  37. package/dist/bundle/chunks/{host-command-FG56Y53E.js → host-command-O2K2WIPO.js} +1 -1
  38. package/dist/bundle/chunks/{host-session-command-UFEOW7EP.js → host-session-command-EWA6N4JJ.js} +1 -1
  39. package/dist/bundle/chunks/interactive-mode-VSZYRVYY.js +2 -0
  40. package/dist/bundle/chunks/{login-health-XBTIORM4.js → login-health-V4B6LSCP.js} +1 -1
  41. package/dist/bundle/chunks/main-VEWKRBTD.js +2 -0
  42. package/dist/bundle/chunks/{multi-session-host-Q6SHI22A.js → multi-session-host-HC6NR5N2.js} +1 -1
  43. package/dist/bundle/chunks/{openai-codex-responses-VRGOAFEG.js → openai-codex-responses-IFPWK7NG.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-2BTL5MA2.js +5 -0
  45. package/dist/bundle/chunks/{package-manager-cli-LILAWI3Q.js → package-manager-cli-OZ6DK6GI.js} +3 -3
  46. package/dist/bundle/chunks/{role-KODRTWH5.js → role-BTH5PVME.js} +1 -1
  47. package/dist/bundle/chunks/{rotation-stream-2KNROTYB.js → rotation-stream-ZGPXLY62.js} +1 -1
  48. package/dist/bundle/chunks/rpc-mode-WPF3NVBL.js +2 -0
  49. package/dist/bundle/chunks/{run-attached-tui-OEFHV5CZ.js → run-attached-tui-RVVYEINN.js} +1 -1
  50. package/dist/bundle/chunks/{schedule-command-VO4RP2KX.js → schedule-command-6TAAG2KU.js} +1 -1
  51. package/dist/bundle/chunks/{session-control-endpoint-CCVRJHSC.js → session-control-endpoint-3FNVOKKT.js} +1 -1
  52. package/dist/bundle/chunks/{session-picker-VN5I2ZDI.js → session-picker-YDXDCBRL.js} +1 -1
  53. package/dist/bundle/chunks/session-slot-N4E4OSCX.js +2 -0
  54. package/dist/bundle/chunks/session-worker.js +22 -21
  55. package/dist/bundle/chunks/{state-store-7RVODZJU.js → state-store-I6MUHET3.js} +1 -1
  56. package/dist/bundle/cli.js +2 -2
  57. package/dist/bundle/index.js +1 -1
  58. package/dist/bundle/rpc-entry.js +1 -1
  59. package/dist/bundle/runtime-manifest.json +1 -1
  60. package/dist/core/agent-session.d.ts +5 -3
  61. package/dist/core/agent-session.js +16 -6
  62. package/dist/core/credential-accounts.d.ts +5 -3
  63. package/dist/core/credential-accounts.js +8 -6
  64. package/dist/core/credential-pool/classify.js +5 -1
  65. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.d.ts +6 -0
  66. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.js +14 -0
  67. package/dist/core/extensions/builtin/anthropic-subscription/prompt-bridge.js +3 -1
  68. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +4 -1
  69. package/dist/core/extensions/builtin/permission-system/index.js +5 -1
  70. package/dist/core/reasoning-baseline.d.ts +8 -1
  71. package/dist/core/reasoning-baseline.js +24 -0
  72. package/dist/modes/rpc/connection-handler.js +4 -0
  73. package/dist/modes/rpc/method-classes-schema-session.d.ts +3 -0
  74. package/dist/modes/rpc/method-classes-schema-session.js +6 -2
  75. package/dist/modes/rpc/method-classes-schema.d.ts +3 -0
  76. package/dist/modes/rpc/project-expected-cwd.d.ts +29 -0
  77. package/dist/modes/rpc/project-expected-cwd.js +45 -0
  78. package/dist/modes/rpc/rpc-error-types.d.ts +7 -1
  79. package/dist/modes/rpc/rpc-error-types.js +6 -0
  80. package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
  81. package/dist/package-manager-cli.d.ts +14 -0
  82. package/dist/package-manager-cli.js +20 -4
  83. package/dist/utils/version-check.d.ts +10 -7
  84. package/dist/utils/version-check.js +24 -5
  85. package/docs/rpc.md +20 -7
  86. package/package.json +7 -7
  87. package/dist/bundle/chunks/chunk-GLTOBXZY.js +0 -2
  88. package/dist/bundle/chunks/chunk-PBUV2Z3R.js +0 -2
  89. package/dist/bundle/chunks/chunk-WRBOKYPS.js +0 -2
  90. package/dist/bundle/chunks/credential-accounts-ZB5IXHIG.js +0 -2
  91. package/dist/bundle/chunks/interactive-mode-PHES47E3.js +0 -2
  92. package/dist/bundle/chunks/main-PR4FI6HQ.js +0 -2
  93. package/dist/bundle/chunks/openai-responses-I7PXRWCM.js +0 -4
  94. package/dist/bundle/chunks/rpc-mode-CGVK4SSA.js +0 -2
  95. package/dist/bundle/chunks/session-slot-GHJVOSG7.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- var GITHUB_COPILOT_INDIVIDUAL_BASE_URL="https://api.individual.githubcopilot.com";function githubCopilotTokenField(token,key){for(let part of token.split(";")){let separator=part.indexOf("=");if(separator>0&&part.slice(0,separator)===key)return part.slice(separator+1)||void 0}}function githubCopilotBaseUrlFromToken(token){let proxyHost=githubCopilotTokenField(token,"proxy-ep");return proxyHost?`https://${proxyHost.replace(/^proxy\./,"api.")}`:void 0}function parseGitHubCopilotApiEndpoint(value){if(typeof value=="string")try{let url=new URL(value.trim());return url.protocol!=="https:"||!url.hostname||url.username||url.password?void 0:`${url.origin}${url.pathname.replace(/\/+$/,"")}`}catch{return}}function endpointForToken(endpoint,token){if(!token||typeof endpoint!="object"||endpoint===null)return;let tid=Reflect.get(endpoint,"tid"),url=parseGitHubCopilotApiEndpoint(Reflect.get(endpoint,"url"));return typeof tid=="string"&&tid===githubCopilotTokenField(token,"tid")?url:void 0}function resolveGitHubCopilotBaseUrl(input){return endpointForToken(input.apiEndpoint,input.token)??(input.token?githubCopilotBaseUrlFromToken(input.token):void 0)??(input.enterpriseDomain?`https://copilot-api.${input.enterpriseDomain}`:void 0)??GITHUB_COPILOT_INDIVIDUAL_BASE_URL}var GITHUB_COPILOT_REJECTED_TOKEN_STATUSES=[401,403];function formatThrownValue(value){return value instanceof Error?value.message||value.name:typeof value=="string"?value:String(value)}var ModelsError=class extends Error{constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}var _a,OAuthTokenEndpointError=class extends Error{constructor(message,status,facts={}){super(message),this.status=status,this.oauthError=facts.oauthError,this.credentialRefused=facts.credentialRefused??!1}};var UNAVAILABLE=Symbol.for("senpi.oauthRefreshUnavailable"),OAuthRefreshUnavailableError=class extends ModelsError{static{_a=UNAVAILABLE}constructor(provider,cause){super("oauth",`OAuth refresh failed for ${provider}`,{cause}),this[_a]=!0,this.name="OAuthRefreshUnavailableError"}};function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var github_copilot_default={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.2":{id:"claude-fable-5.2",name:"Claude Fable 5.2",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:8,output:40,cacheRead:.2,cacheWrite:10},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e5,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-argon":{id:"gemini-4-argon",name:"Gemini 4 Argon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-carbon":{id:"gemini-4-carbon",name:"Gemini 4 Carbon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:6e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-terra":{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.05,cacheWrite:1.25,tiers:[{inputTokensAbove:272e3,input:2,output:7.5,cacheRead:.1,cacheWrite:2.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};var MAX_EFFORT_MODEL_IDS=new Set;function flattenModelCatalog(groups,type){return Object.fromEntries(Object.values(groups).flatMap(models=>Object.values(models)).filter(model=>model.type===type).map(model=>[model.id,model]))}function flattenChatModelCatalog(_provider,groups){let catalog=flattenModelCatalog(groups,"chat");for(let model of Object.values(catalog))typeof model.thinkingLevelMap?.max=="string"&&MAX_EFFORT_MODEL_IDS.add(model.id);return catalog}function flattenImageModelCatalog(_provider,groups){return flattenModelCatalog(groups,"image")}function flattenClassifierModelCatalog(_provider,groups){return flattenModelCatalog(groups,"classifier")}var GITHUB_COPILOT_MODELS=flattenChatModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_IMAGE_MODELS=flattenImageModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_CLASSIFIER_MODELS=flattenClassifierModelCatalog("github-copilot",github_copilot_default);function asRecord(value){return value&&typeof value=="object"?value:void 0}function positiveInteger(value){return typeof value=="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseGitHubCopilotModelLimit(id,rawLimits){let limits=asRecord(rawLimits);if(!limits)return;let maxContextWindowTokens=positiveInteger(limits.max_context_window_tokens),maxPromptTokens=positiveInteger(limits.max_prompt_tokens),maxOutputTokens=positiveInteger(limits.max_output_tokens);if(!(maxContextWindowTokens===void 0&&maxPromptTokens===void 0&&maxOutputTokens===void 0))return{id,...maxContextWindowTokens!==void 0?{maxContextWindowTokens}:{},...maxPromptTokens!==void 0?{maxPromptTokens}:{},...maxOutputTokens!==void 0?{maxOutputTokens}:{}}}function asRecord2(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord2(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord2(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord2(item.capabilities);return asRecord2(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord2(item.policy)?.state,limits:parseGitHubCopilotModelLimit(id,capabilities?.limits)}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id),modelLimits=accountModels.map(model=>model.limits).filter(limits=>limits!==void 0);return{availableModelIds,policyModelIds,modelLimits}}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint){return resolveGitHubCopilotBaseUrl({token,enterpriseDomain,apiEndpoint})}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy,apiEndpoint){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain,apiEndpoint),allowPolicyFallback=baseUrl===GITHUB_COPILOT_INDIVIDUAL_BASE_URL,response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new OAuthTokenEndpointError(`${response.status} ${response.statusText}: ${await response.text()}`,response.status);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new OAuthTokenEndpointError(`${response.status} ${response.statusText}: ${text}`,response.status)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");let endpoints=raw.endpoints,apiUrl=parseGitHubCopilotApiEndpoint(typeof endpoints=="object"&&endpoints!==null?Reflect.get(endpoints,"api"):void 0),tid=githubCopilotTokenField(token,"tid");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain,...apiUrl!==void 0&&tid!==void 0?{copilotApiEndpoint:{tid,url:apiUrl}}:{}}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds,modelLimits}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0},credentials.copilotApiEndpoint);return{...credentials,availableModelIds,copilotModelLimits:modelLimits}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal,apiEndpoint){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3},credentials.copilotApiEndpoint),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal,credentials.copilotApiEndpoint)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])],copilotModelLimits:models.modelLimits}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,rejectedTokenStatuses:GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential),credential.copilotApiEndpoint)}}};export{githubCopilotOAuth};
2
+ var GITHUB_COPILOT_INDIVIDUAL_BASE_URL="https://api.individual.githubcopilot.com";function githubCopilotTokenField(token,key){for(let part of token.split(";")){let separator=part.indexOf("=");if(separator>0&&part.slice(0,separator)===key)return part.slice(separator+1)||void 0}}function githubCopilotBaseUrlFromToken(token){let proxyHost=githubCopilotTokenField(token,"proxy-ep");return proxyHost?`https://${proxyHost.replace(/^proxy\./,"api.")}`:void 0}function parseGitHubCopilotApiEndpoint(value){if(typeof value=="string")try{let url=new URL(value.trim());return url.protocol!=="https:"||!url.hostname||url.username||url.password?void 0:`${url.origin}${url.pathname.replace(/\/+$/,"")}`}catch{return}}function endpointForToken(endpoint,token){if(!token||typeof endpoint!="object"||endpoint===null)return;let tid=Reflect.get(endpoint,"tid"),url=parseGitHubCopilotApiEndpoint(Reflect.get(endpoint,"url"));return typeof tid=="string"&&tid===githubCopilotTokenField(token,"tid")?url:void 0}function resolveGitHubCopilotBaseUrl(input){return endpointForToken(input.apiEndpoint,input.token)??(input.token?githubCopilotBaseUrlFromToken(input.token):void 0)??(input.enterpriseDomain?`https://copilot-api.${input.enterpriseDomain}`:void 0)??GITHUB_COPILOT_INDIVIDUAL_BASE_URL}var GITHUB_COPILOT_REJECTED_TOKEN_STATUSES=[401,403];function formatThrownValue(value){return value instanceof Error?value.message||value.name:typeof value=="string"?value:String(value)}var ModelsError=class extends Error{constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}var _a,OAuthTokenEndpointError=class extends Error{constructor(message,status,facts={}){super(message),this.status=status,this.oauthError=facts.oauthError,this.credentialRefused=facts.credentialRefused??!1}};var UNAVAILABLE=Symbol.for("senpi.oauthRefreshUnavailable"),OAuthRefreshUnavailableError=class extends ModelsError{static{_a=UNAVAILABLE}constructor(provider,cause){super("oauth",`OAuth refresh failed for ${provider}`,{cause}),this[_a]=!0,this.name="OAuthRefreshUnavailableError"}};function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var github_copilot_default={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.2":{id:"claude-fable-5.2",name:"Claude Fable 5.2",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:8,output:40,cacheRead:.2,cacheWrite:10},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e5,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-argon":{id:"gemini-4-argon",name:"Gemini 4 Argon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-carbon":{id:"gemini-4-carbon",name:"Gemini 4 Carbon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-hydrogen":{id:"gemini-4-hydrogen",name:"Gemini 4 Hydrogen",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:7.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},deprecated:!0,inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:1048576,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},deprecated:!0,thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:6e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-terra":{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.05,cacheWrite:1.25,tiers:[{inputTokensAbove:272e3,input:2,output:7.5,cacheRead:.1,cacheWrite:2.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};var MAX_EFFORT_MODEL_IDS=new Set;function flattenModelCatalog(groups,type){return Object.fromEntries(Object.values(groups).flatMap(models=>Object.values(models)).filter(model=>model.type===type).map(model=>[model.id,model]))}function flattenChatModelCatalog(_provider,groups){let catalog=flattenModelCatalog(groups,"chat");for(let model of Object.values(catalog))typeof model.thinkingLevelMap?.max=="string"&&MAX_EFFORT_MODEL_IDS.add(model.id);return catalog}function flattenImageModelCatalog(_provider,groups){return flattenModelCatalog(groups,"image")}function flattenClassifierModelCatalog(_provider,groups){return flattenModelCatalog(groups,"classifier")}var GITHUB_COPILOT_MODELS=flattenChatModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_IMAGE_MODELS=flattenImageModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_CLASSIFIER_MODELS=flattenClassifierModelCatalog("github-copilot",github_copilot_default);function asRecord(value){return value&&typeof value=="object"?value:void 0}function positiveInteger(value){return typeof value=="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseGitHubCopilotModelLimit(id,rawLimits){let limits=asRecord(rawLimits);if(!limits)return;let maxContextWindowTokens=positiveInteger(limits.max_context_window_tokens),maxPromptTokens=positiveInteger(limits.max_prompt_tokens),maxOutputTokens=positiveInteger(limits.max_output_tokens);if(!(maxContextWindowTokens===void 0&&maxPromptTokens===void 0&&maxOutputTokens===void 0))return{id,...maxContextWindowTokens!==void 0?{maxContextWindowTokens}:{},...maxPromptTokens!==void 0?{maxPromptTokens}:{},...maxOutputTokens!==void 0?{maxOutputTokens}:{}}}function asRecord2(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord2(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord2(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord2(item.capabilities);return asRecord2(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord2(item.policy)?.state,limits:parseGitHubCopilotModelLimit(id,capabilities?.limits)}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id),modelLimits=accountModels.map(model=>model.limits).filter(limits=>limits!==void 0);return{availableModelIds,policyModelIds,modelLimits}}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint){return resolveGitHubCopilotBaseUrl({token,enterpriseDomain,apiEndpoint})}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy,apiEndpoint){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain,apiEndpoint),allowPolicyFallback=baseUrl===GITHUB_COPILOT_INDIVIDUAL_BASE_URL,response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new OAuthTokenEndpointError(`${response.status} ${response.statusText}: ${await response.text()}`,response.status);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new OAuthTokenEndpointError(`${response.status} ${response.statusText}: ${text}`,response.status)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");let endpoints=raw.endpoints,apiUrl=parseGitHubCopilotApiEndpoint(typeof endpoints=="object"&&endpoints!==null?Reflect.get(endpoints,"api"):void 0),tid=githubCopilotTokenField(token,"tid");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain,...apiUrl!==void 0&&tid!==void 0?{copilotApiEndpoint:{tid,url:apiUrl}}:{}}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds,modelLimits}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0},credentials.copilotApiEndpoint);return{...credentials,availableModelIds,copilotModelLimits:modelLimits}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal,apiEndpoint){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3},credentials.copilotApiEndpoint),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal,credentials.copilotApiEndpoint)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])],copilotModelLimits:models.modelLimits}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,rejectedTokenStatuses:GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential),credential.copilotApiEndpoint)}}};export{githubCopilotOAuth};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{PresentationBroker,bootstrapRuntime,buildToolRegistry,builtInExtensions,canonicalizeFilesystemPath,childModuleRoots,createAgentSessionServices,createProjectTrustContext,createToolChildRuntime,forwardToolEvents,presetTrustsProject,resolveProjectTrusted,sessionExtensionFlagValues,toolChildModuleRoots,toolInfoOf,withFileMutationQueue,withFileMutationQueues}from"./chunk-I4N2OIY4.js";import"./chunk-Y4PFEXFN.js";import"./chunk-KKB3K5CV.js";import"./chunk-NI2AOYP6.js";import"./chunk-WRBOKYPS.js";import"./chunk-CU6HUYL7.js";import"./chunk-NLYT7BND.js";import{SettingsManager}from"./chunk-EQT4WNCW.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-7GD2EO6T.js";import"./chunk-WMDJMN5W.js";import"./chunk-GTJJ73DE.js";import{ProjectTrustStore,getSavedProjectTrust,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-V4VDIV3U.js";import"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import"./chunk-BKDXY6EM.js";import"./chunk-HKCFMDJN.js";import"./chunk-E6ZBTSC6.js";import"./chunk-3QPE75AR.js";import"./chunk-ULWRGKP2.js";import"./chunk-4B5JSLLR.js";import"./chunk-FWIO636S.js";import"./chunk-MOVB6H22.js";import"./chunk-DLPV4B3R.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import{closeServer,listen,prepareSocketPath}from"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import"./chunk-UYPH6RHY.js";import"./chunk-AZ27TE3H.js";import"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import"./chunk-C4AHHZ6P.js";import"./chunk-CEFKVI3E.js";import"./chunk-HGCQAMC6.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import"./chunk-WHQ2QPP5.js";import"./chunk-PBUV2Z3R.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-2IKL4F24.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-HZQHA4PA.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{localDeviceFiles}from"./chunk-JJYN347Z.js";import{DeviceFileError,FILE_CHANNEL_MAX_BYTES,base64Length,createReliableTransport,createRemoteExecutor,decodeBase64,decodeDeviceFileArgs,encodeBase64,fileRefusal,fileResult,serveLoopHooks}from"./chunk-NDI6N4NJ.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import{validateToolArguments}from"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-GLTOBXZY.js";import"./chunk-U4FAWC6C.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-2SOVDETB.js";import"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import{shieldSocketDuringClose,unlinkOwnedSocket}from"./chunk-5XHOHZIR.js";import{authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{isLocalPath,resolvePath}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createServer}from"node:net";import{posix as posix2,win32}from"node:path";import{isAbsolute as isAbsolute2}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{basename as basename4,dirname as dirname4,join as join4,resolve as resolve3}from"node:path";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync}from"node:fs";import{constants as fsConstants}from"node:fs";import{open}from"node:fs/promises";import{constants as osConstants}from"node:os";import{basename,dirname,join,resolve}from"node:path";var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,RETRY_MS=5,LOCK_SH=1,LOCK_NB=4;function classifyFlockErrno(errno){let{EAGAIN,EWOULDBLOCK,ENOLCK,EOPNOTSUPP,ENOSYS}=osConstants.errno;return errno===EAGAIN||errno===EWOULDBLOCK?"busy":errno===ENOLCK||errno===EOPNOTSUPP||errno===ENOSYS?"no-lock":"failed"}function identityLocksDir(repoDir){let repo=resolve(repoDir);if(!(basename(repo)!=="repo"||basename(dirname(dirname(repo)))!=="agents"))return join(dirname(repo),"runtime","locks")}var NO_HOLD={fd:void 0,release:async()=>{}},delay=ms=>new Promise(done=>setTimeout(done,ms));async function holdActivityLock(cwd,flock,waitMs=GIT_ACTIVITY_SHARED_WAIT_MS){let locksDir=identityLocksDir(cwd);if(locksDir===void 0||flock===void 0)return NO_HOLD;if(!existsSync(locksDir))throw new DeviceFileError("not_found","the identity's locks directory does not exist");let handle=await open(join(locksDir,GIT_ACTIVITY_LOCK_NAME),fsConstants.O_RDWR|fsConstants.O_CREAT,384),deadline=Date.now()+waitMs;try{for(;;){let{rc,errno}=flock(handle.fd,LOCK_SH|LOCK_NB);if(rc===0)return{fd:handle.fd,release:()=>handle.close()};let kind=classifyFlockErrno(errno);if(kind==="no-lock")return await handle.close(),NO_HOLD;if(kind==="failed")throw new DeviceFileError("io",`flock on the git-activity lock failed (errno ${errno})`);if(Date.now()>=deadline)throw new DeviceFileError("io",`the git-activity lock stayed exclusively held for ${waitMs} ms`);await delay(RETRY_MS)}}catch(error){throw await handle.close(),error}}import{posix}from"node:path";var k=kind=>({kind}),eq=(prefix,kind)=>({prefix,kind}),opt=(...optional)=>({optional}),rep=(min,...repeat)=>({repeat,min}),NUL=/\0/,REV=/^(?![-./~:])[A-Za-z0-9._/@{}^~+-]+$/,REL=/^(?![/-])(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/,rev=value=>REV.test(value)&&!value.includes("..")&&!value.includes("//"),range=value=>{let parts=value.split("..");return parts.length===2&&parts.every(rev)},blobref=value=>{let at=value.indexOf(":");return at>=0&&(at===0||rev(value.slice(0,at)))&&REL.test(value.slice(at+1))},filesystem=value=>value.length>0&&!NUL.test(value)&&!/^[-:]/.test(value);function scheme(value){return/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(value)?.[1]}function urlIsLocal(value){let colon=value.indexOf(":"),slash=value.indexOf("/");return colon<0||slash>=0&&slash<colon||process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(value)}var unsafeUrl=value=>value.length===0||NUL.test(value)||/\s/.test(value)||value.startsWith("-")||value.includes("::");function remote(value){if(unsafeUrl(value))return!1;let named=scheme(value);return named!==void 0?named==="https"||named==="ssh":!urlIsLocal(value)}function localUrlPath(value){if(unsafeUrl(value)||scheme(value)!=="file")return;let rest=value.slice(7);if(!rest.startsWith("/")||/[?#]/.test(rest))return;let path;try{path=decodeURIComponent(rest)}catch{return}return path.length>1&&!NUL.test(path)&&!path.endsWith("/")&&posix.normalize(path)===path&&path.split("/").slice(1).every(part=>part!==""&&part!=="."&&part!=="..")?path:void 0}var localCandidate=value=>!unsafeUrl(value)&&(scheme(value)==="file"||scheme(value)===void 0&&urlIsLocal(value)),KINDS={rev,range,revish:value=>rev(value)||range(value),object:value=>rev(value)||blobref(value),blobref,ref:value=>value==="HEAD"||/^refs\/[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refpat:value=>/^refs\/[A-Za-z0-9._/-]+\*?$/.test(value)&&!value.includes(".."),branch:value=>/^(?![-./])[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refspec:value=>/^[A-Za-z0-9._/]+(?:-[A-Za-z0-9._/]+)*:[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),msg:value=>!NUL.test(value),count:value=>/^\d{1,9}$/.test(value),mode:value=>/^(?:100644|100755|120000|160000)$/.test(value),oid:value=>/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(value),filter:value=>/^[ACDMRTUXB]+$/i.test(value),fmt:value=>!NUL.test(value),iso:value=>/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value),relpath:value=>REL.test(value),gitpath:value=>value==="index"||value==="MERGE_HEAD",path:filesystem,worktree:filesystem,source:value=>remote(value)||localCandidate(value),target:value=>remote(value)||localCandidate(value)},FORMAT=eq("--format=","fmt"),LOG_RECORD="--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI",SHAPES={add:[["-A","--",rep(1,k("path"))]],branch:[["--show-current"],["-D",k("branch")]],"cat-file":[["blob",k("object")],["--batch"],["-e",k("blobref")]],checkout:[[k("rev"),"--",k("path")]],commit:[["-q","--no-verify","-m",k("msg")]],"commit-tree":[[k("rev"),opt("-p",k("rev")),"-F","-"]],"count-objects":[["-v"]],diff:[["--cached","-M","-C","-z","--raw","--no-abbrev"],["--name-only","-z",eq("--diff-filter=","filter"),k("rev"),k("rev"),"--"],["--name-status","-M","-z",k("range"),"--"],["--cached","--quiet",k("rev"),"--"],["--no-renames","--name-only","-z",k("range"),"--",k("path")],["--name-only","-z",k("range"),"--"],["--name-only",eq("--diff-filter=","filter")]],"diff-files":[["--name-only","-z"]],"diff-tree":[["-r","-m","--no-commit-id","--no-renames",eq("--diff-filter=","filter"),"--raw","-z",k("rev")]],"for-each-ref":[[FORMAT,rep(1,k("refpat"))]],"hash-object":[[opt("-w"),"--no-filters","--stdin"],[opt("-w"),eq("--path=","relpath"),"--stdin"]],init:[["--template="]],log:[["-1",FORMAT,k("rev")],[{prefix:"-",kind:"count"},FORMAT,k("rev")],[FORMAT,"--name-only","-z","--no-renames","--diff-merges=first-parent",eq("--diff-filter=","filter"),rep(0,k("revish")),"--"],[LOG_RECORD,opt("--name-only","-z","--no-renames","--full-diff"),opt("--fixed-strings","--all-match",rep(1,eq("--grep=","msg"))),opt("-n",k("count")),opt(eq("--since=","iso")),opt(k("revish")),opt("--",rep(1,k("path")))]],"ls-files":[["--stage","-z","--",k("path")],["--eol","-z"]],"ls-remote":[[k("source"),k("ref")]],"ls-tree":[["-r","--name-only","-z",k("rev"),opt("--",k("path"))],["-r","-l","-z",k("rev")],["-r","-z",k("rev")],["-z",k("rev"),"--",k("path")]],maintenance:[["run","--task=loose-objects","--quiet"]],merge:[[],["--abort"],[opt("--no-ff"),opt("-m",k("msg")),k("rev")],["--no-ff",k("rev"),rep(1,"-m",k("msg"))]],"merge-base":[["--is-ancestor",k("rev"),k("rev")]],"prune-packed":[["--quiet"]],push:[["--quiet",k("target"),k("refspec")]],"read-tree":[["--empty"],[k("rev")]],remote:[["-v"]],reset:[["--soft",k("rev")]],restore:[["--source=HEAD","--staged",opt("--worktree"),"--",rep(1,k("path"))]],"rev-list":[[opt("--count"),k("range")],["--reverse",k("range")]],"rev-parse":[["--verify",opt("--quiet"),k("rev")],["-q","--verify",k("rev")],["--git-path",k("gitpath")],["--git-common-dir"]],rm:[["-q","--cached",opt("-f"),"--ignore-unmatch","--",rep(1,k("path"))],["-rf","-q","--ignore-unmatch","--",k("path")]],show:[["-s",FORMAT,k("rev")],[k("blobref")]],"show-ref":[["--verify",k("ref")]],status:[["--porcelain",opt("--untracked-files=all",opt("--",rep(1,k("path"))))]],"symbolic-ref":[["HEAD",k("ref")]],"update-index":[["--force-remove","--",k("path")],["--add","--cacheinfo",k("mode"),k("oid"),k("path")],["-q","-z","--stdin"]],"update-ref":[["-m",k("msg"),"HEAD",k("rev"),k("rev")]],worktree:[["add","-b",k("branch"),k("worktree"),k("rev")],["remove",opt("--force"),k("worktree")],["list","--porcelain"],["prune"]],"write-tree":[[]]};function match(items,args,at,paths,then){let[item,...rest]=items;if(item===void 0)return then(at);let next=to=>match(rest,args,to,paths,then);if(typeof item=="string")return args[at]===item&&next(at+1);if("optional"in item)return match(item.optional,args,at,paths,next)||next(at);if("repeat"in item){let again=(count,from)=>count>=item.min&&next(from)||match(item.repeat,args,from,paths,to=>to>from&&again(count+1,to));return again(0,at)}let arg=args[at];if(arg===void 0)return!1;let value="prefix"in item?arg.startsWith(item.prefix)?arg.slice(item.prefix.length):void 0:arg;if(value===void 0||!KINDS[item.kind](value))return!1;let kind=item.kind,typed=kind==="path"||kind==="worktree"||(kind==="source"||kind==="target")&&localCandidate(value);return typed&&paths.push({kind,value}),next(at+1)?!0:(typed&&paths.pop(),!1)}function matchShape(sub,args){for(let shape of SHAPES[sub]??[]){let paths=[];if(match(shape,args,0,paths,at=>at===args.length))return paths}}var HAND_GIT_PREFIX=["-c","core.fsmonitor=false","-c","protocol.file.allow=always"],SUBCOMMANDS=new Set(["add","branch","cat-file","checkout","commit","commit-tree","config","count-objects","diff","diff-files","diff-tree","for-each-ref","hash-object","init","log","ls-files","ls-remote","ls-tree","maintenance","merge","merge-base","prune-packed","push","read-tree","remote","reset","restore","rev-list","rev-parse","rm","show","show-ref","status","symbolic-ref","update-index","update-ref","worktree","write-tree"]);function configKey(key){let parts=key.split(".");if(parts.length<2)return key;let section=parts[0]?.toLowerCase()??"",name=parts[parts.length-1]?.toLowerCase()??"";return[section,...parts.slice(1,-1),name].join(".")}var keySet=keys=>new Set(keys.map(configKey)),CALLER_C_KEYS=keySet(["maintenance.auto","gc.auto","user.name","user.email","core.autocrlf","log.showRoot","core.quotePath","log.showSignature","log.follow"]),CONFIG_KEYS=keySet(["omo.agentId","user.name","user.email","commit.gpgsign","gc.auto","core.autocrlf","omo.memoryRepository.url","omo.sync.binding","omo.sync.space"]);function subcommandArgs(sub,rest){if(sub==="config"){let[scope,first,second,extra]=rest;if(scope!=="--local"||first===void 0||extra!==void 0)return"config shape";let key=first==="--get"||first==="--unset-all"?second:first;return key===void 0||first!=="--get"&&first!=="--unset-all"&&(second??"-").startsWith("-")?"config shape":CONFIG_KEYS.has(configKey(key))?[]:`config key ${key}`}return matchShape(sub,rest)??`${sub} shape`}function planGit(argv){let index=0;for(;argv[index]?.startsWith("-");){let arg=argv[index]??"";if(arg==="--literal-pathspecs"){index++;continue}if(arg!=="-c")return arg;let setting=argv[index+1]??"",separator=setting.indexOf("=");if(separator<=0||!CALLER_C_KEYS.has(configKey(setting.slice(0,separator))))return`-c ${setting}`;index+=2}let sub=argv[index];if(sub===void 0||!SUBCOMMANDS.has(sub))return`subcommand ${sub??"(none)"}`;let paths=subcommandArgs(sub,argv.slice(index+1));return typeof paths=="string"?paths:{argv:[...HAND_GIT_PREFIX,...argv],paths}}var equal=(args,expected)=>args.length===expected.length&&args.every((arg,index)=>arg===expected[index]);function planLsof(argv,uid){let holders=argv.length===3&&argv[0]==="-t"&&argv[1]==="--"&&(argv[2]??"").length>0,inUse=equal(argv,["-w","-a","-d","cwd","-u",String(uid),"-Fpn"]);return holders||inUse?[...argv]:"lsof shape"}var CALLER_ENV={GIT_TERMINAL_PROMPT:value=>value==="0",GIT_INDEX_FILE:value=>value.length>0,GIT_GLOB_PATHSPECS:value=>value==="0"||value==="1",GIT_AUTHOR_NAME:()=>!0,GIT_AUTHOR_EMAIL:()=>!0,GIT_COMMITTER_NAME:()=>!0,GIT_COMMITTER_EMAIL:()=>!0},WIN32_BASELINE=["SYSTEMROOT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","PATHEXT"];function baseline(context){let env={},keep=key=>{let value=context.ownEnv[key];value!==void 0&&(env[key]=value)};for(let key of["PATH","HOME","SSH_AUTH_SOCK"])keep(key);if(context.platform==="win32")for(let key of WIN32_BASELINE)keep(key);else keep("TMPDIR"),env.LANG="C";return env.GIT_PROTOCOL_FROM_USER="0",env}function planRun(request,context){let env=baseline(context);for(let[key,value]of Object.entries(request.env)){let allowed2=Object.hasOwn(CALLER_ENV,key)?CALLER_ENV[key]:void 0;if(allowed2===void 0||!allowed2(value))return{ok:!1,reason:`not in the run allowlist: env ${key}`};env[key]=value}let planned=request.exe==="git"?planGit(request.argv):request.exe==="lsof"?planLsof(request.argv,context.uid):`executable ${request.exe}`;return typeof planned=="string"?{ok:!1,reason:`not in the run allowlist: ${planned}`}:Array.isArray(planned)?{ok:!0,exe:"lsof",argv:planned,env,paths:[]}:{ok:!0,exe:"git",argv:planned.argv,env,paths:planned.paths}}var SAFE=/^[A-Za-z0-9@%+=:,./_-]+$/;function renderCommand(exe,argv){return[exe,...argv].map(arg=>SAFE.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" ")}import{execFile as execFile2}from"node:child_process";import{lstat as lstat2,stat}from"node:fs/promises";import{basename as basename3,dirname as dirname3,isAbsolute,join as join3,resolve as resolve2,sep}from"node:path";import{execFile}from"node:child_process";import{lstat,readdir,realpath}from"node:fs/promises";import{basename as basename2,dirname as dirname2,join as join2}from"node:path";var SHAPE="local_repo_shape_unsupported",WALK_BOUND=2e4,refuse=detail=>{throw new DeviceFileError("refused_by_policy",`${SHAPE}: ${detail}`)};async function kindOf(path){let entry=await lstat(path).catch(()=>{});if(entry!==void 0)return entry.isSymbolicLink()?"link":entry.isFile()?"file":entry.isDirectory()?"dir":"other"}async function noLinks(path,recursive,budget){let kind=await kindOf(path);if(kind!==void 0&&(kind==="link"&&refuse(`symlink at ${path}`),kind==="dir"))for(let name of await readdir(path)){budget.left-=1,budget.left<0&&refuse(`more than ${WALK_BOUND} entries under the repository`);let child=join2(path,name),childKind=await kindOf(child);childKind==="link"&&refuse(`symlink at ${child}`),recursive&&childKind==="dir"&&await noLinks(child,!0,budget)}}async function plainGitDir(dir){let[head,objects,refs,commondir,alternates]=await Promise.all(["HEAD","objects","refs","commondir","objects/info/alternates"].map(entry=>kindOf(join2(dir,entry))));(head!=="file"||objects!=="dir"||refs!=="dir")&&refuse(`${dir} is not a plain git directory`),(commondir!==void 0||alternates!==void 0)&&refuse(`${dir} redirects through commondir or alternates`);let budget={left:WALK_BOUND};for(let entry of["HEAD","config","packed-refs"])await noLinks(join2(dir,entry),!1,budget);await noLinks(join2(dir,"refs"),!0,budget),await noLinks(join2(dir,"hooks"),!0,budget),await noLinks(join2(dir,"logs"),!0,budget),await noLinks(join2(dir,"worktrees"),!1,budget),await noLinks(join2(dir,"objects"),!1,budget);for(let sub of["info","pack"])await noLinks(join2(dir,"objects",sub),!1,budget)}function gitConfig(file){let env={PATH:process.env.PATH??"/usr/bin:/bin",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",LANG:"C"};return new Promise((done,fail)=>{execFile("git",["config","--file",file,"--no-includes","--list","-z"],{env,timeout:3e4,windowsHide:!0},(error,stdout)=>{if(error)return fail(error);let records=String(stdout).split("\0").filter(Boolean);done(records.map(record=>{let at=record.indexOf(`
2
+ import{PresentationBroker,bootstrapRuntime,buildToolRegistry,builtInExtensions,canonicalizeFilesystemPath,childModuleRoots,createAgentSessionServices,createProjectTrustContext,createToolChildRuntime,forwardToolEvents,presetTrustsProject,resolveProjectTrusted,sessionExtensionFlagValues,toolChildModuleRoots,toolInfoOf,withFileMutationQueue,withFileMutationQueues}from"./chunk-6QXAYNO7.js";import"./chunk-5IXYN6DK.js";import"./chunk-Q4RJ4WLE.js";import"./chunk-6MRUNB3Z.js";import"./chunk-75O3CWR5.js";import"./chunk-WAGFTIT4.js";import"./chunk-NLYT7BND.js";import{SettingsManager}from"./chunk-TACOXP5H.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-FYVQEZYN.js";import"./chunk-WMDJMN5W.js";import"./chunk-GTJJ73DE.js";import{ProjectTrustStore,getSavedProjectTrust,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-PWA75RQU.js";import"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import"./chunk-5NECOJNK.js";import"./chunk-HKCFMDJN.js";import"./chunk-A3LGSX7Z.js";import"./chunk-3QPE75AR.js";import"./chunk-ULWRGKP2.js";import"./chunk-4B5JSLLR.js";import"./chunk-FWIO636S.js";import"./chunk-MOVB6H22.js";import"./chunk-DLPV4B3R.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import{closeServer,listen,prepareSocketPath}from"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import"./chunk-Z4PN2MDA.js";import"./chunk-7BX3JQ7F.js";import"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import"./chunk-C4AHHZ6P.js";import"./chunk-CEFKVI3E.js";import"./chunk-HGCQAMC6.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import"./chunk-WHQ2QPP5.js";import"./chunk-RLIY3AUC.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-2IKL4F24.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-3RILB2OD.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{localDeviceFiles}from"./chunk-ZJUL5ODW.js";import{DeviceFileError,FILE_CHANNEL_MAX_BYTES,base64Length,createReliableTransport,createRemoteExecutor,decodeBase64,decodeDeviceFileArgs,encodeBase64,fileRefusal,fileResult,serveLoopHooks}from"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import{validateToolArguments}from"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-QVG5SUSV.js";import"./chunk-GXPH7RN6.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-2SOVDETB.js";import"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import{shieldSocketDuringClose,unlinkOwnedSocket}from"./chunk-5XHOHZIR.js";import{authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{isLocalPath,resolvePath}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createServer}from"node:net";import{posix as posix2,win32}from"node:path";import{isAbsolute as isAbsolute2}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{basename as basename4,dirname as dirname4,join as join4,resolve as resolve3}from"node:path";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync}from"node:fs";import{constants as fsConstants}from"node:fs";import{open}from"node:fs/promises";import{constants as osConstants}from"node:os";import{basename,dirname,join,resolve}from"node:path";var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,RETRY_MS=5,LOCK_SH=1,LOCK_NB=4;function classifyFlockErrno(errno){let{EAGAIN,EWOULDBLOCK,ENOLCK,EOPNOTSUPP,ENOSYS}=osConstants.errno;return errno===EAGAIN||errno===EWOULDBLOCK?"busy":errno===ENOLCK||errno===EOPNOTSUPP||errno===ENOSYS?"no-lock":"failed"}function identityLocksDir(repoDir){let repo=resolve(repoDir);if(!(basename(repo)!=="repo"||basename(dirname(dirname(repo)))!=="agents"))return join(dirname(repo),"runtime","locks")}var NO_HOLD={fd:void 0,release:async()=>{}},delay=ms=>new Promise(done=>setTimeout(done,ms));async function holdActivityLock(cwd,flock,waitMs=GIT_ACTIVITY_SHARED_WAIT_MS){let locksDir=identityLocksDir(cwd);if(locksDir===void 0||flock===void 0)return NO_HOLD;if(!existsSync(locksDir))throw new DeviceFileError("not_found","the identity's locks directory does not exist");let handle=await open(join(locksDir,GIT_ACTIVITY_LOCK_NAME),fsConstants.O_RDWR|fsConstants.O_CREAT,384),deadline=Date.now()+waitMs;try{for(;;){let{rc,errno}=flock(handle.fd,LOCK_SH|LOCK_NB);if(rc===0)return{fd:handle.fd,release:()=>handle.close()};let kind=classifyFlockErrno(errno);if(kind==="no-lock")return await handle.close(),NO_HOLD;if(kind==="failed")throw new DeviceFileError("io",`flock on the git-activity lock failed (errno ${errno})`);if(Date.now()>=deadline)throw new DeviceFileError("io",`the git-activity lock stayed exclusively held for ${waitMs} ms`);await delay(RETRY_MS)}}catch(error){throw await handle.close(),error}}import{posix}from"node:path";var k=kind=>({kind}),eq=(prefix,kind)=>({prefix,kind}),opt=(...optional)=>({optional}),rep=(min,...repeat)=>({repeat,min}),NUL=/\0/,REV=/^(?![-./~:])[A-Za-z0-9._/@{}^~+-]+$/,REL=/^(?![/-])(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/,rev=value=>REV.test(value)&&!value.includes("..")&&!value.includes("//"),range=value=>{let parts=value.split("..");return parts.length===2&&parts.every(rev)},blobref=value=>{let at=value.indexOf(":");return at>=0&&(at===0||rev(value.slice(0,at)))&&REL.test(value.slice(at+1))},filesystem=value=>value.length>0&&!NUL.test(value)&&!/^[-:]/.test(value);function scheme(value){return/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(value)?.[1]}function urlIsLocal(value){let colon=value.indexOf(":"),slash=value.indexOf("/");return colon<0||slash>=0&&slash<colon||process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(value)}var unsafeUrl=value=>value.length===0||NUL.test(value)||/\s/.test(value)||value.startsWith("-")||value.includes("::");function remote(value){if(unsafeUrl(value))return!1;let named=scheme(value);return named!==void 0?named==="https"||named==="ssh":!urlIsLocal(value)}function localUrlPath(value){if(unsafeUrl(value)||scheme(value)!=="file")return;let rest=value.slice(7);if(!rest.startsWith("/")||/[?#]/.test(rest))return;let path;try{path=decodeURIComponent(rest)}catch{return}return path.length>1&&!NUL.test(path)&&!path.endsWith("/")&&posix.normalize(path)===path&&path.split("/").slice(1).every(part=>part!==""&&part!=="."&&part!=="..")?path:void 0}var localCandidate=value=>!unsafeUrl(value)&&(scheme(value)==="file"||scheme(value)===void 0&&urlIsLocal(value)),KINDS={rev,range,revish:value=>rev(value)||range(value),object:value=>rev(value)||blobref(value),blobref,ref:value=>value==="HEAD"||/^refs\/[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refpat:value=>/^refs\/[A-Za-z0-9._/-]+\*?$/.test(value)&&!value.includes(".."),branch:value=>/^(?![-./])[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refspec:value=>/^[A-Za-z0-9._/]+(?:-[A-Za-z0-9._/]+)*:[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),msg:value=>!NUL.test(value),count:value=>/^\d{1,9}$/.test(value),mode:value=>/^(?:100644|100755|120000|160000)$/.test(value),oid:value=>/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(value),filter:value=>/^[ACDMRTUXB]+$/i.test(value),fmt:value=>!NUL.test(value),iso:value=>/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value),relpath:value=>REL.test(value),gitpath:value=>value==="index"||value==="MERGE_HEAD",path:filesystem,worktree:filesystem,source:value=>remote(value)||localCandidate(value),target:value=>remote(value)||localCandidate(value)},FORMAT=eq("--format=","fmt"),LOG_RECORD="--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI",SHAPES={add:[["-A","--",rep(1,k("path"))]],branch:[["--show-current"],["-D",k("branch")]],"cat-file":[["blob",k("object")],["--batch"],["-e",k("blobref")]],checkout:[[k("rev"),"--",k("path")]],commit:[["-q","--no-verify","-m",k("msg")]],"commit-tree":[[k("rev"),opt("-p",k("rev")),"-F","-"]],"count-objects":[["-v"]],diff:[["--cached","-M","-C","-z","--raw","--no-abbrev"],["--name-only","-z",eq("--diff-filter=","filter"),k("rev"),k("rev"),"--"],["--name-status","-M","-z",k("range"),"--"],["--cached","--quiet",k("rev"),"--"],["--no-renames","--name-only","-z",k("range"),"--",k("path")],["--name-only","-z",k("range"),"--"],["--name-only",eq("--diff-filter=","filter")]],"diff-files":[["--name-only","-z"]],"diff-tree":[["-r","-m","--no-commit-id","--no-renames",eq("--diff-filter=","filter"),"--raw","-z",k("rev")]],"for-each-ref":[[FORMAT,rep(1,k("refpat"))]],"hash-object":[[opt("-w"),"--no-filters","--stdin"],[opt("-w"),eq("--path=","relpath"),"--stdin"]],init:[["--template="]],log:[["-1",FORMAT,k("rev")],[{prefix:"-",kind:"count"},FORMAT,k("rev")],[FORMAT,"--name-only","-z","--no-renames","--diff-merges=first-parent",eq("--diff-filter=","filter"),rep(0,k("revish")),"--"],[LOG_RECORD,opt("--name-only","-z","--no-renames","--full-diff"),opt("--fixed-strings","--all-match",rep(1,eq("--grep=","msg"))),opt("-n",k("count")),opt(eq("--since=","iso")),opt(k("revish")),opt("--",rep(1,k("path")))]],"ls-files":[["--stage","-z","--",k("path")],["--eol","-z"]],"ls-remote":[[k("source"),k("ref")]],"ls-tree":[["-r","--name-only","-z",k("rev"),opt("--",k("path"))],["-r","-l","-z",k("rev")],["-r","-z",k("rev")],["-z",k("rev"),"--",k("path")]],maintenance:[["run","--task=loose-objects","--quiet"]],merge:[[],["--abort"],[opt("--no-ff"),opt("-m",k("msg")),k("rev")],["--no-ff",k("rev"),rep(1,"-m",k("msg"))]],"merge-base":[["--is-ancestor",k("rev"),k("rev")]],"prune-packed":[["--quiet"]],push:[["--quiet",k("target"),k("refspec")]],"read-tree":[["--empty"],[k("rev")]],remote:[["-v"]],reset:[["--soft",k("rev")]],restore:[["--source=HEAD","--staged",opt("--worktree"),"--",rep(1,k("path"))]],"rev-list":[[opt("--count"),k("range")],["--reverse",k("range")]],"rev-parse":[["--verify",opt("--quiet"),k("rev")],["-q","--verify",k("rev")],["--git-path",k("gitpath")],["--git-common-dir"]],rm:[["-q","--cached",opt("-f"),"--ignore-unmatch","--",rep(1,k("path"))],["-rf","-q","--ignore-unmatch","--",k("path")]],show:[["-s",FORMAT,k("rev")],[k("blobref")]],"show-ref":[["--verify",k("ref")]],status:[["--porcelain",opt("--untracked-files=all",opt("--",rep(1,k("path"))))]],"symbolic-ref":[["HEAD",k("ref")]],"update-index":[["--force-remove","--",k("path")],["--add","--cacheinfo",k("mode"),k("oid"),k("path")],["-q","-z","--stdin"]],"update-ref":[["-m",k("msg"),"HEAD",k("rev"),k("rev")]],worktree:[["add","-b",k("branch"),k("worktree"),k("rev")],["remove",opt("--force"),k("worktree")],["list","--porcelain"],["prune"]],"write-tree":[[]]};function match(items,args,at,paths,then){let[item,...rest]=items;if(item===void 0)return then(at);let next=to=>match(rest,args,to,paths,then);if(typeof item=="string")return args[at]===item&&next(at+1);if("optional"in item)return match(item.optional,args,at,paths,next)||next(at);if("repeat"in item){let again=(count,from)=>count>=item.min&&next(from)||match(item.repeat,args,from,paths,to=>to>from&&again(count+1,to));return again(0,at)}let arg=args[at];if(arg===void 0)return!1;let value="prefix"in item?arg.startsWith(item.prefix)?arg.slice(item.prefix.length):void 0:arg;if(value===void 0||!KINDS[item.kind](value))return!1;let kind=item.kind,typed=kind==="path"||kind==="worktree"||(kind==="source"||kind==="target")&&localCandidate(value);return typed&&paths.push({kind,value}),next(at+1)?!0:(typed&&paths.pop(),!1)}function matchShape(sub,args){for(let shape of SHAPES[sub]??[]){let paths=[];if(match(shape,args,0,paths,at=>at===args.length))return paths}}var HAND_GIT_PREFIX=["-c","core.fsmonitor=false","-c","protocol.file.allow=always"],SUBCOMMANDS=new Set(["add","branch","cat-file","checkout","commit","commit-tree","config","count-objects","diff","diff-files","diff-tree","for-each-ref","hash-object","init","log","ls-files","ls-remote","ls-tree","maintenance","merge","merge-base","prune-packed","push","read-tree","remote","reset","restore","rev-list","rev-parse","rm","show","show-ref","status","symbolic-ref","update-index","update-ref","worktree","write-tree"]);function configKey(key){let parts=key.split(".");if(parts.length<2)return key;let section=parts[0]?.toLowerCase()??"",name=parts[parts.length-1]?.toLowerCase()??"";return[section,...parts.slice(1,-1),name].join(".")}var keySet=keys=>new Set(keys.map(configKey)),CALLER_C_KEYS=keySet(["maintenance.auto","gc.auto","user.name","user.email","core.autocrlf","log.showRoot","core.quotePath","log.showSignature","log.follow"]),CONFIG_KEYS=keySet(["omo.agentId","user.name","user.email","commit.gpgsign","gc.auto","core.autocrlf","omo.memoryRepository.url","omo.sync.binding","omo.sync.space"]);function subcommandArgs(sub,rest){if(sub==="config"){let[scope,first,second,extra]=rest;if(scope!=="--local"||first===void 0||extra!==void 0)return"config shape";let key=first==="--get"||first==="--unset-all"?second:first;return key===void 0||first!=="--get"&&first!=="--unset-all"&&(second??"-").startsWith("-")?"config shape":CONFIG_KEYS.has(configKey(key))?[]:`config key ${key}`}return matchShape(sub,rest)??`${sub} shape`}function planGit(argv){let index=0;for(;argv[index]?.startsWith("-");){let arg=argv[index]??"";if(arg==="--literal-pathspecs"){index++;continue}if(arg!=="-c")return arg;let setting=argv[index+1]??"",separator=setting.indexOf("=");if(separator<=0||!CALLER_C_KEYS.has(configKey(setting.slice(0,separator))))return`-c ${setting}`;index+=2}let sub=argv[index];if(sub===void 0||!SUBCOMMANDS.has(sub))return`subcommand ${sub??"(none)"}`;let paths=subcommandArgs(sub,argv.slice(index+1));return typeof paths=="string"?paths:{argv:[...HAND_GIT_PREFIX,...argv],paths}}var equal=(args,expected)=>args.length===expected.length&&args.every((arg,index)=>arg===expected[index]);function planLsof(argv,uid){let holders=argv.length===3&&argv[0]==="-t"&&argv[1]==="--"&&(argv[2]??"").length>0,inUse=equal(argv,["-w","-a","-d","cwd","-u",String(uid),"-Fpn"]);return holders||inUse?[...argv]:"lsof shape"}var CALLER_ENV={GIT_TERMINAL_PROMPT:value=>value==="0",GIT_INDEX_FILE:value=>value.length>0,GIT_GLOB_PATHSPECS:value=>value==="0"||value==="1",GIT_AUTHOR_NAME:()=>!0,GIT_AUTHOR_EMAIL:()=>!0,GIT_COMMITTER_NAME:()=>!0,GIT_COMMITTER_EMAIL:()=>!0},WIN32_BASELINE=["SYSTEMROOT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","PATHEXT"];function baseline(context){let env={},keep=key=>{let value=context.ownEnv[key];value!==void 0&&(env[key]=value)};for(let key of["PATH","HOME","SSH_AUTH_SOCK"])keep(key);if(context.platform==="win32")for(let key of WIN32_BASELINE)keep(key);else keep("TMPDIR"),env.LANG="C";return env.GIT_PROTOCOL_FROM_USER="0",env}function planRun(request,context){let env=baseline(context);for(let[key,value]of Object.entries(request.env)){let allowed2=Object.hasOwn(CALLER_ENV,key)?CALLER_ENV[key]:void 0;if(allowed2===void 0||!allowed2(value))return{ok:!1,reason:`not in the run allowlist: env ${key}`};env[key]=value}let planned=request.exe==="git"?planGit(request.argv):request.exe==="lsof"?planLsof(request.argv,context.uid):`executable ${request.exe}`;return typeof planned=="string"?{ok:!1,reason:`not in the run allowlist: ${planned}`}:Array.isArray(planned)?{ok:!0,exe:"lsof",argv:planned,env,paths:[]}:{ok:!0,exe:"git",argv:planned.argv,env,paths:planned.paths}}var SAFE=/^[A-Za-z0-9@%+=:,./_-]+$/;function renderCommand(exe,argv){return[exe,...argv].map(arg=>SAFE.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" ")}import{execFile as execFile2}from"node:child_process";import{lstat as lstat2,stat}from"node:fs/promises";import{basename as basename3,dirname as dirname3,isAbsolute,join as join3,resolve as resolve2,sep}from"node:path";import{execFile}from"node:child_process";import{lstat,readdir,realpath}from"node:fs/promises";import{basename as basename2,dirname as dirname2,join as join2}from"node:path";var SHAPE="local_repo_shape_unsupported",WALK_BOUND=2e4,refuse=detail=>{throw new DeviceFileError("refused_by_policy",`${SHAPE}: ${detail}`)};async function kindOf(path){let entry=await lstat(path).catch(()=>{});if(entry!==void 0)return entry.isSymbolicLink()?"link":entry.isFile()?"file":entry.isDirectory()?"dir":"other"}async function noLinks(path,recursive,budget){let kind=await kindOf(path);if(kind!==void 0&&(kind==="link"&&refuse(`symlink at ${path}`),kind==="dir"))for(let name of await readdir(path)){budget.left-=1,budget.left<0&&refuse(`more than ${WALK_BOUND} entries under the repository`);let child=join2(path,name),childKind=await kindOf(child);childKind==="link"&&refuse(`symlink at ${child}`),recursive&&childKind==="dir"&&await noLinks(child,!0,budget)}}async function plainGitDir(dir){let[head,objects,refs,commondir,alternates]=await Promise.all(["HEAD","objects","refs","commondir","objects/info/alternates"].map(entry=>kindOf(join2(dir,entry))));(head!=="file"||objects!=="dir"||refs!=="dir")&&refuse(`${dir} is not a plain git directory`),(commondir!==void 0||alternates!==void 0)&&refuse(`${dir} redirects through commondir or alternates`);let budget={left:WALK_BOUND};for(let entry of["HEAD","config","packed-refs"])await noLinks(join2(dir,entry),!1,budget);await noLinks(join2(dir,"refs"),!0,budget),await noLinks(join2(dir,"hooks"),!0,budget),await noLinks(join2(dir,"logs"),!0,budget),await noLinks(join2(dir,"worktrees"),!1,budget),await noLinks(join2(dir,"objects"),!1,budget);for(let sub of["info","pack"])await noLinks(join2(dir,"objects",sub),!1,budget)}function gitConfig(file){let env={PATH:process.env.PATH??"/usr/bin:/bin",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",LANG:"C"};return new Promise((done,fail)=>{execFile("git",["config","--file",file,"--no-includes","--list","-z"],{env,timeout:3e4,windowsHide:!0},(error,stdout)=>{if(error)return fail(error);let records=String(stdout).split("\0").filter(Boolean);done(records.map(record=>{let at=record.indexOf(`
3
3
  `);return at<0?[record,""]:[record.slice(0,at),record.slice(at+1)]}))})})}var INIT_KEYS=new Set(["core.repositoryformatversion","core.filemode","core.bare","core.ignorecase","core.precomposeunicode","core.logallrefupdates"]),CLONE_KEY=/^remote\..+\.(?:url|fetch|mirror|tagopt)$/,WORKING_CLONE_KEY=/^branch\..+\.(?:remote|merge)$|^user\.(?:name|email)$/;async function allowlistedConfig(dir,bare){let config=join2(dir,"config");await kindOf(config)!=="file"&&refuse(`${dir} has no config file`);let entries=await gitConfig(config).catch(()=>refuse("target config is unreadable"));for(let[key,value]of entries){if(key==="core.bare"){value!==String(bare)&&refuse(`core.bare=${value} on a ${bare?"bare":"working-clone"} target`);continue}INIT_KEYS.has(key)||CLONE_KEY.test(key)||!bare&&WORKING_CLONE_KEY.test(key)||refuse(`target config key ${key} is not allowlisted`)}}async function canonicalLocalRepo(path){let parent=await realpath(dirname2(path)).catch(()=>refuse(`no repository at ${path}`)),real=join2(parent,basename2(path)),self=await kindOf(real);self==="link"&&refuse(`${path} is a symlink`),self!=="dir"&&refuse(`no repository at ${path}`),await kindOf(`${real}.git`)!==void 0&&refuse(`${path}.git exists`);let dotGit=await kindOf(join2(real,".git"));dotGit!==void 0&&dotGit!=="dir"&&refuse(`${path}/.git is not a directory`);let gitDir=dotGit==="dir"?join2(real,".git"):real;return await plainGitDir(gitDir),await allowlistedConfig(gitDir,dotGit!=="dir"),gitDir}var MIN_GIT=[2,29];function git(argv,cwd,env){return new Promise((done,fail)=>{execFile2("git",[...argv],{cwd,env,timeout:3e4,windowsHide:!0},(error,stdout)=>error?fail(error):done(String(stdout)))})}var versionChecked;function gitIsSupported(env){return versionChecked??=git(["--version"],process.cwd(),env).then(output=>{let match2=/git version (\d+)\.(\d+)/.exec(output);if(match2===null)return!1;let[major,minor]=[Number(match2[1]),Number(match2[2])];return major>MIN_GIT[0]||major===MIN_GIT[0]&&minor>=MIN_GIT[1]},()=>!1),versionChecked}async function runDirectory(root,cwd){let canonical=await canonicalizeFilesystemPath(resolve2(root,cwd)),entry=await stat(canonical).catch(()=>{});if(entry===void 0)throw new DeviceFileError("not_found",cwd);if(!entry.isDirectory())throw new DeviceFileError("not_a_file",cwd);return canonical}var inside=(path,dir)=>path===dir||path.startsWith(`${dir}${sep}`);async function confinedIndexFile(value,cwd,env){if(!isAbsolute(value))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE must be absolute");let dirs=await gitDirs(cwd,env),parent=await canonicalizeFilesystemPath(dirname3(value));if(!dirs.some(dir=>inside(parent,dir)))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE is outside the repository's git directory");return join3(parent,basename3(value))}async function hasUrlRewrites(cwd,env){return(await git(["config","--get-regexp","^url\\."],cwd,env).catch(error=>error.code===1?"":Promise.reject(error))).trim().length>0}async function gitDirs(cwd,env){let[gitDir,commonDir]=(await git(["rev-parse","--absolute-git-dir","--git-common-dir"],cwd,env)).trim().split(`
4
4
  `);if(gitDir===void 0||commonDir===void 0)throw new DeviceFileError("refused_by_policy","no repository at cwd");return Promise.all([gitDir,resolve2(cwd,commonDir)].map(dir=>canonicalizeFilesystemPath(dir)))}async function canonicalTarget(raw,cwd){let target=resolve2(cwd,raw);if((await lstat2(target).catch(()=>{}))?.isSymbolicLink()===!0)throw new DeviceFileError("refused_by_policy",`symlink: ${raw}`);return join3(await canonicalizeFilesystemPath(dirname3(target)),basename3(target))}async function confinePaths(paths,cwd,env){if(paths.length===0)return[];let dirs=await gitDirs(cwd,env),top=await git(["rev-parse","--show-toplevel"],cwd,env).then(output=>canonicalizeFilesystemPath(output.trim()),()=>{}),targets=[];for(let{kind,value}of paths){if(kind==="source"||kind==="target"){let local=localUrlPath(value);if(local===void 0)throw new DeviceFileError("refused_by_policy",`local_repo_shape_unsupported: only an absolute file:// url: ${value}`);let operation=kind==="source"?"read":"write";targets.push({operation,canonicalPath:await canonicalLocalRepo(local)});continue}let canonical=await canonicalTarget(value,cwd),inGitDir=dirs.some(dir=>inside(canonical,dir)||kind==="worktree"&&inside(dir,canonical));if(kind==="worktree"){if(inGitDir)throw new DeviceFileError("refused_by_policy","worktree path is inside the repository's git directory");targets.push({operation:"write",canonicalPath:canonical})}else if(!inGitDir&&(top===void 0||!inside(canonical,top)))throw new DeviceFileError("refused_by_policy",`path outside the repository: ${value}`)}return targets}var HARDENED_RECEIVE_PACK=["git","-c core.hooksPath=/dev/null","-c receive.denyCurrentBranch=refuse","-c core.fsmonitor=false","-c receive.autogc=false","-c gc.auto=0","-c maintenance.auto=false","receive-pack"].join(" "),CLIENT_LOCAL_GUARDS=["-c","core.hooksPath=/dev/null"],REMOTE_GUARDS=["-c","protocol.file.allow=never","-c","protocol.ext.allow=never","-c","protocol.fd.allow=never"];function subcommandAt(argv){let index=0;for(;index<argv.length&&(argv[index]??"").startsWith("-");)index+=argv[index]==="-c"?2:1;return index}function transportFor(argv,env,paths){let at=subcommandAt(argv),sub=argv[at];if(paths.some(path=>path.kind==="source"||path.kind==="target")){let pushed=sub==="push"?[`--receive-pack=${HARDENED_RECEIVE_PACK}`]:[];return{argv:[...argv.slice(0,at),...CLIENT_LOCAL_GUARDS,argv[at]??"",...pushed,...argv.slice(at+1)],env:{...env,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"},local:!0}}return sub==="ls-remote"||sub==="push"?{argv:[...argv.slice(0,at),...REMOTE_GUARDS,...argv.slice(at)],env,local:!1}:{argv:[...argv],env,local:!1}}var RUN_TIMEOUT_CAP_MS=3e5,DEFAULT_TIMEOUT_MS=3e4,KILL_GRACE_MS=1e4;async function judged(guards,command,nested){let input={command},decision;try{decision=await guards.beforeToolCall("bash",`run-${randomUUID()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.command!==command)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the command")}async function runOnHand(args,deps,signal){let plan=planRun({exe:args.exe,argv:args.argv,env:args.env},deps.context);if(!plan.ok)throw new DeviceFileError("refused_by_policy",plan.reason);if(args.stdin!==void 0&&base64Length(args.stdin)>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large","stdin");let cwd=await runDirectory(deps.root,args.cwd),verdict=await deps.guards.filesystemPolicy()?.({operation:"write",canonicalPath:cwd,toolName:"bash"});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);let transport=plan.exe==="git"?transportFor(plan.argv,plan.env,plan.paths):{argv:plan.argv,env:plan.env,local:!1},env={...transport.env};if(plan.exe==="git"){if(!await gitIsSupported(env))throw new DeviceFileError("unsupported","git 2.29 or newer is required");if(transport.local&&await hasUrlRewrites(cwd,env))throw new DeviceFileError("refused_by_policy","local_url_rewritten: a url.* rewrite is configured")}if(await judged(deps.guards,renderCommand(plan.exe,transport.argv),deps.nested),plan.exe==="git"){env.GIT_INDEX_FILE!==void 0&&(env.GIT_INDEX_FILE=await confinedIndexFile(env.GIT_INDEX_FILE,cwd,env));for(let{operation,canonicalPath}of await confinePaths(plan.paths,cwd,env)){let decision=await deps.guards.filesystemPolicy()?.({operation,canonicalPath,toolName:"bash"});if(decision!==void 0&&!decision.allow)throw new DeviceFileError("refused_by_policy",decision.reason)}}let hold=args.activityLock===!0&&plan.exe==="git"?await holdActivityLock(cwd,deps.flock):void 0;try{return await spawnBounded(plan.exe,transport.argv,cwd,env,args,hold?.fd,signal)}finally{await hold?.release()}}function spawnBounded(exe,argv,cwd,env,args,lockFd,signal){return new Promise((done,fail)=>{let child=spawn(exe,[...argv],{cwd,env,shell:!1,windowsHide:!0,stdio:["pipe","pipe","pipe",lockFd??"ignore"]}),out=[],err=[],size={out:0,err:0},overflow=!1,killTimer,stop=()=>{child.exitCode===null&&child.signalCode===null&&child.kill("SIGTERM"),killTimer??=setTimeout(()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stderr?.destroy()},KILL_GRACE_MS)},timeout=setTimeout(stop,Math.min(args.timeoutMs??DEFAULT_TIMEOUT_MS,RUN_TIMEOUT_CAP_MS)),onAbort=()=>stop();signal.addEventListener("abort",onAbort,{once:!0});let collect=(into,key)=>chunk=>{if(size={...size,[key]:size[key]+chunk.length},size[key]>FILE_CHANNEL_MAX_BYTES){overflow=!0,stop();return}into.push(chunk)};child.stdout?.on("data",collect(out,"out")),child.stderr?.on("data",collect(err,"err")),child.on("error",error=>fail(new DeviceFileError("io",error.message))),child.on("close",(code,exitSignal)=>{if(clearTimeout(timeout),killTimer!==void 0&&clearTimeout(killTimer),signal.removeEventListener("abort",onAbort),signal.aborted)return fail(new DeviceFileError("aborted","the run was aborted"));if(overflow)return fail(new DeviceFileError("too_large","the run's output passed the limit"));done({code,signal:exitSignal,stdout:encodeBase64(new Uint8Array(Buffer.concat(out))),stderr:Buffer.concat(err).toString("utf8")})}),child.stdin?.on("error",()=>{}),child.stdin?.end(args.stdin===void 0?void 0:Buffer.from(decodeBase64(args.stdin)))})}function checksOf(args){switch(args.op){case"read":return[{toolName:"read",operation:"read",path:args.path}];case"list":return[{toolName:"ls",operation:"enumerate",path:args.path}];case"stat":return[{toolName:"ls",operation:"enumerate",path:args.path,entry:!0}];case"write":return[{toolName:"write",operation:"write",path:args.path,content:new TextDecoder().decode(decodeBase64(args.data))}];case"rename":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0},{toolName:"write",operation:"write",path:args.to,content:"",entry:!0}];case"remove":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0}];case"mkdir":return[{toolName:"write",operation:"write",path:args.path,content:""}]}}async function canonicalOf(path,entry){return entry?join4(await canonicalizeFilesystemPath(dirname4(path)),basename4(path)):canonicalizeFilesystemPath(path)}async function allowed(guards,root,check,nested){let content=check.content??"",input=check.toolName==="write"?{path:check.path,content}:{path:check.path},decision;try{decision=await guards.beforeToolCall(check.toolName,`file-${randomUUID2()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.path!==check.path||check.toolName==="write"&&input.content!==content)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the operation");let canonicalPath=await canonicalOf(resolve3(root,check.path),check.entry===!0),verdict=await guards.filesystemPolicy()?.({operation:check.operation,canonicalPath,toolName:check.toolName});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);return canonicalPath}function createHandFileOps(root,guards,run){let files=localDeviceFiles();return async(op,rawArgs,signal,nested)=>{let args=decodeDeviceFileArgs(op,rawArgs);if(args===void 0)return fileRefusal("protocol",`malformed ${op} arguments`);if(args.op==="run"){if(run===void 0)return fileRefusal("unsupported","this hand serves no run channel");try{let{exe,argv,env,stdin,timeoutMs,activityLock}=args,request={exe,argv,cwd:args.path,env,activityLock,...stdin===void 0?{}:{stdin},...timeoutMs===void 0?{}:{timeoutMs}},outcome=await runOnHand(request,{root,guards,context:run.context,flock:run.flock,...nested?{nested}:{}},signal);return fileResult({ok:!0,value:{...outcome}})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}if(args.op==="write"&&base64Length(args.data)>FILE_CHANNEL_MAX_BYTES)return fileRefusal("too_large",args.path);try{let[target,destination]=await Promise.all(checksOf(args).map(check=>allowed(guards,root,check,nested)));if(target===void 0)return fileRefusal("protocol","no target");let options={signal};switch(args.op){case"read":return fileResult({ok:!0,value:encodeBase64(await files.read(target,options))});case"list":return fileResult({ok:!0,value:[...await files.list(target,options)]});case"stat":return fileResult({ok:!0,value:{...await files.stat(target,options)}});case"write":{let data=decodeBase64(args.data);await withFileMutationQueue(target,()=>files.write(target,data,{...options,exclusive:args.exclusive}));break}case"rename":await withFileMutationQueues([target,destination??target],()=>files.rename(target,destination??target,options));break;case"remove":await withFileMutationQueue(target,()=>files.remove(target,options));break;case"mkdir":await files.mkdir(target,options);break}return fileResult({ok:!0,value:null})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}}var bound;function loadFlock(){return bound===void 0&&(bound=bindFlock()??null),bound??void 0}function bindFlock(){if(process.platform!=="darwin"&&process.platform!=="linux")return;let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return;let errnoSymbol=process.platform==="darwin"?"__error":"__errno_location";try{let library=ffi.dlopen(process.platform==="darwin"?"libSystem.B.dylib":"libc.so.6",{flock:{args:[ffi.FFIType.i32,ffi.FFIType.i32],returns:ffi.FFIType.i32},[errnoSymbol]:{args:[],returns:ffi.FFIType.ptr}}),errnoPointer=library.symbols[errnoSymbol];return(fd,operation)=>{let rc=Number(library.symbols.flock(fd,operation));if(rc===0||errnoPointer===void 0)return{rc,errno:0};let pointer=errnoPointer();return{rc,errno:typeof pointer=="number"&&pointer!==0?ffi.read.i32(pointer,0):-1}}}catch{return}}var LOOPLESS_EXECUTE_CALLERS=["in-process-test-harness","remote-tool-executor"],issued=new WeakSet,LooplessExecuteRefusedError=class extends Error{constructor(reason){super(`loopless_execute_refused: ${reason}`)}};function grantLooplessExecuteToRemoteExecutor(){let grant=Object.freeze({caller:"remote-tool-executor"});return issued.add(grant),grant}function looplessGrantRunsToolHandlers(grant){return isLooplessExecuteGranted(grant)&&grant?.caller==="remote-tool-executor"}function isLooplessExecuteGranted(grant){return grant!==void 0&&issued.has(grant)&&LOOPLESS_EXECUTE_CALLERS.includes(grant.caller)}import{randomUUID as randomUUID3}from"node:crypto";async function resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics){let{parsed,agentDir,appMode}=configuration,{cwd,launchProfile}=profile,trustStore=new ProjectTrustStore(agentDir),flagValues=sessionExtensionFlagValues(parsed.unknownFlags,launchProfile),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd),savedProjectTrust=await getSavedProjectTrust(trustStore,cwd),globalPreset=startupSettingsManager.getGlobalSettings().permissionPreset,fullAccessTrust=presetTrustsProject(flagValues.get("permission-preset"),globalPreset)&&savedProjectTrust!==!1,shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&!fullAccessTrust&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:parsed.projectTrustOverride??(fullAccessTrust||!hasTrustRequiringResources||savedProjectTrust===!0),trustFromFullAccess=fullAccessTrust&&hasTrustRequiringResources&&parsed.projectTrustOverride===void 0&&savedProjectTrust!==!0;return{settingsManager:SettingsManager.create(cwd,agentDir,{projectTrusted,trustFromFullAccess,projectTrustLocked:parsed.projectTrustOverride!==void 0}),flagValues,reloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:({extensionsResult})=>resolveProjectTrusted({cwd,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd,mode:appMode,settingsManager:startupSettingsManager,hasUI:!1}),onExtensionError:message=>diagnostics.push({type:"warning",message})})}:void 0}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}function looplessToolFilters(parsed,settingsManager){let noTools=parsed.noTools?"all":parsed.noBuiltinTools?"builtin":void 0,defaultToolNames=parsed.tools===void 0&&noTools===void 0?settingsManager.getDefaultTools():void 0,allowedToolNames=parsed.tools??(noTools==="all"?[]:void 0);return{...defaultToolNames===void 0?{}:{defaultToolNames:new Set(defaultToolNames)},...allowedToolNames===void 0?{}:{allowedToolNames:new Set(allowedToolNames)},...parsed.excludeTools===void 0?{}:{excludedToolNames:new Set(parsed.excludeTools)}}}function errorResult(message){return{content:[{type:"text",text:message}],details:void 0,isError:!0}}function withOverride(result,override){let structuredContent=override.structuredContent??(override.content?void 0:result.structuredContent),next={...result,content:override.content??result.content,details:override.details??result.details,usage:override.usage??result.usage,isError:override.isError??result.isError===!0};return structuredContent===void 0?delete next.structuredContent:next.structuredContent=structuredContent,next}async function runLooplessToolCall(tool,call,handlers){let{toolCallId,signal}=call,nested=call.nested===void 0?{}:{nested:call.nested},args;try{let prepared=tool.prepareArguments?tool.prepareArguments(call.params):call.params,toolCall={type:"toolCall",id:toolCallId,name:tool.name,arguments:prepared};args=validateToolArguments(tool,toolCall)}catch(error){return errorResult(error instanceof Error?error.message:String(error))}if(handlers){let before;try{before=await handlers.beforeToolCall({toolName:tool.name,toolCallId,input:args,...nested})}catch(error){return errorResult(error instanceof Error?error.message:`Extension failed, blocking execution: ${String(error)}`)}if(signal?.aborted)return errorResult("Operation aborted");if(before?.block){let blocked=errorResult(before.reason||"Tool execution was blocked");return before.terminate===!0&&(blocked.terminate=!0),blocked}}let result;try{result=await tool.execute(toolCallId,args,signal,void 0)}catch(error){result=errorResult(error instanceof Error?error.message:String(error))}if(!handlers)return result;try{let override=await handlers.afterToolCall({toolName:tool.name,toolCallId,input:args,result,isError:result.isError===!0,...nested});return override?withOverride(result,override):result}catch(error){return errorResult(error instanceof Error?error.message:String(error))}}import{AsyncLocalStorage}from"node:async_hooks";var REVOCATION_MAX_AGE_MS=360*60*1e3;var REQUIRED_STRINGS=["accountId","sigKeyId","sigPkSha256"],OPTIONAL_STRINGS=["kemKeyId","kemPkSha256","supersedes"],RECORD_KEYS=["kind","generation","kmsKeyArns","templateVersion","verifierKeyId","vouchedAt","checkedAt",...REQUIRED_STRINGS,...OPTIONAL_STRINGS];var HookContractError=class extends Error{constructor(){super(...arguments),this.name="HookContractError"}};var isPlainObject=value=>{if(typeof value!="object"||value===null||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};function wireJson(value,at){if(value===null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number"){if(Number.isFinite(value))return value;throw new HookContractError(`${at} is not a finite number`)}if(Array.isArray(value))return value.map((item,index)=>wireJson(item,`${at}[${index}]`));if(isPlainObject(value)){let out={};for(let[key,member]of Object.entries(value))member!==void 0&&(out[key]=wireJson(member,`${at}.${key}`));return out}throw new HookContractError(`${at} is not JSON`)}function hookRequestOutputOf(input,payload){let out=wireJson(payload,"payload");return input.model===void 0?{payload:out}:{payload:out,model:input.model}}var MODEL_STRING_FIELDS=["id","name","api","provider","baseUrl"];function parseHookRequestInput(value){if(!isPlainObject(value)||!("payload"in value))throw new HookContractError("hook input is not an object with a payload");let extra=Object.keys(value).filter(key=>key!=="payload"&&key!=="model");if(extra.length>0)throw new HookContractError(`hook input has unknown members: ${extra.join(", ")}`);let payload=wireJson(value.payload,"payload");if(value.model===void 0)return{payload};let model=value.model;if(!isPlainObject(model)||MODEL_STRING_FIELDS.some(field=>typeof model[field]!="string"))throw new HookContractError("hook input model is not a model");if("headers"in model)throw new HookContractError("hook input model carries headers");return{payload,model:wireJson(model,"model")}}function hookModelOf(input){return input.model}function extensionToolHandlers(runner,twoSidedHome="loop"){let twoSided=twoSidedHome==="loop"?runner.twoSidedExtensionPaths():new Set,options=nested=>nested===void 0||twoSided.size===0?{}:{forward:forwardToolEvents(twoSided,nested)};return{beforeToolCall:({toolName,toolCallId,input,nested})=>runner.hasHandlers("tool_call")?runner.emitToolCall({type:"tool_call",toolName,toolCallId,input},options(nested)):Promise.resolve(void 0),afterToolCall:({toolName,toolCallId,input,result,isError,nested})=>runner.hasHandlers("tool_result")?runner.emitToolResult({type:"tool_result",toolName,toolCallId,input,content:result.content,details:result.details,...result.structuredContent===void 0?{}:{structuredContent:result.structuredContent},isError,usage:result.usage},options(nested)):Promise.resolve(void 0)}}var isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function extensionLoopHooks(runner,twoSidedHome,cwd,call){return async(event,payload)=>{if(twoSidedHome!=="hand")throw new Error("this hand is not the home of its extensions' loop hooks");if(!isRecord2(payload)||typeof payload.sessionId!="string"||typeof payload.idle!="boolean")throw new Error(`malformed ${event} payload`);let{sessionId,idle}=payload,images=imagesOf(payload.images);if(images===null)throw new Error(`malformed ${event} payload: images`);if(event==="input"){let{inputId,text,source,attribution,streamingBehavior}=payload;if(typeof inputId!="string"||typeof text!="string"||!isOneOf(source,INPUT_SOURCES)||!isOneOf(attribution,INPUT_ATTRIBUTIONS)||!(streamingBehavior===void 0||isOneOf(streamingBehavior,STREAMING_BEHAVIORS)))throw new Error("malformed input payload");return call.run(sessionId,cwd,idle,effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitInput(text,images,source,streamingBehavior,inputId,attribution,isUserLoopHook)))}if(event==="before_agent_start"){let{prompt,systemPrompt,trigger,preview,systemPromptOptions}=payload;if(typeof prompt!="string"||typeof systemPrompt!="string"||!isOneOf(trigger,TRIGGERS)||!(preview===void 0||typeof preview=="boolean")||!isRecord2(systemPromptOptions))throw new Error("malformed before_agent_start payload");let options={...systemPromptOptions,cwd};return call.run(sessionId,cwd,idle,effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitBeforeAgentStart(prompt,images,systemPrompt,options,{only:isUserLoopHook,trigger,...preview===void 0?{}:{preview}})))}if(event==="before_provider_request"){let input=parseHookRequestInput(payload.input),model=hookModelOf(input);return call.run(sessionId,cwd,idle,effects=>dispatchLoopHook(runner,call,effects,async()=>({output:hookRequestOutputOf(input,await runner.emitBeforeProviderRequest(structuredClone(input.payload),void 0,void 0,{only:isUserLoopHook,...model===void 0?{}:{model}}))})))}throw new Error(`no loop hooks run on a hand for ${event}`)}}var isUserLoopHook=extensionPath=>!extensionPath.startsWith("<builtin:")||extensionPath==="<builtin:hooks>",INPUT_SOURCES=["interactive","rpc","extension"],INPUT_ATTRIBUTIONS=["user","agent"],STREAMING_BEHAVIORS=["steer","followUp"],TRIGGERS=["prompt","delivery","extension"],isOneOf=(value,allowed2)=>typeof value=="string"&&allowed2.includes(value),imagesOf=value=>value===void 0?void 0:Array.isArray(value)&&value.every(isImage)?value:null,isImage=value=>isRecord2(value)&&value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string";async function dispatchLoopHook(runner,call,effects,dispatch){let own=call.current(),errors=[],stop=runner.onError(({extensionPath,event,error})=>{own!==void 0&&call.current()===own&&errors.push({extensionPath,event,error})});try{let result=await dispatch(),{sent,notices}=effects;return JSON.parse(JSON.stringify({...result,...sent.length>0?{sent}:{},...notices.length>0?{notices}:{},...effects.dropped>0?{droppedLate:effects.dropped}:{},...errors.length>0?{errors}:{}}))}finally{stop()}}var LATE_PER_SESSION=256;function createLoopHookCall(){let calls=new AsyncLocalStorage,late=new Map,holdLate=(sessionId,add)=>{let held=late.get(sessionId)??{sent:[],notices:[],dropped:0};for(add(held);held.sent.length+held.notices.length>LATE_PER_SESSION;)(held.notices.length>0?held.notices:held.sent).shift(),held.dropped++;late.set(sessionId,held)};return{current:()=>{let call=calls.getStore();return call?.live()===!0?call.facts:void 0},sender:()=>calls.getStore()?.facts.sendMessage,async run(sessionId,cwd,idle,dispatch){let live=!0,controller=new AbortController,effects=late.get(sessionId)??{sent:[],notices:[],dropped:0};late.delete(sessionId);let facts=Object.freeze({sessionManager:readOnlySession(sessionId,cwd,()=>live),signal:controller.signal,isIdle:()=>idle,sendMessage:(message,options)=>{let entry=options===void 0?{message}:{message,options};live?effects.sent.push(entry):holdLate(sessionId,held=>held.sent.push(entry))},notify:(message,type)=>{let entry=type===void 0?{message}:{message,type};live?effects.notices.push(entry):holdLate(sessionId,held=>held.notices.push(entry))}});try{return await calls.run({live:()=>live,facts},()=>dispatch(effects))}finally{live=!1,controller.abort()}}}}var LoopHookCallEndedError=class extends Error{constructor(member){super(`this loop-hook call has ended; ${member} is bound to that call only`),this.name="LoopHookCallEndedError",this.member=member}};function readOnlySession(sessionId,cwd,live){let bound2=(member,read)=>()=>{if(!live())throw new LoopHookCallEndedError(`sessionManager.${member}`);return read()},unbound=member=>()=>{throw new Error(`sessionManager.${member} is loop-side: a loop-hook call on a hand carries only the session's id`)};return Object.freeze({getSessionId:bound2("getSessionId",()=>sessionId),getSessionFile:bound2("getSessionFile",()=>{}),getCwd:bound2("getCwd",()=>cwd),getSessionDir:unbound("getSessionDir"),getLeafId:unbound("getLeafId"),getLeafEntry:unbound("getLeafEntry"),getEntry:unbound("getEntry"),getLabel:unbound("getLabel"),getBranch:unbound("getBranch"),getFullBranch:unbound("getFullBranch"),buildContextEntries:unbound("buildContextEntries"),buildSessionContext:unbound("buildSessionContext"),buildSessionProjection:unbound("buildSessionProjection"),getHeader:unbound("getHeader"),getEntries:unbound("getEntries"),reduceHistory:unbound("reduceHistory"),getTree:unbound("getTree"),getSessionName:unbound("getSessionName")})}var LooplessToolNotFoundError=class extends Error{constructor(toolName){super(`loopless_tool_not_found: ${toolName}`),this.toolName=toolName}};function createLooplessRuntimeFactory(configuration,local={}){let{parsed,agentDir,toolRuntime}=configuration,extensionFactories=local.extensionFactories??builtInExtensions,startupSettingsManager=local.startupSettingsManager??SettingsManager.create(configuration.cwd,configuration.agentDir);return async profile=>{let{cwd}=profile,diagnostics=[],{settingsManager,flagValues,reloadOptions}=await resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics),services=await createAgentSessionServices({cwd,agentDir,settingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:flagValues,...reloadOptions?{resourceLoaderReloadOptions:reloadOptions}:{},resourceLoaderOptions:{sessionKind:profile.launchProfile?.sessionKind,sessionContext:profile.launchProfile?.sessionContext,additionalExtensionPaths:resolveCliPaths(cwd,parsed.extensions),additionalSkillPaths:resolveCliPaths(cwd,parsed.skills),additionalPromptTemplatePaths:resolveCliPaths(cwd,parsed.promptTemplates),additionalThemePaths:resolveCliPaths(cwd,parsed.themes),noExtensions:parsed.noExtensions,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,extensionFactories}}),extensionsResult=services.resourceLoader.getExtensions();diagnostics.push(...services.diagnostics,...extensionsResult.errors.map(({path,error})=>({type:"warning",message:`Failed to load extension "${path}": ${error}`})),...(extensionsResult.warnings??[]).map(({path,warning})=>({type:"warning",message:`Extension package "${path}": ${warning}`})));let execute=()=>Promise.reject(new Error("Loopless runtime is not ready")),toolNames=()=>[],toolChildRuntime=createToolChildRuntime({toolRuntime:toolRuntime??"in-process",agentDir,scopeId:`loopless-${randomUUID3()}`,cwd:services.cwd,moduleRoots:()=>[...toolChildModuleRoots(runtime.extensionRunner.getAllRegisteredTools()),...childModuleRoots(runtime.extensionRunner.getAllChildModules())],hostCallDeps:{cwd:services.cwd,executeNested:async(_parentToolCallId,name,args,signal)=>{let toolCall={type:"toolCall",id:`nested-${randomUUID3()}`,name,arguments:{}},result=await execute(name,toolCall.id,args,signal);return{toolCall,result,isError:result.isError===!0}},callableToolNames:()=>toolNames(),target:()=>{},filesystemPolicy:()=>runtime.filesystemPolicy},onRecord:()=>{}}),{dispatcher,toolChild}=toolChildRuntime,runtime=bootstrapRuntime({cwd:services.cwd,settingsManager:services.settingsManager,extensionsResult,modelRegistry:services.modelRegistry,toolDispatcher:dispatcher}),registry=buildToolRegistry({baseToolDefinitions:runtime.baseToolDefinitions,runner:runtime.extensionRunner,dispatcher,...looplessToolFilters(parsed,services.settingsManager)});toolNames=()=>[...registry.toolRegistry.keys()];let getLoadedHookSources=services.resourceLoader.getLoadedHookSources?.bind(services.resourceLoader),loopHookCall=createLoopHookCall();runtime.extensionRunner.bindSessionlessFacts({getAllTools:()=>Array.from(registry.definitions.values(),toolInfoOf),loopHookCall:()=>loopHookCall.current(),loopHookSend:()=>loopHookCall.sender(),...getLoadedHookSources?{getLoadedHookSources}:{}});let presentation=new PresentationBroker(error=>runtime.extensionRunner.emitError({extensionPath:"<presentation-port>",event:"ui_presentation",error:`A presentation could not reach the attached client: ${error instanceof Error?error.message:String(error)}`}));runtime.extensionRunner.setUiBroker(presentation);let toolHandlers=looplessGrantRunsToolHandlers(local.executeGrant)?extensionToolHandlers(runtime.extensionRunner,local.twoSidedHome):void 0;execute=(name,toolCallId,params,signal,nested)=>{if(!isLooplessExecuteGranted(local.executeGrant))return Promise.reject(new LooplessExecuteRefusedError("no executor runs the tool_call/tool_result handlers for this runtime yet"));let tool=registry.toolRegistry.get(name);return tool===void 0?Promise.reject(new LooplessToolNotFoundError(name)):presentation.present(nested,()=>runLooplessToolCall(tool,{toolCallId,params,...signal?{signal}:{},...nested?{nested}:{}},toolHandlers))};let fileGuards=toolHandlers!==void 0&&isLooplessExecuteGranted(local.executeGrant)?{beforeToolCall:(toolName,toolCallId,input,nested)=>presentation.present(nested,()=>toolHandlers.beforeToolCall({toolName,toolCallId,input,...nested?{nested}:{}})),filesystemPolicy:()=>runtime.filesystemPolicy}:void 0;return{cwd:services.cwd,definitions:registry.definitions,diagnostics,fileGuards,execute:(name,toolCallId,params,signal,nested)=>execute(name,toolCallId,params,signal,nested),runLoopHooks:extensionLoopHooks(runtime.extensionRunner,local.twoSidedHome??"loop",services.cwd,loopHookCall),dispose:async()=>{runtime.extensionRunner.invalidate("This loopless runtime was disposed.");let failure=(await Promise.allSettled([dispatcher.dispose(),toolChild?.close()])).find(outcome=>outcome.status==="rejected");if(failure!==void 0)throw failure.reason}}}}var handRun={context:{uid:process.getuid?.()??-1,platform:process.platform,ownEnv:process.env},flock:loadFlock()};function notFound(name){return{content:[{type:"text",text:`Tool ${name} not found`}],details:{},isError:!0}}var isRecord3=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function scopeOf(payload){let scope=isRecord3(payload)?payload.scope:void 0;if(!isRecord3(scope)||typeof scope.id!="string"||typeof scope.root!="string")throw new Error("a loop-hook call names no scope");return{id:scope.id,root:scope.root}}function createLooplessHand(configuration,local={}){let factory=createLooplessRuntimeFactory(configuration,{...local,executeGrant:grantLooplessExecuteToRemoteExecutor()}),runtimes=new Map,disposed=new Set,closed=!1,disposals=new WeakMap,disposeOnce=runtime=>{let known=disposals.get(runtime);if(known!==void 0)return known;let disposing=runtime.dispose();return disposals.set(runtime,disposing),disposing},runtimeOf=(scope,reopen)=>{if(closed)return Promise.reject(new Error("this hand is closed"));if(!isAbsolute2(scope.root))return Promise.reject(new Error(`scope root must be an absolute path: ${JSON.stringify(scope.root)}`));let known=runtimes.get(scope.id);if(known!==void 0)return known.root===scope.root?known.runtime:Promise.reject(new Error(`scope_binding_mismatch: scope ${JSON.stringify(scope.id)} is bound to another root`));if(!reopen&&disposed.has(scope.id))return Promise.reject(new Error(`scope ${JSON.stringify(scope.id)} was disposed; its extensions' loop-hook state is gone`));disposed.delete(scope.id);let opened=factory({cwd:scope.root});return runtimes.set(scope.id,{root:scope.root,runtime:opened}),opened.catch(()=>runtimes.delete(scope.id)),opened};return{async openScope(scope){let runtime=await runtimeOf(scope,!0);return{run:call=>runtime.definitions.has(call.name)?runtime.execute(call.name,call.toolCallId,call.arguments,call.signal,call.nested):Promise.resolve(notFound(call.name)),isSequential:name=>runtime.definitions.get(name)?.definition.executionMode==="sequential",...runtime.fileGuards===void 0?{}:{file:createHandFileOps(scope.root,runtime.fileGuards,handRun)},dispose:()=>(runtimes.delete(scope.id),disposed.add(scope.id),disposeOnce(runtime))}},runLoopHooks:async(scope,event,payload)=>(await runtimeOf(scope,!1)).runLoopHooks(event,payload),loopHooks:async(event,payload)=>(await runtimeOf(scopeOf(payload),!1)).runLoopHooks(event,payload),async close(){closed=!0;let open2=[...runtimes.values()];runtimes.clear();let failures=(await Promise.allSettled(open2.map(({runtime})=>runtime.then(opened=>disposeOnce(opened),()=>{})))).flatMap(outcome=>outcome.status==="rejected"?[outcome.reason]:[]);if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,"disposing this hand's runtimes failed")}}}var isRecord4=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function encodeCarrierLine(message){if(!isRecord4(message)||typeof message.lane!="string"||typeof message.seq!="number")return;if(message.kind==="ack")return`${JSON.stringify({kind:"ack",lane:message.lane,seq:message.seq})}
5
5
  `;if(message.kind!=="data"||!(message.payload instanceof Uint8Array))return;let payload=Buffer.from(message.payload).toString("base64");return`${JSON.stringify({kind:"data",lane:message.lane,seq:message.seq,payload})}
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{createReliableTransport,createRemoteToolHost}from"./chunk-NDI6N4NJ.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{posix,win32}from"node:path";var HAND_SELECTION_ENTRY="hand_selection";function unreachableHost(){let transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:()=>()=>{}},onHandlerError:()=>{}});return transport.close(),createRemoteToolHost({transport,placement:"cross-machine"})}function recordedDevice(session){let device=null;for(let entry of session.sessionManager.getEntries()){if(entry.type!=="custom"||entry.customType!==HAND_SELECTION_ENTRY)continue;let recorded=Reflect.get(Object(entry.data),"device");device=typeof recorded=="string"?recorded:null}return device}function createHandSelection(directory,options={}){let sessions=new Map,gate=options.gate??((_id,host)=>host),stateOf=(durableSessionId,session)=>{let known=sessions.get(durableSessionId);if(known!==void 0)return known;let fresh={own:session.agent.toolHost,device:null,remote:void 0,linked:!1};return sessions.set(durableSessionId,fresh),fresh},install=(durableSessionId,session,device,remote)=>{let state=stateOf(durableSessionId,session);state.remote?.close(),sessions.set(durableSessionId,{own:state.own,device,remote:remote?.host,linked:remote?.linked??!1}),session.agent.toolHost=remote===void 0?state.own:gate(durableSessionId,remote.host),options.onChange?.(durableSessionId,device)},unreachable=()=>({host:unreachableHost(),linked:!1}),linkTo=device=>{try{return{host:createRemoteToolHost(directory.link(device)),linked:!0}}catch{return unreachable()}};return{hands:()=>directory.list(),selected:durableSessionId=>sessions.get(durableSessionId)?.device??null,select:(durableSessionId,session,device)=>{let current=stateOf(durableSessionId,session);if(current.device===device&&(device===null||current.linked))return{ok:!0};if(session.isStreaming)return{ok:!1,refusal:"session_busy"};let remote;if(device!==null){let row=directory.list().find(hand=>hand.device===device);if(row===void 0)return{ok:!1,refusal:"hand_not_listed"};if(!row.reachable)return{ok:!1,refusal:"hand_unreachable"};if(remote=linkTo(device),!remote.linked)return remote.host.close(),{ok:!1,refusal:"hand_unreachable"}}try{current.device!==device&&session.sessionManager.appendCustomEntry(HAND_SELECTION_ENTRY,{device})}catch(cause){throw remote?.host.close(),cause}return install(durableSessionId,session,device,remote),{ok:!0}},restore:(durableSessionId,session)=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),stateOf(durableSessionId,session);let device=recordedDevice(session);if(device===null)return;let row=directory.list().find(hand=>hand.device===device);install(durableSessionId,session,device,row?.reachable===!0?linkTo(device):unreachable())},release:durableSessionId=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),options.onRelease?.(durableSessionId)}}}function gatePresence(agent,presence,sessionId){let prepareRequest=agent.prepareRequest;agent.prepareRequest=async(request,signal)=>(await presence.ready(sessionId,"request",signal),await prepareRequest?.(request,signal)??void 0);let host=agent.toolHost;if(host===void 0)return;let deviceFiles=host.deviceFiles?.bind(host);agent.toolHost={execute:async(call,options)=>(await presence.ready(sessionId,"tools",options.signal),host.execute(call,options)),...deviceFiles===void 0?{}:{deviceFiles}}}var HEADLESS_SOCKET_FILE="headless.sock";function headlessSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix).join(agentDir,"rpc",HEADLESS_SOCKET_FILE)}function headlessEndpoint(agentDir,platform=process.platform,secret){return resolveSocketTransportAddress(headlessSocketPath(agentDir,platform),platform,secret)}function headlessHostOptions(options){let{presence,hands,...host}=options,runtimes=new Map,handSelection=hands===void 0?void 0:createHandSelection(hands,presence===void 0?{}:presenceHooks(presence,runtimes)),gated=presence===void 0?host.createRuntime:presenceRuntime(host.createRuntime,presence);return{...host,sessionOwner:"machine",listen:options.listen??`unix://${headlessSocketPath(options.agentDir)}`,createRuntime:handSelection===void 0?gated:handRuntime(gated,handSelection,runtimes),...presence===void 0?{}:{sessionPresence:presence.presence},...handSelection===void 0?{}:{handSelection}}}function presenceHooks(binding,runtimes){let tracking=new Map;return{gate:(sessionId,host)=>({execute:async(call,options)=>(await tracking.get(sessionId),await binding.presence.ready(sessionId,"tools",options.signal),host.execute(call,options))}),onChange:(sessionId,device)=>{let runtime=runtimes.get(sessionId),sessionHands=device!==null?[device]:runtime===void 0?[]:binding.handsOf(runtime),update=binding.presence.track(sessionId,sessionHands);update.catch(()=>{}),tracking.set(sessionId,update)},onRelease:sessionId=>{tracking.delete(sessionId)}}}function handRuntime(createRuntime,selection,runtimes){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime,sessionId=session.sessionId;runtimes.set(sessionId,runtime),selection.restore(sessionId,session);let dispose=session.dispose.bind(session);return session.dispose=()=>{runtimes.get(sessionId)===runtime&&(runtimes.delete(sessionId),selection.release(sessionId)),dispose()},runtime},createRuntime)}function presenceRuntime(createRuntime,binding){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime;return await binding.presence.track(session.sessionId,binding.handsOf(runtime)),gatePresence(session.agent,binding.presence,session.sessionId),runtime},createRuntime)}export{headlessEndpoint,headlessHostOptions,headlessSocketPath};
2
+ import{createReliableTransport,createRemoteToolHost}from"./chunk-7CXLNKEH.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{posix,win32}from"node:path";var HAND_SELECTION_ENTRY="hand_selection";function unreachableHost(){let transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:()=>()=>{}},onHandlerError:()=>{}});return transport.close(),createRemoteToolHost({transport,placement:"cross-machine"})}function recordedDevice(session){let device=null;for(let entry of session.sessionManager.getEntries()){if(entry.type!=="custom"||entry.customType!==HAND_SELECTION_ENTRY)continue;let recorded=Reflect.get(Object(entry.data),"device");device=typeof recorded=="string"?recorded:null}return device}function createHandSelection(directory,options={}){let sessions=new Map,gate=options.gate??((_id,host)=>host),stateOf=(durableSessionId,session)=>{let known=sessions.get(durableSessionId);if(known!==void 0)return known;let fresh={own:session.agent.toolHost,device:null,remote:void 0,linked:!1};return sessions.set(durableSessionId,fresh),fresh},install=(durableSessionId,session,device,remote)=>{let state=stateOf(durableSessionId,session);state.remote?.close(),sessions.set(durableSessionId,{own:state.own,device,remote:remote?.host,linked:remote?.linked??!1}),session.agent.toolHost=remote===void 0?state.own:gate(durableSessionId,remote.host),options.onChange?.(durableSessionId,device)},unreachable=()=>({host:unreachableHost(),linked:!1}),linkTo=device=>{try{return{host:createRemoteToolHost(directory.link(device)),linked:!0}}catch{return unreachable()}};return{hands:()=>directory.list(),selected:durableSessionId=>sessions.get(durableSessionId)?.device??null,select:(durableSessionId,session,device)=>{let current=stateOf(durableSessionId,session);if(current.device===device&&(device===null||current.linked))return{ok:!0};if(session.isStreaming)return{ok:!1,refusal:"session_busy"};let remote;if(device!==null){let row=directory.list().find(hand=>hand.device===device);if(row===void 0)return{ok:!1,refusal:"hand_not_listed"};if(!row.reachable)return{ok:!1,refusal:"hand_unreachable"};if(remote=linkTo(device),!remote.linked)return remote.host.close(),{ok:!1,refusal:"hand_unreachable"}}try{current.device!==device&&session.sessionManager.appendCustomEntry(HAND_SELECTION_ENTRY,{device})}catch(cause){throw remote?.host.close(),cause}return install(durableSessionId,session,device,remote),{ok:!0}},restore:(durableSessionId,session)=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),stateOf(durableSessionId,session);let device=recordedDevice(session);if(device===null)return;let row=directory.list().find(hand=>hand.device===device);install(durableSessionId,session,device,row?.reachable===!0?linkTo(device):unreachable())},release:durableSessionId=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),options.onRelease?.(durableSessionId)}}}function gatePresence(agent,presence,sessionId){let prepareRequest=agent.prepareRequest;agent.prepareRequest=async(request,signal)=>(await presence.ready(sessionId,"request",signal),await prepareRequest?.(request,signal)??void 0);let host=agent.toolHost;if(host===void 0)return;let deviceFiles=host.deviceFiles?.bind(host);agent.toolHost={execute:async(call,options)=>(await presence.ready(sessionId,"tools",options.signal),host.execute(call,options)),...deviceFiles===void 0?{}:{deviceFiles}}}var HEADLESS_SOCKET_FILE="headless.sock";function headlessSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix).join(agentDir,"rpc",HEADLESS_SOCKET_FILE)}function headlessEndpoint(agentDir,platform=process.platform,secret){return resolveSocketTransportAddress(headlessSocketPath(agentDir,platform),platform,secret)}function headlessHostOptions(options){let{presence,hands,...host}=options,runtimes=new Map,handSelection=hands===void 0?void 0:createHandSelection(hands,presence===void 0?{}:presenceHooks(presence,runtimes)),gated=presence===void 0?host.createRuntime:presenceRuntime(host.createRuntime,presence);return{...host,sessionOwner:"machine",listen:options.listen??`unix://${headlessSocketPath(options.agentDir)}`,createRuntime:handSelection===void 0?gated:handRuntime(gated,handSelection,runtimes),...presence===void 0?{}:{sessionPresence:presence.presence},...handSelection===void 0?{}:{handSelection}}}function presenceHooks(binding,runtimes){let tracking=new Map;return{gate:(sessionId,host)=>({execute:async(call,options)=>(await tracking.get(sessionId),await binding.presence.ready(sessionId,"tools",options.signal),host.execute(call,options))}),onChange:(sessionId,device)=>{let runtime=runtimes.get(sessionId),sessionHands=device!==null?[device]:runtime===void 0?[]:binding.handsOf(runtime),update=binding.presence.track(sessionId,sessionHands);update.catch(()=>{}),tracking.set(sessionId,update)},onRelease:sessionId=>{tracking.delete(sessionId)}}}function handRuntime(createRuntime,selection,runtimes){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime,sessionId=session.sessionId;runtimes.set(sessionId,runtime),selection.restore(sessionId,session);let dispose=session.dispose.bind(session);return session.dispose=()=>{runtimes.get(sessionId)===runtime&&(runtimes.delete(sessionId),selection.release(sessionId)),dispose()},runtime},createRuntime)}function presenceRuntime(createRuntime,binding){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime;return await binding.presence.track(session.sessionId,binding.handsOf(runtime)),gatePresence(session.agent,binding.presence,session.sessionId),runtime},createRuntime)}export{headlessEndpoint,headlessHostOptions,headlessSocketPath};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-HLY7CND7.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{STORE_BUSY,writeHealthUnlessStoreBusy};
2
+ import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-HLY7CND7.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{STORE_BUSY,writeHealthUnlessStoreBusy};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-NLYT7BND.js";import"./chunk-VD7AKTGP.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
2
+ import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-NLYT7BND.js";import"./chunk-VD7AKTGP.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-C4AHHZ6P.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-R7J5TEYK.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
2
+ import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-C4AHHZ6P.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-R7J5TEYK.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};