import{G as e,U as t,k as n}from"../../paths-DBmKCtUs.js";import{c as r}from"../../paths-CChBdtE8.js";import{t as i}from"../../subsystem-hyY_8Y33.js";import{H as a,Q as o,R as s}from"../../workspace-Dc-i8PF7.js";import"../../utils-HgCTSfjA.js";import{Tn as c}from"../../model-selection-BDkm-Fer.js";import"../../github-copilot-token-DePP-lIf.js";import"../../boolean-DypnRoRK.js";import"../../proxy-env-BWBLvN-u.js";import"../../frontmatter-DWwQ2Ef1.js";import"../../logger-Cb-sKDne.js";import"../../send-C8A14jM5.js";import"../../send-DJQkChGb.js";import"../../pi-embedded-CrmNQ_Cj.js";import"../../tokens-BYXU3z3M.js";import"../../deliver-CfDssPIx.js";import"../../diagnostic-BLPiUEBS.js";import"../../send-CJY5c6qr.js";import"../../pi-model-discovery-BJumnCnW.js";import"../../image-BRyK9As_.js";import"../../audio-transcription-runner-hFq0JYz3.js";import"../../fetch-CeRf3vRn.js";import"../../fetch-guard-ag8y9zvK.js";import"../../api-key-rotation-CtnQP1Xf.js";import"../../proxy-fetch-BJmmcDWW.js";import"../../ir-Cvv5XLLr.js";import"../../render-CBsnn-2A.js";import"../../target-errors-BLmHIqmS.js";import"../../commands-registry-BMp2dhwV.js";import"../../fetch-_g8lZ8K8.js";import"../../skill-commands-BTSeGUD5.js";import"../../channel-activity-Be1YqKEM.js";import"../../tables-DnqgRgZi.js";import"../../send-BcsfxQVr2.js";import"../../outbound-attachment-DUg_yKsu.js";import"../../send-De2DLShl.js";import"../../fetch-BBL4TFBl.js";import"../../query-expansion-CC3GwLhd.js";import"../../manager-BRhhB_kG.js";import{generateSlugViaLLM as l}from"../../llm-slug-generator.js";import{t as u}from"../../config-BqW5S1xL.js";import d from"node:fs/promises";import f from"node:os";import p from"node:path";const m=i(`hooks/session-memory`);function h(e){if(!e.cfg||!e.workspaceDir)return e.sessionKey;let n=t(e.cfg,e.workspaceDir),r=o(e.sessionKey);return!n||!r||n===r.agentId?e.sessionKey:a({agentId:n,requestKey:r.rest})}async function g(e,t=15){try{let n=(await d.readFile(e,`utf-8`)).trim().split(`
`),r=[];for(let e of n)try{let t=JSON.parse(e);if(t.type===`message`&&t.message){let e=t.message,n=e.role;if((n===`user`||n===`assistant`)&&e.content){if(n===`user`&&c(e))continue;let t=Array.isArray(e.content)?e.content.find(e=>e.type===`text`)?.text:e.content;t&&!t.startsWith(`/`)&&r.push(`${n}: ${t}`)}}}catch{}return r.slice(-t).join(`
`)}catch{return null}}async function _(e,t=15){let n=await g(e,t);if(n)return n;try{let r=p.dirname(e),i=`${p.basename(e)}.reset.`,a=(await d.readdir(r)).filter(e=>e.startsWith(i)).toSorted();if(a.length===0)return n;let o=p.join(r,a[a.length-1]),s=await g(o,t);return s&&m.debug(`Loaded session content from reset fallback`,{sessionFilePath:e,latestResetPath:o}),s||n}catch{return n}}function v(e){let t=e.indexOf(`.reset.`);return t===-1?e:e.slice(0,t)}async function y(e){try{let t=await d.readdir(e.sessionsDir),n=new Set(t),r=e.currentSessionFile?v(p.basename(e.currentSessionFile)):void 0;if(r&&n.has(r))return p.join(e.sessionsDir,r);let i=e.sessionId?.trim();if(i){let r=`${i}.jsonl`;if(n.has(r))return p.join(e.sessionsDir,r);let a=t.filter(e=>e.startsWith(`${i}-topic-`)&&e.endsWith(`.jsonl`)&&!e.includes(`.reset.`)).toSorted().toReversed();if(a.length>0)return p.join(e.sessionsDir,a[0])}if(!e.currentSessionFile)return;let a=t.filter(e=>e.endsWith(`.jsonl`)&&!e.includes(`.reset.`)).toSorted().toReversed();if(a.length>0)return p.join(e.sessionsDir,a[0])}catch{}}const b=async t=>{let i=t.action===`new`||t.action===`reset`;if(!(t.type!==`command`||!i))try{m.debug(`Hook triggered for reset/new command`,{action:t.action});let i=t.context||{},a=i.cfg,o=typeof i.workspaceDir==`string`&&i.workspaceDir.trim().length>0?i.workspaceDir:void 0,c=s(t.sessionKey),g=o||(a?e(a,c):p.join(r(process.env,f.homedir),`workspace`)),v=h({cfg:a,workspaceDir:o,sessionKey:t.sessionKey}),b=p.join(g,`memory`);await d.mkdir(b,{recursive:!0});let x=new Date(t.timestamp),S=x.toISOString().split(`T`)[0],C=i.previousSessionEntry||i.sessionEntry||{},w=C.sessionId,T=C.sessionFile||void 0;if(!T||T.includes(`.reset.`)){let e=new Set;T&&e.add(p.dirname(T)),e.add(p.join(g,`sessions`));for(let t of e){let e=await y({sessionsDir:t,currentSessionFile:T,sessionId:w});if(e){T=e,m.debug(`Found previous session file`,{file:T});break}}}m.debug(`Session context resolved`,{sessionId:w,sessionFile:T,hasCfg:!!a});let E=T||void 0,D=u(a,`session-memory`),O=typeof D?.messages==`number`&&D.messages>0?D.messages:15,k=null,A=null;if(E){A=await _(E,O),m.debug(`Session content loaded`,{length:A?.length??0,messageCount:O});let e=!(process.env.OPENCLAW_TEST_FAST===`1`||process.env.VITEST===`true`||process.env.VITEST===`1`)&&D?.llmSlug!==!1;A&&a&&e&&(m.debug(`Calling generateSlugViaLLM...`),k=await l({sessionContent:A,cfg:a}),m.debug(`Generated slug`,{slug:k}))}k||(k=x.toISOString().split(`T`)[1].split(`.`)[0].replace(/:/g,``).slice(0,4),m.debug(`Using fallback timestamp slug`,{slug:k}));let j=`${S}-${k}.md`,M=p.join(b,j);m.debug(`Memory file path resolved`,{filename:j,path:M.replace(f.homedir(),`~`)});let N=x.toISOString().split(`T`)[1].split(`.`)[0],P=C.sessionId||`unknown`,F=i.commandSource||`unknown`,I=[`# Session: ${S} ${N} UTC`,``,`- **Session Key**: ${v}`,`- **Session ID**: ${P}`,`- **Source**: ${F}`,``];A&&I.push(`## Conversation Summary`,``,A,``),await n({rootDir:b,relativePath:j,data:I.join(`
`),encoding:`utf-8`}),m.debug(`Memory file written successfully`);let L=M.replace(f.homedir(),`~`);m.info(`Session context saved to ${L}`)}catch(e){e instanceof Error?m.error(`Failed to save session memory`,{errorName:e.name,errorMessage:e.message,stack:e.stack}):m.error(`Failed to save session memory`,{error:String(e)})}};export{b as default};
