@qoder-ai/qoder-agent-sdk 1.0.58 → 1.0.59
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/README.md +23 -0
- package/dist/core/process-transport.d.ts +3 -0
- package/dist/core/runtime-launch-options.d.ts +3 -0
- package/dist/daemon/daemon-connection.d.ts +3 -6
- package/dist/daemon/daemon-session-transport.d.ts +3 -0
- package/dist/daemon/global-daemon.d.ts +4 -0
- package/dist/daemon/protocol.d.ts +6 -0
- package/dist/daemon/start-daemon.d.ts +4 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +32 -32
- package/dist/protocol/control.d.ts +1 -0
- package/dist/protocol/index.d.ts +1 -1
- package/dist/protocol/messages.d.ts +70 -2
- package/dist/query/query-runner.d.ts +4 -1
- package/dist/runtime-manifest.json +5 -5
- package/dist/types/messages.d.ts +3 -1
- package/dist/types/options.d.ts +13 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);super(n?.trim()?n:"Qoder CLI initialization failed."),this.name="QoderCliInitializationError",this.code=e.error_code,this.result=e}},E=class extends Error{constructor(e="Operation was aborted"){super(e),this.name="AbortError"}},Le=class extends Error{timeoutMs;constructor(e){super(`resolveModel did not return within ${e}ms. Increase resolveModelTimeoutMs or ensure the callback resolves faster.`),this.name="ModelPolicyTimeoutError",this.timeoutMs=e}},V=class extends Error{cliProtocolVersion;sdkProtocolVersion;constructor(e,n){super(`Wire protocol major mismatch: CLI announced "${e}" but this SDK was built for "${n}". Upgrade either qodercli or @qoder-ai/qoder-agent-sdk so the major versions align.`),this.name="ProtocolVersionMismatchError",this.cliProtocolVersion=e,this.sdkProtocolVersion=n}},L=class extends Error{capability;constructor(e){super(`The running qodercli does not advertise the required capability "${e}". Upgrade qodercli or use a matching bundled SDK runtime.`),this.name="UnsupportedCliCapabilityError",this.capability=e}},Yt="CONTROL_REQUEST_TIMEOUT",Ce=class extends Error{requestId;code;retryable;details;constructor(e){super(e.message),this.name="ControlRequestError",this.requestId=e.requestId,this.code=e.code,this.retryable=e.retryable===!0,this.details=e.details}};import{chmod as fs,mkdtemp as ki,rm as gs,writeFile as Ci}from"fs/promises";import{existsSync as St,mkdtempSync as Ri,readFileSync as Pi,rmSync as Ei,writeFileSync as Ti}from"fs";import{homedir as Mi,tmpdir as hs}from"os";import{dirname as ks,join as z}from"path";import{fileURLToPath as Ai}from"url";var pi=["PreToolUse","PostToolUse","PostToolUseFailure","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStart","SubagentStop","PreCompact","PostCompact","CwdChanged","InstructionsLoaded","FileChanged","PermissionRequest","PermissionDenied","WorktreeCreate","WorktreeRemove"],mi=["clear","resume","logout","prompt_input_exit","other","bypass_permissions_disabled"],Xt=2e3;var ft="1.0.58";var as=["Agent","AskUserQuestion","Bash","Edit","Glob","Grep","ImageGen","ImageSearch","NotebookEdit","Read","Skill","TaskCreate","TaskGet","TaskUpdate","TaskList","UpdateGoal","WebFetch","WebSearch","Write"],us=["TaskCreate","TaskGet","TaskUpdate","TaskList"],fi="QODER_FEATURE_TASKS";function cs(t){let e=t[fi];if(e!=="0"&&e!=="false")return[...as];let n=new Set(us);return as.flatMap(s=>s===us[0]?["TodoWrite"]:n.has(s)?[]:[s])}var gi=/^[A-Za-z0-9_-]{1,64}$/,hi=new Set(["mcp_list","mcp_get","mcp_call"]);function Zt(t,e){if(e.exposedName!==void 0){if(e.alwaysLoad!==!0)throw new Error(`MCP tool "${t}/${e.name}" requires alwaysLoad: true when exposedName is set.`);if(!gi.test(e.exposedName))throw new Error(`MCP tool "${t}/${e.name}" has invalid exposedName "${e.exposedName}".`);if(hi.has(e.exposedName))throw new Error(`MCP tool "${t}/${e.name}" cannot use reserved exposedName "${e.exposedName}".`)}}function en(t,e){let n={};for(let s of e)Zt(t,s),(s.exposedName!==void 0||s.alwaysLoad===!0)&&(n[s.name]={...s.exposedName!==void 0?{exposedName:s.exposedName}:{},...s.alwaysLoad===!0?{alwaysLoad:!0}:{}});return Object.keys(n).length>0?n:void 0}function tn(t,e,n=e.tools??[]){let{tools:s,...o}=e,r=en(t,n);return{...o,...r?{toolOverrides:r}:{}}}function ls(t){let e={};for(let[n,s]of Object.entries(t)){if(s.type==="sdk")throw new Error(`MCP server "${n}" uses an in-process SDK transport and cannot be changed with setMcpServers().`);let o=s.tools??[],r=o.find(i=>i.permission_policy!==void 0);if(r)throw new Error(`MCP tool "${n}/${r.name}" cannot set permission_policy through setMcpServers(); configure it when creating the query.`);e[n]=tn(n,s,o)}return e}var ds=w.accessTokenEnv,gt=w.serviceAccountEnv;function yi(t){return{type:"accessToken",accessToken:t}}function Si(t=ds){return{type:"accessToken",accessToken:{envVar:t}}}function vi(){return{type:"qodercli"}}function wi(t){let e=t.serviceAccountKey!==void 0,n=typeof t.fetchServiceAccountToken=="function";if(e===n)throw new TypeError("serviceAccount() requires exactly one credential source: serviceAccountKey or fetchServiceAccountToken");return{type:"serviceAccount",...t}}function bi(t=gt){return{type:"serviceAccount",serviceAccountKey:{envVar:t}}}function _i(t){return{type:"jobToken",fetchJobToken:t}}var ps=["l1StaticCheck","l2LightweightScan","l3DeepScan"];function ms(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("securityScan must be an object.");let e=new Set(ps),n=Object.keys(t).filter(s=>!e.has(s));if(n.length>0)throw new TypeError(`securityScan contains unknown option${n.length===1?"":"s"}: ${n.join(", ")}.`);for(let s of ps){let o=t[s];if(o!==void 0&&typeof o!="boolean")throw new TypeError(`securityScan.${s} must be a boolean.`)}return{l1StaticCheck:t.l1StaticCheck??!1,l2LightweightScan:t.l2LightweightScan??!1,l3DeepScan:t.l3DeepScan??!1}}var ys="QODER_AGENT_SDK_ENTRYPOINT",Ss="QODER_AGENT_SDK_VERSION",vs="QODER_SDK_AUTH_PAYLOAD_FILE",Ii="sdk-ts",Di=Ai(import.meta.url),ws=ks(Di),ht=class extends Error{code="auth_access_token_env_var_not_configured";constructor(e){super(`The auth access token environment variable "${e}" is not set; set it or pass auth.accessToken directly.`),this.name="AuthAccessTokenEnvVarError"}},yt=class extends Error{code="auth_service_account_env_var_not_configured";constructor(e){super(`The Service Account key environment variable "${e}" is not set; set it or pass auth.serviceAccountKey directly.`),this.name="AuthServiceAccountEnvVarError"}};function Re(t){return/\.(js|mjs|tsx?|jsx)$/.test(t)}function Pe(){if(process.env.QODERCLI_PATH)return process.env.QODERCLI_PATH;let t=xi();if(t)return t;let e=Oi();if(St(e))return e;let n=qi();return n||w.cliCommands[0]}function xi(){for(let t of Cs())for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=z(t,"dist","_bundled",n);if(St(s))return s}return null}function Oi(){for(let t of Cs())for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=[z(t,"node_modules",".bin",n),z(t,"..","..",".bin",n)];for(let o of s)if(St(o))return o}return w.cliCommands[0]}function qi(){let t=process.env[w.cliHomeEnv]??Mi();for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=z(t,w.configDirName,"local",n);if(St(s))return s}return null}function Cs(){let t=[z(ws,".."),z(ws,"..","..")];return[...new Set(t)]}function Ni(){return{allow:[],ask:[],deny:[]}}function bs(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ji(t,e){if(e.startsWith("mcp__"))return e;let n=bs(t),s=e==="*"?"*":bs(e);if(!n||!s)throw new Error(`Invalid MCP tool policy name for server "${t}" and tool "${e}"`);return`mcp__${n}__${s}`}function _s(t,e){if(e.length===0)return;let n=new Set(t);for(let s of e)n.has(s)||(t.push(s),n.add(s))}function Fi(t){let e=t??{},n=e.general&&typeof e.general=="object"&&!Array.isArray(e.general)?e.general:{},s=n.fileCheckpointing&&typeof n.fileCheckpointing=="object"&&!Array.isArray(n.fileCheckpointing)?n.fileCheckpointing:{};return{...e,general:{...n,fileCheckpointing:{...s,enabled:!0}}}}var ae=class{options;diagnostics;logPrefix;authPayloadPath=null;generatedSettingsDir;constructor(e,n,s="[RuntimeLaunch]"){this.options=e,this.diagnostics=n,this.logPrefix=s}async prepare(){return this.options.auth&&(this.authPayloadPath=await this.createAuthPayloadFile(this.options.auth)),{args:this.buildArgs(),env:this.buildEnv(),authPayloadPath:this.authPayloadPath??void 0}}cleanupGeneratedSettings(){if(this.generatedSettingsDir)try{Ei(this.generatedSettingsDir,{recursive:!0,force:!0})}catch{}finally{this.generatedSettingsDir=void 0}}async cleanupLaunchArtifacts(){this.cleanupGeneratedSettings(),await this.cleanupAuthPayload()}async cleanupAuthPayload(){if(!this.authPayloadPath)return;let e=ks(this.authPayloadPath);try{await gs(e,{recursive:!0,force:!0}),this.diagnostics?.record(`${this.logPrefix} Auth payload cleaned up`)}catch{}this.authPayloadPath=null}buildEnv(){let e=this.options.env??{...process.env},n={};for(let[s,o]of Object.entries(e))o!==void 0&&(n[s]=o);delete n[ys],delete n[Ss],delete n[vs];for(let s of this.serviceAccountCredentialEnvVars())Li(n,s);if(n[ys]=Ii,n[Ss]=ft,this.authPayloadPath&&(n[vs]=this.authPayloadPath),delete n.NODE_OPTIONS,this.options.vpcEndpoint!==void 0){let s=this.options.vpcEndpoint.trim();s?n[Jt]=s:delete n[Jt]}return n}serviceAccountCredentialEnvVars(){let e=this.options.auth;if(e?.type!=="serviceAccount")return[];let n=[gt];return e.serviceAccountKey&&typeof e.serviceAccountKey!="string"&&n.push(e.serviceAccountKey.envVar),n}buildArgs(){let e=[],n=this.options;if(n.extraArgs&&Object.hasOwn(n.extraArgs,"proxy"))throw new Error("extraArgs.proxy is reserved; use the dedicated proxy option instead.");if(e.push("--print"),e.push("--output-format","stream-json"),e.push("--input-format","stream-json"),n.sessionMirror&&e.push("--session-mirror"),n.persistSession===!1&&e.push("--no-session-persistence"),n.model&&e.push("--model",n.model),n.proxy!==void 0&&e.push("--proxy",n.proxy),n.agent&&e.push("--agent",n.agent),n.debug&&e.push("--debug"),n.resume?e.push("--resume",n.resume):n.continue&&e.push("--continue"),n.resumeSessionAt&&e.push(`--resume-session-at=${n.resumeSessionAt}`),n.resumeDropsTurn!==void 0&&e.push(`--resume-drops-turn=${n.resumeDropsTurn}`),n.sessionId&&e.push("--session-id",n.sessionId),n.permissionMode&&(n.permissionMode==="yolo"?e.push("--yolo"):e.push("--permission-mode",n.permissionMode)),n.allowDangerouslySkipPermissions&&n.permissionMode!=="yolo"&&e.push("--dangerously-skip-permissions"),n.includePartialMessages&&e.push("--include-partial-messages"),n.allowedTools&&n.allowedTools.length>0)for(let r of n.allowedTools)e.push("--allowed-tools",r);if(n.disallowedTools&&n.disallowedTools.length>0)for(let r of n.disallowedTools)e.push("--disallowed-tools",r);let s=n.tools??cs(n.env??process.env);if(Array.isArray(s)?e.push("--tools",s.join(",")):e.push("--tools","default"),n.canUseTool){if(n.permissionPromptToolName)throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");e.push("--permission-prompt-tool","stdio")}else n.permissionPromptToolName&&e.push("--permission-prompt-tool",n.permissionPromptToolName);if(n.extensions&&n.extensions.length>0)for(let r of n.extensions)e.push("--extensions",r);if(n.mcpServers&&Object.keys(n.mcpServers).length>0&&e.push("--mcp-config",JSON.stringify({mcpServers:this.buildCliMcpServers()})),n.allowedMcpServerNames&&n.allowedMcpServerNames.length>0)for(let r of n.allowedMcpServerNames)e.push("--allowed-mcp-server-names",r);n.strictMcpConfig&&e.push("--strict-mcp-config");let o=this.buildSettingsArg();if(o!==void 0&&e.push("--settings",o),n.settingSources!==void 0&&e.push("--setting-sources",n.settingSources.join(",")),e.push("--disable-builtin-skills"),n.additionalDirectories&&n.additionalDirectories.length>0)for(let r of n.additionalDirectories)e.push("--add-dir",r);if(n.maxTurns!==void 0&&e.push("--max-turns",String(n.maxTurns)),n.forkSession&&e.push("--fork-session"),n.plugins&&n.plugins.length>0)for(let r of n.plugins)r.type==="local"&&e.push("--plugin-dir",r.path);if(n.extraArgs)for(let[r,i]of Object.entries(n.extraArgs))e.push(`--${r}`),i!==null&&e.push(i);return e}buildSettingsArg(){let e=this.options.settings,n=this.collectMcpPolicyPermissionRules();if(typeof e=="string"){if(e.length===0)return;if(!this.hasMcpPolicyRules(n)&&!this.options.enableFileCheckpointing&&this.options.securityScan===void 0&&(!this.options.additionalDirectories||this.options.additionalDirectories.length===0))return e;let r=this.readSettingsFile(e);this.applySettingsCompatibility(r),this.applyAdditionalDirectories(r),this.applyMcpPolicyRules(r,n),this.applySecurityScanSetting(r);let i=this.applyFileCheckpointingSetting(r);return Object.keys(i).length>0?this.writeGeneratedSettingsFile(i):void 0}let s={...e??{}};this.applySettingsCompatibility(s),this.applyAdditionalDirectories(s),this.applyMcpPolicyRules(s,n),this.applySecurityScanSetting(s);let o=this.applyFileCheckpointingSetting(s);return Object.keys(o).length>0?JSON.stringify(o):void 0}applyFileCheckpointingSetting(e){return this.options.enableFileCheckpointing?Fi(e):e}applySecurityScanSetting(e){let n=this.options.securityScan;n!==void 0&&(e.securityScan=ms(n))}applySettingsCompatibility(e){let n=e.permissions;if(n?.defaultMode!==void 0){let s=e.general!==null&&typeof e.general=="object"?e.general:{},o=this.toQoderDefaultPermissionMode(n.defaultMode);o!==void 0&&s.defaultPermissionMode===void 0&&(s.defaultPermissionMode=o),e.general=s}n?.disableBypassPermissionsMode==="disable"&&(e.security={...e.security??{},disableYoloMode:!0})}toQoderDefaultPermissionMode(e){switch(e){case"acceptEdits":return"accept_edits";case"bypassPermissions":case"yolo":return"bypass_permissions";case"dontAsk":return"dont_ask";case"default":case"accept_edits":case"bypass_permissions":case"dont_ask":case"plan":case"auto":return e;default:return}}applyAdditionalDirectories(e){let n=this.options.additionalDirectories;if(!n||n.length===0)return;let s=e.permissions!==null&&typeof e.permissions=="object"?e.permissions:{},o=Array.isArray(s.additionalDirectories)?[...s.additionalDirectories]:[];_s(o,n),s.additionalDirectories=o,e.permissions=s}buildCliMcpServers(){let e=this.options.mcpServers;if(!e||Object.keys(e).length===0)return e;let n={};for(let[s,o]of Object.entries(e)){let r=this.options.mcpToolPolicies?.[s]??o.tools??[];n[s]=tn(s,o,r)}return n}collectMcpPolicyPermissionRules(){let e=Ni(),n=new Map;for(let[s,o]of Object.entries(this.options.mcpToolPolicies??{}))o.length>0&&n.set(s,o);for(let[s,o]of Object.entries(this.options.mcpServers??{})){let r=o.tools;Array.isArray(r)&&r.length>0&&n.set(s,[...n.get(s)??[],...r])}for(let[s,o]of n)for(let r of o){let i=ji(s,r.name);switch(r.permission_policy){case"always_allow":e.allow.push(i);break;case"always_ask":e.ask.push(i);break;case"always_deny":e.deny.push(i);break;case void 0:break}}return e}hasMcpPolicyRules(e){return e.allow.length>0||e.ask.length>0||e.deny.length>0}applyMcpPolicyRules(e,n){if(!this.hasMcpPolicyRules(n))return;let s=e.permissions!==null&&typeof e.permissions=="object"?e.permissions:{};e.permissions=s;for(let o of["allow","ask","deny"]){let r=Array.isArray(s[o])?[...s[o]]:[];_s(r,n[o]),s[o]=r}}readSettingsFile(e){let n=Pi(e,"utf8").trim();if(!n)return{};let s=JSON.parse(n);if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Settings file must contain a JSON object.");return s}writeGeneratedSettingsFile(e){this.generatedSettingsDir=Ri(z(hs(),"qoder-agent-sdk-settings-"));let n=z(this.generatedSettingsDir,"settings.json");return Ti(n,JSON.stringify(e),"utf8"),n}async createAuthPayloadFile(e){let n=vt(e,this.options.env),s=await ki(z(hs(),"qoder-sdk-auth-"));try{await fs(s,448);let o=z(s,"payload.json");return await Ci(o,JSON.stringify(n),{mode:384}),await fs(o,384),this.diagnostics?.record(`${this.logPrefix} Auth payload created: type=${n.type}, path=${o}`),o}catch(o){throw await gs(s,{recursive:!0,force:!0}).catch(()=>{}),o}}};function vt(t,e){switch(t.type){case"accessToken":return{type:"accessToken",accessToken:Ki(t,e)};case"qodercli":return{type:"qodercli"};case"jobToken":return{type:"jobToken",jobTokenProvider:"host"};case"serviceAccount":{let n=t.serviceAccountKey!==void 0,s=typeof t.fetchServiceAccountToken=="function";if(n===s)throw new TypeError("Service Account auth requires exactly one credential source: serviceAccountKey or fetchServiceAccountToken");return s?{type:"serviceAccount",serviceAccountTokenProvider:"host"}:{type:"serviceAccount",serviceAccountKey:Ui(t,e)}}}}function Ui(t,e){if(!t.serviceAccountKey)throw new Error("Service Account key authentication requires serviceAccountKey");if(typeof t.serviceAccountKey=="string")return t.serviceAccountKey;let n=t.serviceAccountKey.envVar,s=e&&Object.hasOwn(e,n)?e[n]:process.env[n];if(!s)throw new yt(n);return s}function Ki(t,e){if(typeof t.accessToken=="string")return t.accessToken;let n=t.accessToken.envVar,s=e&&Object.hasOwn(e,n)?e[n]:process.env[n];if(!s)throw new ht(n);return s}function Li(t,e){if(process.platform!=="win32"){delete t[e];return}let n=e.toLowerCase();for(let s of Object.keys(t))s.toLowerCase()===n&&delete t[s]}function bt(t){if(!ue(t)||Array.isArray(t))return;let e=t.total_credits,n=t.model_usage;if(!nn(e)||e<0||!ue(n)||Array.isArray(n))return;let s={};for(let[o,r]of Object.entries(n)){if(!ue(r)||Array.isArray(r))continue;let i=r.credits;nn(i)&&i>=0&&(s[o]={credits:i})}return{total_credits:e,model_usage:s}}function _t(t){if(!ue(t)||Array.isArray(t))return null;let e={};Ee(e,t,"userId"),Ee(e,t,"userType"),H(e,t,"totalUsagePercentage"),wt(e,t,"isHighestTier"),H(e,t,"expiresAt"),Ee(e,t,"upgradeUrl"),wt(e,t,"isQuotaExceeded"),wt(e,t,"isPlanQuotaProrated");let n=Rs(t.userQuota);n&&(e.userQuota=n);let s=Bi(t.addOnQuota);s&&(e.addOnQuota=s);let o=$i(t.orgResourcePackage);return o&&(e.orgResourcePackage=o),e}function ue(t){return typeof t=="object"&&t!==null}function nn(t){return typeof t=="number"&&Number.isFinite(t)}function sn(t){return Object.keys(t).length>0}function H(t,e,n){let s=e[n];nn(s)&&(t[n]=s)}function Ee(t,e,n){let s=e[n];typeof s=="string"&&(t[n]=s)}function wt(t,e,n){let s=e[n];typeof s=="boolean"&&(t[n]=s)}function Rs(t){if(!ue(t)||Array.isArray(t))return;let e={};return H(e,t,"total"),H(e,t,"used"),H(e,t,"remaining"),H(e,t,"percentage"),Ee(e,t,"unit"),sn(e)?e:void 0}function Bi(t){if(!ue(t)||Array.isArray(t))return;let e=Rs(t)??{};return Ee(e,t,"detailUrl"),sn(e)?e:void 0}function $i(t){if(!ue(t)||Array.isArray(t))return;let e={};return H(e,t,"used"),H(e,t,"cap"),H(e,t,"remaining"),H(e,t,"percentage"),wt(e,t,"available"),Ee(e,t,"unit"),sn(e)?e:void 0}import{existsSync as un}from"node:fs";import{dirname as ca,join as ce}from"node:path";import{fileURLToPath as la}from"node:url";import{createHash as Qi}from"node:crypto";import{existsSync as Gi}from"node:fs";import{chmod as zi,lstat as Hi,mkdir as Be,readFile as Ps,readdir as Wi,readlink as Ji,rename as Vi,rm as kt,stat as Yi,symlink as Xi,writeFile as Es}from"node:fs/promises";import{tmpdir as Zi,userInfo as ea}from"node:os";import{basename as Ts,dirname as Te,join as W,relative as ta}from"node:path";var na="QODER_WORKER_RUNTIME_ASSET_ROOT",Ms=/(^|[\\/])app\.asar([\\/]|$)/,rn=".qoder-worker-runtime-ready";function As(t){return Ms.test(t)}function an(t){return As(t)?t.replace(Ms,(e,n,s)=>`${n}app.asar.unpacked${s}`):null}async function Me(t,e={}){let n=an(t);if(!e.forceMaterialize&&n){let u=Te(n);if(Gi(n))return e.diagnostics?.record(`[WorkerTransport] Using asar-unpacked worker runtime: ${n}`),on(n,u,!1,Te(t))}if(!(e.forceMaterialize||As(t))){let u=Te(t);return on(t,u,!1)}let o=Te(t),r=await sa(o,t,{cacheDir:e.cacheDir,diagnostics:e.diagnostics}),i=ta(o,t)||Ts(t),a=W(r,i);return on(a,r,!0,o)}function on(t,e,n,s){return{runtimePath:t,runtimeRoot:e,materialized:n,sourceRuntimeRoot:s,env:{[na]:e}}}async function sa(t,e,n){let s=await oa(t,e),o=n.cacheDir??aa(),r=W(o,s),i=W(r,rn);if(await Ds(i)===s)return r;let a=W(o,`.setup-${s}-${process.pid}-${Date.now()}`);await Be(o,{recursive:!0,mode:448}),await kt(a,{recursive:!0,force:!0}),await kt(r,{recursive:!0,force:!0}),n.diagnostics?.record(`[WorkerTransport] Materializing worker runtime: ${t} -> ${r}`);try{return await Be(a,{recursive:!0,mode:448}),await Is(t,a),await Es(W(a,rn),s,{mode:384}),await ia(a,r,s),r}catch(u){throw await kt(a,{recursive:!0,force:!0}).catch(()=>{}),u}}async function oa(t,e){let n=Qi("sha256");n.update("qoder-worker-runtime-v1\0");let s=await xs(W(t,"runtime-info.json"));if(s)n.update(s);else{n.update(e);let o=await Yi(e).catch(()=>null);o&&n.update(`${o.size}\0${o.mtimeMs}`)}return`runtime-${n.digest("hex").slice(0,24)}`}async function Is(t,e){let n=await Wi(t,{withFileTypes:!0});await Be(e,{recursive:!0,mode:448});for(let s of n){let o=W(t,s.name),r=W(e,s.name);if(s.isDirectory()){await Is(o,r);continue}if(s.isSymbolicLink()){await Be(Te(r),{recursive:!0,mode:448}),await Xi(await Ji(o),r);continue}if(!s.isFile())continue;let i=await ra(o);await Be(Te(r),{recursive:!0,mode:448}),await Es(r,await Ps(o),{mode:i}),process.platform!=="win32"&&await zi(r,i)}}async function ra(t){let e=((await Hi(t)).mode||420)&511;if(process.platform==="win32")return e||420;let n=Ts(t);return n==="rg"||n==="spawn-helper"||/\.(?:node|dylib|exe)$/.test(n)||/\.so(?:\.\d+)*$/.test(n)?493:e||420}async function ia(t,e,n){try{await Vi(t,e)}catch(s){if(await Ds(W(e,rn))===n){await kt(t,{recursive:!0,force:!0});return}throw s}}async function Ds(t){let e=await xs(t);return e?e.toString("utf8"):null}async function xs(t){try{return await Ps(t)}catch{return null}}function aa(){let t=ua(ea().username||process.env.USER||process.env.USERNAME||"user");return W(Zi(),`qoder-sdk-worker-runtime-${t}`)}function ua(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_")||"unknown"}var da=la(import.meta.url),cn=ca(da);function le(t){if(t)return t;let e=[];for(let n of pa())e.push(ce(n,"dist","_worker","qoder-worker-runtime.obf.mjs"),ce(n,"dist","_worker","qoder-worker-runtime.mjs"),ce(n,"_worker","qoder-worker-runtime.obf.mjs"),ce(n,"_worker","qoder-worker-runtime.mjs"));for(let n of e)if(un(n))return n;return e[0]??ce(cn,"..","_worker","qoder-worker-runtime.obf.mjs")}function $e(t){let e=le(t);if(un(e))return!0;let n=an(e);return n!==null&&un(n)}function pa(){let t=[ce(cn,".."),ce(cn,"..","..")];return[...new Set(t)]}import{appendFileSync as ma,mkdirSync as fa}from"fs";import{dirname as ga}from"path";import{randomUUID as ha}from"node:crypto";var ya="QODER_AGENT_SDK_DEBUG";function Sa(t){return t.debugFile?!0:t.debug===!0||wa(process.env[ya])}function va(t){if(t.debugFile)return t.debugFile}function wa(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"&&e!=="no"&&e!=="off"}var Z=class{correlationId=ha();onCloseDiagnostic;enabled;debugFile;stderr;constructor(e={}){this.onCloseDiagnostic=e.onCloseDiagnostic,this.enabled=Sa(e),this.debugFile=va(e),this.stderr=e.stderr}record(e,n){if(!this.enabled)return;let s=this.formatLine(e,n),o=this.debugFile;if(o){this.writeToFile(o,s);return}this.writeToStderr(s)}recordClose(e){let n=Object.freeze({...e,correlationId:this.correlationId});this.record(`[SDK close] ${JSON.stringify(n)}`),queueMicrotask(()=>{try{Promise.resolve(this.onCloseDiagnostic?.(n)).catch(()=>{})}catch{}})}get filePath(){return this.debugFile}writeToFile(e,n){try{fa(ga(e),{recursive:!0}),ma(e,n,"utf8")}catch{}}writeToStderr(e){try{this.stderr?this.stderr(e):process.stderr.write(e)}catch{}}formatLine(e,n){let s=new Date().toISOString(),o=this.formatError(n);return`${s} ${e}${o}
|
|
1
|
+
var oi=Object.defineProperty;var ri=(t,e)=>{for(var n in e)oi(t,n,{get:e[n],enumerable:!0})};function rs(t){return typeof t=="object"&&t!==null&&typeof t.create=="function"}function we(t,e){return t.create(e)}var be=class{constructor(e){this.bootstrap=e}transport;bootstrapPromise;pending=[];closed=!1;closePromise;cleanup;cleanupPromise;async initialize(){if(this.closed){await this.closePromise;return}try{let e=await this.getTransport();if(this.closed)return;if(await e.initialize(),this.closed){await e.close(),await this.runCleanup();return}for(let n of this.pending.splice(0))n.type==="write"?await e.write(n.data):e.endInput()}catch(e){throw await this.runCleanup(),e}}write(e){if(this.closed)throw new Error("Transport has been closed");if(this.transport?.isReady()){this.transport.write(e);return}this.pending.push({type:"write",data:e})}close(){return this.closePromise||(this.closed=!0,this.pending.length=0,this.closePromise=this.performClose(),this.closePromise.catch(()=>{})),this.closePromise}isReady(){return!this.closed&&(this.transport?.isReady()??!1)}async*readMessages(){try{if(await this.initialize(),this.closed)return;yield*(await this.getTransport()).readMessages()}finally{await this.runCleanup()}}endInput(){if(!this.closed){if(this.transport?.isReady()){this.transport.endInput();return}this.pending.push({type:"endInput"})}}async getTransport(){return this.bootstrapPromise||(this.bootstrapPromise=this.bootstrap().then(e=>(this.transport=e.transport,this.cleanup=e.cleanup,e.transport))),this.bootstrapPromise}async performClose(){let e=this.transport;if(!e&&this.bootstrapPromise)try{e=await this.bootstrapPromise}catch{await this.runCleanup();return}try{await e?.close()}finally{await this.runCleanup()}}runCleanup(){return this.cleanupPromise||(this.cleanupPromise=this.cleanup?.()??Promise.resolve()),this.cleanupPromise}};import{spawn as su}from"node:child_process";import{join as ou}from"node:path";import{homedir as ui}from"os";import{join as us}from"path";var ii="global",is=ii==="cn",ai=is?"QODERCN_":"QODER_",Jt=`${ai}VPC_ENDPOINT`,w=is?{productName:"QoderCN",packageName:"@qodercn-ai/qodercn-agent-sdk",cliCommands:["qoderclicn","qodercn"],configDirName:".qoder-cn",projectConfigDirName:".qoder",configDirEnv:"QODERCN_CONFIG_DIR",configDirNameEnv:"QODERCN_CONFIG_DIR_NAME",cliHomeEnv:"QODERCN_CLI_HOME",accessTokenEnv:"QODERCN_PERSONAL_ACCESS_TOKEN",serviceAccountEnv:"QODERCN_SERVICE_ACCOUNT_KEY"}:{productName:"Qoder",packageName:"@qoder-ai/qoder-agent-sdk",cliCommands:["qodercli","qoder"],configDirName:".qoder",projectConfigDirName:".qoder",configDirEnv:"QODER_CONFIG_DIR",configDirNameEnv:"QODER_CONFIG_DIR_NAME",cliHomeEnv:"QODER_CLI_HOME",accessTokenEnv:"QODER_PERSONAL_ACCESS_TOKEN",serviceAccountEnv:"QODER_SERVICE_ACCOUNT_KEY"};var ci=w.configDirName,li=w.cliHomeEnv,di=w.configDirEnv,as=200;function pi(){return process.env[li]||ui()}function Vt(){let t=process.env[di];return t||us(pi(),ci)}function _e(){return us(Vt(),"projects")}function mi(t){let e=5381;for(let n=0;n<t.length;n++)e=e*33^t.charCodeAt(n);return e}function j(t){let e=t.replace(/[^a-zA-Z0-9]/g,"-");if(e.length<=as)return e;let n=Math.abs(mi(t)).toString(36);return`${e.slice(0,as)}-${n}`}var K=class extends Error{code="QODER_CLI_PROCESS_ERROR";exitCode;signal;stderr;constructor(e,n){super(e,n?.cause?{cause:n.cause}:void 0),this.name="QoderCliProcessError",this.exitCode=n?.exitCode,this.signal=n?.signal,this.stderr=n?.stderr}},G=class extends Error{constructor(n,s,o,r,i){super(`${r} exceeded the ${s}-byte frame limit`+(n==="input"?". Reduce the input text or remove attachments and try again.":""));this.direction=n;this.limit=s;this.actualBytes=o;this.source=r;this.inputMessageUuid=i;this.name="FrameTooLargeError",this.code=n==="input"?"SDK_INPUT_TOO_LARGE":"SDK_OUTPUT_TOO_LARGE"}code},ke=class extends Error{code;result;constructor(e){let n=e.subtype==="success"?e.result:e.errors?.filter(s=>s.trim().length>0).join(`
|
|
2
|
+
`);super(n?.trim()?n:"Qoder CLI initialization failed."),this.name="QoderCliInitializationError",this.code=e.error_code,this.result=e}},E=class extends Error{constructor(e="Operation was aborted"){super(e),this.name="AbortError"}},Le=class extends Error{timeoutMs;constructor(e){super(`resolveModel did not return within ${e}ms. Increase resolveModelTimeoutMs or ensure the callback resolves faster.`),this.name="ModelPolicyTimeoutError",this.timeoutMs=e}},X=class extends Error{cliProtocolVersion;sdkProtocolVersion;constructor(e,n){super(`Wire protocol major mismatch: CLI announced "${e}" but this SDK was built for "${n}". Upgrade either qodercli or @qoder-ai/qoder-agent-sdk so the major versions align.`),this.name="ProtocolVersionMismatchError",this.cliProtocolVersion=e,this.sdkProtocolVersion=n}},L=class extends Error{capability;constructor(e){super(`The running qodercli does not advertise the required capability "${e}". Upgrade qodercli or use a matching bundled SDK runtime.`),this.name="UnsupportedCliCapabilityError",this.capability=e}},Yt="CONTROL_REQUEST_TIMEOUT",Ce=class extends Error{requestId;code;retryable;details;constructor(e){super(e.message),this.name="ControlRequestError",this.requestId=e.requestId,this.code=e.code,this.retryable=e.retryable===!0,this.details=e.details}};import{chmod as hs,mkdtemp as Ri,rm as ys,writeFile as Pi}from"fs/promises";import{existsSync as vt,mkdtempSync as Ei,readFileSync as Ti,rmSync as Mi,writeFileSync as Ai}from"fs";import{homedir as Di,tmpdir as Ss}from"os";import{dirname as Rs,join as H}from"path";import{fileURLToPath as Ii}from"url";var fi=["PreToolUse","PostToolUse","PostToolUseFailure","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStart","SubagentStop","PreCompact","PostCompact","CwdChanged","InstructionsLoaded","FileChanged","PermissionRequest","PermissionDenied","WorktreeCreate","WorktreeRemove"],gi=["clear","resume","logout","prompt_input_exit","other","bypass_permissions_disabled"],Xt=2e3;var gt="1.0.59";var cs=["Agent","AskUserQuestion","Bash","Edit","Glob","Grep","ImageGen","ImageSearch","NotebookEdit","Read","Skill","TaskCreate","TaskGet","TaskUpdate","TaskList","UpdateGoal","WebFetch","WebSearch","Write"],ls=["TaskCreate","TaskGet","TaskUpdate","TaskList"],hi="QODER_FEATURE_TASKS";function ds(t){let e=t[hi];if(e!=="0"&&e!=="false")return[...cs];let n=new Set(ls);return cs.flatMap(s=>s===ls[0]?["TodoWrite"]:n.has(s)?[]:[s])}var yi=/^[A-Za-z0-9_-]{1,64}$/,Si=new Set(["mcp_list","mcp_get","mcp_call"]);function Zt(t,e){if(e.exposedName!==void 0){if(e.alwaysLoad!==!0)throw new Error(`MCP tool "${t}/${e.name}" requires alwaysLoad: true when exposedName is set.`);if(!yi.test(e.exposedName))throw new Error(`MCP tool "${t}/${e.name}" has invalid exposedName "${e.exposedName}".`);if(Si.has(e.exposedName))throw new Error(`MCP tool "${t}/${e.name}" cannot use reserved exposedName "${e.exposedName}".`)}}function en(t,e){let n={};for(let s of e)Zt(t,s),(s.exposedName!==void 0||s.alwaysLoad===!0)&&(n[s.name]={...s.exposedName!==void 0?{exposedName:s.exposedName}:{},...s.alwaysLoad===!0?{alwaysLoad:!0}:{}});return Object.keys(n).length>0?n:void 0}function tn(t,e,n=e.tools??[]){let{tools:s,...o}=e,r=en(t,n);return{...o,...r?{toolOverrides:r}:{}}}function ps(t){let e={};for(let[n,s]of Object.entries(t)){if(s.type==="sdk")throw new Error(`MCP server "${n}" uses an in-process SDK transport and cannot be changed with setMcpServers().`);let o=s.tools??[],r=o.find(i=>i.permission_policy!==void 0);if(r)throw new Error(`MCP tool "${n}/${r.name}" cannot set permission_policy through setMcpServers(); configure it when creating the query.`);e[n]=tn(n,s,o)}return e}var ms=w.accessTokenEnv,ht=w.serviceAccountEnv;function vi(t){return{type:"accessToken",accessToken:t}}function wi(t=ms){return{type:"accessToken",accessToken:{envVar:t}}}function bi(){return{type:"qodercli"}}function _i(t){let e=t.serviceAccountKey!==void 0,n=typeof t.fetchServiceAccountToken=="function";if(e===n)throw new TypeError("serviceAccount() requires exactly one credential source: serviceAccountKey or fetchServiceAccountToken");return{type:"serviceAccount",...t}}function ki(t=ht){return{type:"serviceAccount",serviceAccountKey:{envVar:t}}}function Ci(t){return{type:"jobToken",fetchJobToken:t}}var fs=["l1StaticCheck","l2LightweightScan","l3DeepScan"];function gs(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("securityScan must be an object.");let e=new Set(fs),n=Object.keys(t).filter(s=>!e.has(s));if(n.length>0)throw new TypeError(`securityScan contains unknown option${n.length===1?"":"s"}: ${n.join(", ")}.`);for(let s of fs){let o=t[s];if(o!==void 0&&typeof o!="boolean")throw new TypeError(`securityScan.${s} must be a boolean.`)}return{l1StaticCheck:t.l1StaticCheck??!1,l2LightweightScan:t.l2LightweightScan??!1,l3DeepScan:t.l3DeepScan??!1}}var vs="QODER_AGENT_SDK_ENTRYPOINT",ws="QODER_AGENT_SDK_VERSION",bs="QODER_SDK_AUTH_PAYLOAD_FILE",xi="sdk-ts",Oi=Ii(import.meta.url),_s=Rs(Oi),yt=class extends Error{code="auth_access_token_env_var_not_configured";constructor(e){super(`The auth access token environment variable "${e}" is not set; set it or pass auth.accessToken directly.`),this.name="AuthAccessTokenEnvVarError"}},St=class extends Error{code="auth_service_account_env_var_not_configured";constructor(e){super(`The Service Account key environment variable "${e}" is not set; set it or pass auth.serviceAccountKey directly.`),this.name="AuthServiceAccountEnvVarError"}};function Re(t){return/\.(js|mjs|tsx?|jsx)$/.test(t)}function Pe(){if(process.env.QODERCLI_PATH)return process.env.QODERCLI_PATH;let t=qi();if(t)return t;let e=Ni();if(vt(e))return e;let n=ji();return n||w.cliCommands[0]}function qi(){for(let t of Ps())for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=H(t,"dist","_bundled",n);if(vt(s))return s}return null}function Ni(){for(let t of Ps())for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=[H(t,"node_modules",".bin",n),H(t,"..","..",".bin",n)];for(let o of s)if(vt(o))return o}return w.cliCommands[0]}function ji(){let t=process.env[w.cliHomeEnv]??Di();for(let e of w.cliCommands){let n=process.platform==="win32"?`${e}.exe`:e,s=H(t,w.configDirName,"local",n);if(vt(s))return s}return null}function Ps(){let t=[H(_s,".."),H(_s,"..","..")];return[...new Set(t)]}function Fi(){return{allow:[],ask:[],deny:[]}}function ks(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function Ui(t,e){if(e.startsWith("mcp__"))return e;let n=ks(t),s=e==="*"?"*":ks(e);if(!n||!s)throw new Error(`Invalid MCP tool policy name for server "${t}" and tool "${e}"`);return`mcp__${n}__${s}`}function Cs(t,e){if(e.length===0)return;let n=new Set(t);for(let s of e)n.has(s)||(t.push(s),n.add(s))}function Ki(t){let e=t??{},n=e.general&&typeof e.general=="object"&&!Array.isArray(e.general)?e.general:{},s=n.fileCheckpointing&&typeof n.fileCheckpointing=="object"&&!Array.isArray(n.fileCheckpointing)?n.fileCheckpointing:{};return{...e,general:{...n,fileCheckpointing:{...s,enabled:!0}}}}var ue=class{options;diagnostics;logPrefix;authPayloadPath=null;generatedSettingsDir;constructor(e,n,s="[RuntimeLaunch]"){this.options=e,this.diagnostics=n,this.logPrefix=s}async prepare(){return this.options.auth&&(this.authPayloadPath=await this.createAuthPayloadFile(this.options.auth)),{args:this.buildArgs(),env:this.buildEnv(),authPayloadPath:this.authPayloadPath??void 0}}cleanupGeneratedSettings(){if(this.generatedSettingsDir)try{Mi(this.generatedSettingsDir,{recursive:!0,force:!0})}catch{}finally{this.generatedSettingsDir=void 0}}async cleanupLaunchArtifacts(){this.cleanupGeneratedSettings(),await this.cleanupAuthPayload()}async cleanupAuthPayload(){if(!this.authPayloadPath)return;let e=Rs(this.authPayloadPath);try{await ys(e,{recursive:!0,force:!0}),this.diagnostics?.record(`${this.logPrefix} Auth payload cleaned up`)}catch{}this.authPayloadPath=null}buildEnv(){let e=this.options.env??{...process.env},n={};for(let[s,o]of Object.entries(e))o!==void 0&&(n[s]=o);delete n[vs],delete n[ws],delete n[bs];for(let s of this.serviceAccountCredentialEnvVars())$i(n,s);if(n[vs]=xi,n[ws]=gt,this.authPayloadPath&&(n[bs]=this.authPayloadPath),delete n.NODE_OPTIONS,this.options.vpcEndpoint!==void 0){let s=this.options.vpcEndpoint.trim();s?n[Jt]=s:delete n[Jt]}return n}serviceAccountCredentialEnvVars(){let e=this.options.auth;if(e?.type!=="serviceAccount")return[];let n=[ht];return e.serviceAccountKey&&typeof e.serviceAccountKey!="string"&&n.push(e.serviceAccountKey.envVar),n}buildArgs(){let e=[],n=this.options;if(n.extraArgs&&Object.hasOwn(n.extraArgs,"proxy"))throw new Error("extraArgs.proxy is reserved; use the dedicated proxy option instead.");if(e.push("--print"),e.push("--output-format","stream-json"),e.push("--input-format","stream-json"),n.sessionMirror&&e.push("--session-mirror"),n.persistSession===!1&&e.push("--no-session-persistence"),n.model&&e.push("--model",n.model),n.proxy!==void 0&&e.push("--proxy",n.proxy),n.agent&&e.push("--agent",n.agent),n.debug&&e.push("--debug"),n.resume?e.push("--resume",n.resume):n.continue&&e.push("--continue"),n.resumeSessionAt&&e.push(`--resume-session-at=${n.resumeSessionAt}`),n.resumeDropsTurn!==void 0&&e.push(`--resume-drops-turn=${n.resumeDropsTurn}`),n.sessionId&&e.push("--session-id",n.sessionId),n.permissionMode&&(n.permissionMode==="yolo"?e.push("--yolo"):e.push("--permission-mode",n.permissionMode)),n.allowDangerouslySkipPermissions&&n.permissionMode!=="yolo"&&e.push("--dangerously-skip-permissions"),n.includePartialMessages&&e.push("--include-partial-messages"),n.allowedTools&&n.allowedTools.length>0)for(let r of n.allowedTools)e.push("--allowed-tools",r);if(n.disallowedTools&&n.disallowedTools.length>0)for(let r of n.disallowedTools)e.push("--disallowed-tools",r);let s=n.tools??ds(n.env??process.env);if(Array.isArray(s)?e.push("--tools",s.join(",")):e.push("--tools","default"),n.canUseTool){if(n.permissionPromptToolName)throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");e.push("--permission-prompt-tool","stdio")}else n.permissionPromptToolName&&e.push("--permission-prompt-tool",n.permissionPromptToolName);if(n.extensions&&n.extensions.length>0)for(let r of n.extensions)e.push("--extensions",r);if(n.mcpServers&&Object.keys(n.mcpServers).length>0&&e.push("--mcp-config",JSON.stringify({mcpServers:this.buildCliMcpServers()})),n.allowedMcpServerNames&&n.allowedMcpServerNames.length>0)for(let r of n.allowedMcpServerNames)e.push("--allowed-mcp-server-names",r);n.strictMcpConfig&&e.push("--strict-mcp-config");let o=this.buildSettingsArg();if(o!==void 0&&e.push("--settings",o),n.settingSources!==void 0&&e.push("--setting-sources",n.settingSources.join(",")),e.push("--disable-builtin-skills"),n.additionalDirectories&&n.additionalDirectories.length>0)for(let r of n.additionalDirectories)e.push("--add-dir",r);if(n.maxTurns!==void 0&&e.push("--max-turns",String(n.maxTurns)),n.forkSession&&e.push("--fork-session"),n.plugins&&n.plugins.length>0)for(let r of n.plugins)r.type==="local"&&e.push("--plugin-dir",r.path);if(n.extraArgs)for(let[r,i]of Object.entries(n.extraArgs))e.push(`--${r}`),i!==null&&e.push(i);return e}buildSettingsArg(){let e=this.options.settings,n=this.collectMcpPolicyPermissionRules();if(typeof e=="string"){if(e.length===0)return;if(!this.hasMcpPolicyRules(n)&&!this.options.enableFileCheckpointing&&this.options.securityScan===void 0&&(!this.options.additionalDirectories||this.options.additionalDirectories.length===0))return e;let r=this.readSettingsFile(e);this.applySettingsCompatibility(r),this.applyAdditionalDirectories(r),this.applyMcpPolicyRules(r,n),this.applySecurityScanSetting(r);let i=this.applyFileCheckpointingSetting(r);return Object.keys(i).length>0?this.writeGeneratedSettingsFile(i):void 0}let s={...e??{}};this.applySettingsCompatibility(s),this.applyAdditionalDirectories(s),this.applyMcpPolicyRules(s,n),this.applySecurityScanSetting(s);let o=this.applyFileCheckpointingSetting(s);return Object.keys(o).length>0?JSON.stringify(o):void 0}applyFileCheckpointingSetting(e){return this.options.enableFileCheckpointing?Ki(e):e}applySecurityScanSetting(e){let n=this.options.securityScan;n!==void 0&&(e.securityScan=gs(n))}applySettingsCompatibility(e){let n=e.permissions;if(n?.defaultMode!==void 0){let s=e.general!==null&&typeof e.general=="object"?e.general:{},o=this.toQoderDefaultPermissionMode(n.defaultMode);o!==void 0&&s.defaultPermissionMode===void 0&&(s.defaultPermissionMode=o),e.general=s}n?.disableBypassPermissionsMode==="disable"&&(e.security={...e.security??{},disableYoloMode:!0})}toQoderDefaultPermissionMode(e){switch(e){case"acceptEdits":return"accept_edits";case"bypassPermissions":case"yolo":return"bypass_permissions";case"dontAsk":return"dont_ask";case"default":case"accept_edits":case"bypass_permissions":case"dont_ask":case"plan":case"auto":return e;default:return}}applyAdditionalDirectories(e){let n=this.options.additionalDirectories;if(!n||n.length===0)return;let s=e.permissions!==null&&typeof e.permissions=="object"?e.permissions:{},o=Array.isArray(s.additionalDirectories)?[...s.additionalDirectories]:[];Cs(o,n),s.additionalDirectories=o,e.permissions=s}buildCliMcpServers(){let e=this.options.mcpServers;if(!e||Object.keys(e).length===0)return e;let n={};for(let[s,o]of Object.entries(e)){let r=this.options.mcpToolPolicies?.[s]??o.tools??[];n[s]=tn(s,o,r)}return n}collectMcpPolicyPermissionRules(){let e=Fi(),n=new Map;for(let[s,o]of Object.entries(this.options.mcpToolPolicies??{}))o.length>0&&n.set(s,o);for(let[s,o]of Object.entries(this.options.mcpServers??{})){let r=o.tools;Array.isArray(r)&&r.length>0&&n.set(s,[...n.get(s)??[],...r])}for(let[s,o]of n)for(let r of o){let i=Ui(s,r.name);switch(r.permission_policy){case"always_allow":e.allow.push(i);break;case"always_ask":e.ask.push(i);break;case"always_deny":e.deny.push(i);break;case void 0:break}}return e}hasMcpPolicyRules(e){return e.allow.length>0||e.ask.length>0||e.deny.length>0}applyMcpPolicyRules(e,n){if(!this.hasMcpPolicyRules(n))return;let s=e.permissions!==null&&typeof e.permissions=="object"?e.permissions:{};e.permissions=s;for(let o of["allow","ask","deny"]){let r=Array.isArray(s[o])?[...s[o]]:[];Cs(r,n[o]),s[o]=r}}readSettingsFile(e){let n=Ti(e,"utf8").trim();if(!n)return{};let s=JSON.parse(n);if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Settings file must contain a JSON object.");return s}writeGeneratedSettingsFile(e){this.generatedSettingsDir=Ei(H(Ss(),"qoder-agent-sdk-settings-"));let n=H(this.generatedSettingsDir,"settings.json");return Ai(n,JSON.stringify(e),"utf8"),n}async createAuthPayloadFile(e){let n=wt(e,this.options.env),s=await Ri(H(Ss(),"qoder-sdk-auth-"));try{await hs(s,448);let o=H(s,"payload.json");return await Pi(o,JSON.stringify(n),{mode:384}),await hs(o,384),this.diagnostics?.record(`${this.logPrefix} Auth payload created: type=${n.type}, path=${o}`),o}catch(o){throw await ys(s,{recursive:!0,force:!0}).catch(()=>{}),o}}};function wt(t,e){switch(t.type){case"accessToken":return{type:"accessToken",accessToken:Bi(t,e)};case"qodercli":return{type:"qodercli"};case"jobToken":return{type:"jobToken",jobTokenProvider:"host"};case"serviceAccount":{let n=t.serviceAccountKey!==void 0,s=typeof t.fetchServiceAccountToken=="function";if(n===s)throw new TypeError("Service Account auth requires exactly one credential source: serviceAccountKey or fetchServiceAccountToken");return s?{type:"serviceAccount",serviceAccountTokenProvider:"host"}:{type:"serviceAccount",serviceAccountKey:Li(t,e)}}}}function Li(t,e){if(!t.serviceAccountKey)throw new Error("Service Account key authentication requires serviceAccountKey");if(typeof t.serviceAccountKey=="string")return t.serviceAccountKey;let n=t.serviceAccountKey.envVar,s=e&&Object.hasOwn(e,n)?e[n]:process.env[n];if(!s)throw new St(n);return s}function Bi(t,e){if(typeof t.accessToken=="string")return t.accessToken;let n=t.accessToken.envVar,s=e&&Object.hasOwn(e,n)?e[n]:process.env[n];if(!s)throw new yt(n);return s}function $i(t,e){if(process.platform!=="win32"){delete t[e];return}let n=e.toLowerCase();for(let s of Object.keys(t))s.toLowerCase()===n&&delete t[s]}function _t(t){if(!ce(t)||Array.isArray(t))return;let e=t.total_credits,n=t.model_usage;if(!nn(e)||e<0||!ce(n)||Array.isArray(n))return;let s={};for(let[o,r]of Object.entries(n)){if(!ce(r)||Array.isArray(r))continue;let i=r.credits;nn(i)&&i>=0&&(s[o]={credits:i})}return{total_credits:e,model_usage:s}}function kt(t){if(!ce(t)||Array.isArray(t))return null;let e={};Ee(e,t,"userId"),Ee(e,t,"userType"),W(e,t,"totalUsagePercentage"),bt(e,t,"isHighestTier"),W(e,t,"expiresAt"),Ee(e,t,"upgradeUrl"),bt(e,t,"isQuotaExceeded"),bt(e,t,"isPlanQuotaProrated");let n=Es(t.userQuota);n&&(e.userQuota=n);let s=Qi(t.addOnQuota);s&&(e.addOnQuota=s);let o=zi(t.orgResourcePackage);return o&&(e.orgResourcePackage=o),e}function ce(t){return typeof t=="object"&&t!==null}function nn(t){return typeof t=="number"&&Number.isFinite(t)}function sn(t){return Object.keys(t).length>0}function W(t,e,n){let s=e[n];nn(s)&&(t[n]=s)}function Ee(t,e,n){let s=e[n];typeof s=="string"&&(t[n]=s)}function bt(t,e,n){let s=e[n];typeof s=="boolean"&&(t[n]=s)}function Es(t){if(!ce(t)||Array.isArray(t))return;let e={};return W(e,t,"total"),W(e,t,"used"),W(e,t,"remaining"),W(e,t,"percentage"),Ee(e,t,"unit"),sn(e)?e:void 0}function Qi(t){if(!ce(t)||Array.isArray(t))return;let e=Es(t)??{};return Ee(e,t,"detailUrl"),sn(e)?e:void 0}function zi(t){if(!ce(t)||Array.isArray(t))return;let e={};return W(e,t,"used"),W(e,t,"cap"),W(e,t,"remaining"),W(e,t,"percentage"),bt(e,t,"available"),Ee(e,t,"unit"),sn(e)?e:void 0}import{existsSync as un}from"node:fs";import{dirname as da,join as le}from"node:path";import{fileURLToPath as pa}from"node:url";import{createHash as Gi}from"node:crypto";import{existsSync as Hi}from"node:fs";import{chmod as Wi,lstat as Ji,mkdir as Be,readFile as Ts,readdir as Vi,readlink as Yi,rename as Xi,rm as Ct,stat as Zi,symlink as ea,writeFile as Ms}from"node:fs/promises";import{tmpdir as ta,userInfo as na}from"node:os";import{basename as As,dirname as Te,join as J,relative as sa}from"node:path";var oa="QODER_WORKER_RUNTIME_ASSET_ROOT",Ds=/(^|[\\/])app\.asar([\\/]|$)/,rn=".qoder-worker-runtime-ready";function Is(t){return Ds.test(t)}function an(t){return Is(t)?t.replace(Ds,(e,n,s)=>`${n}app.asar.unpacked${s}`):null}async function Me(t,e={}){let n=an(t);if(!e.forceMaterialize&&n){let u=Te(n);if(Hi(n))return e.diagnostics?.record(`[WorkerTransport] Using asar-unpacked worker runtime: ${n}`),on(n,u,!1,Te(t))}if(!(e.forceMaterialize||Is(t))){let u=Te(t);return on(t,u,!1)}let o=Te(t),r=await ra(o,t,{cacheDir:e.cacheDir,diagnostics:e.diagnostics}),i=sa(o,t)||As(t),a=J(r,i);return on(a,r,!0,o)}function on(t,e,n,s){return{runtimePath:t,runtimeRoot:e,materialized:n,sourceRuntimeRoot:s,env:{[oa]:e}}}async function ra(t,e,n){let s=await ia(t,e),o=n.cacheDir??ca(),r=J(o,s),i=J(r,rn);if(await Os(i)===s)return r;let a=J(o,`.setup-${s}-${process.pid}-${Date.now()}`);await Be(o,{recursive:!0,mode:448}),await Ct(a,{recursive:!0,force:!0}),await Ct(r,{recursive:!0,force:!0}),n.diagnostics?.record(`[WorkerTransport] Materializing worker runtime: ${t} -> ${r}`);try{return await Be(a,{recursive:!0,mode:448}),await xs(t,a),await Ms(J(a,rn),s,{mode:384}),await ua(a,r,s),r}catch(u){throw await Ct(a,{recursive:!0,force:!0}).catch(()=>{}),u}}async function ia(t,e){let n=Gi("sha256");n.update("qoder-worker-runtime-v1\0");let s=await qs(J(t,"runtime-info.json"));if(s)n.update(s);else{n.update(e);let o=await Zi(e).catch(()=>null);o&&n.update(`${o.size}\0${o.mtimeMs}`)}return`runtime-${n.digest("hex").slice(0,24)}`}async function xs(t,e){let n=await Vi(t,{withFileTypes:!0});await Be(e,{recursive:!0,mode:448});for(let s of n){let o=J(t,s.name),r=J(e,s.name);if(s.isDirectory()){await xs(o,r);continue}if(s.isSymbolicLink()){await Be(Te(r),{recursive:!0,mode:448}),await ea(await Yi(o),r);continue}if(!s.isFile())continue;let i=await aa(o);await Be(Te(r),{recursive:!0,mode:448}),await Ms(r,await Ts(o),{mode:i}),process.platform!=="win32"&&await Wi(r,i)}}async function aa(t){let e=((await Ji(t)).mode||420)&511;if(process.platform==="win32")return e||420;let n=As(t);return n==="rg"||n==="spawn-helper"||/\.(?:node|dylib|exe)$/.test(n)||/\.so(?:\.\d+)*$/.test(n)?493:e||420}async function ua(t,e,n){try{await Xi(t,e)}catch(s){if(await Os(J(e,rn))===n){await Ct(t,{recursive:!0,force:!0});return}throw s}}async function Os(t){let e=await qs(t);return e?e.toString("utf8"):null}async function qs(t){try{return await Ts(t)}catch{return null}}function ca(){let t=la(na().username||process.env.USER||process.env.USERNAME||"user");return J(ta(),`qoder-sdk-worker-runtime-${t}`)}function la(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_")||"unknown"}var ma=pa(import.meta.url),cn=da(ma);function de(t){if(t)return t;let e=[];for(let n of fa())e.push(le(n,"dist","_worker","qoder-worker-runtime.obf.mjs"),le(n,"dist","_worker","qoder-worker-runtime.mjs"),le(n,"_worker","qoder-worker-runtime.obf.mjs"),le(n,"_worker","qoder-worker-runtime.mjs"));for(let n of e)if(un(n))return n;return e[0]??le(cn,"..","_worker","qoder-worker-runtime.obf.mjs")}function $e(t){let e=de(t);if(un(e))return!0;let n=an(e);return n!==null&&un(n)}function fa(){let t=[le(cn,".."),le(cn,"..","..")];return[...new Set(t)]}import{appendFileSync as ga,mkdirSync as ha}from"fs";import{dirname as ya}from"path";import{randomUUID as Sa}from"node:crypto";var va="QODER_AGENT_SDK_DEBUG";function wa(t){return t.debugFile?!0:t.debug===!0||_a(process.env[va])}function ba(t){if(t.debugFile)return t.debugFile}function _a(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"&&e!=="no"&&e!=="off"}var ee=class{correlationId=Sa();onCloseDiagnostic;enabled;debugFile;stderr;constructor(e={}){this.onCloseDiagnostic=e.onCloseDiagnostic,this.enabled=wa(e),this.debugFile=ba(e),this.stderr=e.stderr}record(e,n){if(!this.enabled)return;let s=this.formatLine(e,n),o=this.debugFile;if(o){this.writeToFile(o,s);return}this.writeToStderr(s)}recordClose(e){let n=Object.freeze({...e,correlationId:this.correlationId});this.record(`[SDK close] ${JSON.stringify(n)}`),queueMicrotask(()=>{try{Promise.resolve(this.onCloseDiagnostic?.(n)).catch(()=>{})}catch{}})}get filePath(){return this.debugFile}writeToFile(e,n){try{ha(ya(e),{recursive:!0}),ga(e,n,"utf8")}catch{}}writeToStderr(e){try{this.stderr?this.stderr(e):process.stderr.write(e)}catch{}}formatLine(e,n){let s=new Date().toISOString(),o=this.formatError(n);return`${s} ${e}${o}
|
|
3
3
|
`}formatError(e){if(e===void 0)return"";if(e instanceof Error)return`
|
|
4
|
-
${e.stack??e.message}`;try{return` ${JSON.stringify(e)}`}catch{return` ${String(e)}`}}};import{StringDecoder as
|
|
4
|
+
${e.stack??e.message}`;try{return` ${JSON.stringify(e)}`}catch{return` ${String(e)}`}}};import{StringDecoder as ka}from"node:string_decoder";var Ns="\u2028",js="\u2029";function Fs(t){return!t.includes(Ns)&&!t.includes(js)?t:t.replaceAll(Ns,"\\u2028").replaceAll(js,"\\u2029")}async function*Us(t){let e=new ka("utf8"),n="";for await(let s of t){n+=typeof s=="string"?s:e.write(s);let o=n.indexOf(`
|
|
5
5
|
`);for(;o!==-1;){let r=n.slice(0,o);r.endsWith("\r")&&(r=r.slice(0,-1)),n=n.slice(o+1),yield r,o=n.indexOf(`
|
|
6
|
-
`)}}n+=e.end(),n.length!==0&&(n.endsWith("\r")&&(n=n.slice(0,-1)),yield n)}var
|
|
7
|
-
`)||e.includes("\r"))throw new h("daemon protocol frame must not contain raw line breaks");return mn(e),e}function Ls(t,e){let n=e.response.response;switch(t){case"initialize":{M(e,"initialize response");let s=k(n,"initialize response");if(R(s,["daemon_protocol_version","daemon_version","capabilities"],"initialize response"),s.daemon_protocol_version!==Ge)throw new h(`unsupported daemon_protocol_version: ${String(s.daemon_protocol_version)}`);return P(s,"daemon_version"),Ta(s,"capabilities"),s}case"open_session":{let s=dn(e,"open_session response");return ln(n,"open_session"),{session_id:s}}case"list_sessions":{M(e,"list_sessions response");let s=k(n,"list_sessions response");R(s,["sessions"],"list_sessions response");let o=s.sessions;if(!Array.isArray(o))throw new h("sessions must be an array");for(let[r,i]of o.entries())Us(k(i,`sessions[${r}]`),`sessions[${r}]`);return s}case"rename_session":{dn(e,"rename_session response");let s=k(n,"rename_session response");return R(s,["session"],"rename_session response"),Us(k(s.session,"rename_session session"),"rename_session session"),s}case"close_session":return dn(e,`${t} response`),ln(n,t),null;case"delete_session":case"shutdown":case"update_byok_config":case"delete_byok_config":return M(e,`${t} response`),ln(n,t),null;case"authenticate":{M(e,`${t} response`);let s=k(n,"authenticate response");if(R(s,["authenticated"],"authenticate response"),typeof s.authenticated!="boolean")throw new h("authenticated must be a boolean");return s}case"get_models":return M(e,`${t} response`),Qe(n,t,"models");case"get_byok_config":return M(e,`${t} response`),Qe(n,t,"providers");case"list_byok_configs":return M(e,`${t} response`),Qe(n,t,"configs");case"list_plugins":return M(e,`${t} response`),Qe(n,t,"plugins");case"validate_plugins":return M(e,`${t} response`),Qe(n,t,"reports");case"setproxy":{M(e,`${t} response`);let s=k(n,`${t} response`);if(R(s,["proxy","no_proxy"],`${t} response`),s.proxy!==null&&typeof s.proxy!="string")throw new h(`${t} response proxy must be a string or null`);let o=s.no_proxy;if(o!=null&&typeof o!="string")throw new h(`${t} response no_proxy must be a string or null`);return s}case"validate_byok_model":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["success"],`${t} response`),pn(s,"success"),s}case"create_byok_config":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["config"],`${t} response`),k(s.config,`${t} response config`),s}case"account_info":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["account"],`${t} response`),k(s.account,`${t} response account`),s}case"check_byok_config":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["success","error","code","requestId","details"],`${t} response`),pn(s,"success"),Fs(s,["error","code","requestId"]),s.details!==void 0&&k(s.details,`${t} response details`),s}case"get_usage_info":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["usage","session","usage_error"],`${t} response`),s.usage!==null&&k(s.usage,`${t} response usage`),k(s.session,`${t} response session`),Fs(s,["usage_error"]),s}default:throw new h(`unknown daemon command result method: ${String(t)}`)}}function _a(t){if(R(t,["type","status","data"],"status_event frame"),t.status!=="daemon.session_updated")throw new h("unsupported status_event status");let e=k(t.data,"status_event data");if(R(e,["local_session_id","state","error"],"status_event data"),P(e,"local_session_id"),e.state!=="failed")throw new h("status_event state must be failed");k(e.error,"status_event error")}function ka(t){if(R(t,["type","code","message","malformed_lines","malformed_bytes","last_frame_type","last_frame_session_id"],"protocol_error frame"),P(t,"code"),t.message!==void 0&&typeof t.message!="string")throw new h("message must be a string");for(let e of["malformed_lines","malformed_bytes"]){let n=t[e];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`${e} must be a non-negative safe integer`)}for(let e of["last_frame_type","last_frame_session_id"])t[e]!==void 0&&P(t,e)}function Ca(t){R(t,["type","request_id","session_id","request"],"control_request frame"),P(t,"request_id"),fn(t);let e=k(t.request,"control request");if(!(typeof e.type=="string"&&e.type.length>0)&&!(typeof e.subtype=="string"&&e.subtype.length>0))throw new h("control request must have a non-empty string type or subtype")}function Ra(t){R(t,["type","session_id","response"],"control_response frame"),fn(t);let e=k(t.response,"control response");P(e,"request_id");let n=P(e,"subtype");if(n==="success"){if(["error","code","retryable","details"].some(s=>Object.hasOwn(e,s)))throw new h("success control response must not include error fields");R(e,["subtype","request_id","response"],"success control response"),e.response!==void 0&&k(e.response,"success response result");return}if(n!=="error")throw new h(`unknown control response subtype: ${n}`);if(Object.hasOwn(e,"response"))throw new h("error control response must not include response");if(R(e,["subtype","request_id","error","code","retryable","details","pending_permission_requests"],"error control response"),P(e,"error"),e.code!==void 0&&P(e,"code"),e.retryable!==void 0&&pn(e,"retryable"),e.details!==void 0&&k(e.details,"control response details"),e.pending_permission_requests!==void 0&&!Array.isArray(e.pending_permission_requests))throw new h("pending_permission_requests must be an array")}function Fs(t,e){for(let n of e)t[n]!==void 0&&P(t,n)}function Qe(t,e,n){let s=k(t,`${e} response`);if(R(s,[n],`${e} response`),!Array.isArray(s[n]))throw new h(`${e} response ${n} must be an array`);return s}function Us(t,e){R(t,["local_session_id","title","cwd","state","created_at","updated_at"],e),P(t,"local_session_id"),t.cwd!==void 0&&P(t,"cwd"),P(t,"title");let n=P(t,"state");if(!["pending","ready","inactive","failed"].includes(n))throw new h(`${e} has invalid state: ${n}`);P(t,"created_at"),P(t,"updated_at")}function ln(t,e){if(t!==void 0)throw new h(`${e} success must omit response`)}function dn(t,e){let n=t;try{return P(n,"session_id")}catch{throw new h(`${e} requires a valid session_id`)}}function M(t,e){if(Object.hasOwn(t,"session_id"))throw new h(`${e} must not include session_id`)}function fn(t){let e=t;e.session_id!==void 0&&P(e,"session_id")}function Pa(t){for(let e of["session_epoch","sequence"])if(Object.hasOwn(t,e))throw new h(`${e} is reserved for daemon-internal Session ordering`)}function Ea(t){return typeof t=="string"&&["user","assistant","stream_event","tool_progress","result","system","prompt_suggestion","command_lifecycle","control_cancel_request","control_cancel","transcript_mirror"].includes(t)}function k(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new h(`${e} must be a JSON object`);return t}function P(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new h(`${e} must be a non-empty string`);return n}function pn(t,e){let n=t[e];if(typeof n!="boolean")throw new h(`${e} must be a boolean`);return n}function Ta(t,e){let n=t[e];if(!Array.isArray(n)||n.some(s=>typeof s!="string"))throw new h(`${e} must be an array of strings`);return n}function R(t,e,n){let s=new Set(e),o=Object.keys(t).find(r=>!s.has(r));if(o!==void 0)throw new h(`${n} contains unknown field: ${o}`)}var ee=class{queue=[];readResolve;readReject;isDone=!1;errorValue;started=!1;returnCallback;constructor(e){this.returnCallback=e}[Symbol.asyncIterator](){if(this.started)throw new Error("Stream can only be iterated once");return this.started=!0,this}async next(){if(this.queue.length>0)return{done:!1,value:this.queue.shift()};if(this.isDone)return{done:!0,value:void 0};if(this.errorValue!==void 0)throw this.errorValue;return new Promise((e,n)=>{this.readResolve=e,this.readReject=n})}enqueue(e){if(!this.isDone)if(this.readResolve){let n=this.readResolve;this.readResolve=void 0,this.readReject=void 0,n({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.errorValue=e,this.readReject){let n=this.readReject;this.readResolve=void 0,this.readReject=void 0,n(e)}}async return(){return this.isDone=!0,this.returnCallback?.(),{done:!0,value:void 0}}async throw(e){return this.error(e),{done:!0,value:void 0}}};var Ct=class{constructor(e,n){this.connection=e;this.options=n}messages=new ee;pendingMessages=[];initializePromise;sessionId;flushingPendingMessages=!1;inputEnded=!1;resultReceived=!1;commandLifecycleSupported=!1;pendingCommandUuids=new Set;closed=!1;cleaned=!1;releasePromise;closePromise;initialize(){return this.initializePromise||(this.initializePromise=this.open(),this.initializePromise.catch(()=>{})),this.initializePromise}write(e){if(this.closed)throw new Error("Transport is not ready or has been closed");let n=Ma(e);if(this.trackOutboundCommand(n),!this.sessionId||this.flushingPendingMessages){if(!this.initializePromise)throw new Error("Transport is not ready or has been closed");this.pendingMessages.push(n);return}let s;try{s=Bs(n,this.sessionId)}catch(o){this.failAndRelease(o);return}this.connection.sendSessionMessage(s).catch(o=>this.failAndRelease(o))}async*readMessages(){await this.initialize();for await(let e of this.messages)yield e}endInput(){this.closed||(this.inputEnded=!0,this.maybeCloseAfterResult())}close(){return this.closePromise||(this.closePromise=this.performClose(),this.closePromise.catch(()=>{})),this.closePromise}isReady(){return this.sessionId!==void 0&&!this.closed}acceptOutput(e){this.closed||(this.observeCapabilities(e),this.messages.enqueue(e),this.observeCommandLifecycle(e),e.type==="result"&&(this.resultReceived=!0),this.maybeCloseAfterResult())}fail(e){this.closed||(this.closed=!0,this.cleanup(),this.messages.error(e instanceof Error?e:new Error(String(e))))}async open(){let e,n=!1,s=this.options.claim;try{s&&(await s.ready,n=!0);let o=await this.connection.openSession({worker_args:[...this.options.workerArgs],...this.options.cwd!==void 0?{cwd:this.options.cwd}:{},...this.options.configDir!==void 0?{config_dir:this.options.configDir}:{}},this);if(s&&s.sessionId!==o&&(this.connection.releaseSessionClaim(s.sessionId),n=!1),this.sessionId=o,e=o,this.record(`session opened cwd=${this.options.cwd??"(inherit)"} workerArgs=${this.options.workerArgs.length}`),this.closed){await this.releaseSessionOnce(o);return}this.flushingPendingMessages=!0;try{for(;this.pendingMessages.length>0;){let r=this.pendingMessages.map(i=>Bs(i,o));this.pendingMessages.splice(0);for(let i of r)await this.connection.sendSessionMessage(i)}}finally{this.flushingPendingMessages=!1}}catch(o){throw e!==void 0?this.startRelease(e):n&&s&&this.connection.releaseSessionClaim(s.sessionId),this.fail(o),o}}failAndRelease(e){let n=this.sessionId;this.record("session failed, releasing",e),n!==void 0&&this.startRelease(n),this.fail(e)}record(e,n){let s=this.sessionId;this.options.diagnostics?.record(`[DaemonSession]${s!==void 0?` sessionId=${s}`:""} ${e}`,n)}startRelease(e){this.releaseSessionOnce(e).catch(()=>{})}releaseSessionOnce(e){return this.releasePromise||(this.releasePromise=this.releaseSession(e)),this.releasePromise}releaseSession(e){return this.connection.closeSession(e)}trackOutboundCommand(e){if(!this.commandLifecycleSupported||e.type!=="user")return;let n=e.uuid;typeof n=="string"&&n.trim().length>0&&this.pendingCommandUuids.add(n)}observeCapabilities(e){e.type!=="system"||e.subtype!=="init"||this.updateCommandLifecycleCapability(e)}updateCommandLifecycleCapability(e){let n=e.capabilities;this.commandLifecycleSupported=Array.isArray(n)&&n.includes("msg_lifecycle_v1")}observeCommandLifecycle(e){if(e.type!=="command_lifecycle"||e.state!=="completed"&&e.state!=="cancelled"&&e.state!=="discarded")return;let n=e.command_uuid;typeof n=="string"&&this.pendingCommandUuids.delete(n)}maybeCloseAfterResult(){!this.inputEnded||!this.resultReceived||this.commandLifecycleSupported&&this.pendingCommandUuids.size>0||this.close().catch(()=>{})}async performClose(){this.initializePromise&&await this.initializePromise.catch(()=>{});try{this.releasePromise?await this.releasePromise:this.sessionId&&await this.releaseSessionOnce(this.sessionId)}catch(e){throw this.record("close handshake failed",e),this.markClosed(),this.messages.error(e),e}this.record("closed"),this.markClosed(),this.messages.done()}markClosed(){this.closed||(this.closed=!0,this.cleanup())}cleanup(){this.cleaned||(this.cleaned=!0,this.options.cleanup?.())}};function Ma(t){let e;try{e=JSON.parse(t.trim())}catch{throw new Error("Query transport input must contain valid JSON")}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Query transport input must be a JSON object");return e}function Bs(t,e){if(Object.hasOwn(t,"session_id")&&t.session_id!==e)throw new Error(`Query message session_id must match daemon Session: expected ${e}, received ${String(t.session_id)}`);return{...t,session_id:e}}import{Transform as Aa}from"node:stream";var Pt=64*1024*1024,Rt=class extends Aa{constructor(n=Pt,s="SDK output"){super();this.maxLineBytes=n;this.source=s;if(!Number.isSafeInteger(n)||n<=0)throw new Error("maxLineBytes must be a positive safe integer")}bytesSinceNewline=0;_transform(n,s,o){let r=Buffer.isBuffer(n)?n:Buffer.from(n,s),i=0;for(let a=0;a<r.length;a+=1)if(r[a]===10){if(this.bytesSinceNewline+=a-i,this.bytesSinceNewline>this.maxLineBytes){o(new G("output",this.maxLineBytes,this.bytesSinceNewline,this.source));return}this.bytesSinceNewline=0,i=a+1}if(this.bytesSinceNewline+=r.length-i,this.bytesSinceNewline>this.maxLineBytes){o(new G("output",this.maxLineBytes,this.bytesSinceNewline,this.source));return}o(void 0,r)}};function $s(t,e=Pt,n="SDK input",s){let o=t.endsWith(`
|
|
8
|
-
`)?t.slice(0,-1):t,r=Buffer.byteLength(o,"utf8");if(r>e)throw new G("input",e,r,n,s)}var gn="multi_session_v2",Qs="session_title_sync_v1",Gs="session_delete_v1";var Ia=12e4,Ws=12e4,yn="daemon_keep_alive_v1",Mt="daemon_async_session_teardown_v1",Da=5e3,hn=3e4,xa=125e3,Oa=12e4,qa=12e4,Na=5e3,ja=6e4,Fa=15e4,Ua=12e4,Ka=1024,La=64,Ba=8*1024*1024,$a=256,Qa=32*1024*1024,Ga=new Set(["daemon.auth.fetch_job_token","daemon.auth.fetch_service_account_token"]),Et=class extends Error{code;retryable;details;constructor(e){super(e.message),this.name="DaemonRpcError",this.code=e.code,this.retryable=e.retryable,this.details=e.details}},me=class extends Error{code;retryable;details;constructor(e){super(e.message),this.name="DaemonRequestError",this.code=e.code,this.retryable=e.retryable,this.details=e.details}},He=class extends Error{constructor(n,s){super(`session ${n} is already open (state=${s})`);this.sessionId=n;this.state=s;this.name="DaemonSessionAlreadyOpenError"}code="SESSION_ALREADY_OPEN"},Ie=class extends Error{code="DAEMON_HEARTBEAT_TIMEOUT";elapsedMs;partialFrame;constructor(e,n=!1){super(`DAEMON_HEARTBEAT_TIMEOUT Qoder CLI daemon stopped responding (no inbound data for ${e}ms${n?"; partial frame in progress":""})`),this.name="DaemonHeartbeatTimeoutError",this.elapsedMs=e,this.partialFrame=n}},Tt=class{input;requestHandler;pendingRequests=new Map;timedOutRequestIds=new Set;activeInboundRequestIds=new Set;sessions=new Map;sessionSlots=new Map;closedSessionIds=new Set;sessionCwds=new Map;pendingSessionMessages=new Map;pendingSessionMessageBytes=new Map;pendingSessionMessageFrameCount=0;pendingSessionMessageByteCount=0;maxFrameBytes;readTask;writeChain=Promise.resolve();nextRequestId=1;initializing=!1;initialized=!1;capabilities=new Set;stopping=!1;failure;failureListeners=new Set;describeUnexpectedClose;diagnostics;lastInboundAt=performance.now();inboundFrameInProgress=!1;heartbeatWatchdog;heartbeatTimeoutMs;constructor(e){if(this.input=e.input,this.requestHandler=e.requestHandler,this.describeUnexpectedClose=e.describeUnexpectedClose,this.diagnostics=e.diagnostics,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??Ws,this.maxFrameBytes=e.maxFrameBytes??Pt,!Number.isSafeInteger(this.maxFrameBytes)||this.maxFrameBytes<=0)throw new TypeError("maxFrameBytes must be a positive safe integer");this.readTask=this.readOutput(e.output)}async initialize(e,n={}){if(this.initialized)throw new h("daemon connection is already initialized");if(this.initializing)throw new h("daemon initialize is already in progress");this.initializing=!0;let s,o=n.timeoutMs??Ia,r=this.request("initialize",{daemon_protocol_version:Ge,sdk_version:e,capabilities:[gn,...n.capabilities??[]],...n.auth?{auth:n.auth}:{},...n.proxy===void 0?{}:{proxy:n.proxy},...n.noProxy===void 0?{}:{no_proxy:n.noProxy}}),i=new Promise((u,c)=>{s=setTimeout(()=>{let d=new Error(`Qoder CLI daemon did not initialize within ${o}ms`);this.fail(d),c(d)},o)}),a;try{a=await Promise.race([r,i])}finally{this.initializing=!1,s&&clearTimeout(s)}if(!a.capabilities.includes(gn))throw new h(`daemon is missing required capability: ${gn}`);for(let u of a.capabilities)this.capabilities.add(u);this.initialized=!0,this.capabilities.has(yn)?this.armHeartbeatWatchdog():this.diagnostics?.record("[DaemonConnection] heartbeat not negotiated; watchdog disarmed")}createSessionTransport(e){if(!this.initialized||this.stopping||this.failure)throw this.failure??new Error("Daemon connection is not ready");return new Ct(this,{...e,diagnostics:this.diagnostics})}supportsCapability(e){return this.capabilities.has(e)}async setProxy(e,n){return(await this.setProxySettings(e,n)).proxy}async setProxySettings(e,n){if(!this.capabilities.has(de))throw new h(`daemon is missing required capability: ${de}`);if(n!==void 0&&!this.capabilities.has(pe))throw new h(`daemon is missing required capability: ${pe}`);let s=await this.request("setproxy",{proxy:e||null,...n===void 0?{}:{no_proxy:n}},void 0,void 0,hn,"request");return{proxy:s.proxy,noProxy:Object.hasOwn(s,"no_proxy")?s.no_proxy??null:n===void 0?null:n}}claimSessionId(e){let n=this.sessionSlots.get(e);if(!n)return this.sessionSlots.set(e,{state:"opening",waiters:[]}),{sessionId:e,ready:Promise.resolve()};if(n.state==="closing"){let s=new Promise((o,r)=>{n.waiters.push({resolve:o,reject:r})});return{sessionId:e,ready:s}}throw new He(e,n.state)}markSessionOpen(e){let n=this.sessionSlots.get(e);n?n.state="open":this.sessionSlots.set(e,{state:"open",waiters:[]})}markSessionClosing(e){let n=this.sessionSlots.get(e);n?n.state="closing":this.sessionSlots.set(e,{state:"closing",waiters:[]})}releaseSessionClaim(e){let n=this.sessionSlots.get(e);!n||n.state!=="opening"||this.advanceSessionSlot(e,n)}completeSessionClose(e){let n=this.sessionSlots.get(e);!n||n.state!=="closing"||this.advanceSessionSlot(e,n)}advanceSessionSlot(e,n){let s=n.waiters.shift();if(!s){this.sessionSlots.delete(e);return}n.state="opening",s.resolve();for(let o of n.waiters.splice(0))o.reject(new He(e,"opening"))}validatePlugins(e,n){return this.capabilities.has(Ae)?this.request("validate_plugins",{paths:[...e],...n===void 0?{}:{config_dir:n}},void 0,void 0,Fa,"request").then(s=>s.reports):Promise.reject(new h(`daemon is missing required capability: ${Ae}`))}setRequestHandler(e){this.requestHandler=e}onFailure(e){return this.failureListeners.add(e),this.failure&&e(this.failure),()=>this.failureListeners.delete(e)}async openSession(e,n){let s=await this.request("open_session",e,n,void 0,Oa);return e.cwd!==void 0&&this.sessionCwds.set(s.session_id,e.cwd),s.session_id}async listSessions(e){return(await this.request("list_sessions",e===void 0?{}:{cwd:e},void 0,void 0,xa,"request")).sessions}renameSession(e,n,s){if(!this.capabilities.has(Qs))return Promise.reject(new h(`daemon is missing required capability: ${Qs}`));let o=s??this.sessionCwds.get(e);return this.request("rename_session",o===void 0?{title:n}:{title:n,cwd:o},void 0,e,hn)}sendSessionMessage(e){return this.writeFrame(e)}async closeSession(e){this.markSessionClosing(e);try{await this.request("close_session",{},void 0,e,qa,"request")}finally{this.sessions.delete(e),this.closedSessionIds.add(e),this.completeSessionClose(e)}}async deleteSession(e,n){if(!this.capabilities.has(Gs))throw new h(`daemon is missing required capability: ${Gs}`);let s=n??this.sessionCwds.get(e);await this.request("delete_session",s===void 0?{local_session_id:e}:{local_session_id:e,cwd:s},void 0,void 0,hn)}query(e,n){return this.capabilities.has(ze)?this.request(e,n,void 0,void 0,ja,"request"):Promise.reject(new h(`daemon is missing required capability: ${ze}`))}authenticate(e){return this.capabilities.has(ze)?this.request("authenticate",e===void 0?{}:{auth:e},void 0,void 0,Ua,"request"):Promise.reject(new h(`daemon is missing required capability: ${ze}`))}async shutdown(e=Na){if(this.stopping){await this.readTask.catch(()=>{});return}this.stopping=!0,this.disarmHeartbeatWatchdog();try{this.failure||await this.request("shutdown",{},void 0,void 0,e,"connection")}finally{let n=new Error("Daemon is stopping");for(let s of this.sessions.values())s.fail(n);this.sessions.clear();for(let s of this.sessionSlots.values())for(let o of s.waiters.splice(0))o.reject(n);this.sessionSlots.clear(),!this.input.destroyed&&!this.input.writableEnded&&this.input.end()}}async resolveUnexpectedClose(){if(!this.describeUnexpectedClose)return new Error("Daemon connection closed");try{return await this.describeUnexpectedClose()??new Error("Daemon connection closed")}catch{return new Error("Daemon connection closed")}}fail(e,n=!0){let s=e instanceof Error?e:new Error(String(e));if(!this.failure){this.failure=s,this.disarmHeartbeatWatchdog(),this.diagnostics?.record(`[DaemonConnection] connection failed pendingRequests=${this.pendingRequests.size} sessions=${this.sessions.size}`,s);for(let o of this.pendingRequests.values())o.timeout&&clearTimeout(o.timeout),o.reject(s);this.pendingRequests.clear(),this.timedOutRequestIds.clear(),this.clearPendingSessionMessages();for(let o of this.sessions.values())o.fail(s);this.sessions.clear();for(let o of this.sessionSlots.values())for(let r of o.waiters.splice(0))r.reject(s);if(this.sessionSlots.clear(),n)for(let o of this.failureListeners)try{o(s)}catch{}}}armHeartbeatWatchdog(){if(this.heartbeatTimeoutMs<=0)return;this.lastInboundAt=performance.now();let e=Math.min(Da,Math.max(25,Math.floor(this.heartbeatTimeoutMs/2)));this.heartbeatWatchdog=setInterval(()=>{if(this.failure||this.stopping||!this.initialized)return;let n=Math.round(performance.now()-this.lastInboundAt);n<=this.heartbeatTimeoutMs||(this.diagnostics?.record(`[DaemonConnection] heartbeat timeout elapsed=${n}ms pendingRequests=${this.pendingRequests.size} sessions=${this.sessions.size} partialFrame=${this.inboundFrameInProgress}`),this.fail(new Ie(n,this.inboundFrameInProgress)))},e),this.heartbeatWatchdog.unref()}disarmHeartbeatWatchdog(){this.heartbeatWatchdog!==void 0&&(clearInterval(this.heartbeatWatchdog),this.heartbeatWatchdog=void 0)}request(e,n,s,o,r,i="request"){if(this.failure)return Promise.reject(this.failure);if(e!=="initialize"&&!this.initialized)return Promise.reject(new h("daemon connection is not initialized"));let a=`sdk_daemon_${this.nextRequestId++}`,u={type:"control_request",request_id:a,...o!==void 0?{session_id:o}:{},request:{type:`daemon.${e}`,...n}};return new Promise((c,d)=>{let m={method:e,resolve:p=>c(p),reject:d,...s?{sessionTransport:s}:{},...o!==void 0?{sessionId:o}:{}};r!==void 0&&(m.timeout=setTimeout(()=>{if(this.pendingRequests.get(a)!==m)return;let p=new h(`daemon ${e} request timed out after ${r}ms`);if(this.diagnostics?.record(`[DaemonConnection] request timeout method=${e} requestId=${a}${o!==void 0?` sessionId=${o}`:""} timeoutMs=${r} scope=${i}`),i==="request"){this.pendingRequests.delete(a),this.rememberTimedOutRequestId(a),m.reject(p);return}this.fail(p)},r),m.timeout.unref?.()),this.pendingRequests.set(a,m),this.diagnostics?.record(`[DaemonConnection] request sent method=${e} requestId=${a}${o!==void 0?` sessionId=${o}`:""}${r!==void 0?` timeoutMs=${r}`:""}`),this.writeFrame(u).catch(p=>{let l=this.pendingRequests.get(a);l?.timeout&&clearTimeout(l.timeout),this.pendingRequests.delete(a),this.diagnostics?.record(`[DaemonConnection] request write failed method=${e} requestId=${a}`,p),d(p),l?.sessionTransport&&this.failIfSessionMessagesAreOrphaned()})})}async readOutput(e){let n=new Rt(this.maxFrameBytes,"SDK daemon output"),s=o=>{this.lastInboundAt=performance.now();let r=o.length===0?void 0:typeof o=="string"?o.charCodeAt(o.length-1):o[o.length-1];this.inboundFrameInProgress=r!==void 0&&r!==10};e.on("data",s),e.pipe(n);try{for await(let o of js(n)){if(!o.trim())continue;let r=za(o);r!==void 0&&this.rejectLegacyInitialize(r)||this.acceptFrame(mn(o))}(!this.stopping||this.pendingRequests.size>0)&&this.fail(await this.resolveUnexpectedClose(),!1)}catch(o){this.fail(o)}finally{e.off("data",s),e.unpipe(n),n.destroy()}}acceptFrame(e){let n=e;if(n.type!=="keep_alive"){if(n.type==="protocol_error"){let s=e,o=[`code=${s.code}`,...s.malformed_lines===void 0?[]:[`malformed_lines=${s.malformed_lines}`],...s.malformed_bytes===void 0?[]:[`malformed_bytes=${s.malformed_bytes}`],...s.last_frame_type===void 0?[]:[`last_frame_type=${s.last_frame_type}`],...s.last_frame_session_id===void 0?[]:[`last_frame_session_id=${s.last_frame_session_id}`]].join(" ");this.fail(new h(`daemon reported a fatal protocol error: ${o}`+(s.message===void 0?"":`: ${s.message}`)));return}if(n.type==="control_response"){let s=e,o=s.response.request_id;if(this.pendingRequests.has(o)){this.acceptControlResponse(s);return}if(this.timedOutRequestIds.delete(o)){this.abandonSessionFromLateResponse(s);return}this.routeSessionMessage(n);return}if(n.type==="control_request"){let s=e,o=Ha(s);if(o==="valid"){this.acceptRequest(s);return}if(o==="contradictory")throw new h(`contradictory daemon reverse RPC routing markers: ${s.request_id}`)}if(n.type==="status_event"){this.acceptSessionUpdatedStatusEvent(e);return}this.routeSessionMessage(n)}}rememberTimedOutRequestId(e){if(this.timedOutRequestIds.size>=Ka){let n=this.timedOutRequestIds.values().next().value;n!==void 0&&this.timedOutRequestIds.delete(n)}this.timedOutRequestIds.add(e)}abandonSessionFromLateResponse(e){let n=e.session_id;typeof n!="string"||n.length===0||this.sessions.has(n)||(this.closedSessionIds.add(n),this.deletePendingSessionMessages(n))}routeSessionMessage(e){let n=e.session_id;if(typeof n!="string"||n.length===0)throw new h(`daemon Session message requires a valid session_id: ${String(n)}`);let s=this.sessions.get(n);if(s){s.acceptOutput(e);return}if(this.hasPendingSessionRequest()){this.bufferPendingSessionMessage(n,e);return}if(!this.closedSessionIds.has(n))throw new h(`daemon output has unknown session_id: ${n}`)}acceptControlResponse(e){let n=e.response.request_id,s=this.pendingRequests.get(n);if(!s)throw new h(`daemon response has unknown request_id: ${n}`);if(s.timeout&&clearTimeout(s.timeout),s.sessionId!==void 0&&e.session_id!==s.sessionId){this.pendingRequests.delete(n),s.reject(new h(`${s.method} response session_id does not match request: expected ${s.sessionId}, received ${String(e.session_id)}`));return}if(this.pendingRequests.delete(n),e.response.subtype==="error"){if(s.method==="initialize"&&e.response.code==="PROTOCOL_VERSION_UNSUPPORTED"){s.reject(new V("1","2"));return}s.reject(new Et({code:e.response.code??"DAEMON_REQUEST_FAILED",message:e.response.error,retryable:e.response.retryable??!1,...e.response.details===void 0?{}:{details:e.response.details}})),s.sessionTransport&&this.failIfSessionMessagesAreOrphaned();return}try{let o=e,r=o.response.response?.daemon_protocol_version;if(s.method==="initialize"&&typeof r=="number"&&r!==Ge)throw new V(String(r),String(Ge));let i=Ls(s.method,o);if(s.sessionTransport){let a=i.session_id;if(typeof a!="string"||a.length===0)throw new h(`${s.method} did not return a valid session_id`);let u=this.takePendingSessionMessages(a);this.closedSessionIds.delete(a);let c=this.failIfSessionMessagesAreOrphaned(`${s.method} response session_id does not match buffered output`);if(c)throw c;if(this.sessions.has(a)){let d=new h(`daemon returned duplicate session_id: ${a}`);this.diagnostics?.record(`[DaemonConnection] rejecting duplicate open session_id=${a}`),s.reject(d);return}this.sessions.set(a,s.sessionTransport),this.markSessionOpen(a);for(let d of u)s.sessionTransport.acceptOutput(d)}s.resolve(i)}catch(o){s.reject(o instanceof Error?o:new Error(String(o))),s.sessionTransport&&this.failIfSessionMessagesAreOrphaned()}}hasPendingSessionRequest(){return[...this.pendingRequests.values()].some(e=>e.sessionTransport!==void 0)}failIfSessionMessagesAreOrphaned(e="daemon left orphaned pre-response Session output"){if(this.hasPendingSessionRequest())return;for(let o of this.pendingSessionMessages.keys())this.closedSessionIds.has(o)&&this.deletePendingSessionMessages(o);if(this.pendingSessionMessages.size===0)return;let n=[...this.pendingSessionMessages.keys()].join(", "),s=new h(`${e}: ${n}`);return this.clearPendingSessionMessages(),this.fail(s),s}bufferPendingSessionMessage(e,n){let s=this.pendingSessionMessages.get(e)??[],o=Buffer.byteLength(JSON.stringify(n),"utf8"),r=this.pendingSessionMessageBytes.get(e)??0;if(s.length+1>La||r+o>Ba||this.pendingSessionMessageFrameCount+1>$a||this.pendingSessionMessageByteCount+o>Qa)throw new h("daemon pre-response Session output exceeded its bounded buffer");s.push(n),this.pendingSessionMessages.set(e,s),this.pendingSessionMessageBytes.set(e,r+o),this.pendingSessionMessageFrameCount+=1,this.pendingSessionMessageByteCount+=o}takePendingSessionMessages(e){let n=this.pendingSessionMessages.get(e)??[];return this.deletePendingSessionMessages(e),n}deletePendingSessionMessages(e){let n=this.pendingSessionMessages.get(e)?.length??0,s=this.pendingSessionMessageBytes.get(e)??0;this.pendingSessionMessages.delete(e),this.pendingSessionMessageBytes.delete(e),this.pendingSessionMessageFrameCount-=n,this.pendingSessionMessageByteCount-=s}clearPendingSessionMessages(){this.pendingSessionMessages.clear(),this.pendingSessionMessageBytes.clear(),this.pendingSessionMessageFrameCount=0,this.pendingSessionMessageByteCount=0}rejectLegacyInitialize(e){let n=this.pendingRequests.get(e);return n?.method!=="initialize"?!1:(this.pendingRequests.delete(e),n.reject(new V("1","2")),!0)}acceptRequest(e){if(this.activeInboundRequestIds.has(e.request_id)){this.writeInboundError(e.request_id,"DUPLICATE_REQUEST_ID",`daemon request_id is already active: ${e.request_id}`);return}if(!this.requestHandler){this.writeInboundError(e.request_id,"METHOD_NOT_FOUND",`SDK has no handler for daemon method: ${e.request.type}`);return}this.activeInboundRequestIds.add(e.request_id),Promise.resolve().then(()=>this.requestHandler(e)).then(n=>{let s={type:"control_response",response:{subtype:"success",request_id:e.request_id,...n===null?{}:{response:n}}};return this.writeFrame(s)}).catch(n=>{let s=n instanceof me?n:void 0,o={type:"control_response",response:{subtype:"error",request_id:e.request_id,code:s?.code??"SDK_REQUEST_FAILED",error:n instanceof Error?n.message:String(n),retryable:s?.retryable??!1,...s?.details?{details:s.details}:{}}};return this.writeFrame(o)}).catch(n=>this.fail(n)).finally(()=>{this.activeInboundRequestIds.delete(e.request_id)})}writeInboundError(e,n,s){let o={type:"control_response",response:{subtype:"error",request_id:e,code:n,error:s,retryable:!1}};this.writeFrame(o).catch(r=>this.fail(r))}acceptSessionUpdatedStatusEvent(e){let n=e.data.local_session_id,s=this.sessions.get(n);s&&(this.sessions.delete(n),this.closedSessionIds.add(n),s.fail(Wa(e.data)))}writeFrame(e){let n;try{n=`${Ks(e)}
|
|
9
|
-
`,$s(n,this.maxFrameBytes,"SDK daemon input",e.type==="user"&&"uuid"in e&&typeof e.uuid=="string"?e.uuid:void 0)}catch(o){let r=o instanceof Error?o:new Error(String(o));return this.fail(r),Promise.reject(r)}let s=this.writeChain.then(()=>new Promise((o,r)=>{this.input.write(n,"utf8",i=>{if(i){r(i);return}o()})}));return this.writeChain=s.catch(()=>{}),s.catch(o=>this.fail(o)),s}};function za(t){let e;try{e=JSON.parse(t)}catch{return}if(!zs(e)||!Hs(e,["protocol_version","frame_type","request_id","ok","error"])||e.protocol_version!==1||e.frame_type!=="response"||e.ok!==!1||typeof e.request_id!="string"||e.request_id.length===0)return;let n=e.error;if(!(!zs(n)||!Hs(n,["code","message","retryable"])||n.code!=="PROTOCOL_VERSION_UNSUPPORTED"||typeof n.message!="string"||n.message.length===0||n.retryable!==!1))return e.request_id}function zs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hs(t,e){return Object.keys(t).length===e.length&&e.every(n=>Object.hasOwn(t,n))}function Ha(t){let e=Ga.has(t.request.type),n=t.request_id.startsWith("daemon_sdk_");return e&&n&&t.session_id===void 0?"valid":e||n?"contradictory":"none"}function Wa(t){let e=t.error,n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},s=typeof n.message=="string"&&n.message.length>0?n.message:"Qoder CLI Worker exited before Session completed",o=n.exit_code===null||typeof n.exit_code=="number"?n.exit_code:void 0,r=n.signal===null||typeof n.signal=="string"?n.signal:void 0,i=typeof n.stderr=="string"&&n.stderr.length>0?n.stderr:void 0;return new K(s,{exitCode:o,signal:r,stderr:i})}var Ja=3e4;function Sn(t,e=Ja){return eu(e,"callbackTimeoutMs"),async n=>{switch(n.request.type){case"daemon.auth.fetch_job_token":return Va(t,n,e);case"daemon.auth.fetch_service_account_token":return Ya(t,n,e);default:throw O("METHOD_NOT_FOUND",`SDK has no handler for daemon method: ${n.request.type}`)}}}async function Va(t,e,n){if(t.type!=="jobToken")throw O("DAEMON_AUTH_CALLBACK_UNAVAILABLE","Host job token callback is not configured");let s=Js(e,["reason","session_id"]),o=Vs(s.reason),r=Xa(s.session_id,"session_id"),i=new AbortController;try{let a=await Ys(()=>t.fetchJobToken({requestId:e.request_id,reason:o,sessionId:r},{signal:i.signal}),n,i);if(!a||typeof a.token!="string"||!a.token)throw O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback did not provide a token");let u=a.expiresAt;if(u!==void 0&&(!Number.isFinite(u)||u<1e12))throw O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback returned invalid expiresAt");return{token:a.token,...u!==void 0?{expires_at:u}:{}}}catch(a){throw a instanceof me?a:O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback failed",!0)}}async function Ya(t,e,n){if(t.type!=="serviceAccount"||typeof t.fetchServiceAccountToken!="function")throw O("DAEMON_AUTH_CALLBACK_UNAVAILABLE","Host Service Account token callback is not configured");let s=Js(e,["reason","required_scopes"]);Vs(s.reason),Za(s.required_scopes,"required_scopes");let o=new AbortController;try{let r=await Ys(()=>t.fetchServiceAccountToken(),n,o);if(!r||typeof r.token!="string"||!r.token)throw O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback did not provide a token");let i=r.expiresAt;if(i!==void 0&&(!Number.isFinite(i)||i<1e12))throw O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback returned invalid expiresAt");return{token:r.token,...i!==void 0?{expires_at:i}:{}}}catch(r){throw r instanceof me?r:O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback failed",!0)}}function Js(t,e){let n=Object.keys(t.request).find(s=>s!=="type"&&!e.includes(s));if(n)throw O("DAEMON_AUTH_INVALID_REQUEST",`request contains unknown field: ${n}`);return t.request}function Vs(t){if(t!=="initial"&&t!=="unauthorized")throw O("DAEMON_AUTH_INVALID_REQUEST","reason must be initial or unauthorized");return t}function Xa(t,e){if(t!==void 0){if(typeof t!="string"||!t)throw O("DAEMON_AUTH_INVALID_REQUEST",`${e} must be a non-empty string`);return t}}function Za(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw O("DAEMON_AUTH_INVALID_REQUEST",`${e} must be an array of strings`);return t}async function Ys(t,e,n){let s;try{return await Promise.race([Promise.resolve().then(t),new Promise((o,r)=>{s=setTimeout(()=>{n.abort(),r(new Error("daemon auth callback timed out"))},e),s.unref?.()})])}finally{s&&clearTimeout(s)}}function eu(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive integer`)}function O(t,e,n=!1){return new me({code:t,message:e,retryable:n})}var Xs="QODER_AGENT_SDK_DAEMON",Zs="ELECTRON_RUN_AS_NODE",vn="--sdk",We=2e3,eo=8192,to=255,De=new WeakMap;function Ve(t){return De.get(t)}async function _n(t){au(t.initializeTimeoutMs),uu(t.heartbeatTimeoutMs);let e=t.noProxy===void 0?void 0:t.noProxy.trim(),n=new ae({auth:t.auth,env:t.env,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint}),s=await n.prepare(),o=t.auth?vt(t.auth,t.env):void 0,r=new Z({debug:t.debug,debugFile:t.debugFile??kn(t),stderr:t.stderr}),i=t.launchMode??"process";i==="worker"&&!$e(t.pathToQoderWorkerRuntime)&&(r.record("[DaemonLaunch] worker runtime is unavailable; falling back to process"),i="process");let a=await so({pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,launchMode:i,pathToQoderWorkerRuntime:t.pathToQoderWorkerRuntime});r.record(`[DaemonLaunch] mode=${i} command=${a.command} args=${JSON.stringify(a.args)}`);let u=e===void 0?s.env:{...s.env,NO_PROXY:e,no_proxy:e},c={...u,...a.env,[Xs]:"1"},d;try{try{d=await At.spawn({command:a.command,args:a.args,env:c,stderrHandler:t.stderr})}catch(y){if(i==="process"&&cu(y)&&$e())r.record("[DaemonLaunch] process spawn failed; falling back to worker runtime",y),i="worker",a=await so({pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,launchMode:i,pathToQoderWorkerRuntime:t.pathToQoderWorkerRuntime}),c={...u,...a.env,[Xs]:"1"},r.record(`[DaemonLaunch] mode=${i} command=${a.command} args=${JSON.stringify(a.args)}`),d=await At.spawn({command:a.command,args:a.args,env:c,stderrHandler:t.stderr});else throw y}r.record(`[Daemon] spawned pid=${d.process.pid}`);let m=new Tt({input:d.process.stdin,output:d.process.stdout,requestHandler:t.auth?Sn(t.auth):void 0,diagnostics:r,describeUnexpectedClose:()=>d.describeUnexpectedClose(),...t.heartbeatTimeoutMs===void 0?{}:{heartbeatTimeoutMs:t.heartbeatTimeoutMs}});d.setConnection(m);let p=Date.now();await m.initialize(ft,{capabilities:["session_delete_v1",yn,Mt],...o===void 0?{}:{auth:o},...t.proxy===void 0?{}:{proxy:t.proxy},...e===void 0?{}:{noProxy:e},...t.initializeTimeoutMs===void 0?{}:{timeoutMs:t.initializeTimeoutMs}}),r.record(`[Daemon] initialized in ${Date.now()-p}ms`);let l=m.supportsCapability(de);t.proxy!==void 0&&!l&&r.record(`[Daemon] proxy requested but ${de} is not supported by this CLI; the proxy was not applied to the daemon`);let f=t.proxy!==void 0&&l&&t.proxy.trim()||null,S=m.supportsCapability(pe);if(e!==void 0&&!S)throw new h(`daemon is missing required capability: ${pe}`);let g=e===void 0||!S?null:e||null,v=e;await n.cleanupAuthPayload();let b=new wn(m,d,t.env,r);return De.set(b,{hostActionLaunch:{proxy:t.proxy,noProxy:v,cliPath:t.pathToQoderCLIExecutable,env:t.env},auth:t.auth,proxy:f,noProxy:g,transportProvider:new bn(m,u)}),b}catch(m){throw await n.cleanupAuthPayload(),await d?.stop().catch(()=>{}),m}}var wn=class{constructor(e,n,s,o){this.connection=e;this.processController=n;this.env=s;this.diagnostics=o;this.connection.onFailure(r=>this.acceptDaemonFailure(r)),this.processController.onFailure(r=>this.acceptDaemonFailure(r))}currentState="ready";stopPromise;get state(){return this.currentState}onFailure(e){return this.connection.onFailure(e)}async listSessions(e){return this.requireReady(),(await this.connection.listSessions(e)).map(no)}async renameSession(e,n,s){if(this.requireReady(),typeof e!="string"||!e.trim())throw new TypeError("localSessionId must be a non-empty string");let o=su(n),r=await this.connection.renameSession(e,o,s);return no(r.session)}async deleteSession(e,n){if(this.requireReady(),typeof e!="string"||!e.trim())throw new TypeError("localSessionId must be a non-empty string");await this.connection.deleteSession(e,n)}async setProxy(e,n){this.requireReady();let s=n?.noProxy,o=await this.connection.setProxySettings(e,s),r=De.get(this);return r&&(r.proxy=o.proxy,r.hostActionLaunch.proxy=o.proxy??void 0,s!==void 0&&(r.noProxy=o.noProxy,r.hostActionLaunch.noProxy=o.noProxy===null?null:o.noProxy)),o.proxy}getProxy(){return De.get(this)?.proxy??null}getNoProxy(){return De.get(this)?.noProxy??null}async auth(e){this.requireReady();let n;if(e!==void 0){n=vt(e,this.env),this.connection.setRequestHandler(Sn(e));let o=De.get(this);o&&(o.auth=e)}return(await this.connection.authenticate(n)).authenticated}async getModels(e={}){return this.requireReady(),(await this.connection.query("get_models",{...e.fetchStrategy?{fetchStrategy:e.fetchStrategy}:{},...e.uid?{uid:e.uid}:{},...e.outerProviders?{outerProviders:e.outerProviders}:{}})).models}async getByokConfig(){return this.requireReady(),(await this.connection.query("get_byok_config",{})).providers}async validateByokModel(e){return this.requireReady(),(await this.connection.query("validate_byok_model",{provider:e.provider,model:e.model,api_key:e.api_key,...e.url!==void 0?{url:e.url}:{},...e.style!==void 0?{style:e.style}:{},...e.model_type!==void 0?{model_type:e.model_type}:{},...e.provider_type!==void 0?{provider_type:e.provider_type}:{}})).success}async listByokConfigs(){return this.requireReady(),(await this.connection.query("list_byok_configs",{})).configs}async createByokConfig(e){return this.requireReady(),(await this.connection.query("create_byok_config",{config:e})).config}async updateByokConfig(e){this.requireReady(),await this.connection.query("update_byok_config",{config:e})}async deleteByokConfig(e){this.requireReady(),await this.connection.query("delete_byok_config",{target:e})}async checkByokConfig(e){return this.requireReady(),this.connection.query("check_byok_config",{config:e})}async listPlugins(){return this.requireReady(),(await this.connection.query("list_plugins",{})).plugins}supportsCapability(e){return this.connection.supportsCapability(e)}async validatePlugins(e,n={}){if(this.requireReady(),!Array.isArray(e)||e.length===0||e.some(s=>typeof s!="string"||s.length===0))throw new TypeError("paths must be a non-empty array of non-empty strings");return this.connection.validatePlugins(e,n.configDir)}async getUsageInfo(){this.requireReady();let e=await this.connection.query("get_usage_info",{}),n=_t(e.usage),s=bt(e.session);return!n&&!s?null:{...n??{},...s?{session:s}:{}}}async accountInfo(){return this.requireReady(),(await this.connection.query("account_info",{})).account}stop(){return this.stopPromise||(this.processController.beginStopping(),this.currentState!=="failed"&&this.setDaemonState("stopping"),this.stopPromise=this.stopInternal()),this.stopPromise}async stopInternal(){try{await this.connection.shutdown().catch(()=>{}),await this.processController.stop(),this.currentState!=="failed"&&this.setDaemonState("stopped")}catch(e){throw this.setDaemonState("failed",e instanceof Error?e:new Error(String(e))),e}}acceptDaemonFailure(e){this.currentState==="ready"&&this.setDaemonState("failed",e),e instanceof Ie&&this.processController.stop().then(({settledAfterSigkill:n})=>{n||this.diagnostics?.record("[Daemon] heartbeat reclaim: process still present after SIGKILL grace; left to OS")}).catch(n=>{this.diagnostics?.record("[Daemon] heartbeat reclaim: forced stop failed",n)})}setDaemonState(e,n){this.currentState!==e&&(this.currentState=e)}requireReady(){if(this.currentState!=="ready")throw new Error("Daemon is not ready")}};function su(t){if(typeof t!="string")throw new TypeError("title must be a non-empty string");let e=t.replace(/[\r\n]+/g," ").trim();if(!e)throw new TypeError("title must be a non-empty string");if(e.length>to)throw new TypeError(`title must be at most ${to} characters`);return e}function no(t){return{localSessionId:t.local_session_id,title:t.title,...t.cwd?{cwd:t.cwd}:{},state:t.state,createdAt:t.created_at,updatedAt:t.updated_at}}var bn=class{constructor(e,n){this.connection=e;this.daemonEnv=n}create(e){let n=new ae({...e,auth:void 0,env:this.daemonEnv}),s=n.buildArgs(),o=iu(s),r=o===void 0?void 0:this.connection.claimSessionId(o);try{return this.connection.createSessionTransport({workerArgs:s,claim:r,cwd:e.cwd??process.cwd(),...e.materializedSessionConfigDir!==void 0?{configDir:e.materializedSessionConfigDir}:{},cleanup:()=>n.cleanupGeneratedSettings()})}catch(i){throw r&&this.connection.releaseSessionClaim(r.sessionId),i}}};function ou(t){let e=t.findIndex(n=>n==="--session-id"||n==="--resume");if(e>=0&&e+1<t.length)return t[e+1];for(let n of t)if(n.startsWith("--session-id="))return n.slice(13)}function ru(t){let e=t.findIndex(n=>n==="--session-id");if(e>=0&&e+1<t.length)return t[e+1];for(let n of t)if(n.startsWith("--session-id="))return n.slice(13)}function iu(t){return t.includes("--fork-session")?ru(t):ou(t)}function au(t){if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new TypeError("initializeTimeoutMs must be a positive integer")}function uu(t){if(t!==void 0&&(!Number.isSafeInteger(t)||t<0))throw new TypeError("heartbeatTimeoutMs must be a non-negative integer")}function cu(t){let e=t.cause?.code;return e==="ENOEXEC"||e==="EACCES"}async function so({pathToQoderCLIExecutable:t,executable:e,executableArgs:n,launchMode:s="process",pathToQoderWorkerRuntime:o}){if(s==="worker"){let i=await Me(o??le());return{command:e??process.execPath,args:[...n??[],i.runtimePath,vn],env:{...i.env,...typeof process.versions.electron=="string"?{[Zs]:"1"}:{}}}}let r=t??Pe();return Re(r)?{command:e??process.execPath,args:[...n??[],r,vn],env:typeof process.versions.electron=="string"?{[Zs]:"1"}:{}}:{command:r,args:[vn],env:{}}}var At=class t{constructor(e,n){this.process=e;this.stderrHandler=n;this.exited=new Promise(s=>{e.once("exit",()=>s()),e.once("error",()=>s())}),this.closed=new Promise(s=>{e.once("close",()=>s()),e.once("error",()=>s())}),e.stderr?.on("data",s=>{let o=s.toString("utf8");if(this.stderrTail+=o,this.stderrTail.length>eo&&(this.stderrTail=this.stderrTail.slice(-eo)),!!this.stderrHandler)try{this.stderrHandler(o)}catch{}}),e.once("error",s=>{this.reportFailure(new K(`Failed to spawn Qoder CLI daemon: ${s.message}`,{stderr:this.getStderr(),cause:s}))}),e.once("exit",(s,o)=>{this.exitInfo={code:s,signal:o},!this.stopping&&Je(this.closed,We).then(()=>{if(this.stopping)return;let r=this.getStderr(),i=s!==null?`Qoder CLI daemon exited with code ${s}`:`Qoder CLI daemon terminated by signal ${o}`;this.reportFailure(new K(r?`${i}
|
|
6
|
+
`)}}n+=e.end(),n.length!==0&&(n.endsWith("\r")&&(n=n.slice(0,-1)),yield n)}var ze=2,Ge="daemon_queries_v1",Ae="daemon_validate_plugins_v1",pe="daemon_proxy_v1",me="daemon_proxy_bypass_v1",h=class extends Error{code="DAEMON_PROTOCOL_ERROR";constructor(e){super(e),this.name="DaemonProtocolError"}};function mn(t){if(t.trim().length===0)throw new h("daemon protocol line must not be empty");let e;try{e=JSON.parse(t)}catch{throw new h("daemon protocol line must contain valid JSON")}let n=k(e,"daemon protocol frame");if(Object.hasOwn(n,"frame_type")||Object.hasOwn(n,"protocol_version")&&!Object.hasOwn(n,"type"))throw new h("daemon v1 frame envelopes are not supported on the v2 wire");switch(n.type){case"control_request":Pa(n);break;case"control_response":Ea(n);break;case"status_event":Ca(n);break;case"keep_alive":R(n,["type"],"keep_alive frame");break;case"protocol_error":Ra(n);break;case"session_input":case"session_output":throw new h(`${String(n.type)} is not supported on the v2 wire`);default:if(P(n,"type"),!Ma(n.type))throw new h(`unknown daemon message type: ${String(n.type)}`);Ta(n),fn(n)}return n}function Bs(t){let e=Fs(JSON.stringify(t));if(e.includes(`
|
|
7
|
+
`)||e.includes("\r"))throw new h("daemon protocol frame must not contain raw line breaks");return mn(e),e}function $s(t,e){let n=e.response.response;switch(t){case"initialize":{M(e,"initialize response");let s=k(n,"initialize response");if(R(s,["daemon_protocol_version","daemon_version","capabilities"],"initialize response"),s.daemon_protocol_version!==ze)throw new h(`unsupported daemon_protocol_version: ${String(s.daemon_protocol_version)}`);return P(s,"daemon_version"),Aa(s,"capabilities"),s}case"open_session":{let s=dn(e,"open_session response");return ln(n,"open_session"),{session_id:s}}case"list_sessions":{M(e,"list_sessions response");let s=k(n,"list_sessions response");R(s,["sessions"],"list_sessions response");let o=s.sessions;if(!Array.isArray(o))throw new h("sessions must be an array");for(let[r,i]of o.entries())Ls(k(i,`sessions[${r}]`),`sessions[${r}]`);return s}case"rename_session":{dn(e,"rename_session response");let s=k(n,"rename_session response");return R(s,["session"],"rename_session response"),Ls(k(s.session,"rename_session session"),"rename_session session"),s}case"close_session":return dn(e,`${t} response`),ln(n,t),null;case"delete_session":case"shutdown":case"update_byok_config":case"delete_byok_config":return M(e,`${t} response`),ln(n,t),null;case"authenticate":{M(e,`${t} response`);let s=k(n,"authenticate response");if(R(s,["authenticated"],"authenticate response"),typeof s.authenticated!="boolean")throw new h("authenticated must be a boolean");return s}case"get_models":return M(e,`${t} response`),Qe(n,t,"models");case"get_byok_config":return M(e,`${t} response`),Qe(n,t,"providers");case"list_byok_configs":return M(e,`${t} response`),Qe(n,t,"configs");case"list_plugins":return M(e,`${t} response`),Qe(n,t,"plugins");case"validate_plugins":return M(e,`${t} response`),Qe(n,t,"reports");case"setproxy":{M(e,`${t} response`);let s=k(n,`${t} response`);if(R(s,["proxy","no_proxy"],`${t} response`),s.proxy!==null&&typeof s.proxy!="string")throw new h(`${t} response proxy must be a string or null`);let o=s.no_proxy;if(o!=null&&typeof o!="string")throw new h(`${t} response no_proxy must be a string or null`);return s}case"validate_byok_model":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["success"],`${t} response`),pn(s,"success"),s}case"create_byok_config":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["config"],`${t} response`),k(s.config,`${t} response config`),s}case"account_info":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["account"],`${t} response`),k(s.account,`${t} response account`),s}case"check_byok_config":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["success","error","code","requestId","details"],`${t} response`),pn(s,"success"),Ks(s,["error","code","requestId"]),s.details!==void 0&&k(s.details,`${t} response details`),s}case"get_usage_info":{M(e,`${t} response`);let s=k(n,`${t} response`);return R(s,["usage","session","usage_error"],`${t} response`),s.usage!==null&&k(s.usage,`${t} response usage`),k(s.session,`${t} response session`),Ks(s,["usage_error"]),s}default:throw new h(`unknown daemon command result method: ${String(t)}`)}}function Ca(t){if(R(t,["type","status","data"],"status_event frame"),t.status!=="daemon.session_updated")throw new h("unsupported status_event status");let e=k(t.data,"status_event data");if(R(e,["local_session_id","state","error"],"status_event data"),P(e,"local_session_id"),e.state!=="failed")throw new h("status_event state must be failed");k(e.error,"status_event error")}function Ra(t){if(R(t,["type","code","message","malformed_lines","malformed_bytes","last_frame_type","last_frame_session_id"],"protocol_error frame"),P(t,"code"),t.message!==void 0&&typeof t.message!="string")throw new h("message must be a string");for(let e of["malformed_lines","malformed_bytes"]){let n=t[e];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`${e} must be a non-negative safe integer`)}for(let e of["last_frame_type","last_frame_session_id"])t[e]!==void 0&&P(t,e)}function Pa(t){R(t,["type","request_id","session_id","request"],"control_request frame"),P(t,"request_id"),fn(t);let e=k(t.request,"control request");if(!(typeof e.type=="string"&&e.type.length>0)&&!(typeof e.subtype=="string"&&e.subtype.length>0))throw new h("control request must have a non-empty string type or subtype")}function Ea(t){R(t,["type","session_id","response"],"control_response frame"),fn(t);let e=k(t.response,"control response");P(e,"request_id");let n=P(e,"subtype");if(n==="success"){if(["error","code","retryable","details"].some(s=>Object.hasOwn(e,s)))throw new h("success control response must not include error fields");R(e,["subtype","request_id","response"],"success control response"),e.response!==void 0&&k(e.response,"success response result");return}if(n!=="error")throw new h(`unknown control response subtype: ${n}`);if(Object.hasOwn(e,"response"))throw new h("error control response must not include response");if(R(e,["subtype","request_id","error","code","retryable","details","pending_permission_requests"],"error control response"),P(e,"error"),e.code!==void 0&&P(e,"code"),e.retryable!==void 0&&pn(e,"retryable"),e.details!==void 0&&k(e.details,"control response details"),e.pending_permission_requests!==void 0&&!Array.isArray(e.pending_permission_requests))throw new h("pending_permission_requests must be an array")}function Ks(t,e){for(let n of e)t[n]!==void 0&&P(t,n)}function Qe(t,e,n){let s=k(t,`${e} response`);if(R(s,[n],`${e} response`),!Array.isArray(s[n]))throw new h(`${e} response ${n} must be an array`);return s}function Ls(t,e){R(t,["local_session_id","title","cwd","state","created_at","updated_at"],e),P(t,"local_session_id"),t.cwd!==void 0&&P(t,"cwd"),P(t,"title");let n=P(t,"state");if(!["pending","ready","inactive","failed"].includes(n))throw new h(`${e} has invalid state: ${n}`);P(t,"created_at"),P(t,"updated_at")}function ln(t,e){if(t!==void 0)throw new h(`${e} success must omit response`)}function dn(t,e){let n=t;try{return P(n,"session_id")}catch{throw new h(`${e} requires a valid session_id`)}}function M(t,e){if(Object.hasOwn(t,"session_id"))throw new h(`${e} must not include session_id`)}function fn(t){let e=t;e.session_id!==void 0&&P(e,"session_id")}function Ta(t){for(let e of["session_epoch","sequence"])if(Object.hasOwn(t,e))throw new h(`${e} is reserved for daemon-internal Session ordering`)}function Ma(t){return typeof t=="string"&&["user","assistant","stream_event","tool_progress","result","system","prompt_suggestion","command_lifecycle","control_cancel_request","control_cancel","transcript_mirror"].includes(t)}function k(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new h(`${e} must be a JSON object`);return t}function P(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new h(`${e} must be a non-empty string`);return n}function pn(t,e){let n=t[e];if(typeof n!="boolean")throw new h(`${e} must be a boolean`);return n}function Aa(t,e){let n=t[e];if(!Array.isArray(n)||n.some(s=>typeof s!="string"))throw new h(`${e} must be an array of strings`);return n}function R(t,e,n){let s=new Set(e),o=Object.keys(t).find(r=>!s.has(r));if(o!==void 0)throw new h(`${n} contains unknown field: ${o}`)}var te=class{queue=[];readResolve;readReject;isDone=!1;errorValue;started=!1;returnCallback;constructor(e){this.returnCallback=e}[Symbol.asyncIterator](){if(this.started)throw new Error("Stream can only be iterated once");return this.started=!0,this}async next(){if(this.queue.length>0)return{done:!1,value:this.queue.shift()};if(this.isDone)return{done:!0,value:void 0};if(this.errorValue!==void 0)throw this.errorValue;return new Promise((e,n)=>{this.readResolve=e,this.readReject=n})}enqueue(e){if(!this.isDone)if(this.readResolve){let n=this.readResolve;this.readResolve=void 0,this.readReject=void 0,n({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.errorValue=e,this.readReject){let n=this.readReject;this.readResolve=void 0,this.readReject=void 0,n(e)}}async return(){return this.isDone=!0,this.returnCallback?.(),{done:!0,value:void 0}}async throw(e){return this.error(e),{done:!0,value:void 0}}};var Rt=class{constructor(e,n){this.connection=e;this.options=n}messages=new te;pendingMessages=[];initializePromise;sessionId;flushingPendingMessages=!1;inputEnded=!1;resultReceived=!1;commandLifecycleSupported=!1;pendingCommandUuids=new Set;closed=!1;cleaned=!1;releasePromise;closePromise;initialize(){return this.initializePromise||(this.initializePromise=this.open(),this.initializePromise.catch(()=>{})),this.initializePromise}write(e){if(this.closed)throw new Error("Transport is not ready or has been closed");let n=Da(e);if(this.trackOutboundCommand(n),!this.sessionId||this.flushingPendingMessages){if(!this.initializePromise)throw new Error("Transport is not ready or has been closed");this.pendingMessages.push(n);return}let s;try{s=Qs(n,this.sessionId)}catch(o){this.failAndRelease(o);return}this.connection.sendSessionMessage(s).catch(o=>this.failAndRelease(o))}async*readMessages(){await this.initialize();for await(let e of this.messages)yield e}endInput(){this.closed||(this.inputEnded=!0,this.maybeCloseAfterResult())}close(){return this.closePromise||(this.closePromise=this.performClose(),this.closePromise.catch(()=>{})),this.closePromise}isReady(){return this.sessionId!==void 0&&!this.closed}acceptOutput(e){this.closed||(this.observeCapabilities(e),this.messages.enqueue(e),this.observeCommandLifecycle(e),e.type==="result"&&(this.resultReceived=!0),this.maybeCloseAfterResult())}fail(e){this.closed||(this.closed=!0,this.cleanup(),this.messages.error(e instanceof Error?e:new Error(String(e))))}async open(){let e,n=!1,s=this.options.claim;try{s&&(await s.ready,n=!0);let o=await this.connection.openSession({...this.options.business===void 0?{}:{business:this.options.business},worker_args:[...this.options.workerArgs],...this.options.cwd!==void 0?{cwd:this.options.cwd}:{},...this.options.configDir!==void 0?{config_dir:this.options.configDir}:{}},this);if(s&&s.sessionId!==o&&(this.connection.releaseSessionClaim(s.sessionId),n=!1),this.sessionId=o,e=o,this.record(`session opened cwd=${this.options.cwd??"(inherit)"} workerArgs=${this.options.workerArgs.length}`),this.closed){await this.releaseSessionOnce(o);return}this.flushingPendingMessages=!0;try{for(;this.pendingMessages.length>0;){let r=this.pendingMessages.map(i=>Qs(i,o));this.pendingMessages.splice(0);for(let i of r)await this.connection.sendSessionMessage(i)}}finally{this.flushingPendingMessages=!1}}catch(o){throw e!==void 0?this.startRelease(e):n&&s&&this.connection.releaseSessionClaim(s.sessionId),this.fail(o),o}}failAndRelease(e){let n=this.sessionId;this.record("session failed, releasing",e),n!==void 0&&this.startRelease(n),this.fail(e)}record(e,n){let s=this.sessionId;this.options.diagnostics?.record(`[DaemonSession]${s!==void 0?` sessionId=${s}`:""} ${e}`,n)}startRelease(e){this.releaseSessionOnce(e).catch(()=>{})}releaseSessionOnce(e){return this.releasePromise||(this.releasePromise=this.releaseSession(e)),this.releasePromise}releaseSession(e){return this.connection.closeSession(e)}trackOutboundCommand(e){if(!this.commandLifecycleSupported||e.type!=="user")return;let n=e.uuid;typeof n=="string"&&n.trim().length>0&&this.pendingCommandUuids.add(n)}observeCapabilities(e){e.type!=="system"||e.subtype!=="init"||this.updateCommandLifecycleCapability(e)}updateCommandLifecycleCapability(e){let n=e.capabilities;this.commandLifecycleSupported=Array.isArray(n)&&n.includes("msg_lifecycle_v1")}observeCommandLifecycle(e){if(e.type!=="command_lifecycle"||e.state!=="completed"&&e.state!=="cancelled"&&e.state!=="discarded")return;let n=e.command_uuid;typeof n=="string"&&this.pendingCommandUuids.delete(n)}maybeCloseAfterResult(){!this.inputEnded||!this.resultReceived||this.commandLifecycleSupported&&this.pendingCommandUuids.size>0||this.close().catch(()=>{})}async performClose(){this.initializePromise&&await this.initializePromise.catch(()=>{});try{this.releasePromise?await this.releasePromise:this.sessionId&&await this.releaseSessionOnce(this.sessionId)}catch(e){throw this.record("close handshake failed",e),this.markClosed(),this.messages.error(e),e}this.record("closed"),this.markClosed(),this.messages.done()}markClosed(){this.closed||(this.closed=!0,this.cleanup())}cleanup(){this.cleaned||(this.cleaned=!0,this.options.cleanup?.())}};function Da(t){let e;try{e=JSON.parse(t.trim())}catch{throw new Error("Query transport input must contain valid JSON")}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Query transport input must be a JSON object");return e}function Qs(t,e){if(Object.hasOwn(t,"session_id")&&t.session_id!==e)throw new Error(`Query message session_id must match daemon Session: expected ${e}, received ${String(t.session_id)}`);return{...t,session_id:e}}import{Transform as Ia}from"node:stream";var Et=64*1024*1024,Pt=class extends Ia{constructor(n=Et,s="SDK output"){super();this.maxLineBytes=n;this.source=s;if(!Number.isSafeInteger(n)||n<=0)throw new Error("maxLineBytes must be a positive safe integer")}bytesSinceNewline=0;_transform(n,s,o){let r=Buffer.isBuffer(n)?n:Buffer.from(n,s),i=0;for(let a=0;a<r.length;a+=1)if(r[a]===10){if(this.bytesSinceNewline+=a-i,this.bytesSinceNewline>this.maxLineBytes){o(new G("output",this.maxLineBytes,this.bytesSinceNewline,this.source));return}this.bytesSinceNewline=0,i=a+1}if(this.bytesSinceNewline+=r.length-i,this.bytesSinceNewline>this.maxLineBytes){o(new G("output",this.maxLineBytes,this.bytesSinceNewline,this.source));return}o(void 0,r)}};function zs(t,e=Et,n="SDK input",s){let o=t.endsWith(`
|
|
8
|
+
`)?t.slice(0,-1):t,r=Buffer.byteLength(o,"utf8");if(r>e)throw new G("input",e,r,n,s)}var gn="multi_session_v2",Gs="session_title_sync_v1",Hs="session_delete_v1";var xa=12e4,Vs=12e4,yn="daemon_keep_alive_v1",Oa=5e3,hn=3e4,qa=125e3,Na=12e4,ja=12e4,Fa=5e3,Ua=6e4,Ka=15e4,La=12e4,Ba=1024,$a=64,Qa=8*1024*1024,za=256,Ga=32*1024*1024,Ha=new Set(["daemon.auth.fetch_job_token","daemon.auth.fetch_service_account_token"]),Tt=class extends Error{code;retryable;details;constructor(e){super(e.message),this.name="DaemonRpcError",this.code=e.code,this.retryable=e.retryable,this.details=e.details}},fe=class extends Error{code;retryable;details;constructor(e){super(e.message),this.name="DaemonRequestError",this.code=e.code,this.retryable=e.retryable,this.details=e.details}},He=class extends Error{constructor(n,s){super(`session ${n} is already open (state=${s})`);this.sessionId=n;this.state=s;this.name="DaemonSessionAlreadyOpenError"}code="SESSION_ALREADY_OPEN"},De=class extends Error{code="DAEMON_HEARTBEAT_TIMEOUT";elapsedMs;partialFrame;constructor(e,n=!1){super(`DAEMON_HEARTBEAT_TIMEOUT Qoder CLI daemon stopped responding (no inbound data for ${e}ms${n?"; partial frame in progress":""})`),this.name="DaemonHeartbeatTimeoutError",this.elapsedMs=e,this.partialFrame=n}},Mt=class{input;requestHandler;pendingRequests=new Map;timedOutRequestIds=new Set;activeInboundRequestIds=new Set;sessions=new Map;sessionSlots=new Map;closedSessionIds=new Set;sessionCwds=new Map;pendingSessionMessages=new Map;pendingSessionMessageBytes=new Map;pendingSessionMessageFrameCount=0;pendingSessionMessageByteCount=0;maxFrameBytes;readTask;writeChain=Promise.resolve();nextRequestId=1;initializing=!1;initialized=!1;capabilities=new Set;stopping=!1;failure;failureListeners=new Set;describeUnexpectedClose;diagnostics;lastInboundAt=performance.now();inboundFrameInProgress=!1;heartbeatWatchdog;heartbeatTimeoutMs;constructor(e){if(this.input=e.input,this.requestHandler=e.requestHandler,this.describeUnexpectedClose=e.describeUnexpectedClose,this.diagnostics=e.diagnostics,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??Vs,this.maxFrameBytes=e.maxFrameBytes??Et,!Number.isSafeInteger(this.maxFrameBytes)||this.maxFrameBytes<=0)throw new TypeError("maxFrameBytes must be a positive safe integer");this.readTask=this.readOutput(e.output)}async initialize(e,n={}){if(this.initialized)throw new h("daemon connection is already initialized");if(this.initializing)throw new h("daemon initialize is already in progress");this.initializing=!0;let s,o=n.timeoutMs??xa,r=this.request("initialize",{...n.business===void 0?{}:{business:n.business},daemon_protocol_version:ze,sdk_version:e,capabilities:[gn,...n.capabilities??[]],...n.auth?{auth:n.auth}:{},...n.proxy===void 0?{}:{proxy:n.proxy},...n.noProxy===void 0?{}:{no_proxy:n.noProxy}}),i=new Promise((u,c)=>{s=setTimeout(()=>{let l=new Error(`Qoder CLI daemon did not initialize within ${o}ms`);this.fail(l),c(l)},o)}),a;try{a=await Promise.race([r,i])}finally{this.initializing=!1,s&&clearTimeout(s)}if(!a.capabilities.includes(gn))throw new h(`daemon is missing required capability: ${gn}`);if(n.business!==void 0&&!a.capabilities.includes("business_product_v1"))throw new h("daemon is missing required capability: business_product_v1");for(let u of a.capabilities)this.capabilities.add(u);this.initialized=!0,this.capabilities.has(yn)?this.armHeartbeatWatchdog():this.diagnostics?.record("[DaemonConnection] heartbeat not negotiated; watchdog disarmed")}createSessionTransport(e){if(!this.initialized||this.stopping||this.failure)throw this.failure??new Error("Daemon connection is not ready");return new Rt(this,{...e,diagnostics:this.diagnostics})}supportsCapability(e){return this.capabilities.has(e)}async setProxy(e,n){return(await this.setProxySettings(e,n)).proxy}async setProxySettings(e,n){if(!this.capabilities.has(pe))throw new h(`daemon is missing required capability: ${pe}`);if(n!==void 0&&!this.capabilities.has(me))throw new h(`daemon is missing required capability: ${me}`);let s=await this.request("setproxy",{proxy:e||null,...n===void 0?{}:{no_proxy:n}},void 0,void 0,hn,"request");return{proxy:s.proxy,noProxy:Object.hasOwn(s,"no_proxy")?s.no_proxy??null:n===void 0?null:n}}claimSessionId(e){let n=this.sessionSlots.get(e);if(!n)return this.sessionSlots.set(e,{state:"opening",waiters:[]}),{sessionId:e,ready:Promise.resolve()};if(n.state==="closing"){let s=new Promise((o,r)=>{n.waiters.push({resolve:o,reject:r})});return{sessionId:e,ready:s}}throw new He(e,n.state)}markSessionOpen(e){let n=this.sessionSlots.get(e);n?n.state="open":this.sessionSlots.set(e,{state:"open",waiters:[]})}markSessionClosing(e){let n=this.sessionSlots.get(e);n?n.state="closing":this.sessionSlots.set(e,{state:"closing",waiters:[]})}releaseSessionClaim(e){let n=this.sessionSlots.get(e);!n||n.state!=="opening"||this.advanceSessionSlot(e,n)}completeSessionClose(e){let n=this.sessionSlots.get(e);!n||n.state!=="closing"||this.advanceSessionSlot(e,n)}advanceSessionSlot(e,n){let s=n.waiters.shift();if(!s){this.sessionSlots.delete(e);return}n.state="opening",s.resolve();for(let o of n.waiters.splice(0))o.reject(new He(e,"opening"))}validatePlugins(e,n){return this.capabilities.has(Ae)?this.request("validate_plugins",{paths:[...e],...n===void 0?{}:{config_dir:n}},void 0,void 0,Ka,"request").then(s=>s.reports):Promise.reject(new h(`daemon is missing required capability: ${Ae}`))}setRequestHandler(e){this.requestHandler=e}onFailure(e){return this.failureListeners.add(e),this.failure&&e(this.failure),()=>this.failureListeners.delete(e)}async openSession(e,n){if(e.business!==void 0&&!this.supportsCapability("query_business_type_v1"))throw new h("daemon is missing required capability: query_business_type_v1");let s=await this.request("open_session",e,n,void 0,Na);return e.cwd!==void 0&&this.sessionCwds.set(s.session_id,e.cwd),s.session_id}async listSessions(e){return(await this.request("list_sessions",e===void 0?{}:{cwd:e},void 0,void 0,qa,"request")).sessions}renameSession(e,n,s){if(!this.capabilities.has(Gs))return Promise.reject(new h(`daemon is missing required capability: ${Gs}`));let o=s??this.sessionCwds.get(e);return this.request("rename_session",o===void 0?{title:n}:{title:n,cwd:o},void 0,e,hn)}sendSessionMessage(e){return this.writeFrame(e)}async closeSession(e){this.markSessionClosing(e);try{await this.request("close_session",{},void 0,e,ja,"request")}finally{this.sessions.delete(e),this.closedSessionIds.add(e),this.completeSessionClose(e)}}async deleteSession(e,n){if(!this.capabilities.has(Hs))throw new h(`daemon is missing required capability: ${Hs}`);let s=n??this.sessionCwds.get(e);await this.request("delete_session",s===void 0?{local_session_id:e}:{local_session_id:e,cwd:s},void 0,void 0,hn)}query(e,n){return this.capabilities.has(Ge)?this.request(e,n,void 0,void 0,Ua,"request"):Promise.reject(new h(`daemon is missing required capability: ${Ge}`))}authenticate(e){return this.capabilities.has(Ge)?this.request("authenticate",e===void 0?{}:{auth:e},void 0,void 0,La,"request"):Promise.reject(new h(`daemon is missing required capability: ${Ge}`))}async shutdown(e=Fa){if(this.stopping){await this.readTask.catch(()=>{});return}this.stopping=!0,this.disarmHeartbeatWatchdog();try{this.failure||await this.request("shutdown",{},void 0,void 0,e,"connection")}finally{let n=new Error("Daemon is stopping");for(let s of this.sessions.values())s.fail(n);this.sessions.clear();for(let s of this.sessionSlots.values())for(let o of s.waiters.splice(0))o.reject(n);this.sessionSlots.clear(),!this.input.destroyed&&!this.input.writableEnded&&this.input.end()}}async resolveUnexpectedClose(){if(!this.describeUnexpectedClose)return new Error("Daemon connection closed");try{return await this.describeUnexpectedClose()??new Error("Daemon connection closed")}catch{return new Error("Daemon connection closed")}}fail(e,n=!0){let s=e instanceof Error?e:new Error(String(e));if(!this.failure){this.failure=s,this.disarmHeartbeatWatchdog(),this.diagnostics?.record(`[DaemonConnection] connection failed pendingRequests=${this.pendingRequests.size} sessions=${this.sessions.size}`,s);for(let o of this.pendingRequests.values())o.timeout&&clearTimeout(o.timeout),o.reject(s);this.pendingRequests.clear(),this.timedOutRequestIds.clear(),this.clearPendingSessionMessages();for(let o of this.sessions.values())o.fail(s);this.sessions.clear();for(let o of this.sessionSlots.values())for(let r of o.waiters.splice(0))r.reject(s);if(this.sessionSlots.clear(),n)for(let o of this.failureListeners)try{o(s)}catch{}}}armHeartbeatWatchdog(){if(this.heartbeatTimeoutMs<=0)return;this.lastInboundAt=performance.now();let e=Math.min(Oa,Math.max(25,Math.floor(this.heartbeatTimeoutMs/2)));this.heartbeatWatchdog=setInterval(()=>{if(this.failure||this.stopping||!this.initialized)return;let n=Math.round(performance.now()-this.lastInboundAt);n<=this.heartbeatTimeoutMs||(this.diagnostics?.record(`[DaemonConnection] heartbeat timeout elapsed=${n}ms pendingRequests=${this.pendingRequests.size} sessions=${this.sessions.size} partialFrame=${this.inboundFrameInProgress}`),this.fail(new De(n,this.inboundFrameInProgress)))},e),this.heartbeatWatchdog.unref()}disarmHeartbeatWatchdog(){this.heartbeatWatchdog!==void 0&&(clearInterval(this.heartbeatWatchdog),this.heartbeatWatchdog=void 0)}request(e,n,s,o,r,i="request"){if(this.failure)return Promise.reject(this.failure);if(e!=="initialize"&&!this.initialized)return Promise.reject(new h("daemon connection is not initialized"));let a=`sdk_daemon_${this.nextRequestId++}`,u={type:"control_request",request_id:a,...o!==void 0?{session_id:o}:{},request:{type:`daemon.${e}`,...n}};return new Promise((c,l)=>{let m={method:e,resolve:p=>c(p),reject:l,...s?{sessionTransport:s}:{},...o!==void 0?{sessionId:o}:{}};r!==void 0&&(m.timeout=setTimeout(()=>{if(this.pendingRequests.get(a)!==m)return;let p=new h(`daemon ${e} request timed out after ${r}ms`);if(this.diagnostics?.record(`[DaemonConnection] request timeout method=${e} requestId=${a}${o!==void 0?` sessionId=${o}`:""} timeoutMs=${r} scope=${i}`),i==="request"){this.pendingRequests.delete(a),this.rememberTimedOutRequestId(a),m.reject(p);return}this.fail(p)},r),m.timeout.unref?.()),this.pendingRequests.set(a,m),this.diagnostics?.record(`[DaemonConnection] request sent method=${e} requestId=${a}${o!==void 0?` sessionId=${o}`:""}${r!==void 0?` timeoutMs=${r}`:""}`),this.writeFrame(u).catch(p=>{let d=this.pendingRequests.get(a);d?.timeout&&clearTimeout(d.timeout),this.pendingRequests.delete(a),this.diagnostics?.record(`[DaemonConnection] request write failed method=${e} requestId=${a}`,p),l(p),d?.sessionTransport&&this.failIfSessionMessagesAreOrphaned()})})}async readOutput(e){let n=new Pt(this.maxFrameBytes,"SDK daemon output"),s=o=>{this.lastInboundAt=performance.now();let r=o.length===0?void 0:typeof o=="string"?o.charCodeAt(o.length-1):o[o.length-1];this.inboundFrameInProgress=r!==void 0&&r!==10};e.on("data",s),e.pipe(n);try{for await(let o of Us(n)){if(!o.trim())continue;let r=Wa(o);r!==void 0&&this.rejectLegacyInitialize(r)||this.acceptFrame(mn(o))}(!this.stopping||this.pendingRequests.size>0)&&this.fail(await this.resolveUnexpectedClose())}catch(o){this.fail(o)}finally{e.off("data",s),e.unpipe(n),n.destroy()}}acceptFrame(e){let n=e;if(n.type!=="keep_alive"){if(n.type==="protocol_error"){let s=e,o=[`code=${s.code}`,...s.malformed_lines===void 0?[]:[`malformed_lines=${s.malformed_lines}`],...s.malformed_bytes===void 0?[]:[`malformed_bytes=${s.malformed_bytes}`],...s.last_frame_type===void 0?[]:[`last_frame_type=${s.last_frame_type}`],...s.last_frame_session_id===void 0?[]:[`last_frame_session_id=${s.last_frame_session_id}`]].join(" ");this.fail(new h(`daemon reported a fatal protocol error: ${o}`+(s.message===void 0?"":`: ${s.message}`)));return}if(n.type==="control_response"){let s=e,o=s.response.request_id;if(this.pendingRequests.has(o)){this.acceptControlResponse(s);return}if(this.timedOutRequestIds.delete(o)){this.abandonSessionFromLateResponse(s);return}this.routeSessionMessage(n);return}if(n.type==="control_request"){let s=e,o=Ja(s);if(o==="valid"){this.acceptRequest(s);return}if(o==="contradictory")throw new h(`contradictory daemon reverse RPC routing markers: ${s.request_id}`)}if(n.type==="status_event"){this.acceptSessionUpdatedStatusEvent(e);return}this.routeSessionMessage(n)}}rememberTimedOutRequestId(e){if(this.timedOutRequestIds.size>=Ba){let n=this.timedOutRequestIds.values().next().value;n!==void 0&&this.timedOutRequestIds.delete(n)}this.timedOutRequestIds.add(e)}abandonSessionFromLateResponse(e){let n=e.session_id;typeof n!="string"||n.length===0||this.sessions.has(n)||(this.closedSessionIds.add(n),this.deletePendingSessionMessages(n))}routeSessionMessage(e){let n=e.session_id;if(typeof n!="string"||n.length===0)throw new h(`daemon Session message requires a valid session_id: ${String(n)}`);let s=this.sessions.get(n);if(s){s.acceptOutput(e);return}if(this.hasPendingSessionRequest()){this.bufferPendingSessionMessage(n,e);return}if(!this.closedSessionIds.has(n))throw new h(`daemon output has unknown session_id: ${n}`)}acceptControlResponse(e){let n=e.response.request_id,s=this.pendingRequests.get(n);if(!s)throw new h(`daemon response has unknown request_id: ${n}`);if(s.timeout&&clearTimeout(s.timeout),s.sessionId!==void 0&&e.session_id!==s.sessionId){this.pendingRequests.delete(n),s.reject(new h(`${s.method} response session_id does not match request: expected ${s.sessionId}, received ${String(e.session_id)}`));return}if(this.pendingRequests.delete(n),e.response.subtype==="error"){if(s.method==="initialize"&&e.response.code==="PROTOCOL_VERSION_UNSUPPORTED"){s.reject(new X("1","2"));return}s.reject(new Tt({code:e.response.code??"DAEMON_REQUEST_FAILED",message:e.response.error,retryable:e.response.retryable??!1,...e.response.details===void 0?{}:{details:e.response.details}})),s.sessionTransport&&this.failIfSessionMessagesAreOrphaned();return}try{let o=e,r=o.response.response?.daemon_protocol_version;if(s.method==="initialize"&&typeof r=="number"&&r!==ze)throw new X(String(r),String(ze));let i=$s(s.method,o);if(s.sessionTransport){let a=i.session_id;if(typeof a!="string"||a.length===0)throw new h(`${s.method} did not return a valid session_id`);let u=this.takePendingSessionMessages(a);this.closedSessionIds.delete(a);let c=this.failIfSessionMessagesAreOrphaned(`${s.method} response session_id does not match buffered output`);if(c)throw c;if(this.sessions.has(a)){let l=new h(`daemon returned duplicate session_id: ${a}`);this.diagnostics?.record(`[DaemonConnection] rejecting duplicate open session_id=${a}`),s.reject(l);return}this.sessions.set(a,s.sessionTransport),this.markSessionOpen(a);for(let l of u)s.sessionTransport.acceptOutput(l)}s.resolve(i)}catch(o){s.reject(o instanceof Error?o:new Error(String(o))),s.sessionTransport&&this.failIfSessionMessagesAreOrphaned()}}hasPendingSessionRequest(){return[...this.pendingRequests.values()].some(e=>e.sessionTransport!==void 0)}failIfSessionMessagesAreOrphaned(e="daemon left orphaned pre-response Session output"){if(this.hasPendingSessionRequest())return;for(let o of this.pendingSessionMessages.keys())this.closedSessionIds.has(o)&&this.deletePendingSessionMessages(o);if(this.pendingSessionMessages.size===0)return;let n=[...this.pendingSessionMessages.keys()].join(", "),s=new h(`${e}: ${n}`);return this.clearPendingSessionMessages(),this.fail(s),s}bufferPendingSessionMessage(e,n){let s=this.pendingSessionMessages.get(e)??[],o=Buffer.byteLength(JSON.stringify(n),"utf8"),r=this.pendingSessionMessageBytes.get(e)??0;if(s.length+1>$a||r+o>Qa||this.pendingSessionMessageFrameCount+1>za||this.pendingSessionMessageByteCount+o>Ga)throw new h("daemon pre-response Session output exceeded its bounded buffer");s.push(n),this.pendingSessionMessages.set(e,s),this.pendingSessionMessageBytes.set(e,r+o),this.pendingSessionMessageFrameCount+=1,this.pendingSessionMessageByteCount+=o}takePendingSessionMessages(e){let n=this.pendingSessionMessages.get(e)??[];return this.deletePendingSessionMessages(e),n}deletePendingSessionMessages(e){let n=this.pendingSessionMessages.get(e)?.length??0,s=this.pendingSessionMessageBytes.get(e)??0;this.pendingSessionMessages.delete(e),this.pendingSessionMessageBytes.delete(e),this.pendingSessionMessageFrameCount-=n,this.pendingSessionMessageByteCount-=s}clearPendingSessionMessages(){this.pendingSessionMessages.clear(),this.pendingSessionMessageBytes.clear(),this.pendingSessionMessageFrameCount=0,this.pendingSessionMessageByteCount=0}rejectLegacyInitialize(e){let n=this.pendingRequests.get(e);return n?.method!=="initialize"?!1:(this.pendingRequests.delete(e),n.reject(new X("1","2")),!0)}acceptRequest(e){if(this.activeInboundRequestIds.has(e.request_id)){this.writeInboundError(e.request_id,"DUPLICATE_REQUEST_ID",`daemon request_id is already active: ${e.request_id}`);return}if(!this.requestHandler){this.writeInboundError(e.request_id,"METHOD_NOT_FOUND",`SDK has no handler for daemon method: ${e.request.type}`);return}this.activeInboundRequestIds.add(e.request_id),Promise.resolve().then(()=>this.requestHandler(e)).then(n=>{let s={type:"control_response",response:{subtype:"success",request_id:e.request_id,...n===null?{}:{response:n}}};return this.writeFrame(s)}).catch(n=>{let s=n instanceof fe?n:void 0,o={type:"control_response",response:{subtype:"error",request_id:e.request_id,code:s?.code??"SDK_REQUEST_FAILED",error:n instanceof Error?n.message:String(n),retryable:s?.retryable??!1,...s?.details?{details:s.details}:{}}};return this.writeFrame(o)}).catch(n=>this.fail(n)).finally(()=>{this.activeInboundRequestIds.delete(e.request_id)})}writeInboundError(e,n,s){let o={type:"control_response",response:{subtype:"error",request_id:e,code:n,error:s,retryable:!1}};this.writeFrame(o).catch(r=>this.fail(r))}acceptSessionUpdatedStatusEvent(e){let n=e.data.local_session_id,s=this.sessions.get(n);s&&(this.sessions.delete(n),this.closedSessionIds.add(n),s.fail(Va(e.data)))}writeFrame(e){let n;try{n=`${Bs(e)}
|
|
9
|
+
`,zs(n,this.maxFrameBytes,"SDK daemon input",e.type==="user"&&"uuid"in e&&typeof e.uuid=="string"?e.uuid:void 0)}catch(o){let r=o instanceof Error?o:new Error(String(o));return this.fail(r),Promise.reject(r)}let s=this.writeChain.then(()=>new Promise((o,r)=>{this.input.write(n,"utf8",i=>{if(i){r(i);return}o()})}));return this.writeChain=s.catch(()=>{}),s.catch(o=>this.fail(o)),s}};function Wa(t){let e;try{e=JSON.parse(t)}catch{return}if(!Ws(e)||!Js(e,["protocol_version","frame_type","request_id","ok","error"])||e.protocol_version!==1||e.frame_type!=="response"||e.ok!==!1||typeof e.request_id!="string"||e.request_id.length===0)return;let n=e.error;if(!(!Ws(n)||!Js(n,["code","message","retryable"])||n.code!=="PROTOCOL_VERSION_UNSUPPORTED"||typeof n.message!="string"||n.message.length===0||n.retryable!==!1))return e.request_id}function Ws(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Js(t,e){return Object.keys(t).length===e.length&&e.every(n=>Object.hasOwn(t,n))}function Ja(t){let e=Ha.has(t.request.type),n=t.request_id.startsWith("daemon_sdk_");return e&&n&&t.session_id===void 0?"valid":e||n?"contradictory":"none"}function Va(t){let e=t.error,n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},s=typeof n.message=="string"&&n.message.length>0?n.message:"Qoder CLI Worker exited before Session completed",o=n.exit_code===null||typeof n.exit_code=="number"?n.exit_code:void 0,r=n.signal===null||typeof n.signal=="string"?n.signal:void 0,i=typeof n.stderr=="string"&&n.stderr.length>0?n.stderr:void 0;return new K(s,{exitCode:o,signal:r,stderr:i})}var Ya=3e4;function Sn(t,e=Ya){return nu(e,"callbackTimeoutMs"),async n=>{switch(n.request.type){case"daemon.auth.fetch_job_token":return Xa(t,n,e);case"daemon.auth.fetch_service_account_token":return Za(t,n,e);default:throw O("METHOD_NOT_FOUND",`SDK has no handler for daemon method: ${n.request.type}`)}}}async function Xa(t,e,n){if(t.type!=="jobToken")throw O("DAEMON_AUTH_CALLBACK_UNAVAILABLE","Host job token callback is not configured");let s=Ys(e,["reason","session_id"]),o=Xs(s.reason),r=eu(s.session_id,"session_id"),i=new AbortController;try{let a=await Zs(()=>t.fetchJobToken({requestId:e.request_id,reason:o,sessionId:r},{signal:i.signal}),n,i);if(!a||typeof a.token!="string"||!a.token)throw O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback did not provide a token");let u=a.expiresAt;if(u!==void 0&&(!Number.isFinite(u)||u<1e12))throw O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback returned invalid expiresAt");return{token:a.token,...u!==void 0?{expires_at:u}:{}}}catch(a){throw a instanceof fe?a:O("DAEMON_AUTH_CALLBACK_FAILED","Host job token callback failed",!0)}}async function Za(t,e,n){if(t.type!=="serviceAccount"||typeof t.fetchServiceAccountToken!="function")throw O("DAEMON_AUTH_CALLBACK_UNAVAILABLE","Host Service Account token callback is not configured");let s=Ys(e,["reason","required_scopes"]);Xs(s.reason),tu(s.required_scopes,"required_scopes");let o=new AbortController;try{let r=await Zs(()=>t.fetchServiceAccountToken(),n,o);if(!r||typeof r.token!="string"||!r.token)throw O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback did not provide a token");let i=r.expiresAt;if(i!==void 0&&(!Number.isFinite(i)||i<1e12))throw O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback returned invalid expiresAt");return{token:r.token,...i!==void 0?{expires_at:i}:{}}}catch(r){throw r instanceof fe?r:O("DAEMON_AUTH_CALLBACK_FAILED","Host Service Account token callback failed",!0)}}function Ys(t,e){let n=Object.keys(t.request).find(s=>s!=="type"&&!e.includes(s));if(n)throw O("DAEMON_AUTH_INVALID_REQUEST",`request contains unknown field: ${n}`);return t.request}function Xs(t){if(t!=="initial"&&t!=="unauthorized")throw O("DAEMON_AUTH_INVALID_REQUEST","reason must be initial or unauthorized");return t}function eu(t,e){if(t!==void 0){if(typeof t!="string"||!t)throw O("DAEMON_AUTH_INVALID_REQUEST",`${e} must be a non-empty string`);return t}}function tu(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw O("DAEMON_AUTH_INVALID_REQUEST",`${e} must be an array of strings`);return t}async function Zs(t,e,n){let s;try{return await Promise.race([Promise.resolve().then(t),new Promise((o,r)=>{s=setTimeout(()=>{n.abort(),r(new Error("daemon auth callback timed out"))},e),s.unref?.()})])}finally{s&&clearTimeout(s)}}function nu(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive integer`)}function O(t,e,n=!1){return new fe({code:t,message:e,retryable:n})}var eo="QODER_AGENT_SDK_DAEMON",to="ELECTRON_RUN_AS_NODE",vn="--sdk",We=2e3,no=8192,so=255,Ie=new WeakMap;function Ve(t){return Ie.get(t)}async function _n(t){t={...t,business:t.business&&{...t.business}},cu(t.initializeTimeoutMs),lu(t.heartbeatTimeoutMs);let e=t.noProxy===void 0?void 0:t.noProxy.trim(),n=new ue({auth:t.auth,env:t.env,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint}),s=await n.prepare(),o=t.auth?wt(t.auth,t.env):void 0,r=new ee({debug:t.debug,debugFile:t.debugFile??kn(t),stderr:t.stderr}),i=t.launchMode??"process";i==="worker"&&!$e(t.pathToQoderWorkerRuntime)&&(r.record("[DaemonLaunch] worker runtime is unavailable; falling back to process"),i="process");let a=await ro({pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,launchMode:i,pathToQoderWorkerRuntime:t.pathToQoderWorkerRuntime});r.record(`[DaemonLaunch] mode=${i} command=${a.command} args=${JSON.stringify(a.args)}`);let u=e===void 0?s.env:{...s.env,NO_PROXY:e,no_proxy:e},c={...u,...a.env,[eo]:"1"},l;try{try{l=await At.spawn({command:a.command,args:a.args,env:c,stderrHandler:t.stderr})}catch(y){if(i==="process"&&du(y)&&$e())r.record("[DaemonLaunch] process spawn failed; falling back to worker runtime",y),i="worker",a=await ro({pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,launchMode:i,pathToQoderWorkerRuntime:t.pathToQoderWorkerRuntime}),c={...u,...a.env,[eo]:"1"},r.record(`[DaemonLaunch] mode=${i} command=${a.command} args=${JSON.stringify(a.args)}`),l=await At.spawn({command:a.command,args:a.args,env:c,stderrHandler:t.stderr});else throw y}r.record(`[Daemon] spawned pid=${l.process.pid}`);let m=new Mt({input:l.process.stdin,output:l.process.stdout,requestHandler:t.auth?Sn(t.auth):void 0,diagnostics:r,describeUnexpectedClose:()=>l.describeUnexpectedClose(),...t.heartbeatTimeoutMs===void 0?{}:{heartbeatTimeoutMs:t.heartbeatTimeoutMs}});l.setConnection(m);let p=Date.now();await m.initialize(gt,{business:t.business,capabilities:["session_delete_v1",yn],...o===void 0?{}:{auth:o},...t.proxy===void 0?{}:{proxy:t.proxy},...e===void 0?{}:{noProxy:e},...t.initializeTimeoutMs===void 0?{}:{timeoutMs:t.initializeTimeoutMs}}),r.record(`[Daemon] initialized in ${Date.now()-p}ms`);let d=m.supportsCapability(pe);t.proxy!==void 0&&!d&&r.record(`[Daemon] proxy requested but ${pe} is not supported by this CLI; the proxy was not applied to the daemon`);let f=t.proxy!==void 0&&d&&t.proxy.trim()||null,S=m.supportsCapability(me);if(e!==void 0&&!S)throw new h(`daemon is missing required capability: ${me}`);let g=e===void 0||!S?null:e||null,v=e;await n.cleanupAuthPayload();let b=new wn(m,l,t.env,r);return Ie.set(b,{hostActionLaunch:{proxy:t.proxy,noProxy:v,cliPath:t.pathToQoderCLIExecutable,env:t.env},auth:t.auth,proxy:f,noProxy:g,transportProvider:new bn(m,u)}),b}catch(m){throw await n.cleanupAuthPayload(),await l?.stop().catch(()=>{}),m}}var wn=class{constructor(e,n,s,o){this.connection=e;this.processController=n;this.env=s;this.diagnostics=o;this.connection.onFailure(r=>this.acceptDaemonFailure(r)),this.processController.onFailure(r=>this.acceptDaemonFailure(r))}currentState="ready";stopPromise;get state(){return this.currentState}onFailure(e){return this.connection.onFailure(e)}async listSessions(e){return this.requireReady(),(await this.connection.listSessions(e)).map(oo)}async renameSession(e,n,s){if(this.requireReady(),typeof e!="string"||!e.trim())throw new TypeError("localSessionId must be a non-empty string");let o=ru(n),r=await this.connection.renameSession(e,o,s);return oo(r.session)}async deleteSession(e,n){if(this.requireReady(),typeof e!="string"||!e.trim())throw new TypeError("localSessionId must be a non-empty string");await this.connection.deleteSession(e,n)}async setProxy(e,n){this.requireReady();let s=n?.noProxy,o=await this.connection.setProxySettings(e,s),r=Ie.get(this);return r&&(r.proxy=o.proxy,r.hostActionLaunch.proxy=o.proxy??void 0,s!==void 0&&(r.noProxy=o.noProxy,r.hostActionLaunch.noProxy=o.noProxy===null?null:o.noProxy)),o.proxy}getProxy(){return Ie.get(this)?.proxy??null}getNoProxy(){return Ie.get(this)?.noProxy??null}async auth(e){this.requireReady();let n;if(e!==void 0){n=wt(e,this.env),this.connection.setRequestHandler(Sn(e));let o=Ie.get(this);o&&(o.auth=e)}return(await this.connection.authenticate(n)).authenticated}async getModels(e={}){return this.requireReady(),(await this.connection.query("get_models",{...e.fetchStrategy?{fetchStrategy:e.fetchStrategy}:{},...e.uid?{uid:e.uid}:{},...e.outerProviders?{outerProviders:e.outerProviders}:{}})).models}async getByokConfig(){return this.requireReady(),(await this.connection.query("get_byok_config",{})).providers}async validateByokModel(e){return this.requireReady(),(await this.connection.query("validate_byok_model",{provider:e.provider,model:e.model,api_key:e.api_key,...e.url!==void 0?{url:e.url}:{},...e.style!==void 0?{style:e.style}:{},...e.model_type!==void 0?{model_type:e.model_type}:{},...e.provider_type!==void 0?{provider_type:e.provider_type}:{}})).success}async listByokConfigs(){return this.requireReady(),(await this.connection.query("list_byok_configs",{})).configs}async createByokConfig(e){return this.requireReady(),(await this.connection.query("create_byok_config",{config:e})).config}async updateByokConfig(e){this.requireReady(),await this.connection.query("update_byok_config",{config:e})}async deleteByokConfig(e){this.requireReady(),await this.connection.query("delete_byok_config",{target:e})}async checkByokConfig(e){return this.requireReady(),this.connection.query("check_byok_config",{config:e})}async listPlugins(){return this.requireReady(),(await this.connection.query("list_plugins",{})).plugins}supportsCapability(e){return this.connection.supportsCapability(e)}async validatePlugins(e,n={}){if(this.requireReady(),!Array.isArray(e)||e.length===0||e.some(s=>typeof s!="string"||s.length===0))throw new TypeError("paths must be a non-empty array of non-empty strings");return this.connection.validatePlugins(e,n.configDir)}async getUsageInfo(){this.requireReady();let e=await this.connection.query("get_usage_info",{}),n=kt(e.usage),s=_t(e.session);return!n&&!s?null:{...n??{},...s?{session:s}:{}}}async accountInfo(){return this.requireReady(),(await this.connection.query("account_info",{})).account}stop(){return this.stopPromise||(this.processController.beginStopping(),this.currentState!=="failed"&&this.setDaemonState("stopping"),this.stopPromise=this.stopInternal()),this.stopPromise}async stopInternal(){try{await this.connection.shutdown().catch(()=>{});let{settledAfterSigkill:e}=await this.processController.stop();if(!e)throw new Error("Qoder CLI daemon process did not exit after SIGKILL grace");this.currentState!=="failed"&&this.setDaemonState("stopped")}catch(e){throw this.setDaemonState("failed",e instanceof Error?e:new Error(String(e))),e}}acceptDaemonFailure(e){this.currentState==="ready"&&this.setDaemonState("failed",e),e instanceof De&&this.processController.stop().then(({settledAfterSigkill:n})=>{n||this.diagnostics?.record("[Daemon] heartbeat reclaim: process still present after SIGKILL grace; left to OS")}).catch(n=>{this.diagnostics?.record("[Daemon] heartbeat reclaim: forced stop failed",n)})}setDaemonState(e,n){this.currentState!==e&&(this.currentState=e)}requireReady(){if(this.currentState!=="ready")throw new Error("Daemon is not ready")}};function ru(t){if(typeof t!="string")throw new TypeError("title must be a non-empty string");let e=t.replace(/[\r\n]+/g," ").trim();if(!e)throw new TypeError("title must be a non-empty string");if(e.length>so)throw new TypeError(`title must be at most ${so} characters`);return e}function oo(t){return{localSessionId:t.local_session_id,title:t.title,...t.cwd?{cwd:t.cwd}:{},state:t.state,createdAt:t.created_at,updatedAt:t.updated_at}}var bn=class{constructor(e,n){this.connection=e;this.daemonEnv=n}create(e){let n=new ue({...e,auth:void 0,env:this.daemonEnv}),s=n.buildArgs(),o=uu(s),r=o===void 0?void 0:this.connection.claimSessionId(o);try{return this.connection.createSessionTransport({business:e.business,workerArgs:s,claim:r,cwd:e.cwd??process.cwd(),...e.materializedSessionConfigDir!==void 0?{configDir:e.materializedSessionConfigDir}:{},cleanup:()=>n.cleanupGeneratedSettings()})}catch(i){throw r&&this.connection.releaseSessionClaim(r.sessionId),i}}};function iu(t){let e=t.findIndex(n=>n==="--session-id"||n==="--resume");if(e>=0&&e+1<t.length)return t[e+1];for(let n of t)if(n.startsWith("--session-id="))return n.slice(13)}function au(t){let e=t.findIndex(n=>n==="--session-id");if(e>=0&&e+1<t.length)return t[e+1];for(let n of t)if(n.startsWith("--session-id="))return n.slice(13)}function uu(t){return t.includes("--fork-session")?au(t):iu(t)}function cu(t){if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new TypeError("initializeTimeoutMs must be a positive integer")}function lu(t){if(t!==void 0&&(!Number.isSafeInteger(t)||t<0))throw new TypeError("heartbeatTimeoutMs must be a non-negative integer")}function du(t){let e=t.cause?.code;return e==="ENOEXEC"||e==="EACCES"}async function ro({pathToQoderCLIExecutable:t,executable:e,executableArgs:n,launchMode:s="process",pathToQoderWorkerRuntime:o}){if(s==="worker"){let i=await Me(o??de());return{command:e??process.execPath,args:[...n??[],i.runtimePath,vn],env:{...i.env,...typeof process.versions.electron=="string"?{[to]:"1"}:{}}}}let r=t??Pe();return Re(r)?{command:e??process.execPath,args:[...n??[],r,vn],env:typeof process.versions.electron=="string"?{[to]:"1"}:{}}:{command:r,args:[vn],env:{}}}var At=class t{constructor(e,n){this.process=e;this.stderrHandler=n;this.exited=new Promise(s=>{e.once("exit",()=>s())}),this.closed=new Promise(s=>{e.once("close",()=>s())}),e.stderr?.on("data",s=>{let o=s.toString("utf8");if(this.stderrTail+=o,this.stderrTail.length>no&&(this.stderrTail=this.stderrTail.slice(-no)),!!this.stderrHandler)try{this.stderrHandler(o)}catch{}}),e.on("error",s=>{this.reportFailure(new K(`Failed to spawn Qoder CLI daemon: ${s.message}`,{stderr:this.getStderr(),cause:s}))}),e.once("exit",(s,o)=>{this.exitInfo={code:s,signal:o},!this.stopping&&Je(this.closed,We).then(()=>{if(this.stopping)return;let r=this.getStderr(),i=s!==null?`Qoder CLI daemon exited with code ${s}`:`Qoder CLI daemon terminated by signal ${o}`;this.reportFailure(new K(r?`${i}
|
|
10
10
|
daemon stderr:
|
|
11
11
|
${r}`:i,{exitCode:s,signal:o,stderr:r}))})})}connection;failure;failureListeners=new Set;stderrTail="";exited;closed;exitInfo;stopping=!1;async describeUnexpectedClose(){if(!await Je(this.closed,We))return;let e=this.exitInfo;if(!e)return;let n=this.getStderr(),s=e.code!==null?`Qoder CLI daemon exited with code ${e.code}`:`Qoder CLI daemon terminated by signal ${e.signal}`;return new K(n?`${s}
|
|
12
12
|
daemon stderr:
|
|
13
|
-
${n}`:s,{exitCode:e.code,signal:e.signal,stderr:n})}static async spawn(e){let n;try{n=tu(e.command,e.args,{env:e.env,stdio:["pipe","pipe","pipe"]}),await du(n)}catch(s){throw new K(`Failed to spawn Qoder CLI daemon: ${lu(s)}`,{cause:s})}if(!n.stdin||!n.stdout)throw n.kill("SIGTERM"),new Error("Qoder CLI daemon did not expose piped stdin/stdout");return new t(n,e.stderrHandler)}setConnection(e){this.connection=e,this.failure&&e.fail(this.failure)}onFailure(e){this.failureListeners.add(e),this.failure&&e(this.failure)}beginStopping(){this.stopping=!0}async stop(){return this.beginStopping(),await Je(this.exited,We)?{settledAfterSigkill:!0}:(this.process.kill("SIGTERM"),await Je(this.exited,We)?{settledAfterSigkill:!0}:(this.process.kill("SIGKILL"),{settledAfterSigkill:await Je(this.exited,We)}))}getStderr(){return this.stderrTail.trim()||void 0}reportFailure(e){if(!(this.stopping||this.failure)){this.failure=e,this.connection?.fail(e);for(let n of this.failureListeners)n(e)}}};function lu(t){return t instanceof Error?t.message:String(t)}async function du(t){t.pid===void 0&&await new Promise((e,n)=>{let s=()=>{t.off("error",o),e()},o=r=>{t.off("spawn",s),n(r)};t.once("spawn",s),t.once("error",o)})}function kn(t){if(t.debug!==!0)return nu(Vt(),"logs",`sdk-daemon-${process.pid}-${Date.now()}.log`)}async function Je(t,e){let n;try{return await Promise.race([t.then(()=>!0),new Promise(s=>{n=setTimeout(()=>s(!1),e),n.unref?.()})])}finally{n&&clearTimeout(n)}}var It=class extends Error{constructor(){super("Global daemon is already initialized with different options"),this.name="DaemonConfigurationConflictError"}},ne,D,se,te;function Rn(t){if(te)return te.then(()=>Rn(t));if(ne){if(ne.state==="ready")return oo(t)?(fe(t).record("[GlobalDaemon] init reused the ready daemon"),Promise.resolve(ne)):(fe(t).record("[GlobalDaemon] init rejected: configuration conflict with the ready daemon"),Promise.reject(new It));ne=void 0,D=void 0}return se?oo(t)?(fe(t).record("[GlobalDaemon] init joined an in-flight initialization"),se):(fe(t).record("[GlobalDaemon] init rejected: configuration conflict with an in-flight initialization"),Promise.reject(new It)):(D=t,uo(t,fe(t)))}function Dt(t){let e=Rn(t);return{daemon:new Cn(e,t.proxy),transportProvider:{create:n=>new be(async()=>{let s=await e,o=Ve(s);if(!o)throw new Error("The global daemon is not managed by this SDK instance.");return{transport:o.transportProvider.create(n)}})}}}function uo(t,e){let n;return n=_n(t).then(s=>(ne=s,s.onFailure(o=>pu(o,t)),e.record("[GlobalDaemon] daemon ready"),s)).catch(s=>{throw D=void 0,e.record("[GlobalDaemon] startDaemon failed",s),s}).finally(()=>{se===n&&(se=void 0)}),se=n,n}function pu(t,e){let n=fe(e);n.record(`[GlobalDaemon] active daemon failed: ${t.message}; clearing the slot`,t),ne=void 0,!(te||se)&&(n.record("[GlobalDaemon] eagerly rebuilding the global daemon"),uo(e,n).catch(()=>{}))}function fe(t){return new Z({debug:t.debug,debugFile:t.debugFile??kn(t),stderr:t.stderr})}function mu(){if(te)return te;let t=se,e=ne,n=fe(D??{}),s;return s=(async()=>{let o=e??await t?.catch(()=>{});o?(n.record("[GlobalDaemon] shutting down the global daemon"),await o.stop(),n.record("[GlobalDaemon] global daemon stopped")):n.record("[GlobalDaemon] shutdown with no daemon to stop")})().finally(()=>{te===s&&(ne=void 0,D=void 0,se=void 0,te=void 0)}),te=s,s}function oo(t){return fu(D?.auth,t.auth)&&ao(D?.launchMode)===ao(t.launchMode)&&D?.pathToQoderCLIExecutable===t.pathToQoderCLIExecutable&&D?.executable===t.executable&&hu(D?.executableArgs,t.executableArgs)&&D?.proxy===t.proxy&&D?.noProxy===t.noProxy&&D?.vpcEndpoint===t.vpcEndpoint&&gu(D?.env,t.env)}function fu(t,e){if(t===e)return!0;if(!t||!e||t.type!==e.type)return!1;switch(t.type){case"qodercli":return!0;case"accessToken":return ro(t.accessToken,e.accessToken);case"serviceAccount":{let n=e;return ro(t.serviceAccountKey,n.serviceAccountKey)&&t.fetchServiceAccountToken===n.fetchServiceAccountToken}case"jobToken":return t.fetchJobToken===e.fetchJobToken}}function ro(t,e){return t===e?!0:typeof t=="string"||typeof e=="string"?!1:t?.envVar===e?.envVar}function gu(t,e){if(t===e)return!0;let n=io(t),s=io(e),o=new Set([...Object.keys(n),...Object.keys(s)]);for(let r of o)if(n[r]!==s[r])return!1;return!0}function io(t){let e={};for(let[n,s]of Object.entries(t??{}))s!==void 0&&(e[n]=s);return e}function ao(t){return t??"process"}function hu(t,e){return t===e?!0:t===void 0||e===void 0?!1:t.length===e.length&&t.every((n,s)=>n===e[s])}var Cn=class{constructor(e,n){this.initialization=e;this.initialProxy=n;e.then(s=>{this.resolved=s;for(let o of this.failureListeners)s.onFailure(o)}).catch(()=>{this.failed=!0})}resolved;failed=!1;failureListeners=new Set;get state(){return this.resolved?this.resolved.state:this.failed?"failed":"ready"}ready(){return this.initialization}onFailure(e){this.failureListeners.add(e);let n,s=!0;return this.initialization.then(o=>{s&&(n=o.onFailure(e))}).catch(()=>{}),()=>{s=!1,this.failureListeners.delete(e),n?.()}}async listSessions(e){return(await this.ready()).listSessions(e)}async renameSession(e,n,s){return(await this.ready()).renameSession(e,n,s)}async deleteSession(e,n){await(await this.ready()).deleteSession(e,n)}async setProxy(e,n){return(await this.ready()).setProxy(e,n)}getProxy(){return this.resolved?this.resolved.getProxy():this.initialProxy?.trim()||null}getNoProxy(){return this.resolved?.getNoProxy()??null}async auth(e){return(await this.ready()).auth(e)}async getModels(e){return(await this.ready()).getModels(e)}async getByokConfig(){return(await this.ready()).getByokConfig()}async validateByokModel(e){return(await this.ready()).validateByokModel(e)}async listByokConfigs(){return(await this.ready()).listByokConfigs()}async createByokConfig(e){return(await this.ready()).createByokConfig(e)}async updateByokConfig(e){await(await this.ready()).updateByokConfig(e)}async deleteByokConfig(e){await(await this.ready()).deleteByokConfig(e)}async checkByokConfig(e){return(await this.ready()).checkByokConfig(e)}async listPlugins(){return(await this.ready()).listPlugins()}supportsCapability(e){return this.resolved?.supportsCapability(e)??!1}async validatePlugins(e,n){return(await this.ready()).validatePlugins(e,n)}async getUsageInfo(){return(await this.ready()).getUsageInfo()}async accountInfo(){return(await this.ready()).accountInfo()}async stop(){await(await this.ready()).stop()}};function xt(t,e){let n=t.auth;if(!n)throw new Error("Legacy transport providers require options.auth to execute through the shared daemon.");let s=Dt({auth:n,pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint,env:t.env,stderr:t.stderrHandler,debug:t.debug,launchMode:e.launchMode,pathToQoderWorkerRuntime:e.pathToQoderWorkerRuntime});return we(s.transportProvider,t)}var xe=class t{static default=new t;create(e){return xt(e,{launchMode:"process"})}};var Pn=class extends Error{code="QODER_WORKER_RUNTIME_ERROR";exitCode;stderr;constructor(e,n){super(e,n?.cause?{cause:n.cause}:void 0),this.name="QoderWorkerRuntimeError",this.exitCode=n?.exitCode,this.stderr=n?.stderr}},Oe=class t{constructor(e={}){this.options=e}static default=new t;getPathToQoderWorkerRuntime(){return this.options.pathToQoderWorkerRuntime}create(e){return xt(e,{launchMode:"worker",pathToQoderWorkerRuntime:this.options.pathToQoderWorkerRuntime})}};function yu(){switch("worker"){case"worker":return"worker";case"process":return"process"}return"process"}var Ye=yu();import{performance as co}from"node:perf_hooks";async function Y(t,e,n,s){let o=co.now(),r=i=>{try{t?.recordClose?.({component:e,stage:n,outcome:i,elapsedMs:Math.max(0,Math.round(co.now()-o)),...i==="failed"?{errorCode:"SDK_CLOSE_STAGE_FAILED"}:{}})}catch{}};r("started");try{let i=await s();return r("completed"),i}catch(i){throw r("failed"),i}}import{randomUUID as Iu}from"node:crypto";var lo=["copy_text","helpful","not_helpful","create_branch_task","copy_markdown","add_reply_to_task"];var po=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mo(t){if(!po.test(t.uuid))throw new Error("uuid must be a UUID");if(!t.sessionId.trim())throw new Error("sessionId is required");if(!po.test(t.parentResultUuid))throw new Error("parentResultUuid must be a UUID");if(!lo.includes(t.action))throw new Error("action is not supported");return{type:"feedback",subtype:"action",uuid:t.uuid,action:t.action,session_id:t.sessionId,parent_result_uuid:t.parentResultUuid}}import{isAbsolute as Su}from"node:path";function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xe(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-empty string`);return n}function fo(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string")throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a string`);return n}}function go(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-negative finite number`);return n}}function ho(t,e){let n=t[e];if(!Number.isSafeInteger(n)||n<0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-negative safe integer`);return n}function vu(t){if(!En(t))throw new TypeError("resolveSessionArtifacts result artifacts must contain objects");let e=Xe(t,"path");if(!Su(e))throw new TypeError('resolveSessionArtifacts result field "path" must be absolute');let n=Xe(t,"displayPath"),s=Xe(t,"name"),o=fo(t,"relativePath"),r=fo(t,"mime"),i=go(t,"size"),a=go(t,"mtime"),u;if(t.group!==void 0){if(!En(t.group))throw new TypeError('resolveSessionArtifacts result field "group" must be an object');u={key:Xe(t.group,"key"),name:Xe(t.group,"name")}}let c={path:e,displayPath:n,name:s,...u?{group:u}:{},...o!==void 0?{relativePath:o}:{},...i!==void 0?{size:i}:{},...r!==void 0?{mime:r}:{},...a!==void 0?{mtime:a}:{}};if(t.kind==="presented")return{...c,kind:"presented"};if(t.kind!=="changed")throw new TypeError('resolveSessionArtifacts result field "kind" must be "presented" or "changed"');if(typeof t.isNew!="boolean")throw new TypeError('resolveSessionArtifacts result field "isNew" must be a boolean');return{...c,kind:"changed",additions:ho(t,"additions"),deletions:ho(t,"deletions"),isNew:t.isNew}}function yo(t){if(!En(t)||!Array.isArray(t.artifacts))throw new TypeError("resolveSessionArtifacts must return an object with an artifacts array");return{artifacts:t.artifacts.map(vu)}}var Tn="1.5.0";var wu=new Set(["default","acceptEdits","auto","bypassPermissions"]);function Ze(t){if(t===void 0)return;if(t==="yolo")return"bypassPermissions";if(typeof t=="string"&&wu.has(t))return t;if(t==="plan")throw new Error('permissionMode="plan" is not supported for daemon Queries; use planMode or setPlanMode() instead.');let e=typeof t=="string"?JSON.stringify(t):t===null?"null":typeof t;throw new Error(`permissionMode=${e} is not supported for daemon Queries; use default, acceptEdits, auto, or bypassPermissions.`)}function et(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`goalMaxTurns must be a positive safe integer, received ${String(t)}.`)}function So(t,e,n,s){return new Promise((o,r)=>{if(!("id"in e&&e.id!==null)){try{n.onmessage?.(e)}catch(u){r(u);return}o({jsonrpc:"2.0"});return}let a=`${t}:${e.id}`;s.set(a,{resolve:o,reject:r}),n.onmessage?n.onmessage(e):(s.delete(a),r(new Error(`No message handler registered for MCP server "${t}"`)))})}function vo(t,e,n){if("id"in e&&e.id!==null){let s=`${t}:${e.id}`,o=n.get(s);if(o)return o.resolve(e),n.delete(s),!0}return!1}function wo(t,e,n){let s=0,o=`${t}:`,r=Array.from(n.entries());for(let i of r){let[a,u]=i;a.startsWith(o)&&(u.reject(e),n.delete(a),s++)}return s}import{randomUUID as bu}from"crypto";function ko(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.type==="transcript_mirror"&&typeof e.filePath=="string"&&Array.isArray(e.entries)}var _u=500,ku=1024*1024,Cu=6e4,Ot=class{constructor(e){this.options=e;this.holding=e.holdUntilFlush===!0}states=new Map;failures=[];holding;receivedEntryCount=0;enqueue(e){let n=Ru(e.filePath),s=Pu(e.entries);this.receivedEntryCount+=s.length;let o=_o(n),r=this.states.get(o);r||(r={key:n,entries:[],bytes:0,tail:Promise.resolve()},this.states.set(o,r)),r.entries.push(...s),r.bytes+=Tu(s),!this.holding&&(this.options.flushMode==="eager"||r.entries.length>=_u||r.bytes>=ku)&&this.drain(r)}async flush(e={}){for(let n of this.states.values())this.drain(n);if(await Promise.all([...this.states.values()].map(n=>n.tail)),e.throwOnError===!0&&this.failures.length>0)throw new AggregateError(this.failures,`SessionStore failed to persist ${this.failures.length} transcript mirror batch(es).`)}async completeBarrier(){if(this.receivedEntryCount===0)throw new Error("SessionStore Fork persistence barrier received no transcript entries.");await this.flush({throwOnError:!0}),this.holding=!1}discardPending(){for(let e of this.states.values())e.entries=[],e.bytes=0}drain(e){if(e.entries.length===0)return;let n=e.entries;e.entries=[],e.bytes=0,e.tail=e.tail.then(async()=>{try{await Mu(this.options.store,e.key,n,this.options.appendTimeoutMs??Cu)}catch(s){this.failures.push(s),this.options.diagnostics?.record(`[SessionStore] append failed for ${_o(e.key)}`,s),this.options.onMirrorError({type:"system",subtype:"mirror_error",error:s instanceof Error?s.message:String(s),key:{...e.key},uuid:bu(),session_id:e.key.sessionId})}})}};function Ru(t){let e=t.replaceAll("\\","/").split("/").filter(Boolean),n=e.lastIndexOf("projects"),s=e.slice(n+1);if(n<0||s.length<2)throw new Error(`Invalid transcript mirror path: ${t}`);let o=s[0],r=/^([0-9a-f-]{36})\.jsonl$/i.exec(s[1]);if(s.length===2&&r)return{projectKey:o,sessionId:bo(r[1])};let i=bo(s[1]),a=s.slice(2),u=a.at(-1);a[a.length-1]=u.endsWith(".jsonl")?u.slice(0,-6):u;let c=a.join("/");return Eu(c),{projectKey:o,sessionId:i,subpath:c}}function Pu(t){return t.map((e,n)=>{if(typeof e!="object"||e===null||typeof e.type!="string")throw new Error(`Transcript mirror entry ${n} is not a typed object`);return e})}function bo(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new Error(`Invalid transcript session id: ${t}`);return t}function Eu(t){let e=t.split("/");if(!t||t.includes("\0")||/^[a-z]:/i.test(t)||e.some(n=>!n||n==="."||n===".."))throw new Error(`Invalid transcript subpath: ${t}`)}function _o(t){return JSON.stringify([t.projectKey,t.sessionId,t.subpath??null])}function Tu(t){return t.reduce((e,n)=>e+Buffer.byteLength(JSON.stringify(n))+1,0)}async function Mu(t,e,n,s){await Au(t.append({...e},structuredClone(n)),s)}async function Au(t,e){let n;t.catch(()=>{});try{await Promise.race([t,new Promise((s,o)=>{n=setTimeout(()=>o(new Mn(e)),e)})])}finally{n!==void 0&&clearTimeout(n)}}var Mn=class extends Error{constructor(e){super(`SessionStore append timed out after ${e}ms`),this.name="SessionStoreTimeoutError"}};function Co(){return Math.random().toString(36).substring(2,15)}function Ro(t,e){let n="type"in e&&!("subtype"in e)?{...e,subtype:e.type}:e;return{type:"control_request",request_id:t,request:n}}function Po(t,e){return{type:"control_response",response:{subtype:"success",request_id:t,response:e}}}function Eo(t,e,n){return{type:"control_response",response:{subtype:"error",request_id:t,error:e,...n?{code:n}:{}}}}function To(t){return typeof t=="object"&&t!==null&&t.type==="control_response"}function Mo(t){return typeof t=="object"&&t!==null&&t.type==="control_request"}function Ao(t){return typeof t=="object"&&t!==null&&(t.type==="control_cancel_request"||t.type==="control_cancel")}function tt(t){if(typeof t!="object"||t===null)return;let e=t,n=e.subtype;if(typeof n=="string")return n;let s=e.type;return typeof s=="string"?s:void 0}function Io(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return e==="keepalive"||e==="keep_alive"}function Do(t){return typeof t=="object"&&t!==null&&t.type==="streamlined_text"}function xo(t){return typeof t=="object"&&t!==null&&t.type==="streamlined_tool_use_summary"}function Oo(t){return typeof t=="object"&&t!==null&&t.type==="post_turn_summary"}function qo(t){return typeof t=="object"&&t!==null&&t.type==="result"}var Du="<synthetic>";function xu(t){return t.type!=="assistant"||t.isApiErrorMessage===!0||t.message.model!==Du?t:{...t,isApiErrorMessage:!0}}function No(t){if(!t)return null;let e=t.trim();return e?e.startsWith("socks5h:")?`socks5:${e.slice(8)}`:e:null}var qt=class t{constructor(e,n,s,o,r,i,a,u,c,d,m,p,l,f,S,g,v,b="batched",y,A,I,re,C,U,ie=!1,ut,Ht){this.hostActionDirect=ie;if(this.transport=e,this.isSingleTurn=n,this.canUseTool=s,this.hooks=o??{},this.abortController=r,this.sdkMcpServers=i??new Map,this.sdkMcpTransports=p??new Map,this.pendingMcpResponses=l??new Map,this.sdkMcpToolOverrides=y??{},this.initConfig=a??{},this.onElicitation=u,this.onAuthExpired=d,this.fetchJobToken=f,this.fetchServiceAccountToken=A,this.diagnostics=c,this.controlRequestTimeoutMs=m??6e4,this.resolveModel=S,this.resolveModelTimeoutMs=g??500,this.memoryCallbacks=I,this.skillEvolutionCallbacks=re,this.hostActionFallback=U,this.resolveSessionArtifacts=C,this.daemonAccountQueries=ut,this.daemonProxyProvider=Ht,this.inputStream=new ee(()=>{this.close().catch(()=>{})}),v&&(this.transcriptMirrorBatcher=new Ot({store:v,flushMode:b,holdUntilFlush:this.initConfig.requireSessionStoreForkBarrier===!0,diagnostics:c,onMirrorError:X=>this.inputStream.enqueue(X)})),this.readLoopPromise=this.readMessages().catch(X=>{this.inputStream.error(X)}),this.initializationPromise=this.startInitialization(),this.initializationPromise.catch(()=>{}),this.abortController){let X=this.abortController.signal,ct=()=>{this.failInitialization(new E),this.close().catch(()=>{})};X.aborted?ct():X.addEventListener("abort",ct,{once:!0})}}static CUSTOM_CONTEXT_CAPABILITY="custom_context_v1";static SELECTED_SKILLS_CAPABILITY="selected_skills_v1";static INITIALIZE_TIMEOUT_MS=12e4;static BACKGROUND_TASKS_CAPABILITY="background_tasks_v1";static SIDE_QUESTION_CAPABILITY="side_question_v1";static GOAL_CAPABILITY="goal_v1";static GOAL_RESUME_CAPABILITY="goal_resume_v1";static GOAL_MAX_TURNS_CAPABILITY="goal_max_turns_v1";static PLAN_MODE_CAPABILITY="plan_mode_v1";static SESSION_STORE_FORK_BARRIER_CAPABILITY="session_store_fork_barrier_v1";static HOST_ACTION_CAPABILITY="host_action";static BYOK_CONFIG_MANAGEMENT_CAPABILITY="byok_config_management_v1";static REMOTE_PROJECTION_REQUEST_ID_PREFIX="daemon_worker_sdk_";transport;inputStream;pendingRequests=new Map;pendingInboundRequests=new Map;hooks;hookCallbacks=new Map;nextHookCallbackId=0;sdkMcpServers;sdkMcpTransports;pendingMcpResponses;sdkMcpToolOverrides;isSingleTurn;canUseTool;abortController;initConfig;onElicitation;onAuthExpired;fetchJobToken;fetchServiceAccountToken;diagnostics;controlRequestTimeoutMs;resolveModel;resolveModelTimeoutMs;transcriptMirrorBatcher;memoryCallbacks;skillEvolutionCallbacks;hostActionFallback;resolveSessionArtifacts;daemonAccountQueries;daemonProxyProvider;resolveStreamInitialization;initResponse;latestCommands=[];initializationPromise;rejectInitialization;resultMessage;pendingErrorResultExit=!1;readLoopPromise;closed=!1;authExpiredFired=!1;protocolHandshakeValidated=!1;cliCapabilities;customContextCapabilityWarningEmitted=!1;firstResultReceived=!1;sdkStartupTimingSent=!1;firstResultReceivedResolve;memoryFlushPromise;endInputFlushPromise;skillEvolutionFlushPromise;closePromise;sessionStoreForkBarrierComplete=!1;inputEnded=!1;getRecord(e){return typeof e=="object"&&e!==null?e:void 0}normalizeLogPreview(e){let s=e.replace(/\s+/g," ").trim();return s.length>200?`${s.slice(0,200)}...`:s}extractMessagePreview(e){if(typeof e=="string")return this.normalizeLogPreview(e);if(Array.isArray(e)){for(let i of e){let a=this.extractMessagePreview(i);if(a)return a}return""}let n=this.getRecord(e);if(!n)return"";let s=n.text;if(typeof s=="string")return this.normalizeLogPreview(s);let o=this.extractMessagePreview(n.content);if(o)return o;let r=this.getRecord(n.message);return r?this.extractMessagePreview(r):""}getMessagePreviewSuffix(e){let n=this.extractMessagePreview(e);return n?` preview=${JSON.stringify(n)}`:""}getMessageType(e){let s=this.getRecord(e)?.type;return typeof s=="string"&&s?s:"unknown"}getMessageSubtype(e){let s=this.getRecord(e)?.subtype;return typeof s=="string"&&s?s:"none"}getMessageUuid(e){let s=this.getRecord(e)?.uuid;return typeof s=="string"&&s?s:"none"}recordInboundSessionMessage(e){this.diagnostics?.record(`[QueryRunner] inbound session_message received type=${this.getMessageType(e)} subtype=${this.getMessageSubtype(e)} uuid=${this.getMessageUuid(e)}${this.getMessagePreviewSuffix(e)}`)}recordOutboundSessionMessage(e){let n=this.getRecord(e)?.message,o=this.getRecord(n)?.content,r=Array.isArray(o)?o.length:0;this.diagnostics?.record(`[QueryRunner] outbound session_message sent type=${this.getMessageType(e)} uuid=${this.getMessageUuid(e)} content_blocks=${r}${this.getMessagePreviewSuffix(e)}`)}[Symbol.asyncIterator](){return this}async next(){return this.inputStream.next()}async return(){return await this.close(),{done:!0,value:void 0}}async throw(e){return await this.inputStream.throw(e),{done:!0,value:void 0}}async readMessages(){let e;try{for await(let n of this.transport.readMessages()){if(this.closed)break;if(ko(n)){try{this.transcriptMirrorBatcher?.enqueue(n)}catch(o){this.diagnostics?.record("[QueryRunner] invalid transcript_mirror frame ignored:",o)}continue}if(To(n)){this.handleControlResponse(n);continue}if(Mo(n)){this.handleControlRequest(n).catch(o=>{this.diagnostics?.record("[QueryRunner] Error handling control request:",o)});continue}if(Ao(n)){this.handleControlCancelRequest(n);continue}if(Io(n)||Do(n)||xo(n)||Oo(n))continue;if(qo(n)){await this.transcriptMirrorBatcher?.flush();let o=n;if(this.recordInboundSessionMessage(o),this.resultMessage=o,this.pendingErrorResultExit=this.resultMessage.is_error===!0,this.firstResultReceived=!0,this.firstResultReceivedResolve?.(),this.firstResultReceivedResolve=void 0,this.inputStream.enqueue(o),this.rejectInitialization&&this.resultMessage.is_error===!0){let r=this.resultMessage.terminal_reason;this.failInitialization(this.abortController?.signal.aborted||this.closed||r==="aborted_streaming"||r==="aborted_tools"||r==="abort"?new E:new ke(this.resultMessage))}this.isSingleTurn&&this.flushBeforeEndInput();continue}let s=xu(n);if((s.type==="user"||s.type==="assistant")&&(this.pendingErrorResultExit=!1),this.recordInboundSessionMessage(s),s.type==="system"&&s.subtype==="init")try{let o=s;this.validateProtocolHandshake(o),this.cliCapabilities=new Set(o.capabilities??[]);let r=o.commands;r!==void 0&&this.replaceLatestCommands(r),this.resolveStreamInitialization&&(this.initResponse=o,this.resolveStreamInitialization(this.initResponse),this.resolveStreamInitialization=void 0)}catch(o){throw this.inputStream.error(o),o}s.type==="system"&&s.subtype==="commands_changed"&&this.replaceLatestCommands(s.commands),this.dispatchMemoryCallbacks(s),this.dispatchSkillEvolutionCallbacks(s),this.notifyAuthExpiredIfNeeded(s),this.inputStream.enqueue(s)}}catch(n){this.isStructuredResultExit(n)?this.diagnostics?.record("[QueryRunner] exit code 1 accepted after the latest structured error result"):e=n}finally{await this.flushTranscriptMirrorForLifecycle();let n=e instanceof Error?e:new Error("Transport closed");this.failInitialization(n),this.firstResultReceivedResolve?.(),this.firstResultReceivedResolve=void 0;for(let[,s]of this.pendingRequests)s.reject(n);this.pendingRequests.clear(),e!==void 0?this.inputStream.error(e):this.inputStream.done()}}isStructuredResultExit(e){if(!this.pendingErrorResultExit||e===null||typeof e!="object")return!1;let n=e;return n.exitCode===1&&(n.signal===void 0||n.signal===null)}notifyAuthExpiredIfNeeded(e){if(!this.onAuthExpired||this.authExpiredFired)return;let s=e.type==="auth_status"&&!!e.error,o=e.type==="assistant"&&e.error==="authentication_failed";!s&&!o||(this.authExpiredFired=!0,Promise.resolve(this.onAuthExpired()).catch(r=>{this.diagnostics?.record("[QueryRunner] onAuthExpired callback threw:",r)}))}dispatchMemoryCallbacks(e){if(!(e.type!=="system"||!this.memoryCallbacks))try{let n;e.subtype==="memory_generation"?n=this.memoryCallbacks.onGenerationResult?.(e.result):e.subtype==="memory_consumption"&&(n=this.memoryCallbacks.onConsumptionResult?.(e.result)),n!==void 0&&Promise.resolve(n).catch(s=>{this.diagnostics?.record("[QueryRunner] memory callback threw:",s)})}catch(n){this.diagnostics?.record("[QueryRunner] memory callback threw:",n)}}dispatchSkillEvolutionCallbacks(e){if(!(e.type!=="system"||e.subtype!=="skill_evolution"||!this.skillEvolutionCallbacks))try{let n=this.skillEvolutionCallbacks.onResult?.(e.result);n!==void 0&&Promise.resolve(n).catch(s=>this.diagnostics?.record("[QueryRunner] skill evolution callback threw:",s))}catch(n){this.diagnostics?.record("[QueryRunner] skill evolution callback threw:",n)}}flushBeforeEndInput(){return this.endInputFlushPromise||(this.endInputFlushPromise=this.performFlushBeforeEndInput()),this.endInputFlushPromise}async performFlushBeforeEndInput(){try{let e=[];this.initConfig.memory!==void 0&&e.push(Y(this.diagnostics,"query","memory_flush",()=>this.flushMemory())),this.initConfig.evolution?.skill!==void 0&&e.push(Y(this.diagnostics,"query","skill_flush",()=>this.flushSkillEvolution()));let s=(await Promise.allSettled(e)).find(o=>o.status==="rejected");if(s)throw s.reason}catch(e){this.diagnostics?.record("[QueryRunner] post-turn flush before end input failed:",e)}finally{this.endTransportInput()}}endTransportInput(){this.inputEnded||(this.inputEnded=!0,this.transport.endInput())}async request(e,n){if(n?.signal?.aborted)throw new E;let s=`${n?.requestIdPrefix??""}${Co()}`,o=Ro(s,e),r=n?.timeoutMs??this.controlRequestTimeoutMs,i=tt(o.request)??"unknown",a=Date.now();return new Promise((u,c)=>{let d=null,m=()=>{try{this.transport.write(JSON.stringify({type:"control_cancel_request",request_id:s})+`
|
|
14
|
-
`)}catch(f){this.diagnostics?.record("[QueryRunner] Failed to send control_cancel_request:",f)}},p=()=>{
|
|
15
|
-
`),this.diagnostics?.record(`[QueryRunner] control_request sent request_id=${s} subtype=${i}`)}catch(f){p(),this.pendingRequests.delete(s),this.diagnostics?.record(`[QueryRunner] control_request send failed request_id=${s} subtype=${i}`,f),c(f)}})}handleControlResponse(e){let n=e.response,s=n.request_id,o=this.pendingRequests.get(s);if(!o){this.diagnostics?.record(`[QueryRunner] unmatched control_response received request_id=${s} status=${n.subtype}`);return}if(this.pendingRequests.delete(s),n.subtype==="success")o.resolve(n.response);else{let r=new Ce({requestId:s,message:n.error,code:n.code,retryable:n.retryable,details:n.details});o.reject(r),this.processPendingPermissionRequests(n.pending_permission_requests)}}processPendingPermissionRequests(e){if(e)for(let n of e)
|
|
16
|
-
`),this.diagnostics?.record(`[QueryRunner] inbound control_response sent request_id=${n} subtype=${s} status=success duration_ms=${Date.now()-o}`)}}catch(i){if(!r.signal.aborted){let{error:a,code:u}=
|
|
17
|
-
`),this.diagnostics?.record(`[QueryRunner] inbound control_response sent request_id=${n} subtype=${s} status=error duration_ms=${Date.now()-o}`,i)}}finally{this.pendingInboundRequests.delete(n)}}handleControlCancelRequest(e){let n=this.pendingInboundRequests.get(e.request_id);n&&(n.abortController.abort(),this.pendingInboundRequests.delete(e.request_id))}throwIfAborted(e){if(e.aborted)throw new E}validateProtocolHandshake(e){if(this.protocolHandshakeValidated)return;this.protocolHandshakeValidated=!0;let n=e.protocol_version,s=Tn;if(!n){this.diagnostics?.record(`[QueryRunner] CLI did not announce protocol_version. This SDK was built for ${s}. Consider upgrading qodercli for the version handshake.`);return}let o=jo(n),r=jo(s);if(!o||!r){this.diagnostics?.record(`[QueryRunner] Could not parse protocol_version "${n}" or built-in "${s}"; skipping handshake.`);return}if(o.major!==r.major)throw new V(n,s);o.minor<r.minor&&this.diagnostics?.record(`[QueryRunner] CLI protocol_version ${n} is older than this SDK's ${s}. New optional fields may be absent.`)}async awaitAbortable(e,n){if(n.aborted)throw new E;return new Promise((s,o)=>{let r=()=>{o(new E)};n.addEventListener("abort",r,{once:!0}),e.then(i=>{n.removeEventListener("abort",r),s(i)},i=>{n.removeEventListener("abort",r),o(i)})})}async processControlRequest(e,n){this.throwIfAborted(n);let s=e.request,o=tt(s),r=s;switch(o){case"resolve_session_artifacts":{if(!this.resolveSessionArtifacts)throw new Error("resolve_session_artifacts_unavailable: No resolveSessionArtifacts callback configured");let i=r.local_session_id,a=r.cwd;if(typeof i!="string"||i.length===0||typeof a!="string"||a.length===0)throw new TypeError("resolve_session_artifacts requires local_session_id and cwd");let u=await this.awaitAbortable(Promise.resolve().then(()=>this.resolveSessionArtifacts(i,a)),n);return yo(u)}case"fetch_job_token":{if(!this.fetchJobToken)throw new Error("job_token_unavailable: No fetchJobToken callback configured");let i=r.reason??"initial",a=r.session_id,u=e.request_id,c=await this.awaitAbortable(this.fetchJobToken({requestId:u,reason:i,sessionId:a},{signal:n}),n);if(!c?.token)throw new Error("job_token_unavailable: Host did not provide a Job Token");let d=c.expiresAt;if(d!==void 0&&(!Number.isFinite(d)||d<1e12))throw new Error("job_token_unavailable: expiresAt must be a Unix timestamp in milliseconds");return this.diagnostics?.record(`[QueryRunner] fetch_job_token fulfilled: reason=${i}`),{token:c.token,...d!==void 0?{expires_at:d}:{}}}case"fetch_service_account_token":{if(!this.fetchServiceAccountToken)throw new Error("service_account_token_unavailable: No fetchServiceAccountToken callback configured");let i=await this.awaitAbortable(this.fetchServiceAccountToken(),n);if(!i?.token)throw new Error("service_account_token_unavailable: Host did not provide a Service Account token");let a=i.expiresAt;if(a!==void 0&&(!Number.isFinite(a)||a<1e12))throw new Error("service_account_token_unavailable: expiresAt must be a Unix timestamp in milliseconds");return this.diagnostics?.record("[QueryRunner] fetch_service_account_token fulfilled"),{token:i.token,...a!==void 0?{expires_at:a}:{}}}case"can_use_tool":{let i=r.tool_name,a=r.input??{};if(!this.canUseTool)throw new Error("canUseTool callback is not provided.");let u=r.tool_use_id,c=r.permission_suggestions??r.suggestions,d=r.blocked_path,m=r.decision_reason,p=r.title,l=r.display_name,f=r.description,S=r.agent_id,g=r.permission_kind,v=r.options,b=r.details,y=await this.awaitAbortable(this.canUseTool(i,a,{signal:n,suggestions:c,blockedPath:d,decisionReason:m,title:p,displayName:l,description:f,toolUseID:u,agentID:S,permissionKind:g,permissionOptions:v,details:b}),n);if(y.behavior==="deny"&&!y.message)throw new Error("Permission deny result must include a message.");return y.behavior==="allow"?{...y,updatedInput:y.updatedInput??a,toolUseID:u}:{...y,toolUseID:u}}case"hook_callback":{let i=r.callback_id;if(!i)throw new Error("Hook callback missing callback_id");return this.invokeRegisteredHookCallback(i,r.input,r.tool_use_id,n)}case"memory_should_generate":{let i=r.callbackId;if(!i)throw new Error("Memory shouldGenerate request missing callbackId");let a=this.memoryCallbacks?.shouldGenerateCallbacks.get(i);if(!a)throw new Error(`Unknown memory shouldGenerate callback: ${i}`);let u=await this.awaitAbortable(a(r.input,{signal:n}),n);if(!u||typeof u.run!="boolean")throw new TypeError("Memory shouldGenerate callback must return { run: boolean }");return{run:u.run,...typeof u.reason=="string"?{reason:u.reason}:{}}}case"skill_evolution_should_review":{let i=r.callbackId;if(!i)throw new Error("Skill evolution shouldReview request missing callbackId");let a=this.skillEvolutionCallbacks?.shouldReviewCallbacks.get(i);if(!a)throw new Error(`Unknown skill evolution shouldReview callback: ${i}`);let u=await this.awaitAbortable(a(r.input,{signal:n}),n);if(!u||typeof u.run!="boolean")throw new TypeError("Skill evolution shouldReview callback must return { run: boolean }");return{run:u.run,...typeof u.reason=="string"?{reason:u.reason}:{}}}case"mcp_message":{let i=r.server_name,a=r.message,u=this.sdkMcpTransports.get(i);if(!u)throw new Error(`Unknown in-process MCP server: ${i}`);return{mcp_response:await this.awaitAbortable(So(i,a,u,this.pendingMcpResponses),n)}}case"elicitation":case"elicitation_response":return this.onElicitation?await this.awaitAbortable(this.onElicitation({serverName:r.mcp_server_name??"",message:r.message??r.prompt??"",mode:r.mode,url:r.url,elicitationId:r.elicitation_id,requestedSchema:r.requested_schema,title:r.title,displayName:r.display_name,description:r.description},{signal:n}),n):{action:"cancel"};case"get_model_policy":{if(!this.resolveModel)return{type:"get_model_policy"};let i={purpose:r.purpose,sessionId:r.sessionId,turnIndex:r.turnIndex,agentId:r.agentId,agentType:r.agentType,resolvedModel:r.resolvedModel,availableModels:r.models??[]},a=this.resolveModelTimeoutMs,u=Promise.resolve(this.resolveModel(i)),c,d=new Promise((g,v)=>{c=setTimeout(()=>{v(new Le(a))},a)}),m;try{m=await this.awaitAbortable(Promise.race([u,d]),n)}finally{clearTimeout(c)}let p={type:"get_model_policy",...m?.parameters!==void 0?{parameters:m.parameters}:{}},l=m?.model;if(typeof l=="string")p.model=l;else if(l!==void 0){let{model:g,...v}=l;p.model=g,p.custom_model={...v,style:v.style??"openai"}}let f=m?.taskId?.trim();f&&(p.task_id=f);let S=m?.subTask?.trim();return S&&(p.sub_task=S),p}default:throw new Error(`Unhandled control request subtype: ${o??"unknown"}`)}}async initialize(){return this.initializationPromise||(this.initializationPromise=this.startInitialization()),this.initializationPromise}startInitialization(){let e=new Promise((s,o)=>{this.rejectInitialization=o}),n=this.initConfig.resolveInitializationFromStream?this.waitForStreamInitialization():this.performInitialize();return Promise.race([n,e]).then(s=>(this.rejectInitialization=void 0,this.initResponse=s,this.cliCapabilities=new Set(s.capabilities??[]),s),s=>{throw this.rejectInitialization=void 0,s})}failInitialization(e){let n=this.rejectInitialization;if(n){this.rejectInitialization=void 0,n(e);for(let s of this.pendingRequests.values())s.reject(e);this.pendingRequests.clear()}}async performInitialize(){await this.initConfig.beforeInitialize?.();let e={type:"initialize",modelPolicyProvider:this.resolveModel!==void 0,supportsCatalogReadyInitialize:!0,supportsAvailableModelsUpdate:!0,supportsCommandsChanged:!0,initializeTimeoutMs:t.INITIALIZE_TIMEOUT_MS},n={};for(let[o,r]of Object.entries(this.hooks)){if(!r||r.length===0)continue;let i=[];for(let a of r){let u=a.hooks.map(c=>{let d=`hook_${this.nextHookCallbackId++}`;return this.hookCallbacks.set(d,c),d});u.length!==0&&i.push({matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout})}i.length>0&&(n[o]=i)}if(Object.keys(n).length>0&&(e.hooks=n),this.initConfig.systemPrompt!==void 0&&(e.systemPrompt=this.initConfig.systemPrompt),this.initConfig.appendSystemPrompt!==void 0&&(e.appendSystemPrompt=this.initConfig.appendSystemPrompt),this.initConfig.modelRequestPatches!==void 0&&(e.modelRequestPatches=this.initConfig.modelRequestPatches),this.initConfig.agents&&(e.agents=this.initConfig.agents),this.initConfig.skills!==void 0&&(e.skills=this.initConfig.skills),this.initConfig.includeShellProgress===!0&&(e.includeShellProgress=!0),this.initConfig.promptSuggestions!==void 0&&(e.promptSuggestions=this.initConfig.promptSuggestions),this.initConfig.hostActions!==void 0&&(e.hostActions=this.initConfig.hostActions),this.initConfig.enableFileCheckpointing!==void 0&&(e.enableFileCheckpointing=this.initConfig.enableFileCheckpointing),this.initConfig.independentPlanModeControls===!0){e.independentPlanModeControls=!0;let o=Ze(this.initConfig.permissionMode);o!==void 0&&(e.permissionMode=o)}this.initConfig.memory!==void 0&&(e.memory=this.initConfig.memory),this.initConfig.evolution!==void 0&&(e.evolution=this.initConfig.evolution),this.resolveSessionArtifacts!==void 0&&(e.resolveSessionArtifacts=!0),this.sdkMcpServers.size>0&&(e.sdkMcpServers=Array.from(this.sdkMcpServers.keys()),Object.keys(this.sdkMcpToolOverrides).length>0&&(e.sdkMcpToolOverrides=this.sdkMcpToolOverrides));let s=await this.request(e,{timeoutMs:t.INITIALIZE_TIMEOUT_MS});if(s&&typeof s=="object"){let o=s;this.initResponse=o,this.replaceLatestCommands(o.commands),this.cliCapabilities=new Set(o.capabilities??[])}if(!this.initResponse)throw new Error("Failed to receive initialization response");if(this.initConfig.goalMaxTurns!==void 0&&!this.cliCapabilities?.has(t.GOAL_MAX_TURNS_CAPABILITY))throw new L(t.GOAL_MAX_TURNS_CAPABILITY);if(this.initConfig.hostActions!==void 0&&!this.cliCapabilities?.has(t.HOST_ACTION_CAPABILITY))throw new L(t.HOST_ACTION_CAPABILITY);if(this.initConfig.planMode!==void 0){if(!this.cliCapabilities?.has(t.PLAN_MODE_CAPABILITY))throw new L(t.PLAN_MODE_CAPABILITY);let o={subtype:"set_plan_mode",active:this.initConfig.planMode};await this.request(o)}return await this.completeSessionStoreForkBarrier(),this.initResponse}async completeSessionStoreForkBarrier(){if(this.initConfig.requireSessionStoreForkBarrier!==!0)return;if(!this.cliCapabilities?.has(t.SESSION_STORE_FORK_BARRIER_CAPABILITY))throw new L(t.SESSION_STORE_FORK_BARRIER_CAPABILITY);let e=this.transcriptMirrorBatcher;if(!e)throw new Error("SessionStore Fork persistence barrier requires a transcript mirror.");await e.completeBarrier(),this.sessionStoreForkBarrierComplete=!0}async flushTranscriptMirrorForLifecycle(){if(this.initConfig.requireSessionStoreForkBarrier===!0&&!this.sessionStoreForkBarrierComplete){this.transcriptMirrorBatcher?.discardPending();return}await this.transcriptMirrorBatcher?.flush()}async invokeRegisteredHookCallback(e,n,s,o){let r=this.hookCallbacks.get(e);if(!r)throw new Error(`Unknown hook callback: ${e}`);return await this.awaitAbortable(r(n,s,{signal:o}),o)??{continue:!0}}async initializationResult(){return this.initialize()}replaceLatestCommands(e){this.latestCommands=(e??[]).map(n=>({...n}))}getLatestCommands(){return this.latestCommands.map(e=>({...e}))}waitForStreamInitialization(){return new Promise(e=>{this.resolveStreamInitialization=e})}async streamInput(e){(async()=>{let n,s=!1;try{n=e[Symbol.asyncIterator]();let o=async()=>{let a=await n.next();return s=a.done===!0,{...a,submittedAtMs:Date.now()}},[,r]=await Promise.all([this.initialize(),o()]),i=0;for(;!r.done;r=await o()){let a=r.value,u=r.submittedAtMs;if(this.closed)break;i+=1;let d=Object.prototype.hasOwnProperty.call(a,"custom_context")?a.custom_context:this.initConfig.customContext,m=typeof a.uuid=="string"&&a.uuid.trim().length>0?a.uuid:Iu(),p={...a,uuid:m,extra:{...!this.sdkStartupTimingSent&&this.initConfig.sdkStartedAtMs!==void 0?{started_at_ms:this.initConfig.sdkStartedAtMs}:{},submitted_at_ms:u,...a.extra},...d===void 0?{}:{custom_context:d}};if(this.pendingErrorResultExit=!1,p.selected_skills!==void 0&&p.selected_skills.length>0&&!this.cliCapabilities?.has(t.SELECTED_SKILLS_CAPABILITY))throw new L(t.SELECTED_SKILLS_CAPABILITY);d!==void 0&&!this.cliCapabilities?.has(t.CUSTOM_CONTEXT_CAPABILITY)&&!this.customContextCapabilityWarningEmitted&&(this.customContextCapabilityWarningEmitted=!0,this.diagnostics?.record("[QueryRunner] custom_context requested but paired CLI does not advertise custom_context_v1; the field may be ignored"));try{await this.transport.write(JSON.stringify(p)+`
|
|
18
|
-
`)}catch(
|
|
19
|
-
`);return}catch(s){this.diagnostics?.record("[QueryRunner] active Host action transport failed; using fallback:",s)}if(!this.hostActionFallback)throw new Error("Host action transport is no longer writable");await this.hostActionFallback(n)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).cancelled}async stopTask(e){await this.requireCliCapability(t.BACKGROUND_TASKS_CAPABILITY),await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){await this.requireCliCapability(t.BACKGROUND_TASKS_CAPABILITY);let n=await this.request({subtype:"background_tasks",tool_use_id:e});return typeof n?.backgrounded=="boolean"?n.backgrounded:!0}async setGoal(e){await this.requireCliCapability(t.GOAL_CAPABILITY);let n={subtype:"set_goal"};e.objective!==void 0&&(n.objective=e.objective),e.status!==void 0&&(n.status=e.status),e.creditsBudget!==void 0&&(n.credits_budget=e.creditsBudget);let s=e.customContext??this.initConfig.customContext;return s!==void 0&&(n.custom_context=s),(await this.request(n))?.goal??null}async setGoalMaxTurns(e){e!==null&&et(e),await this.requireCliCapability(t.GOAL_MAX_TURNS_CAPABILITY);let n={subtype:"set_goal_max_turns",max_turns:e},s=await this.request(n);return et(s.goal_max_turns),s.goal_max_turns}async resumeGoal(){await this.requireCliCapability(t.GOAL_RESUME_CAPABILITY);let e={subtype:"resume_goal"};return(await this.request(e))?.goal??null}async getGoal(){await this.requireCliCapability(t.GOAL_CAPABILITY);let e={subtype:"get_goal"};return(await this.request(e))?.goal??null}async clearGoal(){await this.requireCliCapability(t.GOAL_CAPABILITY);let e={subtype:"clear_goal"};return(await this.request(e))?.cleared===!0}async setPlanMode(e){await this.requireCliCapability(t.PLAN_MODE_CAPABILITY);let n={subtype:"set_plan_mode",active:e};return(await this.request(n)).plan_mode}async getPlanMode(){await this.requireCliCapability(t.PLAN_MODE_CAPABILITY);let e={subtype:"get_plan_mode"};return(await this.request(e)).plan_mode}async requireCliCapability(e){if(await this.initializationResult(),!this.cliCapabilities?.has(e))throw new L(e)}async setPermissionMode(e){let n=this.initConfig.independentPlanModeControls===!0?Ze(e):e==="yolo"?"bypassPermissions":e;if(n===void 0)throw new Error("permissionMode is required.");await this.request({type:"set_permission_mode",mode:n,...this.initConfig.independentPlanModeControls===!0?{preservePlanMode:!0}:{}})}waitForFirstResult(){return this.firstResultReceived||this.closed?Promise.resolve():new Promise(e=>{if(this.abortController?.signal.aborted){e();return}this.firstResultReceivedResolve=e,this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0})})}async setModel(e){await this.request({type:"set_model",model:e??""})}async enableRemoteProjection(e,n={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("remoteSessionId must be a non-empty string");if(n.fromSequenceNum!==void 0&&(!Number.isSafeInteger(n.fromSequenceNum)||n.fromSequenceNum<=0))throw new TypeError("fromSequenceNum must be a positive safe integer");await this.request({type:"enable_remote_projection",remote_session_id:e,...n.suppressInitialIdleStateEvents===!0?{suppress_initial_idle_state_events:!0}:{},...n.skipInitialFlush===!0?{skip_initial_flush:!0}:{},...n.fromSequenceNum===void 0?{}:{from_sequence_num:n.fromSequenceNum}},{requestIdPrefix:t.REMOTE_PROJECTION_REQUEST_ID_PREFIX,...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs}})}async disableRemoteProjection(e={}){let n=await this.request({type:"disable_remote_projection"},{requestIdPrefix:t.REMOTE_PROJECTION_REQUEST_ID_PREFIX,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});if(!(typeof n?.remote_session_id!="string"||n.remote_session_id.length===0||typeof n.last_sequence_num!="number"||!Number.isSafeInteger(n.last_sequence_num)||n.last_sequence_num<=0))return{remoteSessionId:n.remote_session_id,lastSequenceNum:n.last_sequence_num}}async setProxy(e){if(this.daemonProxyProvider){if(No(e)!==No(this.daemonProxyProvider()))throw new Error("proxy must be set via daemon.setProxy(); a daemon-bound Query cannot change it per session");return}await this.request({type:"set_proxy",proxy:e||null})}async generateSessionTitle(e,n){let s=n?.customContext??this.initConfig.customContext;return(await this.request({type:"generate_session_title",description:e,...n?.persist!==void 0?{persist:n.persist}:{},...s!==void 0?{custom_context:s}:{}}))?.title??null}async askSideQuestion(e,n){await this.requireCliCapability(t.SIDE_QUESTION_CAPABILITY);let s=n?.customContext??this.initConfig.customContext,o=await this.request({subtype:"side_question",question:e,...n?.history?.length?{history:n.history.map(r=>({...r}))}:{},...s!==void 0?{custom_context:s}:{}},{timeoutMs:0,signal:n?.signal});return o?.response==null?null:{response:o.response,synthetic:o.synthetic??!1,...o.refusal_fallback?{refusalFallback:{originalModel:o.refusal_fallback.original_model,fallbackModel:o.refusal_fallback.fallback_model,content:o.refusal_fallback.content}}:{}}}async addDirectories(e){if(!Array.isArray(e))throw new Error("directories must be an array");return await this.request({type:"add_directories",directories:e})}async applyFlagSettings(e){await this.request({type:"apply_flag_settings",settings:e})}async supportedCommands(){return await this.initializationResult(),this.getLatestCommands()}async getAvailableModels(e){if(this.daemonAccountQueries)return await this.daemonAccountQueries.getModels(e)??[];let n={subtype:"get_models",...e?.fetchStrategy?{fetchStrategy:e.fetchStrategy}:{},...e?.uid?{uid:e.uid}:{},...e?.outerProviders?{outerProviders:e.outerProviders}:{}};return(await this.request(n))?.models??[]}async listByokProviders(){if(this.daemonAccountQueries)try{return await this.daemonAccountQueries.getByokConfig()??null}catch{return null}try{return(await this.request({type:"get_byok_config"}))?.providers??null}catch{return null}}async validateByokModel(e){if(this.daemonAccountQueries)try{let n=await this.daemonAccountQueries.validateByokModel(e);return typeof n=="boolean"?n:null}catch{return null}try{let n=await this.request({type:"validate_byok_model",provider:e.provider,model:e.model,api_key:e.api_key,...e.url!==void 0?{url:e.url}:{},...e.style!==void 0?{style:e.style}:{}});return typeof n?.success=="boolean"?n.success:null}catch{return null}}async listByokConfigs(e){if(e&&!e.uid?.trim())throw new Error("BYOK_UID_REQUIRED");return this.daemonAccountQueries&&!e?this.daemonAccountQueries.listByokConfigs():(await this.requireCliCapability(e?"byok_config_read_v1":t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),(await this.request({type:"list_byok_configs",...e?{uid:e.uid}:{}})).configs)}async createByokConfig(e){return this.daemonAccountQueries?this.daemonAccountQueries.createByokConfig(e):(await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),(await this.request({type:"create_byok_config",config:e})).config)}async updateByokConfig(e){if(this.daemonAccountQueries){await this.daemonAccountQueries.updateByokConfig(e);return}await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"update_byok_config",config:e})}async deleteByokConfig(e){if(this.daemonAccountQueries){await this.daemonAccountQueries.deleteByokConfig(e);return}await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"delete_byok_config",target:e})}async checkByokConfig(e){return this.daemonAccountQueries?this.daemonAccountQueries.checkByokConfig(e):(await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"check_byok_config",config:e}))}async supportedAgents(){return(await this.initializationResult()).agents??[]}async accountInfo(){if(this.daemonAccountQueries)try{let n=await this.daemonAccountQueries.accountInfo();if(n&&Object.keys(n).length>0)return n}catch{}else try{let n=await this.request({type:"account_info"});if(n?.account&&Object.keys(n.account).length>0)return n.account}catch{}return(await this.initializationResult()).account??{}}async mcpServerStatus(){return(await this.request({type:"mcp_status"}))?.servers??[]}async getContextUsage(){return await this.request({type:"get_context_usage"})}async getUsageInfo(){if(this.daemonAccountQueries)try{return await this.daemonAccountQueries.getUsageInfo()}catch{return null}try{let e=await this.request({type:"get_usage_info"}),n=_t(e?.usage),s=bt(e?.session);return!n&&!s?null:{...n??{},...s?{session:s}:{}}}catch{return null}}async reloadPlugins(){let e=await this.request({type:"reload_plugins"});return this.replaceLatestCommands(e.commands),e}async reloadSkills(){return await this.requireCliCapability("reload_skills_v1"),await this.request({type:"reload_skills"})}async listPlugins(){return(await this.request({type:"list_plugins"})).plugins}async rewindFiles(e,n){let s={type:"rewind_files",user_message_id:e};n?.dryRun&&(s.dry_run=!0);let r=await this.request(s);if(!n?.dryRun&&r?.canRewind===!1)throw new Error(typeof r.error=="string"&&r.error.length>0?r.error:"Unable to rewind files.");return r}async rewind(e,n){if(!(await this.initializationResult()).capabilities?.includes("session_rewind_v1"))throw new Error("The connected qodercli does not support full session rewind (session_rewind_v1).");let o={type:"rewind",user_message_id:e,scope:n?.scope??"both"};return n?.dryRun&&(o.dry_run=!0),await this.request(o)}async seedReadState(e,n){await this.request({type:"seed_read_state",path:e,mtime:n})}async flushMemory(){return this.memoryFlushPromise||(this.memoryFlushPromise=this.performMemoryFlush().finally(()=>{this.memoryFlushPromise=void 0})),this.memoryFlushPromise}async flushSkillEvolution(){return this.skillEvolutionFlushPromise||(this.skillEvolutionFlushPromise=this.performSkillEvolutionFlush().finally(()=>{this.skillEvolutionFlushPromise=void 0})),this.skillEvolutionFlushPromise}async performSkillEvolutionFlush(){await this.requireSkillEvolutionEnabled(),await this.request({type:"flush_skill_evolution"})}async requireSkillEvolutionEnabled(){let e=await this.initializationResult();if(!this.cliCapabilities?.has("skill_evolution_v1"))throw new L("skill_evolution_v1");if(e.evolution?.skill?.enabled!==!0||e.evolution.skill.requester!=="sdk")throw new Error("The connected CLI did not enable SDK skill evolution for this query")}async performMemoryFlush(){await this.requireSdkMemoryEnabled(),await this.request({type:"flush_memory"})}async refreshMemory(){await this.requireSdkMemoryEnabled(),await this.request({type:"refresh_memory"})}async requireSdkMemoryEnabled(){let e=await this.initializationResult();if(e.memory?.enabled!==!0||e.memory.requester!=="sdk")throw new Error("The connected CLI did not enable SDK memory for this query")}async reconnectMcpServer(e){await this.request({type:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,n){await this.request({type:"mcp_toggle",serverName:e,enabled:n})}async setMcpServers(e){let n=ls(e);return await this.request({type:"mcp_set_servers",servers:n})??{added:[],removed:[],errors:{}}}async injectMcpToken(e,n){await this.request({type:"mcp_inject_token",serverName:e,token:n})}async mcpAuthenticate(e,n){let s=await this.request({type:"mcp_authenticate",serverName:e,...n!==void 0?{redirectUri:n}:{}}),o=s?.requiresUserAction===!0,r=typeof s?.authUrl=="string"?s.authUrl:void 0;if(o&&r===void 0)throw new Error("mcp_authenticate response set requiresUserAction=true but did not include an authUrl");return o?{authUrl:r,requiresUserAction:!0}:{requiresUserAction:!1}}async mcpSubmitOAuthCallbackUrl(e,n){await this.request({type:"mcp_oauth_callback_url",serverName:e,callbackUrl:n})}async mcpClearAuth(e){await this.request({type:"mcp_clear_auth",serverName:e})}async close(){return this.closePromise||(this.closePromise=Y(this.diagnostics,"query","close",()=>this.performClose())),this.closePromise}async performClose(){if(this.closed)return;if(!(this.cliCapabilities?.has(Mt)===!0)&&(this.initConfig.memory!==void 0||this.initConfig.evolution?.skill!==void 0)&&(this.initResponse?.memory?.enabled===!0||this.initResponse?.evolution?.skill?.enabled===!0)&&this.transport.isReady()&&this.abortController?.signal.aborted!==!0)try{await Y(this.diagnostics,"query","flush",()=>this.endInputFlushPromise??this.flushBeforeEndInput())}catch(o){this.diagnostics?.record("[QueryRunner] post-turn flush during close failed:",o)}this.closed=!0;for(let[,o]of this.pendingInboundRequests)o.abortController.abort();this.pendingInboundRequests.clear(),this.hookCallbacks.clear();let n=new Error("SDK closing");for(let[o,r]of this.sdkMcpTransports){try{await Y(this.diagnostics,"query","mcp_close",()=>r.close())}catch(i){this.diagnostics?.record(`[QueryRunner] error closing SDK MCP transport "${o}":`,i)}wo(o,n,this.pendingMcpResponses)}let s;try{await Y(this.diagnostics,"query","transport_close",()=>this.transport.close())}catch(o){s={error:o}}try{await Y(this.diagnostics,"query","read_loop",()=>this.readLoopPromise)}catch{}if(await Y(this.diagnostics,"query","transcript_flush",()=>this.flushTranscriptMirrorForLifecycle()),s)throw s.error}async[Symbol.asyncDispose](){await this.close()}};function Ou(t){let e=t instanceof Error?t.message:String(t),n=typeof t=="object"&&t!==null?t.code:void 0,s=typeof n=="string"&&n.length>0?n:void 0,o=/^([a-z][a-z0-9_]*):\s*(.*)$/.exec(e);if(o){let r=s??o[1];return(!s||s===o[1])&&(e=o[2]||e),{error:e,code:r}}return s?{error:e,code:s}:{error:e}}function jo(t){let e=/^(\d+)\.(\d+)(?:\.\d+)?(?:[-+].*)?$/.exec(t);return e?{major:Number(e[1]),minor:Number(e[2])}:null}var Nt=class{sendMcpMessage;isClosed=!1;onclose;onerror;onmessage;constructor(e){this.sendMcpMessage=e}async start(){}async send(e){if(this.isClosed)throw new Error("Transport is closed");this.sendMcpMessage(e)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}get closed(){return this.isClosed}};import{randomUUID as Fo}from"crypto";var qu="QODER_CLOUD_AGENT_API_BASE",Nu="https://api.qoder.com/api/v1/cloud",oe={agentMessage:"agent.message",modelRequestEnd:"span.model_request_end",idle:"session.status_idle",error:"session.error",terminated:"terminated",userMessage:"user.message",userInterrupt:"user.interrupt"},ju=1024,Uo=1*1024*1024,Ko=4*1024*1024,Fu=8*1024,In=class extends Error{code="auth_access_token_env_var_not_configured";constructor(e){super(`The auth access token environment variable "${e}" is not set; set it or pass auth.accessToken directly.`),this.name="CloudAuthAccessTokenEnvVarError"}},jt=class extends Error{code="cloud_agent_auth_requires_access_token";constructor(){super("options.experimentalCloudAgent requires PAT authentication via accessToken() or accessTokenFromEnv()."),this.name="CloudAgentUnsupportedAuthError"}},Dn=class extends Error{code="cloud_agent_api_error";status;constructor(e,n){super(`Cloud Agent API request failed with status ${e}: ${n}`),this.name="CloudAgentApiError",this.status=e}},Uu=new Set(["abortController","auth","experimentalCloudAgent","debug","debugFile","stderr","env","includePartialMessages","onAuthExpired"]);function Qo(t){if(!t.experimentalCloudAgent)return;let e=Object.keys(t).filter(r=>t[r]!==void 0&&!Uu.has(r));if(e.length>0)throw new Error(`options.experimentalCloudAgent cannot be combined with CLI runtime options: ${e.join(", ")}`);if(t.auth?.type!=="accessToken")throw new jt;let{agent:n,session:s}=t.experimentalCloudAgent;if(n&&qe(n)&&An(n))throw new Error("options.experimentalCloudAgent.agent must specify either id or create, not both.");if(s&&qe(s)&&An(s))throw new Error("options.experimentalCloudAgent.session must specify either id or create, not both.");if(s&&qe(s)&&n!==void 0)throw new Error("options.experimentalCloudAgent.agent cannot be combined with experimentalCloudAgent.session.id because an existing session already selects its agent.");let o=!!s&&qe(s);if(!o&&n===void 0)throw new Error("options.experimentalCloudAgent.agent is required when experimentalCloudAgent.session.id is not provided.");if(!o){if(!s||!An(s))throw new Error("options.experimentalCloudAgent.session.create is required when creating a Cloud Agent session.");if(typeof s.create.environment_id!="string"||s.create.environment_id.length===0)throw new Error("options.experimentalCloudAgent.session.create.environment_id is required when creating a Cloud Agent session.")}}function qe(t){return"id"in t&&t.id!==void 0}function An(t){return"create"in t&&t.create!==void 0}function Go(t){return new xn(t)}var xn=class{experimentalCloudAgent;inputStream;abortController=new AbortController;accessToken;apiBase;diagnostics;onAuthExpired;sessionReadyPromise;readLoopPromise;sseConnected=ec();startedAt=Date.now();closed=!1;authExpiredFired=!1;sessionId;assistantTextParts=[];currentTurnId;lastSseEventId;hasCurrentTurn=!1;pendingTurnEvents=[];latestUsage=$o();latestModelUsage={};totalCostUsd=0;postedMessages=0;activeInputStreams=0;idleSeen=!1;resultEmitted=!1;constructor(e){if(!e.options.experimentalCloudAgent)throw new Error("options.experimentalCloudAgent is required for CloudAgentQuery.");this.experimentalCloudAgent=e.options.experimentalCloudAgent,this.diagnostics=e.diagnostics,this.onAuthExpired=e.options.onAuthExpired,this.accessToken=Ku(e.options.auth,e.options.env),this.apiBase=Lu(),this.inputStream=new ee(()=>{this.close().catch(()=>{})});let n=e.options.abortController?.signal;n?.aborted?this.abortController.abort():n?.addEventListener("abort",()=>{this.close().catch(()=>{})},{once:!0}),this.sessionReadyPromise=this.initializeCloudSession(),this.readLoopPromise=this.readCloudEvents().catch(s=>{this.sseConnected.reject(s),this.closed||this.inputStream.error(s)}),this.streamInput(Xu(e.prompt)).catch(s=>{this.closed||this.inputStream.error(s)})}[Symbol.asyncIterator](){return this}async next(){return this.inputStream.next()}async return(){return await this.close(),{done:!0,value:void 0}}async throw(e){return await this.inputStream.throw(e),{done:!0,value:void 0}}async initializationResult(){return(await this.sessionReadyPromise).init}async streamInput(e){this.activeInputStreams+=1,(async()=>{try{await this.sessionReadyPromise,await this.sseConnected.promise;for await(let n of e){if(this.closed)break;let s=Yu(n);this.beginPendingTurn();let o=await this.postSessionEvents([{type:oe.userMessage,content:s}]);this.postedMessages+=1,this.activateTurn(o.find(r=>r.type===oe.userMessage)?.turnId)}}finally{this.activeInputStreams=Math.max(0,this.activeInputStreams-1),this.finishIfIdle()}})().catch(n=>{this.closed||this.inputStream.error(n)})}async interrupt(){await this.sessionReadyPromise,await this.postSessionEvents([{type:oe.userInterrupt}])}async cancelAsyncMessage(e){this.unsupported("cancelAsyncMessage")}async sendHostAction(e){throw new Error("Host actions are not supported by Cloud Agent queries.")}async stopTask(e){this.unsupported("stopTask")}async backgroundTasks(e){this.unsupported("backgroundTasks")}async setPermissionMode(e){this.unsupported("setPermissionMode")}async setModel(e){this.unsupported("setModel")}async setProxy(e){this.unsupported("setProxy")}async generateSessionTitle(e,n){this.unsupported("generateSessionTitle")}async addDirectories(e){this.unsupported("addDirectories")}async applyFlagSettings(e){this.unsupported("applyFlagSettings")}async supportedCommands(){this.unsupported("supportedCommands")}async getAvailableModels(){this.unsupported("getAvailableModels")}async listByokProviders(){this.unsupported("listByokProviders")}async validateByokModel(e){this.unsupported("validateByokModel")}async listByokConfigs(){this.unsupported("listByokConfigs")}async createByokConfig(e){this.unsupported("createByokConfig")}async updateByokConfig(e){this.unsupported("updateByokConfig")}async deleteByokConfig(e){this.unsupported("deleteByokConfig")}async checkByokConfig(e){this.unsupported("checkByokConfig")}async supportedAgents(){this.unsupported("supportedAgents")}async mcpServerStatus(){this.unsupported("mcpServerStatus")}async getContextUsage(){this.unsupported("getContextUsage")}async getUsageInfo(){this.unsupported("getUsageInfo")}async reloadPlugins(){this.unsupported("reloadPlugins")}async reloadSkills(){this.unsupported("reloadSkills")}async listPlugins(){this.unsupported("listPlugins")}async accountInfo(){this.unsupported("accountInfo")}async rewindFiles(e,n){this.unsupported("rewindFiles")}async rewind(e,n){this.unsupported("rewind")}async seedReadState(e,n){this.unsupported("seedReadState")}async flushMemory(){this.unsupported("flushMemory")}async flushSkillEvolution(){this.unsupported("flushSkillEvolution")}async refreshMemory(){this.unsupported("refreshMemory")}async mcpAuthenticate(e,n){this.unsupported("mcpAuthenticate")}async mcpSubmitOAuthCallbackUrl(e,n){this.unsupported("mcpSubmitOAuthCallbackUrl")}async close(){this.finish();try{await this.readLoopPromise}catch{}}async[Symbol.asyncDispose](){await this.close()}async initializeCloudSession(){if(this.closed)throw new Error("Cloud Agent query is closed.");let{session:e}=this.experimentalCloudAgent,n;if(e&&qe(e))n=e.id;else{let s=await this.resolveAgentId(),o=e.create,r=await this.requestJson("/sessions",{method:"POST",body:{agent:s,...$u(o)}});n=Lo(r,"Cloud session")}return this.sessionId=n,this.diagnostics?.record(`[cloud-agent] session ready: ${n}`),{sessionId:n,init:{commands:[],agents:[],output_style:"cloud-agent",available_output_styles:["cloud-agent"],models:[],account:{}}}}async resolveAgentId(){let{agent:e}=this.experimentalCloudAgent;if(!e)throw new Error("options.experimentalCloudAgent.agent is required when experimentalCloudAgent.session.id is not provided.");if(qe(e))return e.id;let n=await this.requestJson("/agents",{method:"POST",body:Bu(e.create)});return Lo(n,"Cloud agent")}async readCloudEvents(){let{sessionId:e}=await this.sessionReadyPromise,n=0;for(;!this.closed;){let s=this.lastSseEventId;if(await this.readCloudEventStream(e),this.closed||this.resultEmitted)return;if(!this.shouldReconnectSse()||n>=3){this.finishAfterSseClosed();return}this.lastSseEventId!==s&&(n=0),n+=1,await Zu(250*n,this.abortController.signal)}}async readCloudEventStream(e){let n=new URL(`${this.apiBase}/sessions/${encodeURIComponent(e)}/events/stream`),s=this.lastSseEventId??this.experimentalCloudAgent.stream?.afterId;s&&n.searchParams.set("after_id",s),this.experimentalCloudAgent.stream?.deltaFlushIntervalMs!==void 0&&n.searchParams.set("delta_flush_interval_ms",String(this.experimentalCloudAgent.stream.deltaFlushIntervalMs));let o=await fetch(n.toString(),{headers:this.authHeaders({accept:"text/event-stream"}),signal:this.abortController.signal});if(!o.ok)throw this.handleAuthFailure(o.status),await Bo(o);if(!o.body)throw new Error("Cloud Agent SSE response did not include a body.");this.sseConnected.resolve(),await this.readSseBody(o.body)}async readSseBody(e){let n=e.getReader(),s=new TextDecoder,o="",r={data:[],dataBytes:0};try{for(;!this.closed;){let{done:i,value:a}=await n.read();if(i){o+=s.decode(),o.length>0&&this.consumeSseLine(o,r);break}o+=s.decode(a,{stream:!0});let u;for(;(u=o.indexOf(`
|
|
20
|
-
`))!==-1;){let c=o.slice(0,u);o=o.slice(u+1);let
|
|
21
|
-
`))}),n.id=void 0,n.event=void 0,n.data.length=0,n.dataBytes=0;return}if(e.startsWith(":"))return;let s=e.indexOf(":"),o=s===-1?e:e.slice(0,s),r=s===-1?"":e.slice(s+1);switch(r.startsWith(" ")&&(r=r.slice(1)),o){case"id":n.id=r;break;case"event":n.event=r;break;case"data":if(n.dataBytes+r.length>
|
|
22
|
-
`):JSON.stringify(e)}function
|
|
23
|
-
`);await
|
|
24
|
-
`:"")}async function tr(t,e){await Yo(ac(t),{recursive:!0,mode:448}),await oc(t,e,{encoding:"utf8",mode:384}),await Vo(t,384)}async function Nn(t,e,n){let s;t.catch(()=>{});try{return await Promise.race([t,new Promise((o,r)=>{s=setTimeout(()=>r(new Error(`SessionStore ${n} timed out after ${e}ms`)),e)})])}finally{s!==void 0&&clearTimeout(s)}}import nr from"node:path";function Ne(t,e){if(typeof t!="string"||t.trim()==="")throw new TypeError(`${e} must be a non-empty string`)}function st(t,e){if(t!==void 0&&typeof t!="function")throw new TypeError(`${e} must be a function`)}function vc(t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0)throw new TypeError("options.memory.generation.roots must be a non-empty array");let e=new Set;for(let[n,s]of t.entries()){if(!s||typeof s!="object")throw new TypeError(`options.memory.generation.roots[${n}] must be an object`);if(Ne(s.id,`options.memory.generation.roots[${n}].id`),Ne(s.path,`options.memory.generation.roots[${n}].path`),e.has(s.id))throw new TypeError(`options.memory.generation.roots contains duplicate id "${s.id}"`);if(e.add(s.id),s.access!==void 0&&s.access!=="read"&&s.access!=="read-write")throw new TypeError(`options.memory.generation.roots[${n}].access must be "read" or "read-write"`);if(s.indexFile!==void 0){Ne(s.indexFile,`options.memory.generation.roots[${n}].indexFile`);let o=s.indexFile.replaceAll("\\","/");if(nr.posix.isAbsolute(o)||nr.win32.isAbsolute(s.indexFile)||o.split("/").includes(".."))throw new TypeError(`options.memory.generation.roots[${n}].indexFile must stay within its root`)}}}function wc(t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0)throw new TypeError("options.memory.consumption.files must be a non-empty array");let e=new Set;for(let[n,s]of t.entries()){if(!s||typeof s!="object")throw new TypeError(`options.memory.consumption.files[${n}] must be an object`);if(Ne(s.id,`options.memory.consumption.files[${n}].id`),Ne(s.path,`options.memory.consumption.files[${n}].path`),e.has(s.id))throw new TypeError(`options.memory.consumption.files contains duplicate id "${s.id}"`);if(e.add(s.id),s.required!==void 0&&typeof s.required!="boolean")throw new TypeError(`options.memory.consumption.files[${n}].required must be a boolean`)}}function sr(t){if(t===void 0)return{};if(!t||typeof t!="object")throw new TypeError("options.memory must be an object");if(Array.isArray(t))throw new TypeError("options.memory must be an object");if(Object.keys(t).length===0)return{};if(t.mode!=="native"&&t.mode!=="custom")throw new TypeError('options.memory.mode must be "native" or "custom"');if(t.projectScope!==void 0&&typeof t.projectScope!="boolean")throw new TypeError("options.memory.projectScope must be a boolean");if(t.userScope!==void 0&&typeof t.userScope!="boolean")throw new TypeError("options.memory.userScope must be a boolean");let e=new Map;if(t.mode==="native"){if(t.projectScope===!1&&t.userScope===!1)throw new TypeError("options.memory native mode requires at least one enabled scope; use memory: {} to disable SDK memory");let i=Object.keys(t.generation??{}),a=Object.keys(t.consumption??{});if(i.some(u=>u!=="onResult")||a.some(u=>u!=="onResult"))throw new TypeError('options.memory mode "native" only accepts generation.onResult and consumption.onResult');return st(t.generation?.onResult,"options.memory.generation.onResult"),st(t.consumption?.onResult,"options.memory.consumption.onResult"),{config:{requester:"sdk",mode:"native",...t.projectScope!==void 0?{projectScope:t.projectScope}:{},...t.userScope!==void 0?{userScope:t.userScope}:{}},callbacks:{shouldGenerateCallbacks:e,onGenerationResult:t.generation?.onResult,onConsumptionResult:t.consumption?.onResult}}}let n,s=t.generation;if(s!==void 0){if(!s||typeof s!="object")throw new TypeError("options.memory.generation must be an object");if(s.enabled!==void 0&&typeof s.enabled!="boolean")throw new TypeError("options.memory.generation.enabled must be a boolean");vc(s.roots),s.prompt!==void 0&&Ne(s.prompt,"options.memory.generation.prompt"),st(s.onResult,"options.memory.generation.onResult");let i;if(s.turnComplete!==void 0){let a=s.turnComplete;if(!a||typeof a!="object")throw new TypeError("options.memory.generation.turnComplete must be an object");if(a.enabled!==void 0&&typeof a.enabled!="boolean")throw new TypeError("options.memory.generation.turnComplete.enabled must be a boolean");if(st(a.shouldGenerate,"options.memory.generation.turnComplete.shouldGenerate"),a.timeoutMs!==void 0&&(!Number.isFinite(a.timeoutMs)||a.timeoutMs<=0))throw new TypeError("options.memory.generation.turnComplete.timeoutMs must be a positive finite number");if(a.onGateError!==void 0&&a.onGateError!=="skip"&&a.onGateError!=="report_failed")throw new TypeError('options.memory.generation.turnComplete.onGateError must be "skip" or "report_failed"');let u=a.shouldGenerate?"memory_should_generate_0":void 0;u&&a.shouldGenerate&&e.set(u,a.shouldGenerate),i={enabled:a.enabled??!0,shouldGenerateCallbackId:u,timeoutMs:a.timeoutMs,onGateError:a.onGateError}}if(s.turnComplete?.enabled===!0&&s.enabled===!1)throw new TypeError("options.memory.generation.turnComplete cannot be enabled when generation.enabled is false");n={enabled:s.enabled??!0,roots:s.roots?.map(a=>({...a})),prompt:s.prompt,turnComplete:i}}let o,r=t.consumption;if(r!==void 0){if(!r||typeof r!="object")throw new TypeError("options.memory.consumption must be an object");if(r.enabled!==void 0&&typeof r.enabled!="boolean")throw new TypeError("options.memory.consumption.enabled must be a boolean");if(wc(r.files),r.maxTokens!==void 0&&(!Number.isInteger(r.maxTokens)||r.maxTokens<=0))throw new TypeError("options.memory.consumption.maxTokens must be a positive integer");if(r.overflow!==void 0&&r.overflow!=="truncate"&&r.overflow!=="fail_query")throw new TypeError('options.memory.consumption.overflow must be "truncate" or "fail_query"');if(r.failureMode!==void 0&&r.failureMode!=="best_effort"&&r.failureMode!=="fail_query")throw new TypeError('options.memory.consumption.failureMode must be "best_effort" or "fail_query"');st(r.onResult,"options.memory.consumption.onResult"),o={enabled:r.enabled??!0,files:r.files?.map(i=>({...i,required:i.required??!1})),maxTokens:r.maxTokens,overflow:r.overflow,failureMode:r.failureMode}}return{config:{requester:"sdk",mode:t.mode,...t.projectScope!==void 0?{projectScope:t.projectScope}:{},...t.userScope!==void 0?{userScope:t.userScope}:{},generation:n,consumption:o},callbacks:{shouldGenerateCallbacks:e,onGenerationResult:s?.onResult,onConsumptionResult:r?.onResult}}}var Ut=10;function bc(t,e){if(typeof t!="string"||t.trim()==="")throw new TypeError(`${e} must be a non-empty string`)}function Kt(t,e){if(t!==void 0&&typeof t!="function")throw new TypeError(`${e} must be a function`)}function or(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>10)throw new TypeError(`options.evolution.skill.generation.turnComplete.reviewThreshold must be an integer between 1 and ${10}`);return t}}function _c(t){let e={shouldReviewCallbacks:new Map};if(t===void 0)return{config:void 0,callbacks:e};if(!t||typeof t!="object")throw new TypeError("options.evolution.skill.generation must be an object");if("roots"in t)throw new TypeError("options.evolution.skill.generation does not accept roots; roots are derived from loaded skills");if(t.enabled!==void 0&&typeof t.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.enabled must be a boolean");if(t.prompt!==void 0&&bc(t.prompt,"options.evolution.skill.generation.prompt"),t.maxSuggestions!==void 0&&(!Number.isInteger(t.maxSuggestions)||t.maxSuggestions<1||t.maxSuggestions>10))throw new TypeError("options.evolution.skill.generation.maxSuggestions must be an integer between 1 and 10");Kt(t.onResult,"options.evolution.skill.generation.onResult");let n;if(t.turnComplete!==void 0){if(!t.turnComplete||typeof t.turnComplete!="object")throw new TypeError("options.evolution.skill.generation.turnComplete must be an object");if(t.turnComplete.enabled!==void 0&&typeof t.turnComplete.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.turnComplete.enabled must be a boolean");let s=or(t.turnComplete.reviewThreshold);if(Kt(t.turnComplete.shouldReview,"options.evolution.skill.generation.turnComplete.shouldReview"),t.turnComplete.timeoutMs!==void 0&&(!Number.isFinite(t.turnComplete.timeoutMs)||t.turnComplete.timeoutMs<=0))throw new TypeError("options.evolution.skill.generation.turnComplete.timeoutMs must be a positive finite number");if(t.turnComplete.onGateError!==void 0&&t.turnComplete.onGateError!=="skip"&&t.turnComplete.onGateError!=="report_failed")throw new TypeError('options.evolution.skill.generation.turnComplete.onGateError must be "skip" or "report_failed"');let o=t.turnComplete.shouldReview?"skill_evolution_should_review_0":void 0;o&&e.shouldReviewCallbacks.set(o,t.turnComplete.shouldReview),n={enabled:t.turnComplete.enabled??!0,reviewThreshold:s,shouldReviewCallbackId:o,timeoutMs:t.turnComplete.timeoutMs,onGateError:t.turnComplete.onGateError}}if(t.turnComplete!==void 0&&n?.enabled===!0&&t.enabled===!1)throw new TypeError("options.evolution.skill.generation.turnComplete cannot be enabled when generation.enabled is false");return{config:{enabled:t.enabled??!0,prompt:t.prompt,maxSuggestions:t.maxSuggestions,turnComplete:n},callbacks:{...e,onResult:t.onResult}}}function rr(t){if(t===void 0)return{};if(!t||typeof t!="object")throw new TypeError("options.evolution.skill must be an object");if(t.mode!=="native"&&t.mode!=="custom")throw new TypeError('options.evolution.skill.mode must be "native" or "custom"');let e=t.generation;if(t.mode==="native"){if(Object.keys(e??{}).some(i=>i!=="enabled"&&i!=="onResult"&&i!=="turnComplete"))throw new TypeError('options.evolution.skill mode "native" only accepts generation.enabled, generation.onResult, and generation.turnComplete.reviewThreshold');if(e?.enabled!==void 0&&typeof e.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.enabled must be a boolean");let o=e?.turnComplete;if(o!==void 0){if(!o||typeof o!="object")throw new TypeError("options.evolution.skill.generation.turnComplete must be an object");if(Object.keys(o).some(i=>i!=="reviewThreshold"))throw new TypeError('options.evolution.skill mode "native" only accepts generation.turnComplete.reviewThreshold')}let r=or(o?.reviewThreshold);return e?.enabled===!1?(Kt(e?.onResult,"options.evolution.skill.generation.onResult"),{callbacks:{shouldReviewCallbacks:new Map,onResult:e?.onResult}}):(Kt(e?.onResult,"options.evolution.skill.generation.onResult"),{config:{requester:"sdk",mode:"native",...r===void 0?{}:{generation:{turnComplete:{reviewThreshold:r}}}},callbacks:{shouldReviewCallbacks:new Map,onResult:e?.onResult}})}let n=_c(e);return n.config?.enabled===!1?{callbacks:n.callbacks}:{config:{requester:"sdk",mode:"custom",generation:n.config},callbacks:n.callbacks}}import{execFile as Cc,spawn as Rc}from"child_process";import{randomUUID as Pc}from"node:crypto";import{homedir as Ec}from"node:os";import{resolve as ar}from"node:path";var kc=/^(?:qoder(?:cli|clicn|cn)?-)?worker-runtime(?:\.obf)?\.mjs$/i;function jn(t){let e=t.replace(/\\/g,"/").split("/").at(-1)??"";return kc.test(e)}function ir(t,e,n=process.env){let s=t.pathToQoderCLIExecutable;return s?jn(s)?{transport:"worker",pathToQoderWorkerRuntime:s}:{transport:"process"}:t.executable!==void 0||t.executableArgs!==void 0||t.spawnQoderCLIProcess!==void 0?{transport:"process"}:n.QODERCLI_PATH?{transport:"process"}:{transport:e}}function ur(){return Pe()}function cr(t=process.env){return ar(t.QODERCLI_HOST_ACTION_STORAGE_DIR??t[w.configDirEnv]??ar(t[w.cliHomeEnv]??Ec(),t[`${w.configDirEnv}_NAME`]??w.configDirName))}async function lr(t,e={}){let n=e.cliPath??ur(),s=e.timeout??125e3,o=["feedback","action","send","--json"];e.proxy!==void 0&&o.push("--proxy",e.proxy);let r=await Tc(t,e.auth,s),i=jn(n)?await Me(n):void 0,a=i?.runtimePath??n,u=Re(a)?process.execPath:a,c=Re(a)?[a,...o]:o;await new Promise((d,m)=>{let p=Rc(u,c,{cwd:e.cwd,env:{...e.env??process.env,...i?.env,...Re(a)&&process.versions.electron?{ELECTRON_RUN_AS_NODE:"1"}:{}},stdio:["pipe","ignore","ignore"]}),l=setTimeout(()=>{p.kill("SIGTERM"),m(new Error("Host action fallback timed out"))},s);l.unref?.(),p.once("error",f=>{clearTimeout(l),m(f)}),p.once("exit",(f,S)=>{clearTimeout(l),f===0?d():m(new Error(`Host action fallback exited with ${f??S??"unknown status"}`))}),p.stdin.on("error",f=>{clearTimeout(l),p.kill("SIGTERM"),m(f)}),p.stdin.end(`${JSON.stringify(r?{event:t,credential:r}:t)}
|
|
25
|
-
`)})}async function Tc(t,e,n){if(e?.type==="serviceAccount")throw new Error("Host actions are not supported for Service Account authentication");if(e?.type!=="jobToken")return;let s=new AbortController,o;try{let r=await Promise.race([Promise.resolve().then(()=>e.fetchJobToken({requestId:Pc(),reason:"initial",sessionId:t.session_id},{signal:s.signal})),new Promise((i,a)=>{o=setTimeout(()=>{s.abort(),a(new Error("Host action authentication timed out"))},Math.min(n,3e4))})]);if(!r?.token?.trim()||r.expiresAt!==void 0&&(!Number.isFinite(r.expiresAt)||r.expiresAt<=Date.now()))throw new Error("Host action credentials are unavailable or expired");return{type:e.type,token:r.token,expiresAt:r.expiresAt}}catch{throw new Error("Host action authentication failed")}finally{o&&clearTimeout(o)}}async function Mc(t,e){if(!t.content)return{success:!1,message:"Feedback content is required"};let n=e?.cliPath??ur(),s=e?.timeout??6e4,o=["feedback","-c",t.content,"--json"];if(e?.storageDir&&o.push("--storage-dir",e.storageDir),t.sessionId&&o.push("-s",t.sessionId),t.workdir&&o.push("--workdir",t.workdir),t.email&&o.push("--email",t.email),t.include)for(let r of t.include)o.push("--include",r);if(t.imagePaths)for(let r of t.imagePaths)o.push("--images",r);if(t.callerVersion&&o.push("--caller-version",t.callerVersion),e?.integrationMode){let r=e.integrationMode==="qoder_work"?"QoderWork":e.integrationMode==="quest"?"Quest":e.integrationMode;r&&o.push("--ide-type",r)}return new Promise(r=>{Cc(n,o,{env:e?.env??process.env,timeout:s,maxBuffer:1024*1024},(i,a)=>{let u=a.trim();if(u)try{let c=JSON.parse(u);r({success:!!c.success,message:c.success?c.message||"Feedback submitted successfully":c.error||c.message||"Failed to submit feedback",requestId:c.request_id});return}catch{}r(i?{success:!1,message:i.message||"Failed to submit feedback"}:{success:!0,message:u||"Feedback submitted successfully"})})})}var Fn=class extends Error{code="auth_not_configured";constructor(){super("The auth option is required when calling query(); configure options.auth so the SDK can create an auth payload file before spawning qodercli."),this.name="AuthNotConfiguredError"}};function Ac(t,e){let n=t.daemon;if(n){let s=Ve(n);if(!s)throw new Error("options.daemon must be returned by startDaemon().");return{daemon:n,transportProvider:s.transportProvider,hostActionLaunch:s.hostActionLaunch}}if(t.transport!==void 0){if(Ic(t.transport))return{...dr(t,e),legacyTransport:!0};if(!ss(t.transport))throw new Error("options.transport must implement QueryTransportProvider. Use ProcessTransport.default, WorkerTransport.default, or a custom provider with create().");return{transportProvider:t.transport,hostActionLaunch:{proxy:t.proxy,cliPath:t.pathToQoderCLIExecutable,env:t.env}}}return dr(t,e)}function Ic(t){return t instanceof xe||t instanceof Oe}function dr(t,e){let n=Dt(Oc(t,e));return{daemon:n.daemon,transportProvider:n.transportProvider,hostActionLaunch:{get proxy(){return n.daemon.getProxy()??void 0},get noProxy(){return n.daemon.getNoProxy()},cliPath:t.pathToQoderCLIExecutable,env:t.env}}}function Dc(t){return t.options?.pathToQoderWorkerRuntime}function xc(t){return t.transport instanceof Oe?{launchMode:"worker",pathToQoderWorkerRuntime:Dc(t.transport)}:t.transport instanceof xe?{launchMode:"process"}:{launchMode:Ye}}function Oc(t,e){return{auth:e,pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint,env:t.env,stderr:t.stderr,debug:t.debug,debugFile:t.debugFile,...xc(t)}}function Un(t){let e=Date.now(),{prompt:n,options:s={}}=t,o=s.daemon;if(s.planMode!==void 0&&typeof s.planMode!="boolean")throw new TypeError("options.planMode must be a boolean");let r=Ze(s.permissionMode);o&&qc(s);let i=o?Ve(o):void 0;if(o&&!i)throw new Error("options.daemon must be returned by startDaemon().");let a=s.sessionStore,u=s.sessionStoreFlush??"batched",c=new Z({onCloseDiagnostic:s.onCloseDiagnostic,debug:s.debug,debugFile:s.debugFile,stderr:s.stderr});if(o!==void 0&&c.record("[DaemonRoute] explicit_daemon transport_overridden"),s.canUseTool&&s.permissionPromptToolName)throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");s.goalMaxTurns!==void 0&&et(s.goalMaxTurns);let d=i?.auth??s.auth;if(d==null)throw new Fn;if(s.hostActions!==void 0&&d.type==="serviceAccount")throw new Error("Host actions are not supported for Service Account authentication: Tracking requires a user signing context");let m=a!==void 0&&s.forkSession===!0;if(a&&s.persistSession===!1)throw new Error(`sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use ${w.configDirEnv}=/tmp for ephemeral local writes with external mirroring.`);if(a&&s.sessionStoreFlush!==void 0&&s.sessionStoreFlush!=="batched"&&s.sessionStoreFlush!=="eager")throw new Error('sessionStoreFlush must be "batched" or "eager".');if(a&&s.loadTimeoutMs!==void 0&&(!Number.isFinite(s.loadTimeoutMs)||s.loadTimeoutMs<=0))throw new Error("loadTimeoutMs must be a positive finite number.");if(a&&s.experimentalCloudAgent!==void 0)throw new Error("sessionStore is not supported by the experimental Cloud Agent runtime.");if(s.cloudAgent!==void 0)throw new Error("options.cloudAgent is not supported. Use options.experimentalCloudAgent for the experimental Cloud Agent runtime.");if(s.experimentalCloudAgent!==void 0)return Qo(s),Go({prompt:n,options:s,diagnostics:c});let{daemon:p,transportProvider:l,hostActionLaunch:f,legacyTransport:S}=Ac(s,d);S&&c.record("[Transport] Process/Worker selection executes through the shared daemon"),(s.spawnQoderCLIProcess!==void 0||s.closeGraceMs!==void 0)&&c.record("[Transport] spawnQoderCLIProcess/closeGraceMs are handled by the daemon and ignored");let g=sr(s.memory),v=rr(s.evolution?.skill),b=s.onAuthExpired,y=!1,A=b?()=>{y||(y=!0,Promise.resolve(b()).catch(_=>{c.record("[query] onAuthExpired callback threw:",_)}))}:void 0,I=new Map,re=new Map,C=new Map,U={},ie={},ut={};if(s.mcpServers)for(let[_,T]of Object.entries(s.mcpServers)){let N=T.tools;if(Array.isArray(N)&&N.length>0&&(ie[_]=N),T.type==="sdk"&&"instance"in T&&T.instance){let J=T.instance;if(I.set(_,J),N){let mt=en(_,N);mt&&(ut[_]=mt)}let pt=new Nt(mt=>{vo(_,mt,C)});re.set(_,pt),J.connect(pt).catch(()=>{})}else U[_]=T}let Ht=Object.keys(U).length>0,X=Object.keys(ie).length>0,ct=s.pathToQoderCLIExecutable,Yr=s.env,Xr=d?.type==="jobToken"?d.fetchJobToken:void 0,Zr=d?.type==="serviceAccount"?d.fetchServiceAccountToken:void 0,lt={pathToQoderCLIExecutable:ct,executable:s.executable,executableArgs:s.executableArgs,env:Yr,proxy:s.proxy,vpcEndpoint:s.vpcEndpoint,cwd:s.cwd,closeGraceMs:s.closeGraceMs,auth:d,model:s.model,agent:s.agent,debug:s.debug,diagnostics:c,maxTurns:s.maxTurns,includePartialMessages:s.includePartialMessages,includeHookEvents:s.includeHookEvents,sessionMirror:a!==void 0,permissionMode:s.permissionMode,allowDangerouslySkipPermissions:s.allowDangerouslySkipPermissions,permissionPromptToolName:s.permissionPromptToolName,canUseTool:s.canUseTool!==void 0,continue:s.continue,resume:s.resume,resumeSessionAt:s.resumeSessionAt,resumeDropsTurn:s.resumeDropsTurn,forkSession:s.forkSession,sessionId:s.sessionId,persistSession:s.persistSession,allowedTools:(()=>{let _=s.allowedTools??[];if(s.skills===void 0)return _.length>0?_:void 0;let T=s.skills==="all"?["Skill"]:s.skills.map(J=>`Skill(${J})`),N=new Set(_);return[..._,...T.filter(J=>!N.has(J))]})(),disallowedTools:s.disallowedTools,tools:s.tools,toolConfig:s.toolConfig,extensions:s.extensions,extraArgs:s.extraArgs,mcpServers:Ht?U:void 0,mcpToolPolicies:X?ie:void 0,allowedMcpServerNames:s.allowedMcpServerNames,strictMcpConfig:s.strictMcpConfig,settings:s.settings,securityScan:s.securityScan,settingSources:s.settingSources,additionalDirectories:s.additionalDirectories,plugins:s.plugins,enableFileCheckpointing:s.enableFileCheckpointing,stderr:"pipe",stderrHandler:s.stderr,spawnQoderCLIProcess:s.spawnQoderCLIProcess,onAuthExpired:A},dt,es=a!==void 0&&(s.resume!==void 0||s.continue===!0)?new be(async()=>{let _=await er({store:a,cwd:s.cwd,resume:s.resume,continue:s.continue,loadTimeoutMs:s.loadTimeoutMs,env:s.env});if(!_)return{transport:we(l,{...lt,continue:!1})};dt=cr(s.env);try{return{transport:we(l,{...lt,env:{...lt.env??process.env,[w.configDirEnv]:_.configDir,...s.hostActions!==void 0?{QODERCLI_HOST_ACTION_STORAGE_DIR:dt}:{}},materializedSessionConfigDir:_.configDir,continue:!1,resume:_.sessionId}),cleanup:_.cleanup}}catch(T){throw await _.cleanup(),T}}):we(l,lt);es.initialize().catch(()=>{});let ei=typeof n=="string",ve=s.systemPrompt,ts,ns;if(typeof ve=="string")ts=ve;else if(typeof ve=="object"&&ve!==null&&ve.type==="preset"){let _=ve;if(_.preset!=="qodercli")throw new Error(`Unsupported systemPrompt preset: ${String(_.preset)}`);ns=_.append}let ti={sdkStartedAtMs:e,systemPrompt:ts,appendSystemPrompt:ns,modelRequestPatches:s.modelRequestPatches,agents:s.agents,skills:Array.isArray(s.skills)?s.skills:void 0,planMode:p!==void 0?s.planMode??!1:s.planMode,promptSuggestions:s.promptSuggestions,includeShellProgress:s.includeShellProgress,hostActions:s.hostActions,goalMaxTurns:s.goalMaxTurns,enableFileCheckpointing:s.enableFileCheckpointing,memory:g.config,evolution:v.config?{skill:v.config}:void 0,customContext:s.customContext,beforeInitialize:void 0,requireSessionStoreForkBarrier:m,...p!==void 0?{independentPlanModeControls:!0,permissionMode:r}:{}},Wt=new qt(es,ei,s.canUseTool,s.hooks,s.abortController,I,ti,s.onElicitation,c,A,s.controlRequestTimeoutMs,re,C,Xr,s.resolveModel,s.resolveModelTimeoutMs,a,u,ut,Zr,g.callbacks,v.callbacks,s.resolveSessionArtifacts,async _=>{let T=f,N=T.noProxy,J=new ae({auth:d,vpcEndpoint:s.vpcEndpoint,env:{...T.env??s.env??process.env,...N!=null?{NO_PROXY:N,no_proxy:N}:{},...dt!==void 0?{QODERCLI_HOST_ACTION_STORAGE_DIR:dt}:{}}});try{let pt=await J.prepare();await lr(_,{cliPath:T.cliPath??s.pathToQoderCLIExecutable,env:pt.env,cwd:s.cwd,auth:d,proxy:T.proxy??s.proxy})}finally{await J.cleanupAuthPayload()}},p!==void 0,p,p?()=>p.getProxy():void 0);if(typeof n=="string"){let _={type:"user",extra:{submitted_at_ms:e},message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null};Wt.streamInput(async function*(){yield _}())}else Wt.streamInput(n);return Wt}function qc(t){let e=t,s=[["auth",t.auth],["transport",e.transport],["env",t.env],["pathToQoderCLIExecutable",t.pathToQoderCLIExecutable],["executable",t.executable],["executableArgs",t.executableArgs],["proxy",t.proxy],["vpcEndpoint",t.vpcEndpoint],["spawnQoderCLIProcess",e.spawnQoderCLIProcess],["closeGraceMs",e.closeGraceMs]].find(([,o])=>o!==void 0);if(s)throw new Error(`options.${s[0]} is part of startDaemon() configuration and cannot be overridden by a daemon-bound Query.`)}var Nc=1e3,Kn=class{resolvePrompt;prompt=new Promise(e=>{this.resolvePrompt=e});settled=!1;activate(e){if(this.settled)throw new Error("WarmQuery can only be queried once");this.settled=!0,this.resolvePrompt(e)}discard(){this.settled||(this.settled=!0,this.resolvePrompt(void 0))}async*[Symbol.asyncIterator](){let e=await this.prompt;if(e!==void 0){if(typeof e=="string"){yield{type:"user",message:{role:"user",content:[{type:"text",text:e}]},parent_tool_use_id:null};return}yield*e}}},Ln=class{constructor(e,n){this.session=e;this.gate=n}used=!1;closed=!1;query(e){if(this.closed)throw new Error("WarmQuery is closed");if(this.used)throw new Error("WarmQuery can only be queried once");return this.used=!0,this.gate.activate(e),this.session}close(){this.closed||(this.closed=!0,this.gate.discard(),this.session.close())}async[Symbol.asyncDispose](){this.closed||(this.closed=!0,this.gate.discard()),await this.session.close()}};async function jc(t={}){let e=t.initializeTimeoutMs??6e4;if(!Number.isFinite(e)||e<=0)throw new TypeError("initializeTimeoutMs must be a positive finite number");if(t.options?.experimentalCloudAgent!==void 0)throw new Error("startup is not supported by the experimental Cloud Agent runtime");let n=new Kn,s=Un({prompt:n,options:t.options}),o,r;try{return await Promise.race([s.initializationResult(),new Promise((i,a)=>{o=setTimeout(()=>{a(new Error(`Qoder Agent SDK startup timed out after ${e}ms while waiting for qodercli initialization. Check authentication and network connectivity, then retry.`))},e)})]),new Ln(s,n)}catch(i){n.discard();let a=t.options?.closeGraceMs??Xt,u=(Number.isFinite(a)?Math.max(0,a):Xt)+Nc;throw await Promise.race([s.close().catch(()=>{}),new Promise(c=>{r=setTimeout(c,u)})]),i}finally{o!==void 0&&clearTimeout(o),r!==void 0&&clearTimeout(r)}}import{readFile as Fc}from"node:fs/promises";import Uc from"node:os";import $ from"node:path";var Kc=["user","project","local"],Qn=new Set(["__proto__","constructor","prototype"]),Lc=/^[\p{L}\p{N}\p{M}._ -]+$/u,Bc=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu,$c=new Set([".git",".svn",".hg",".vscode",".idea",".husky",".github","node_modules","bower_components"]),Qc=new Set(["mcpServers","providers","skillOverrides","enabledPlugins","extraKnownMarketplaces","pluginConfigs"]),Gc=new Set(["context.fileFiltering.customIgnoreFilePaths","tools.exclude","mcp.enabledProjectMcpServers","mcp.disabledProjectMcpServers","security.approvedExternalImportProjects","advanced.excludedEnvVars","extensions.disabled","extensions.workspacesWithMigrationNudge","plugins.enabled","plugins.disabled","skills.disabled","blockedMarketplaces","allowedHttpHookUrls"]);function he(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function zc(t){let e=t.charCodeAt(0)===65279?t.slice(1):t,n="",s=!1,o=!1,r=!1,i=!1;for(let a=0;a<e.length;a+=1){let u=e[a],c=e[a+1];if(r){u===`
|
|
13
|
+
${n}`:s,{exitCode:e.code,signal:e.signal,stderr:n})}static async spawn(e){let n;try{n=su(e.command,e.args,{env:e.env,stdio:["pipe","pipe","pipe"]}),await mu(n)}catch(s){throw new K(`Failed to spawn Qoder CLI daemon: ${pu(s)}`,{cause:s})}if(!n.stdin||!n.stdout)throw n.kill("SIGTERM"),new Error("Qoder CLI daemon did not expose piped stdin/stdout");return new t(n,e.stderrHandler)}setConnection(e){this.connection=e,this.failure&&e.fail(this.failure)}onFailure(e){this.failureListeners.add(e),this.failure&&e(this.failure)}beginStopping(){this.stopping=!0}async stop(){return this.beginStopping(),await Je(this.exited,We)?{settledAfterSigkill:!0}:(this.process.kill("SIGTERM"),await Je(this.exited,We)?{settledAfterSigkill:!0}:(this.process.kill("SIGKILL"),{settledAfterSigkill:await Je(this.exited,We)}))}getStderr(){return this.stderrTail.trim()||void 0}reportFailure(e){if(!(this.stopping||this.failure)){this.failure=e,this.connection?.fail(e);for(let n of this.failureListeners)n(e)}}};function pu(t){return t instanceof Error?t.message:String(t)}async function mu(t){t.pid===void 0&&await new Promise((e,n)=>{let s=()=>{t.off("error",o),e()},o=r=>{t.off("spawn",s),n(r)};t.once("spawn",s),t.once("error",o)})}function kn(t){if(t.debug!==!0)return ou(Vt(),"logs",`sdk-daemon-${process.pid}-${Date.now()}.log`)}async function Je(t,e){let n;try{return await Promise.race([t.then(()=>!0),new Promise(s=>{n=setTimeout(()=>s(!1),e),n.unref?.()})])}finally{n&&clearTimeout(n)}}var Ye=class extends Error{constructor(){super("Global daemon is already initialized with different options"),this.name="DaemonConfigurationConflictError"}},V,A,Dt,Pn=!1,se,B;function En(t){return t={...t,business:t.business&&{...t.business}},B?B.then(()=>En(t)):Pn&&t.business?.product!==Dt?.product?Promise.reject(new Ye):se?io(t)?(ne(t).record("[GlobalDaemon] init joined an in-flight initialization"),se):(ne(t).record("[GlobalDaemon] init rejected: configuration conflict with an in-flight initialization"),Promise.reject(new Ye)):V?V.state==="ready"?io(t)?(ne(t).record("[GlobalDaemon] init reused the ready daemon"),Promise.resolve(V)):(ne(t).record("[GlobalDaemon] init rejected: configuration conflict with the ready daemon"),Promise.reject(new Ye)):Cn(t,ne(t),V):Cn(t,ne(t))}function It(t){t={...t,business:t.business&&{...t.business}};let e=lo(t);return{daemon:new Rn(e,t.proxy),transportProvider:{create:n=>new be(async()=>{let s=await e,o=Ve(s);if(!o)throw new Error("The global daemon is not managed by this SDK instance.");return{transport:o.transportProvider.create(n)}})}}}function lo(t){return B?B.then(()=>lo(t)):En({...t,business:t.business??A?.business??Dt})}function Cn(t,e,n){A=t;let s;return s=(async()=>{if(n){if(await n.stop(),B)return n;V=void 0}try{let o=await _n(t);return V=o,Dt=t.business,Pn=!0,o.onFailure(r=>fu(o,r,t)),e.record("[GlobalDaemon] daemon ready"),o}catch(o){throw A=void 0,e.record("[GlobalDaemon] startDaemon failed",o),o}})().finally(()=>{se===s&&(se=void 0)}),se=s,s}function fu(t,e,n){if(V!==t||B||se)return;let s=ne(n);s.record(`[GlobalDaemon] active daemon failed: ${e.message}; stopping before rebuild`,e),Cn(n,s,t).catch(o=>{s.record("[GlobalDaemon] recovery failed",o)})}function ne(t){return new ee({debug:t.debug,debugFile:t.debugFile??kn(t),stderr:t.stderr})}function gu(){if(B)return B;let t=se,e=V,n=ne(A??{}),s;return s=(async()=>{let o=t?await t.catch(r=>{if(V)throw r}):e;o?(n.record("[GlobalDaemon] shutting down the global daemon"),await o.stop(),n.record("[GlobalDaemon] global daemon stopped")):n.record("[GlobalDaemon] shutdown with no daemon to stop")})().then(()=>{V=void 0,A=void 0,se=void 0,Dt=void 0,Pn=!1}).finally(()=>{B===s&&(B=void 0)}),B=s,s}function io(t){return hu(A?.auth,t.auth)&&A?.business?.product===t.business?.product&&co(A?.launchMode)===co(t.launchMode)&&A?.pathToQoderCLIExecutable===t.pathToQoderCLIExecutable&&A?.executable===t.executable&&Su(A?.executableArgs,t.executableArgs)&&A?.proxy===t.proxy&&A?.noProxy===t.noProxy&&A?.vpcEndpoint===t.vpcEndpoint&&yu(A?.env,t.env)}function hu(t,e){if(t===e)return!0;if(!t||!e||t.type!==e.type)return!1;switch(t.type){case"qodercli":return!0;case"accessToken":return ao(t.accessToken,e.accessToken);case"serviceAccount":{let n=e;return ao(t.serviceAccountKey,n.serviceAccountKey)&&t.fetchServiceAccountToken===n.fetchServiceAccountToken}case"jobToken":return t.fetchJobToken===e.fetchJobToken}}function ao(t,e){return t===e?!0:typeof t=="string"||typeof e=="string"?!1:t?.envVar===e?.envVar}function yu(t,e){if(t===e)return!0;let n=uo(t),s=uo(e),o=new Set([...Object.keys(n),...Object.keys(s)]);for(let r of o)if(n[r]!==s[r])return!1;return!0}function uo(t){let e={};for(let[n,s]of Object.entries(t??{}))s!==void 0&&(e[n]=s);return e}function co(t){return t??"process"}function Su(t,e){return t===e?!0:t===void 0||e===void 0?!1:t.length===e.length&&t.every((n,s)=>n===e[s])}var Rn=class{constructor(e,n){this.initialization=e;this.initialProxy=n;e.then(s=>{this.resolved=s;for(let o of this.failureListeners)s.onFailure(o)}).catch(()=>{this.failed=!0})}resolved;failed=!1;failureListeners=new Set;get state(){return this.resolved?this.resolved.state:this.failed?"failed":"ready"}ready(){return this.initialization}onFailure(e){this.failureListeners.add(e);let n,s=!0;return this.initialization.then(o=>{s&&(n=o.onFailure(e))}).catch(()=>{}),()=>{s=!1,this.failureListeners.delete(e),n?.()}}async listSessions(e){return(await this.ready()).listSessions(e)}async renameSession(e,n,s){return(await this.ready()).renameSession(e,n,s)}async deleteSession(e,n){await(await this.ready()).deleteSession(e,n)}async setProxy(e,n){return(await this.ready()).setProxy(e,n)}getProxy(){return this.resolved?this.resolved.getProxy():this.initialProxy?.trim()||null}getNoProxy(){return this.resolved?.getNoProxy()??null}async auth(e){return(await this.ready()).auth(e)}async getModels(e){return(await this.ready()).getModels(e)}async getByokConfig(){return(await this.ready()).getByokConfig()}async validateByokModel(e){return(await this.ready()).validateByokModel(e)}async listByokConfigs(){return(await this.ready()).listByokConfigs()}async createByokConfig(e){return(await this.ready()).createByokConfig(e)}async updateByokConfig(e){await(await this.ready()).updateByokConfig(e)}async deleteByokConfig(e){await(await this.ready()).deleteByokConfig(e)}async checkByokConfig(e){return(await this.ready()).checkByokConfig(e)}async listPlugins(){return(await this.ready()).listPlugins()}supportsCapability(e){return this.resolved?.supportsCapability(e)??!1}async validatePlugins(e,n){return(await this.ready()).validatePlugins(e,n)}async getUsageInfo(){return(await this.ready()).getUsageInfo()}async accountInfo(){return(await this.ready()).accountInfo()}async stop(){await(await this.ready()).stop()}};function xt(t,e){let n=t.auth;if(!n)throw new Error("Legacy transport providers require options.auth to execute through the shared daemon.");let s=It({auth:n,pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint,env:t.env,stderr:t.stderrHandler,debug:t.debug,launchMode:e.launchMode,pathToQoderWorkerRuntime:e.pathToQoderWorkerRuntime});return we(s.transportProvider,t)}var xe=class t{static default=new t;create(e){return xt(e,{launchMode:"process"})}};var Tn=class extends Error{code="QODER_WORKER_RUNTIME_ERROR";exitCode;stderr;constructor(e,n){super(e,n?.cause?{cause:n.cause}:void 0),this.name="QoderWorkerRuntimeError",this.exitCode=n?.exitCode,this.stderr=n?.stderr}},Oe=class t{constructor(e={}){this.options=e}static default=new t;getPathToQoderWorkerRuntime(){return this.options.pathToQoderWorkerRuntime}create(e){return xt(e,{launchMode:"worker",pathToQoderWorkerRuntime:this.options.pathToQoderWorkerRuntime})}};function vu(){switch("worker"){case"worker":return"worker";case"process":return"process"}return"process"}var Xe=vu();import{performance as po}from"node:perf_hooks";async function oe(t,e,n,s){let o=po.now(),r=i=>{try{t?.recordClose?.({component:e,stage:n,outcome:i,elapsedMs:Math.max(0,Math.round(po.now()-o)),...i==="failed"?{errorCode:"SDK_CLOSE_STAGE_FAILED"}:{}})}catch{}};r("started");try{let i=await s();return r("completed"),i}catch(i){throw r("failed"),i}}import{randomUUID as xu}from"node:crypto";var mo=["copy_text","helpful","not_helpful","create_branch_task","copy_markdown","add_reply_to_task"];var fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function go(t){if(!fo.test(t.uuid))throw new Error("uuid must be a UUID");if(!t.sessionId.trim())throw new Error("sessionId is required");if(!fo.test(t.parentResultUuid))throw new Error("parentResultUuid must be a UUID");if(!mo.includes(t.action))throw new Error("action is not supported");return{type:"feedback",subtype:"action",uuid:t.uuid,action:t.action,session_id:t.sessionId,parent_result_uuid:t.parentResultUuid}}import{isAbsolute as wu}from"node:path";function Mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ze(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-empty string`);return n}function ho(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string")throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a string`);return n}}function yo(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-negative finite number`);return n}}function So(t,e){let n=t[e];if(!Number.isSafeInteger(n)||n<0)throw new TypeError(`resolveSessionArtifacts result field "${e}" must be a non-negative safe integer`);return n}function bu(t){if(!Mn(t))throw new TypeError("resolveSessionArtifacts result artifacts must contain objects");let e=Ze(t,"path");if(!wu(e))throw new TypeError('resolveSessionArtifacts result field "path" must be absolute');let n=Ze(t,"displayPath"),s=Ze(t,"name"),o=ho(t,"relativePath"),r=ho(t,"mime"),i=yo(t,"size"),a=yo(t,"mtime"),u;if(t.group!==void 0){if(!Mn(t.group))throw new TypeError('resolveSessionArtifacts result field "group" must be an object');u={key:Ze(t.group,"key"),name:Ze(t.group,"name")}}let c={path:e,displayPath:n,name:s,...u?{group:u}:{},...o!==void 0?{relativePath:o}:{},...i!==void 0?{size:i}:{},...r!==void 0?{mime:r}:{},...a!==void 0?{mtime:a}:{}};if(t.kind==="presented")return{...c,kind:"presented"};if(t.kind!=="changed")throw new TypeError('resolveSessionArtifacts result field "kind" must be "presented" or "changed"');if(typeof t.isNew!="boolean")throw new TypeError('resolveSessionArtifacts result field "isNew" must be a boolean');return{...c,kind:"changed",additions:So(t,"additions"),deletions:So(t,"deletions"),isNew:t.isNew}}function vo(t){if(!Mn(t)||!Array.isArray(t.artifacts))throw new TypeError("resolveSessionArtifacts must return an object with an artifacts array");return{artifacts:t.artifacts.map(bu)}}var An="1.5.0";var _u=new Set(["default","acceptEdits","auto","bypassPermissions"]);function et(t){if(t===void 0)return;if(t==="yolo")return"bypassPermissions";if(typeof t=="string"&&_u.has(t))return t;if(t==="plan")throw new Error('permissionMode="plan" is not supported for daemon Queries; use planMode or setPlanMode() instead.');let e=typeof t=="string"?JSON.stringify(t):t===null?"null":typeof t;throw new Error(`permissionMode=${e} is not supported for daemon Queries; use default, acceptEdits, auto, or bypassPermissions.`)}function tt(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`goalMaxTurns must be a positive safe integer, received ${String(t)}.`)}function wo(t,e,n,s){return new Promise((o,r)=>{if(!("id"in e&&e.id!==null)){try{n.onmessage?.(e)}catch(u){r(u);return}o({jsonrpc:"2.0"});return}let a=`${t}:${e.id}`;s.set(a,{resolve:o,reject:r}),n.onmessage?n.onmessage(e):(s.delete(a),r(new Error(`No message handler registered for MCP server "${t}"`)))})}function bo(t,e,n){if("id"in e&&e.id!==null){let s=`${t}:${e.id}`,o=n.get(s);if(o)return o.resolve(e),n.delete(s),!0}return!1}function _o(t,e,n){let s=0,o=`${t}:`,r=Array.from(n.entries());for(let i of r){let[a,u]=i;a.startsWith(o)&&(u.reject(e),n.delete(a),s++)}return s}import{randomUUID as ku}from"crypto";function Ro(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.type==="transcript_mirror"&&typeof e.filePath=="string"&&Array.isArray(e.entries)}var Cu=500,Ru=1024*1024,Pu=6e4,Ot=class{constructor(e){this.options=e;this.holding=e.holdUntilFlush===!0}states=new Map;failures=[];holding;receivedEntryCount=0;enqueue(e){let n=Eu(e.filePath),s=Tu(e.entries);this.receivedEntryCount+=s.length;let o=Co(n),r=this.states.get(o);r||(r={key:n,entries:[],bytes:0,tail:Promise.resolve()},this.states.set(o,r)),r.entries.push(...s),r.bytes+=Au(s),!this.holding&&(this.options.flushMode==="eager"||r.entries.length>=Cu||r.bytes>=Ru)&&this.drain(r)}async flush(e={}){for(let n of this.states.values())this.drain(n);if(await Promise.all([...this.states.values()].map(n=>n.tail)),e.throwOnError===!0&&this.failures.length>0)throw new AggregateError(this.failures,`SessionStore failed to persist ${this.failures.length} transcript mirror batch(es).`)}async completeBarrier(){if(this.receivedEntryCount===0)throw new Error("SessionStore Fork persistence barrier received no transcript entries.");await this.flush({throwOnError:!0}),this.holding=!1}discardPending(){for(let e of this.states.values())e.entries=[],e.bytes=0}drain(e){if(e.entries.length===0)return;let n=e.entries;e.entries=[],e.bytes=0,e.tail=e.tail.then(async()=>{try{await Du(this.options.store,e.key,n,this.options.appendTimeoutMs??Pu)}catch(s){this.failures.push(s),this.options.diagnostics?.record(`[SessionStore] append failed for ${Co(e.key)}`,s),this.options.onMirrorError({type:"system",subtype:"mirror_error",error:s instanceof Error?s.message:String(s),key:{...e.key},uuid:ku(),session_id:e.key.sessionId})}})}};function Eu(t){let e=t.replaceAll("\\","/").split("/").filter(Boolean),n=e.lastIndexOf("projects"),s=e.slice(n+1);if(n<0||s.length<2)throw new Error(`Invalid transcript mirror path: ${t}`);let o=s[0],r=/^([0-9a-f-]{36})\.jsonl$/i.exec(s[1]);if(s.length===2&&r)return{projectKey:o,sessionId:ko(r[1])};let i=ko(s[1]),a=s.slice(2),u=a.at(-1);a[a.length-1]=u.endsWith(".jsonl")?u.slice(0,-6):u;let c=a.join("/");return Mu(c),{projectKey:o,sessionId:i,subpath:c}}function Tu(t){return t.map((e,n)=>{if(typeof e!="object"||e===null||typeof e.type!="string")throw new Error(`Transcript mirror entry ${n} is not a typed object`);return e})}function ko(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new Error(`Invalid transcript session id: ${t}`);return t}function Mu(t){let e=t.split("/");if(!t||t.includes("\0")||/^[a-z]:/i.test(t)||e.some(n=>!n||n==="."||n===".."))throw new Error(`Invalid transcript subpath: ${t}`)}function Co(t){return JSON.stringify([t.projectKey,t.sessionId,t.subpath??null])}function Au(t){return t.reduce((e,n)=>e+Buffer.byteLength(JSON.stringify(n))+1,0)}async function Du(t,e,n,s){await Iu(t.append({...e},structuredClone(n)),s)}async function Iu(t,e){let n;t.catch(()=>{});try{await Promise.race([t,new Promise((s,o)=>{n=setTimeout(()=>o(new Dn(e)),e)})])}finally{n!==void 0&&clearTimeout(n)}}var Dn=class extends Error{constructor(e){super(`SessionStore append timed out after ${e}ms`),this.name="SessionStoreTimeoutError"}};function Po(){return Math.random().toString(36).substring(2,15)}function Eo(t,e){let n="type"in e&&!("subtype"in e)?{...e,subtype:e.type}:e;return{type:"control_request",request_id:t,request:n}}function To(t,e){return{type:"control_response",response:{subtype:"success",request_id:t,response:e}}}function Mo(t,e,n){return{type:"control_response",response:{subtype:"error",request_id:t,error:e,...n?{code:n}:{}}}}function Ao(t){return typeof t=="object"&&t!==null&&t.type==="control_response"}function Do(t){return typeof t=="object"&&t!==null&&t.type==="control_request"}function Io(t){return typeof t=="object"&&t!==null&&(t.type==="control_cancel_request"||t.type==="control_cancel")}function nt(t){if(typeof t!="object"||t===null)return;let e=t,n=e.subtype;if(typeof n=="string")return n;let s=e.type;return typeof s=="string"?s:void 0}function xo(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return e==="keepalive"||e==="keep_alive"}function Oo(t){return typeof t=="object"&&t!==null&&t.type==="streamlined_text"}function qo(t){return typeof t=="object"&&t!==null&&t.type==="streamlined_tool_use_summary"}function No(t){return typeof t=="object"&&t!==null&&t.type==="post_turn_summary"}function jo(t){return typeof t=="object"&&t!==null&&t.type==="result"}var Ou="<synthetic>";function qu(t){return t.type!=="assistant"||t.isApiErrorMessage===!0||t.message.model!==Ou?t:{...t,isApiErrorMessage:!0}}function Fo(t){if(!t)return null;let e=t.trim();return e?e.startsWith("socks5h:")?`socks5:${e.slice(8)}`:e:null}var qt=class t{constructor(e,n,s,o,r,i,a,u,c,l,m,p,d,f,S,g,v,b="batched",y,D,I,ie,C,U,ae=!1,ct,Ht){this.hostActionDirect=ae;if(this.transport=e,this.isSingleTurn=n,this.canUseTool=s,this.hooks=o??{},this.abortController=r,this.sdkMcpServers=i??new Map,this.sdkMcpTransports=p??new Map,this.pendingMcpResponses=d??new Map,this.sdkMcpToolOverrides=y??{},this.initConfig=a??{},this.onElicitation=u,this.onAuthExpired=l,this.fetchJobToken=f,this.fetchServiceAccountToken=D,this.diagnostics=c,this.controlRequestTimeoutMs=m??6e4,this.resolveModel=S,this.resolveModelTimeoutMs=g??500,this.memoryCallbacks=I,this.skillEvolutionCallbacks=ie,this.hostActionFallback=U,this.resolveSessionArtifacts=C,this.daemonAccountQueries=ct,this.daemonProxyProvider=Ht,this.inputStream=new te(()=>{this.close().catch(()=>{})}),v&&(this.transcriptMirrorBatcher=new Ot({store:v,flushMode:b,holdUntilFlush:this.initConfig.requireSessionStoreForkBarrier===!0,diagnostics:c,onMirrorError:Z=>this.inputStream.enqueue(Z)})),this.readLoopPromise=this.readMessages().catch(Z=>{this.inputStream.error(Z)}),this.initializationPromise=this.startInitialization(),this.initializationPromise.catch(()=>{}),this.abortController){let Z=this.abortController.signal,lt=()=>{this.failInitialization(new E),this.close().catch(()=>{})};Z.aborted?lt():Z.addEventListener("abort",lt,{once:!0})}}extraHeadersSent=!1;static CUSTOM_CONTEXT_CAPABILITY="custom_context_v1";static SELECTED_SKILLS_CAPABILITY="selected_skills_v1";static INITIALIZE_TIMEOUT_MS=12e4;static BACKGROUND_TASKS_CAPABILITY="background_tasks_v1";static SIDE_QUESTION_CAPABILITY="side_question_v1";static GOAL_CAPABILITY="goal_v1";static GOAL_RESUME_CAPABILITY="goal_resume_v1";static GOAL_MAX_TURNS_CAPABILITY="goal_max_turns_v1";static PLAN_MODE_CAPABILITY="plan_mode_v1";static SESSION_STORE_FORK_BARRIER_CAPABILITY="session_store_fork_barrier_v1";static HOST_ACTION_CAPABILITY="host_action";static BYOK_CONFIG_MANAGEMENT_CAPABILITY="byok_config_management_v1";static REMOTE_PROJECTION_REQUEST_ID_PREFIX="daemon_worker_sdk_";transport;inputStream;pendingRequests=new Map;pendingInboundRequests=new Map;hooks;hookCallbacks=new Map;nextHookCallbackId=0;sdkMcpServers;sdkMcpTransports;pendingMcpResponses;sdkMcpToolOverrides;isSingleTurn;canUseTool;abortController;initConfig;onElicitation;onAuthExpired;fetchJobToken;fetchServiceAccountToken;diagnostics;controlRequestTimeoutMs;resolveModel;resolveModelTimeoutMs;transcriptMirrorBatcher;memoryCallbacks;skillEvolutionCallbacks;hostActionFallback;resolveSessionArtifacts;daemonAccountQueries;daemonProxyProvider;resolveStreamInitialization;initResponse;latestCommands=[];initializationPromise;rejectInitialization;resultMessage;pendingErrorResultExit=!1;readLoopPromise;closed=!1;authExpiredFired=!1;protocolHandshakeValidated=!1;cliCapabilities;customContextCapabilityWarningEmitted=!1;firstResultReceived=!1;sdkStartupTimingSent=!1;firstResultReceivedResolve;memoryFlushPromise;endInputFlushPromise;skillEvolutionFlushPromise;closePromise;sessionStoreForkBarrierComplete=!1;inputEnded=!1;getRecord(e){return typeof e=="object"&&e!==null?e:void 0}normalizeLogPreview(e){let s=e.replace(/\s+/g," ").trim();return s.length>200?`${s.slice(0,200)}...`:s}extractMessagePreview(e){if(typeof e=="string")return this.normalizeLogPreview(e);if(Array.isArray(e)){for(let i of e){let a=this.extractMessagePreview(i);if(a)return a}return""}let n=this.getRecord(e);if(!n)return"";let s=n.text;if(typeof s=="string")return this.normalizeLogPreview(s);let o=this.extractMessagePreview(n.content);if(o)return o;let r=this.getRecord(n.message);return r?this.extractMessagePreview(r):""}getMessagePreviewSuffix(e){let n=this.extractMessagePreview(e);return n?` preview=${JSON.stringify(n)}`:""}getMessageType(e){let s=this.getRecord(e)?.type;return typeof s=="string"&&s?s:"unknown"}getMessageSubtype(e){let s=this.getRecord(e)?.subtype;return typeof s=="string"&&s?s:"none"}getMessageUuid(e){let s=this.getRecord(e)?.uuid;return typeof s=="string"&&s?s:"none"}recordInboundSessionMessage(e){this.diagnostics?.record(`[QueryRunner] inbound session_message received type=${this.getMessageType(e)} subtype=${this.getMessageSubtype(e)} uuid=${this.getMessageUuid(e)}${this.getMessagePreviewSuffix(e)}`)}recordOutboundSessionMessage(e){let n=this.getRecord(e)?.message,o=this.getRecord(n)?.content,r=Array.isArray(o)?o.length:0;this.diagnostics?.record(`[QueryRunner] outbound session_message sent type=${this.getMessageType(e)} uuid=${this.getMessageUuid(e)} content_blocks=${r}${this.getMessagePreviewSuffix(e)}`)}[Symbol.asyncIterator](){return this}async next(){return this.inputStream.next()}async return(){return await this.close(),{done:!0,value:void 0}}async throw(e){return await this.inputStream.throw(e),{done:!0,value:void 0}}async readMessages(){let e;try{for await(let n of this.transport.readMessages()){if(this.closed)break;if(Ro(n)){try{this.transcriptMirrorBatcher?.enqueue(n)}catch(o){this.diagnostics?.record("[QueryRunner] invalid transcript_mirror frame ignored:",o)}continue}if(Ao(n)){this.handleControlResponse(n);continue}if(Do(n)){this.handleControlRequest(n).catch(o=>{this.diagnostics?.record("[QueryRunner] Error handling control request:",o)});continue}if(Io(n)){this.handleControlCancelRequest(n);continue}if(xo(n)||Oo(n)||qo(n)||No(n))continue;if(jo(n)){await this.transcriptMirrorBatcher?.flush();let o=n;if(this.recordInboundSessionMessage(o),this.resultMessage=o,this.pendingErrorResultExit=this.resultMessage.is_error===!0,this.firstResultReceived=!0,this.firstResultReceivedResolve?.(),this.firstResultReceivedResolve=void 0,this.inputStream.enqueue(o),this.rejectInitialization&&this.resultMessage.is_error===!0){let r=this.resultMessage.terminal_reason;this.failInitialization(this.abortController?.signal.aborted||this.closed||r==="aborted_streaming"||r==="aborted_tools"||r==="abort"?new E:new ke(this.resultMessage))}this.isSingleTurn&&this.flushBeforeEndInput();continue}let s=qu(n);if((s.type==="user"||s.type==="assistant")&&(this.pendingErrorResultExit=!1),this.recordInboundSessionMessage(s),s.type==="system"&&s.subtype==="init")try{let o=s;this.validateProtocolHandshake(o),this.cliCapabilities=new Set(o.capabilities??[]);let r=o.commands;r!==void 0&&this.replaceLatestCommands(r),this.resolveStreamInitialization&&(this.initResponse=o,this.resolveStreamInitialization(this.initResponse),this.resolveStreamInitialization=void 0)}catch(o){throw this.inputStream.error(o),o}s.type==="system"&&s.subtype==="commands_changed"&&this.replaceLatestCommands(s.commands),this.dispatchMemoryCallbacks(s),this.dispatchSkillEvolutionCallbacks(s),this.notifyAuthExpiredIfNeeded(s),this.inputStream.enqueue(s)}}catch(n){this.isStructuredResultExit(n)?this.diagnostics?.record("[QueryRunner] exit code 1 accepted after the latest structured error result"):e=n}finally{await this.flushTranscriptMirrorForLifecycle();let n=e instanceof Error?e:new Error("Transport closed");this.failInitialization(n),this.firstResultReceivedResolve?.(),this.firstResultReceivedResolve=void 0;for(let[,s]of this.pendingRequests)s.reject(n);this.pendingRequests.clear(),e!==void 0?this.inputStream.error(e):this.inputStream.done()}}isStructuredResultExit(e){if(!this.pendingErrorResultExit||e===null||typeof e!="object")return!1;let n=e;return n.exitCode===1&&(n.signal===void 0||n.signal===null)}notifyAuthExpiredIfNeeded(e){if(!this.onAuthExpired||this.authExpiredFired)return;let s=e.type==="auth_status"&&!!e.error,o=e.type==="assistant"&&e.error==="authentication_failed";!s&&!o||(this.authExpiredFired=!0,Promise.resolve(this.onAuthExpired()).catch(r=>{this.diagnostics?.record("[QueryRunner] onAuthExpired callback threw:",r)}))}dispatchMemoryCallbacks(e){if(!(e.type!=="system"||!this.memoryCallbacks))try{let n;e.subtype==="memory_generation"?n=this.memoryCallbacks.onGenerationResult?.(e.result):e.subtype==="memory_consumption"&&(n=this.memoryCallbacks.onConsumptionResult?.(e.result)),n!==void 0&&Promise.resolve(n).catch(s=>{this.diagnostics?.record("[QueryRunner] memory callback threw:",s)})}catch(n){this.diagnostics?.record("[QueryRunner] memory callback threw:",n)}}dispatchSkillEvolutionCallbacks(e){if(!(e.type!=="system"||e.subtype!=="skill_evolution"||!this.skillEvolutionCallbacks))try{let n=this.skillEvolutionCallbacks.onResult?.(e.result);n!==void 0&&Promise.resolve(n).catch(s=>this.diagnostics?.record("[QueryRunner] skill evolution callback threw:",s))}catch(n){this.diagnostics?.record("[QueryRunner] skill evolution callback threw:",n)}}flushBeforeEndInput(){return this.endInputFlushPromise||(this.endInputFlushPromise=this.performFlushBeforeEndInput()),this.endInputFlushPromise}async performFlushBeforeEndInput(){try{let e=[];this.initConfig.memory!==void 0&&e.push(oe(this.diagnostics,"query","memory_flush",()=>this.flushMemory())),this.initConfig.evolution?.skill!==void 0&&e.push(oe(this.diagnostics,"query","skill_flush",()=>this.flushSkillEvolution()));let s=(await Promise.allSettled(e)).find(o=>o.status==="rejected");if(s)throw s.reason}catch(e){this.diagnostics?.record("[QueryRunner] post-turn flush before end input failed:",e)}finally{this.endTransportInput()}}endTransportInput(){this.inputEnded||(this.inputEnded=!0,this.transport.endInput())}async request(e,n){if(n?.signal?.aborted)throw new E;let s=`${n?.requestIdPrefix??""}${Po()}`,o=Eo(s,e),r=n?.timeoutMs??this.controlRequestTimeoutMs,i=nt(o.request)??"unknown",a=Date.now();return new Promise((u,c)=>{let l=null,m=()=>{try{this.transport.write(JSON.stringify({type:"control_cancel_request",request_id:s})+`
|
|
14
|
+
`)}catch(f){this.diagnostics?.record("[QueryRunner] Failed to send control_cancel_request:",f)}},p=()=>{l&&(clearTimeout(l),l=null),n?.signal?.removeEventListener("abort",d)},d=()=>{this.pendingRequests.delete(s)&&(p(),this.diagnostics?.record(`[QueryRunner] control_request cancelled request_id=${s} subtype=${i}`),m(),c(new E))};this.pendingRequests.set(s,{resolve:f=>{p(),this.diagnostics?.record(`[QueryRunner] control_response received request_id=${s} subtype=${i} status=success duration_ms=${Date.now()-a}`),u(f)},reject:f=>{p(),this.diagnostics?.record(`[QueryRunner] control_response received request_id=${s} subtype=${i} status=error duration_ms=${Date.now()-a}`,f),c(f)}}),n?.signal?.addEventListener("abort",d,{once:!0}),r>0&&Number.isFinite(r)&&(l=setTimeout(()=>{if(!this.pendingRequests.has(s))return;this.pendingRequests.delete(s),p();let f=Date.now()-a;this.diagnostics?.record(`[QueryRunner] control_request timed out request_id=${s} subtype=${i} timeout_ms=${r} elapsed_ms=${f}`),m(),c(new Ce({requestId:s,message:`Control request "${i}" timed out after ${r}ms`,code:Yt,details:{requestType:i,timeoutMs:r,elapsedMs:f}}))},r));try{this.diagnostics?.record(`[QueryRunner] control_request sending request_id=${s} subtype=${i} timeout_ms=${r}`),this.transport.write(JSON.stringify(o)+`
|
|
15
|
+
`),this.diagnostics?.record(`[QueryRunner] control_request sent request_id=${s} subtype=${i}`)}catch(f){p(),this.pendingRequests.delete(s),this.diagnostics?.record(`[QueryRunner] control_request send failed request_id=${s} subtype=${i}`,f),c(f)}})}handleControlResponse(e){let n=e.response,s=n.request_id,o=this.pendingRequests.get(s);if(!o){this.diagnostics?.record(`[QueryRunner] unmatched control_response received request_id=${s} status=${n.subtype}`);return}if(this.pendingRequests.delete(s),n.subtype==="success")o.resolve(n.response);else{let r=new Ce({requestId:s,message:n.error,code:n.code,retryable:n.retryable,details:n.details});o.reject(r),this.processPendingPermissionRequests(n.pending_permission_requests)}}processPendingPermissionRequests(e){if(e)for(let n of e)nt(n.request)==="can_use_tool"&&this.handleControlRequest(n).catch(s=>{this.diagnostics?.record("[QueryRunner] Error handling pending permission request:",s)})}async handleControlRequest(e){let n=e.request_id,s=nt(e.request)??"unknown",o=Date.now(),r=new AbortController;this.pendingInboundRequests.set(n,{abortController:r}),this.diagnostics?.record(`[QueryRunner] inbound control_request received request_id=${n} subtype=${s}`);try{let i=await this.awaitAbortable(this.processControlRequest(e,r.signal),r.signal);if(!r.signal.aborted){let a=To(n,i);this.transport.write(JSON.stringify(a)+`
|
|
16
|
+
`),this.diagnostics?.record(`[QueryRunner] inbound control_response sent request_id=${n} subtype=${s} status=success duration_ms=${Date.now()-o}`)}}catch(i){if(!r.signal.aborted){let{error:a,code:u}=Nu(i),c=Mo(n,a,u);this.transport.write(JSON.stringify(c)+`
|
|
17
|
+
`),this.diagnostics?.record(`[QueryRunner] inbound control_response sent request_id=${n} subtype=${s} status=error duration_ms=${Date.now()-o}`,i)}}finally{this.pendingInboundRequests.delete(n)}}handleControlCancelRequest(e){let n=this.pendingInboundRequests.get(e.request_id);n&&(n.abortController.abort(),this.pendingInboundRequests.delete(e.request_id))}throwIfAborted(e){if(e.aborted)throw new E}validateProtocolHandshake(e){if(this.protocolHandshakeValidated)return;this.protocolHandshakeValidated=!0;let n=e.protocol_version,s=An;if(!n){this.diagnostics?.record(`[QueryRunner] CLI did not announce protocol_version. This SDK was built for ${s}. Consider upgrading qodercli for the version handshake.`);return}let o=Uo(n),r=Uo(s);if(!o||!r){this.diagnostics?.record(`[QueryRunner] Could not parse protocol_version "${n}" or built-in "${s}"; skipping handshake.`);return}if(o.major!==r.major)throw new X(n,s);o.minor<r.minor&&this.diagnostics?.record(`[QueryRunner] CLI protocol_version ${n} is older than this SDK's ${s}. New optional fields may be absent.`)}async awaitAbortable(e,n){if(n.aborted)throw new E;return new Promise((s,o)=>{let r=()=>{o(new E)};n.addEventListener("abort",r,{once:!0}),e.then(i=>{n.removeEventListener("abort",r),s(i)},i=>{n.removeEventListener("abort",r),o(i)})})}async processControlRequest(e,n){this.throwIfAborted(n);let s=e.request,o=nt(s),r=s;switch(o){case"resolve_session_artifacts":{if(!this.resolveSessionArtifacts)throw new Error("resolve_session_artifacts_unavailable: No resolveSessionArtifacts callback configured");let i=r.local_session_id,a=r.cwd;if(typeof i!="string"||i.length===0||typeof a!="string"||a.length===0)throw new TypeError("resolve_session_artifacts requires local_session_id and cwd");let u=await this.awaitAbortable(Promise.resolve().then(()=>this.resolveSessionArtifacts(i,a)),n);return vo(u)}case"fetch_job_token":{if(!this.fetchJobToken)throw new Error("job_token_unavailable: No fetchJobToken callback configured");let i=r.reason??"initial",a=r.session_id,u=e.request_id,c=await this.awaitAbortable(this.fetchJobToken({requestId:u,reason:i,sessionId:a},{signal:n}),n);if(!c?.token)throw new Error("job_token_unavailable: Host did not provide a Job Token");let l=c.expiresAt;if(l!==void 0&&(!Number.isFinite(l)||l<1e12))throw new Error("job_token_unavailable: expiresAt must be a Unix timestamp in milliseconds");return this.diagnostics?.record(`[QueryRunner] fetch_job_token fulfilled: reason=${i}`),{token:c.token,...l!==void 0?{expires_at:l}:{}}}case"fetch_service_account_token":{if(!this.fetchServiceAccountToken)throw new Error("service_account_token_unavailable: No fetchServiceAccountToken callback configured");let i=await this.awaitAbortable(this.fetchServiceAccountToken(),n);if(!i?.token)throw new Error("service_account_token_unavailable: Host did not provide a Service Account token");let a=i.expiresAt;if(a!==void 0&&(!Number.isFinite(a)||a<1e12))throw new Error("service_account_token_unavailable: expiresAt must be a Unix timestamp in milliseconds");return this.diagnostics?.record("[QueryRunner] fetch_service_account_token fulfilled"),{token:i.token,...a!==void 0?{expires_at:a}:{}}}case"can_use_tool":{let i=r.tool_name,a=r.input??{};if(!this.canUseTool)throw new Error("canUseTool callback is not provided.");let u=r.tool_use_id,c=r.permission_suggestions??r.suggestions,l=r.blocked_path,m=r.decision_reason,p=r.title,d=r.display_name,f=r.description,S=r.agent_id,g=r.permission_kind,v=r.options,b=r.details,y=await this.awaitAbortable(this.canUseTool(i,a,{signal:n,suggestions:c,blockedPath:l,decisionReason:m,title:p,displayName:d,description:f,toolUseID:u,agentID:S,permissionKind:g,permissionOptions:v,details:b}),n);if(y.behavior==="deny"&&!y.message)throw new Error("Permission deny result must include a message.");return y.behavior==="allow"?{...y,updatedInput:y.updatedInput??a,toolUseID:u}:{...y,toolUseID:u}}case"hook_callback":{let i=r.callback_id;if(!i)throw new Error("Hook callback missing callback_id");return this.invokeRegisteredHookCallback(i,r.input,r.tool_use_id,n)}case"memory_should_generate":{let i=r.callbackId;if(!i)throw new Error("Memory shouldGenerate request missing callbackId");let a=this.memoryCallbacks?.shouldGenerateCallbacks.get(i);if(!a)throw new Error(`Unknown memory shouldGenerate callback: ${i}`);let u=await this.awaitAbortable(a(r.input,{signal:n}),n);if(!u||typeof u.run!="boolean")throw new TypeError("Memory shouldGenerate callback must return { run: boolean }");return{run:u.run,...typeof u.reason=="string"?{reason:u.reason}:{}}}case"skill_evolution_should_review":{let i=r.callbackId;if(!i)throw new Error("Skill evolution shouldReview request missing callbackId");let a=this.skillEvolutionCallbacks?.shouldReviewCallbacks.get(i);if(!a)throw new Error(`Unknown skill evolution shouldReview callback: ${i}`);let u=await this.awaitAbortable(a(r.input,{signal:n}),n);if(!u||typeof u.run!="boolean")throw new TypeError("Skill evolution shouldReview callback must return { run: boolean }");return{run:u.run,...typeof u.reason=="string"?{reason:u.reason}:{}}}case"mcp_message":{let i=r.server_name,a=r.message,u=this.sdkMcpTransports.get(i);if(!u)throw new Error(`Unknown in-process MCP server: ${i}`);return{mcp_response:await this.awaitAbortable(wo(i,a,u,this.pendingMcpResponses),n)}}case"elicitation":case"elicitation_response":return this.onElicitation?await this.awaitAbortable(this.onElicitation({serverName:r.mcp_server_name??"",message:r.message??r.prompt??"",mode:r.mode,url:r.url,elicitationId:r.elicitation_id,requestedSchema:r.requested_schema,title:r.title,displayName:r.display_name,description:r.description},{signal:n}),n):{action:"cancel"};case"get_model_policy":{if(!this.resolveModel)return{type:"get_model_policy"};let i={purpose:r.purpose,sessionId:r.sessionId,turnIndex:r.turnIndex,agentId:r.agentId,agentType:r.agentType,resolvedModel:r.resolvedModel,availableModels:r.models??[]},a=this.resolveModelTimeoutMs,u=Promise.resolve(this.resolveModel(i)),c,l=new Promise((g,v)=>{c=setTimeout(()=>{v(new Le(a))},a)}),m;try{m=await this.awaitAbortable(Promise.race([u,l]),n)}finally{clearTimeout(c)}let p={type:"get_model_policy",...m?.parameters!==void 0?{parameters:m.parameters}:{}},d=m?.model;if(typeof d=="string")p.model=d;else if(d!==void 0){let{model:g,...v}=d;p.model=g,p.custom_model={...v,style:v.style??"openai"}}let f=m?.taskId?.trim();f&&(p.task_id=f);let S=m?.subTask?.trim();return S&&(p.sub_task=S),p}default:throw new Error(`Unhandled control request subtype: ${o??"unknown"}`)}}async initialize(){return this.initializationPromise||(this.initializationPromise=this.startInitialization()),this.initializationPromise}startInitialization(){let e=new Promise((s,o)=>{this.rejectInitialization=o}),n=this.initConfig.resolveInitializationFromStream?this.waitForStreamInitialization():this.performInitialize();return Promise.race([n,e]).then(s=>(this.rejectInitialization=void 0,this.initResponse=s,this.cliCapabilities=new Set(s.capabilities??[]),s),s=>{throw this.rejectInitialization=void 0,s})}failInitialization(e){let n=this.rejectInitialization;if(n){this.rejectInitialization=void 0,n(e);for(let s of this.pendingRequests.values())s.reject(e);this.pendingRequests.clear()}}async performInitialize(){await this.initConfig.beforeInitialize?.();let e={type:"initialize",modelPolicyProvider:this.resolveModel!==void 0,supportsCatalogReadyInitialize:!0,supportsAvailableModelsUpdate:!0,supportsCommandsChanged:!0,initializeTimeoutMs:t.INITIALIZE_TIMEOUT_MS},n={};for(let[o,r]of Object.entries(this.hooks)){if(!r||r.length===0)continue;let i=[];for(let a of r){let u=a.hooks.map(c=>{let l=`hook_${this.nextHookCallbackId++}`;return this.hookCallbacks.set(l,c),l});u.length!==0&&i.push({matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout})}i.length>0&&(n[o]=i)}if(Object.keys(n).length>0&&(e.hooks=n),this.initConfig.systemPrompt!==void 0&&(e.systemPrompt=this.initConfig.systemPrompt),this.initConfig.appendSystemPrompt!==void 0&&(e.appendSystemPrompt=this.initConfig.appendSystemPrompt),this.initConfig.modelRequestPatches!==void 0&&(e.modelRequestPatches=this.initConfig.modelRequestPatches),this.initConfig.agents&&(e.agents=this.initConfig.agents),this.initConfig.skills!==void 0&&(e.skills=this.initConfig.skills),this.initConfig.includeShellProgress===!0&&(e.includeShellProgress=!0),this.initConfig.promptSuggestions!==void 0&&(e.promptSuggestions=this.initConfig.promptSuggestions),this.initConfig.hostActions!==void 0&&(e.hostActions=this.initConfig.hostActions),this.initConfig.enableFileCheckpointing!==void 0&&(e.enableFileCheckpointing=this.initConfig.enableFileCheckpointing),this.initConfig.independentPlanModeControls===!0){e.independentPlanModeControls=!0;let o=et(this.initConfig.permissionMode);o!==void 0&&(e.permissionMode=o)}this.initConfig.memory!==void 0&&(e.memory=this.initConfig.memory),this.initConfig.evolution!==void 0&&(e.evolution=this.initConfig.evolution),this.resolveSessionArtifacts!==void 0&&(e.resolveSessionArtifacts=!0),this.sdkMcpServers.size>0&&(e.sdkMcpServers=Array.from(this.sdkMcpServers.keys()),Object.keys(this.sdkMcpToolOverrides).length>0&&(e.sdkMcpToolOverrides=this.sdkMcpToolOverrides));let s=await this.request(e,{timeoutMs:t.INITIALIZE_TIMEOUT_MS});if(s&&typeof s=="object"){let o=s;this.initResponse=o,this.replaceLatestCommands(o.commands),this.cliCapabilities=new Set(o.capabilities??[])}if(!this.initResponse)throw new Error("Failed to receive initialization response");if(this.initConfig.goalMaxTurns!==void 0&&!this.cliCapabilities?.has(t.GOAL_MAX_TURNS_CAPABILITY))throw new L(t.GOAL_MAX_TURNS_CAPABILITY);if(this.initConfig.hostActions!==void 0&&!this.cliCapabilities?.has(t.HOST_ACTION_CAPABILITY))throw new L(t.HOST_ACTION_CAPABILITY);if(this.initConfig.planMode!==void 0){if(!this.cliCapabilities?.has(t.PLAN_MODE_CAPABILITY))throw new L(t.PLAN_MODE_CAPABILITY);let o={subtype:"set_plan_mode",active:this.initConfig.planMode};await this.request(o)}return await this.completeSessionStoreForkBarrier(),this.initResponse}async completeSessionStoreForkBarrier(){if(this.initConfig.requireSessionStoreForkBarrier!==!0)return;if(!this.cliCapabilities?.has(t.SESSION_STORE_FORK_BARRIER_CAPABILITY))throw new L(t.SESSION_STORE_FORK_BARRIER_CAPABILITY);let e=this.transcriptMirrorBatcher;if(!e)throw new Error("SessionStore Fork persistence barrier requires a transcript mirror.");await e.completeBarrier(),this.sessionStoreForkBarrierComplete=!0}async flushTranscriptMirrorForLifecycle(){if(this.initConfig.requireSessionStoreForkBarrier===!0&&!this.sessionStoreForkBarrierComplete){this.transcriptMirrorBatcher?.discardPending();return}await this.transcriptMirrorBatcher?.flush()}async invokeRegisteredHookCallback(e,n,s,o){let r=this.hookCallbacks.get(e);if(!r)throw new Error(`Unknown hook callback: ${e}`);return await this.awaitAbortable(r(n,s,{signal:o}),o)??{continue:!0}}async initializationResult(){return this.initialize()}replaceLatestCommands(e){this.latestCommands=(e??[]).map(n=>({...n}))}getLatestCommands(){return this.latestCommands.map(e=>({...e}))}waitForStreamInitialization(){return new Promise(e=>{this.resolveStreamInitialization=e})}async streamInput(e){(async()=>{let n,s=!1;try{if(await this.initialize(),this.closed)return;n=e[Symbol.asyncIterator]();let o=async()=>{let a=await n.next();return s=a.done===!0,{...a,submittedAtMs:Date.now()}},r=await o(),i=0;for(;!r.done;r=await o()){let a=r.value;if(a?.type!=="user")throw new Error("Expected a user input message.");let u=r.submittedAtMs;if(this.closed)break;i+=1;let l=Object.prototype.hasOwnProperty.call(a,"custom_context")?a.custom_context:this.initConfig.customContext,m=typeof a.uuid=="string"&&a.uuid.trim().length>0?a.uuid:xu(),p=!this.extraHeadersSent&&a.isSynthetic!==!0&&a.shouldQuery!==!1?this.initConfig.extraHeaders:void 0,d={...a,uuid:m,...p!==void 0?{extra_headers:{...p}}:{},extra:{...!this.sdkStartupTimingSent&&this.initConfig.sdkStartedAtMs!==void 0?{started_at_ms:this.initConfig.sdkStartedAtMs}:{},submitted_at_ms:u,...a.extra},...l===void 0?{}:{custom_context:l}};if(this.pendingErrorResultExit=!1,d.selected_skills!==void 0&&d.selected_skills.length>0&&!this.cliCapabilities?.has(t.SELECTED_SKILLS_CAPABILITY))throw new L(t.SELECTED_SKILLS_CAPABILITY);l!==void 0&&!this.cliCapabilities?.has(t.CUSTOM_CONTEXT_CAPABILITY)&&!this.customContextCapabilityWarningEmitted&&(this.customContextCapabilityWarningEmitted=!0,this.diagnostics?.record("[QueryRunner] custom_context requested but paired CLI does not advertise custom_context_v1; the field may be ignored")),p!==void 0&&(this.extraHeadersSent=!0);try{await this.transport.write(JSON.stringify(d)+`
|
|
18
|
+
`)}catch(f){throw f instanceof G&&f.direction==="input"?new G(f.direction,f.limit,f.actualBytes,f.source,m):f}this.sdkStartupTimingSent=!0,this.recordOutboundSessionMessage(d)}i>0&&await this.waitForFirstResult(),(!this.isSingleTurn||!this.firstResultReceived)&&await this.flushBeforeEndInput()}catch(o){this.diagnostics?.record("[QueryRunner] streamInput error:",o),(!(o instanceof ke)||o.result!==this.resultMessage)&&this.inputStream.error(o instanceof Error?o:new Error(String(o))),this.endTransportInput()}finally{n&&!s&&Promise.resolve().then(()=>n?.return?.()).catch(o=>{this.diagnostics?.record("[QueryRunner] input cleanup error:",o)})}})().catch(()=>{})}async interrupt(){let n=(await this.request({type:"interrupt"}))?.still_queued;if(Array.isArray(n))return{still_queued:n.filter(s=>typeof s=="string")}}async sendHostAction(e){if(this.initConfig.hostActions===void 0)throw new Error("Host actions are disabled; configure options.hostActions first");await this.initialize(),await this.requireCliCapability(t.HOST_ACTION_CAPABILITY);let n=go(e);if(!this.hostActionDirect&&!this.closed&&!this.inputEnded&&this.transport.isReady())try{await this.transport.write(`${JSON.stringify(n)}
|
|
19
|
+
`);return}catch(s){this.diagnostics?.record("[QueryRunner] active Host action transport failed; using fallback:",s)}if(!this.hostActionFallback)throw new Error("Host action transport is no longer writable");await this.hostActionFallback(n)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).cancelled}async stopTask(e){await this.requireCliCapability(t.BACKGROUND_TASKS_CAPABILITY),await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){await this.requireCliCapability(t.BACKGROUND_TASKS_CAPABILITY);let n=await this.request({subtype:"background_tasks",tool_use_id:e});return typeof n?.backgrounded=="boolean"?n.backgrounded:!0}async setGoal(e){await this.requireCliCapability(t.GOAL_CAPABILITY);let n={subtype:"set_goal"};e.objective!==void 0&&(n.objective=e.objective),e.status!==void 0&&(n.status=e.status),e.creditsBudget!==void 0&&(n.credits_budget=e.creditsBudget);let s=e.customContext??this.initConfig.customContext;return s!==void 0&&(n.custom_context=s),(await this.request(n))?.goal??null}async setGoalMaxTurns(e){e!==null&&tt(e),await this.requireCliCapability(t.GOAL_MAX_TURNS_CAPABILITY);let n={subtype:"set_goal_max_turns",max_turns:e},s=await this.request(n);return tt(s.goal_max_turns),s.goal_max_turns}async resumeGoal(){await this.requireCliCapability(t.GOAL_RESUME_CAPABILITY);let e={subtype:"resume_goal"};return(await this.request(e))?.goal??null}async getGoal(){await this.requireCliCapability(t.GOAL_CAPABILITY);let e={subtype:"get_goal"};return(await this.request(e))?.goal??null}async clearGoal(){await this.requireCliCapability(t.GOAL_CAPABILITY);let e={subtype:"clear_goal"};return(await this.request(e))?.cleared===!0}async setPlanMode(e){await this.requireCliCapability(t.PLAN_MODE_CAPABILITY);let n={subtype:"set_plan_mode",active:e};return(await this.request(n)).plan_mode}async getPlanMode(){await this.requireCliCapability(t.PLAN_MODE_CAPABILITY);let e={subtype:"get_plan_mode"};return(await this.request(e)).plan_mode}async requireCliCapability(e){if(await this.initializationResult(),!this.cliCapabilities?.has(e))throw new L(e)}async setPermissionMode(e){let n=this.initConfig.independentPlanModeControls===!0?et(e):e==="yolo"?"bypassPermissions":e;if(n===void 0)throw new Error("permissionMode is required.");await this.request({type:"set_permission_mode",mode:n,...this.initConfig.independentPlanModeControls===!0?{preservePlanMode:!0}:{}})}waitForFirstResult(){return this.firstResultReceived||this.closed?Promise.resolve():new Promise(e=>{if(this.abortController?.signal.aborted){e();return}this.firstResultReceivedResolve=e,this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0})})}async setModel(e){await this.request({type:"set_model",model:e??""})}async enableRemoteProjection(e,n={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("remoteSessionId must be a non-empty string");if(n.fromSequenceNum!==void 0&&(!Number.isSafeInteger(n.fromSequenceNum)||n.fromSequenceNum<=0))throw new TypeError("fromSequenceNum must be a positive safe integer");await this.request({type:"enable_remote_projection",remote_session_id:e,...n.suppressInitialIdleStateEvents===!0?{suppress_initial_idle_state_events:!0}:{},...n.skipInitialFlush===!0?{skip_initial_flush:!0}:{},...n.fromSequenceNum===void 0?{}:{from_sequence_num:n.fromSequenceNum}},{requestIdPrefix:t.REMOTE_PROJECTION_REQUEST_ID_PREFIX,...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs}})}async disableRemoteProjection(e={}){let n=await this.request({type:"disable_remote_projection"},{requestIdPrefix:t.REMOTE_PROJECTION_REQUEST_ID_PREFIX,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});if(!(typeof n?.remote_session_id!="string"||n.remote_session_id.length===0||typeof n.last_sequence_num!="number"||!Number.isSafeInteger(n.last_sequence_num)||n.last_sequence_num<=0))return{remoteSessionId:n.remote_session_id,lastSequenceNum:n.last_sequence_num}}async setProxy(e){if(this.daemonProxyProvider){if(Fo(e)!==Fo(this.daemonProxyProvider()))throw new Error("proxy must be set via daemon.setProxy(); a daemon-bound Query cannot change it per session");return}await this.request({type:"set_proxy",proxy:e||null})}async generateSessionTitle(e,n){n?.sourceUserMessageId!==void 0&&await this.requireCliCapability("title_source_message_v1");let s=n?.customContext??this.initConfig.customContext;return(await this.request({type:"generate_session_title",...n?.sourceUserMessageId===void 0?{}:{source_user_message_id:n.sourceUserMessageId},description:e,...n?.persist!==void 0?{persist:n.persist}:{},...s!==void 0?{custom_context:s}:{}}))?.title??null}async askSideQuestion(e,n){await this.requireCliCapability(t.SIDE_QUESTION_CAPABILITY);let s=n?.customContext??this.initConfig.customContext,o=await this.request({subtype:"side_question",question:e,...n?.history?.length?{history:n.history.map(r=>({...r}))}:{},...s!==void 0?{custom_context:s}:{}},{timeoutMs:0,signal:n?.signal});return o?.response==null?null:{response:o.response,synthetic:o.synthetic??!1,...o.refusal_fallback?{refusalFallback:{originalModel:o.refusal_fallback.original_model,fallbackModel:o.refusal_fallback.fallback_model,content:o.refusal_fallback.content}}:{}}}async addDirectories(e){if(!Array.isArray(e))throw new Error("directories must be an array");return await this.request({type:"add_directories",directories:e})}async applyFlagSettings(e){await this.request({type:"apply_flag_settings",settings:e})}async supportedCommands(){return await this.initializationResult(),this.getLatestCommands()}async getAvailableModels(e){if(this.daemonAccountQueries)return await this.daemonAccountQueries.getModels(e)??[];let n={subtype:"get_models",...e?.fetchStrategy?{fetchStrategy:e.fetchStrategy}:{},...e?.uid?{uid:e.uid}:{},...e?.outerProviders?{outerProviders:e.outerProviders}:{}};return(await this.request(n))?.models??[]}async listByokProviders(){if(this.daemonAccountQueries)try{return await this.daemonAccountQueries.getByokConfig()??null}catch{return null}try{return(await this.request({type:"get_byok_config"}))?.providers??null}catch{return null}}async validateByokModel(e){if(this.daemonAccountQueries)try{let n=await this.daemonAccountQueries.validateByokModel(e);return typeof n=="boolean"?n:null}catch{return null}try{let n=await this.request({type:"validate_byok_model",provider:e.provider,model:e.model,api_key:e.api_key,...e.url!==void 0?{url:e.url}:{},...e.style!==void 0?{style:e.style}:{}});return typeof n?.success=="boolean"?n.success:null}catch{return null}}async listByokConfigs(e){if(e&&!e.uid?.trim())throw new Error("BYOK_UID_REQUIRED");return this.daemonAccountQueries&&!e?this.daemonAccountQueries.listByokConfigs():(await this.requireCliCapability(e?"byok_config_read_v1":t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),(await this.request({type:"list_byok_configs",...e?{uid:e.uid}:{}})).configs)}async createByokConfig(e){return this.daemonAccountQueries?this.daemonAccountQueries.createByokConfig(e):(await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),(await this.request({type:"create_byok_config",config:e})).config)}async updateByokConfig(e){if(this.daemonAccountQueries){await this.daemonAccountQueries.updateByokConfig(e);return}await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"update_byok_config",config:e})}async deleteByokConfig(e){if(this.daemonAccountQueries){await this.daemonAccountQueries.deleteByokConfig(e);return}await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"delete_byok_config",target:e})}async checkByokConfig(e){return this.daemonAccountQueries?this.daemonAccountQueries.checkByokConfig(e):(await this.requireCliCapability(t.BYOK_CONFIG_MANAGEMENT_CAPABILITY),await this.request({type:"check_byok_config",config:e}))}async supportedAgents(){return(await this.initializationResult()).agents??[]}async accountInfo(){if(this.daemonAccountQueries)try{let n=await this.daemonAccountQueries.accountInfo();if(n&&Object.keys(n).length>0)return n}catch{}else try{let n=await this.request({type:"account_info"});if(n?.account&&Object.keys(n.account).length>0)return n.account}catch{}return(await this.initializationResult()).account??{}}async mcpServerStatus(){return(await this.request({type:"mcp_status"}))?.servers??[]}async getContextUsage(){return await this.request({type:"get_context_usage"})}async getUsageInfo(){if(this.daemonAccountQueries)try{return await this.daemonAccountQueries.getUsageInfo()}catch{return null}try{let e=await this.request({type:"get_usage_info"}),n=kt(e?.usage),s=_t(e?.session);return!n&&!s?null:{...n??{},...s?{session:s}:{}}}catch{return null}}async reloadPlugins(){let e=await this.request({type:"reload_plugins"});return this.replaceLatestCommands(e.commands),e}async reloadSkills(){return await this.requireCliCapability("reload_skills_v1"),await this.request({type:"reload_skills"})}async listPlugins(){return(await this.request({type:"list_plugins"})).plugins}async rewindFiles(e,n){let s={type:"rewind_files",user_message_id:e};n?.dryRun&&(s.dry_run=!0);let r=await this.request(s);if(!n?.dryRun&&r?.canRewind===!1)throw new Error(typeof r.error=="string"&&r.error.length>0?r.error:"Unable to rewind files.");return r}async rewind(e,n){if(!(await this.initializationResult()).capabilities?.includes("session_rewind_v1"))throw new Error("The connected qodercli does not support full session rewind (session_rewind_v1).");let o={type:"rewind",user_message_id:e,scope:n?.scope??"both"};return n?.dryRun&&(o.dry_run=!0),await this.request(o)}async seedReadState(e,n){await this.request({type:"seed_read_state",path:e,mtime:n})}async flushMemory(){return this.memoryFlushPromise||(this.memoryFlushPromise=this.performMemoryFlush().finally(()=>{this.memoryFlushPromise=void 0})),this.memoryFlushPromise}async flushSkillEvolution(){return this.skillEvolutionFlushPromise||(this.skillEvolutionFlushPromise=this.performSkillEvolutionFlush().finally(()=>{this.skillEvolutionFlushPromise=void 0})),this.skillEvolutionFlushPromise}async performSkillEvolutionFlush(){await this.requireSkillEvolutionEnabled(),await this.request({type:"flush_skill_evolution"})}async requireSkillEvolutionEnabled(){let e=await this.initializationResult();if(!this.cliCapabilities?.has("skill_evolution_v1"))throw new L("skill_evolution_v1");if(e.evolution?.skill?.enabled!==!0||e.evolution.skill.requester!=="sdk")throw new Error("The connected CLI did not enable SDK skill evolution for this query")}async performMemoryFlush(){await this.requireSdkMemoryEnabled(),await this.request({type:"flush_memory"})}async refreshMemory(){await this.requireSdkMemoryEnabled(),await this.request({type:"refresh_memory"})}async requireSdkMemoryEnabled(){let e=await this.initializationResult();if(e.memory?.enabled!==!0||e.memory.requester!=="sdk")throw new Error("The connected CLI did not enable SDK memory for this query")}async reconnectMcpServer(e){await this.request({type:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,n){await this.request({type:"mcp_toggle",serverName:e,enabled:n})}async setMcpServers(e){let n=ps(e);return await this.request({type:"mcp_set_servers",servers:n})??{added:[],removed:[],errors:{}}}async injectMcpToken(e,n){await this.request({type:"mcp_inject_token",serverName:e,token:n})}async mcpAuthenticate(e,n){let s=await this.request({type:"mcp_authenticate",serverName:e,...n!==void 0?{redirectUri:n}:{}}),o=s?.requiresUserAction===!0,r=typeof s?.authUrl=="string"?s.authUrl:void 0;if(o&&r===void 0)throw new Error("mcp_authenticate response set requiresUserAction=true but did not include an authUrl");return o?{authUrl:r,requiresUserAction:!0}:{requiresUserAction:!1}}async mcpSubmitOAuthCallbackUrl(e,n){await this.request({type:"mcp_oauth_callback_url",serverName:e,callbackUrl:n})}async mcpClearAuth(e){await this.request({type:"mcp_clear_auth",serverName:e})}async close(){return this.closePromise||(this.closePromise=oe(this.diagnostics,"query","close",()=>this.performClose())),this.closePromise}async performClose(){if(this.closed)return;this.closed=!0;for(let[,s]of this.pendingInboundRequests)s.abortController.abort();this.pendingInboundRequests.clear(),this.hookCallbacks.clear();let e=new Error("SDK closing");for(let[s,o]of this.sdkMcpTransports){try{await oe(this.diagnostics,"query","mcp_close",()=>o.close())}catch(r){this.diagnostics?.record(`[QueryRunner] error closing SDK MCP transport "${s}":`,r)}_o(s,e,this.pendingMcpResponses)}let n;try{await oe(this.diagnostics,"query","transport_close",()=>this.transport.close())}catch(s){n={error:s}}try{await oe(this.diagnostics,"query","read_loop",()=>this.readLoopPromise)}catch{}if(await oe(this.diagnostics,"query","transcript_flush",()=>this.flushTranscriptMirrorForLifecycle()),n)throw n.error}async[Symbol.asyncDispose](){await this.close()}};function Nu(t){let e=t instanceof Error?t.message:String(t),n=typeof t=="object"&&t!==null?t.code:void 0,s=typeof n=="string"&&n.length>0?n:void 0,o=/^([a-z][a-z0-9_]*):\s*(.*)$/.exec(e);if(o){let r=s??o[1];return(!s||s===o[1])&&(e=o[2]||e),{error:e,code:r}}return s?{error:e,code:s}:{error:e}}function Uo(t){let e=/^(\d+)\.(\d+)(?:\.\d+)?(?:[-+].*)?$/.exec(t);return e?{major:Number(e[1]),minor:Number(e[2])}:null}var Nt=class{sendMcpMessage;isClosed=!1;onclose;onerror;onmessage;constructor(e){this.sendMcpMessage=e}async start(){}async send(e){if(this.isClosed)throw new Error("Transport is closed");this.sendMcpMessage(e)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}get closed(){return this.isClosed}};import{randomUUID as Ko}from"crypto";var ju="QODER_CLOUD_AGENT_API_BASE",Fu="https://api.qoder.com/api/v1/cloud",re={agentMessage:"agent.message",modelRequestEnd:"span.model_request_end",idle:"session.status_idle",error:"session.error",terminated:"terminated",userMessage:"user.message",userInterrupt:"user.interrupt"},Uu=1024,Lo=1*1024*1024,Bo=4*1024*1024,Ku=8*1024,xn=class extends Error{code="auth_access_token_env_var_not_configured";constructor(e){super(`The auth access token environment variable "${e}" is not set; set it or pass auth.accessToken directly.`),this.name="CloudAuthAccessTokenEnvVarError"}},jt=class extends Error{code="cloud_agent_auth_requires_access_token";constructor(){super("options.experimentalCloudAgent requires PAT authentication via accessToken() or accessTokenFromEnv()."),this.name="CloudAgentUnsupportedAuthError"}},On=class extends Error{code="cloud_agent_api_error";status;constructor(e,n){super(`Cloud Agent API request failed with status ${e}: ${n}`),this.name="CloudAgentApiError",this.status=e}},Lu=new Set(["abortController","auth","experimentalCloudAgent","debug","debugFile","stderr","env","includePartialMessages","onAuthExpired"]);function Go(t){if(!t.experimentalCloudAgent)return;let e=Object.keys(t).filter(r=>t[r]!==void 0&&!Lu.has(r));if(e.length>0)throw new Error(`options.experimentalCloudAgent cannot be combined with CLI runtime options: ${e.join(", ")}`);if(t.auth?.type!=="accessToken")throw new jt;let{agent:n,session:s}=t.experimentalCloudAgent;if(n&&qe(n)&&In(n))throw new Error("options.experimentalCloudAgent.agent must specify either id or create, not both.");if(s&&qe(s)&&In(s))throw new Error("options.experimentalCloudAgent.session must specify either id or create, not both.");if(s&&qe(s)&&n!==void 0)throw new Error("options.experimentalCloudAgent.agent cannot be combined with experimentalCloudAgent.session.id because an existing session already selects its agent.");let o=!!s&&qe(s);if(!o&&n===void 0)throw new Error("options.experimentalCloudAgent.agent is required when experimentalCloudAgent.session.id is not provided.");if(!o){if(!s||!In(s))throw new Error("options.experimentalCloudAgent.session.create is required when creating a Cloud Agent session.");if(typeof s.create.environment_id!="string"||s.create.environment_id.length===0)throw new Error("options.experimentalCloudAgent.session.create.environment_id is required when creating a Cloud Agent session.")}}function qe(t){return"id"in t&&t.id!==void 0}function In(t){return"create"in t&&t.create!==void 0}function Ho(t){return new qn(t)}var qn=class{experimentalCloudAgent;inputStream;abortController=new AbortController;accessToken;apiBase;diagnostics;onAuthExpired;sessionReadyPromise;readLoopPromise;sseConnected=nc();startedAt=Date.now();closed=!1;authExpiredFired=!1;sessionId;assistantTextParts=[];currentTurnId;lastSseEventId;hasCurrentTurn=!1;pendingTurnEvents=[];latestUsage=zo();latestModelUsage={};totalCostUsd=0;postedMessages=0;activeInputStreams=0;idleSeen=!1;resultEmitted=!1;constructor(e){if(!e.options.experimentalCloudAgent)throw new Error("options.experimentalCloudAgent is required for CloudAgentQuery.");this.experimentalCloudAgent=e.options.experimentalCloudAgent,this.diagnostics=e.diagnostics,this.onAuthExpired=e.options.onAuthExpired,this.accessToken=Bu(e.options.auth,e.options.env),this.apiBase=$u(),this.inputStream=new te(()=>{this.close().catch(()=>{})});let n=e.options.abortController?.signal;n?.aborted?this.abortController.abort():n?.addEventListener("abort",()=>{this.close().catch(()=>{})},{once:!0}),this.sessionReadyPromise=this.initializeCloudSession(),this.readLoopPromise=this.readCloudEvents().catch(s=>{this.sseConnected.reject(s),this.closed||this.inputStream.error(s)}),this.streamInput(ec(e.prompt)).catch(s=>{this.closed||this.inputStream.error(s)})}[Symbol.asyncIterator](){return this}async next(){return this.inputStream.next()}async return(){return await this.close(),{done:!0,value:void 0}}async throw(e){return await this.inputStream.throw(e),{done:!0,value:void 0}}async initializationResult(){return(await this.sessionReadyPromise).init}async streamInput(e){this.activeInputStreams+=1,(async()=>{try{await this.sessionReadyPromise,await this.sseConnected.promise;for await(let n of e){if(this.closed)break;if(n?.type!=="user")throw new Error("Expected a user input message.");let s=Zu(n);this.beginPendingTurn();let o=await this.postSessionEvents([{type:re.userMessage,content:s}]);this.postedMessages+=1,this.activateTurn(o.find(r=>r.type===re.userMessage)?.turnId)}}finally{this.activeInputStreams=Math.max(0,this.activeInputStreams-1),this.finishIfIdle()}})().catch(n=>{this.closed||this.inputStream.error(n)})}async interrupt(){await this.sessionReadyPromise,await this.postSessionEvents([{type:re.userInterrupt}])}async cancelAsyncMessage(e){this.unsupported("cancelAsyncMessage")}async sendHostAction(e){throw new Error("Host actions are not supported by Cloud Agent queries.")}async stopTask(e){this.unsupported("stopTask")}async backgroundTasks(e){this.unsupported("backgroundTasks")}async setPermissionMode(e){this.unsupported("setPermissionMode")}async setModel(e){this.unsupported("setModel")}async setProxy(e){this.unsupported("setProxy")}async generateSessionTitle(e,n){this.unsupported("generateSessionTitle")}async addDirectories(e){this.unsupported("addDirectories")}async applyFlagSettings(e){this.unsupported("applyFlagSettings")}async supportedCommands(){this.unsupported("supportedCommands")}async getAvailableModels(){this.unsupported("getAvailableModels")}async listByokProviders(){this.unsupported("listByokProviders")}async validateByokModel(e){this.unsupported("validateByokModel")}async listByokConfigs(){this.unsupported("listByokConfigs")}async createByokConfig(e){this.unsupported("createByokConfig")}async updateByokConfig(e){this.unsupported("updateByokConfig")}async deleteByokConfig(e){this.unsupported("deleteByokConfig")}async checkByokConfig(e){this.unsupported("checkByokConfig")}async supportedAgents(){this.unsupported("supportedAgents")}async mcpServerStatus(){this.unsupported("mcpServerStatus")}async getContextUsage(){this.unsupported("getContextUsage")}async getUsageInfo(){this.unsupported("getUsageInfo")}async reloadPlugins(){this.unsupported("reloadPlugins")}async reloadSkills(){this.unsupported("reloadSkills")}async listPlugins(){this.unsupported("listPlugins")}async accountInfo(){this.unsupported("accountInfo")}async rewindFiles(e,n){this.unsupported("rewindFiles")}async rewind(e,n){this.unsupported("rewind")}async seedReadState(e,n){this.unsupported("seedReadState")}async flushMemory(){this.unsupported("flushMemory")}async flushSkillEvolution(){this.unsupported("flushSkillEvolution")}async refreshMemory(){this.unsupported("refreshMemory")}async mcpAuthenticate(e,n){this.unsupported("mcpAuthenticate")}async mcpSubmitOAuthCallbackUrl(e,n){this.unsupported("mcpSubmitOAuthCallbackUrl")}async close(){this.finish();try{await this.readLoopPromise}catch{}}async[Symbol.asyncDispose](){await this.close()}async initializeCloudSession(){if(this.closed)throw new Error("Cloud Agent query is closed.");let{session:e}=this.experimentalCloudAgent,n;if(e&&qe(e))n=e.id;else{let s=await this.resolveAgentId(),o=e.create,r=await this.requestJson("/sessions",{method:"POST",body:{agent:s,...zu(o)}});n=$o(r,"Cloud session")}return this.sessionId=n,this.diagnostics?.record(`[cloud-agent] session ready: ${n}`),{sessionId:n,init:{commands:[],agents:[],output_style:"cloud-agent",available_output_styles:["cloud-agent"],models:[],account:{}}}}async resolveAgentId(){let{agent:e}=this.experimentalCloudAgent;if(!e)throw new Error("options.experimentalCloudAgent.agent is required when experimentalCloudAgent.session.id is not provided.");if(qe(e))return e.id;let n=await this.requestJson("/agents",{method:"POST",body:Qu(e.create)});return $o(n,"Cloud agent")}async readCloudEvents(){let{sessionId:e}=await this.sessionReadyPromise,n=0;for(;!this.closed;){let s=this.lastSseEventId;if(await this.readCloudEventStream(e),this.closed||this.resultEmitted)return;if(!this.shouldReconnectSse()||n>=3){this.finishAfterSseClosed();return}this.lastSseEventId!==s&&(n=0),n+=1,await tc(250*n,this.abortController.signal)}}async readCloudEventStream(e){let n=new URL(`${this.apiBase}/sessions/${encodeURIComponent(e)}/events/stream`),s=this.lastSseEventId??this.experimentalCloudAgent.stream?.afterId;s&&n.searchParams.set("after_id",s),this.experimentalCloudAgent.stream?.deltaFlushIntervalMs!==void 0&&n.searchParams.set("delta_flush_interval_ms",String(this.experimentalCloudAgent.stream.deltaFlushIntervalMs));let o=await fetch(n.toString(),{headers:this.authHeaders({accept:"text/event-stream"}),signal:this.abortController.signal});if(!o.ok)throw this.handleAuthFailure(o.status),await Qo(o);if(!o.body)throw new Error("Cloud Agent SSE response did not include a body.");this.sseConnected.resolve(),await this.readSseBody(o.body)}async readSseBody(e){let n=e.getReader(),s=new TextDecoder,o="",r={data:[],dataBytes:0};try{for(;!this.closed;){let{done:i,value:a}=await n.read();if(i){o+=s.decode(),o.length>0&&this.consumeSseLine(o,r);break}o+=s.decode(a,{stream:!0});let u;for(;(u=o.indexOf(`
|
|
20
|
+
`))!==-1;){let c=o.slice(0,u);o=o.slice(u+1);let l=c.endsWith("\r")?c.slice(0,-1):c;if(this.consumeSseLine(l,r),this.closed)break}o.length>Lo&&(this.diagnostics?.record(`[cloud-agent] SSE line exceeded ${Lo} bytes; resetting buffer.`),o="",r.id=void 0,r.event=void 0,r.data.length=0,r.dataBytes=0)}}finally{try{await n.cancel()}catch{}n.releaseLock()}}consumeSseLine(e,n){if(e===""){(n.event||n.data.length>0)&&this.handleSseEvent({id:n.id,event:n.event??"message",data:Wu(n.data.join(`
|
|
21
|
+
`))}),n.id=void 0,n.event=void 0,n.data.length=0,n.dataBytes=0;return}if(e.startsWith(":"))return;let s=e.indexOf(":"),o=s===-1?e:e.slice(0,s),r=s===-1?"":e.slice(s+1);switch(r.startsWith(" ")&&(r=r.slice(1)),o){case"id":n.id=r;break;case"event":n.event=r;break;case"data":if(n.dataBytes+r.length>Bo){this.diagnostics?.record(`[cloud-agent] SSE event data exceeded ${Bo} bytes; dropping event.`),n.id=void 0,n.event=void 0,n.data.length=0,n.dataBytes=0;return}n.data.push(r),n.dataBytes+=r.length;break}}handleSseEvent(e){if(this.closed)return;let n=$(e.data,"type")??e.event,s=$(e.data,"turn_id"),o={type:"cloud_agent_event",event:n,id:e.id,data:e.data,uuid:e.id??Ko(),session_id:this.sessionId??$(e.data,"session_id")??""};if(e.id&&(this.lastSseEventId=e.id),this.inputStream.enqueue(o),!this.isCurrentTurnEvent(s)){this.bufferPendingTurnEvent(e,n,s);return}this.handleCurrentTurnEvent(e,n)}handleCurrentTurnEvent(e,n){switch(n){case re.agentMessage:{let s=Vu(st(e.data,"content"));s&&this.assistantTextParts.push(s);return}case re.modelRequestEnd:this.captureUsage(e.data);return;case re.idle:this.idleSeen=!0,this.finishIfIdle();return;case re.error:this.emitErrorResult(e),this.finish();return;case re.terminated:this.resultEmitted||this.emitSuccessResult(),this.finish();return}}beginPendingTurn(){this.currentTurnId=void 0,this.hasCurrentTurn=!1,this.pendingTurnEvents=[],this.assistantTextParts=[],this.latestUsage=zo(),this.latestModelUsage={},this.totalCostUsd=0,this.idleSeen=!1}activateTurn(e){this.currentTurnId=e,this.hasCurrentTurn=!0;let n=this.pendingTurnEvents;this.pendingTurnEvents=[];for(let s of n)if(this.isCurrentTurnEvent(s.turnId)&&this.handleCurrentTurnEvent(s.event,s.type),this.closed)break}isCurrentTurnEvent(e){return this.hasCurrentTurn?this.currentTurnId?e===this.currentTurnId:e===void 0:!1}bufferPendingTurnEvent(e,n,s){this.hasCurrentTurn||this.activeInputStreams===0||(this.pendingTurnEvents.length>=Uu&&this.pendingTurnEvents.shift(),this.pendingTurnEvents.push({event:e,type:n,turnId:s}))}finishIfIdle(){this.closed||!this.idleSeen||this.activeInputStreams>0||this.postedMessages===0||(this.emitSuccessResult(),this.finish())}finishAfterSseClosed(){this.finishIfIdle(),!this.closed&&(!this.resultEmitted&&(this.hasCurrentTurn||this.postedMessages>0||this.activeInputStreams>0)&&this.emitErrorResultMessage("Cloud Agent SSE stream closed before the current turn reached a terminal state."),this.finish())}shouldReconnectSse(){return!this.resultEmitted&&(this.hasCurrentTurn||this.postedMessages>0||this.activeInputStreams>0)}emitSuccessResult(){this.resultEmitted||this.closed||(this.resultEmitted=!0,this.inputStream.enqueue({...this.buildResultBase(),subtype:"success",is_error:!1,result:this.assistantTextParts.join("")}))}emitErrorResult(e){this.emitErrorResultMessage($(e.data,"error")??$(Ft(e.data,"error"),"message")??"Cloud Agent session failed.")}emitErrorResultMessage(e){this.resultEmitted||this.closed||(this.resultEmitted=!0,this.inputStream.enqueue({...this.buildResultBase(),subtype:"error_during_execution",is_error:!0,errors:[e]}))}buildResultBase(){let e=Date.now()-this.startedAt;return{type:"result",duration_ms:e,duration_api_ms:e,num_turns:Math.max(1,this.postedMessages),stop_reason:null,total_cost_usd:this.totalCostUsd,usage:this.latestUsage,modelUsage:this.latestModelUsage,permission_denials:[],uuid:Ko(),session_id:this.sessionId??""}}async postSessionEvents(e){let n=this.sessionId??(await this.sessionReadyPromise).sessionId,s=await this.requestJson(`/sessions/${encodeURIComponent(n)}/events`,{method:"POST",body:{events:e}});return Gu(s)}captureUsage(e){let n=Ft(e,"usage");if(!n)return;this.latestUsage=Yu(this.latestUsage,n);let s=F(e,"total_cost_usd")??F(e,"cost_usd")??F(n,"total_cost_usd")??F(n,"cost_usd");s!==void 0&&(this.totalCostUsd+=s);let o=$(e,"model")??$(n,"model");if(o){let r=this.latestModelUsage[o]?.costUSD??0;this.latestModelUsage[o]=Xu(this.latestUsage,r+(s??0))}}async requestJson(e,n){let s=await fetch(`${this.apiBase}${e}`,{method:n.method,headers:this.authHeaders({accept:"application/json",contentType:n.body?"application/json":void 0}),body:n.body?JSON.stringify(n.body):void 0,signal:this.abortController.signal});if(!s.ok)throw this.handleAuthFailure(s.status),await Qo(s);if(s.status===204)return{};try{return await s.json()}catch{return{}}}authHeaders(e){let n={Authorization:`Bearer ${this.accessToken}`,Accept:e.accept};return e.contentType&&(n["Content-Type"]=e.contentType),n}handleAuthFailure(e){if((e===401||e===403)&&!this.authExpiredFired){this.authExpiredFired=!0;try{this.onAuthExpired?.()}catch(n){this.diagnostics?.record("[cloud-agent] onAuthExpired callback threw:",n)}}}finish(){this.closed||(this.closed=!0,this.abortController.abort(),this.sseConnected.resolve(),this.inputStream.done())}unsupported(e){throw new Error(`Query.${e}() is not supported when options.experimentalCloudAgent is enabled.`)}};function Bu(t,e){if(t?.type!=="accessToken")throw new jt;if(typeof t.accessToken=="string")return t.accessToken;let n=t.accessToken.envVar,s=e&&Object.hasOwn(e,n)?e[n]:process.env[n];if(!s)throw new xn(n);return s}function $u(){return process.env[ju]?.replace(/\/+$/,"")??Fu}function Qu(t){return Nn({name:t.name,model:t.model,system:t.system,description:t.description,tools:t.tools,mcp_servers:t.mcp_servers,skills:t.skills,metadata:t.metadata})}function zu(t){return Nn({title:t.title,environment_id:t.environment_id,resources:t.resources?.map(e=>Nn({...e})),vault_ids:t.vault_ids,memory_store_ids:t.memory_store_ids})}function Nn(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function $o(t,e){let n=$(t,"id");if(!n)throw new Error(`${e} response did not include an id.`);return n}function Gu(t){let e=Ju(t,"data");return e?e.flatMap(n=>n===null||typeof n!="object"||Array.isArray(n)?[]:[{id:$(n,"id"),turnId:$(n,"turn_id"),type:$(n,"type")}]):[]}async function Qo(t){let e=await Hu(t,Ku);return new On(t.status,e||t.statusText||"unknown error")}async function Hu(t,e){if(!t.body)try{return(await t.text()).slice(0,e)}catch{return""}let n=t.body.getReader(),s=new TextDecoder,o=[],r=0;try{for(;r<e;){let{done:i,value:a}=await n.read();if(i)break;r+=a.byteLength,o.push(s.decode(a,{stream:!0}))}o.push(s.decode())}catch{}finally{try{await n.cancel()}catch{}n.releaseLock()}return o.join("").slice(0,e)}function Wu(t){if(t.length===0)return{};try{return JSON.parse(t)}catch{return t}}function Ft(t,e){let n=st(t,e);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Ju(t,e){let n=st(t,e);return Array.isArray(n)?n:void 0}function $(t,e){let n=st(t,e);return typeof n=="string"?n:void 0}function F(t,e){let n=st(t,e);return typeof n=="number"&&Number.isFinite(n)?n:void 0}function st(t,e){if(!(t===null||typeof t!="object"||Array.isArray(t)))return t[e]}function Vu(t){return typeof t=="string"?t:Array.isArray(t)&&t.map(n=>Wo(n)?n.text:"").filter(Boolean).join("")||void 0}function Yu(t,e){let n=Ft(e,"cache_creation"),s=Ft(e,"server_tool_use");return{...t,cache_creation:{ephemeral_1h_input_tokens:F(n,"ephemeral_1h_input_tokens")??t.cache_creation.ephemeral_1h_input_tokens,ephemeral_5m_input_tokens:F(n,"ephemeral_5m_input_tokens")??t.cache_creation.ephemeral_5m_input_tokens},cache_creation_input_tokens:F(e,"cache_creation_input_tokens")??t.cache_creation_input_tokens,cache_read_input_tokens:F(e,"cache_read_input_tokens")??t.cache_read_input_tokens,input_tokens:F(e,"input_tokens")??t.input_tokens,output_tokens:F(e,"output_tokens")??t.output_tokens,server_tool_use:{web_fetch_requests:F(s,"web_fetch_requests")??t.server_tool_use.web_fetch_requests,web_search_requests:F(s,"web_search_requests")??t.server_tool_use.web_search_requests}}}function Xu(t,e){return{inputTokens:t.input_tokens,outputTokens:t.output_tokens,cacheReadInputTokens:t.cache_read_input_tokens,cacheCreationInputTokens:t.cache_creation_input_tokens,webSearchRequests:t.server_tool_use.web_search_requests,costUSD:e,contextWindow:0,maxOutputTokens:0}}function Zu(t){let e=t.message.content;return typeof e=="string"?e:Array.isArray(e)?e.map(n=>Wo(n)?n.text:JSON.stringify(n)).join(`
|
|
22
|
+
`):JSON.stringify(e)}function Wo(t){return t!==null&&typeof t=="object"&&"type"in t&&t.type==="text"&&"text"in t&&typeof t.text=="string"}function ec(t){return typeof t!="string"?t:async function*(){yield{type:"user",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null}}()}function zo(){return{cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:0,inference_geo:"",input_tokens:0,iterations:[],output_tokens:0,server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard",speed:"standard"}}async function tc(t,e){e.aborted||await new Promise(n=>{let s=setTimeout(n,t);e.addEventListener("abort",()=>{clearTimeout(s),n()},{once:!0})})}function nc(){let t,e;return{promise:new Promise((s,o)=>{t=s,e=o}),resolve:t,reject:e}}import{access as sc,chmod as Xo,cp as oc,mkdtemp as rc,mkdir as Zo,realpath as er,rm as Jo,writeFile as ic}from"fs/promises";import{homedir as ac,tmpdir as uc}from"os";import{dirname as cc,isAbsolute as tr,join as ge,relative as lc,resolve as jn,sep as dc}from"path";var pc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,mc=6e4;async function nr(t){if(t.resume===void 0&&!t.continue)return;let e=j(await hc(t.cwd)),n=t.loadTimeoutMs??mc,s=t.resume!==void 0?t.resume:await yc(t.store,e,n);if(s===void 0||!pc.test(s))return;let o={projectKey:e,sessionId:s},r=await Vo(t.store,o,n);if(!r)return;let i=t.store.listSubkeys?await Fn(t.store.listSubkeys(o),n,"listSubkeys"):[];if(!Array.isArray(i))throw new Error("SessionStore listSubkeys() must return an array");let a=[];for(let c of i){if(!vc(c)){console.warn(`[SessionStore] skipping unsafe subpath from listSubkeys: ${String(c)}`);continue}let l=await Vo(t.store,{...o,subpath:c},n);l&&a.push({subpath:c,entries:l})}let u;try{u=await rc(ge(uc(),"qoder-session-store-")),await Xo(u,448),u=await er(u),await gc(fc(t.env),u);let c=ge(u,"projects",e),l=ge(c,s);await Zo(c,{recursive:!0,mode:448}),await Yo(ge(c,`${s}.jsonl`),r);for(let{subpath:p,entries:d}of a){let f=wc(l,`${p}.jsonl`),S=d.filter(v=>v.type==="agent_metadata"),g=d.filter(v=>v.type!=="agent_metadata");if(g.length>0&&await Yo(f,g),S.length>0){let v={...S.at(-1)};delete v.type,await sr(f.slice(0,-6)+".meta.json",JSON.stringify(v))}}let m=u;return{configDir:m,projectKey:e,sessionId:s,cleanup:async()=>{await Jo(m,{recursive:!0,force:!0})}}}catch(c){throw u!==void 0&&await Jo(u,{recursive:!0,force:!0}),c}}function fc(t){let e=t?.[w.cliHomeEnv]??process.env[w.cliHomeEnv]??ac();return jn(t?.[w.configDirEnv]??process.env[w.configDirEnv]??ge(e,w.configDirName))}async function gc(t,e){for(let n of[".auth","oauth_creds.json"]){let s=ge(t,n);try{await sc(s),await oc(s,ge(e,n),{recursive:!0,force:!1,preserveTimestamps:!0})}catch(o){if(o.code!=="ENOENT")throw o}}}async function hc(t){let e=jn(t??process.cwd());try{return await er(e)}catch{return e}}async function yc(t,e,n){if(!t.listSessions)throw new Error("sessionStore.listSessions() is required when options.continue is true");let s=await Fn(t.listSessions(e),n,"listSessions");if(!Array.isArray(s))throw new Error("SessionStore listSessions() must return an array");return s.slice().sort((o,r)=>r.mtime-o.mtime)[0]?.sessionId}async function Vo(t,e,n){let s=await Fn(t.load({...e}),n,"load");if(!(s===null||s.length===0)){if(!Array.isArray(s))throw new Error("SessionStore load() must return an array or null");return s.map((o,r)=>Sc(o,r))}}function Sc(t,e){if(t===null||typeof t!="object"||typeof t.type!="string")throw new Error(`SessionStore entry ${e} is not a typed object`);try{let n=JSON.stringify(t);if(n===void 0)throw new Error("JSON serialization returned undefined");return JSON.parse(n)}catch(n){throw new Error(`SessionStore entry ${e} is not JSON-safe`,{cause:n})}}function vc(t){return!(typeof t!="string"||!t||t.includes("\0")||t.includes("\\")||tr(t)||/^[a-z]:/i.test(t)||t.replaceAll("\\","/").split("/").some(e=>!e||e==="."||e===".."))}function wc(t,e){let n=jn(t,e),s=lc(t,n);if(s===""||s===".."||s.startsWith(`..${dc}`)||tr(s))throw new Error(`SessionStore subpath escapes the session: ${e}`);return n}async function Yo(t,e){let n=e.map(s=>JSON.stringify(s)).join(`
|
|
23
|
+
`);await sr(t,n?`${n}
|
|
24
|
+
`:"")}async function sr(t,e){await Zo(cc(t),{recursive:!0,mode:448}),await ic(t,e,{encoding:"utf8",mode:384}),await Xo(t,384)}async function Fn(t,e,n){let s;t.catch(()=>{});try{return await Promise.race([t,new Promise((o,r)=>{s=setTimeout(()=>r(new Error(`SessionStore ${n} timed out after ${e}ms`)),e)})])}finally{s!==void 0&&clearTimeout(s)}}import or from"node:path";function Ne(t,e){if(typeof t!="string"||t.trim()==="")throw new TypeError(`${e} must be a non-empty string`)}function ot(t,e){if(t!==void 0&&typeof t!="function")throw new TypeError(`${e} must be a function`)}function bc(t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0)throw new TypeError("options.memory.generation.roots must be a non-empty array");let e=new Set;for(let[n,s]of t.entries()){if(!s||typeof s!="object")throw new TypeError(`options.memory.generation.roots[${n}] must be an object`);if(Ne(s.id,`options.memory.generation.roots[${n}].id`),Ne(s.path,`options.memory.generation.roots[${n}].path`),e.has(s.id))throw new TypeError(`options.memory.generation.roots contains duplicate id "${s.id}"`);if(e.add(s.id),s.access!==void 0&&s.access!=="read"&&s.access!=="read-write")throw new TypeError(`options.memory.generation.roots[${n}].access must be "read" or "read-write"`);if(s.indexFile!==void 0){Ne(s.indexFile,`options.memory.generation.roots[${n}].indexFile`);let o=s.indexFile.replaceAll("\\","/");if(or.posix.isAbsolute(o)||or.win32.isAbsolute(s.indexFile)||o.split("/").includes(".."))throw new TypeError(`options.memory.generation.roots[${n}].indexFile must stay within its root`)}}}function _c(t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0)throw new TypeError("options.memory.consumption.files must be a non-empty array");let e=new Set;for(let[n,s]of t.entries()){if(!s||typeof s!="object")throw new TypeError(`options.memory.consumption.files[${n}] must be an object`);if(Ne(s.id,`options.memory.consumption.files[${n}].id`),Ne(s.path,`options.memory.consumption.files[${n}].path`),e.has(s.id))throw new TypeError(`options.memory.consumption.files contains duplicate id "${s.id}"`);if(e.add(s.id),s.required!==void 0&&typeof s.required!="boolean")throw new TypeError(`options.memory.consumption.files[${n}].required must be a boolean`)}}function rr(t){if(t===void 0)return{};if(!t||typeof t!="object")throw new TypeError("options.memory must be an object");if(Array.isArray(t))throw new TypeError("options.memory must be an object");if(Object.keys(t).length===0)return{};if(t.mode!=="native"&&t.mode!=="custom")throw new TypeError('options.memory.mode must be "native" or "custom"');if(t.projectScope!==void 0&&typeof t.projectScope!="boolean")throw new TypeError("options.memory.projectScope must be a boolean");if(t.userScope!==void 0&&typeof t.userScope!="boolean")throw new TypeError("options.memory.userScope must be a boolean");let e=new Map;if(t.mode==="native"){if(t.projectScope===!1&&t.userScope===!1)throw new TypeError("options.memory native mode requires at least one enabled scope; use memory: {} to disable SDK memory");let i=Object.keys(t.generation??{}),a=Object.keys(t.consumption??{});if(i.some(u=>u!=="onResult")||a.some(u=>u!=="onResult"))throw new TypeError('options.memory mode "native" only accepts generation.onResult and consumption.onResult');return ot(t.generation?.onResult,"options.memory.generation.onResult"),ot(t.consumption?.onResult,"options.memory.consumption.onResult"),{config:{requester:"sdk",mode:"native",...t.projectScope!==void 0?{projectScope:t.projectScope}:{},...t.userScope!==void 0?{userScope:t.userScope}:{}},callbacks:{shouldGenerateCallbacks:e,onGenerationResult:t.generation?.onResult,onConsumptionResult:t.consumption?.onResult}}}let n,s=t.generation;if(s!==void 0){if(!s||typeof s!="object")throw new TypeError("options.memory.generation must be an object");if(s.enabled!==void 0&&typeof s.enabled!="boolean")throw new TypeError("options.memory.generation.enabled must be a boolean");bc(s.roots),s.prompt!==void 0&&Ne(s.prompt,"options.memory.generation.prompt"),ot(s.onResult,"options.memory.generation.onResult");let i;if(s.turnComplete!==void 0){let a=s.turnComplete;if(!a||typeof a!="object")throw new TypeError("options.memory.generation.turnComplete must be an object");if(a.enabled!==void 0&&typeof a.enabled!="boolean")throw new TypeError("options.memory.generation.turnComplete.enabled must be a boolean");if(ot(a.shouldGenerate,"options.memory.generation.turnComplete.shouldGenerate"),a.timeoutMs!==void 0&&(!Number.isFinite(a.timeoutMs)||a.timeoutMs<=0))throw new TypeError("options.memory.generation.turnComplete.timeoutMs must be a positive finite number");if(a.onGateError!==void 0&&a.onGateError!=="skip"&&a.onGateError!=="report_failed")throw new TypeError('options.memory.generation.turnComplete.onGateError must be "skip" or "report_failed"');let u=a.shouldGenerate?"memory_should_generate_0":void 0;u&&a.shouldGenerate&&e.set(u,a.shouldGenerate),i={enabled:a.enabled??!0,shouldGenerateCallbackId:u,timeoutMs:a.timeoutMs,onGateError:a.onGateError}}if(s.turnComplete?.enabled===!0&&s.enabled===!1)throw new TypeError("options.memory.generation.turnComplete cannot be enabled when generation.enabled is false");n={enabled:s.enabled??!0,roots:s.roots?.map(a=>({...a})),prompt:s.prompt,turnComplete:i}}let o,r=t.consumption;if(r!==void 0){if(!r||typeof r!="object")throw new TypeError("options.memory.consumption must be an object");if(r.enabled!==void 0&&typeof r.enabled!="boolean")throw new TypeError("options.memory.consumption.enabled must be a boolean");if(_c(r.files),r.maxTokens!==void 0&&(!Number.isInteger(r.maxTokens)||r.maxTokens<=0))throw new TypeError("options.memory.consumption.maxTokens must be a positive integer");if(r.overflow!==void 0&&r.overflow!=="truncate"&&r.overflow!=="fail_query")throw new TypeError('options.memory.consumption.overflow must be "truncate" or "fail_query"');if(r.failureMode!==void 0&&r.failureMode!=="best_effort"&&r.failureMode!=="fail_query")throw new TypeError('options.memory.consumption.failureMode must be "best_effort" or "fail_query"');ot(r.onResult,"options.memory.consumption.onResult"),o={enabled:r.enabled??!0,files:r.files?.map(i=>({...i,required:i.required??!1})),maxTokens:r.maxTokens,overflow:r.overflow,failureMode:r.failureMode}}return{config:{requester:"sdk",mode:t.mode,...t.projectScope!==void 0?{projectScope:t.projectScope}:{},...t.userScope!==void 0?{userScope:t.userScope}:{},generation:n,consumption:o},callbacks:{shouldGenerateCallbacks:e,onGenerationResult:s?.onResult,onConsumptionResult:r?.onResult}}}var Ut=10;function kc(t,e){if(typeof t!="string"||t.trim()==="")throw new TypeError(`${e} must be a non-empty string`)}function Kt(t,e){if(t!==void 0&&typeof t!="function")throw new TypeError(`${e} must be a function`)}function ir(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>10)throw new TypeError(`options.evolution.skill.generation.turnComplete.reviewThreshold must be an integer between 1 and ${10}`);return t}}function Cc(t){let e={shouldReviewCallbacks:new Map};if(t===void 0)return{config:void 0,callbacks:e};if(!t||typeof t!="object")throw new TypeError("options.evolution.skill.generation must be an object");if("roots"in t)throw new TypeError("options.evolution.skill.generation does not accept roots; roots are derived from loaded skills");if(t.enabled!==void 0&&typeof t.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.enabled must be a boolean");if(t.prompt!==void 0&&kc(t.prompt,"options.evolution.skill.generation.prompt"),t.maxSuggestions!==void 0&&(!Number.isInteger(t.maxSuggestions)||t.maxSuggestions<1||t.maxSuggestions>10))throw new TypeError("options.evolution.skill.generation.maxSuggestions must be an integer between 1 and 10");Kt(t.onResult,"options.evolution.skill.generation.onResult");let n;if(t.turnComplete!==void 0){if(!t.turnComplete||typeof t.turnComplete!="object")throw new TypeError("options.evolution.skill.generation.turnComplete must be an object");if(t.turnComplete.enabled!==void 0&&typeof t.turnComplete.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.turnComplete.enabled must be a boolean");let s=ir(t.turnComplete.reviewThreshold);if(Kt(t.turnComplete.shouldReview,"options.evolution.skill.generation.turnComplete.shouldReview"),t.turnComplete.timeoutMs!==void 0&&(!Number.isFinite(t.turnComplete.timeoutMs)||t.turnComplete.timeoutMs<=0))throw new TypeError("options.evolution.skill.generation.turnComplete.timeoutMs must be a positive finite number");if(t.turnComplete.onGateError!==void 0&&t.turnComplete.onGateError!=="skip"&&t.turnComplete.onGateError!=="report_failed")throw new TypeError('options.evolution.skill.generation.turnComplete.onGateError must be "skip" or "report_failed"');let o=t.turnComplete.shouldReview?"skill_evolution_should_review_0":void 0;o&&e.shouldReviewCallbacks.set(o,t.turnComplete.shouldReview),n={enabled:t.turnComplete.enabled??!0,reviewThreshold:s,shouldReviewCallbackId:o,timeoutMs:t.turnComplete.timeoutMs,onGateError:t.turnComplete.onGateError}}if(t.turnComplete!==void 0&&n?.enabled===!0&&t.enabled===!1)throw new TypeError("options.evolution.skill.generation.turnComplete cannot be enabled when generation.enabled is false");return{config:{enabled:t.enabled??!0,prompt:t.prompt,maxSuggestions:t.maxSuggestions,turnComplete:n},callbacks:{...e,onResult:t.onResult}}}function ar(t){if(t===void 0)return{};if(!t||typeof t!="object")throw new TypeError("options.evolution.skill must be an object");if(t.mode!=="native"&&t.mode!=="custom")throw new TypeError('options.evolution.skill.mode must be "native" or "custom"');let e=t.generation;if(t.mode==="native"){if(Object.keys(e??{}).some(i=>i!=="enabled"&&i!=="onResult"&&i!=="turnComplete"))throw new TypeError('options.evolution.skill mode "native" only accepts generation.enabled, generation.onResult, and generation.turnComplete.reviewThreshold');if(e?.enabled!==void 0&&typeof e.enabled!="boolean")throw new TypeError("options.evolution.skill.generation.enabled must be a boolean");let o=e?.turnComplete;if(o!==void 0){if(!o||typeof o!="object")throw new TypeError("options.evolution.skill.generation.turnComplete must be an object");if(Object.keys(o).some(i=>i!=="reviewThreshold"))throw new TypeError('options.evolution.skill mode "native" only accepts generation.turnComplete.reviewThreshold')}let r=ir(o?.reviewThreshold);return e?.enabled===!1?(Kt(e?.onResult,"options.evolution.skill.generation.onResult"),{callbacks:{shouldReviewCallbacks:new Map,onResult:e?.onResult}}):(Kt(e?.onResult,"options.evolution.skill.generation.onResult"),{config:{requester:"sdk",mode:"native",...r===void 0?{}:{generation:{turnComplete:{reviewThreshold:r}}}},callbacks:{shouldReviewCallbacks:new Map,onResult:e?.onResult}})}let n=Cc(e);return n.config?.enabled===!1?{callbacks:n.callbacks}:{config:{requester:"sdk",mode:"custom",generation:n.config},callbacks:n.callbacks}}import{execFile as Pc,spawn as Ec}from"child_process";import{randomUUID as Tc}from"node:crypto";import{homedir as Mc}from"node:os";import{resolve as cr}from"node:path";var Rc=/^(?:qoder(?:cli|clicn|cn)?-)?worker-runtime(?:\.obf)?\.mjs$/i;function Un(t){let e=t.replace(/\\/g,"/").split("/").at(-1)??"";return Rc.test(e)}function ur(t,e,n=process.env){let s=t.pathToQoderCLIExecutable;return s?Un(s)?{transport:"worker",pathToQoderWorkerRuntime:s}:{transport:"process"}:t.executable!==void 0||t.executableArgs!==void 0||t.spawnQoderCLIProcess!==void 0?{transport:"process"}:n.QODERCLI_PATH?{transport:"process"}:{transport:e}}function lr(){return Pe()}function dr(t=process.env){return cr(t.QODERCLI_HOST_ACTION_STORAGE_DIR??t[w.configDirEnv]??cr(t[w.cliHomeEnv]??Mc(),t[`${w.configDirEnv}_NAME`]??w.configDirName))}async function pr(t,e={}){let n=e.cliPath??lr(),s=e.timeout??125e3,o=["feedback","action","send","--json"];e.proxy!==void 0&&o.push("--proxy",e.proxy);let r=await Ac(t,e.auth,s),i=Un(n)?await Me(n):void 0,a=i?.runtimePath??n,u=Re(a)?process.execPath:a,c=Re(a)?[a,...o]:o;await new Promise((l,m)=>{let p=Ec(u,c,{cwd:e.cwd,env:{...e.env??process.env,...i?.env,...Re(a)&&process.versions.electron?{ELECTRON_RUN_AS_NODE:"1"}:{}},stdio:["pipe","ignore","ignore"]}),d=setTimeout(()=>{p.kill("SIGTERM"),m(new Error("Host action fallback timed out"))},s);d.unref?.(),p.once("error",f=>{clearTimeout(d),m(f)}),p.once("exit",(f,S)=>{clearTimeout(d),f===0?l():m(new Error(`Host action fallback exited with ${f??S??"unknown status"}`))}),p.stdin.on("error",f=>{clearTimeout(d),p.kill("SIGTERM"),m(f)}),p.stdin.end(`${JSON.stringify(r?{event:t,credential:r}:t)}
|
|
25
|
+
`)})}async function Ac(t,e,n){if(e?.type==="serviceAccount")throw new Error("Host actions are not supported for Service Account authentication");if(e?.type!=="jobToken")return;let s=new AbortController,o;try{let r=await Promise.race([Promise.resolve().then(()=>e.fetchJobToken({requestId:Tc(),reason:"initial",sessionId:t.session_id},{signal:s.signal})),new Promise((i,a)=>{o=setTimeout(()=>{s.abort(),a(new Error("Host action authentication timed out"))},Math.min(n,3e4))})]);if(!r?.token?.trim()||r.expiresAt!==void 0&&(!Number.isFinite(r.expiresAt)||r.expiresAt<=Date.now()))throw new Error("Host action credentials are unavailable or expired");return{type:e.type,token:r.token,expiresAt:r.expiresAt}}catch{throw new Error("Host action authentication failed")}finally{o&&clearTimeout(o)}}async function Dc(t,e){if(!t.content)return{success:!1,message:"Feedback content is required"};let n=e?.cliPath??lr(),s=e?.timeout??6e4,o=["feedback","-c",t.content,"--json"];if(e?.storageDir&&o.push("--storage-dir",e.storageDir),t.sessionId&&o.push("-s",t.sessionId),t.workdir&&o.push("--workdir",t.workdir),t.email&&o.push("--email",t.email),t.include)for(let r of t.include)o.push("--include",r);if(t.imagePaths)for(let r of t.imagePaths)o.push("--images",r);if(t.callerVersion&&o.push("--caller-version",t.callerVersion),e?.integrationMode){let r=e.integrationMode==="qoder_work"?"QoderWork":e.integrationMode==="quest"?"Quest":e.integrationMode;r&&o.push("--ide-type",r)}return new Promise(r=>{Pc(n,o,{env:e?.env??process.env,timeout:s,maxBuffer:1024*1024},(i,a)=>{let u=a.trim();if(u)try{let c=JSON.parse(u);r({success:!!c.success,message:c.success?c.message||"Feedback submitted successfully":c.error||c.message||"Failed to submit feedback",requestId:c.request_id});return}catch{}r(i?{success:!1,message:i.message||"Failed to submit feedback"}:{success:!0,message:u||"Feedback submitted successfully"})})})}var Kn=class extends Error{code="auth_not_configured";constructor(){super("The auth option is required when calling query(); configure options.auth so the SDK can create an auth payload file before spawning qodercli."),this.name="AuthNotConfiguredError"}};function Ic(t,e){let n=t.daemon;if(n){let s=Ve(n);if(!s)throw new Error("options.daemon must be returned by startDaemon().");return{daemon:n,transportProvider:s.transportProvider,hostActionLaunch:s.hostActionLaunch}}if(t.transport!==void 0){if(xc(t.transport))return{...mr(t,e),legacyTransport:!0};if(!rs(t.transport))throw new Error("options.transport must implement QueryTransportProvider. Use ProcessTransport.default, WorkerTransport.default, or a custom provider with create().");if(t.business!==void 0)throw new Error("options.business requires a daemon transport");return{transportProvider:t.transport,hostActionLaunch:{proxy:t.proxy,cliPath:t.pathToQoderCLIExecutable,env:t.env}}}return mr(t,e)}function xc(t){return t instanceof xe||t instanceof Oe}function mr(t,e){let n=It(Nc(t,e));return{daemon:n.daemon,transportProvider:n.transportProvider,hostActionLaunch:{get proxy(){return n.daemon.getProxy()??void 0},get noProxy(){return n.daemon.getNoProxy()},cliPath:t.pathToQoderCLIExecutable,env:t.env}}}function Oc(t){return t.options?.pathToQoderWorkerRuntime}function qc(t){return t.transport instanceof Oe?{launchMode:"worker",pathToQoderWorkerRuntime:Oc(t.transport)}:t.transport instanceof xe?{launchMode:"process"}:{launchMode:Xe}}function Nc(t,e){return{auth:e,pathToQoderCLIExecutable:t.pathToQoderCLIExecutable,executable:t.executable,executableArgs:t.executableArgs,proxy:t.proxy,vpcEndpoint:t.vpcEndpoint,env:t.env,stderr:t.stderr,debug:t.debug,debugFile:t.debugFile,...qc(t)}}function Ln(t){let e=Date.now(),{prompt:n,options:s={}}=t;if(s.extraHeaders!==void 0&&(s.extraHeaders===null||typeof s.extraHeaders!="object"||Array.isArray(s.extraHeaders)||Object.values(s.extraHeaders).some(_=>typeof _!="string")))throw new TypeError("options.extraHeaders must be a map of strings");let o=s.daemon;if(s.planMode!==void 0&&typeof s.planMode!="boolean")throw new TypeError("options.planMode must be a boolean");let r=et(s.permissionMode);o&&jc(s);let i=o?Ve(o):void 0;if(o&&!i)throw new Error("options.daemon must be returned by startDaemon().");let a=s.sessionStore,u=s.sessionStoreFlush??"batched",c=new ee({onCloseDiagnostic:s.onCloseDiagnostic,debug:s.debug,debugFile:s.debugFile,stderr:s.stderr});if(o!==void 0&&c.record("[DaemonRoute] explicit_daemon transport_overridden"),s.canUseTool&&s.permissionPromptToolName)throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");s.goalMaxTurns!==void 0&&tt(s.goalMaxTurns);let l=i?.auth??s.auth;if(l==null)throw new Kn;if(s.hostActions!==void 0&&l.type==="serviceAccount")throw new Error("Host actions are not supported for Service Account authentication: Tracking requires a user signing context");let m=a!==void 0&&s.forkSession===!0;if(a&&s.persistSession===!1)throw new Error(`sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use ${w.configDirEnv}=/tmp for ephemeral local writes with external mirroring.`);if(a&&s.sessionStoreFlush!==void 0&&s.sessionStoreFlush!=="batched"&&s.sessionStoreFlush!=="eager")throw new Error('sessionStoreFlush must be "batched" or "eager".');if(a&&s.loadTimeoutMs!==void 0&&(!Number.isFinite(s.loadTimeoutMs)||s.loadTimeoutMs<=0))throw new Error("loadTimeoutMs must be a positive finite number.");if(a&&s.experimentalCloudAgent!==void 0)throw new Error("sessionStore is not supported by the experimental Cloud Agent runtime.");if(s.cloudAgent!==void 0)throw new Error("options.cloudAgent is not supported. Use options.experimentalCloudAgent for the experimental Cloud Agent runtime.");if(s.experimentalCloudAgent!==void 0)return Go(s),Ho({prompt:n,options:s,diagnostics:c});let{daemon:p,transportProvider:d,hostActionLaunch:f,legacyTransport:S}=Ic(s,l);S&&c.record("[Transport] Process/Worker selection executes through the shared daemon"),(s.spawnQoderCLIProcess!==void 0||s.closeGraceMs!==void 0)&&c.record("[Transport] spawnQoderCLIProcess/closeGraceMs are handled by the daemon and ignored");let g=rr(s.memory),v=ar(s.evolution?.skill),b=s.onAuthExpired,y=!1,D=b?()=>{y||(y=!0,Promise.resolve(b()).catch(_=>{c.record("[query] onAuthExpired callback threw:",_)}))}:void 0,I=new Map,ie=new Map,C=new Map,U={},ae={},ct={};if(s.mcpServers)for(let[_,T]of Object.entries(s.mcpServers)){let N=T.tools;if(Array.isArray(N)&&N.length>0&&(ae[_]=N),T.type==="sdk"&&"instance"in T&&T.instance){let Y=T.instance;if(I.set(_,Y),N){let ft=en(_,N);ft&&(ct[_]=ft)}let mt=new Nt(ft=>{bo(_,ft,C)});ie.set(_,mt),Y.connect(mt).catch(()=>{})}else U[_]=T}let Ht=Object.keys(U).length>0,Z=Object.keys(ae).length>0,lt=s.pathToQoderCLIExecutable,Zr=s.env,ei=l?.type==="jobToken"?l.fetchJobToken:void 0,ti=l?.type==="serviceAccount"?l.fetchServiceAccountToken:void 0,dt={business:s.business&&{...s.business},pathToQoderCLIExecutable:lt,executable:s.executable,executableArgs:s.executableArgs,env:Zr,proxy:s.proxy,vpcEndpoint:s.vpcEndpoint,cwd:s.cwd,closeGraceMs:s.closeGraceMs,auth:l,model:s.model,agent:s.agent,debug:s.debug,diagnostics:c,maxTurns:s.maxTurns,includePartialMessages:s.includePartialMessages,includeHookEvents:s.includeHookEvents,sessionMirror:a!==void 0,permissionMode:s.permissionMode,allowDangerouslySkipPermissions:s.allowDangerouslySkipPermissions,permissionPromptToolName:s.permissionPromptToolName,canUseTool:s.canUseTool!==void 0,continue:s.continue,resume:s.resume,resumeSessionAt:s.resumeSessionAt,resumeDropsTurn:s.resumeDropsTurn,forkSession:s.forkSession,sessionId:s.sessionId,persistSession:s.persistSession,allowedTools:(()=>{let _=s.allowedTools??[];if(s.skills===void 0)return _.length>0?_:void 0;let T=s.skills==="all"?["Skill"]:s.skills.map(Y=>`Skill(${Y})`),N=new Set(_);return[..._,...T.filter(Y=>!N.has(Y))]})(),disallowedTools:s.disallowedTools,tools:s.tools,toolConfig:s.toolConfig,extensions:s.extensions,extraArgs:s.extraArgs,mcpServers:Ht?U:void 0,mcpToolPolicies:Z?ae:void 0,allowedMcpServerNames:s.allowedMcpServerNames,strictMcpConfig:s.strictMcpConfig,settings:s.settings,securityScan:s.securityScan,settingSources:s.settingSources,additionalDirectories:s.additionalDirectories,plugins:s.plugins,enableFileCheckpointing:s.enableFileCheckpointing,stderr:"pipe",stderrHandler:s.stderr,spawnQoderCLIProcess:s.spawnQoderCLIProcess,onAuthExpired:D},pt,ns=a!==void 0&&(s.resume!==void 0||s.continue===!0)?new be(async()=>{let _=await nr({store:a,cwd:s.cwd,resume:s.resume,continue:s.continue,loadTimeoutMs:s.loadTimeoutMs,env:s.env});if(!_)return{transport:we(d,{...dt,continue:!1})};pt=dr(s.env);try{return{transport:we(d,{...dt,env:{...dt.env??process.env,[w.configDirEnv]:_.configDir,...s.hostActions!==void 0?{QODERCLI_HOST_ACTION_STORAGE_DIR:pt}:{}},materializedSessionConfigDir:_.configDir,continue:!1,resume:_.sessionId}),cleanup:_.cleanup}}catch(T){throw await _.cleanup(),T}}):we(d,dt);ns.initialize().catch(()=>{});let ni=typeof n=="string",ve=s.systemPrompt,ss,os;if(typeof ve=="string")ss=ve;else if(typeof ve=="object"&&ve!==null&&ve.type==="preset"){let _=ve;if(_.preset!=="qodercli")throw new Error(`Unsupported systemPrompt preset: ${String(_.preset)}`);os=_.append}let si={sdkStartedAtMs:e,extraHeaders:s.extraHeaders===void 0?void 0:{...s.extraHeaders},systemPrompt:ss,appendSystemPrompt:os,modelRequestPatches:s.modelRequestPatches,agents:s.agents,skills:Array.isArray(s.skills)?s.skills:void 0,planMode:p!==void 0?s.planMode??!1:s.planMode,promptSuggestions:s.promptSuggestions,includeShellProgress:s.includeShellProgress,hostActions:s.hostActions,goalMaxTurns:s.goalMaxTurns,enableFileCheckpointing:s.enableFileCheckpointing,memory:g.config,evolution:v.config?{skill:v.config}:void 0,customContext:s.customContext,beforeInitialize:void 0,requireSessionStoreForkBarrier:m,...p!==void 0?{independentPlanModeControls:!0,permissionMode:r}:{}},Wt=new qt(ns,ni,s.canUseTool,s.hooks,s.abortController,I,si,s.onElicitation,c,D,s.controlRequestTimeoutMs,ie,C,ei,s.resolveModel,s.resolveModelTimeoutMs,a,u,ct,ti,g.callbacks,v.callbacks,s.resolveSessionArtifacts,async _=>{let T=f,N=T.noProxy,Y=new ue({auth:l,vpcEndpoint:s.vpcEndpoint,env:{...T.env??s.env??process.env,...N!=null?{NO_PROXY:N,no_proxy:N}:{},...pt!==void 0?{QODERCLI_HOST_ACTION_STORAGE_DIR:pt}:{}}});try{let mt=await Y.prepare();await pr(_,{cliPath:T.cliPath??s.pathToQoderCLIExecutable,env:mt.env,cwd:s.cwd,auth:l,proxy:T.proxy??s.proxy})}finally{await Y.cleanupAuthPayload()}},p!==void 0,p,p?()=>p.getProxy():void 0);if(typeof n=="string"){let _={type:"user",extra:{submitted_at_ms:e},message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null};Wt.streamInput(async function*(){yield _}())}else Wt.streamInput(n);return Wt}function jc(t){let e=t,s=[["auth",t.auth],["transport",e.transport],["env",t.env],["pathToQoderCLIExecutable",t.pathToQoderCLIExecutable],["executable",t.executable],["executableArgs",t.executableArgs],["proxy",t.proxy],["vpcEndpoint",t.vpcEndpoint],["spawnQoderCLIProcess",e.spawnQoderCLIProcess],["closeGraceMs",e.closeGraceMs]].find(([,o])=>o!==void 0);if(s)throw new Error(`options.${s[0]} is part of startDaemon() configuration and cannot be overridden by a daemon-bound Query.`)}var Fc=1e3,Bn=class{resolvePrompt;prompt=new Promise(e=>{this.resolvePrompt=e});settled=!1;activate(e){if(this.settled)throw new Error("WarmQuery can only be queried once");this.settled=!0,this.resolvePrompt(e)}discard(){this.settled||(this.settled=!0,this.resolvePrompt(void 0))}async*[Symbol.asyncIterator](){let e=await this.prompt;if(e!==void 0){if(typeof e=="string"){yield{type:"user",message:{role:"user",content:[{type:"text",text:e}]},parent_tool_use_id:null};return}yield*e}}},$n=class{constructor(e,n){this.session=e;this.gate=n}used=!1;closed=!1;query(e){if(this.closed)throw new Error("WarmQuery is closed");if(this.used)throw new Error("WarmQuery can only be queried once");return this.used=!0,this.gate.activate(e),this.session}close(){this.closed||(this.closed=!0,this.gate.discard(),this.session.close())}async[Symbol.asyncDispose](){this.closed||(this.closed=!0,this.gate.discard()),await this.session.close()}};async function Uc(t={}){let e=t.initializeTimeoutMs??6e4;if(!Number.isFinite(e)||e<=0)throw new TypeError("initializeTimeoutMs must be a positive finite number");if(t.options?.experimentalCloudAgent!==void 0)throw new Error("startup is not supported by the experimental Cloud Agent runtime");let n=new Bn,s=Ln({prompt:n,options:t.options}),o,r;try{return await Promise.race([s.initializationResult(),new Promise((i,a)=>{o=setTimeout(()=>{a(new Error(`Qoder Agent SDK startup timed out after ${e}ms while waiting for qodercli initialization. Check authentication and network connectivity, then retry.`))},e)})]),new $n(s,n)}catch(i){n.discard();let a=t.options?.closeGraceMs??Xt,u=(Number.isFinite(a)?Math.max(0,a):Xt)+Fc;throw await Promise.race([s.close().catch(()=>{}),new Promise(c=>{r=setTimeout(c,u)})]),i}finally{o!==void 0&&clearTimeout(o),r!==void 0&&clearTimeout(r)}}import{readFile as Kc}from"node:fs/promises";import Lc from"node:os";import Q from"node:path";var Bc=["user","project","local"],Gn=new Set(["__proto__","constructor","prototype"]),$c=/^[\p{L}\p{N}\p{M}._ -]+$/u,Qc=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu,zc=new Set([".git",".svn",".hg",".vscode",".idea",".husky",".github","node_modules","bower_components"]),Gc=new Set(["mcpServers","providers","skillOverrides","enabledPlugins","extraKnownMarketplaces","pluginConfigs"]),Hc=new Set(["context.fileFiltering.customIgnoreFilePaths","tools.exclude","mcp.enabledProjectMcpServers","mcp.disabledProjectMcpServers","security.approvedExternalImportProjects","advanced.excludedEnvVars","extensions.disabled","extensions.workspacesWithMigrationNudge","plugins.enabled","plugins.disabled","skills.disabled","blockedMarketplaces","allowedHttpHookUrls"]);function he(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Wc(t){let e=t.charCodeAt(0)===65279?t.slice(1):t,n="",s=!1,o=!1,r=!1,i=!1;for(let a=0;a<e.length;a+=1){let u=e[a],c=e[a+1];if(r){u===`
|
|
26
26
|
`||u==="\r"?(r=!1,n+=u):n+=" ";continue}if(i){u==="*"&&c==="/"?(i=!1,n+=" ",a+=1):n+=u===`
|
|
27
|
-
`||u==="\r"?u:" ";continue}if(s){n+=u,o?o=!1:u==="\\"?o=!0:u==='"'&&(s=!1);continue}u==='"'?(s=!0,n+=u):u==="/"&&c==="/"?(r=!0,n+=" ",a+=1):u==="/"&&c==="*"?(i=!0,n+=" ",a+=1):n+=u}return n}function Hc(t,e){let n;try{n=JSON.parse(zc(t))}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`Unable to parse settings from ${e}: ${o}`)}if(!he(n))throw new TypeError(`Settings from ${e} must be a JSON object`);return Lt(n)}function je(t){return Array.isArray(t)?t.map(je):he(t)?Lt(t):t}function Lt(t){let e={};for(let[n,s]of Object.entries(t))Qn.has(n)||s===void 0||(e[n]=je(s));return e}function Wc(t){let e=t.join(".");if(Qc.has(e)||t.length===2&&t[0]==="providers")return"shallow";if(Gc.has(e))return"union";if(t.length===2&&t[0]==="hooks")return"concat"}function $n(t,e,n=[]){for(let[s,o]of Object.entries(e)){if(Qn.has(s)||o===void 0)continue;let r=[...n,s],i=t[s],a=Wc(r);if(a==="shallow"&&i&&o){let u={};he(i)&&Object.assign(u,Lt(i)),he(o)&&Object.assign(u,Lt(o)),t[s]=u;continue}if(Array.isArray(i)){let u=Array.isArray(o)?o:[o];if(a==="concat"){t[s]=[...i.map(je),...u.map(je)];continue}if(a==="union"){t[s]=[...new Set([...i,...u])].map(je);continue}}if(he(i)&&he(o))$n(i,o,r);else if(he(o)){let u={};$n(u,o,r),t[s]=u}else t[s]=je(o)}}function Jc(t){let e=t?.[w.configDirNameEnv];if(e===void 0||e==="")return{user:w.configDirName,project:w.projectConfigDirName};let n=e.normalize("NFC");if(Array.from(n).length<1||Array.from(n).length>64||n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")||n==="."||n===".."||!Lc.test(n)||Bc.test(n))throw new Error(`${w.configDirNameEnv} must be a valid directory name`);if($c.has(n.toLowerCase()))throw new Error(`${w.configDirNameEnv} must not use a protected directory name`);return{user:n,project:n}}async function Bn(t,e){let n;try{n=await Fc(e,"utf8")}catch(s){if(s.code==="ENOENT")return;throw s}return{source:t,path:$.resolve(e),settings:Hc(n,$.resolve(e))}}async function Vc(t={}){let e=$.resolve(t.cwd??process.cwd()),n=process.env,s=Jc(n),o=n[w.cliHomeEnv]??n.GEMINI_CLI_HOME,r=o?$.resolve(e,o):Uc.homedir(),i=n[w.configDirEnv]?$.resolve(e,n[w.configDirEnv]):$.join(r,s.user),a=$.join(e,s.project),u=new Set(t.settingSources??Kc),c=$.resolve(r)===e,d=[];if(u.has("user")){let l=await Bn("user",$.join(i,"settings.json"));l&&d.push(l)}if(u.has("project")&&!c){let l=await Bn("project",$.join(a,"settings.json"));l&&d.push(l)}if(u.has("local")&&!c){let l=await Bn("local",$.join(a,"settings.local.json"));l&&d.push(l)}let m={},p={};for(let l of d){$n(m,l.settings);for(let f of Object.keys(l.settings))Qn.has(f)||(p[f]={source:l.source,...l.path?{path:l.path}:{}})}return{effective:m,provenance:p,sources:d}}import{McpServer as Yc}from"@modelcontextprotocol/sdk/server/mcp.js";function Xc(t){if(!t.name||typeof t.name!="string"||t.name.trim()==="")throw new Error("[createSdkMcpServer] Server name must be a non-empty string.");let e=new Yc({name:t.name,version:t.version??"1.0.0"},{capabilities:{tools:t.tools&&t.tools.length>0?{}:void 0}}),n=[];if(t.tools&&t.tools.length>0)for(let s of t.tools){if(!s.name||typeof s.name!="string"||s.name.trim()==="")throw new Error(`[createSdkMcpServer] Tool name must be a non-empty string in server "${t.name}".`);if(!s.description||typeof s.description!="string")throw new Error(`[createSdkMcpServer] Tool "${s.name}" must have a non-empty description string.`);Zt(t.name,{name:s.name,exposedName:s.exposedName,alwaysLoad:s.alwaysLoad}),(s.exposedName!==void 0||s.alwaysLoad!==void 0||s.permissionPolicy!==void 0)&&n.push({name:s.name,...s.exposedName!==void 0?{exposedName:s.exposedName}:{},...s.alwaysLoad!==void 0?{alwaysLoad:s.alwaysLoad}:{},...s.permissionPolicy!==void 0?{permission_policy:s.permissionPolicy}:{}});try{e.registerTool(s.name,{description:s.description,inputSchema:s.inputSchema,...s.annotations?{annotations:s.annotations}:{}},s.handler)}catch(o){throw o instanceof Error&&o.message.includes("already registered")?new Error(`[createSdkMcpServer] Duplicate tool name "${s.name}" in server "${t.name}". Each tool name must be unique within a server.`):o}}return{type:"sdk",name:t.name,instance:e,...n.length>0?{tools:n}:{}}}function Zc(t,e,n,s,o){return{name:t,description:e,inputSchema:n,handler:s,annotations:o?.annotations,...o?.exposedName!==void 0?{exposedName:o.exposedName}:{},...o?.alwaysLoad!==void 0?{alwaysLoad:o.alwaysLoad}:{},...o?.permissionPolicy!==void 0?{permissionPolicy:o.permissionPolicy}:{}}}import{readdir as Gn,readFile as $t,stat as Fe,appendFile as vr,realpath as el,rm as mr}from"fs/promises";import{basename as tl,join as x,resolve as fr}from"path";import{execFile as nl}from"child_process";import{randomUUID as wr}from"crypto";import{promisify as sl}from"util";async function pr(t,e){let n=0,s=524288;for(;n<t.length;){n>=s&&(await new Promise(u=>setImmediate(u)),s=n+524288);let o=t.indexOf(10,n),r=o===-1?t.length:o,i=t.toString("utf8",n,r).trim();if(n=r+1,!i)continue;let a;try{a=JSON.parse(i)}catch{continue}e(a)}}var ol=sl(nl),rl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,br=new Set(["user","assistant","system","progress","attachment"]);function q(t){return t!==null&&typeof t=="object"}function ye(t){return rl.test(t)}function _r(t,e){if(!q(t)||t.type!=="active-leaf"||(t.sessionId??t.session_id)!==e)return;let s=Object.hasOwn(t,"leafUuid")?t.leafUuid:t.leaf_uuid;if(!(s!==null&&typeof s!="string"))return{leafUuid:s,sessionId:e}}async function il(t,e){let n=[],s;return await pr(t,o=>{s=_r(o,e)??s,q(o)&&typeof o.uuid=="string"&&typeof o.type=="string"&&br.has(o.type)&&n.push(o)}),{entries:n,activeLeaf:s}}function Bt(t){if(!q(t.message))return[];let e=t.message.content;return Array.isArray(e)?e:[]}var al=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","automode-parsing-error","interrupted","cancelled"]);function ul(t){return typeof t=="string"&&al.has(t)?t:void 0}function zn(t){if(t.type!=="user")return;let e=Bt(t).filter(r=>q(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string");if(e.length===0)return;let n=Array.isArray(t.toolDenialKind)?t.toolDenialKind:e.length===1?[t.toolDenialKind]:[],s=Array.isArray(t.userFeedback)?t.userFeedback:e.length===1?[t.userFeedback]:[],o=e.flatMap((r,i)=>{let a=ul(n[i]);if(!a)return[];let u=s[i];return[{id:r.tool_use_id,non_execution_kind:a,...typeof u=="string"?{user_feedback:u}:{}}]});return o.length>0?o:void 0}function ot(t){if(t.type!=="assistant"||!q(t.message))return;let e=t.message.id;return typeof e=="string"&&e?e:void 0}function kr(t){return t.type!=="user"||!t.parentUuid?!1:Bt(t).some(e=>q(e)&&e.type==="tool_result")}function cl(t){if(!q(t.message))return null;let e=t.message.id;return typeof e=="string"&&e.length>0?e:null}function ll(t,e){let n=new Map;for(let[s,o]of t){let r=cl(o);if(r){let i=n.get(r);i?i.push(s):n.set(r,[s])}}for(let[s,o]of t){let r=dl(o,o.parentUuid,t,n,e);r!==o.parentUuid&&t.set(s,{...o,parentUuid:r})}}function dl(t,e,n,s,o){if(!e||n.has(e))return e;let r=s.get(e);return!r||r.length===0?e:r.length===1?r[0]:pl(t,r,n)??ml(t,r,n,o)??e}function pl(t,e,n){if(!kr(t))return;let s=Bt(t).filter(r=>q(r)&&r.type==="tool_result").map(r=>r.tool_use_id).filter(r=>typeof r=="string");if(s.length===0)return;let o=e.filter(r=>{let i=n.get(r);return i?Bt(i).some(a=>q(a)&&a.type==="tool_use"&&s.includes(typeof a.id=="string"?a.id:"")):!1});return o.length===1?o[0]:void 0}function ml(t,e,n,s){return e.map(r=>n.get(r)).filter(r=>r!==void 0).filter(r=>(s.get(r.uuid)??-1)<(s.get(t.uuid)??-1)).at(-1)?.uuid}function fl(t){for(let e of t.values()){if(e.type!=="system"||e.subtype!=="compact_boundary")continue;let n=e.compactMetadata?.preservedSegment,s=n?.headUuid,o=n?.anchorUuid,r=n?.tailUuid;if(!s||!o||!r)continue;let i=t.get(s);i&&t.set(s,{...i,parentUuid:o});for(let[a,u]of t)a!==s&&u.parentUuid===o&&t.set(a,{...u,parentUuid:r})}}function gr(t,e,n){let s=(t.timestamp??"").localeCompare(e.timestamp??"");return s!==0?s:(n.get(t.uuid)??Number.MAX_SAFE_INTEGER)-(n.get(e.uuid)??Number.MAX_SAFE_INTEGER)}function Cr(t,e,n){let s=e.filter(p=>p.type==="assistant");if(s.length===0)return e;let o=new Map,r=0;for(let p of t.keys())o.set(p,r++);let i=new Map;for(let p of s){let l=ot(p);l&&i.set(l,p)}let a=new Map,u=new Map;for(let p of t.values()){let l=ot(p);if(l){let f=a.get(l)??[];f.push(p),a.set(l,f);continue}if(kr(p)&&p.parentUuid){let f=u.get(p.parentUuid)??[];f.push(p),u.set(p.parentUuid,f)}}let c=new Set,d=new Map;for(let p of s){let l=ot(p);if(!l||c.has(l))continue;c.add(l);let f=a.get(l)??[p],S=f.filter(C=>!n.has(C.uuid)),g=[];for(let C of f){let U=u.get(C.uuid)??[];for(let ie of U)n.has(ie.uuid)||g.push(ie)}if(S.length===0&&g.length===0)continue;let v=i.get(l);if(!v)continue;let b=[...f].sort((C,U)=>gr(C,U,o));g.sort((C,U)=>gr(C,U,o));let y=b.findIndex(C=>C.uuid===v.uuid),A=b.slice(0,Math.max(y,0)).filter(C=>!n.has(C.uuid)),I=b.slice(y+1).filter(C=>!n.has(C.uuid)),re=[...A,...I,...g];for(let C of re)n.add(C.uuid);d.set(v.uuid,re)}if(d.size===0)return e;let m=[];for(let p of e){let l=d.get(p.uuid);if(l){let f=o.get(p.uuid)??Number.MAX_SAFE_INTEGER,S=[],g=[];for(let v of l)(p.type==="assistant"&&v.type==="assistant"&&ot(v)===ot(p)&&(o.get(v.uuid)??Number.MAX_SAFE_INTEGER)<f?S:g).push(v);m.push(...S,p,...g)}else m.push(p)}return m}function Rr(t,e,n="runtime"){if(t.length===0)return[];let s=new Map,o=new Map;for(let[d,m]of t.entries())s.set(m.uuid,m),o.set(m.uuid,d);n==="runtime"&&fl(s),ll(s,o);let r;if(e?.leafUuid===null)return[];if(e){let d=s.get(e.leafUuid),m=d?.sessionId??d?.session_id;d&&(m===void 0||m===e.sessionId)&&(r=d)}if(!r){let d=new Set;for(let S of s.values())S.parentUuid&&d.add(S.parentUuid);let m=Array.from(s.values()).filter(S=>!d.has(S.uuid)),p=[];for(let S of m){let g=S,v=new Set;for(;g&&!v.has(g.uuid);){if(v.add(g.uuid),g.type==="user"||g.type==="assistant"){p.push(g);break}g=g.parentUuid?s.get(g.parentUuid):void 0}}if(p.length===0)return[];let l=p.filter(S=>!S.isSidechain&&!S.teamName&&!S.isMeta);r=(l.length>0?l:p).reduce((S,g)=>(o.get(g.uuid)??-1)>(o.get(S.uuid)??-1)?g:S)}let i=[],a=new Set,u=r;for(;u&&!a.has(u.uuid);){a.add(u.uuid),i.push(u);let d=n==="historical"&&u.type==="system"&&u.subtype==="compact_boundary"?u.logicalParentUuid??u.parentUuid:u.parentUuid;u=d?s.get(d):void 0}i.reverse();let c=n==="runtime"?gl(i):i;return Cr(s,c,new Set(c.map(d=>d.uuid)))}function gl(t){let e=-1;for(let n=t.length-1;n>=0;n--){let s=t[n];if(s?.type==="system"&&s.subtype==="compact_boundary"){e=n;break}}return e>=0?t.slice(e):[...t]}function hl(t){return t.isCompactSummary===!0||t.type==="system"&&t.subtype==="compact_boundary"}function Hn(t,e,n){let s=t.flatMap(r=>q(r)&&typeof r.uuid=="string"&&typeof r.type=="string"&&br.has(r.type)?[r]:[]),o;for(let r of t)o=_r(r,e)??o;return Rr(s,o,n)}function hr(t,e,n){if(n==="historical"&&hl(t))return!1;let s=t.type==="user"||t.type==="assistant",o=e&&t.type==="system";return!(!s&&!o||t.isMeta||t.isSidechain||t.teamName)}function yl(t){if(!t)return;let e=t.preservedSegment,n={trigger:t.trigger,pre_tokens:t.preTokens??t.pre_tokens,post_tokens:t.postTokens??t.post_tokens,messages_summarized:t.messagesSummarized??t.messages_summarized,duration_ms:t.durationMs??t.duration_ms};return!e?.headUuid||!e.anchorUuid||!e.tailUuid?n:{...n,preserved_segment:{head_uuid:e.headUuid,anchor_uuid:e.anchorUuid,tail_uuid:e.tailUuid}}}function Wn(t){return t.type==="assistant"&&t.isApiErrorMessage===!0?{isApiErrorMessage:!0}:{}}function Jn(t){return t.type==="user"&&t.toolUseResult!==void 0?{tool_use_result:t.toolUseResult}:{}}function yr(t){let e=t.type==="system"?yl(t.compactMetadata):void 0,n=zn(t);return{type:t.type,uuid:t.uuid,session_id:t.sessionId??t.session_id??"",message:t.message,parent_tool_use_id:null,parent_agent_id:null,...Wn(t),...Jn(t),...n?{tool_result_meta:n}:{},...typeof t.timestamp=="string"&&t.timestamp.length>0?{timestamp:t.timestamp}:{},...t.type==="system"&&t.subtype?{subtype:t.subtype}:{},...e?{compact_metadata:e}:{}}}function Sr(t,e){let n=Math.max(0,e?.offset??0),s=e?.limit;return s!==void 0&&s>0?t.slice(n,n+s):n>0?t.slice(n):t}async function Qt(t){try{return await el(fr(t))}catch{return fr(t)}}async function Sl(t){return j(await Qt(t))}async function Se(t){let e=[];for await(let n of Pr(t))e.push(n);return e}async function*Pr(t){let e=_e();if(t?.dir){let n=await Qt(t.dir);if(yield x(e,j(n)),t.includeWorktrees!==!1)try{let{stdout:s}=await ol("git",["worktree","list","--porcelain"],{cwd:t.dir,timeout:1e3,killSignal:"SIGKILL"}),o=s.split(`
|
|
28
|
-
`).filter(r=>r.startsWith("worktree ")).map(r=>r.substring(9).trim()).filter(r=>r
|
|
29
|
-
`).filter(Boolean).flatMap(r=>{try{let i=JSON.parse(r);return q(i)?[i]:[]}catch{return[]}});if(s.length===0)return null;let o=
|
|
30
|
-
`).filter(Boolean))try{let m=JSON.parse(
|
|
31
|
-
`," ").trim();if(!i)continue;let a=
|
|
32
|
-
`);return}catch{continue}}throw new Error(`Session ${t} not found`)}async function
|
|
33
|
-
`);return}catch{continue}}throw new Error(`Session ${t} not found`)}async function
|
|
34
|
-
`))if(s.trim())try{n.push(JSON.parse(s))}catch{}return
|
|
35
|
-
`).trim();if(r)return r}}function
|
|
36
|
-
`).filter(i=>i.trim()).flatMap(i=>{try{return[JSON.parse(i)]}catch{return[]}}),r=
|
|
27
|
+
`||u==="\r"?u:" ";continue}if(s){n+=u,o?o=!1:u==="\\"?o=!0:u==='"'&&(s=!1);continue}u==='"'?(s=!0,n+=u):u==="/"&&c==="/"?(r=!0,n+=" ",a+=1):u==="/"&&c==="*"?(i=!0,n+=" ",a+=1):n+=u}return n}function Jc(t,e){let n;try{n=JSON.parse(Wc(t))}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`Unable to parse settings from ${e}: ${o}`)}if(!he(n))throw new TypeError(`Settings from ${e} must be a JSON object`);return Lt(n)}function je(t){return Array.isArray(t)?t.map(je):he(t)?Lt(t):t}function Lt(t){let e={};for(let[n,s]of Object.entries(t))Gn.has(n)||s===void 0||(e[n]=je(s));return e}function Vc(t){let e=t.join(".");if(Gc.has(e)||t.length===2&&t[0]==="providers")return"shallow";if(Hc.has(e))return"union";if(t.length===2&&t[0]==="hooks")return"concat"}function zn(t,e,n=[]){for(let[s,o]of Object.entries(e)){if(Gn.has(s)||o===void 0)continue;let r=[...n,s],i=t[s],a=Vc(r);if(a==="shallow"&&i&&o){let u={};he(i)&&Object.assign(u,Lt(i)),he(o)&&Object.assign(u,Lt(o)),t[s]=u;continue}if(Array.isArray(i)){let u=Array.isArray(o)?o:[o];if(a==="concat"){t[s]=[...i.map(je),...u.map(je)];continue}if(a==="union"){t[s]=[...new Set([...i,...u])].map(je);continue}}if(he(i)&&he(o))zn(i,o,r);else if(he(o)){let u={};zn(u,o,r),t[s]=u}else t[s]=je(o)}}function Yc(t){let e=t?.[w.configDirNameEnv];if(e===void 0||e==="")return{user:w.configDirName,project:w.projectConfigDirName};let n=e.normalize("NFC");if(Array.from(n).length<1||Array.from(n).length>64||n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")||n==="."||n===".."||!$c.test(n)||Qc.test(n))throw new Error(`${w.configDirNameEnv} must be a valid directory name`);if(zc.has(n.toLowerCase()))throw new Error(`${w.configDirNameEnv} must not use a protected directory name`);return{user:n,project:n}}async function Qn(t,e){let n;try{n=await Kc(e,"utf8")}catch(s){if(s.code==="ENOENT")return;throw s}return{source:t,path:Q.resolve(e),settings:Jc(n,Q.resolve(e))}}async function Xc(t={}){let e=Q.resolve(t.cwd??process.cwd()),n=process.env,s=Yc(n),o=n[w.cliHomeEnv]??n.GEMINI_CLI_HOME,r=o?Q.resolve(e,o):Lc.homedir(),i=n[w.configDirEnv]?Q.resolve(e,n[w.configDirEnv]):Q.join(r,s.user),a=Q.join(e,s.project),u=new Set(t.settingSources??Bc),c=Q.resolve(r)===e,l=[];if(u.has("user")){let d=await Qn("user",Q.join(i,"settings.json"));d&&l.push(d)}if(u.has("project")&&!c){let d=await Qn("project",Q.join(a,"settings.json"));d&&l.push(d)}if(u.has("local")&&!c){let d=await Qn("local",Q.join(a,"settings.local.json"));d&&l.push(d)}let m={},p={};for(let d of l){zn(m,d.settings);for(let f of Object.keys(d.settings))Gn.has(f)||(p[f]={source:d.source,...d.path?{path:d.path}:{}})}return{effective:m,provenance:p,sources:l}}import{McpServer as Zc}from"@modelcontextprotocol/sdk/server/mcp.js";function el(t){if(!t.name||typeof t.name!="string"||t.name.trim()==="")throw new Error("[createSdkMcpServer] Server name must be a non-empty string.");let e=new Zc({name:t.name,version:t.version??"1.0.0"},{capabilities:{tools:t.tools&&t.tools.length>0?{}:void 0}}),n=[];if(t.tools&&t.tools.length>0)for(let s of t.tools){if(!s.name||typeof s.name!="string"||s.name.trim()==="")throw new Error(`[createSdkMcpServer] Tool name must be a non-empty string in server "${t.name}".`);if(!s.description||typeof s.description!="string")throw new Error(`[createSdkMcpServer] Tool "${s.name}" must have a non-empty description string.`);Zt(t.name,{name:s.name,exposedName:s.exposedName,alwaysLoad:s.alwaysLoad}),(s.exposedName!==void 0||s.alwaysLoad!==void 0||s.permissionPolicy!==void 0)&&n.push({name:s.name,...s.exposedName!==void 0?{exposedName:s.exposedName}:{},...s.alwaysLoad!==void 0?{alwaysLoad:s.alwaysLoad}:{},...s.permissionPolicy!==void 0?{permission_policy:s.permissionPolicy}:{}});try{e.registerTool(s.name,{description:s.description,inputSchema:s.inputSchema,...s.annotations?{annotations:s.annotations}:{}},s.handler)}catch(o){throw o instanceof Error&&o.message.includes("already registered")?new Error(`[createSdkMcpServer] Duplicate tool name "${s.name}" in server "${t.name}". Each tool name must be unique within a server.`):o}}return{type:"sdk",name:t.name,instance:e,...n.length>0?{tools:n}:{}}}function tl(t,e,n,s,o){return{name:t,description:e,inputSchema:n,handler:s,annotations:o?.annotations,...o?.exposedName!==void 0?{exposedName:o.exposedName}:{},...o?.alwaysLoad!==void 0?{alwaysLoad:o.alwaysLoad}:{},...o?.permissionPolicy!==void 0?{permissionPolicy:o.permissionPolicy}:{}}}import{readdir as Hn,readFile as Qt,stat as Fe,appendFile as br,realpath as nl,rm as gr}from"fs/promises";import{basename as sl,join as x,resolve as hr}from"path";import{execFile as ol}from"child_process";import{randomUUID as _r}from"crypto";import{promisify as rl}from"util";async function fr(t,e){let n=0,s=524288;for(;n<t.length;){n>=s&&(await new Promise(u=>setImmediate(u)),s=n+524288);let o=t.indexOf(10,n),r=o===-1?t.length:o,i=t.toString("utf8",n,r).trim();if(n=r+1,!i)continue;let a;try{a=JSON.parse(i)}catch{continue}e(a)}}var il=rl(ol),al=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,kr=new Set(["user","assistant","system","progress","attachment"]);function q(t){return t!==null&&typeof t=="object"}function ye(t){return al.test(t)}function Cr(t,e){if(!q(t)||t.type!=="active-leaf"||(t.sessionId??t.session_id)!==e)return;let s=Object.hasOwn(t,"leafUuid")?t.leafUuid:t.leaf_uuid;if(!(s!==null&&typeof s!="string"))return{leafUuid:s,sessionId:e}}async function ul(t,e){let n=[],s;return await fr(t,o=>{s=Cr(o,e)??s,q(o)&&typeof o.uuid=="string"&&typeof o.type=="string"&&kr.has(o.type)&&n.push(o)}),{entries:n,activeLeaf:s}}function Bt(t){if(!q(t.message))return[];let e=t.message.content;return Array.isArray(e)?e:[]}var cl=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","automode-parsing-error","interrupted","cancelled"]);function ll(t){return typeof t=="string"&&cl.has(t)?t:void 0}function Wn(t){if(t.type!=="user")return;let e=Bt(t).filter(r=>q(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string");if(e.length===0)return;let n=Array.isArray(t.toolDenialKind)?t.toolDenialKind:e.length===1?[t.toolDenialKind]:[],s=Array.isArray(t.userFeedback)?t.userFeedback:e.length===1?[t.userFeedback]:[],o=e.flatMap((r,i)=>{let a=ll(n[i]);if(!a)return[];let u=s[i];return[{id:r.tool_use_id,non_execution_kind:a,...typeof u=="string"?{user_feedback:u}:{}}]});return o.length>0?o:void 0}function rt(t){if(t.type!=="assistant"||!q(t.message))return;let e=t.message.id;return typeof e=="string"&&e?e:void 0}function Rr(t){return t.type!=="user"||!t.parentUuid?!1:Bt(t).some(e=>q(e)&&e.type==="tool_result")}function dl(t){if(!q(t.message))return null;let e=t.message.id;return typeof e=="string"&&e.length>0?e:null}function pl(t,e){let n=new Map;for(let[s,o]of t){let r=dl(o);if(r){let i=n.get(r);i?i.push(s):n.set(r,[s])}}for(let[s,o]of t){let r=ml(o,o.parentUuid,t,n,e);r!==o.parentUuid&&t.set(s,{...o,parentUuid:r})}}function ml(t,e,n,s,o){if(!e||n.has(e))return e;let r=s.get(e);return!r||r.length===0?e:r.length===1?r[0]:fl(t,r,n)??gl(t,r,n,o)??e}function fl(t,e,n){if(!Rr(t))return;let s=Bt(t).filter(r=>q(r)&&r.type==="tool_result").map(r=>r.tool_use_id).filter(r=>typeof r=="string");if(s.length===0)return;let o=e.filter(r=>{let i=n.get(r);return i?Bt(i).some(a=>q(a)&&a.type==="tool_use"&&s.includes(typeof a.id=="string"?a.id:"")):!1});return o.length===1?o[0]:void 0}function gl(t,e,n,s){return e.map(r=>n.get(r)).filter(r=>r!==void 0).filter(r=>(s.get(r.uuid)??-1)<(s.get(t.uuid)??-1)).at(-1)?.uuid}function hl(t){for(let e of t.values()){if(e.type!=="system"||e.subtype!=="compact_boundary")continue;let n=e.compactMetadata?.preservedSegment,s=n?.headUuid,o=n?.anchorUuid,r=n?.tailUuid;if(!s||!o||!r)continue;let i=t.get(s);i&&t.set(s,{...i,parentUuid:o});for(let[a,u]of t)a!==s&&u.parentUuid===o&&t.set(a,{...u,parentUuid:r})}}function yr(t,e,n){let s=(t.timestamp??"").localeCompare(e.timestamp??"");return s!==0?s:(n.get(t.uuid)??Number.MAX_SAFE_INTEGER)-(n.get(e.uuid)??Number.MAX_SAFE_INTEGER)}function Pr(t,e,n){let s=e.filter(p=>p.type==="assistant");if(s.length===0)return e;let o=new Map,r=0;for(let p of t.keys())o.set(p,r++);let i=new Map;for(let p of s){let d=rt(p);d&&i.set(d,p)}let a=new Map,u=new Map;for(let p of t.values()){let d=rt(p);if(d){let f=a.get(d)??[];f.push(p),a.set(d,f);continue}if(Rr(p)&&p.parentUuid){let f=u.get(p.parentUuid)??[];f.push(p),u.set(p.parentUuid,f)}}let c=new Set,l=new Map;for(let p of s){let d=rt(p);if(!d||c.has(d))continue;c.add(d);let f=a.get(d)??[p],S=f.filter(C=>!n.has(C.uuid)),g=[];for(let C of f){let U=u.get(C.uuid)??[];for(let ae of U)n.has(ae.uuid)||g.push(ae)}if(S.length===0&&g.length===0)continue;let v=i.get(d);if(!v)continue;let b=[...f].sort((C,U)=>yr(C,U,o));g.sort((C,U)=>yr(C,U,o));let y=b.findIndex(C=>C.uuid===v.uuid),D=b.slice(0,Math.max(y,0)).filter(C=>!n.has(C.uuid)),I=b.slice(y+1).filter(C=>!n.has(C.uuid)),ie=[...D,...I,...g];for(let C of ie)n.add(C.uuid);l.set(v.uuid,ie)}if(l.size===0)return e;let m=[];for(let p of e){let d=l.get(p.uuid);if(d){let f=o.get(p.uuid)??Number.MAX_SAFE_INTEGER,S=[],g=[];for(let v of d)(p.type==="assistant"&&v.type==="assistant"&&rt(v)===rt(p)&&(o.get(v.uuid)??Number.MAX_SAFE_INTEGER)<f?S:g).push(v);m.push(...S,p,...g)}else m.push(p)}return m}function Er(t,e,n="runtime"){if(t.length===0)return[];let s=new Map,o=new Map;for(let[l,m]of t.entries())s.set(m.uuid,m),o.set(m.uuid,l);n==="runtime"&&hl(s),pl(s,o);let r;if(e?.leafUuid===null)return[];if(e){let l=s.get(e.leafUuid),m=l?.sessionId??l?.session_id;l&&(m===void 0||m===e.sessionId)&&(r=l)}if(!r){let l=new Set;for(let S of s.values())S.parentUuid&&l.add(S.parentUuid);let m=Array.from(s.values()).filter(S=>!l.has(S.uuid)),p=[];for(let S of m){let g=S,v=new Set;for(;g&&!v.has(g.uuid);){if(v.add(g.uuid),g.type==="user"||g.type==="assistant"){p.push(g);break}g=g.parentUuid?s.get(g.parentUuid):void 0}}if(p.length===0)return[];let d=p.filter(S=>!S.isSidechain&&!S.teamName&&!S.isMeta);r=(d.length>0?d:p).reduce((S,g)=>(o.get(g.uuid)??-1)>(o.get(S.uuid)??-1)?g:S)}let i=[],a=new Set,u=r;for(;u&&!a.has(u.uuid);){a.add(u.uuid),i.push(u);let l=n==="historical"&&u.type==="system"&&u.subtype==="compact_boundary"?u.logicalParentUuid??u.parentUuid:u.parentUuid;u=l?s.get(l):void 0}i.reverse();let c=n==="runtime"?yl(i):i;return Pr(s,c,new Set(c.map(l=>l.uuid)))}function yl(t){let e=-1;for(let n=t.length-1;n>=0;n--){let s=t[n];if(s?.type==="system"&&s.subtype==="compact_boundary"){e=n;break}}return e>=0?t.slice(e):[...t]}function Sl(t){return t.isCompactSummary===!0||t.type==="system"&&t.subtype==="compact_boundary"}function Jn(t,e,n){let s=t.flatMap(r=>q(r)&&typeof r.uuid=="string"&&typeof r.type=="string"&&kr.has(r.type)?[r]:[]),o;for(let r of t)o=Cr(r,e)??o;return Er(s,o,n)}function Sr(t,e,n){if(n==="historical"&&Sl(t))return!1;let s=t.type==="user"||t.type==="assistant",o=e&&t.type==="system";return!(!s&&!o||t.isMeta||t.isSidechain||t.teamName)}function vl(t){if(!t)return;let e=t.preservedSegment,n={trigger:t.trigger,pre_tokens:t.preTokens??t.pre_tokens,post_tokens:t.postTokens??t.post_tokens,messages_summarized:t.messagesSummarized??t.messages_summarized,duration_ms:t.durationMs??t.duration_ms};return!e?.headUuid||!e.anchorUuid||!e.tailUuid?n:{...n,preserved_segment:{head_uuid:e.headUuid,anchor_uuid:e.anchorUuid,tail_uuid:e.tailUuid}}}function Vn(t){return t.type==="assistant"&&t.isApiErrorMessage===!0?{isApiErrorMessage:!0}:{}}function Yn(t){return t.type==="user"&&t.toolUseResult!==void 0?{tool_use_result:t.toolUseResult}:{}}function vr(t){let e=t.type==="system"?vl(t.compactMetadata):void 0,n=Wn(t);return{type:t.type,uuid:t.uuid,session_id:t.sessionId??t.session_id??"",message:t.message,parent_tool_use_id:null,parent_agent_id:null,...Vn(t),...Yn(t),...n?{tool_result_meta:n}:{},...typeof t.timestamp=="string"&&t.timestamp.length>0?{timestamp:t.timestamp}:{},...t.type==="system"&&t.subtype?{subtype:t.subtype}:{},...e?{compact_metadata:e}:{}}}function wr(t,e){let n=Math.max(0,e?.offset??0),s=e?.limit;return s!==void 0&&s>0?t.slice(n,n+s):n>0?t.slice(n):t}async function $t(t){try{return await nl(hr(t))}catch{return hr(t)}}async function Se(t){let e=[];for await(let n of Tr(t))e.push(n);return e}async function*Tr(t){let e=_e();if(t?.dir){let n=await $t(t.dir);if(yield x(e,j(n)),t.includeWorktrees!==!1)try{let{stdout:s}=await il("git",["worktree","list","--porcelain"],{cwd:t.dir,timeout:1e3,killSignal:"SIGKILL"}),o=await Promise.all(s.split(`
|
|
28
|
+
`).filter(r=>r.startsWith("worktree ")).map(r=>r.substring(9).trim()).filter(r=>r.length>0).map(r=>$t(r)));if(o.some(r=>r===n))for(let r of o)r!==n&&(yield x(e,j(r)))}catch{}return}try{let n=await Hn(e,{withFileTypes:!0});for(let s of n)s.isDirectory()&&(yield x(e,s.name))}catch{return}}async function Mr(t){try{let[e,n]=await Promise.all([Qt(t,"utf-8"),Fe(t)]),s=e.trim().split(`
|
|
29
|
+
`).filter(Boolean).flatMap(r=>{try{let i=JSON.parse(r);return q(i)?[i]:[]}catch{return[]}});if(s.length===0)return null;let o=sl(t,".jsonl");return Xn(o,s,n.mtimeMs,{fileSize:n.size})??null}catch{return null}}function Ar(t,e){return x(t,e,"subagents")}function Dr(t){if(typeof t!="object"||t===null)return!1;let e=t;return(e.type==="user"||e.type==="assistant")&&typeof e.uuid=="string"}async function Ir(t){let e=[];async function n(s){let o;try{o=await Hn(s,{withFileTypes:!0})}catch{return}for(let r of o){let i=x(s,r.name);if(r.isDirectory()){await n(i);continue}if(r.isFile()&&r.name.startsWith("agent-")&&r.name.endsWith(".jsonl")){let a=r.name.slice(6,-6);a&&e.push({agentId:a,filePath:i})}}}return await n(t),e}async function wl(t){try{let e=await Qt(t.replace(/\.jsonl$/,".meta.json"),"utf-8"),n=JSON.parse(e);return{parentToolUseId:typeof n.toolUseId=="string"&&n.toolUseId.length>0?n.toolUseId:null,parentAgentId:typeof n.parentAgentId=="string"&&n.parentAgentId.length>0?n.parentAgentId:null}}catch{return{parentToolUseId:null,parentAgentId:null}}}function xr(t){if(t.length===0)return[];let e=new Map(t.map(i=>[i.uuid,i])),n=t[t.length-1],s=[],o=new Set,r=n;for(;r&&!o.has(r.uuid);)o.add(r.uuid),s.push(r),r=r.parentUuid!==void 0&&r.parentUuid!==null?e.get(r.parentUuid):void 0;return s.reverse(),Pr(e,s,o)}async function bl(t,e,n){let[s,o]=await Promise.all([Qt(t,"utf-8"),wl(t)]),r=[];for(let l of s.trim().split(`
|
|
30
|
+
`).filter(Boolean))try{let m=JSON.parse(l);Dr(m)&&r.push(m)}catch{}let a=xr(r).map(l=>{let m=Wn(l);return{type:l.type,uuid:l.uuid,session_id:l.sessionId??e,message:l.message,parent_tool_use_id:o.parentToolUseId,parent_agent_id:o.parentAgentId,...Vn(l),...Yn(l),...m?{tool_result_meta:m}:{}}}),u=n?.offset??0,c=n?.limit;return c!==void 0?a.slice(u,u+c):a.slice(u)}async function Ue(t){return j(await $t(t??process.cwd()))}function it(t,e){return{projectKey:t,sessionId:e}}function _l(t){let e=0;for(let n of t){if(typeof n.timestamp!="string")continue;let s=Date.parse(n.timestamp);Number.isFinite(s)&&(e=Math.max(e,s))}return e}function kl(t){let e=t.at(-1)?.timestamp;if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return n}return Date.now()}var Cl=/[\p{Cf}\p{Co}\p{Cn}\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\ue000-\uf8ff]/gu;function Rl(t){let e=t;for(let n=0;n<10;n+=1){let s=e.normalize("NFKC").replace(Cl,"");if(s===e)return s;e=s}return e}var Pl=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,El=/<command-name>(.*?)<\/command-name>/,Tl=/<bash-input>([\s\S]*?)<\/bash-input>/;function Ml(t){if(t.length<=200)return t;let e=t.slice(0,200),n=e.charCodeAt(e.length-1);return`${(n>=55296&&n<=56319?e.slice(0,-1):e).trim()}\u2026`}function Al(t,e){if(t.type!=="user"||t.isMeta===!0||t.isCompactSummary===!0)return;let n=t.message;if(!q(n))return;let s=n.content,o=[];if(typeof s=="string")o.push(s);else if(Array.isArray(s)){for(let r of s)if(q(r)){if(r.type==="tool_result")return;r.type==="text"&&typeof r.text=="string"&&o.push(r.text)}}for(let r of o){let i=r.replaceAll(`
|
|
31
|
+
`," ").trim();if(!i)continue;let a=El.exec(i);if(a){e.commandFallback??=a[1];continue}let u=Tl.exec(i);if(u)return`! ${u[1].trim()}`;if(!Pl.test(i))return Ml(i)}}function Xn(t,e,n,s={}){if(e.length===0)return;let o,r,i,a,u,c,l,m,p,d,f;for(let b of e){let y=b;if(f??=y.isSidechain===!0,d===void 0&&typeof y.timestamp=="string"){let D=Date.parse(y.timestamp);Number.isFinite(D)&&(d=D)}if(!o){let D={commandFallback:r};o=Al(y,D),r=D.commandFallback}y.type==="custom-title"&&typeof y.customTitle=="string"&&(i=y.customTitle),y.type==="ai-title"&&typeof y.aiTitle=="string"&&(a=y.aiTitle),typeof y.lastPrompt=="string"&&(u=y.lastPrompt),typeof y.summary=="string"&&(c=y.summary),y.type==="tag"&&(p=typeof y.tag=="string"&&y.tag?y.tag:void 0),typeof y.gitBranch=="string"&&(l=y.gitBranch),m===void 0&&typeof y.cwd=="string"&&(m=y.cwd),y.type==="relocated"&&typeof y.relocatedCwd=="string"&&(m=y.relocatedCwd)}if(f)return;let S=o??r,g=i||a,v=g||u||c||S;if(v)return{sessionId:t,summary:v,lastModified:n??_l(e),fileSize:s.fileSize,customTitle:g,firstPrompt:S,gitBranch:l,cwd:m||s.defaultCwd,tag:p,createdAt:d}}async function Or(t,e,n){let s=it(await Ue(n),e),o=await t.load(s);return o?{key:s,entries:o}:void 0}async function Dl(t){if(t?.sessionStore){let c=t.sessionStore;if(!c.listSessions)throw new Error("sessionStore.listSessions() is required by listSessions()");let l=await $t(t.dir??process.cwd()),m=j(l),p=(await c.listSessions(m)).slice().sort((g,v)=>v.mtime-g.mtime),d=Math.max(0,t.offset??0),f=t.limit!==void 0&&t.limit>0?p.slice(d,d+t.limit):d>0?p.slice(d):p;return(await Promise.allSettled(f.map(async({sessionId:g,mtime:v})=>{let b=await c.load(it(m,g));return b?Xn(g,b,v,{defaultCwd:l}):void 0}))).flatMap((g,v)=>{if(g.status==="fulfilled")return g.value?[g.value]:[];let b=f[v];return[{sessionId:b.sessionId,summary:"",lastModified:b.mtime}]})}let e=await Se(t),s=(await Promise.all(e.map(async c=>{try{return(await Hn(c)).filter(m=>m.endsWith(".jsonl")).map(m=>x(c,m))}catch{return[]}}))).flat(),o=await Promise.all(s.map(Mr)),r=new Map;for(let c of o){if(!c)continue;let l=r.get(c.sessionId);(!l||c.lastModified>l.lastModified)&&r.set(c.sessionId,c)}let i=Array.from(r.values()).sort((c,l)=>l.lastModified-c.lastModified),a=t?.offset??0,u=t?.limit;return u!==void 0?i.slice(a,a+u):i.slice(a)}async function Il(t,e){if(e?.sessionStore){if(!ye(t))return;let s=await Or(e.sessionStore,t,e.dir);return s?Xn(t,s.entries,kl(s.entries)):void 0}let n=await Se(e);for(let s of n){let o=x(s,`${t}.jsonl`),r=await Mr(o);if(r)return r}}async function xl(t,e){if(!ye(t))return[];let n=e?.includeSystemMessages===!0,s=e?.view??"runtime";if(e?.sessionStore){let o=await Or(e.sessionStore,t,e.dir);if(!o)return[];let r=Jn(o.entries,t,s);return wr(r.filter(i=>Sr(i,n,s)).map(vr),e)}for await(let o of Tr(e)){let r=x(o,`${t}.jsonl`);try{let i=await Qt(r),{entries:a,activeLeaf:u}=await ul(i,t),l=Er(a,u,s).filter(m=>Sr(m,n,s)).map(vr);return wr(l,e)}catch{continue}}return[]}async function Ol(t,e,n){if(!ye(t))throw new Error(`Invalid sessionId: ${t}`);let s=e.trim();if(!s)throw new Error("title must be non-empty");if(n?.sessionStore){await n.sessionStore.append(it(await Ue(n.dir),t),[{type:"custom-title",sessionId:t,customTitle:s,uuid:_r(),timestamp:new Date().toISOString()}]);return}let o=await Se(n);for(let r of o){let i=x(r,`${t}.jsonl`);try{await Fe(i);let a=JSON.stringify({type:"custom-title",sessionId:t,customTitle:s,timestamp:new Date().toISOString()});await br(i,a+`
|
|
32
|
+
`);return}catch{continue}}throw new Error(`Session ${t} not found`)}async function ql(t,e,n){if(!ye(t))throw new Error(`Invalid sessionId: ${t}`);let s=e===null?null:Rl(e).trim();if(s!==null&&!s)throw new Error("tag must be non-empty (use null to clear)");if(n?.sessionStore){await n.sessionStore.append(it(await Ue(n.dir),t),[{type:"tag",sessionId:t,tag:s??"",uuid:_r(),timestamp:new Date().toISOString()}]);return}let o=await Se(n);for(let r of o){let i=x(r,`${t}.jsonl`);try{await Fe(i);let a=JSON.stringify({type:"tag",sessionId:t,tag:s??"",timestamp:new Date().toISOString()});await br(i,a+`
|
|
33
|
+
`);return}catch{continue}}throw new Error(`Session ${t} not found`)}async function Nl(t,e){if(e?.sessionStore){if(!ye(t))return[];if(!e.sessionStore.listSubkeys)throw new Error("sessionStore.listSubkeys() is required by listSubagents()");let s=await e.sessionStore.listSubkeys({projectKey:await Ue(e.dir),sessionId:t});return Array.from(new Set(s.map(o=>{if(!o.startsWith("subagents/"))return;let r=o.split("/").at(-1);return r?.startsWith("agent-")?r.slice(6):void 0}).filter(o=>o!==void 0)))}let n=await Se(e);for(let s of n){let o=x(s,`${t}.jsonl`);try{await Fe(o);let r=await Ir(Ar(s,t));return Array.from(new Set(r.map(i=>i.agentId)))}catch{continue}}return[]}async function jl(t,e,n){if(n?.sessionStore){if(!ye(t)||!e)return[];let o=await Ue(n.dir),r=`subagents/agent-${e}`;if(n.sessionStore.listSubkeys){let d=await n.sessionStore.listSubkeys({projectKey:o,sessionId:t}),f=`agent-${e}`,S=d.find(g=>g.startsWith("subagents/")&&g.split("/").at(-1)===f);if(!S)return[];r=S}let i=await n.sessionStore.load({projectKey:o,sessionId:t,subpath:r});if(!i)return[];let a=i.filter(Dr),u=i.filter(d=>d.type==="agent_metadata").at(-1),c=typeof u?.toolUseId=="string"?u.toolUseId:null,l=typeof u?.parentAgentId=="string"?u.parentAgentId:null,m=xr(a).map(d=>{let f=Wn(d);return{type:d.type,uuid:d.uuid,session_id:d.sessionId??t,message:d.message,parent_tool_use_id:c,parent_agent_id:l,...Vn(d),...Yn(d),...f?{tool_result_meta:f}:{}}}),p=Math.max(0,n.offset??0);return n.limit!==void 0?m.slice(p,p+n.limit):m.slice(p)}let s=await Se(n);for(let o of s){let r=x(o,`${t}.jsonl`);try{await Fe(r);let a=(await Ir(Ar(o,t))).find(u=>u.agentId===e);return a?await bl(a.filePath,t,n):[]}catch{continue}}return[]}async function Fl(t,e){if(!ye(t))throw new Error(`Invalid sessionId: ${t}`);if(e?.sessionStore){if(!e.sessionStore.delete)throw new Error("SessionStore does not support delete()");await e.sessionStore.delete(it(await Ue(e.dir),t));return}let n=await Se(e);for(let s of n){let o=x(s,`${t}.jsonl`);try{await Fe(o),await Promise.all([gr(o,{force:!0}),gr(x(s,t),{recursive:!0,force:!0})]);return}catch{continue}}throw new Error(`Session ${t} not found`)}import{randomUUID as zt}from"crypto";import{readdir as Ul,readFile as Kl,realpath as Ll,stat as qr,writeFile as Bl}from"fs/promises";import{dirname as $l,join as Zn,resolve as Ql}from"path";var Nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zl=new Set(["user","assistant","attachment","system","progress"]);async function Fr(t){let e=Ql(t);try{return await Ll(e)}catch{return e}}async function Gl(t,e){let n=_e();if(e){let o=j(await Fr(e)),r=Zn(n,o,`${t}.jsonl`);try{if((await qr(r)).size>0)return r}catch{}return}let s;try{s=await Ul(n,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let r=Zn(n,o.name,`${t}.jsonl`);try{if((await qr(r)).size>0)return r}catch{}}}function Ur(t,e){let n=[],s;for(let r of t){if(r===null||typeof r!="object")continue;let i=r;if(i.type==="content-replacement"&&i.sessionId===e&&Array.isArray(i.replacements)){n.push(...i.replacements);continue}i.type==="relocated"&&i.sessionId===e&&typeof i.relocatedCwd=="string"&&(s=i.relocatedCwd)}return{transcript:Jn(t,e,"historical").filter(r=>zl.has(r.type)),contentReplacements:n,relocatedCwd:s}}function Hl(t,e){let n=[];for(let s of t.split(`
|
|
34
|
+
`))if(s.trim())try{n.push(JSON.parse(s))}catch{}return Ur(n,e)}function Wl(t){for(let e of t){if(e===null||typeof e!="object")continue;let n=e;if(n.type!=="user"||n.isMeta===!0||n.isCompactSummary===!0)continue;let s=n.message;if(s===null||typeof s!="object")continue;let o=s.content;if(typeof o=="string"&&o.trim())return o.trim();if(!Array.isArray(o)||o.some(i=>i!==null&&typeof i=="object"&&i.type==="tool_result"))continue;let r=o.filter(i=>i!==null&&typeof i=="object"&&i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
|
|
35
|
+
`).trim();if(r)return r}}function Jl(t){let e,n;for(let s of t){if(s===null||typeof s!="object")continue;let o=s;typeof o.customTitle=="string"&&o.customTitle&&(e=o.customTitle),typeof o.aiTitle=="string"&&o.aiTitle&&(n=o.aiTitle)}return e??n??Wl(t)}function jr(t,e,n,s){let o=t.transcript.filter(d=>d.isSidechain!==!0);if(o.length===0)throw new Error(`Session ${e} has no messages to fork`);if(n.upToMessageId){let d=o.findIndex(f=>f.uuid===n.upToMessageId);if(d<0)throw new Error(`Message ${n.upToMessageId} not found in session ${e}`);o=o.slice(0,d+1)}let r=new Set(o.map(d=>d.uuid)),i=new Map(o.map(d=>[d.uuid,zt()])),a=o.filter(d=>d.type!=="progress");if(a.length===0)throw new Error(`Session ${e} has no messages to fork`);let u=new Map(o.map(d=>[d.uuid,d])),c=zt(),l=new Date().toISOString(),m=a.map((d,f)=>{let S=null,g=typeof d.parentUuid=="string"?d.parentUuid:void 0;for(;g;){let y=u.get(g);if(!y)break;if(y.type!=="progress"){S=i.get(g)??null;break}g=typeof y.parentUuid=="string"?y.parentUuid:void 0}let v=typeof d.logicalParentUuid=="string"?i.get(d.logicalParentUuid)??null:d.logicalParentUuid??null,b={...d,...d.type==="system"&&d.subtype==="model_refusal_fallback"?{neutralizedByFork:!0}:{},uuid:i.get(d.uuid),parentUuid:S,logicalParentUuid:v,sessionId:c,timestamp:f===a.length-1?l:typeof d.timestamp=="string"?d.timestamp:l,isSidechain:!1,forkedFrom:{sessionId:e,messageUuid:d.uuid}};return delete b.teamName,delete b.agentName,delete b.sessionKind,delete b.slug,delete b.sourceToolAssistantUUID,b});if(t.contentReplacements.length>0){let d=t.contentReplacements.flatMap(f=>{if(f===null||typeof f!="object")return[];let S=f.messageUuid;if(typeof S!="string"||!r.has(S))return[];let g=i.get(S);return g?[{...f,messageUuid:g}]:[]});d.length>0&&m.push({type:"content-replacement",sessionId:c,replacements:d,uuid:zt(),timestamp:l})}t.relocatedCwd&&m.push({type:"relocated",sessionId:c,relocatedCwd:t.relocatedCwd});let p=n.title?.trim();return m.push({type:"custom-title",sessionId:c,customTitle:p||`${Jl(s)??"Forked session"} (fork)`,uuid:zt(),timestamp:l}),{sessionId:c,entries:m}}async function Vl(t,e={}){if(!Nr.test(t))throw new Error(`Invalid sessionId: ${t}`);if(e.upToMessageId&&!Nr.test(e.upToMessageId))throw new Error(`Invalid upToMessageId: ${e.upToMessageId}`);if(e.sessionStore){let i=await Fr(e.dir??process.cwd()),a=j(i),u=await e.sessionStore.load({projectKey:a,sessionId:t});if(!u?.length)throw new Error(`Session ${t} not found`);let c=jr(Ur(u,t),t,e,u);return await e.sessionStore.append({projectKey:a,sessionId:c.sessionId},c.entries),{sessionId:c.sessionId}}let n=await Gl(t,e.dir);if(!n)throw new Error(`Session ${t} not found`);let s=await Kl(n,"utf8"),o=s.split(`
|
|
36
|
+
`).filter(i=>i.trim()).flatMap(i=>{try{return[JSON.parse(i)]}catch{return[]}}),r=jr(Hl(s,t),t,e,o);return await Bl(Zn($l(n),`${r.sessionId}.jsonl`),`${r.entries.map(i=>JSON.stringify(i)).join(`
|
|
37
37
|
`)}
|
|
38
|
-
`,{flag:"wx",mode:384}),{sessionId:r.sessionId}}function
|
|
39
|
-
${s.stdout}`);throw
|
|
38
|
+
`,{flag:"wx",mode:384}),{sessionId:r.sessionId}}function Gt(t){return JSON.stringify([t.projectKey,t.sessionId,t.subpath??null])}var es=class{entries=new Map;keys=new Map;modifiedAt=new Map;lastModifiedAt=0;async append(e,n){if(n.length===0)return;let s=Gt(e),o=this.entries.get(s)??[];o.push(...n),this.entries.set(s,o),this.keys.set(s,{...e});let r=Math.max(Date.now(),this.lastModifiedAt+1);this.lastModifiedAt=r,this.modifiedAt.set(s,r)}async load(e){let n=this.entries.get(Gt(e));return n?[...n]:null}async listSessions(e){let n=[];for(let[s,o]of this.keys)o.projectKey!==e||o.subpath!==void 0||n.push({sessionId:o.sessionId,mtime:this.modifiedAt.get(s)??0});return n.sort((s,o)=>o.mtime-s.mtime)}async delete(e){if(e.subpath!==void 0){this.deleteSerialized(Gt(e));return}for(let[n,s]of this.keys)s.projectKey===e.projectKey&&s.sessionId===e.sessionId&&this.deleteSerialized(n)}async listSubkeys(e){let n=[];for(let s of this.keys.values())s.projectKey===e.projectKey&&s.sessionId===e.sessionId&&s.subpath!==void 0&&n.push(s.subpath);return n.sort()}getEntries(e){return[...this.entries.get(Gt(e))??[]]}get size(){let e=0;for(let n of this.keys.values())n.subpath===void 0&&(e+=1);return e}clear(){this.entries.clear(),this.keys.clear(),this.modifiedAt.clear(),this.lastModifiedAt=0}deleteSerialized(e){this.entries.delete(e),this.keys.delete(e),this.modifiedAt.delete(e)}};import{createReadStream as Yl}from"fs";import{readdir as $r,readFile as Xl,realpath as Zl,stat as Kr}from"fs/promises";import{basename as Lr,dirname as ed,join as at,relative as td,resolve as nd,sep as sd}from"path";import{createInterface as od}from"readline";var rd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,id=500,ad=1024*1024;async function ud(t){let e=nd(t);try{return await Zl(e)}catch{return e}}async function cd(t,e){let n=_e();if(e){let o=j(await ud(e)),r=at(n,o,`${t}.jsonl`);try{if((await Kr(r)).size>0)return{filePath:r,projectKey:o}}catch{}return}let s;try{s=await $r(n,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let r=at(n,o.name,`${t}.jsonl`);try{if((await Kr(r)).size>0)return{filePath:r,projectKey:o.name}}catch{}}}async function ld(t){let e=[];async function n(s){let o;try{o=await $r(s,{withFileTypes:!0})}catch{return}o.sort((r,i)=>r.name.localeCompare(i.name));for(let r of o){let i=at(s,r.name);r.isDirectory()?await n(i):r.isFile()&&r.name.endsWith(".jsonl")&&e.push(i)}}return await n(t),e}async function Br(t,e,n,s){let o=od({input:Yl(t,{encoding:"utf8"}),crlfDelay:1/0}),r=[],i=0;for await(let a of o){if(!a.trim())continue;let u;try{u=JSON.parse(a)}catch(c){console.warn(`importSessionToStore: skipping unparseable line in ${t}: ${String(c)}`);continue}if(u===null||typeof u!="object"){console.warn(`importSessionToStore: skipping non-object line in ${t}`);continue}r.push(u),i+=Buffer.byteLength(a),(r.length>=s||i>=ad)&&(await n.append(e,r),r=[],i=0)}r.length>0&&await n.append(e,r)}async function dd(t,e,n={}){if(!rd.test(t))throw new Error(`Invalid sessionId: ${t}`);let s=await cd(t,n.dir);if(!s)throw new Error(`Session ${t} not found`);let o=n.batchSize!==void 0&&n.batchSize>0?n.batchSize:id;if(await Br(s.filePath,{projectKey:s.projectKey,sessionId:t},e,o),n.includeSubagents===!1)return;let r=s.filePath.replace(/\.jsonl$/,""),i=at(r,"subagents");for(let a of await ld(i)){let c=td(r,a).split(sd);c[c.length-1]=Lr(c[c.length-1],".jsonl");let l={projectKey:s.projectKey,sessionId:t,subpath:c.join("/")};await Br(a,l,e,o);let m=at(ed(a),`${Lr(a,".jsonl")}.meta.json`);try{let p=JSON.parse(await Xl(m,"utf8"));await e.append(l,[{type:"agent_metadata",...p}])}catch(p){if(typeof p=="object"&&p!==null&&"code"in p&&p.code==="ENOENT")continue;console.warn(`importSessionToStore: skipping unreadable sidecar ${m}: ${String(p)}`)}}}import{spawn as md}from"node:child_process";import{existsSync as fd}from"node:fs";import{Worker as gd}from"node:worker_threads";var pd="QODER_WORKER_CWD";function Qr(t,e){return{env:{...e.env,[pd]:e.cwd,...t.env},workerData:{...e.workerData??{},qoderWorkerRuntime:{cwd:e.cwd,runtimeRoot:t.runtimeRoot,materialized:t.materialized}}}}var ts=3e4;async function zr(t,e={}){let n=ur({pathToQoderCLIExecutable:e.pathToQoderCLIExecutable},Xe);return n.transport==="worker"?yd(t,{...e,pathToQoderWorkerRuntime:n.pathToQoderWorkerRuntime}):hd(t,{...e,pathToQoderCLIExecutable:e.pathToQoderCLIExecutable??Pe()})}function hd(t,e){return new Promise((n,s)=>{let o=md(e.pathToQoderCLIExecutable,t,{cwd:e.cwd,env:Gr(e.env),stdio:["ignore","pipe","pipe"],signal:e.signal}),r="",i="",a=!1,u=setTimeout(()=>{a||(a=!0,o.kill("SIGTERM"),s(Hr(e.timeoutMs)))},e.timeoutMs??ts);o.stdout.on("data",c=>{r+=c.toString()}),o.stderr.on("data",c=>{i+=c.toString()}),o.on("error",c=>{a||(a=!0,clearTimeout(u),s(c))}),o.on("close",c=>{a||(a=!0,clearTimeout(u),n({stdout:r,stderr:i,exitCode:c??1}))})})}async function yd(t,e){vd(e.signal);let n=de(e.pathToQoderWorkerRuntime),s=await Me(n);Sd(s);let o=e.cwd??process.cwd(),r=Gr(e.env);delete r.NODE_OPTIONS;let i=Qr(s,{cwd:o,env:r});return new Promise((a,u)=>{let c=new gd(s.runtimePath,{argv:t,env:i.env,execArgv:[],stdin:!0,stdout:!0,stderr:!0,workerData:i.workerData}),l="",m="",p=!1,d,f=c.stdout===null,S=c.stderr===null,g=()=>{clearTimeout(D),e.signal?.removeEventListener("abort",y)},v=I=>{p||(p=!0,g(),u(I))},b=()=>{p||d===void 0||!f||!S||(p=!0,g(),a({stdout:l,stderr:m,exitCode:d}))},y=()=>{c.terminate(),v(Wr(e.signal))},D=setTimeout(()=>{c.terminate(),v(Hr(e.timeoutMs))},e.timeoutMs??ts);c.stdin?.end(),c.stdout?.on("data",I=>{l+=I.toString()}),c.stdout?.on("end",()=>{f=!0,b()}),c.stderr?.on("data",I=>{m+=I.toString()}),c.stderr?.on("end",()=>{S=!0,b()}),c.once("error",v),c.once("exit",I=>{d=I,b()}),e.signal?.addEventListener("abort",y,{once:!0}),e.signal?.aborted&&y()})}function Gr(t){let e={...process.env,...t},n={};for(let[s,o]of Object.entries(e))o!==void 0&&(n[s]=o);return n}function Sd(t){if(!fd(t.runtimePath))throw new Error(`Qoder worker runtime not found: ${t.runtimePath}`)}function Hr(t){return new Error(`qodercli subprocess timed out after ${t??ts}ms`)}function vd(t){if(t?.aborted)throw Wr(t)}function Wr(t){if(t?.reason instanceof Error)return t.reason;let e=new Error("The operation was aborted");return e.name="AbortError",e}async function wd(t){let e=["plugins","list","--json"];t?.orgId&&e.push("--org-id",t.orgId);let n=await Ke(e,t);return JSON.parse(n.stdout).map(o=>({id:o.id,name:o.name,source:o.source,path:o.installPath??o.path,version:o.version??"unknown",scope:o.scope,enabled:o.enabled,canDisable:o.canDisable,displayName:o.displayName,description:o.description,installedAt:o.installedAt,lastUpdated:o.lastUpdated,...typeof o.projectPath=="string"?{projectPath:o.projectPath}:{},resources:o.resources}))}async function bd(t,e){let n=["plugins","enable",t];e?.scope&&n.push("--scope",e.scope);let s=await Ke(n,e);s.exitCode!==0&&ut(s)}async function _d(t,e){let n=["plugins","disable",t];e?.scope&&n.push("--scope",e.scope);let s=await Ke(n,e);s.exitCode!==0&&ut(s)}async function kd(t,e){let n=e?.scope??"user",s=await Ke(["plugins","install",t,"--scope",n,"--json"],e);s.exitCode!==0&&ut(s);let o=JSON.parse(s.stdout);return{pluginId:o.pluginId,version:o.version??"local",path:o.path}}async function Cd(t,e){let n=e?.scope??"user",s=["plugins","uninstall",t,"--scope",n,"--json"];e?.keepData&&s.push("--keep-data");let o=await Ke(s,e);o.exitCode!==0&&ut(o);let r=JSON.parse(o.stdout);return{pluginId:r.pluginId,fullyRemoved:r.fullyRemoved,reverseDependents:r.reverseDependents??[]}}async function Rd(t,e){let n=e?.daemon;if(n&&n.state==="ready"&&n.supportsCapability(Ae))return Pd(t,n,e);let s;try{s=await Ke(["plugins","validate",t,"--json"],e)}catch(r){if(e?.signal?.aborted||r instanceof Error&&r.name==="AbortError")throw new E("Plugin validation was aborted");let i=r instanceof Error?r.message:String(r);throw z("plugin_validation_failed",`Failed to run qodercli plugin validation: ${i}`)}let o;try{o=JSON.parse(s.stdout)}catch{let r=Ed(`${s.stderr}
|
|
39
|
+
${s.stdout}`);throw z(r?"plugin_validation_unsupported":"plugin_validation_protocol_error",r?"The selected qodercli does not support structured plugin validation.":"qodercli returned an invalid plugin validation response.")}if(o&&typeof o=="object"&&"ok"in o&&o.schemaVersion!==1)throw z("plugin_validation_schema_unsupported","qodercli returned an unsupported plugin validation schema version.");if(o&&typeof o=="object"&&o.ok===!0&&o.report){let r=o.report;if(Jr(r))return r;throw z("plugin_validation_protocol_error","qodercli returned a malformed plugin validation report.")}if(o&&typeof o=="object"&&o.ok===!1){let r=o.error;if(!r||typeof r!="object"||typeof r.code!="string"||typeof r.message!="string")throw z("plugin_validation_protocol_error","qodercli returned a malformed plugin validation error.");let i=r;throw z(i.code,i.message)}throw s.exitCode!==0&&ut(s),z("plugin_validation_protocol_error","qodercli returned an unrecognized plugin validation response.")}async function Pd(t,e,n){if(n.signal?.aborted)throw new E("Plugin validation was aborted");let s=n.env?.QODER_CONFIG_DIR??n.env?.QODERCN_CONFIG_DIR,o;try{o=await e.validatePlugins([t],s?{configDir:s}:void 0)}catch(i){if(n.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw new E("Plugin validation was aborted");if(i instanceof Error&&i.name==="DaemonRpcError"&&typeof i.code=="string")throw z(i.code,i.message);let a=i instanceof Error?i.message:String(i);throw z("plugin_validation_failed",`Failed to run qodercli plugin validation: ${a}`)}if(n.signal?.aborted)throw new E("Plugin validation was aborted");let r=o[0];if(o.length!==1||!Jr(r))throw z("plugin_validation_protocol_error","qodercli returned a malformed plugin validation report.");return r}function Ed(t){return/unknown option[^\n]*--json/i.test(t)||/unknown command[^\n]*validate/i.test(t)}var Td=3e4;function Ke(t,e){return zr(t,{pathToQoderCLIExecutable:e?.cliPath,cwd:e?.cwd,env:e?.env,signal:e?.signal,timeoutMs:Td})}function ut(t){let e="plugin_operation_failed",n=t.stderr||t.stdout;try{let s=JSON.parse(t.stdout);s.error&&s.code?(e=s.code,n=s.message??n):s.ok===!1&&s.error&&(e=s.error.code??e,n=s.error.message??n)}catch{}throw z(e,n)}function z(t,e){let n=new Error(e);return n.code=t,n}function Jr(t){if(!t||typeof t!="object")return!1;let e=t;if(e.schemaVersion!==1||typeof e.valid!="boolean"||!e.validator||e.validator.name!=="qodercli"||typeof e.validator.version!="string"||!e.target||typeof e.target.inputPath!="string"||typeof e.target.resolvedPath!="string"||!Array.isArray(e.diagnostics)||!e.summary||typeof e.summary.errorCount!="number"||typeof e.summary.warningCount!="number"||typeof e.summary.componentCount!="number")return!1;let n=new Set(["target","manifest","component","load-simulation","installability"]);return e.diagnostics.every(s=>s!==null&&typeof s=="object"&&(s.severity==="error"||s.severity==="warning")&&typeof s.code=="string"&&typeof s.message=="string"&&typeof s.phase=="string"&&n.has(s.phase)&&(s.location===void 0||s.location!==null&&typeof s.location=="object"&&typeof s.location.path=="string"))}var Xr={};ri(Xr,{filterEscalatingDefaultMode:()=>Vr,isBashToolBackgroundLaunchResult:()=>Yr});var Md=new Set(["bypassPermissions","yolo","auto","acceptEdits"]);function Vr(t){let e=t.effective.permissions?.defaultMode;if(!e||!Md.has(e))return t.effective;for(let n=t.sources.length-1;n>=0;n-=1){let s=t.sources[n];if(s.settings.permissions?.defaultMode!==void 0){if(s.source==="project"){let{defaultMode:o,...r}=t.effective.permissions??{};return{...t.effective,permissions:r}}return t.effective}}return t.effective}function Yr(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=r=>r===void 0||typeof r=="string",s=r=>r===void 0||typeof r=="number"&&Number.isInteger(r)&&r>=0,o=e.backgroundReason;return e.kind==="backgrounded"&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.taskId=="string"&&typeof e.command=="string"&&typeof e.initialOutput=="string"&&n(e.outputFile)&&n(e.stdout)&&n(e.telemetryExecutionId)&&s(e.totalLines)&&s(e.totalBytes)&&(o===void 0||o==="user"||o==="model"||o==="timeout"||o==="auto")}export{E as AbortError,yt as AuthAccessTokenEnvVarError,St as AuthServiceAccountEnvVarError,Yt as CONTROL_REQUEST_TIMEOUT_CODE,Ce as ControlRequestError,Vs as DAEMON_HEARTBEAT_TIMEOUT_MS,me as DAEMON_PROXY_BYPASS_CAPABILITY,pe as DAEMON_PROXY_CAPABILITY,Ae as DAEMON_VALIDATE_PLUGINS_CAPABILITY,ms as DEFAULT_ACCESS_TOKEN_ENV_VAR,Xe as DEFAULT_RUNTIME_TRANSPORT,ht as DEFAULT_SERVICE_ACCOUNT_ENV_VAR,De as DaemonHeartbeatTimeoutError,Tt as DaemonRpcError,He as DaemonSessionAlreadyOpenError,gi as EXIT_REASONS,G as FrameTooLargeError,fi as HOOK_EVENTS,es as InMemorySessionStore,Ut as MAX_SKILL_EVOLUTION_REVIEW_THRESHOLD,Le as ModelPolicyTimeoutError,xe as ProcessTransport,X as ProtocolVersionMismatchError,ke as QoderCliInitializationError,K as QoderCliProcessError,Tn as QoderWorkerRuntimeError,L as UnsupportedCliCapabilityError,An as WIRE_PROTOCOL_VERSION,Oe as WorkerTransport,vi as accessToken,wi as accessTokenFromEnv,Xr as coreTypes,el as createSdkMcpServer,Fl as deleteSession,_d as disablePlugin,bd as enablePlugin,Vr as filterEscalatingDefaultMode,Vl as forkSession,Il as getSessionInfo,xl as getSessionMessages,jl as getSubagentMessages,$e as hasResolvableQoderWorkerRuntime,dd as importSessionToStore,En as initDaemon,kd as installPlugin,Yr as isBashToolBackgroundLaunchResult,Ci as jobToken,wd as listPlugins,Dl as listSessions,Nl as listSubagents,bi as qodercliAuth,Ln as query,Ol as renameSession,de as resolveQoderWorkerRuntimePath,Xc as resolveSettings,_i as serviceAccount,ki as serviceAccountFromEnv,gu as shutdownDaemon,_n as startDaemon,Uc as startup,Dc as submitFeedback,ql as tagSession,tl as tool,Cd as uninstallPlugin,Rd as validatePlugin};
|