@humain/terminal 0.0.16 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/bundle/chunks/{chunk-Z4RA2T5Q.js → chunk-QLVZGOBY.js} +131 -128
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/tools/subagent-worktree.d.ts +25 -0
- package/dist/core/tools/subagent-worktree.d.ts.map +1 -0
- package/dist/core/tools/subagent-worktree.js +267 -0
- package/dist/core/tools/subagent-worktree.js.map +1 -0
- package/dist/core/tools/subagent.d.ts +8 -0
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +116 -20
- package/dist/core/tools/subagent.js.map +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
var github_copilot_default={"anthropic-messages":{"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}},"claude-opus-4.5":{id:"claude-opus-4.5",name:"Claude Opus 4.5 (latest)",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:2e5,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"}},"claude-opus-4.6":{id:"claude-opus-4.6",name:"Claude Opus 4.6",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"},thinkingLevelMap:{max:"max"},compat:{forceAdaptiveThinking:!0}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4 (latest)",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:216e3,maxTokens:16e3,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}},"claude-sonnet-4.5":{id:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (latest)",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:2e5,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:{supportsEagerToolInputStreaming:!1}},"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}},"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}}},"openai-completions":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"openai-completions",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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"}},"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:18,cacheRead:.4,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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:128e3,maxTokens:16384,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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",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: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:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 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: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:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"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}},"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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: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:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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: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:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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:105e4,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}},"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:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,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}},"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:105e4,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}},"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}},"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}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,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}},"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}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);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 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 getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),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);return{availableModelIds,policyModelIds}}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){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",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 Error(`${response.status} ${response.statusText}: ${await response.text()}`);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 Error(`${response.status} ${response.statusText}: ${text}`)}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");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/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){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&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}),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,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
|
|
2
|
+
var github_copilot_default={"anthropic-messages":{"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}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"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"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"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}},"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}}},"openai-completions":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"openai-completions",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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"}},"claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"openai-completions",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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"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:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"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}},"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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: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:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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: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:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"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"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"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:105e4,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}},"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:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,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}},"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:105e4,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}},"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}},"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}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,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}},"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}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);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 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 getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),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);return{availableModelIds,policyModelIds}}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){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",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 Error(`${response.status} ${response.statusText}: ${await response.text()}`);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 Error(`${response.status} ${response.statusText}: ${text}`)}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");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/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){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&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}),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,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
|
package/dist/bundle/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-QLVZGOBY.js";import{APP_NAME,ENV_PREFIX}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";process.title=APP_NAME;process.env[`${ENV_PREFIX}_CODING_AGENT`]="true";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPowerShellConfig,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-
|
|
2
|
+
import{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPowerShellConfig,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-QLVZGOBY.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,formatDimensionNote,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath,resizeImage}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UPSTREAM_PI_VERSION,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-QLVZGOBY.js";import{APP_NAME}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type SubagentIsolation = "shared" | "worktree";
|
|
2
|
+
export type SubagentMergeOutcome = "clean" | "conflict" | "skipped";
|
|
3
|
+
export interface SubagentWorktree {
|
|
4
|
+
readonly path: string;
|
|
5
|
+
readonly cwd: string;
|
|
6
|
+
readonly snapshotSha: string;
|
|
7
|
+
/** Apply the child's changes back onto the parent working tree. Never leaves conflict markers. */
|
|
8
|
+
mergeBack(): Promise<{
|
|
9
|
+
outcome: SubagentMergeOutcome;
|
|
10
|
+
changedFiles: string[];
|
|
11
|
+
patchPath?: string;
|
|
12
|
+
}>;
|
|
13
|
+
/** Remove the worktree; safe to call twice. */
|
|
14
|
+
dispose(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare function isGitWorkTree(cwd: string): Promise<boolean>;
|
|
17
|
+
/** Remove worktrees and patches left by dead or stale processes. */
|
|
18
|
+
export declare function sweepStaleSubagentWorktrees(parentCwd: string, now?: number): Promise<{
|
|
19
|
+
removed: string[];
|
|
20
|
+
}>;
|
|
21
|
+
export declare function createSubagentWorktree(input: {
|
|
22
|
+
parentCwd: string;
|
|
23
|
+
label: string;
|
|
24
|
+
}): Promise<SubagentWorktree>;
|
|
25
|
+
//# sourceMappingURL=subagent-worktree.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subagent-worktree.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent-worktree.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,UAAU,CAAC;AACtD,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,CAAC;AAEpE,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,kGAAkG;IAClG,SAAS,IAAI,OAAO,CAAC;QAAE,OAAO,EAAE,oBAAoB,CAAC;QAAC,YAAY,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpG,+CAA+C;IAC/C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAgED,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAGjE;AAgCD,oEAAoE;AACpE,wBAAsB,2BAA2B,CAChD,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAAmB,GACtB,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CA8BhC;AAqED,wBAAsB,sBAAsB,CAAC,KAAK,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAkFnH"}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { rmSync } from "node:fs";
|
|
3
|
+
import { mkdir, mkdtemp, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { spawnProcess, spawnProcessSync } from "../../utils/child-process.js";
|
|
7
|
+
const WORKTREE_ROOT = join(tmpdir(), "humain-terminal-worktrees");
|
|
8
|
+
const STALE_AFTER_MS = 6 * 60 * 60_000;
|
|
9
|
+
const active = new Map();
|
|
10
|
+
const mergeLocks = new Map();
|
|
11
|
+
const sweptRepositories = new Set();
|
|
12
|
+
const sweepingRepositories = new Map();
|
|
13
|
+
function runGit(cwd, args, stdin, env) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const proc = spawnProcess("git", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
|
|
16
|
+
let stdout = "";
|
|
17
|
+
let stderr = "";
|
|
18
|
+
proc.stdout?.on("data", (chunk) => {
|
|
19
|
+
stdout += String(chunk);
|
|
20
|
+
});
|
|
21
|
+
proc.stderr?.on("data", (chunk) => {
|
|
22
|
+
stderr += String(chunk);
|
|
23
|
+
});
|
|
24
|
+
proc.once("error", reject);
|
|
25
|
+
proc.once("close", (status) => resolve({ status: status ?? 1, stdout, stderr }));
|
|
26
|
+
proc.stdin?.end(stdin);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function gitOutput(cwd, args, stdin, env) {
|
|
30
|
+
const result = await runGit(cwd, args, stdin, env);
|
|
31
|
+
if (result.status !== 0) {
|
|
32
|
+
throw new Error(`git ${args[0]} failed: ${result.stderr.trim() || result.stdout.trim()}`);
|
|
33
|
+
}
|
|
34
|
+
return result.stdout;
|
|
35
|
+
}
|
|
36
|
+
async function gitOk(cwd, args, stdin, env) {
|
|
37
|
+
return (await gitOutput(cwd, args, stdin, env)).trim();
|
|
38
|
+
}
|
|
39
|
+
async function getRepositoryContext(cwd) {
|
|
40
|
+
const parentCwd = await realpath(await gitOk(cwd, ["rev-parse", "--show-toplevel"]));
|
|
41
|
+
const commonDir = await realpath(await gitOk(parentCwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]));
|
|
42
|
+
const key = createHash("sha256").update(`${parentCwd}\0${commonDir}`).digest("hex").slice(0, 24);
|
|
43
|
+
return { parentCwd, key, worktreeRoot: join(WORKTREE_ROOT, key) };
|
|
44
|
+
}
|
|
45
|
+
export async function isGitWorkTree(cwd) {
|
|
46
|
+
const result = await runGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
|
|
47
|
+
return result.status === 0 && result.stdout.trim() === "true";
|
|
48
|
+
}
|
|
49
|
+
/** Commit HEAD plus tracked and non-ignored untracked files without changing the parent's index or refs. */
|
|
50
|
+
async function snapshotParent(parentCwd) {
|
|
51
|
+
const indexDir = await mkdtemp(join(tmpdir(), "humain-terminal-worktree-index-"));
|
|
52
|
+
const env = {
|
|
53
|
+
...process.env,
|
|
54
|
+
GIT_INDEX_FILE: join(indexDir, "index"),
|
|
55
|
+
GIT_AUTHOR_NAME: "HUMAIN Terminal",
|
|
56
|
+
GIT_AUTHOR_EMAIL: "noreply@humain.ai",
|
|
57
|
+
GIT_COMMITTER_NAME: "HUMAIN Terminal",
|
|
58
|
+
GIT_COMMITTER_EMAIL: "noreply@humain.ai",
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
await gitOk(parentCwd, ["read-tree", "HEAD"], undefined, env);
|
|
62
|
+
await gitOk(parentCwd, ["add", "-A"], undefined, env);
|
|
63
|
+
const tree = await gitOk(parentCwd, ["write-tree"], undefined, env);
|
|
64
|
+
return gitOk(parentCwd, ["commit-tree", tree, "-p", "HEAD"], "subagent worktree snapshot\n", env);
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await rm(indexDir, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function pidIsAlive(pid) {
|
|
71
|
+
try {
|
|
72
|
+
process.kill(pid, 0);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
return error.code === "EPERM";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Remove worktrees and patches left by dead or stale processes. */
|
|
80
|
+
export async function sweepStaleSubagentWorktrees(parentCwd, now = Date.now()) {
|
|
81
|
+
const repository = await getRepositoryContext(parentCwd);
|
|
82
|
+
const removed = [];
|
|
83
|
+
await gitOk(repository.parentCwd, ["worktree", "prune"]);
|
|
84
|
+
let entries;
|
|
85
|
+
try {
|
|
86
|
+
entries = await readdir(repository.worktreeRoot);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (error.code === "ENOENT")
|
|
90
|
+
return { removed };
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
for (const name of entries) {
|
|
94
|
+
const path = join(repository.worktreeRoot, name);
|
|
95
|
+
const pid = Number.parseInt(name.split("-")[0] ?? "", 10);
|
|
96
|
+
let ageMs;
|
|
97
|
+
try {
|
|
98
|
+
ageMs = now - (await stat(path)).mtimeMs;
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error.code === "ENOENT")
|
|
102
|
+
continue;
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
if (pidIsAlive(pid) && ageMs < STALE_AFTER_MS)
|
|
106
|
+
continue;
|
|
107
|
+
if (!name.endsWith(".patch")) {
|
|
108
|
+
await runGit(repository.parentCwd, ["worktree", "remove", "--force", path]);
|
|
109
|
+
}
|
|
110
|
+
await rm(path, { recursive: true, force: true });
|
|
111
|
+
removed.push(path);
|
|
112
|
+
}
|
|
113
|
+
await gitOk(repository.parentCwd, ["worktree", "prune"]);
|
|
114
|
+
return { removed };
|
|
115
|
+
}
|
|
116
|
+
async function sweepOnce(repository) {
|
|
117
|
+
if (sweptRepositories.has(repository.key))
|
|
118
|
+
return;
|
|
119
|
+
let sweep = sweepingRepositories.get(repository.key);
|
|
120
|
+
if (!sweep) {
|
|
121
|
+
sweep = sweepStaleSubagentWorktrees(repository.parentCwd).then(() => undefined);
|
|
122
|
+
sweepingRepositories.set(repository.key, sweep);
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
await sweep;
|
|
126
|
+
sweptRepositories.add(repository.key);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
if (sweepingRepositories.get(repository.key) === sweep)
|
|
130
|
+
sweepingRepositories.delete(repository.key);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function withMergeLock(repository, action) {
|
|
134
|
+
const previous = mergeLocks.get(repository.key) ?? Promise.resolve();
|
|
135
|
+
let release = () => { };
|
|
136
|
+
const gate = new Promise((resolve) => {
|
|
137
|
+
release = resolve;
|
|
138
|
+
});
|
|
139
|
+
const next = previous.then(() => gate);
|
|
140
|
+
mergeLocks.set(repository.key, next);
|
|
141
|
+
await previous;
|
|
142
|
+
try {
|
|
143
|
+
return await action();
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
release();
|
|
147
|
+
if (mergeLocks.get(repository.key) === next)
|
|
148
|
+
mergeLocks.delete(repository.key);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function disposeAllActiveSync() {
|
|
152
|
+
for (const [worktree, record] of active) {
|
|
153
|
+
try {
|
|
154
|
+
spawnProcessSync("git", ["worktree", "remove", "--force", record.path], {
|
|
155
|
+
cwd: record.parentCwd,
|
|
156
|
+
encoding: "utf8",
|
|
157
|
+
stdio: "ignore",
|
|
158
|
+
});
|
|
159
|
+
rmSync(record.path, { recursive: true, force: true });
|
|
160
|
+
spawnProcessSync("git", ["worktree", "prune"], {
|
|
161
|
+
cwd: record.parentCwd,
|
|
162
|
+
encoding: "utf8",
|
|
163
|
+
stdio: "ignore",
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// Process termination leaves no async recovery path; the next sweep retries any residue.
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
active.delete(worktree);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
process.once("exit", disposeAllActiveSync);
|
|
175
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
176
|
+
const handler = () => {
|
|
177
|
+
disposeAllActiveSync();
|
|
178
|
+
if (process.listeners(signal).filter((listener) => listener !== handler).length === 0) {
|
|
179
|
+
process.removeListener(signal, handler);
|
|
180
|
+
process.kill(process.pid, signal);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
process.prependListener(signal, handler);
|
|
184
|
+
}
|
|
185
|
+
export async function createSubagentWorktree(input) {
|
|
186
|
+
const repository = await getRepositoryContext(input.parentCwd);
|
|
187
|
+
const requestedCwd = await realpath(input.parentCwd);
|
|
188
|
+
const relativeCwd = relative(repository.parentCwd, requestedCwd);
|
|
189
|
+
if (relativeCwd === ".." || relativeCwd.startsWith(`..${sep}`) || isAbsolute(relativeCwd)) {
|
|
190
|
+
throw new Error(`Subagent cwd is outside the repository: ${input.parentCwd}`);
|
|
191
|
+
}
|
|
192
|
+
await mkdir(repository.worktreeRoot, { recursive: true });
|
|
193
|
+
await sweepOnce(repository);
|
|
194
|
+
const safeLabel = input.label.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 64) || "subagent";
|
|
195
|
+
const snapshotSha = await snapshotParent(repository.parentCwd);
|
|
196
|
+
const path = await mkdtemp(join(repository.worktreeRoot, `${process.pid}-${safeLabel}-`));
|
|
197
|
+
try {
|
|
198
|
+
await gitOk(repository.parentCwd, ["worktree", "add", "--detach", path, snapshotSha]);
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
await rm(path, { recursive: true, force: true });
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
let cwd;
|
|
205
|
+
try {
|
|
206
|
+
const mappedCwd = resolve(path, relativeCwd);
|
|
207
|
+
await mkdir(mappedCwd, { recursive: true });
|
|
208
|
+
cwd = await realpath(mappedCwd);
|
|
209
|
+
const worktreeRelativeCwd = relative(await realpath(path), cwd);
|
|
210
|
+
if (worktreeRelativeCwd === ".." ||
|
|
211
|
+
worktreeRelativeCwd.startsWith(`..${sep}`) ||
|
|
212
|
+
isAbsolute(worktreeRelativeCwd)) {
|
|
213
|
+
throw new Error(`Subagent cwd resolves outside its worktree: ${input.parentCwd}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
await runGit(repository.parentCwd, ["worktree", "remove", "--force", path]);
|
|
218
|
+
await rm(path, { recursive: true, force: true });
|
|
219
|
+
await gitOk(repository.parentCwd, ["worktree", "prune"]);
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
let disposePromise;
|
|
223
|
+
const worktree = {
|
|
224
|
+
path,
|
|
225
|
+
cwd,
|
|
226
|
+
snapshotSha,
|
|
227
|
+
async mergeBack() {
|
|
228
|
+
await gitOk(path, ["add", "-A"]);
|
|
229
|
+
const changedFiles = (await gitOk(path, ["diff", "--cached", "--name-only", snapshotSha]))
|
|
230
|
+
.split("\n")
|
|
231
|
+
.filter(Boolean)
|
|
232
|
+
.sort();
|
|
233
|
+
if (changedFiles.length === 0)
|
|
234
|
+
return { outcome: "clean", changedFiles };
|
|
235
|
+
const patch = await gitOutput(path, ["diff", "--cached", "--binary", snapshotSha]);
|
|
236
|
+
return withMergeLock(repository, async () => {
|
|
237
|
+
const check = await runGit(repository.parentCwd, ["apply", "--check", "--whitespace=nowarn"], patch);
|
|
238
|
+
if (check.status === 0) {
|
|
239
|
+
const apply = await runGit(repository.parentCwd, ["apply", "--whitespace=nowarn"], patch);
|
|
240
|
+
if (apply.status === 0)
|
|
241
|
+
return { outcome: "clean", changedFiles };
|
|
242
|
+
}
|
|
243
|
+
const patchPath = `${path}.patch`;
|
|
244
|
+
await writeFile(patchPath, patch);
|
|
245
|
+
return { outcome: "conflict", changedFiles, patchPath };
|
|
246
|
+
});
|
|
247
|
+
},
|
|
248
|
+
dispose() {
|
|
249
|
+
if (disposePromise)
|
|
250
|
+
return disposePromise;
|
|
251
|
+
disposePromise = (async () => {
|
|
252
|
+
await runGit(repository.parentCwd, ["worktree", "remove", "--force", path]);
|
|
253
|
+
await rm(path, { recursive: true, force: true });
|
|
254
|
+
await gitOk(repository.parentCwd, ["worktree", "prune"]);
|
|
255
|
+
})().then(() => {
|
|
256
|
+
active.delete(worktree);
|
|
257
|
+
}, (error) => {
|
|
258
|
+
disposePromise = undefined;
|
|
259
|
+
throw error;
|
|
260
|
+
});
|
|
261
|
+
return disposePromise;
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
active.set(worktree, { parentCwd: repository.parentCwd, path });
|
|
265
|
+
return worktree;
|
|
266
|
+
}
|
|
267
|
+
//# sourceMappingURL=subagent-worktree.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subagent-worktree.js","sourceRoot":"","sources":["../../../src/core/tools/subagent-worktree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAgC9E,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,2BAA2B,CAAC,CAAC;AAClE,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC;AACvC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAoC,CAAC;AAC3D,MAAM,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CAAC,UAAU,CAAC,SAAS,EAAE,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;YAC1D,CAAC,CAAC,EAAE,CAAC,IAAI,CACR,GAAG,EAAE;gBACJ,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YACzB,CAAC,EACD,CAAC,KAAc,EAAE,EAAE;gBAClB,cAAc,GAAG,SAAS,CAAC;gBAC3B,MAAM,KAAK,CAAC;YACb,CAAC,CACD,CAAC;YACF,OAAO,cAAc,CAAC;QACvB,CAAC;KACD,CAAC;IACF,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,UAAU,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAChE,OAAO,QAAQ,CAAC;AACjB,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { rmSync } from \"node:fs\";\nimport { mkdir, mkdtemp, readdir, realpath, rm, stat, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { spawnProcess, spawnProcessSync } from \"../../utils/child-process.ts\";\n\nexport type SubagentIsolation = \"shared\" | \"worktree\";\nexport type SubagentMergeOutcome = \"clean\" | \"conflict\" | \"skipped\";\n\nexport interface SubagentWorktree {\n\treadonly path: string;\n\treadonly cwd: string;\n\treadonly snapshotSha: string;\n\t/** Apply the child's changes back onto the parent working tree. Never leaves conflict markers. */\n\tmergeBack(): Promise<{ outcome: SubagentMergeOutcome; changedFiles: string[]; patchPath?: string }>;\n\t/** Remove the worktree; safe to call twice. */\n\tdispose(): Promise<void>;\n}\n\ninterface GitResult {\n\tstatus: number;\n\tstdout: string;\n\tstderr: string;\n}\n\ninterface RepositoryContext {\n\tparentCwd: string;\n\tkey: string;\n\tworktreeRoot: string;\n}\n\ninterface ActiveWorktree {\n\tparentCwd: string;\n\tpath: string;\n}\n\nconst WORKTREE_ROOT = join(tmpdir(), \"humain-terminal-worktrees\");\nconst STALE_AFTER_MS = 6 * 60 * 60_000;\nconst active = new Map<SubagentWorktree, ActiveWorktree>();\nconst mergeLocks = new Map<string, Promise<void>>();\nconst sweptRepositories = new Set<string>();\nconst sweepingRepositories = new Map<string, Promise<void>>();\n\nfunction runGit(cwd: string, args: string[], stdin?: string, env?: NodeJS.ProcessEnv): Promise<GitResult> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst proc = spawnProcess(\"git\", args, { cwd, env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tproc.stdout?.on(\"data\", (chunk) => {\n\t\t\tstdout += String(chunk);\n\t\t});\n\t\tproc.stderr?.on(\"data\", (chunk) => {\n\t\t\tstderr += String(chunk);\n\t\t});\n\t\tproc.once(\"error\", reject);\n\t\tproc.once(\"close\", (status) => resolve({ status: status ?? 1, stdout, stderr }));\n\t\tproc.stdin?.end(stdin);\n\t});\n}\n\nasync function gitOutput(cwd: string, args: string[], stdin?: string, env?: NodeJS.ProcessEnv): Promise<string> {\n\tconst result = await runGit(cwd, args, stdin, env);\n\tif (result.status !== 0) {\n\t\tthrow new Error(`git ${args[0]} failed: ${result.stderr.trim() || result.stdout.trim()}`);\n\t}\n\treturn result.stdout;\n}\n\nasync function gitOk(cwd: string, args: string[], stdin?: string, env?: NodeJS.ProcessEnv): Promise<string> {\n\treturn (await gitOutput(cwd, args, stdin, env)).trim();\n}\n\nasync function getRepositoryContext(cwd: string): Promise<RepositoryContext> {\n\tconst parentCwd = await realpath(await gitOk(cwd, [\"rev-parse\", \"--show-toplevel\"]));\n\tconst commonDir = await realpath(\n\t\tawait gitOk(parentCwd, [\"rev-parse\", \"--path-format=absolute\", \"--git-common-dir\"]),\n\t);\n\tconst key = createHash(\"sha256\").update(`${parentCwd}\\0${commonDir}`).digest(\"hex\").slice(0, 24);\n\treturn { parentCwd, key, worktreeRoot: join(WORKTREE_ROOT, key) };\n}\n\nexport async function isGitWorkTree(cwd: string): Promise<boolean> {\n\tconst result = await runGit(cwd, [\"rev-parse\", \"--is-inside-work-tree\"]);\n\treturn result.status === 0 && result.stdout.trim() === \"true\";\n}\n\n/** Commit HEAD plus tracked and non-ignored untracked files without changing the parent's index or refs. */\nasync function snapshotParent(parentCwd: string): Promise<string> {\n\tconst indexDir = await mkdtemp(join(tmpdir(), \"humain-terminal-worktree-index-\"));\n\tconst env = {\n\t\t...process.env,\n\t\tGIT_INDEX_FILE: join(indexDir, \"index\"),\n\t\tGIT_AUTHOR_NAME: \"HUMAIN Terminal\",\n\t\tGIT_AUTHOR_EMAIL: \"noreply@humain.ai\",\n\t\tGIT_COMMITTER_NAME: \"HUMAIN Terminal\",\n\t\tGIT_COMMITTER_EMAIL: \"noreply@humain.ai\",\n\t};\n\ttry {\n\t\tawait gitOk(parentCwd, [\"read-tree\", \"HEAD\"], undefined, env);\n\t\tawait gitOk(parentCwd, [\"add\", \"-A\"], undefined, env);\n\t\tconst tree = await gitOk(parentCwd, [\"write-tree\"], undefined, env);\n\t\treturn gitOk(parentCwd, [\"commit-tree\", tree, \"-p\", \"HEAD\"], \"subagent worktree snapshot\\n\", env);\n\t} finally {\n\t\tawait rm(indexDir, { recursive: true, force: true });\n\t}\n}\n\nfunction pidIsAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\n/** Remove worktrees and patches left by dead or stale processes. */\nexport async function sweepStaleSubagentWorktrees(\n\tparentCwd: string,\n\tnow: number = Date.now(),\n): Promise<{ removed: string[] }> {\n\tconst repository = await getRepositoryContext(parentCwd);\n\tconst removed: string[] = [];\n\tawait gitOk(repository.parentCwd, [\"worktree\", \"prune\"]);\n\tlet entries: string[];\n\ttry {\n\t\tentries = await readdir(repository.worktreeRoot);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { removed };\n\t\tthrow error;\n\t}\n\tfor (const name of entries) {\n\t\tconst path = join(repository.worktreeRoot, name);\n\t\tconst pid = Number.parseInt(name.split(\"-\")[0] ?? \"\", 10);\n\t\tlet ageMs: number;\n\t\ttry {\n\t\t\tageMs = now - (await stat(path)).mtimeMs;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\tthrow error;\n\t\t}\n\t\tif (pidIsAlive(pid) && ageMs < STALE_AFTER_MS) continue;\n\t\tif (!name.endsWith(\".patch\")) {\n\t\t\tawait runGit(repository.parentCwd, [\"worktree\", \"remove\", \"--force\", path]);\n\t\t}\n\t\tawait rm(path, { recursive: true, force: true });\n\t\tremoved.push(path);\n\t}\n\tawait gitOk(repository.parentCwd, [\"worktree\", \"prune\"]);\n\treturn { removed };\n}\n\nasync function sweepOnce(repository: RepositoryContext): Promise<void> {\n\tif (sweptRepositories.has(repository.key)) return;\n\tlet sweep = sweepingRepositories.get(repository.key);\n\tif (!sweep) {\n\t\tsweep = sweepStaleSubagentWorktrees(repository.parentCwd).then(() => undefined);\n\t\tsweepingRepositories.set(repository.key, sweep);\n\t}\n\ttry {\n\t\tawait sweep;\n\t\tsweptRepositories.add(repository.key);\n\t} finally {\n\t\tif (sweepingRepositories.get(repository.key) === sweep) sweepingRepositories.delete(repository.key);\n\t}\n}\n\nasync function withMergeLock<T>(repository: RepositoryContext, action: () => Promise<T>): Promise<T> {\n\tconst previous = mergeLocks.get(repository.key) ?? Promise.resolve();\n\tlet release: () => void = () => {};\n\tconst gate = new Promise<void>((resolve) => {\n\t\trelease = resolve;\n\t});\n\tconst next = previous.then(() => gate);\n\tmergeLocks.set(repository.key, next);\n\tawait previous;\n\ttry {\n\t\treturn await action();\n\t} finally {\n\t\trelease();\n\t\tif (mergeLocks.get(repository.key) === next) mergeLocks.delete(repository.key);\n\t}\n}\n\nfunction disposeAllActiveSync(): void {\n\tfor (const [worktree, record] of active) {\n\t\ttry {\n\t\t\tspawnProcessSync(\"git\", [\"worktree\", \"remove\", \"--force\", record.path], {\n\t\t\t\tcwd: record.parentCwd,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tstdio: \"ignore\",\n\t\t\t});\n\t\t\trmSync(record.path, { recursive: true, force: true });\n\t\t\tspawnProcessSync(\"git\", [\"worktree\", \"prune\"], {\n\t\t\t\tcwd: record.parentCwd,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tstdio: \"ignore\",\n\t\t\t});\n\t\t} catch {\n\t\t\t// Process termination leaves no async recovery path; the next sweep retries any residue.\n\t\t} finally {\n\t\t\tactive.delete(worktree);\n\t\t}\n\t}\n}\n\nprocess.once(\"exit\", disposeAllActiveSync);\n\nfor (const signal of [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const) {\n\tconst handler = () => {\n\t\tdisposeAllActiveSync();\n\t\tif (process.listeners(signal).filter((listener) => listener !== handler).length === 0) {\n\t\t\tprocess.removeListener(signal, handler);\n\t\t\tprocess.kill(process.pid, signal);\n\t\t}\n\t};\n\tprocess.prependListener(signal, handler);\n}\n\nexport async function createSubagentWorktree(input: { parentCwd: string; label: string }): Promise<SubagentWorktree> {\n\tconst repository = await getRepositoryContext(input.parentCwd);\n\tconst requestedCwd = await realpath(input.parentCwd);\n\tconst relativeCwd = relative(repository.parentCwd, requestedCwd);\n\tif (relativeCwd === \"..\" || relativeCwd.startsWith(`..${sep}`) || isAbsolute(relativeCwd)) {\n\t\tthrow new Error(`Subagent cwd is outside the repository: ${input.parentCwd}`);\n\t}\n\tawait mkdir(repository.worktreeRoot, { recursive: true });\n\tawait sweepOnce(repository);\n\tconst safeLabel = input.label.replace(/[^A-Za-z0-9_.-]/g, \"-\").slice(0, 64) || \"subagent\";\n\tconst snapshotSha = await snapshotParent(repository.parentCwd);\n\tconst path = await mkdtemp(join(repository.worktreeRoot, `${process.pid}-${safeLabel}-`));\n\ttry {\n\t\tawait gitOk(repository.parentCwd, [\"worktree\", \"add\", \"--detach\", path, snapshotSha]);\n\t} catch (error) {\n\t\tawait rm(path, { recursive: true, force: true });\n\t\tthrow error;\n\t}\n\tlet cwd: string;\n\ttry {\n\t\tconst mappedCwd = resolve(path, relativeCwd);\n\t\tawait mkdir(mappedCwd, { recursive: true });\n\t\tcwd = await realpath(mappedCwd);\n\t\tconst worktreeRelativeCwd = relative(await realpath(path), cwd);\n\t\tif (\n\t\t\tworktreeRelativeCwd === \"..\" ||\n\t\t\tworktreeRelativeCwd.startsWith(`..${sep}`) ||\n\t\t\tisAbsolute(worktreeRelativeCwd)\n\t\t) {\n\t\t\tthrow new Error(`Subagent cwd resolves outside its worktree: ${input.parentCwd}`);\n\t\t}\n\t} catch (error) {\n\t\tawait runGit(repository.parentCwd, [\"worktree\", \"remove\", \"--force\", path]);\n\t\tawait rm(path, { recursive: true, force: true });\n\t\tawait gitOk(repository.parentCwd, [\"worktree\", \"prune\"]);\n\t\tthrow error;\n\t}\n\n\tlet disposePromise: Promise<void> | undefined;\n\tconst worktree: SubagentWorktree = {\n\t\tpath,\n\t\tcwd,\n\t\tsnapshotSha,\n\t\tasync mergeBack() {\n\t\t\tawait gitOk(path, [\"add\", \"-A\"]);\n\t\t\tconst changedFiles = (await gitOk(path, [\"diff\", \"--cached\", \"--name-only\", snapshotSha]))\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.sort();\n\t\t\tif (changedFiles.length === 0) return { outcome: \"clean\" as const, changedFiles };\n\t\t\tconst patch = await gitOutput(path, [\"diff\", \"--cached\", \"--binary\", snapshotSha]);\n\t\t\treturn withMergeLock(repository, async () => {\n\t\t\t\tconst check = await runGit(repository.parentCwd, [\"apply\", \"--check\", \"--whitespace=nowarn\"], patch);\n\t\t\t\tif (check.status === 0) {\n\t\t\t\t\tconst apply = await runGit(repository.parentCwd, [\"apply\", \"--whitespace=nowarn\"], patch);\n\t\t\t\t\tif (apply.status === 0) return { outcome: \"clean\" as const, changedFiles };\n\t\t\t\t}\n\t\t\t\tconst patchPath = `${path}.patch`;\n\t\t\t\tawait writeFile(patchPath, patch);\n\t\t\t\treturn { outcome: \"conflict\" as const, changedFiles, patchPath };\n\t\t\t});\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposePromise) return disposePromise;\n\t\t\tdisposePromise = (async () => {\n\t\t\t\tawait runGit(repository.parentCwd, [\"worktree\", \"remove\", \"--force\", path]);\n\t\t\t\tawait rm(path, { recursive: true, force: true });\n\t\t\t\tawait gitOk(repository.parentCwd, [\"worktree\", \"prune\"]);\n\t\t\t})().then(\n\t\t\t\t() => {\n\t\t\t\t\tactive.delete(worktree);\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tdisposePromise = undefined;\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn disposePromise;\n\t\t},\n\t};\n\tactive.set(worktree, { parentCwd: repository.parentCwd, path });\n\treturn worktree;\n}\n"]}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import type { Message } from "@earendil-works/pi-ai";
|
|
15
15
|
import { Type } from "typebox";
|
|
16
16
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
17
|
+
import { type SubagentIsolation, type SubagentMergeOutcome } from "./subagent-worktree.ts";
|
|
17
18
|
/** Children must not delegate further: depth 0 = top-level agent, depth >= 1 = subagent. */
|
|
18
19
|
export declare const SUBAGENT_DEPTH_ENV = "HUMAIN_TERMINAL_SUBAGENT_DEPTH";
|
|
19
20
|
export type AgentScope = "user" | "project" | "both";
|
|
@@ -52,6 +53,11 @@ export interface SubagentSingleResult {
|
|
|
52
53
|
stopReason?: string;
|
|
53
54
|
errorMessage?: string;
|
|
54
55
|
step?: number;
|
|
56
|
+
isolation: SubagentIsolation;
|
|
57
|
+
isolationDegradedReason?: "not-a-git-repo";
|
|
58
|
+
mergeOutcome?: SubagentMergeOutcome;
|
|
59
|
+
changedFiles?: string[];
|
|
60
|
+
patchPath?: string;
|
|
55
61
|
}
|
|
56
62
|
export interface SubagentDetails {
|
|
57
63
|
mode: "single" | "parallel" | "chain";
|
|
@@ -68,6 +74,7 @@ declare const SubagentParams: Type.TObject<{
|
|
|
68
74
|
task: Type.TString;
|
|
69
75
|
model: Type.TOptional<Type.TString>;
|
|
70
76
|
cwd: Type.TOptional<Type.TString>;
|
|
77
|
+
isolation: Type.TOptional<Type.TUnsafe<"shared" | "worktree">>;
|
|
71
78
|
}>>>;
|
|
72
79
|
chain: Type.TOptional<Type.TArray<Type.TObject<{
|
|
73
80
|
agent: Type.TString;
|
|
@@ -78,6 +85,7 @@ declare const SubagentParams: Type.TObject<{
|
|
|
78
85
|
agentScope: Type.TOptional<Type.TUnsafe<"both" | "project" | "user">>;
|
|
79
86
|
confirmProjectAgents: Type.TOptional<Type.TBoolean>;
|
|
80
87
|
cwd: Type.TOptional<Type.TString>;
|
|
88
|
+
isolation: Type.TOptional<Type.TUnsafe<"shared" | "worktree">>;
|
|
81
89
|
}>;
|
|
82
90
|
export declare function createSubagentToolDefinition(cwd: string): ToolDefinition<typeof SubagentParams, SubagentDetails>;
|
|
83
91
|
export declare function createSubagentTool(cwd: string): import("@earendil-works/pi-agent-core").AgentTool<any, SubagentDetails>;
|