| 16444 | `);jM({mode:"prompt",value:_6,uuid:wW()}),f6();return}if(P&&!W){W=!0,N("[print.ts] Input closed with active teammates, injecting shutdown prompt"),jM({mode:"prompt",value:l75,uuid:wW()}),f6();return}await R7(500)}}if(P)if(await(async()=>{let E6=O();if(RV1(E6))await hV1(w,E6);let R6=O(),h6=R6.teamContext;return h6&&Object.keys(h6.teammates).length>0||Of8(R6)})())jM({mode:"prompt",value:l75,uuid:wW()}),f6();else{if(T.inflightPromise)await Promise.race([T.inflightPromise,R7(5000)]);T.abortController?.abort(),T.abortController=null,await P17(),J6(),v?.(),Xq6.delete(V),G.done()}},N6=null;if(d75&&c75?.isKairosCronEnabled())N6=d75.createCronScheduler({onFire:(l6)=>{if(P)return;jM({mode:"prompt",value:l6,uuid:wW(),priority:"later",isMeta:!0,workload:LD8}),f6()},isLoading:()=>M||P,getJitterConfig:toY?.getCronJitterConfig,isKilled:()=>!c75?.isKairosCronEnabled()}),N6.start();let Z6=function(l6,S6){G.enqueue({type:"control_response",response:{subtype:"success",request_id:l6.request_id,response:S6}})},V6=function(l6,S6){G.enqueue({type:"control_response",response:{subtype:"error",request_id:l6.request_id,error:S6}})},y6=new Set;q.setUnexpectedResponseCallback(async(l6)=>{await e75({message:l6,setAppState:w,handledToolUseIds:y6,onEnqueued:()=>{f6()}})});let T6=new Map,n6=new Map,o6=new Set,I6=new Map,C6=null;return(async()=>{let l6=!1;c8("info","cli_message_loop_started");for await(let S6 of q.structuredInput){let E6="uuid"in S6?S6.uuid:void 0;if(E6&&S6.type!=="user"&&S6.type!=="control_response")jU(E6,"completed");if(S6.type==="control_request"){if(S6.request.subtype==="interrupt"){if(f)f.abort();T.abortController?.abort(),T.abortController=null,T.lastEmitted=null,T.pendingSuggestion=null,Z6(S6)}else if(S6.request.subtype==="end_session"){if(N(`[print.ts] end_session received, reason=${S6.request.reason??"unspecified"}`),f)f.abort();T.abortController?.abort(),T.abortController=null,T.lastEmitted=null,T.pendingSuggestion=null,Z6(S6);break}else if(S6.request.subtype==="initialize"){if(S6.request.sdkMcpServers&&S6.request.sdkMcpServers.length>0)for(let R6 of S6.request.sdkMcpServers)A[R6]={type:"sdk",name:R6};if(await YaY(S6.request,S6.request_id,l6,G,_,B,q,!!H.enableAuthStatus,H,j,O),S6.request.promptSuggestions)w((R6)=>{if(R6.promptSuggestionEnabled)return R6;return{...R6,promptSuggestionEnabled:!0}});if(S6.request.agentProgressSummaries&&g8("tengu_slate_prism",!0))Di8(!0);if(l6=!0,br6())f6()}else if(S6.request.subtype==="set_permission_mode"){let R6=S6.request;w((h6)=>({...h6,toolPermissionContext:$aY(R6,S6.request_id,h6.toolPermissionContext,G),isUltraplanMode:R6.ultraplan??h6.isUltraplanMode}))}else if(S6.request.subtype==="set_model"){let R6=S6.request.model??"default",h6=R6==="default"?If():R6;p=h6,YP(h6),_48({model:h6}),C(R6,h6),Z6(S6)}else if(S6.request.subtype==="set_max_thinking_tokens"){if(S6.request.max_thinking_tokens===null)H.thinkingConfig=void 0;else if(S6.request.max_thinking_tokens===0)H.thinkingConfig={type:"disabled"};else H.thinkingConfig={type:"enabled",budgetTokens:S6.request.max_thinking_tokens};Z6(S6)}else if(S6.request.subtype==="mcp_status")Z6(S6,{mcpServers:G6()});else if(S6.request.subtype==="get_context_usage")try{let R6=O(),h6=await pg8({messages:E,getAppState:O,options:{mainLoopModel:D5(),tools:q6(R6),agentDefinitions:R6.agentDefinitions,customSystemPrompt:H.systemPrompt,appendSystemPrompt:H.appendSystemPrompt}});Z6(S6,{...h6})}catch(R6){V6(S6,d6(R6))}else if(S6.request.subtype==="mcp_message"){let R6=S6.request,h6=g.find((x6)=>x6.name===R6.server_name);if(h6&&h6.type==="connected"&&h6.client?.transport?.onmessage)h6.client.transport.onmessage(R6.message);Z6(S6)}else if(S6.request.subtype==="rewind_files"){let R6=O(),h6=await s75(S6.request.user_message_id,R6,w,S6.request.dry_run??!1);if(h6.canRewind||S6.request.dry_run)Z6(S6,h6);else V6(S6,h6.error??"Unexpected error")}else if(S6.request.subtype==="cancel_async_message"){let R6=S6.request.message_uuid,h6=$V6((x6)=>x6.uuid===R6);Z6(S6,{cancelled:h6.length>0})}else if(S6.request.subtype==="seed_read_state"){try{let R6=lq(S6.request.path),h6=Math.floor((await soY(R6)).mtimeMs);if(h6<=S6.request.mtime){let x6=await aoY(R6,"utf-8"),b6=(x6.charCodeAt(0)===65279?x6.slice(1):x6).replaceAll(`\r |
| 16446 | `);R.set(R6,{content:b6,timestamp:h6,offset:void 0,limit:void 0})}}catch{}Z6(S6)}else if(S6.request.subtype==="mcp_set_servers"){let{response:R6,sdkServersChanged:h6}=await j6(S6.request.servers);if(Z6(S6,R6),h6)K6()}else if(S6.request.subtype==="reload_plugins")try{let R6=await XJ6(w),h6=n.filter((_6)=>_6.source==="flagSettings");n=[...R6.agentDefinitions.allAgents,...h6];let x6=[],[b6,Q6,Y6]=await Promise.allSettled([u0(GK8()),A6(),ZJ()]);if(b6.status==="fulfilled")a=b6.value;else H6(b6.reason);if(Q6.status==="rejected")H6(Q6.reason);if(Y6.status==="fulfilled")x6=Y6.value.enabled.map((_6)=>({name:_6.name,path:_6.path,source:_6.source}));else H6(Y6.reason);Z6(S6,{commands:a.filter((_6)=>_6.userInvocable!==!1).map((_6)=>({name:W_(_6),description:UH6(_6),argumentHint:_6.argumentHint||""})),agents:n.map((_6)=>({name:_6.agentType,description:_6.whenToUse,model:_6.model==="inherit"?void 0:_6.model})),plugins:x6,mcpServers:G6(),error_count:R6.error_count})}catch(R6){V6(S6,d6(R6))}else if(S6.request.subtype==="mcp_reconnect"){let R6=O(),{serverName:h6}=S6.request;U.delete(h6);let x6=EN(h6)??K.find((b6)=>b6.name===h6)?.config??g.find((b6)=>b6.name===h6)?.config??t.clients.find((b6)=>b6.name===h6)?.config??R6.mcp.clients.find((b6)=>b6.name===h6)?.config??null;if(!x6)V6(S6,`Server not found: ${h6}`);else{let b6=await qm(h6,x6),Q6=kE(h6);if(w((Y6)=>({...Y6,mcp:{...Y6.mcp,clients:Y6.mcp.clients.map((_6)=>_6.name===h6?b6.client:_6),tools:[...D0(Y6.mcp.tools,(_6)=>_6.name?.startsWith(Q6)),...b6.tools],commands:[...D0(Y6.mcp.commands,(_6)=>LU(_6,h6)),...b6.commands],resources:b6.resources&&b6.resources.length>0?{...Y6.mcp.resources,[h6]:b6.resources}:W56(Y6.mcp.resources,h6)}})),t={...t,clients:[...t.clients.filter((Y6)=>Y6.name!==h6),b6.client],tools:[...t.tools.filter((Y6)=>!Y6.name?.startsWith(Q6)),...b6.tools]},b6.client.type==="connected")c([b6.client]),iA7(b6.client),Z6(S6);else{let Y6=b6.client.type==="failed"?b6.client.error??"Connection failed":`Server status: ${b6.client.type}`;V6(S6,Y6)}}}else if(S6.request.subtype==="mcp_toggle"){let R6=O(),{serverName:h6,enabled:x6}=S6.request;U.delete(h6);let b6=EN(h6)??K.find((Q6)=>Q6.name===h6)?.config??g.find((Q6)=>Q6.name===h6)?.config??t.clients.find((Q6)=>Q6.name===h6)?.config??R6.mcp.clients.find((Q6)=>Q6.name===h6)?.config??null;if(!b6)V6(S6,`Server not found: ${h6}`);else if(!x6){HN6(h6,!1);let Q6=[...K,...g,...t.clients,...R6.mcp.clients].find((_6)=>_6.name===h6);if(Q6&&Q6.type==="connected")await pG(h6,b6);let Y6=kE(h6);w((_6)=>({..._6,mcp:{..._6.mcp,clients:_6.mcp.clients.map((F6)=>F6.name===h6?{name:h6,type:"disabled",config:b6}:F6),tools:D0(_6.mcp.tools,(F6)=>F6.name?.startsWith(Y6)),commands:D0(_6.mcp.commands,(F6)=>LU(F6,h6)),resources:W56(_6.mcp.resources,h6)}})),Z6(S6)}else{HN6(h6,!0);let Q6=await qm(h6,b6),Y6=kE(h6);if(w((_6)=>({..._6,mcp:{..._6.mcp,clients:_6.mcp.clients.map((F6)=>F6.name===h6?Q6.client:F6),tools:[...D0(_6.mcp.tools,(F6)=>F6.name?.startsWith(Y6)),...Q6.tools],commands:[...D0(_6.mcp.commands,(F6)=>LU(F6,h6)),...Q6.commands],resources:Q6.resources&&Q6.resources.length>0?{..._6.mcp.resources,[h6]:Q6.resources}:W56(_6.mcp.resources,h6)}})),Q6.client.type==="connected")c([Q6.client]),iA7(Q6.client),Z6(S6);else{let _6=Q6.client.type==="failed"?Q6.client.error??"Connection failed":`Server status: ${Q6.client.type}`;V6(S6,_6)}}}else if(S6.request.subtype==="channel_enable"){let R6=O();AaY(S6.request_id,S6.request.serverName,[...R6.mcp.clients,...g,...t.clients],G)}else if(S6.request.subtype==="mcp_authenticate"){let{serverName:R6}=S6.request,h6=O(),x6=EN(R6)??K.find((b6)=>b6.name===R6)?.config??h6.mcp.clients.find((b6)=>b6.name===R6)?.config??null;if(!x6)V6(S6,`Server not found: ${R6}`);else if(x6.type!=="sse"&&x6.type!=="http")V6(S6,`Server type "${x6.type}" does not support OAuth authentication`);else try{T6.get(R6)?.abort();let b6=new AbortController;T6.set(R6,b6);let Q6,Y6=new Promise((v6)=>{Q6=v6}),_6=pq6(R6,x6,(v6)=>Q6(v6),b6.signal,{skipBrowserOpen:!0,onWaitingForCallback:(v6)=>{n6.set(R6,v6)}}),F6=await Promise.race([Y6,_6.then(()=>null)]);if(F6)Z6(S6,{authUrl:F6,requiresUserAction:!0});else Z6(S6,{requiresUserAction:!1});I6.set(R6,_6);let W6=_6.then(async()=>{if(bG(R6))return;if(o6.has(R6))return;let v6=await qm(R6,x6),m6=kE(R6);w((K8)=>({...K8,mcp:{...K8.mcp,clients:K8.mcp.clients.map((H8)=>H8.name===R6?v6.client:H8),tools:[...D0(K8.mcp.tools,(H8)=>H8.name?.startsWith(m6)),...v6.tools],commands:[...D0(K8.mcp.commands,(H8)=>LU(H8,R6)),...v6.commands],resources:v6.resources&&v6.resources.length>0?{...K8.mcp.resources,[R6]:v6.resources}:W56(K8.mcp.resources,R6)}})),t={...t,clients:[...t.clients.filter((K8)=>K8.name!==R6),v6.client],tools:[...t.tools.filter((K8)=>!K8.name?.startsWith(m6)),...v6.tools]}}).catch((v6)=>{N(`MCP OAuth failed for ${R6}: ${v6}`,{level:"error"})}).finally(()=>{if(T6.get(R6)===b6)T6.delete(R6),n6.delete(R6),o6.delete(R6),I6.delete(R6)})}catch(b6){V6(S6,d6(b6))}}else if(S6.request.subtype==="mcp_oauth_callback_url"){let{serverName:R6,callbackUrl:h6}=S6.request,x6=n6.get(R6);if(x6){let b6=!1;try{let Q6=new URL(h6);b6=Q6.searchParams.has("code")||Q6.searchParams.has("error")}catch{}if(!b6)V6(S6,"Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.");else{o6.add(R6),x6(h6);let Q6=I6.get(R6);if(Q6)try{await Q6,Z6(S6)}catch(Y6){V6(S6,Y6 instanceof Error?Y6.message:"OAuth authentication failed")}else Z6(S6)}}else V6(S6,`No active OAuth flow for server: ${R6}`)}else if(S6.request.subtype==="claude_authenticate"){let{loginWithClaudeAi:R6}=S6.request;C6?.service.cleanup(),d("tengu_oauth_flow_start",{loginWithClaudeAi:R6??!0});let h6=new Eo,x6,b6=new Promise((Y6)=>{x6=Y6}),Q6=h6.startOAuthFlow(async(Y6,_6)=>{x6({manualUrl:Y6,automaticUrl:_6})},{loginWithClaudeAi:R6??!0,skipBrowserOpen:!0}).then(async(Y6)=>{await u26(Y6),d("tengu_oauth_success",{loginWithClaudeAi:R6??!0})}).finally(()=>{if(h6.cleanup(),C6?.service===h6)C6=null});C6={service:h6,flow:Q6},Q6.catch((Y6)=>N(`claude_authenticate flow ended: ${Y6}`,{level:"info"}));try{let{manualUrl:Y6,automaticUrl:_6}=await Promise.race([b6,Q6.then(()=>{throw Error("OAuth flow completed without producing auth URLs")})]);Z6(S6,{manualUrl:Y6,automaticUrl:_6})}catch(Y6){V6(S6,d6(Y6))}}else if(S6.request.subtype==="claude_oauth_callback"||S6.request.subtype==="claude_oauth_wait_for_completion")if(!C6)V6(S6,"No active claude_authenticate flow");else{if(S6.request.subtype==="claude_oauth_callback")C6.service.handleManualAuthCodeInput({authorizationCode:S6.request.authorizationCode,state:S6.request.state});let{flow:R6}=C6;R6.then(()=>{let h6=RG6();Z6(S6,{account:{email:h6?.email,organization:h6?.organization,subscriptionType:h6?.subscription,tokenSource:h6?.tokenSource,apiKeySource:h6?.apiKeySource,apiProvider:E7()}})},(h6)=>V6(S6,d6(h6)))}else if(S6.request.subtype==="mcp_clear_auth"){let{serverName:R6}=S6.request,h6=O(),x6=EN(R6)??K.find((b6)=>b6.name===R6)?.config??h6.mcp.clients.find((b6)=>b6.name===R6)?.config??null;if(!x6)V6(S6,`Server not found: ${R6}`);else if(x6.type!=="sse"&&x6.type!=="http")V6(S6,`Cannot clear auth for server type "${x6.type}"`);else{await wa6(R6,x6);let b6=await qm(R6,x6),Q6=kE(R6);w((Y6)=>({...Y6,mcp:{...Y6.mcp,clients:Y6.mcp.clients.map((_6)=>_6.name===R6?b6.client:_6),tools:[...D0(Y6.mcp.tools,(_6)=>_6.name?.startsWith(Q6)),...b6.tools],commands:[...D0(Y6.mcp.commands,(_6)=>LU(_6,R6)),...b6.commands],resources:b6.resources&&b6.resources.length>0?{...Y6.mcp.resources,[R6]:b6.resources}:W56(Y6.mcp.resources,R6)}})),Z6(S6,{})}}else if(S6.request.subtype==="apply_flag_settings"){let R6=D5(),h6=IX6()??{},x6=S6.request.settings,b6={...h6,...x6};for(let Y6 of Object.keys(b6))if(b6[Y6]===null)delete b6[Y6];if(Ti8(b6),WX.notifyChange("flagSettings"),"model"in x6)if(x6.model!=null)YP(String(x6.model));else YP(void 0);let Q6=D5();if(Q6!==R6){p=Q6;let Y6=x6.model?String(x6.model):"default";_48({model:Q6}),C(Y6,Q6)}Z6(S6)}else if(S6.request.subtype==="get_settings"){let R6=O(),h6=D5(),x6=fL(h6)?yv6(h6,R6.effortValue):void 0;Z6(S6,{...gS7(),applied:{model:h6,effort:typeof x6==="string"?x6:null}})}else if(S6.request.subtype==="stop_task"){let{task_id:R6}=S6.request;try{await Pm8(R6,{getAppState:O,setAppState:w}),Z6(S6,{})}catch(h6){V6(S6,d6(h6))}}else if(S6.request.subtype==="generate_session_title"){let{description:R6,persist:h6}=S6.request,x6=(f&&!f.signal.aborted?f:P3()).signal;(async()=>{try{let b6=await h56(R6,x6);if(b6&&h6)try{Q97(N8(),b6)}catch(Q6){H6(Q6)}Z6(S6,{title:b6})}catch(b6){V6(S6,d6(b6))}})()}else if(S6.request.subtype==="side_question"){let{question:R6}=S6.request;(async()=>{try{let h6=X18(),x6=h6?{...h6,toolUseContext:{...h6.toolUseContext,abortController:P3()}}:await E75({tools:q6(O()),commands:a,mcpClients:[...O().mcp.clients,...g,...t.clients],messages:E,readFileState:S,getAppState:O,setAppState:w,customSystemPrompt:H.systemPrompt,appendSystemPrompt:H.appendSystemPrompt,thinkingConfig:H.thinkingConfig,agents:n}),b6=await Og8({question:R6,cacheSafeParams:x6});Z6(S6,{response:b6.response})}catch(h6){V6(S6,d6(h6))}})()}else if(S6.request.subtype==="remote_control")if(S6.request.enabled)if(e)Z6(S6,{session_url:MM(e.bridgeSessionId,e.sessionIngressUrl),connect_url:U46(e.environmentId,e.sessionIngressUrl),environment_id:e.environmentId});else{let R6;try{let{initReplBridge:h6}=await Promise.resolve().then(() => (Vz7(),kz7)),x6=await h6({onInboundMessage(b6){let Q6=tQ8(b6);if(!Q6)return;let{content:Y6,uuid:_6}=Q6;jM({value:Y6,mode:"prompt",uuid:_6,skipSlashCommands:!0}),f6()},onPermissionResponse(b6){q.injectControlResponse(b6)},onInterrupt(){f?.abort()},onSetModel(b6){let Q6=b6==="default"?If():b6;p=Q6,YP(Q6)},onSetMaxThinkingTokens(b6){if(b6===null)H.thinkingConfig=void 0;else if(b6===0)H.thinkingConfig={type:"disabled"};else H.thinkingConfig={type:"enabled",budgetTokens:b6}},onStateChange(b6,Q6){if(b6==="failed")R6=Q6;N(`[bridge:sdk] State change: ${b6}${Q6?` — ${Q6}`:""}`),G.enqueue({type:"system",subtype:"bridge_state",state:b6,detail:Q6,uuid:wW(),session_id:N8()})},initialMessages:E.length>0?E:void 0});if(!x6)V6(S6,R6??"Remote Control initialization failed");else e=x6,i=E.length,q.setOnControlRequestSent((b6)=>{x6.sendControlRequest(b6)}),q.setOnControlRequestResolved((b6)=>{x6.sendControlCancelRequest(b6)}),Z6(S6,{session_url:MM(x6.bridgeSessionId,x6.sessionIngressUrl),connect_url:U46(x6.environmentId,x6.sessionIngressUrl),environment_id:x6.environmentId})}catch(h6){V6(S6,d6(h6))}}else{if(e)q.setOnControlRequestSent(void 0),q.setOnControlRequestResolved(void 0),await e.teardown(),e=null;Z6(S6)}else V6(S6,`Unsupported control request subtype: ${S6.request.subtype}`);continue}else if(S6.type==="control_response"){if(H.replayUserMessages)G.enqueue(S6);continue}else if(S6.type==="keep_alive")continue;else if(S6.type==="update_environment_variables")continue;else if(S6.type==="assistant"||S6.type==="system"){let R6=JU8([S6]);if(E.push(...R6),S6.type==="assistant"&&H.replayUserMessages)G.enqueue(S6);continue}if(S6.type!=="user")continue;if(l6=!0,S6.uuid){let R6=N8(),h6=await l97(R6,S6.uuid);if(h6||Vl8.has(S6.uuid)){if(N(`Skipping duplicate user message: ${S6.uuid}`),H.replayUserMessages)N(`Sending acknowledgment for duplicate user message: ${S6.uuid}`),G.enqueue({type:"user",message:S6.message,session_id:R6,parent_tool_use_id:null,uuid:S6.uuid,timestamp:S6.timestamp,isReplay:!0});if(h6)jU(S6.uuid,"completed");continue}qaY(S6.uuid)}jM({mode:"prompt",value:await Nz7(S6,S6.message.content),uuid:S6.uuid,priority:S6.priority}),f6()}if(P=!0,N6?.stop(),!M){if(T.inflightPromise)await Promise.race([T.inflightPromise,R7(5000)]);T.abortController?.abort(),T.abortController=null,await P17(),J6(),v?.(),Xq6.delete(V),G.done()}})(),G}function o75(q){let K=async(_,z,Y,$,A,O)=>{let w=O??await uX(_,z,Y,$,A);if(w.behavior==="allow"||w.behavior==="deny")return w;let{signal:j,cleanup:H}=Ty(Y.abortController.signal);if(j.aborted)return H(),{behavior:"deny",message:"Permission prompt was aborted.",decisionReason:{type:"permissionPromptTool",permissionPromptToolName:_.name,toolResult:void 0}};let J=new Promise((D)=>{j.addEventListener("abort",()=>D("aborted"),{once:!0})}),M=q.call({tool_name:_.name,input:z,tool_use_id:A},Y,K,$),X=await Promise.race([M,J]);if(H(),X==="aborted"||j.aborted)return{behavior:"deny",message:"Permission prompt was aborted.",decisionReason:{type:"permissionPromptTool",permissionPromptToolName:_.name,toolResult:void 0}};let P=X,W=q.mapToolResultToToolResultBlockParam(P.data,"1");if(!W.content||!Array.isArray(W.content)||!W.content[0]||W.content[0].type!=="text"||typeof W.content[0].text!=="string")throw Error('Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.');return xC6(_K8().parse(m5(W.content[0].text)),q,z,Y)};return K}function a75(q,K,_,z){if(q==="stdio")return K.createCanUseTool(z);if(!q)return async($,A,O,w,j,H)=>H??await uX($,A,O,w,j);let Y=null;return async($,A,O,w,j,H)=>{if(!Y){let J=_(),M=J.find((X)=>g_(X,q));if(!M){let X=`Error: MCP tool ${q} (passed via --permission-prompt-tool) not found. Available MCP tools: ${J.map((P)=>P.name).join(", ")||"none"}`;throw process.stderr.write(`${X} |
| 16448 | `),eK(1),Error(X)}Y=o75(M)}return Y($,A,O,w,j,H)}}async function YaY(q,K,_,z,Y,$,A,O,w,j,H){if(_){z.enqueue({type:"control_response",response:{subtype:"error",error:"Already initialized",request_id:K,pending_permission_requests:A.getPendingPermissionRequests()}});return}if(q.systemPrompt!==void 0)w.systemPrompt=q.systemPrompt;if(q.appendSystemPrompt!==void 0)w.appendSystemPrompt=q.appendSystemPrompt;if(q.promptSuggestions!==void 0)w.promptSuggestions=q.promptSuggestions;if(q.agents){let D=oi6(q.agents,"flagSettings");j.push(...D)}if(w.agent){let D=qB()===w.agent,f=j.find((G)=>G.agentType===w.agent);if(f&&!D){if(vc(f.agentType),!w.systemPrompt&&!I2(f)){let G=f.getSystemPrompt();if(G)w.systemPrompt=G}if(!w.userSpecifiedModel&&f.model&&f.model!=="inherit"){let G=A5(f.model);YP(G)}if(f.initialPrompt)A.prependUserMessage(f.initialPrompt)}else if(f?.initialPrompt)A.prependUserMessage(f.initialPrompt)}let M=Z7()?.outputStyle||iv,X=await Dh6(Z8()),P=RG6();if(q.hooks){let D={};for(let[f,G]of Object.entries(q.hooks))D[f]=G.map((Z)=>{let T=Z.hookCallbackIds.map((v)=>{return A.createHookCallback(v,Z.timeout)});return{matcher:Z.matcher,hooks:T}});It(D)}if(q.jsonSchema)di8(q.jsonSchema);let W={commands:Y.filter((D)=>D.userInvocable!==!1).map((D)=>({name:W_(D),description:UH6(D),argumentHint:D.argumentHint||""})),agents:j.map((D)=>({name:D.agentType,description:D.whenToUse,model:D.model==="inherit"?void 0:D.model})),output_style:M,available_output_styles:Object.keys(X),models:$,account:{email:P?.email,organization:P?.organization,subscriptionType:P?.subscription,tokenSource:P?.tokenSource,apiKeySource:P?.apiKeySource,apiProvider:E7()},pid:process.pid};if(BK()&&oJ()){let D=H();W.fast_mode_state=II(w.userSpecifiedModel??null,D.fastMode)}if(z.enqueue({type:"control_response",response:{subtype:"success",request_id:K,response:W}}),O){let f=FW.getInstance().getStatus();if(f)z.enqueue({type:"auth_status",isAuthenticating:f.isAuthenticating,output:f.output,error:f.error,uuid:wW(),session_id:N8()})}}async function s75(q,K,_,z){if(!e$())return{canRewind:!1,error:"File rewinding is not enabled."};if(!Hx8(K.fileHistory,q))return{canRewind:!1,error:"No file checkpoint found for this message."};if(z){let Y=await $68(K.fileHistory,q);return{canRewind:!0,filesChanged:Y?.filesChanged,insertions:Y?.insertions,deletions:Y?.deletions}}try{await jx8((Y)=>_(($)=>({...$,fileHistory:Y($.fileHistory)})),q)}catch(Y){return{canRewind:!1,error:`Failed to rewind: ${d6(Y)}`}}return{canRewind:!0}}function $aY(q,K,_,z){if(q.mode==="bypassPermissions"){if(na())return z.enqueue({type:"control_response",response:{subtype:"error",request_id:K,error:"Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration"}}),_;if(!_.isBypassPermissionsModeAvailable)return z.enqueue({type:"control_response",response:{subtype:"error",request_id:K,error:"Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions"}}),_}if(q.mode==="auto"&&!Xy()){let Y=la();return z.enqueue({type:"control_response",response:{subtype:"error",request_id:K,error:Y?`Cannot set permission mode to auto: ${A56(Y)}`:"Cannot set permission mode to auto"}}),_}return z.enqueue({type:"control_response",response:{subtype:"success",request_id:K,response:{mode:q.mode}}}),{...ca(_.mode,q.mode,_),mode:q.mode}}function AaY(q,K,_,z){let Y=(X)=>z.enqueue({type:"control_response",response:{subtype:"error",request_id:q,error:X}}),$=_.find((X)=>X.name===K&&X.type==="connected");if(!$||$.type!=="connected")return Y(`server ${K} is not connected`);let A=$.config.pluginSource,O=A?Z4(A):void 0;if(!O?.marketplace)return Y(`server ${K} is not plugin-sourced; channel_enable requires a marketplace plugin`);let w={kind:"plugin",name:O.name,marketplace:O.marketplace},j=eH(),H=j.some((X)=>X.kind==="plugin"&&X.name===w.name&&X.marketplace===w.marketplace);if(!H)kc([...j,w]);let J=R78(K,$.capabilities,A);if(J.action==="skip"){if(!H)kc(j);return Y(J.reason)}let M=`${w.name}@${w.marketplace}`;C8(K,"Channel notifications registered"),d("tengu_mcp_channel_enable",{plugin:M}),$.client.setNotificationHandler(E78(),async(X)=>{let{content:P,meta:W}=X.params;C8(K,`notifications/claude/channel: ${P.slice(0,80)}`),d("tengu_mcp_channel_message",{content_length:P.length,meta_key_count:Object.keys(W??{}).length,entry_kind:"plugin",is_dev:!1,plugin:M}),jM({mode:"prompt",value:L78(K,P,W),priority:"next",isMeta:!0,origin:{kind:"channel",server:K},skipSlashCommands:!0})}),z.enqueue({type:"control_response",response:{subtype:"success",request_id:q,response:void 0}})}function iA7(q){if(q.type!=="connected")return;if(R78(q.name,q.capabilities,q.config.pluginSource).action!=="register")return;let _=dH6(q.name,eH()),z=_?.kind==="plugin"?`${_.name}@${_.marketplace}`:void 0;C8(q.name,"Channel notifications re-registered after reconnect"),q.client.setNotificationHandler(E78(),async(Y)=>{let{content:$,meta:A}=Y.params;C8(q.name,`notifications/claude/channel: ${$.slice(0,80)}`),d("tengu_mcp_channel_message",{content_length:$.length,meta_key_count:Object.keys(A??{}).length,entry_kind:_?.kind,is_dev:_?.dev??!1,plugin:z}),jM({mode:"prompt",value:L78(q.name,$,A),priority:"next",isMeta:!0,origin:{kind:"channel",server:q.name},skipSlashCommands:!0})})}function kl8(q,K){if(K==="stream-json"){let _={type:"result",subtype:"error_during_execution",duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:N8(),total_cost_usd:0,usage:n0,modelUsage:{},permission_denials:[],uuid:wW(),errors:[q]};process.stdout.write(g6(_)+` |