@anthropic-ai/claude-agent-sdk 0.3.305 → 0.3.306
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/bridge.mjs +17 -17
- package/browser-sdk.js +2 -2
- package/{core-3z5ypevg.mjs → core-50f20fv8.mjs} +1 -1
- package/{core-thy7v25j.mjs → core-mh5qmqqf.mjs} +1 -1
- package/{core-be3nes5v.mjs → core-p79weg14.mjs} +2 -2
- package/{core-cpeswmq9.mjs → core-x5tcx9zy.mjs} +2 -2
- package/core.mjs +5 -5
- package/manifest.json +15 -15
- package/manifest.zst.json +25 -25
- package/package.json +14 -14
- package/sdk.mjs +3 -3
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.
|
|
3
|
+
// Version: 0.3.306
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -35,7 +35,7 @@ var nL=Object.create;var{getPrototypeOf:rL,defineProperty:jm,getOwnPropertyNames
|
|
|
35
35
|
`;if(this.toStderr){this.deps.writeToStderr(r);return}this.write(r)}write(e){let t=this.getWriter(),n=H4;if(this.storageV5!==void 0){if(n={sessionId:this.deps.sessionId(),fromBackend:Sh.getStore()===!0},n.fromBackend)this.backendLinesLogged++}if(t.write({origin:n,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 ol(e,UR))return;while(!this.isAppendStuck())}isAppendStuck(){let e=this.backlog,{appendSince:t}=e;if(e.stuck==="no"&&t!==0&&Date.now()-t>=z4)e.stuck="suspected",setTimeout(K4,UR,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,n=M4){let o=Wn()&&this.storageV5!==void 0?this.storageV5.hostFiles:void 0;if(this.writtenBytes<0)if(o){let r=await o.stat(Hh(e));this.writtenBytes=r.ok&&r.value.kind!=="absent"?r.value.size:0}else this.writtenBytes=await A4(e).then((r)=>r.size).catch(()=>0);else this.writtenBytes+=t;if(this.writtenBytes<=n||this.rotating)return;this.rotating=!0;try{let r=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;if(o){let i=Hh(e),s=Hh(r),a=await o.rename(i,s);if(!a.ok&&!q4(a.error)){if(await o.delete(s,{missingOk:!0}),!(await o.rename(i,s)).ok)await o.delete(i,{missingOk:!0})}}else try{await LR(e,r)}catch(i){if(!El(i))await Kh(r).catch(()=>{}),await LR(e,r).catch(()=>Kh(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 ZC(e,this.filter)}resolveDirToFile(e){return this.resolvedLogPath=mt(e,`${this.deps.sessionId()}.txt`),this.resolvedLogPath}async appendGroup(e,t,n,o){if(this.storageV5!==void 0&&e.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,n);return}if(e.target===null||!this.writesFiles())return;if(o)await NR(bt(e.target),{recursive:!0}).catch(()=>{});let r=e;try{await Fh(e.target,n)}catch(i){if(!Wg(i))throw i;if(this.storageV5===void 0)r={...e,target:this.resolveDirToFile(e.target)},await Fh(r.target,n);else{if(this.overrideDirectory=e.target,r=KR(t,e.configHome,e.target,e.target),r.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,n);return}await NR(bt(r.target),{recursive:!0}).catch(()=>{});try{await Fh(r.target,n)}catch{return}}}if(r.rotate){if(this.storageV5!==void 0&&r.target!==this.rotationTarget)this.rotationTarget=r.target,this.writtenBytes=-1;await this.maybeRotate(r.target,Buffer.byteLength(n)).catch(FR)}if(r.pointLatest)this.markLatestSymlink()}async appendV5AndMark(e,t,n){let o=Wn(),r=o&&!this.latestMarked&&!this.latestRefused,i=await HR(e,t.sessionId,n,r);if(i==="refused")this.latestRefused=!0,i=await HR(e,t.sessionId,n,!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(r&&!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],n=t?.queued;if(n===void 0)return;let o=0,r=0,i=!1;for(let{content:s,queued:a}of this.unflushedChunks){if(a===void 0||a.owner!==n.owner||a.decision.arm!==n.decision.arm||a.decision.target!==n.decision.target||a.origin.sessionId!==n.origin.sessionId||a.origin.fromBackend!==n.origin.fromBackend||o>0&&r+s.length>L4)break;o++,r+=s.length,i||=a.needMkdir}if(e.appendSince=Date.now(),await n.owner.appendGroup(n.decision,n.origin,this.unflushedChunks.slice(0,o).map((s)=>s.content).join(""),i).catch(FR),e.appendSince=0,e.stuck="no",this.unflushedChunks[0]===t)this.unflushedChunks.splice(0,o),e.length-=r}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 n=e.at(-1);if(n!==void 0&&n.armed===t.armed&&(!t.armed||n.target===t.target))n.parts.push(t);else e.push({target:t.target,armed:t.armed,parts:[t]})}for(let{target:t,armed:n,parts:o}of e){let r=n?t:this.logPath(),i=o.map((s)=>s.content).join("");try{Ws().mkdirSync(bt(r))}catch{}try{Ws().appendFileSync(r,i)}catch(s){if(Wg(s))try{if(!n)Ws().appendFileSync(this.resolveDirToFile(r),i);else{let a=(c,d)=>{try{Ws().appendFileSync(mt(r,`${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
|
|
36
36
|
`}groupLines(e){let t=e[0];if(t===void 0)return[];let n=this.filePath??this.deps.env.CLAUDE_CODE_DEBUG_LOGS_DIR??null,o=this.isSessionDiskless();if(o&&(this.storageV5===void 0||n!==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 r=[];for(let i of e){if(o&&i.origin.fromBackend)continue;let s=r.at(-1);if(s!==void 0&&s.origin.sessionId===i.origin.sessionId&&s.origin.fromBackend===i.origin.fromBackend)s.lines.push(i);else r.push({decision:o?F4:KR(i.origin,this.deps.configHomeDir(),n,this.overrideDirectory),origin:i.origin,lines:[i]})}return r}getWriter(){if(this.writer)return this.writer;let e=null,t=this.storageV5!==void 0;if(this.writer=FC({writeBatch:(n)=>{if(this.redirect){this.redirect(n.map((i)=>i.content).join(""));return}if(this.exiting){for(let i of this.groupLines(n))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(),r=this.backlog;this.isAppendStuck();for(let i of this.groupLines(n)){if(i.decision.arm==="raw"&&!o)continue;if(r.droppedCount>0?r.length>=zR/2:r.length>=zR&&Date.now()-(this.unflushedChunks[0]?.queued?.at??1/0)>=N4){r.droppedCount+=i.lines.length,r.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"?bt(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}}),r.length+=s.length,r.chain=U4(()=>r.chain.then(this.appendOldest))}},sizeOf:(n)=>n.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(),t=mt(bt(e),"latest");await Kh(t).catch(()=>{}),await O4(e,t)}catch{}}}class BR{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 V4=new kt(()=>new BR);function Z4(){return ii(V4)}function W4(e,t){return new qR({argv:process.argv,env:process.env,sessionId:()=>zC(),configHomeDir:()=>wh(),onExit:(n)=>{process.on("exit",n)},registerCleanup:(n)=>{HC(n)},writeToStderr:(n)=>{eR(n,{mayDrop:!0})},isAnt:t?.isAnt??!1,isTestEnvironment:t?.isTestEnvironment??!1,launchIdentity:t,storageV5:e.init.storageV5!==void 0&&e.init.configHome===WC()?e.init.storageV5:void 0,syncExitDrain:e.init.syncExitDrain,diskless:()=>yh(),defaultFile:()=>e.defaultFile,limits:()=>e.limits})}function G4(){let e=Z4(),t=e.instance;if(t)return t;let n=W4(e);return e.setInstance(n),n}function _e(e,t={level:"debug"}){G4().log(e,t)}var Due=(()=>{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 J4={[Symbol.dispose](){}};function X4(){return J4}var gt=X4;function lt(e,t,n){let r=[];try{const o=at(r,gt`JSON.stringify(${VR(e)})`,0);return JSON.stringify(e,t,n)}catch(i){var s=i,a=1}finally{ut(r,s,a)}}var pn=(e,t)=>{let o=[];try{const n=at(o,gt`JSON.parse(${VR(e)})`,0);return typeof t>"u"?JSON.parse(e):JSON.parse(e,t)}catch(r){var i=r,s=1}finally{ut(o,i,s)}};function VR(e){return typeof e==="string"?e.length:e}class ho{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})}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 Bh="startup_mark";var ZR=64;var Y4=1000;function Q4(){return{eventQueue:[],sink:null,droppedEventCount:0}}function eK(e,t){if(e.eventQueue.length>=Y4)e.eventQueue.shift(),e.droppedEventCount++;e.eventQueue.push(t)}class WR{state=Q4()}var tK=new kt(()=>new WR);function nK(){return ii(tK)}function li(e,t){let n=nK().state;if(n.sink===null){eK(n,{eventName:e,metadata:t,async:!1});return}n.sink.logEvent(e,t)}function Vh(e,t){li("tengu_feature_ok",{...t,feature_name:ni(e)})}function rK(e,t,n){li("tengu_feature_bad",{...n,feature_name:ni(e),error_code:Zg(t)})}function ql(e,t,n){li("tengu_feature_sad",{...n,feature_name:ni(e),error_code:Zg(t)})}async function ht(e,t,n){try{let o=await t();return Vh(e),o}catch(o){throw rK(e,n?.(o)??"error"),o}}function yo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function GR(e){return"method"in e&&"id"in e&&e.id!==null}var JR=Object.freeze({}),XR=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),Gue=Symbol("swallow");class Zh{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 YR=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var QR="2025-11-25";var oK="notifications/tools/list_changed";function e$(e){return yo(e)&&!("id"in e)&&e.method===oK}function Bl(e){return typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0}var iK={always_allow:!0,always_ask:!0,always_deny:!0};function sK(e){return typeof e==="string"&&Object.hasOwn(iK,e)}function t$(e){if(!yo(e)||typeof e.name!=="string")return;let{name:t,permission_policy:n}=e;if(n===void 0)return{policy:{name:t},rewritten:!1};return sK(n)?{policy:{name:t,permission_policy:n},rewritten:!1}:{policy:{name:t,permission_policy:"always_ask"},rewritten:!0}}function n$(e,t){if(e===void 0||t===void 0)return e===t;return e.length===t.length&&e.every((n,o)=>n.name===t[o]?.name&&n.permission_policy===t[o]?.permission_policy)}function Wh(e){if(!yo(e))return{settings:{},ignored:[]};let{timeout:t,disableAutoBackground:n,tools:o}=e,r=Bl(t),i=[];if(t!==void 0&&r===void 0)i.push("timeout");if(n!==void 0&&typeof n!=="boolean")i.push("disableAutoBackground");let s=aK(o);if(Gh(e)!==void 0)i.push("tools");return{settings:{...r!==void 0&&{timeout:r},...n===!0&&{disableAutoBackground:n},...s!==void 0&&{tools:s}},ignored:i}}function Gh(e){let t=yo(e)?e.tools:void 0;if(t===void 0)return;if(!Array.isArray(t))return{kind:"not_a_list"};let n=0,o=0;for(let r of t){let i=t$(r);if(i===void 0)n++;else if(i.rewritten)o++}return n+o>0?{kind:"entries",dropped:n,rewritten:o,kept:t.length-n}:void 0}function r$(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 aK(e){if(!Array.isArray(e))return;let t=[];for(let n of e){let o=t$(n);if(o!==void 0)t.push(o.policy)}return t}var o$=250,Vl="sdk-manifest-capture:",ci=Symbol("suppressControlResponse");function i$(e,t,n){for(let o of n){let r=o==="tools"?Gh(t):void 0;_e(r?`[Query] MCP server '${e}': ${r$(r)}`:`[Query] MCP server '${e}': ignoring malformed ${o} in its config`)}}class Zl{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 ho;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let n={type:"system",subtype:"mirror_error",error:t,key:e,uuid:Go(),session_id:e.sessionId};this.inputStream.enqueue(n)}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,n,o,r,i=new Map,s,a,u,l,c,d,p=!1,f=ww){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=n;this.hooks=o;this.abortController=r;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);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(()=>{})}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){_e(`[Query.cleanup] transport.close() failed: ${mr(t)}`,{level:"error"})}try{let t=e??Jh();for(let{reject:n}of this.pendingControlResponses.values())n(t);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:n}of this.pendingMcpResponses.values())n(t);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:n}of this.sdkMcpServers.values())n.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(),Zo(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>=Zl.UNMATCHED_CONTROL_RESPONSES_MAX){let n=this.unmatchedControlResponses.keys().next().value;if(n!==void 0)this.unmatchedControlResponses.delete(n)}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(Bh in e){let t=e[Bh];if(typeof t==="string"&&t.length<=ZR)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((n)=>n.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||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(this.lastErrorResultText=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){_e(`[Query.readMessages] The frame observer threw: ${mr(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 ln)&&e?.name!=="SSEHttpError"){let n=Vg(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});_e(`[Query.readMessages] Replacing exit error with result text. Original: ${mr(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){_e(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){_e(`[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 n;try{let o=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(o===ci)return;let r={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:o}};n=lt(r)+`
|
|
37
37
|
`}catch(o){if(this.cleanupPerformed)return;let r={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:mr(o)}};n=lt(r)+`
|
|
38
|
-
`}try{await Promise.resolve(this.transport.write(n))}catch(o){_e(`[Query.handleControlRequest] Response write failed: ${mr(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(YR.some((n)=>n===e.request.subtype))return _e(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),ci;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=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 n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.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 ci;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 n=e.request,o=this.sdkMcpServers.get(n.server_name)?.transport;if(!o)throw Error(`SDK MCP server not found: ${n.server_name}`);if(GR(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,o)};else{if(o.onmessage)o.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(o===null)return ci;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=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(n===null)return ci;return n}return _e(`[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`),li("tengu_request_user_dialog_response_ignored",{shape:ni("auto_cancel")}),ci}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,o=await this.getOAuthToken({signal:t,onDecline:(r)=>{if(xw(r))n=r}})??null;return o===null&&n!==void 0?{accessToken:o,reason:n}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!s$(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}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,n;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{n=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let r=(await n).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&r.plugins_applied!==!0)_e(`[Query.initialize] Claude Code reported plugins_applied=${String(r.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 r}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}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=n.length>0?Object.fromEntries(n):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}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,n)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"initialize",method:"initialize",params:{protocolVersion:QR,capabilities:JR,clientInfo:{...XR,version:"0.3.305"}}}},p);if(n)return;if(!("result"in f)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${lt(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 P=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"tools-list",method:"tools/list"}},p);if(n)return;if(!("result"in P)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${lt(P)}`,{level:"warn"});return}if(P.result.nextCursor===void 0)v=P.result}let b=pn(lt(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:b})}catch(f){if(!n)_e(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},r=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(r).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await ol(Promise.race([i,s]),o$);n=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:r.length,captured:t.size,elapsed_ms:u};if(a==="closed"){ql("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)_e(`[Query.captureSdkMcpServerManifests] ${t.size}/${r.length} in-process MCP servers captured within ${o$} ms; the rest will handshake over the control channel`,{level:"warn"}),ql("sdk_mcp_manifest_capture","deadline",l);else if(t.size<r.length)ql("sdk_mcp_manifest_capture","partial",l);else Vh("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 _e(`[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}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let o=t.response?.cancelled;return{still_queued:n.filter((r)=>typeof r==="string"),...Array.isArray(o)&&{cancelled:o.filter((r)=>typeof r==="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,n)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,...u}=i;t(u)}else n(new $l(i.error,"awaitControlResponse: CLI error verdict"));if(i.pending_permission_requests||i.pending_user_dialog_requests)_e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Jh());return}let r=this.unmatchedControlResponses.get(e);if(r){this.unmatchedControlResponses.delete(e),o(r);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:n})})}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),n=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return n;let r=o.initialize,i=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied,code_running_mcp_tools_applied:l.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),s=r.hooks_applied??i.hooks_applied,a=r.plugins_applied??i.plugins_applied,u=r.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...r,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{code_running_mcp_tools_applied:u}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let o=++this.remoteControlCallGeneration,r=this.workSecretAnswerer,i=n?.reattachSessionId||(n?.workSecret===void 0?void 0:lK(n.workSecret)),s=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:n.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:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.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,r];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&s$(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 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 n=t?.signal;if(n?.aborted)return Promise.reject(ri(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Jh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let r={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(n){let m=()=>{if(d(ri(n.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(lt({type:"control_cancel_request",request_id:o})+`
|
|
38
|
+
`}try{await Promise.resolve(this.transport.write(n))}catch(o){_e(`[Query.handleControlRequest] Response write failed: ${mr(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(YR.some((n)=>n===e.request.subtype))return _e(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),ci;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=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 n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.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 ci;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 n=e.request,o=this.sdkMcpServers.get(n.server_name)?.transport;if(!o)throw Error(`SDK MCP server not found: ${n.server_name}`);if(GR(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,o)};else{if(o.onmessage)o.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(o===null)return ci;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=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(n===null)return ci;return n}return _e(`[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`),li("tengu_request_user_dialog_response_ignored",{shape:ni("auto_cancel")}),ci}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,o=await this.getOAuthToken({signal:t,onDecline:(r)=>{if(xw(r))n=r}})??null;return o===null&&n!==void 0?{accessToken:o,reason:n}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!s$(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}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,n;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{n=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let r=(await n).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&r.plugins_applied!==!0)_e(`[Query.initialize] Claude Code reported plugins_applied=${String(r.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 r}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}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=n.length>0?Object.fromEntries(n):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}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,n)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"initialize",method:"initialize",params:{protocolVersion:QR,capabilities:JR,clientInfo:{...XR,version:"0.3.306"}}}},p);if(n)return;if(!("result"in f)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${lt(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 P=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"tools-list",method:"tools/list"}},p);if(n)return;if(!("result"in P)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${lt(P)}`,{level:"warn"});return}if(P.result.nextCursor===void 0)v=P.result}let b=pn(lt(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:b})}catch(f){if(!n)_e(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},r=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(r).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await ol(Promise.race([i,s]),o$);n=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:r.length,captured:t.size,elapsed_ms:u};if(a==="closed"){ql("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)_e(`[Query.captureSdkMcpServerManifests] ${t.size}/${r.length} in-process MCP servers captured within ${o$} ms; the rest will handshake over the control channel`,{level:"warn"}),ql("sdk_mcp_manifest_capture","deadline",l);else if(t.size<r.length)ql("sdk_mcp_manifest_capture","partial",l);else Vh("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 _e(`[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}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let o=t.response?.cancelled;return{still_queued:n.filter((r)=>typeof r==="string"),...Array.isArray(o)&&{cancelled:o.filter((r)=>typeof r==="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,n)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,...u}=i;t(u)}else n(new $l(i.error,"awaitControlResponse: CLI error verdict"));if(i.pending_permission_requests||i.pending_user_dialog_requests)_e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Jh());return}let r=this.unmatchedControlResponses.get(e);if(r){this.unmatchedControlResponses.delete(e),o(r);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:n})})}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),n=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return n;let r=o.initialize,i=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied,code_running_mcp_tools_applied:l.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),s=r.hooks_applied??i.hooks_applied,a=r.plugins_applied??i.plugins_applied,u=r.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...r,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{code_running_mcp_tools_applied:u}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let o=++this.remoteControlCallGeneration,r=this.workSecretAnswerer,i=n?.reattachSessionId||(n?.workSecret===void 0?void 0:lK(n.workSecret)),s=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:n.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:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.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,r];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&s$(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 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 n=t?.signal;if(n?.aborted)return Promise.reject(ri(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Jh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let r={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(n){let m=()=>{if(d(ri(n.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(lt({type:"control_cancel_request",request_id:o})+`
|
|
39
39
|
`)).catch(()=>{})}catch{}};n.addEventListener("abort",m,{once:!0}),u=()=>{n.removeEventListener("abort",m)}}this.pendingControlResponses.set(o,{handler:(m)=>{if(m.subtype==="success")c(m);else d(Vg(Error(m.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof m.error_code==="string"&&uK.test(m.error_code)?m.error_code:void 0}));if(!i&&(m.pending_permission_requests||m.pending_user_dialog_requests))_e(`[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=lt(r)+`
|
|
40
40
|
`,f=()=>{if(n?.aborted)return;return l=!0,this.transport.write(p)};try{(this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(f()):this.initializeWritten.then(f)).catch(d)}catch(m){d(m)}})}initializationResult(){return this.initialization}writeAfterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(this.transport.write(e));return this.initializeWritten.then(()=>this.transport.write(e))}reinitialize(){return ht("sdk_reinitialize",()=>this.initialize({first:!1}))}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){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:t})).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){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e})).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 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}})).response)}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={},n={};for(let[a,u]of Object.entries(e))if(u.type==="sdk"&&"instance"in u)t[a]=u;else n[a]=u;let o=new Set(this.sdkMcpServers.keys()),r=new Set(Object.keys(t));for(let a of o)if(!r.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}=Wh(u);if(i$(a,u,d),c.timeout!==l.settings.timeout||c.disableAutoBackground!==l.settings.disableAutoBackground)_e(`[Query.setMcpServers] MCP server '${a}' is already registered, so the different timeout or disableAutoBackground passed to setMcpServers is ignored; remove and re-add the server to change it`);if(c.tools!==void 0&&!n$(c.tools,l.settings.tools))_e(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:{...n,...i}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){_e("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let t=0;for await(let n of e){if(t++,_e(`[Query.streamInput] Processing message ${t}: ${n.type}`),this.abortController?.signal.aborted)break;this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),await Promise.resolve(this.transport.write(lt(this.verbatimPrompts?{...n,client_composed:!0}:n)+`
|
|
41
41
|
`))}if(_e(`[Query.streamInput] Finished processing ${t} messages from input stream`),t>0&&this.hasBidirectionalNeeds())_e("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();_e("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(t){if(!(t instanceof ln))throw t}}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)_e("[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(()=>{_e(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,Tw)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return _e("[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 n=()=>e();t?.addEventListener("abort",n,{once:!0}),this.addCleanupCallback(()=>{t?.removeEventListener("abort",n),e()}),this.runEndedResolve=()=>{t?.removeEventListener("abort",n),e()}})}handleHookCallbacks(e,t,n,o){let r=this.hookCallbacks.get(e);if(!r)throw Error(`No hook callback found for ID: ${e}`);return r(t,n,{signal:o})}connectSdkMcpServer(e,t){let n=new Zh((s)=>this.sendMcpServerMessageToCli(e,s)),o=t.instance.connect(n).catch((s)=>{if(this.sdkMcpServers.get(e)?.transport===n)this.sdkMcpServers.delete(e);_e(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${s}`,{level:"error"})}),{settings:r,ignored:i}=Wh(t);i$(e,t,i),this.sdkMcpServers.set(e,{transport:n,settings:r,connection:o})}async disconnectSdkMcpServer(e){let t=this.sdkMcpServers.get(e);if(t){let n=`${e}:${Vl}`;for(let[o,r]of this.pendingMcpResponses)if(o.startsWith(n))this.pendingMcpResponses.delete(o),r.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}`,r=this.pendingMcpResponses.get(o);if(r){r.resolve(t),this.pendingMcpResponses.delete(o);return}if(typeof t.id==="string"&&t.id.startsWith(Vl)){_e(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:Go(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&e$(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.writeAfterInitialize(lt(n)+`
|
|
@@ -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.
|
|
3
|
+
// Version: 0.3.306
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -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.
|
|
3
|
+
// Version: 0.3.306
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -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.
|
|
3
|
+
// Version: 0.3.306
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -22,6 +22,6 @@ if (typeof Symbol.asyncDispose !== 'symbol') {
|
|
|
22
22
|
Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose')
|
|
23
23
|
} catch {}
|
|
24
24
|
}
|
|
25
|
-
import{c,i,l,r,n,_e,yt,j,Ht,Kt,se,et,bt,jt,Ct,tt,ie}from"./core-
|
|
25
|
+
import{c,i,l,r,n,_e,yt,j,Ht,Kt,se,et,bt,jt,Ct,tt,ie}from"./core-50f20fv8.mjs";import{randomUUID as D}from"crypto";import{constants as _}from"fs";import{open as z,readdir as x,rm as L,stat as Z}from"fs/promises";import{join as g}from"path";class I{available=void 0;probing=void 0;procUnreadableLogged=!1}var $e=new i(()=>new I);var k=["commands","agents","output-styles","skills","workflows","routines","themes","rules","session-env","uploads","mcp-skill-archives","usage-data","mcp-discovery-cache"];var cn=new Set(k),un=`must be one of the userConfigDir directory names (${k.join(", ")})`,R=["installed","marketplaces","flagged","catalog","inUseSweep"];var dn=new Set(R),ln=`must be one of the pluginRegistry files (${R.join(", ")})`,w=["manifest","catalog"];var fn=new Set(w),pn=`must be one of the marketplaceCache forms (${w.join(", ")})`;var P=["world"];var mn=new Set(P),gn=`must be one of the session journal names (${P.join(", ")})`;var C=["backup","corrupted"];var hn=new Set(C),yn=`must be one of the global-config copy kinds (${C.join(", ")})`;var B="cloud-snapshots";var W=new Set(["memory","tiny_memory","bagel",B,"bridge-pointer.json",".session-aliases"]);var v=".cast",Sn=`<stamp>${v} inside a session's folder is that session's terminal recording stream: address it as keys.recording(projectKey, sessionId, stamp)`;var J=[".ccr-tip.json",".precompact.json",v],bn=`must not end with ${J.join(", ")}: those name a session's project-level sibling files`;var q=".dir-sync.json",En=`must not end with ${q}: that name is reserved for a cloud session's record at the project level`;var In=`${[...W].join(", ")} are reserved: they name project-level entries, not sessions`;var X="timeline.jsonl",jn=`${X} is the job's timeline stream: address it as keys.jobTimeline(jobId)`;function y(e){return e===void 0?void 0:{source:e,hoverRestOn:c()}}var Q=64;function E(e){return c()?e:void 0}async function K(e,t,a={},s){if(!j(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let o=n({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
|
|
26
26
|
`;await T(e,o,a,E(s))}async function A(e,t,a={},s){if(!j(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let u=_e(t).trim();if(!u)throw Error("tag must be non-empty (use null to clear)");t=u}let o=n({type:"tag",tag:t??"",sessionId:e})+`
|
|
27
27
|
`;await T(e,o,a,E(s))}async function F(e,t={},a){if(!j(e))throw Error(`Invalid sessionId: ${e}`);let s=E(a);for(let o of await ne(t,s)){if(c()&&s!==void 0){let d=bt(o,s.isKeySegment);if(d!==void 0){if(await ee(d,e,s))return;continue}}let u=g(o,`${e}.jsonl`),f;try{({size:f}=await Z(u))}catch(d){let p=r(d);if(p==="ENOENT"||p==="ENOTDIR")continue;throw d}if(f===0)continue;await L(u,{force:!0}),await L(g(o,e),{recursive:!0,force:!0});return}throw Error(t.dir?`Session ${e} not found in project directory for ${t.dir}`:`Session ${e} not found in any project directory`)}async function ee(e,t,a){let{backend:s,transcriptKey:o}=a,u=o(e,t),f=await s.statMeta(u);if(!f.ok){if(f.error.code==="NotFound")return!1;throw Error("Session delete: transcript unreadable via storage",{cause:f.error})}if((f.value.storedBytes??f.value.size)===0)return!1;for(let p of["transcript","sidecar"]){let m=await s.deleteScope({namespace:p,projectKey:e,sessionId:t});if(!m.ok)throw Error("Session delete: session directory not deletable via storage",{cause:m.error})}let d=await s.delete(u);if(!d.ok)throw Error("Session delete: transcript not deletable via storage",{cause:d.error});return!0}async function ne(e,t){if(e.dir){let s=await jt(e.dir,Ht(t,c())),o=await O(s,t),u;try{u=await yt(s)}catch{u=[]}for(let f of u){if(f===s)continue;o.push(...await O(f,t))}return o}let a=se();if(c()&&t!==void 0){let s=await N(t);if(s===void 0)return[];if(s.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return s.names.map((o)=>g(a,o))}try{return(await x(a,{withFileTypes:!0})).filter((o)=>o.isDirectory()||o.isSymbolicLink()).map((o)=>g(a,o.name))}catch{return[]}}async function O(e,t){let a=y(t);if(a===void 0||!a.hoverRestOn)return tt(e);let s=await tt(e,a),o=et(e),u=process.platform==="win32",f=[];for(let d of s)if(d===o||await Ct(d,e,u,a))f.push(d);return f}async function N(e){let t=[],a,s=0;try{do{let o=await e.backend.listEntries({namespace:"transcript"},{skipScopeStats:!0,...a!==void 0&&{cursor:a}});if(!o.ok)return s===0?void 0:{names:t,laterPageFailed:!0};for(let u of o.value.items){let f=Kt(u,e.isKeySegment);if(f!==void 0)t.push(f)}a=o.value.cursor}while(a&&++s<Q);return{names:t,laterPageFailed:Boolean(a)}}catch{return s===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function T(e,t,a,s){let o=`${e}.jsonl`;if(a.dir){let d=await jt(a.dir,Ht(s,c()));for(let m of await tt(d,y(s)))if(await S(g(m,o),t,b(m,e,s)))return;let p;try{p=await yt(d)}catch{p=[]}for(let m of p){if(m===d)continue;for(let h of await tt(m,y(s)))if(await S(g(h,o),t,b(h,e,s)))return}throw Error(`Session ${e} not found in project directory for ${a.dir}`)}let u=se();if(c()&&s!==void 0){let d=await N(s);if(d===void 0)throw new l(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:p}=d;for(let m of p){let h=g(u,m);if(await S(g(h,o),t,b(h,e,s)))return}throw new l(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let f;try{f=await x(u)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let d of f)if(await S(g(u,d,o),t))return;throw Error(`Session ${e} not found in any project directory`)}async function S(e,t,a){if(c()&&a!==void 0)return re(a,t);let s;try{s=await z(e,_.O_WRONLY|_.O_APPEND)}catch(o){let u=r(o);if(u==="ENOENT"||u==="ENOTDIR")return!1;throw o}try{let{size:o}=await s.stat();if(o===0)return!1;let u=process.platform==="win32"?o:void 0,f=Buffer.from(t,"utf8"),d=0;while(d<f.length){let{bytesWritten:p}=await s.write(f,d,f.length-d,u);if(p<=0)throw new l(`tryAppend: short write to ${e} stalled with ${f.length-d} bytes remaining`,"tryAppend: zero-progress short write");if(d+=p,u!==void 0)u+=p}return!0}finally{await s.close()}}async function re({backend:e,key:t},a){let s=await e.append(t,[{data:a}],{precondition:{type:"ifExists",nonEmpty:!0}});if(!s.ok){if(s.error.code==="NotFound")return!1;throw Error("Session append: transcript not writable via storage",{cause:s.error})}return!0}function b(e,t,a){if(!c()||a===void 0)return;let s=bt(e,a.isKeySegment);return s===void 0?void 0:{backend:a.backend,key:a.transcriptKey(s,t)}}async function er(e,t,a){if(a?.sessionStore)return te(a.sessionStore,e,t,a.dir);return K(e,t,a)}async function nr(e,t,a){if(a?.sessionStore)return ae(a.sessionStore,e,t,a.dir);return A(e,t,a)}async function rr(e,t){if(!j(e))throw new l(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let a=ie(t.dir);await t.sessionStore.delete({projectKey:a,sessionId:e});return}return F(e,t)}async function te(e,t,a,s){if(!j(t))throw new l(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!a.trim())throw Error("title must be non-empty");let o=ie(s);await e.append({projectKey:o,sessionId:t},[{type:"custom-title",customTitle:a.trim(),sessionId:t,uuid:D(),timestamp:new Date().toISOString()}])}async function ae(e,t,a,s){if(!j(t))throw new l(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(a!==null){let u=_e(a).trim();if(!u)throw Error("tag must be non-empty (use null to clear)");a=u}let o=ie(s);await e.append({projectKey:o,sessionId:t},[{type:"tag",tag:a??"",sessionId:t,uuid:D(),timestamp:new Date().toISOString()}])}export{rr as deleteSession,er as renameSession,nr as tagSession};
|