@anthropic-ai/claude-agent-sdk 0.3.324 → 0.3.325

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/browser-sdk.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
2
2
 
3
- // Version: 0.3.324
3
+ // Version: 0.3.325
4
4
 
5
5
  //! symbol-dispose-prelude: defines Symbol.dispose and Symbol.asyncDispose if missing, for this bundle's `using`.
6
6
  if (typeof Symbol.dispose !== 'symbol') {
@@ -39,7 +39,7 @@ ${e.via}`}var oL=256;function ro(e){return e??""}class Km{#e=new Set;#t=0;#n=!1;
39
39
  `;if(this.toStderr){this.deps.writeToStderr(n);return}this.write(n)}write(e){let t=this.getWriter(),r=kz;if(this.storageV5!==void 0){if(r={sessionId:this.deps.sessionId(),fromBackend:zg.getStore()===!0},r.fromBackend)this.backendLinesLogged++}if(t.write({origin:r,content:e}),this.exiting)t.flush()}async flush(){let e=this.backendLinesLogged;if(this.writer?.flush(),await this.drained(),this.storageV5!==void 0&&this.successor)return this.successor.flush();for(let t=0;this.backendLinesLogged!==e&&t<3;t++)e=this.backendLinesLogged,this.writer?.flush(),await this.drained();if(this.backlog.droppedCount>0&&this.backlog.length===0&&!this.successor)this.write(""),this.writer?.flush(),await this.drained()}async drained(){if(this.isAppendStuck())return;let e=this.backlog.chain.then(()=>!0);do if(await Wu(e,nR))return;while(!this.isAppendStuck())}isAppendStuck(){let e=this.backlog,{appendSince:t}=e;if(e.stuck==="no"&&t!==0&&Date.now()-t>=yz)e.stuck="suspected",setTimeout(bz,nR,e,t).unref();return e.stuck==="yes"}dispose(e){this.redirect=e;try{this.writer?.dispose()}finally{this.redirect=null,this.writer=null}}succeed(e){this.runtimeDebugEnabled=e.runtimeDebugEnabled,this.hasFormattedOutput=e.hasFormattedOutput,this.unflushedChunks=e.unflushedChunks,this.backlog=e.backlog,this.exitHandlerRegistered=e.exitHandlerRegistered,e.successor=this,e.dispose((t)=>{this.write(t)})}handleExit(){if(this.successor){this.successor.handleExit();return}if(this.exiting=!0,this.backlog.droppedCount>0)try{this.write("")}catch{}this.writer?.flush(),this.drainSync()}async maybeRotate(e,t,r=mz){let o=Kn()&&this.storageV5!==void 0?this.storageV5.hostFiles:void 0;if(this.writtenBytes<0)if(o){let n=await o.stat(mh(e));this.writtenBytes=n.ok&&n.value.kind!=="absent"?n.value.size:0}else this.writtenBytes=await dz(e).then((n)=>n.size).catch(()=>0);else this.writtenBytes+=t;if(this.writtenBytes<=r||this.rotating)return;this.rotating=!0;try{let n=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;if(o){let i=mh(e),s=mh(n),a=await o.rename(i,s);if(!a.ok&&!xz(a.error)){if(await o.delete(s,{missingOk:!0}),!(await o.rename(i,s)).ok)await o.delete(i,{missingOk:!0})}}else try{await eR(e,n)}catch(i){if(!Vu(i))await fh(n).catch(()=>{}),await eR(e,n).catch(()=>fh(e).catch(()=>{}))}this.writtenBytes=0}finally{this.rotating=!1}}shouldLog(e){if(this.deps.isTestEnvironment&&!this.toStderr&&this.filePath===null)return!1;if(!this.deps.isAnt&&!this.isDebugMode())return!1;if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;return oC(e,this.filter)}resolveDirToFile(e){return this.resolvedLogPath=tt(e,`${this.deps.sessionId()}.txt`),this.resolvedLogPath}async appendGroup(e,t,r,o){if(this.storageV5!==void 0&&e.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,r);return}if(e.target===null||!this.writesFiles())return;if(o)await QC(gt(e.target),{recursive:!0}).catch(()=>{});let n=e;try{await ph(e.target,r)}catch(i){if(!Em(i))throw i;if(this.storageV5===void 0)n={...e,target:this.resolveDirToFile(e.target)},await ph(n.target,r);else{if(this.overrideDirectory=e.target,n=iR(t,e.configHome,e.target,e.target),n.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,r);return}await QC(gt(n.target),{recursive:!0}).catch(()=>{});try{await ph(n.target,r)}catch{return}}}if(n.rotate){if(this.storageV5!==void 0&&n.target!==this.rotationTarget)this.rotationTarget=n.target,this.writtenBytes=-1;await this.maybeRotate(n.target,Buffer.byteLength(r)).catch(oR)}if(n.pointLatest)this.markLatestSymlink()}async appendV5AndMark(e,t,r){let o=Kn(),n=o&&!this.latestMarked&&!this.latestRefused,i=await sR(e,t.sessionId,r,n);if(i==="refused")this.latestRefused=!0,i=await sR(e,t.sessionId,r,!1),this.log("debug log: the storage backend refused markLatest; <debug folder>/latest is not pointed in this process",{level:"warn"});if(i!=="landed")return;if(n&&!this.latestRefused)this.latestMarked=!0;else if(!o)this.markLatestSymlink()}markLatestSymlink(){if(!this.latestMarked&&this.writesFiles())this.latestMarked=!0,this.updateLatestSymlink()}isSessionDiskless(){try{return this.deps.diskless?.()===!0}catch{return!0}}writesFiles(){if(this.isSessionDiskless())return!1;try{return this.deps.defaultFile?.()!==!1||this.filePath!==null||this.deps.env.CLAUDE_CODE_DEBUG_LOGS_DIR!==void 0}catch{return!1}}async appendOldestChunks(){let e=this.backlog,t=this.unflushedChunks[0],r=t?.queued;if(r===void 0)return;let o=0,n=0,i=!1;for(let{content:s,queued:a}of this.unflushedChunks){if(a===void 0||a.owner!==r.owner||a.decision.arm!==r.decision.arm||a.decision.target!==r.decision.target||a.origin.sessionId!==r.origin.sessionId||a.origin.fromBackend!==r.origin.fromBackend||o>0&&n+s.length>hz)break;o++,n+=s.length,i||=a.needMkdir}if(e.appendSince=Date.now(),await r.owner.appendGroup(r.decision,r.origin,this.unflushedChunks.slice(0,o).map((s)=>s.content).join(""),i).catch(oR),e.appendSince=0,e.stuck="no",this.unflushedChunks[0]===t)this.unflushedChunks.splice(0,o),e.length-=n}drainSync(){if(this.unflushedChunks.length===0)return;if(this.backlog.length=0,!this.drainsSyncAtExit()||!this.writesFiles()||this.isAppendStuck()){this.unflushedChunks.length=0;return}let e=[];for(let t of this.unflushedChunks.splice(0)){if(t.target===null)continue;let r=e.at(-1);if(r!==void 0&&r.armed===t.armed&&(!t.armed||r.target===t.target))r.parts.push(t);else e.push({target:t.target,armed:t.armed,parts:[t]})}for(let{target:t,armed:r,parts:o}of e){let n=r?t:this.logPath(),i=o.map((s)=>s.content).join("");try{Os().mkdirSync(gt(n))}catch{}try{Os().appendFileSync(n,i)}catch(s){if(Em(s))try{if(!r)Os().appendFileSync(this.resolveDirToFile(n),i);else{let a=(c,d)=>{try{Os().appendFileSync(tt(n,`${c}.txt`),d)}catch{}},u=o[0]?.sessionId,l="";for(let c of o){if(c.sessionId!==u)a(u,l),u=c.sessionId,l="";l+=c.content}a(u,l)}}catch{}}}}droppedLineTotal(){return this.backlog.droppedTotal}takeDroppedNote(){let{droppedCount:e}=this.backlog;if(e===0)return"";return this.backlog.droppedCount=0,`${new Date().toISOString()} [WARN] debug messages not logged: ${e} since the line above, because writes to this log were over 10 s behind, with over 1 MiB waiting
40
40
  `}groupLines(e){let t=e[0];if(t===void 0)return[];let r=this.filePath??this.deps.env.CLAUDE_CODE_DEBUG_LOGS_DIR??null,o=this.isSessionDiskless();if(o&&(this.storageV5===void 0||r!==null))return[];if(this.storageV5===void 0)return[{decision:{target:this.logPath(),arm:"raw",configHome:"",rotate:!0,pointLatest:!0},origin:t.origin,lines:e}];let n=[];for(let i of e){if(o&&i.origin.fromBackend)continue;let s=n.at(-1);if(s!==void 0&&s.origin.sessionId===i.origin.sessionId&&s.origin.fromBackend===i.origin.fromBackend)s.lines.push(i);else n.push({decision:o?Sz:iR(i.origin,this.deps.configHomeDir(),r,this.overrideDirectory),origin:i.origin,lines:[i]})}return n}getWriter(){if(this.writer)return this.writer;let e=null,t=this.storageV5!==void 0;if(this.writer=Xw({writeBatch:(r)=>{if(this.redirect){this.redirect(r.map((i)=>i.content).join(""));return}if(this.exiting){for(let i of this.groupLines(r))this.unflushedChunks.push({target:i.decision.target,sessionId:i.origin.sessionId,armed:t,content:this.takeDroppedNote()+i.lines.map((s)=>s.content).join("")});this.drainSync();return}let o=this.writesFiles(),n=this.backlog;this.isAppendStuck();for(let i of this.groupLines(r)){if(i.decision.arm==="raw"&&!o)continue;if(n.droppedCount>0?n.length>=tR/2:n.length>=tR&&Date.now()-(this.unflushedChunks[0]?.queued?.at??1/0)>=gz){n.droppedCount+=i.lines.length,n.droppedTotal+=i.lines.length;continue}let s=this.takeDroppedNote()+i.lines.map((l)=>l.content).join("");if(s==="")continue;let a=i.decision.arm==="raw"?gt(i.decision.target):null,u=a!==null&&(i.origin.fromBackend||e!==a);if(a!==null)e=a;this.unflushedChunks.push({target:i.decision.target,sessionId:i.origin.sessionId,armed:t,content:s,queued:{at:Date.now(),owner:this,decision:i.decision,origin:i.origin,needMkdir:u}}),n.length+=s.length,n.chain=_z(()=>n.chain.then(this.appendOldest))}},sizeOf:(r)=>r.content.length,flushIntervalMs:1000,maxBufferSize:100,immediateMode:this.isDebugMode()}),this.deps.registerCleanup(async()=>{this.writer?.dispose(),await this.drained()}),!this.exitHandlerRegistered)this.exitHandlerRegistered=!0,this.deps.onExit(this.handleExit.bind(this));return this.writer}async updateLatestSymlink(){try{let e=this.logPath();if(yn(e).toLowerCase()==="latest")return;let t=tt(gt(e),"latest");if((await cz(t).catch(()=>null))?.isSymbolicLink())await fh(t).catch(()=>{});await pz(e,t)}catch{}}}class uR{instance=void 0;init={};defaultFile=!0;limits=void 0;setInstance(e){this.instance=e}setInit(e){this.init=e}disableDefaultFile(){this.defaultFile=!1}setLimits(e){this.limits=e}}var Cz=new vt(()=>new uR);function Rz(){return Bo(Cz)}function Tz(e,t){return new aR({argv:process.argv,env:process.env,sessionId:()=>Gw(),configHomeDir:()=>jg(),onExit:(r)=>{process.on("exit",r)},registerCleanup:(r)=>{Qw(r)},writeToStderr:(r)=>{pC(r,{mayDrop:!0})},isAnt:t?.isAnt??!1,isTestEnvironment:t?.isTestEnvironment??!1,launchIdentity:t,storageV5:e.init.storageV5!==void 0&&e.init.configHome===sC()?e.init.storageV5:void 0,syncExitDrain:e.init.syncExitDrain,diskless:()=>Ng(),defaultFile:()=>e.defaultFile,limits:()=>e.limits})}function Ez(){let e=Rz(),t=e.instance;if(t)return t;let r=Tz(e);return e.setInstance(r),r}function Se(e,t={level:"debug"}){Ez().log(e,t)}var vte=(()=>{let e=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(e!==void 0){let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t}return 1/0})();var Az={[Symbol.dispose](){}};function $z(){return Az}var St=$z;function ut(e,t,r){return JSON.stringify(e,t,r)}var an=(e,t)=>{let o=[];try{const r=ft(o,St`JSON.parse(${Pz(e)})`,0);return typeof t>"u"?JSON.parse(e):JSON.parse(e,t)}catch(n){var i=n,s=1}finally{mt(o,i,s)}};function Pz(e){return typeof e==="string"?e.length:e}var lR="SDK MCP server not found";var cR="No hook callback found for ID";class io{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}get ended(){return this.isDone}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}get readerIsWaiting(){return this.readResolve!==void 0&&!this.isDone}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}dropNewestQueued(e){let t=this.queue.findLastIndex(e);if(t!==-1)this.queue.splice(t,1)}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.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var hh="startup_mark";var dR=64;var Oz=1000;function Dz(){return{eventQueue:[],sink:null,droppedEventCount:0}}function Mz(e,t){if(e.eventQueue.length>=Oz)e.eventQueue.shift(),e.droppedEventCount++;e.eventQueue.push(t)}class pR{state=Dz()}var Nz=new vt(()=>new pR);function Lz(){return Bo(Nz)}function Go(e,t){let r=Lz().state;if(r.sink===null){Mz(r,{eventName:e,metadata:t,async:!1});return}r.sink.logEvent(e,t)}function fl(e,t){Go("tengu_feature_ok",{...t,feature_name:No(e)})}function Uz(e,t,r){Go("tengu_feature_bad",{...r,feature_name:No(e),error_code:Tm(t)})}function Fs(e,t,r){Go("tengu_feature_sad",{...r,feature_name:No(e),error_code:Tm(t)})}async function ht(e,t,r){try{let o=await t();return fl(e),o}catch(o){throw Uz(e,r?.(o)??"error"),o}}function Hn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fR(e){return"method"in e&&"id"in e&&e.id!==null}var mR=Object.freeze({}),gR=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),Nte=Symbol("swallow");class yh{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var hR=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var yR="2025-11-25";var zz="notifications/tools/list_changed";function _R(e){return Hn(e)&&!("id"in e)&&e.method===zz}function Fz(e){if(e.length!==22)return;let t=BigInt(58),r=0n;for(let o of e){let n="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".indexOf(o);if(n<0)return;r=r*t+BigInt(n)}return r}function vR(e){let t=e.lastIndexOf("_");if(t<0)return;let r=e.slice(t+1);if(!r.startsWith("01"))return;let o=Fz(r.slice(2));if(o===void 0)return;let n=o.toString(16).padStart(32,"0");if(n.length!==32)return;return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}function SR(e){return vR(e)??e}function bR(e){if(!Hn(e))return;let{id:t,directory_id:r,transport:o,plugin_id_hash:n}=e;switch(e.type){case"anthropic":return ml(t)?{type:"anthropic",id:t}:void 0;case"claude_ai_connector":return ml(t)&&(r===null||ml(r))?{type:"claude_ai_connector",id:SR(t),directory_id:r}:void 0;case"client_configured":return(o==="stdio"||o==="http"||o==="in_process")&&(n===void 0||ml(n))?{type:"client_configured",transport:o,...n!==void 0&&{plugin_id_hash:n}}:void 0;default:return}}var jz=256;function ml(e){return typeof e==="string"&&e.length>0&&e.length<=jz&&!/[\x00-\x1f\x7f]/.test(e)}function gl(e){return typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0}var Kz={always_allow:!0,always_ask:!0,always_deny:!0};function Hz(e){return typeof e==="string"&&Object.hasOwn(Kz,e)}function kR(e){if(!Hn(e)||typeof e.name!=="string")return;let{name:t,permission_policy:r}=e;if(r===void 0)return{policy:{name:t},rewritten:!1};return Hz(r)?{policy:{name:t,permission_policy:r},rewritten:!1}:{policy:{name:t,permission_policy:"always_ask"},rewritten:!0}}function xR(e,t){if(e===void 0||t===void 0)return e===t;return e.length===t.length&&e.every((r,o)=>r.name===t[o]?.name&&r.permission_policy===t[o]?.permission_policy)}var Bz=64,qz=128;function _h(e){if(!Hn(e))return{settings:{},ignored:[]};let{timeout:t,disableAutoBackground:r,tools:o,connectorId:n,autoModeVerdictTools:i,dataFlowServer:s}=e,a=gl(t),u=[];if(t!==void 0&&a===void 0)u.push("timeout");if(r!==void 0&&typeof r!=="boolean")u.push("disableAutoBackground");let l=Wz(o);if(vh(e)!==void 0)u.push("tools");let c=typeof n==="string"&&n!=="";if(n!==void 0&&!c)u.push("connectorId");let d=Array.isArray(i)?i.filter((m)=>typeof m==="string"&&m.length<=qz):[],p=Array.isArray(i)&&i.length<=Bz&&d.length===i.length;if(i!==void 0&&!p)u.push("autoModeVerdictTools");let f=s===void 0?void 0:bR(s);if(s!==void 0&&f===void 0)u.push("dataFlowServer");return{settings:{...a!==void 0&&{timeout:a},...r===!0&&{disableAutoBackground:r},...l!==void 0&&{tools:l},...c&&{connectorId:n},...p&&{autoModeVerdictTools:d},...f!==void 0&&{dataFlowServer:f}},ignored:u}}function vh(e){let t=Hn(e)?e.tools:void 0;if(t===void 0)return;if(!Array.isArray(t))return{kind:"not_a_list"};let r=0,o=0;for(let n of t){let i=kR(n);if(i===void 0)r++;else if(i.rewritten)o++}return r+o>0?{kind:"entries",dropped:r,rewritten:o,kept:t.length-r}:void 0}function wR(e){if(e.kind==="not_a_list")return"tools[] is not a list; no per-tool policy taken";let t=[];if(e.dropped>0)t.push(`dropped ${e.dropped} malformed tools[] ${e.dropped===1?"entry":"entries"}`);if(e.rewritten>0)t.push(`read ${e.rewritten} tools[] ${e.rewritten===1?"entry":"entries"} with an invalid permission_policy as always_ask`);return`${t.join(", ")}; kept ${e.kept}`}function Wz(e){if(!Array.isArray(e))return;let t=[];for(let r of e){let o=kR(r);if(o!==void 0)t.push(o.policy)}return t}class hl extends Rm{errorCode;constructor(e,t,r,o){super(e,t,o);this.errorCode=r}}var CR=250,Vz=new Set(["interrupt","cancel_async_message"]),Gz=new Set(["initialize","get_binary_version"]),yl="sdk-manifest-capture:",Zo=Symbol("suppressControlResponse");function RR(e,t,r){for(let o of r){let n=o==="tools"?vh(t):void 0;Se(n?`[Query] MCP server '${e}': ${wR(n)}`:`[Query] MCP server '${e}': ignoring malformed ${o} in its config`)}}class _l{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;runEndCeilingMs;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new io;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;promptHold;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;lastStartupFailureReason;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let r={type:"system",subtype:"mirror_error",error:t,key:e,uuid:ir(),session_id:e.sessionId};this.inputStream.enqueue(r)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpServers.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0||this.workSecretAnswerer!==void 0}remoteControlCallGeneration=0;uiHost;workSecretAnswerer;constructor(e,t,r,o,n,i=new Map,s,a,u,l,c,d,p=!1,f=Gx){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=r;this.hooks=o;this.abortController=n;this.jsonSchema=s;this.initConfig=a;this.onElicitation=u;this.getOAuthToken=l;this.getHostAuthToken=c;this.onUserDialog=d;this.verbatimPrompts=p;this.runEndCeilingMs=f;for(let[m,g]of i)this.connectSdkMcpServer(m,g);if(this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((m)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,m()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{}),this.hasHookSetToBlock()||this.initConfig?.managedSettings!==void 0){let m=setTimeout(()=>{this.cleanup(this.hasHookSetToBlock()?Error('Claude Code did not answer initialize, so a hook set to onFailure: "block" could not be confirmed and the prompt was not sent. Check the connection and start a new session.'):Error("Claude Code did not answer initialize, so the managed settings could not be confirmed and the prompt was not sent. Start a new session."))},Yx);m.unref?.(),this.promptHold=this.initialization.then(()=>(clearTimeout(m),!0),(g)=>(clearTimeout(m),this.cleanup(g),!1)),this.writeBehindPromptHold(this.promptHold,()=>{})}}writeBehindPromptHold(e,t){let r=e.then(async(n)=>{if(!n||this.abortController?.signal.aborted)return!1;return await t(),!0}),o=r.catch(()=>!0).then((n)=>{if(n&&this.promptHold===o)this.promptHold=void 0;return n});return this.promptHold=o,r}hasHookSetToBlock(){return Object.values(this.hooks??{}).some((e)=>Array.isArray(e)&&e.some((t)=>t?.onFailure!=null&&t.onFailure!=="continue"))}setError(e){this.inputStream.error(e)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((t)=>t.type==="system"&&t.subtype==="hook_progress"&&t.hook_id===e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let t of this.cleanupCallbacks)try{t()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let t of this.cancelControllers.values())t.abort();this.cancelControllers.clear(),this.transport.close()}catch(t){Se(`[Query.cleanup] transport.close() failed: ${or(t)}`,{level:"error"})}try{let t=e??Sh();for(let{reject:r}of this.pendingControlResponses.values())r(t);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:r}of this.pendingMcpResponses.values())r(t);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:r}of this.sdkMcpServers.values())r.close().catch(()=>{});if(this.sdkMcpServers.clear(),e)this.inputStream.error(e);else this.inputStream.done()}catch(t){}if(this.transport.waitForExit){let t=new AbortController;try{await Promise.race([this.transport.waitForExit(),Mo(2000,t.signal)])}catch{}finally{t.abort()}}}next(...[e]){return this.sdkMessages.next(...[e])}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let t=this.pendingControlResponses.get(e.response.request_id);if(t)t.handler(e.response);else{if(this.unmatchedControlResponses.size>=_l.UNMATCHED_CONTROL_RESPONSES_MAX){let r=this.unmatchedControlResponses.keys().next().value;if(r!==void 0)this.unmatchedControlResponses.delete(r)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive"){if(hh in e){let t=e[hh];if(typeof t==="string"&&t.length<=dR)this.startupMark={mark:t,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=e.is_error?e.subtype==="success"?e.result:e.errors.map((r)=>r.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.lastStartupFailureReason=e.is_error&&"startup_failure_reason"in e&&typeof e.startup_failure_reason==="string"?e.startup_failure_reason:void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else if(!(e.type==="system"&&(e.subtype==="session_writes_lost"||e.subtype==="plugin_install"))){if(this.lastErrorResultText=void 0,this.lastStartupFailureReason=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(e)}catch(t){Se(`[Query.readMessages] The frame observer threw: ${or(t)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(t!==void 0&&!(e instanceof rn)&&e?.name!=="SSEHttpError"){let r=Is(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result",startupFailureReason:this.lastStartupFailureReason});Se(`[Query.readMessages] Replacing exit error with result text. Original: ${or(e)}`),this.inputStream.error(r),this.cleanup(r);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){Se(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){Se(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let t=new AbortController;this.cancelControllers.set(e.request_id,t);try{let r;try{let o=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(o===Zo)return;let n={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:o}};r=ut(n)+`
41
41
  `}catch(o){if(this.cleanupPerformed)return;let n={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:or(o),...o instanceof hl&&{error_code:o.errorCode}}};r=ut(n)+`
42
- `}try{await Promise.resolve(this.transport.write(r))}catch(o){Se(`[Query.handleControlRequest] Response write failed: ${or(o)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(hR.some((r)=>r===e.request.subtype))return Se(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),Zo;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let r=e.request.computer_folder,o=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof r==="object"&&r!==null&&"path"in r&&typeof r.path==="string"&&"computer_name"in r&&typeof r.computer_name==="string"&&{computerFolder:{path:r.path,computer_name:r.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(o===null)return Zo;return{...o,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let r=e.request,o=this.sdkMcpServers.get(r.server_name)?.transport;if(!o)throw Error(`${lR}: ${r.server_name}`);if(fR(r.message))return{mcp_response:await this.handleMcpControlRequest(r.server_name,r,o)};else{if(o.onmessage)o.onmessage(r.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let r=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:r.mcp_server_name,message:r.message,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:t,requestId:e.request_id});if(o===null)return Zo;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let r=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(r===null)return Zo;return r}return Se(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),Go("tengu_request_user_dialog_response_ignored",{shape:No("auto_cancel")}),Zo}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let r,o=await this.getOAuthToken({signal:t,onDecline:(n)=>{if(Vx(n))r=n},...e.request.kind!==void 0&&{kind:e.request.kind},...(e.request.token_state==="refused"||e.request.token_state==="not_refused")&&{tokenState:e.request.token_state},...e.request.token_state==="refused"&&(e.request.refused_call==="model"||e.request.refused_call==="connector"||e.request.refused_call==="other")&&{refusedCall:e.request.refused_call}})??null;return o===null&&r!==void 0?{accessToken:o,reason:r}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let r=await this.getHostAuthToken({signal:t,status:e.request.status})??null;return typeof r==="string"||r===null?{authToken:r}:r}else if(e.request.subtype==="remote_control_work_secret"){let r=this.workSecretAnswerer;if(!r)throw Error("refreshWorkSecret callback is not provided.");if(!ER(r.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await r.refresh(r.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:r,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:r,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:r,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:r,...o}=e.request;return this.uiHost.promptPaint(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:r,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:r,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw new hl("Unsupported control request subtype: "+e.request.subtype,"Unsupported control request subtype","unsupported_request")}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,r;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let s of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,s)?t[s]:void 0;if(a?.toolsListResult!==void 0)t[s]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let i=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{r=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let n=(await r).response;if(this.hasHookSetToBlock()){let i=n.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&n.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(i!==void 0)throw this.cleanup(i),i}if(this.initConfig?.managedSettings!==void 0&&n.managed_settings_applied!==!0){let i=Error("Claude Code did not confirm the managed settings sent with managedSettingsDelivery 'initialize', so the session was ended and no further prompt was sent. For a cloud session, use 'argv', because it does not read this delivery. Otherwise check that no wrapper changes the launch flags or the initialize request.");throw this.cleanup(i),i}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&n.plugins_applied!==!0)Se(`[Query.initialize] Claude Code reported plugins_applied=${String(n.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return n}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[i,s]of Object.entries(this.hooks))if(s?.length>0)this.initHooksPayload[i]=s.map((a)=>{let u=[];for(let l of a.hooks){let c=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(c,l),u.push(c)}return{matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout,onFailure:a.onFailure}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,r=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=r.length>0?Object.fromEntries(r):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:o,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins,managedSettings:this.initConfig?.managedSettings}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,r=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,r)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:yl+"initialize",method:"initialize",params:{protocolVersion:yR,capabilities:mR,clientInfo:{...gR,version:"0.3.324"}}}},p);if(r)return;if(!("result"in f)){Se(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${ut(f)}`,{level:"warn"});return}let m=f.result;p.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let g=m.capabilities,h=typeof g==="object"&&g!==null&&"tools"in g&&g.tools!==void 0&&g.tools!==null,v;if(h){let E=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:yl+"tools-list",method:"tools/list"}},p);if(r)return;if(!("result"in E)){Se(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${ut(E)}`,{level:"warn"});return}if(E.result.nextCursor===void 0)v=E.result}let k=an(ut(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:k})}catch(f){if(!r)Se(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},n=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(n).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await Wu(Promise.race([i,s]),CR);r=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:n.length,captured:t.size,elapsed_ms:u};if(a==="closed"){Fs("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)Se(`[Query.captureSdkMcpServerManifests] ${t.size}/${n.length} in-process MCP servers captured within ${CR} ms; the rest will handshake over the control channel`,{level:"warn"}),Fs("sdk_mcp_manifest_capture","deadline",l);else if(t.size<n.length)Fs("sdk_mcp_manifest_capture","partial",l);else fl("sdk_mcp_manifest_capture",l);if(t.size===0)return;let c=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([d,p])=>{let f=t.get(d);return f!==void 0&&f.transport===p.transport?[[d,f.manifest]]:[]}));if(Object.keys(c).length===0)return;return Se(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(c).join(", ")}] captured in ${u} ms`),c}async interrupt(e){return ht("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),r=t.response?.still_queued;if(!Array.isArray(r))return;let o=t.response?.cancelled;return{still_queued:r.filter((n)=>typeof n==="string"),...Array.isArray(o)&&{cancelled:o.filter((n)=>typeof n==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,r)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,pending_elicitation_requests:u,...l}=i;t(l)}else{let s=new Lo(i.error,"awaitControlResponse: CLI error verdict");r(Is(s,{telemetryMessage:s.telemetryMessage,errorCode:TR(i.error_code)}))}if(i.pending_permission_requests||i.pending_user_dialog_requests||i.pending_elicitation_requests)Se("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){r(Sh());return}let n=this.unmatchedControlResponses.get(e);if(n){this.unmatchedControlResponses.delete(e),o(n);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:r})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return ht("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return ht("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return ht("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return ht("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=ht("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),r=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return r;let n=o.initialize,i=await r.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,managed_settings_applied:c.managed_settings_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,managed_settings_applied:void 0,code_running_mcp_tools_applied:void 0})),s=n.hooks_applied??i.hooks_applied,a=n.plugins_applied??i.plugins_applied,u=n.managed_settings_applied??i.managed_settings_applied,l=n.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...n,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{managed_settings_applied:u},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>r),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,r){let o=++this.remoteControlCallGeneration,n=this.workSecretAnswerer,i=r?.reattachSessionId||(r?.workSecret===void 0?void 0:Jz(r.workSecret)),s=e&&r?.workSecret!==void 0&&r.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:r.refreshWorkSecret}:void 0;this.workSecretAnswerer=s;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:r?.reattachSessionId,keep_session_on_exit:r?.keepSessionOnExit,work_secret:r?.workSecret})).response}catch(u){if(o===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw u}if(e&&o===this.remoteControlCallGeneration){let u=a.bridge_session_id,l=[s,n];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&ER(c.sessionId,u)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return ht("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return ht("sdk_side_question",async()=>{let o=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;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}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let r=t?.signal;if(r?.aborted)return Promise.reject(Uo(r.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Sh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let n={request_id:o,type:"control_request",request:e},i=e.subtype==="initialize";return new Promise((s,a)=>{let u,l=!1,c=(m)=>{this.pendingControlResponses.delete(o),u?.(),s(m)},d=(m)=>{this.pendingControlResponses.delete(o),u?.(),a(m)};if(r){let m=()=>{if(d(Uo(r.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(ut({type:"control_cancel_request",request_id:o})+`
42
+ `}try{await Promise.resolve(this.transport.write(r))}catch(o){Se(`[Query.handleControlRequest] Response write failed: ${or(o)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(hR.some((r)=>r===e.request.subtype))return Se(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),Zo;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let r=e.request.computer_folder,o=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof r==="object"&&r!==null&&"path"in r&&typeof r.path==="string"&&"computer_name"in r&&typeof r.computer_name==="string"&&{computerFolder:{path:r.path,computer_name:r.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(o===null)return Zo;return{...o,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let r=e.request,o=this.sdkMcpServers.get(r.server_name)?.transport;if(!o)throw Error(`${lR}: ${r.server_name}`);if(fR(r.message))return{mcp_response:await this.handleMcpControlRequest(r.server_name,r,o)};else{if(o.onmessage)o.onmessage(r.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let r=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:r.mcp_server_name,message:r.message,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:t,requestId:e.request_id});if(o===null)return Zo;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let r=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(r===null)return Zo;return r}return Se(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),Go("tengu_request_user_dialog_response_ignored",{shape:No("auto_cancel")}),Zo}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let r,o=await this.getOAuthToken({signal:t,onDecline:(n)=>{if(Vx(n))r=n},...e.request.kind!==void 0&&{kind:e.request.kind},...(e.request.token_state==="refused"||e.request.token_state==="not_refused")&&{tokenState:e.request.token_state},...e.request.token_state==="refused"&&(e.request.refused_call==="model"||e.request.refused_call==="connector"||e.request.refused_call==="other")&&{refusedCall:e.request.refused_call}})??null;return o===null&&r!==void 0?{accessToken:o,reason:r}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let r=await this.getHostAuthToken({signal:t,status:e.request.status})??null;return typeof r==="string"||r===null?{authToken:r}:r}else if(e.request.subtype==="remote_control_work_secret"){let r=this.workSecretAnswerer;if(!r)throw Error("refreshWorkSecret callback is not provided.");if(!ER(r.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await r.refresh(r.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:r,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:r,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:r,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:r,...o}=e.request;return this.uiHost.promptPaint(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:r,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:r,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw new hl("Unsupported control request subtype: "+e.request.subtype,"Unsupported control request subtype","unsupported_request")}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,r;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let s of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,s)?t[s]:void 0;if(a?.toolsListResult!==void 0)t[s]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let i=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{r=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let n=(await r).response;if(this.hasHookSetToBlock()){let i=n.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&n.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(i!==void 0)throw this.cleanup(i),i}if(this.initConfig?.managedSettings!==void 0&&n.managed_settings_applied!==!0){let i=Error("Claude Code did not confirm the managed settings sent with managedSettingsDelivery 'initialize', so the session was ended and no further prompt was sent. For a cloud session, use 'argv', because it does not read this delivery. Otherwise check that no wrapper changes the launch flags or the initialize request.");throw this.cleanup(i),i}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&n.plugins_applied!==!0)Se(`[Query.initialize] Claude Code reported plugins_applied=${String(n.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return n}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[i,s]of Object.entries(this.hooks))if(s?.length>0)this.initHooksPayload[i]=s.map((a)=>{let u=[];for(let l of a.hooks){let c=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(c,l),u.push(c)}return{matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout,onFailure:a.onFailure}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,r=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=r.length>0?Object.fromEntries(r):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:o,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins,managedSettings:this.initConfig?.managedSettings}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,r=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,r)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:yl+"initialize",method:"initialize",params:{protocolVersion:yR,capabilities:mR,clientInfo:{...gR,version:"0.3.325"}}}},p);if(r)return;if(!("result"in f)){Se(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${ut(f)}`,{level:"warn"});return}let m=f.result;p.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let g=m.capabilities,h=typeof g==="object"&&g!==null&&"tools"in g&&g.tools!==void 0&&g.tools!==null,v;if(h){let E=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:yl+"tools-list",method:"tools/list"}},p);if(r)return;if(!("result"in E)){Se(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${ut(E)}`,{level:"warn"});return}if(E.result.nextCursor===void 0)v=E.result}let k=an(ut(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:k})}catch(f){if(!r)Se(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},n=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(n).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await Wu(Promise.race([i,s]),CR);r=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:n.length,captured:t.size,elapsed_ms:u};if(a==="closed"){Fs("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)Se(`[Query.captureSdkMcpServerManifests] ${t.size}/${n.length} in-process MCP servers captured within ${CR} ms; the rest will handshake over the control channel`,{level:"warn"}),Fs("sdk_mcp_manifest_capture","deadline",l);else if(t.size<n.length)Fs("sdk_mcp_manifest_capture","partial",l);else fl("sdk_mcp_manifest_capture",l);if(t.size===0)return;let c=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([d,p])=>{let f=t.get(d);return f!==void 0&&f.transport===p.transport?[[d,f.manifest]]:[]}));if(Object.keys(c).length===0)return;return Se(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(c).join(", ")}] captured in ${u} ms`),c}async interrupt(e){return ht("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),r=t.response?.still_queued;if(!Array.isArray(r))return;let o=t.response?.cancelled;return{still_queued:r.filter((n)=>typeof n==="string"),...Array.isArray(o)&&{cancelled:o.filter((n)=>typeof n==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,r)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,pending_elicitation_requests:u,...l}=i;t(l)}else{let s=new Lo(i.error,"awaitControlResponse: CLI error verdict");r(Is(s,{telemetryMessage:s.telemetryMessage,errorCode:TR(i.error_code)}))}if(i.pending_permission_requests||i.pending_user_dialog_requests||i.pending_elicitation_requests)Se("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){r(Sh());return}let n=this.unmatchedControlResponses.get(e);if(n){this.unmatchedControlResponses.delete(e),o(n);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:r})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return ht("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return ht("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return ht("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return ht("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=ht("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),r=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return r;let n=o.initialize,i=await r.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,managed_settings_applied:c.managed_settings_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,managed_settings_applied:void 0,code_running_mcp_tools_applied:void 0})),s=n.hooks_applied??i.hooks_applied,a=n.plugins_applied??i.plugins_applied,u=n.managed_settings_applied??i.managed_settings_applied,l=n.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...n,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{managed_settings_applied:u},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>r),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,r){let o=++this.remoteControlCallGeneration,n=this.workSecretAnswerer,i=r?.reattachSessionId||(r?.workSecret===void 0?void 0:Jz(r.workSecret)),s=e&&r?.workSecret!==void 0&&r.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:r.refreshWorkSecret}:void 0;this.workSecretAnswerer=s;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:r?.reattachSessionId,keep_session_on_exit:r?.keepSessionOnExit,work_secret:r?.workSecret})).response}catch(u){if(o===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw u}if(e&&o===this.remoteControlCallGeneration){let u=a.bridge_session_id,l=[s,n];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&ER(c.sessionId,u)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return ht("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return ht("sdk_side_question",async()=>{let o=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;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}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let r=t?.signal;if(r?.aborted)return Promise.reject(Uo(r.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Sh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let n={request_id:o,type:"control_request",request:e},i=e.subtype==="initialize";return new Promise((s,a)=>{let u,l=!1,c=(m)=>{this.pendingControlResponses.delete(o),u?.(),s(m)},d=(m)=>{this.pendingControlResponses.delete(o),u?.(),a(m)};if(r){let m=()=>{if(d(Uo(r.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(ut({type:"control_cancel_request",request_id:o})+`
43
43
  `)).catch(()=>{})}catch{}};r.addEventListener("abort",m,{once:!0}),u=()=>{r.removeEventListener("abort",m)}}this.pendingControlResponses.set(o,{handler:(m)=>{if(m.subtype==="success")c(m);else d(Is(Error(m.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:TR(m.error_code)}));if(!i&&(m.pending_permission_requests||m.pending_user_dialog_requests||m.pending_elicitation_requests))Se(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`);else{if(m.pending_permission_requests)this.processPendingPermissionRequests(m.pending_permission_requests);if(m.pending_user_dialog_requests)this.processPendingUserDialogRequests(m.pending_user_dialog_requests)}},reject:d});let p=ut(n)+`
44
44
  `,f=()=>{if(r?.aborted)return;return l=!0,this.transport.write(p)};try{let m=this.promptHold,g=Vz.has(e.subtype)||this.initConfig?.managedSettings!==void 0&&!Gz.has(e.subtype);(m!==void 0&&g?this.writeBehindPromptHold(m,f):this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(f()):this.initializeWritten.then(f)).catch(d)}catch(m){d(m)}})}initializationResult(){return this.initialization}afterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(e());return this.initializeWritten.then(e)}writePrompt(e){if(this.promptHold!==void 0)return this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(e)).then(()=>{});return this.afterInitialize(()=>this.writeStreamMessage(e))}reinitialize(){return ht("sdk_reinitialize",()=>this.initialize({first:!1}))}dropHookMatchers(e,t){let r=this.hooks?.[e]??[],o=r.filter((a)=>a.matcher!==t),n=r.length-o.length;if(n===0)return Fs("sdk_drop_hook_matchers","no_match"),0;this.hooks={...this.hooks,[e]:o};let i=this.initHooksPayload,s=i?.[e];if(i!==void 0&&s!==void 0){let a=s.filter((u)=>u.matcher!==t);if(a.length>0)i[e]=a;else delete i[e]}return fl("sdk_drop_hook_matchers",{count:n}),n}async supportedCommands(){let{commands:e}=await this.initialization;return this.latestCommands??e}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,t){return ht("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:t})})}async readMcpResource(e,t){return(await this.request({subtype:"mcp_read_resource",serverName:e,uri:t})).response}async enableChannel(e){return ht("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,t,r){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:t,redirectUriOnly:r?.redirectUriOnly})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,t){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:t})).response}async claudeAuthenticate(e,t){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e,consoleProfile:t?.consoleProfile})).response}async claudeOAuthCallback(e,t){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:t})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(e){return(await this.request({subtype:"get_context_usage",...e})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(e){return(await this.request({subtype:"get_usage",...e?.skipBehaviors&&{skip_behaviors:!0}})).response}async getMemoryDialog(){return(await this.request({subtype:"get_memory_dialog"})).response}async getSkillsDialog(){return(await this.request({subtype:"get_skills_dialog"})).response}async getStatus(){return(await this.request({subtype:"get_status"})).response}async exportConversation(){return(await this.request({subtype:"export_conversation"})).response}async readCloudSessions(e,t){return(await this.request(e,t)).response}async getChromeDialog(){return(await this.request({subtype:"get_chrome_dialog"})).response}async getChromeBrowsers(){return(await this.request({subtype:"get_chrome_browsers"})).response}async selectChromeBrowser(e){return(await this.request({subtype:"select_chrome_browser",device_id:e})).response}async getSandboxDialog(){return(await this.request({subtype:"get_sandbox_dialog"})).response}async readFile(e,t){try{return(await this.request({subtype:"read_file",path:e,max_bytes:t?.maxBytes,encoding:t?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(e){return ht("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...e?.holdOnCacheImpact&&{hold_on_cache_impact:!0},...e?.addPlugins&&e.addPlugins.length>0&&{add_plugins:e.addPlugins},...e?.refuseIfBusy&&{refuse_if_busy:!0}})).response,(t)=>t instanceof Error&&("errorCode"in t)&&t.errorCode==="reload_plugins_busy"?"reload_plugins_busy":"error")}async reloadSkills(){return ht("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return ht("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return ht("sdk_mcp_set_servers",async()=>{let t={},r={};for(let[a,u]of Object.entries(e))if(u.type==="sdk"&&"instance"in u)t[a]=u;else r[a]=u;let o=new Set(this.sdkMcpServers.keys()),n=new Set(Object.keys(t));for(let a of o)if(!n.has(a))await this.disconnectSdkMcpServer(a);for(let[a,u]of Object.entries(t)){let l=this.sdkMcpServers.get(a);if(!l){this.connectSdkMcpServer(a,u);continue}let{settings:c,ignored:d}=_h(u);if(RR(a,u,d),c.timeout!==l.settings.timeout||c.disableAutoBackground!==l.settings.disableAutoBackground||c.connectorId!==l.settings.connectorId)Se(`[Query.setMcpServers] MCP server '${a}' is already registered, so the different timeout, disableAutoBackground or connectorId passed to setMcpServers is ignored; remove and re-add the server to change it`);if(c.tools!==void 0&&!xR(c.tools,l.settings.tools))Se(c.tools.length===0?`[Query.setMcpServers] MCP server '${a}': per-tool policy cleared`:`[Query.setMcpServers] MCP server '${a}': per-tool policy replaced (${c.tools.length} ${c.tools.length===1?"entry":"entries"})`),l.settings={...l.settings,tools:c.tools}}let i={};for(let a of Object.keys(t))i[a]={type:"sdk",name:a,...this.sdkMcpServers.get(a)?.settings};return(await this.request({subtype:"mcp_set_servers",servers:{...r,...i}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){Se("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let t=0,r=[];for await(let o of e){if(t++,Se(`[Query.streamInput] Processing message ${t}: ${o.type}`),this.abortController?.signal.aborted||this.promptHold!==void 0&&this.cleanupPerformed)break;let n=ut(this.verbatimPrompts?{...o,client_composed:!0}:o)+`
45
45
  `;if(this.promptHold===void 0)await Promise.resolve(this.writeStreamMessage(n));else r.push(this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(n)))}if(Se(`[Query.streamInput] Finished processing ${t} messages from input stream`),this.promptHold!==void 0)r.push(this.promptHold);if((await Promise.all(r)).includes(!1))return;if(t>0&&this.hasBidirectionalNeeds())Se("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();Se("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(t){if(!(t instanceof rn))throw t}}writeStreamMessage(e){return this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),this.transport.write(e)}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)Se("[Query.readMessages] Run ended for single-turn query, closing stdin"),this.transport.endInput()}armRunEndCeiling(){if(this.clearRunEndCeiling(),this.runEnded||this.cleanupPerformed||this.runEndCeilingMs<=0)return;this.runEndCeilingTimer=setTimeout(()=>{Se(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,Im)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return Se("[Query.waitForRunEnd] Run already ended, returning immediately"),Promise.resolve();return new Promise((e)=>{let t=this.abortController?.signal;if(this.cleanupPerformed||t?.aborted){e();return}let r=()=>e();t?.addEventListener("abort",r,{once:!0}),this.addCleanupCallback(()=>{t?.removeEventListener("abort",r),e()}),this.runEndedResolve=()=>{t?.removeEventListener("abort",r),e()}})}handleHookCallbacks(e,t,r,o){let n=this.hookCallbacks.get(e);if(!n)throw Error(`${cR}: ${e}`);return n(t,r,{signal:o})}connectSdkMcpServer(e,t){let r=new yh((s)=>this.sendMcpServerMessageToCli(e,s)),o=t.instance.connect(r).catch((s)=>{if(this.sdkMcpServers.get(e)?.transport===r)this.sdkMcpServers.delete(e);Se(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${s}`,{level:"error"})}),{settings:n,ignored:i}=_h(t);RR(e,t,i),this.sdkMcpServers.set(e,{transport:r,settings:n,connection:o})}async disconnectSdkMcpServer(e){let t=this.sdkMcpServers.get(e);if(t){let r=`${e}:${yl}`;for(let[o,n]of this.pendingMcpResponses)if(o.startsWith(r))this.pendingMcpResponses.delete(o),n.reject(Error("MCP server was removed during the manifest capture"));if(await t.transport.close(),this.sdkMcpServers.get(e)===t)this.sdkMcpServers.delete(e)}}sendMcpServerMessageToCli(e,t){if("id"in t&&t.id!==null&&t.id!==void 0){let o=`${e}:${t.id}`,n=this.pendingMcpResponses.get(o);if(n){n.resolve(t),this.pendingMcpResponses.delete(o);return}if(typeof t.id==="string"&&t.id.startsWith(yl)){Se(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let r={type:"control_request",request_id:ir(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&_R(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.afterInitialize(()=>this.transport.write(ut(r)+`
@@ -1,6 +1,6 @@
1
1
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
2
2
 
3
- // Version: 0.3.324
3
+ // Version: 0.3.325
4
4
 
5
5
  //! symbol-dispose-prelude: defines Symbol.dispose and Symbol.asyncDispose if missing, for this bundle's `using`.
6
6
  if (typeof Symbol.dispose !== 'symbol') {
@@ -13,4 +13,4 @@ if (typeof Symbol.asyncDispose !== 'symbol') {
13
13
  Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose')
14
14
  } catch {}
15
15
  }
16
- import{n}from"./core-qkncpzfw.mjs";import{Le,ae}from"./core-de9edyhn.mjs";import{AsyncLocalStorage as y}from"async_hooks";import{constants as b}from"fs";import{appendFile as w,copyFile as P,lstat as S,mkdir as h,open as d,readdir as l,readFile as c,stat as B,unlink as v,writeFile as a}from"fs/promises";class p{read(r){return c(r,"utf8")}readBytes(r){return c(r)}write(r,e,t){return a(r,e,{encoding:"utf8",mode:t})}async mkdir(r,e){try{await h(r,{recursive:!0,mode:e})}catch(t){if(n(t)!=="EEXIST")throw t}}atomicWrite(r,e,t){return Le(r,e,t)}delete(r){return v(r)}list(r){return l(r)}append(r,e,t){return w(r,e,{encoding:"utf8",mode:t})}writeExclusive(r,e,t){return a(r,e,{encoding:"utf8",flag:"wx",mode:t})}writeBytesExclusive(r,e,t){return a(r,e,{flag:"wx",mode:t})}copy(r,e){return P(r,e)}async stat(r){return{mtimeMs:(await B(r)).mtimeMs}}async lstat(r){try{let e=await S(r);return{isSymbolicLink:e.isSymbolicLink(),isFile:e.isFile(),isDirectory:e.isDirectory(),mtimeMs:e.mtimeMs,nlink:e.nlink}}catch(e){if(n(e)==="ENOENT")return;throw e}}async listEntries(r){return(await l(r,{withFileTypes:!0})).map((t)=>({name:t.name,isDirectory:t.isDirectory(),isFile:t.isFile()}))}async readRange(r,e,t){m("readRange","offset",e),m("readRange","length",t);let s=await d(r,"r");try{return await f(s,e,t)}finally{await s.close()}}async readTail(r,e,t){m("readTail","maxBytes",e);let s=t?.noFollow?b.O_RDONLY|ae:"r",i=await d(r,s);try{let o=await i.stat();if(t?.noFollow&&!o.isFile())throw Object.assign(Error("ENXIO: not a regular file"),{code:"ENXIO",path:r});let{size:g}=o,u=Math.min(e,g);return await f(i,g-u,u)}finally{await i.close()}}}function m(r,e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${r}: ${e} must be a non-negative integer, got ${t}`)}async function f(r,e,t){if(t===0)return Buffer.alloc(0);let s=Buffer.alloc(t),i=0;while(i<t){let{bytesRead:o}=await r.read(s,i,t-i,e+i);if(o===0)break;i+=o}return i===t?s:Buffer.from(s.subarray(0,i))}var F=new y;function T(){return F.getStore()??new p}export{T as getStorageBackend};
16
+ import{n}from"./core-msnqqcc2.mjs";import{Le,ae}from"./core-ds2jqcef.mjs";import{AsyncLocalStorage as y}from"async_hooks";import{constants as b}from"fs";import{appendFile as w,copyFile as P,lstat as S,mkdir as h,open as d,readdir as l,readFile as c,stat as B,unlink as v,writeFile as a}from"fs/promises";class p{read(r){return c(r,"utf8")}readBytes(r){return c(r)}write(r,e,t){return a(r,e,{encoding:"utf8",mode:t})}async mkdir(r,e){try{await h(r,{recursive:!0,mode:e})}catch(t){if(n(t)!=="EEXIST")throw t}}atomicWrite(r,e,t){return Le(r,e,t)}delete(r){return v(r)}list(r){return l(r)}append(r,e,t){return w(r,e,{encoding:"utf8",mode:t})}writeExclusive(r,e,t){return a(r,e,{encoding:"utf8",flag:"wx",mode:t})}writeBytesExclusive(r,e,t){return a(r,e,{flag:"wx",mode:t})}copy(r,e){return P(r,e)}async stat(r){return{mtimeMs:(await B(r)).mtimeMs}}async lstat(r){try{let e=await S(r);return{isSymbolicLink:e.isSymbolicLink(),isFile:e.isFile(),isDirectory:e.isDirectory(),mtimeMs:e.mtimeMs,nlink:e.nlink}}catch(e){if(n(e)==="ENOENT")return;throw e}}async listEntries(r){return(await l(r,{withFileTypes:!0})).map((t)=>({name:t.name,isDirectory:t.isDirectory(),isFile:t.isFile()}))}async readRange(r,e,t){m("readRange","offset",e),m("readRange","length",t);let s=await d(r,"r");try{return await f(s,e,t)}finally{await s.close()}}async readTail(r,e,t){m("readTail","maxBytes",e);let s=t?.noFollow?b.O_RDONLY|ae:"r",i=await d(r,s);try{let o=await i.stat();if(t?.noFollow&&!o.isFile())throw Object.assign(Error("ENXIO: not a regular file"),{code:"ENXIO",path:r});let{size:g}=o,u=Math.min(e,g);return await f(i,g-u,u)}finally{await i.close()}}}function m(r,e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${r}: ${e} must be a non-negative integer, got ${t}`)}async function f(r,e,t){if(t===0)return Buffer.alloc(0);let s=Buffer.alloc(t),i=0;while(i<t){let{bytesRead:o}=await r.read(s,i,t-i,e+i);if(o===0)break;i+=o}return i===t?s:Buffer.from(s.subarray(0,i))}var F=new y;function T(){return F.getStore()??new p}export{T as getStorageBackend};