import{n as e}from"./chunk-DR8-3Aex.js";import{Ct as t,cn as n,ot as r}from"./state-sIHsFpDu.js";import{E as i,O as a}from"./debug-otxXY3j-.js";import{n as o,r as s}from"./analytics-DqMQntaB.js";import{c,s as l}from"./types-KeqFPzY5.js";import{i as u,o as d}from"./stringUtils-KZoO4GUd.js";import{Ar as f,Fr as p,Oi as m,Si as h,Tr as g,Vr as _,jr as v}from"./loadAgentsDir-C_wFhytF.js";import{randomUUID as y}from"crypto";import{mkdir as b,readFile as x,writeFile as S}from"fs/promises";function C(e){let t=e?.message?.content;if(!t)return`Branched conversation`;let n=typeof t==`string`?t:t.find(e=>e.type===`text`)?.text;return n&&n.replace(/\s+/g,` `).trim().slice(0,100)||`Branched conversation`}async function w(e){let n=y(),i=t(),o=g(r()),s=v(n),l=f();await b(o,{recursive:!0,mode:448});let u;try{u=await x(l)}catch{throw Error(`No conversation to branch`)}if(u.length===0)throw Error(`No conversation to branch`);let d=c(u),p=d.filter(e=>_(e)&&!e.isSidechain),m=d.filter(e=>e.type===`content-replacement`&&e.sessionId===i).flatMap(e=>e.replacements);if(p.length===0)throw Error(`No messages to branch`);let h=null,C=[],w=[];for(let e of p){let t={...e,sessionId:n,parentUuid:h,isSidechain:!1,forkedFrom:{sessionId:i,messageUuid:e.uuid}},r={...e,sessionId:n};w.push(r),C.push(a(t)),e.type!==`progress`&&(h=e.uuid)}if(m.length>0){let e={type:`content-replacement`,sessionId:n,replacements:m};C.push(a(e))}return await S(s,C.join(`
`)+`
`,{encoding:`utf8`,mode:384}),{sessionId:n,title:e,forkPath:s,serializedMessages:w,contentReplacementRecords:m}}async function T(e){let t=`${e} (Branch)`;if((await m(t,{exact:!0})).length===0)return t;let n=await m(`${e} (Branch`),r=new Set([1]),i=RegExp(`^${u(e)} \\(Branch(?: (\\d+))?\\)$`);for(let e of n){let t=e.customTitle?.match(i);t&&(t[1]?r.add(parseInt(t[1],10)):r.add(1))}let a=2;for(;r.has(a);)a++;return`${e} (Branch ${a})`}async function E(e,n,r){let i=r?.trim()||void 0,a=t();try{let{sessionId:t,title:r,forkPath:o,serializedMessages:c,contentReplacementRecords:l}=await w(i),u=new Date,d=C(c.find(e=>e.type===`user`)),f=await T(r??d);await h(t,f,o),s(`tengu_conversation_forked`,{message_count:c.length,has_custom_title:!!r});let p={date:u.toISOString().split(`T`)[0],messages:c,fullPath:o,value:u.getTime(),created:u,modified:u,firstPrompt:d,messageCount:c.length,isSidechain:!1,sessionId:t,customTitle:f,contentReplacements:l},m=r?` "${r}"`:``,g=`Branched conversation${m}. You are now in the branch.${`\nTo resume the original: claude -r ${a}`}`;return n.resume?(await n.resume(t,p,`fork`),e(g,{display:`system`})):e(`Branched conversation${m}. Resume with: /resume ${t}`),null}catch(t){return e(`Failed to branch conversation: ${t instanceof Error?t.message:`Unknown error occurred`}`),null}}e((()=>{n(),o(),l(),p(),i(),d()}))();export{E as call,C as deriveFirstPrompt};