| 1682 | `).trim();if(O.timestamp){let P=new Date(O.timestamp).getTime();z.set(j,{content:X,timestamp:P,offset:void 0,limit:void 0})}}let H=$.get(w.tool_use_id);if(H&&O.timestamp){let M=new Date(O.timestamp).getTime();z.set(H.filePath,{content:H.content,timestamp:M,offset:void 0,limit:void 0})}let J=A.get(w.tool_use_id);if(J&&w.is_error!==!0)try{let{content:M}=vB(J);z.set(J,{content:M,timestamp:ik(J),offset:void 0,limit:void 0})}catch(M){if(!e3(M))throw M}}}return z}function qp1(q){let K=new Set;for(let _ of q)if(_.type==="assistant"&&Array.isArray(_.message.content)){for(let z of _.message.content)if(z.type==="tool_use"&&z.name===_q){let{input:Y}=z;if(typeof Y!=="object"||Y===null||!("command"in Y))continue;let $=hzz(typeof Y.command==="string"?Y.command:void 0);if($)K.add($)}}return K}function hzz(q){if(!q)return;let K=q.trim().split(/\s+/);for(let _ of K){if(/^[A-Za-z_]\w*=/.test(_))continue;if(Rzz.has(_))continue;return _}return}var yzz=10,Ezz=100,Lzz=30000,Zo6,Rzz;var To6=y(()=>{cl6();v8();tm1();Bq();IY();E2();_8();m8();y8();bK();ZE();NG();i1();dz();_K();Zo6=new Map;Rzz=new Set(["sudo"])});import{randomUUID as Szz}from"crypto";import{rm as Czz}from"fs";import{appendFile as bzz,copyFile as Ly4,mkdir as Kp1}from"fs/promises";import{dirname as Ry4,isAbsolute as xzz,join as jw6,relative as Izz}from"path";function vo6(q){Czz(q,{recursive:!0,force:!0,maxRetries:3,retryDelay:100},()=>{})}function mN8(q){return jw6(AC(),"speculation",String(process.pid),q)}function uN8(q,K){return{behavior:"deny",message:q,decisionReason:{type:"other",reason:K}}}async function gzz(q,K,_){let z=!0;for(let Y of K){let $=jw6(q,Y),A=jw6(_,Y);try{await Kp1(Ry4(A),{recursive:!0}),await Ly4($,A)}catch{z=!1,N(`[Speculation] Failed to copy ${Y} to main`)}}return z}function pN8(q,K,_,z,Y,$,A){d("tengu_speculation",{speculation_id:q,outcome:K,duration_ms:Date.now()-_,suggestion_length:z,tools_executed:zp1(Y),completed:$!==null,boundary_type:$?.type,boundary_tool:Fzz($),boundary_detail:Uzz($),...A})}function zp1(q){let K=q.filter(Yp1).flatMap((_)=>_.message.content).filter((_)=>typeof _==="object"&&_!==null&&("type"in _));return $7(K,(_)=>_.type==="tool_result"&&!_.is_error)}function Fzz(q){if(!q)return;switch(q.type){case"bash":return"Bash";case"edit":case"denied_tool":return q.toolName;case"complete":return}}function Uzz(q){if(!q)return;switch(q.type){case"bash":return q.command.slice(0,200);case"edit":return q.filePath;case"denied_tool":return q.detail;case"complete":return}}function Yp1(q){return q.type==="user"&&"message"in q&&Array.isArray(q.message.content)}function Qzz(q){let K=($)=>typeof $==="object"&&$!==null&&$.type==="tool_result"&&typeof $.tool_use_id==="string",_=($)=>!$.is_error&&!(typeof $.content==="string"&&$.content.includes(j0)),z=new Set(q.filter(Yp1).flatMap(($)=>$.message.content).filter(K).filter(_).map(($)=>$.tool_use_id)),Y=($)=>$.type!=="thinking"&&$.type!=="redacted_thinking"&&!($.type==="tool_use"&&!z.has($.id))&&!($.type==="tool_result"&&!z.has($.tool_use_id))&&!($.type==="text"&&($.text===fq6||$.text===j0));return q.map(($)=>{if(!("message"in $)||!Array.isArray($.message.content))return $;let A=$.message.content.filter(Y);if(A.length===$.message.content.length)return $;if(A.length===0)return null;if(!A.some((w)=>w.type!=="text"||w.text!==void 0&&w.text.trim()!==""))return null;return{...$,message:{...$.message,content:A}}}).filter(($)=>$!==null)}function dzz(q,K,_,z){return null}function SV6(q,K){q((_)=>{if(_.speculation.status!=="active")return _;let z=_.speculation,Y=K(z);if(!Object.entries(Y).some(([A,O])=>z[A]!==O))return _;return{..._,speculation:{...z,...Y}}})}function _p1(q){q((K)=>{if(K.speculation.status==="idle")return K;return{...K,speculation:Wq6}})}function Fm1(){return N("[Speculation] enabled=false"),!1}async function czz(q,K,_,z,Y){try{let $=q.toolUseContext.getAppState(),A=mm1($);if(A){w0(`pipeline_${A}`);return}let O={...q,messages:[...q.messages,U8({content:K}),..._]},w=bC(Y);if(w.signal.aborted)return;let j=GN8(),{suggestion:H,generationRequestId:J}=await Bm1(w,j,hL(O));if(w.signal.aborted)return;if(gm1(H,j))return;N(`[Speculation] Pipelined suggestion: "${H.slice(0,50)}..."`),SV6(z,()=>({pipelinedSuggestion:{text:H,promptId:j,generationRequestId:J}}))}catch($){if($ instanceof Error&&$.name==="AbortError")return;N(`[Speculation] Pipelined suggestion failed: ${d6($)}`)}}async function Um1(q,K,_,z=!1,Y){if(!Fm1())return;ou(_);let $=Szz().slice(0,8),A=bC(K.toolUseContext.abortController);if(A.signal.aborted)return;let O=Date.now(),w={current:[]},j={current:new Set},H=mN8($),J=Vx();try{await Kp1(H,{recursive:!0})}catch{N("[Speculation] Failed to create overlay directory");return}let M={current:K};_((X)=>({...X,speculation:{status:"active",id:$,abort:()=>A.abort(),startTime:O,messagesRef:w,writtenPathsRef:j,boundary:null,suggestionLength:q.length,toolUseCount:0,isPipelined:z,contextRef:M}})),N(`[Speculation] Starting speculation ${$}`);try{let X=await hG({promptMessages:[U8({content:q})],cacheSafeParams:Y??hL(K),skipTranscript:!0,canUseTool:async(P,W)=>{let D=pzz.has(P.name),f=Bzz.has(P.name);if(D){let Z=K.toolUseContext.getAppState(),{mode:T,isBypassPermissionsModeAvailable:v}=Z.toolPermissionContext;if(!(T==="acceptEdits"||T==="bypassPermissions"||T==="plan"&&v)){N(`[Speculation] Stopping at file edit: ${P.name}`);let E="file_path"in W?W.file_path:void 0;return SV6(_,()=>({boundary:{type:"edit",toolName:P.name,filePath:E??"",completedAt:Date.now()}})),A.abort(),uN8("Speculation paused: file edit requires permission","speculation_edit_boundary")}}if(D||f){let Z="notebook_path"in W?"notebook_path":("path"in W)?"path":"file_path",T=W[Z];if(T){let v=Izz(J,T);if(xzz(v)||v.startsWith("..")){if(D)return N(`[Speculation] Denied ${P.name}: path outside cwd: ${T}`),uN8("Write outside cwd not allowed during speculation","speculation_write_outside_root");return{behavior:"allow",updatedInput:W,decisionReason:{type:"other",reason:"speculation_read_outside_root"}}}if(D){if(!j.current.has(v)){let V=jw6(H,v);await Kp1(Ry4(V),{recursive:!0});try{await Ly4(jw6(J,v),V)}catch{}j.current.add(v)}W={...W,[Z]:jw6(H,v)}}else if(j.current.has(v))W={...W,[Z]:jw6(H,v)};return N(`[Speculation] ${D?"Write":"Read"} ${T} -> ${W[Z]}`),{behavior:"allow",updatedInput:W,decisionReason:{type:"other",reason:"speculation_file_access"}}}if(f)return{behavior:"allow",updatedInput:W,decisionReason:{type:"other",reason:"speculation_read_default_cwd"}}}if(P.name==="Bash"){let Z="command"in W&&typeof W.command==="string"?W.command:"";if(!Z||hN8({command:Z},ko6(Z)).behavior!=="allow")return N(`[Speculation] Stopping at bash: ${Z.slice(0,50)||"missing command"}`),SV6(_,()=>({boundary:{type:"bash",command:Z,completedAt:Date.now()}})),A.abort(),uN8("Speculation paused: bash boundary","speculation_bash_boundary");return{behavior:"allow",updatedInput:W,decisionReason:{type:"other",reason:"speculation_readonly_bash"}}}N(`[Speculation] Stopping at denied tool: ${P.name}`);let G=String("url"in W&&W.url||"file_path"in W&&W.file_path||"path"in W&&W.path||"command"in W&&W.command||"").slice(0,200);return SV6(_,()=>({boundary:{type:"denied_tool",toolName:P.name,detail:G,completedAt:Date.now()}})),A.abort(),uN8(`Tool ${P.name} not allowed during speculation`,"speculation_unknown_tool")},querySource:"speculation",forkLabel:"speculation",maxTurns:uzz,overrides:{abortController:A,requireCanUseTool:!0},onMessage:(P)=>{if(P.type==="assistant"||P.type==="user"){if(w.current.push(P),w.current.length>=mzz)A.abort();if(Yp1(P)){let W=$7(P.message.content,(D)=>D.type==="tool_result"&&!D.is_error);if(W>0)SV6(_,(D)=>({toolUseCount:D.toolUseCount+W}))}}}});if(A.signal.aborted)return;SV6(_,()=>({boundary:{type:"complete",completedAt:Date.now(),outputTokens:X.totalUsage.output_tokens}})),N(`[Speculation] Complete: ${zp1(w.current)} tools`),czz(M.current,q,w.current,_,A)}catch(X){if(A.abort(),X instanceof Error&&X.name==="AbortError"){vo6(H),_p1(_);return}vo6(H),H6(X instanceof Error?X:Error("Speculation failed")),pN8($,"error",O,q.length,w.current,null,{error_type:X instanceof Error?X.name:"Unknown",error_message:d6(X).slice(0,200),error_phase:"start",is_pipelined:z}),_p1(_)}}async function lzz(q,K,_){if(q.status!=="active")return null;let{id:z,messagesRef:Y,writtenPathsRef:$,abort:A,startTime:O,suggestionLength:w,isPipelined:j}=q,H=Y.current,J=mN8(z),M=Date.now();if(A(),_>0)await gzz(J,$.current,Vx());vo6(J);let X=q.boundary,P=Math.min(M,X?.completedAt??1/0)-O;if(K((W)=>{if(W.speculation.status==="active"&&W.speculation.boundary)X=W.speculation.boundary,P=Math.min(M,X.completedAt??1/0)-O;return{...W,speculation:Wq6,speculationSessionTimeSavedMs:W.speculationSessionTimeSavedMs+P}}),N(X===null?`[Speculation] Accept ${z}: still running, using ${H.length} messages`:`[Speculation] Accept ${z}: already complete`),pN8(z,"accepted",O,w,H,X,{message_count:H.length,time_saved_ms:P,is_pipelined:j}),P>0){let W={type:"speculation-accept",timestamp:new Date().toISOString(),timeSavedMs:P};bzz(Y$(),g6(W)+` |
| 1683 | `,{mode:384}).catch(()=>{N("[Speculation] Failed to write speculation-accept to transcript")})}return{messages:H,boundary:X,timeSavedMs:P}}function ou(q){q((K)=>{if(K.speculation.status!=="active")return K;let{id:_,abort:z,startTime:Y,boundary:$,suggestionLength:A,messagesRef:O,isPipelined:w}=K.speculation;return N(`[Speculation] Aborting ${_}`),pN8(_,"aborted",Y,A,O.current,$,{abort_reason:"user_typed",is_pipelined:w}),z(),vo6(mN8(_)),{...K,speculation:Wq6}})}async function hy4(q,K,_,z,Y){try{let{setMessages:$,readFileState:A,cwd:O}=Y;_((f)=>{if(f.promptSuggestion.text===null&&f.promptSuggestion.promptId===null)return f;return{...f,promptSuggestion:{text:null,promptId:null,shownAt:0,acceptedAt:0,generationRequestId:null}}});let w=q.messagesRef.current,j=Qzz(w),H=U8({content:z});$((f)=>[...f,H]);let J=await lzz(q,_,j.length),M=J?.boundary?.type==="complete";if(!M){let f=j.findLastIndex((G)=>G.type!=="assistant");j=j.slice(0,f+1)}let X=J?.timeSavedMs??0,P=K+X,W=dzz(j,J?.boundary??null,X,P);$((f)=>[...f,...j]);let D=hV6(j,O,tF);if(A.current=mk6(A.current,D),W)$((f)=>[...f,W]);if(N(`[Speculation] ${J?.boundary?.type??"incomplete"}, injected ${j.length} messages`),M&&q.pipelinedSuggestion){let{text:f,promptId:G,generationRequestId:Z}=q.pipelinedSuggestion;N(`[Speculation] Promoting pipelined suggestion: "${f.slice(0,50)}..."`),_((v)=>({...v,promptSuggestion:{text:f,promptId:G,shownAt:Date.now(),acceptedAt:0,generationRequestId:Z}}));let T={...q.contextRef.current,messages:[...q.contextRef.current.messages,U8({content:z}),...j]};Um1(f,T,_,!0)}return{queryRequired:!M}}catch($){return H6($ instanceof Error?$:Error("handleSpeculationAccept failed")),pN8(q.id,"error",q.startTime,q.suggestionLength,q.messagesRef.current,q.boundary,{error_type:$ instanceof Error?$.name:"Unknown",error_message:d6($).slice(0,200),error_phase:"accept",is_pipelined:q.isPipelined}),vo6(mN8(q.id)),_p1(_),{queryRequired:!0}}}var uzz=20,mzz=100,pzz,Bzz;var Yw6=y(()=>{v8();EV6();DN();am1();B2();V1();_8();y8();NG();nv();U7();E8();i1();Tz();To6();_K();l8();k8();zw6();pzz=new Set(["Edit","Write","NotebookEdit"]),Bzz=new Set(["Read","Glob","Grep","ToolSearch","LSP","TaskGet","TaskList"])});import{randomUUID as nzz}from"crypto";function ur(q){if(!i7())return;if(Vo6.length>=izz)Vo6.shift();Vo6.push(q)}function No6(){if(Vo6.length===0)return[];return Vo6.splice(0).map((K)=>({...K,uuid:nzz(),session_id:N8()}))}function ZN(q,K,_){ur({type:"system",subtype:"task_notification",task_id:q,tool_use_id:_?.toolUseId,status:K,output_file:_?.outputFile??"",summary:_?.summary??"",usage:_?.usage})}var izz=1000,Vo6;var pC=y(()=>{v8();Vo6=[]});function A3(q,K,_){K((z)=>{let Y=z.tasks?.[q];if(!Y)return z;let $=_(Y);if($===Y)return z;return{...z,tasks:{...z.tasks,[q]:$}}})}function H0(q,K){let _=!1;if(K((z)=>{let Y=z.tasks[q.id];_=Y!==void 0;let $=Y&&"retain"in Y?{...q,retain:Y.retain,startTime:Y.startTime,messages:Y.messages,diskLoaded:Y.diskLoaded,pendingMessages:Y.pendingMessages}:q;return{...z,tasks:{...z.tasks,[q.id]:$}}}),_)return;ur({type:"system",subtype:"task_started",task_id:q.id,tool_use_id:q.toolUseId,description:q.description,task_type:q.type,workflow_name:"workflowName"in q?q.workflowName:void 0,prompt:"prompt"in q?q.prompt:void 0})}function CV6(q,K){K((_)=>{let z=_.tasks?.[q];if(!z)return _;if(!mr(z.status))return _;if(!z.notified)return _;if("retain"in z&&(z.evictAfter??1/0)>Date.now())return _;let{[q]:Y,...$}=_.tasks;return{..._,tasks:$}})}function gN8(q){let K=q.tasks??{};return Object.values(K).filter((_)=>_.status==="running")}async function Cy4(q){let K=[],_={},z=[],Y=q.tasks??{};for(let $ of Object.values(Y)){if($.notified)switch($.status){case"completed":case"failed":case"killed":z.push($.id);continue;case"pending":continue;case"running":break}if($.status==="running"){let A=await xy4($.id,$.outputOffset);if(A.content)_[$.id]=A.newOffset}}return{attachments:K,updatedTaskOffsets:_,evictedTaskIds:z}}function by4(q,K,_){let z=Object.keys(K);if(z.length===0&&_.length===0)return;q((Y)=>{let $=!1,A={...Y.tasks};for(let O of z){let w=A[O];if(w?.status==="running")A[O]={...w,outputOffset:K[O]},$=!0}for(let O of _){let w=A[O];if(!w||!mr(w.status)||!w.notified)continue;if("retain"in w&&(w.evictAfter??1/0)>Date.now())continue;delete A[O],$=!0}return $?{...Y,tasks:A}:Y})}var Sy4=3000,BN8=30000;var J0=y(()=>{RY();GN();p2();pC();Ij()});function CL(q){return q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function e9(q){return CL(q).replace(/"/g,""").replace(/'/g,"'")}function my4(q){return q.isNonInteractiveSession}function FN8(q){let K=Iy4.get(q);if(K)return K;let _=azz(q);return Iy4.set(q,_),_}function azz(q){try{let K=new uy4.Ajv({allErrors:!0});if(!K.validateSchema(q))return{error:K.errorsText(K.errors)};let z=K.compile(q);return{tool:{...$p1,inputJSONSchema:q,async call(Y){if(!z(Y)){let A=z.errors?.map((O)=>`${O.instancePath||"root"}: ${O.message}`).join(", ");throw new uk(`Output does not match required schema: ${A}`,`StructuredOutput schema mismatch: ${(A??"").slice(0,150)}`)}return{data:"Structured output provided successfully",structured_output:Y}}}}}catch(K){return{error:K instanceof Error?K.message:String(K)}}}var uy4,rzz,ozz,MD="StructuredOutput",$p1,Iy4;var GU=y(()=>{x7();Bq();y8();l8();uy4=O6(cz8(),1),rzz=B6(()=>L.object({}).passthrough()),ozz=B6(()=>L.string().describe("Structured output tool result"));$p1=sq({isMcp:!1,isEnabled(){return!0},isConcurrencySafe(){return!0},isReadOnly(){return!0},isOpenWorld(){return!1},name:MD,searchHint:"return the final response as structured JSON",maxResultSizeChars:1e5,async description(){return"Return structured output in the requested format"},async prompt(){return"Use this tool to return your final response in the requested structured format. You MUST call this tool exactly once at the end of your response to provide the structured output."},get inputSchema(){return rzz()},get outputSchema(){return ozz()},async call(q){return{data:"Structured output provided successfully",structured_output:q}},async checkPermissions(q){return{behavior:"allow",updatedInput:q}},renderToolUseMessage(q){let K=Object.keys(q);if(K.length===0)return null;if(K.length<=3)return K.map((_)=>`${_}: ${g6(q[_])}`).join(", ");return`${K.length} fields: ${K.slice(0,3).join(", ")}…`},renderToolUseRejectedMessage(){return"Structured output rejected"},renderToolUseErrorMessage(){return"Structured output error"},renderToolUseProgressMessage(){return null},renderToolResultMessage(q){return q},mapToolResultToToolResultBlockParam(q,K){return{tool_use_id:K,type:"tool_result",content:q}}}),Iy4=new WeakMap});function EX(q){return q}function pO(q){return q}function py4(q){return szz.test(q)?q:null}var szz;var M0=y(()=>{szz=/^a(?:.+-)?[0-9a-f]{16}$/});function UN8(q){let K=q.indexOf(` |