@lucasschirm/devin-session-sync 0.1.1 → 0.1.2

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/bin/hook CHANGED
@@ -119,10 +119,11 @@ Configuration is resolved in precedence order (highest first):
119
119
  Security: SAL_STORAGE_ENDPOINT, SAL_STORAGE_ACCESS_KEY_ID, and
120
120
  SAL_STORAGE_SECRET_ACCESS_KEY are only read from process.env or
121
121
  .devin/config.local.json \u2014 never from a file that might be committed to git.
122
- `;function hRe(e,t){return{local:OO.join(e,".devin","config.local.json"),project:OO.join(e,".devin","config.json"),userGlobal:OO.join(t,".config","devin","config.json")}}var pf={profile:Us,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:hRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:Us.harness,helpText:mRe};function p_(e,t=gRe.cwd()){return f_(pf,e,t)}import r7 from"node:process";async function m_(e=r7.cwd(),t=r7.env,r=pf.profile.securityBlocklist){return uu(pf,e,t,r)}import SRe from"node:process";var n7={SessionStart:"session-start",Stop:"stop",PostCompaction:"post-compact",SessionEnd:"session-end"};function s7(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,missing:["session_id"],raw:e};let t=e,r=t.session_id;return typeof r!="string"||r.trim()===""?{ok:!1,missing:["session_id"],raw:e}:{ok:!0,input:t}}function o7(e,t=SRe.cwd()){return{harness:TO,sessionId:e.session_id,cwd:typeof e.cwd=="string"&&e.cwd.trim()!==""?e.cwd:t,startedAt:e.started_at,endedAt:e.ended_at,endReason:e.reason,model:e.model}}function i7(e){return e&&e in n7?n7[e]:"manual"}import _be from"node:process";import HRe from"node:os";import C7 from"node:process";import{existsSync as yRe}from"node:fs";import{join as aa}from"node:path";function ERe(e){return[{label:"home-devin",path:aa(e.home,".devin")},{label:"home-devin-shared",path:aa(e.home,".devin-shared")},{label:"home-codeium",path:aa(e.home,".codeium")},{label:"home-windsurf",path:aa(e.home,".windsurf")},{label:"project-devin",path:aa(e.cwd,".devin")},{label:"project-windsurf",path:aa(e.cwd,".windsurf")}]}function h_(e,t=yRe){let r=lf(e),n=ERe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:aa(r,"sessions.db"),probes:n}}import{createHash as ARe}from"node:crypto";import{copyFileSync as bRe,existsSync as xRe,mkdtempSync as TRe,rmSync as ORe}from"node:fs";import{tmpdir as vRe}from"node:os";import{basename as IRe,join as h7}from"node:path";import{createHash as _Re}from"node:crypto";function a7(e){return`${e.session_id}\0${e.node_id}`}function c7(e){let{row_id:t,created_at:r,...n}=e;return _Re("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[a7(r)]!==c7(r))}function S_(e,t){let r={...e};for(let n of t)r[a7(n)]=c7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},u7=["sessions","message_nodes","prompt_history"];function vO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:CRe(e)}function CRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${u7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...u7],warnings:r}}function d7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as wRe}from"node:crypto";function l7(e){return wRe("sha256").update(JSON.stringify(e)).digest("hex")}function f7(e,t){return e.filter(r=>t[r.id]!==l7(r))}function E_(e,t){let r={...e};for(let n of t)r[n.id]=l7(n);return r}import{createHash as RRe}from"node:crypto";function p7(e){return`${e.session_id}\0${e.tool_call_id}`}function m7(e){let{row_id:t,...r}=e;return RRe("sha256").update(JSON.stringify(r)).digest("hex")}function __(e,t){return e.filter(r=>t[p7(r)]!==m7(r))}function C_(e,t){let r={...e};for(let n of t)r[p7(n)]=m7(n);return r}var w_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},g7=()=>import("node:sqlite");async function kRe(e=g7){let t;try{t=await e()}catch(r){throw new w_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new w_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function S7(e,t=g7){let{DatabaseSync:r}=await kRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return PRe(e,r,n)}}function PRe(e,t,r){try{return DRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function DRe(e,t){let r=TRe(h7(vRe(),"devin-session-sync-snapshot-")),n=h7(r,IRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;xRe(i)&&bRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),ORe(r,{recursive:!0,force:!0})}}}function y7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function R_(e,t,r=[]){return e.prepare(t).all(...r)}function NRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=R_(e,"SELECT * FROM sessions ORDER BY id");return f7(n,r)}function MRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(R_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function LRe(e,t,r){return t.knownTables.includes("prompt_history")?R_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function $Re(e,t,r){return t.knownTables.includes("tool_call_state")?__(R_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function BRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function FRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?ARe("sha256").update(r.sql).digest("hex"):null}function URe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function jRe(e,t){let r=[];for(let n of t){let s=d7(n,URe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function E7(e,t=null){let r=vO(y7(e)),n={};for(let s of Object.keys(y_))n[s]=FRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:BRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...jRe(e,r.knownTables)]}}function _7(e,t){let r=vO(y7(e));return{tables:{sessions:NRe(e,r,t.sessionsContentHashes),messageNodes:MRe(e,r,t.messageNodesContentHashes),promptHistory:LRe(e,r,t.promptHistoryId),toolCallStates:$Re(e,r,t.toolCallStateHashes)},schema:r}}var go={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function GRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??C7.env,r=e.home??HRe.homedir(),n=e.cwd??C7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function w7(e={}){let t=GRe(e),r=e.devinCliVersion??ff(),{db:n,close:s}=await S7(t);try{let{tables:o}=_7(n,go),i=E7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as js from"node:fs/promises";import XAe from"node:os";import Sf from"node:path";import QAe from"node:process";var A7="sal/synthetic_subagent_kind",qRe="sal/synthetic_subagent_rawinput_profile",zRe="sal/synthetic_subagent_tool_call_id",VRe="sal/synthetic_subagent_source_node_id",WRe="sal/synthetic_subagent_is_background";function mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A_(e){if(!e)return null;try{let t=JSON.parse(e);return mf(t)?t:null}catch{return null}}function KRe(e){let t=e._meta;if(!mf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function YRe(e){let t=[];for(let r of e){let n=A_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||KRe(n)!=="run_subagent")continue;let s=mf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function b7(e){let t=A_(e);if(!t)return null;let r=t.metadata;if(!mf(r))return null;let n=r.extensions;return mf(n)?n:null}function IO(e){let t=A_(e);return t&&typeof t.content=="string"?t.content:null}function JRe(e){let t=A_(e);return t&&typeof t.role=="string"?t.role:null}function XRe(e,t){return e?.includes(JSON.stringify(t))??!1}function QRe(e){let t=[];for(let r of e){let s=b7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var ZRe="Background subagent started";function eAe(e,t){let r=e.find(s=>{if(JRe(s.chat_message)!=="system")return!1;let o=IO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=IO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=IO(t.node.chat_message);return n===null||n.startsWith(ZRe)?null:{node:t.node,content:n,isBackground:!1}}function tAe(e){return b7(e)??{}}function x7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var R7=Number.MAX_SAFE_INTEGER;function rAe(e,t){let r=QRe(e),n=[];for(let s of YRe(t)){if(s.task===null)continue;let o=r.find(i=>XRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function nAe(e,t){return x7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[A7]:"prompt",[qRe]:e.invocation.profile,[zRe]:e.invocation.toolCallId})}function sAe(e,t,r,n){let s=eAe(e,t.tagged);return s===null?null:x7(t.tagged.node,r,n,"assistant",s.content,tAe(t.tagged.node.chat_message),{[A7]:"result",[VRe]:s.node.node_id,[WRe]:s.isBackground})}function T7(e,t){let r=[];for(let n of rAe(e,t)){let s=R7-n.tagged.node.node_id*2,o=R7-n.tagged.node.node_id*2-1;r.push(nAe(n,s));let i=sAe(e,n,o,s);i&&r.push(i)}return r}function O7(e,t={}){let r=new Map(e.sessions.map(f=>[f.id,f])),n=hf(e.messageNodes,f=>f.session_id),s=hf(e.promptHistory,f=>f.session_id),o=hf(e.toolCallStates,f=>f.session_id),i=oAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let f of aAe(e))a=cAe(c,a,r.get(f),{nodes:n.get(f)??[],prompts:s.get(f)??[],toolCalls:o.get(f)??[]},iAe(i,f));let u=t.priorWatermarks??go;return{lines:c,text:_Ae(c),watermarks:yAe(e,u)}}function oAe(e){if(e)return{nodesBySession:hf(e.messageNodes,t=>t.session_id),toolCallsBySession:hf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function iAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function aAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function cAe(e,t,r,n,s){let o=t;return r&&(e.push(gAe(r,o)),o+=1),o=pAe(e,o,n.nodes,n.toolCalls),o=uAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=hAe(e,o,n.prompts),o}function uAe(e,t,r,n,s){let o=t;for(let i of T7(r,n))s?.has(i.node_id)||(e.push(v7(i,o)),o+=1);return o}function dAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function lAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&fAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function fAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function pAe(e,t,r,n){let s=t,o=new Set;for(let i of dAe(r)){e.push(v7(i,s)),s+=1;for(let a of lAe(i,n,o))e.push(I7(a,s)),s+=1}return s=mAe(e,s,n,o),s}function mAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(I7(i,s)),s+=1;return s}function hAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(SAe(s,n)),n+=1;return n}function gAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function v7(e,t){return{type:"message",ts:null,order:t,...e}}function I7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function SAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function hf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function yAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:C_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:EAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:E_(t.sessionsContentHashes,e.sessions)}}function EAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function _Ae(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
122
+ `;function hRe(e,t){return{local:OO.join(e,".devin","config.local.json"),project:OO.join(e,".devin","config.json"),userGlobal:OO.join(t,".config","devin","config.json")}}var pf={profile:Us,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:hRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:Us.harness,helpText:mRe};function p_(e,t=gRe.cwd()){return f_(pf,e,t)}import r7 from"node:process";async function m_(e=r7.cwd(),t=r7.env,r=pf.profile.securityBlocklist){return uu(pf,e,t,r)}import SRe from"node:process";var n7={SessionStart:"session-start",Stop:"stop",PostCompaction:"post-compact",SessionEnd:"session-end"};function s7(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,missing:["session_id"],raw:e};let t=e,r=t.session_id;return typeof r!="string"||r.trim()===""?{ok:!1,missing:["session_id"],raw:e}:{ok:!0,input:t}}function o7(e,t=SRe.cwd()){return{harness:TO,sessionId:e.session_id,cwd:typeof e.cwd=="string"&&e.cwd.trim()!==""?e.cwd:t,startedAt:e.started_at,endedAt:e.ended_at,endReason:e.reason,model:e.model}}function i7(e){return e&&e in n7?n7[e]:"manual"}import _be from"node:process";import HRe from"node:os";import C7 from"node:process";import{existsSync as yRe}from"node:fs";import{join as aa}from"node:path";function ERe(e){return[{label:"home-devin",path:aa(e.home,".devin")},{label:"home-devin-shared",path:aa(e.home,".devin-shared")},{label:"home-codeium",path:aa(e.home,".codeium")},{label:"home-windsurf",path:aa(e.home,".windsurf")},{label:"project-devin",path:aa(e.cwd,".devin")},{label:"project-windsurf",path:aa(e.cwd,".windsurf")}]}function h_(e,t=yRe){let r=lf(e),n=ERe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:aa(r,"sessions.db"),probes:n}}import{createHash as ARe}from"node:crypto";import{copyFileSync as bRe,existsSync as xRe,mkdtempSync as TRe,rmSync as ORe}from"node:fs";import{tmpdir as vRe}from"node:os";import{basename as IRe,join as h7}from"node:path";import{createHash as _Re}from"node:crypto";function a7(e){return`${e.session_id}\0${e.node_id}`}function c7(e){let{row_id:t,created_at:r,...n}=e;return _Re("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[a7(r)]!==c7(r))}function S_(e,t){let r={...e};for(let n of t)r[a7(n)]=c7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},u7=["sessions","message_nodes","prompt_history"];function vO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:CRe(e)}function CRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${u7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...u7],warnings:r}}function d7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as wRe}from"node:crypto";function l7(e){return wRe("sha256").update(JSON.stringify(e)).digest("hex")}function f7(e,t){return e.filter(r=>t[r.id]!==l7(r))}function E_(e,t){let r={...e};for(let n of t)r[n.id]=l7(n);return r}import{createHash as RRe}from"node:crypto";function p7(e){return`${e.session_id}\0${e.tool_call_id}`}function m7(e){let{row_id:t,...r}=e;return RRe("sha256").update(JSON.stringify(r)).digest("hex")}function __(e,t){return e.filter(r=>t[p7(r)]!==m7(r))}function C_(e,t){let r={...e};for(let n of t)r[p7(n)]=m7(n);return r}var w_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},g7=()=>import("node:sqlite");async function kRe(e=g7){let t;try{t=await e()}catch(r){throw new w_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new w_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function S7(e,t=g7){let{DatabaseSync:r}=await kRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return PRe(e,r,n)}}function PRe(e,t,r){try{return DRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function DRe(e,t){let r=TRe(h7(vRe(),"devin-session-sync-snapshot-")),n=h7(r,IRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;xRe(i)&&bRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),ORe(r,{recursive:!0,force:!0})}}}function y7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function R_(e,t,r=[]){return e.prepare(t).all(...r)}function NRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=R_(e,"SELECT * FROM sessions ORDER BY id");return f7(n,r)}function MRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(R_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function LRe(e,t,r){return t.knownTables.includes("prompt_history")?R_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function $Re(e,t,r){return t.knownTables.includes("tool_call_state")?__(R_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function BRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function FRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?ARe("sha256").update(r.sql).digest("hex"):null}function URe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function jRe(e,t){let r=[];for(let n of t){let s=d7(n,URe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function E7(e,t=null){let r=vO(y7(e)),n={};for(let s of Object.keys(y_))n[s]=FRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:BRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...jRe(e,r.knownTables)]}}function _7(e,t){let r=vO(y7(e));return{tables:{sessions:NRe(e,r,t.sessionsContentHashes),messageNodes:MRe(e,r,t.messageNodesContentHashes),promptHistory:LRe(e,r,t.promptHistoryId),toolCallStates:$Re(e,r,t.toolCallStateHashes)},schema:r}}var go={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function GRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??C7.env,r=e.home??HRe.homedir(),n=e.cwd??C7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function w7(e={}){let t=GRe(e),r=e.devinCliVersion??ff(),{db:n,close:s}=await S7(t);try{let{tables:o}=_7(n,go),i=E7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as js from"node:fs/promises";import XAe from"node:os";import Sf from"node:path";import QAe from"node:process";var A7="sal/synthetic_subagent_kind",qRe="sal/synthetic_subagent_rawinput_profile",zRe="sal/synthetic_subagent_tool_call_id",VRe="sal/synthetic_subagent_source_node_id",WRe="sal/synthetic_subagent_is_background";function mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A_(e){if(!e)return null;try{let t=JSON.parse(e);return mf(t)?t:null}catch{return null}}function KRe(e){let t=e._meta;if(!mf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function YRe(e){let t=[];for(let r of e){let n=A_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||KRe(n)!=="run_subagent")continue;let s=mf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function b7(e){let t=A_(e);if(!t)return null;let r=t.metadata;if(!mf(r))return null;let n=r.extensions;return mf(n)?n:null}function IO(e){let t=A_(e);return t&&typeof t.content=="string"?t.content:null}function JRe(e){let t=A_(e);return t&&typeof t.role=="string"?t.role:null}function XRe(e,t){return e?.includes(JSON.stringify(t))??!1}function QRe(e){let t=[];for(let r of e){let s=b7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var ZRe="Background subagent started";function eAe(e,t){let r=e.find(s=>{if(JRe(s.chat_message)!=="system")return!1;let o=IO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=IO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=IO(t.node.chat_message);return n===null||n.startsWith(ZRe)?null:{node:t.node,content:n,isBackground:!1}}function tAe(e){return b7(e)??{}}function x7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var R7=Number.MAX_SAFE_INTEGER;function rAe(e,t){let r=QRe(e),n=[];for(let s of YRe(t)){if(s.task===null)continue;let o=r.find(i=>XRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function nAe(e,t){return x7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[A7]:"prompt",[qRe]:e.invocation.profile,[zRe]:e.invocation.toolCallId})}function sAe(e,t,r,n){let s=eAe(e,t.tagged);return s===null?null:x7(t.tagged.node,r,n,"assistant",s.content,tAe(t.tagged.node.chat_message),{[A7]:"result",[VRe]:s.node.node_id,[WRe]:s.isBackground})}function T7(e,t){let r=[];for(let n of rAe(e,t)){let s=R7-n.tagged.node.node_id*2,o=R7-n.tagged.node.node_id*2-1;r.push(nAe(n,s));let i=sAe(e,n,o,s);i&&r.push(i)}return r}function O7(e,t={}){let r=new Map(e.sessions.map(h=>[h.id,h])),n=hf(e.messageNodes,h=>h.session_id),s=hf(e.promptHistory,h=>h.session_id),o=hf(e.toolCallStates,h=>h.session_id),i=oAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let h of aAe(e))a=cAe(c,a,r.get(h),{nodes:n.get(h)??[],prompts:s.get(h)??[],toolCalls:o.get(h)??[]},iAe(i,h));let u=t.priorWatermarks??go,f=t.skipText?"":_Ae(c);return{lines:c,text:f,watermarks:yAe(e,u)}}function oAe(e){if(e)return{nodesBySession:hf(e.messageNodes,t=>t.session_id),toolCallsBySession:hf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function iAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function aAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function cAe(e,t,r,n,s){let o=t;return r&&(e.push(gAe(r,o)),o+=1),o=pAe(e,o,n.nodes,n.toolCalls),o=uAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=hAe(e,o,n.prompts),o}function uAe(e,t,r,n,s){let o=t;for(let i of T7(r,n))s?.has(i.node_id)||(e.push(v7(i,o)),o+=1);return o}function dAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function lAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&fAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function fAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function pAe(e,t,r,n){let s=t,o=new Set;for(let i of dAe(r)){e.push(v7(i,s)),s+=1;for(let a of lAe(i,n,o))e.push(I7(a,s)),s+=1}return s=mAe(e,s,n,o),s}function mAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(I7(i,s)),s+=1;return s}function hAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(SAe(s,n)),n+=1;return n}function gAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function v7(e,t){return{type:"message",ts:null,order:t,...e}}function I7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function SAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function hf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function yAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:C_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:EAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:E_(t.sessionsContentHashes,e.sessions)}}function EAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function _Ae(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
123
123
  `)}
124
124
  `}function k7(e){let t=e.split(`
125
- `).filter(n=>n.length>0),r=t.map(wAe).filter(RAe);return r.length===0?{watermarks:go,lineCount:0,messageNodeIds:new Set}:{watermarks:PAe(r),lineCount:t.length,messageNodeIds:CAe(r)}}function CAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function wAe(e){try{return JSON.parse(e)}catch{return}}function RAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kO(e){let{type:t,ts:r,order:n,...s}=e;return s}function AAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function bAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function xAe(e){return typeof e.id=="string"}function TAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function OAe(e,t){let r=kO(t);return bAe(r)?{...e,toolCallStateHashes:C_(e.toolCallStateHashes,[r])}:e}function vAe(e,t){let r=kO(t);return xAe(r)?{...e,sessionsContentHashes:E_(e.sessionsContentHashes,[r])}:e}function IAe(e,t){let r=kO(t);return TAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function kAe(e,t){switch(t.type){case"message":return IAe(e,t);case"prompt":return{...e,promptHistoryId:AAe(e.promptHistoryId,t.id)};case"tool_call":return OAe(e,t);case"session":return vAe(e,t);default:return e}}function PAe(e){let t=go;for(let r of e)t=kAe(t,r);return t}import{execFile as UAe}from"node:child_process";import*as L7 from"node:fs/promises";import $7 from"node:path";import{promisify as jAe}from"node:util";function D7(e){try{let t=JSON.parse(e);return DAe(t)?t.families.flatMap(r=>MAe(r)):[]}catch{return[]}}function DAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function NAe(e){return N7(e)&&Array.isArray(e.variants)}function MAe(e){return NAe(e)?e.variants.filter(t=>N7(t)).map(t=>LAe(e,t)):[]}function LAe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:P7(t.max_context_tokens),maxOutputTokens:P7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=$Ae(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function N7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function P7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $Ae(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=BAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function BAe(e){let t=PO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=PO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=PO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function PO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${FAe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function FAe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var HAe=jAe(UAe),GAe=1,qAe=9e5;async function DO(e){let t=e.dataDir,r=zAe(t),n=VAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??qAe,i=e.devinCliVersion??WAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await YAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??KAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function B7(e){let t=await DO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=D7(t.raw);return{candidates:[M7(e,"native/models-list.raw.json",t.raw),M7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function zAe(e){return $7.join(e,"devin","models-cache.json")}function VAe(e){return $7.join(e,"devin","models-cache.lock")}function WAe(e){return e.resolveVersion?e.resolveVersion():ff()}async function KAe(){let{stdout:e}=await HAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function YAe(e){try{let t=await L7.readFile(e,"utf8"),r=JSON.parse(t);if(JAe(r))return r}catch(t){let r=t.code}return{version:GAe,entries:{}}}function JAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function M7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function ZAe(e){return e.failed>0||e.errors.length>0}function gf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function ebe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function tbe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function rbe(e){try{return await js.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function nbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:__(e.toolCallStates,t.toolCallStateHashes)}}async function sbe(e,t,r){let n=Sf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>obe(e,t,n))}async function obe(e,t,r){let n=tbe(e,t),s=await rbe(r),o=s?k7(s):{watermarks:go,lineCount:0,messageNodeIds:new Set},i=nbe(n,o.watermarks),{text:a}=O7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});return await js.mkdir(Sf.dirname(r),{recursive:!0}),await js.appendFile(r,a,"utf8"),r}function F7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function ibe(e){let t=e.artifacts.filter(s=>F7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!F7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function abe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function cbe(e){let t;try{t=await js.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await js.readFile(Sf.join(e,n),"utf8")})}catch{}return r}async function ube(e,t,r){return(await cbe(Sf.join(e,".devin","plans"))).filter(o=>abe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function dbe(e,t,r){let n=Sf.join(e,"transcripts",`${t}.json`),s;try{s=await js.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function lbe(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function fbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??QAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function pbe(e,t,r){let n=await _u({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return ibe(n)}async function mbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await ube(r,e.sessionId,o),c=await dbe(n,e.sessionId,o),u=lbe(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function hbe(e,t){let r=await B7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&gf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function gbe(e,t){return JSON.stringify([e,t])}async function Sbe(e,t,r){let n=gbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function ybe(e,t,r,n){let s=[...r.errors];try{await au({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=cu(o);s.includes(i)||s.push(i)}return s}async function Ebe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await Sbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts})),c=iu(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await ybe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function U7(e){let t=e.profile??Us,r=e.homeDir??XAe.homedir(),n=fbe(e,r);gf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await sbe(e.tables,e.sessionId,e.dataDir);gf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await pbe(e,t,s),{candidates:i,error:a}=await hbe(e,t),c=await mbe(e,o,r,n,i);gf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Ebe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),gf(e,ZAe(u)?"failure":"success",ebe(u)),u}function Cbe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
125
+ `).filter(n=>n.length>0),r=t.map(wAe).filter(RAe);return r.length===0?{watermarks:go,lineCount:0,messageNodeIds:new Set}:{watermarks:PAe(r),lineCount:t.length,messageNodeIds:CAe(r)}}function CAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function wAe(e){try{return JSON.parse(e)}catch{return}}function RAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kO(e){let{type:t,ts:r,order:n,...s}=e;return s}function AAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function bAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function xAe(e){return typeof e.id=="string"}function TAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function OAe(e,t){let r=kO(t);return bAe(r)?{...e,toolCallStateHashes:C_(e.toolCallStateHashes,[r])}:e}function vAe(e,t){let r=kO(t);return xAe(r)?{...e,sessionsContentHashes:E_(e.sessionsContentHashes,[r])}:e}function IAe(e,t){let r=kO(t);return TAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function kAe(e,t){switch(t.type){case"message":return IAe(e,t);case"prompt":return{...e,promptHistoryId:AAe(e.promptHistoryId,t.id)};case"tool_call":return OAe(e,t);case"session":return vAe(e,t);default:return e}}function PAe(e){let t=go;for(let r of e)t=kAe(t,r);return t}import{execFile as UAe}from"node:child_process";import*as L7 from"node:fs/promises";import $7 from"node:path";import{promisify as jAe}from"node:util";function D7(e){try{let t=JSON.parse(e);return DAe(t)?t.families.flatMap(r=>MAe(r)):[]}catch{return[]}}function DAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function NAe(e){return N7(e)&&Array.isArray(e.variants)}function MAe(e){return NAe(e)?e.variants.filter(t=>N7(t)).map(t=>LAe(e,t)):[]}function LAe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:P7(t.max_context_tokens),maxOutputTokens:P7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=$Ae(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function N7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function P7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $Ae(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=BAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function BAe(e){let t=PO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=PO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=PO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function PO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${FAe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function FAe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var HAe=jAe(UAe),GAe=1,qAe=9e5;async function DO(e){let t=e.dataDir,r=zAe(t),n=VAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??qAe,i=e.devinCliVersion??WAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await YAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??KAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function B7(e){let t=await DO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=D7(t.raw);return{candidates:[M7(e,"native/models-list.raw.json",t.raw),M7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function zAe(e){return $7.join(e,"devin","models-cache.json")}function VAe(e){return $7.join(e,"devin","models-cache.lock")}function WAe(e){return e.resolveVersion?e.resolveVersion():ff()}async function KAe(){let{stdout:e}=await HAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function YAe(e){try{let t=await L7.readFile(e,"utf8"),r=JSON.parse(t);if(JAe(r))return r}catch(t){let r=t.code}return{version:GAe,entries:{}}}function JAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function M7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function ZAe(e){return e.failed>0||e.errors.length>0}function gf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function ebe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function tbe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function rbe(e){try{return await js.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function nbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:__(e.toolCallStates,t.toolCallStateHashes)}}async function sbe(e,t,r){let n=Sf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>obe(e,t,n))}async function obe(e,t,r){let n=tbe(e,t),s=await rbe(r),o=s?k7(s):{watermarks:go,lineCount:0,messageNodeIds:new Set},i=nbe(n,o.watermarks),{lines:a}=O7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,skipText:!0,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});if(await js.mkdir(Sf.dirname(r),{recursive:!0}),a.length>0){let c=await js.open(r,"a");try{for(let u of a)await c.write(JSON.stringify(u)),await c.write(`
126
+ `);await c.sync()}finally{await c.close()}}return r}function F7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function ibe(e){let t=e.artifacts.filter(s=>F7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!F7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function abe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function cbe(e){let t;try{t=await js.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await js.readFile(Sf.join(e,n),"utf8")})}catch{}return r}async function ube(e,t,r){return(await cbe(Sf.join(e,".devin","plans"))).filter(o=>abe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function dbe(e,t,r){let n=Sf.join(e,"transcripts",`${t}.json`),s;try{s=await js.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function lbe(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function fbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??QAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function pbe(e,t,r){let n=await _u({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return ibe(n)}async function mbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await ube(r,e.sessionId,o),c=await dbe(n,e.sessionId,o),u=lbe(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function hbe(e,t){let r=await B7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&gf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function gbe(e,t){return JSON.stringify([e,t])}async function Sbe(e,t,r){let n=gbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function ybe(e,t,r,n){let s=[...r.errors];try{await au({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=cu(o);s.includes(i)||s.push(i)}return s}async function Ebe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await Sbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts}));for(let f of t)f.candidate.content="";let c=iu(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await ybe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function U7(e){let t=e.profile??Us,r=e.homeDir??XAe.homedir(),n=fbe(e,r);gf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await sbe(e.tables,e.sessionId,e.dataDir);e.releaseTablesAfterMaterialization&&(e.tables.sessions=[],e.tables.messageNodes=[],e.tables.promptHistory=[],e.tables.toolCallStates=[]),gf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await pbe(e,t,s),{candidates:i,error:a}=await hbe(e,t),c=await mbe(e,o,r,n,i);gf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Ebe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),gf(e,ZAe(u)?"failure":"success",ebe(u)),u}function Cbe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
126
127
  `)}async function wbe(e,t){let r=e.env??await m_(e.cwd),n=p_(r,e.cwd);if(!n.ok||!n.config){t.write(`devin-session-sync: ${n.errorMessage??"configuration error"}
127
128
  `);return}return{env:r,config:n.config}}async function j7(e,t){let r=t.stderr??_be.stderr,n=await wbe(t,r);if(!n)return{ok:!1,reason:"config"};let{env:s,config:o}=n,i=t.harnessProfile??Us;try{let a=await w7({env:s,cwd:t.cwd,devinCliVersion:i.harnessVersion,sessionsDbPath:t.sessionsDbPath,home:t.homeDir});return{ok:!0,outcome:await U7({tables:a.tables,schemaDescriptor:a.schemaDescriptor,sessionId:t.sessionId,cwd:t.cwd,config:o,dataDir:Fs(s),storageAdapter:t.storageAdapter??ia(o),trigger:t.trigger,profile:i,env:s,homeDir:t.homeDir,models:t.models,onProgress:u=>Cbe(r,e,u)})}}catch(a){let c=a instanceof Error?a.message:String(a);return r.write(`devin-session-sync ${e} error: ${c}
128
129
  `),{ok:!1,reason:c}}}async function Rbe(e,t={}){let r=s7(e);if(!r.ok)return 0;let n=t.cwd??yf.cwd(),s=t.env??await m_(n),o=o7(r.input,n),i=i7(r.input.hook_event_name);if(p_(s,n).ok){let c=Fs(s),u=t.harnessProfile??Us,f=await DO({dataDir:c,devinCliVersion:u.harnessVersion});f.error&&(t.stderr??yf.stderr).write(`devin-session-sync hook: models capture warning: ${f.error}
package/bin/session-end CHANGED
@@ -119,10 +119,11 @@ Configuration is resolved in precedence order (highest first):
119
119
  Security: SAL_STORAGE_ENDPOINT, SAL_STORAGE_ACCESS_KEY_ID, and
120
120
  SAL_STORAGE_SECRET_ACCESS_KEY are only read from process.env or
121
121
  .devin/config.local.json \u2014 never from a file that might be committed to git.
122
- `;function pRe(e,t){return{local:xO.join(e,".devin","config.local.json"),project:xO.join(e,".devin","config.json"),userGlobal:xO.join(t,".config","devin","config.json")}}var mf={profile:hi,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:pRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:hi.harness,helpText:fRe};function t7(e,t=mRe.cwd()){return f_(mf,e,t)}import r7 from"node:process";async function n7(e=r7.cwd(),t=r7.env,r=mf.profile.securityBlocklist){return du(mf,e,t,r)}import FRe from"node:os";import y7 from"node:process";import{existsSync as hRe}from"node:fs";import{join as ca}from"node:path";function gRe(e){return[{label:"home-devin",path:ca(e.home,".devin")},{label:"home-devin-shared",path:ca(e.home,".devin-shared")},{label:"home-codeium",path:ca(e.home,".codeium")},{label:"home-windsurf",path:ca(e.home,".windsurf")},{label:"project-devin",path:ca(e.cwd,".devin")},{label:"project-windsurf",path:ca(e.cwd,".windsurf")}]}function p_(e,t=hRe){let r=ff(e),n=gRe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:ca(r,"sessions.db"),probes:n}}import{createHash as CRe}from"node:crypto";import{copyFileSync as wRe,existsSync as RRe,mkdtempSync as ARe,rmSync as bRe}from"node:fs";import{tmpdir as xRe}from"node:os";import{basename as TRe,join as f7}from"node:path";import{createHash as SRe}from"node:crypto";function s7(e){return`${e.session_id}\0${e.node_id}`}function o7(e){let{row_id:t,created_at:r,...n}=e;return SRe("sha256").update(JSON.stringify(n)).digest("hex")}function m_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[s7(r)]!==o7(r))}function h_(e,t){let r={...e};for(let n of t)r[s7(n)]=o7(n);return r}var g_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},i7=["sessions","message_nodes","prompt_history"];function TO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(g_),warnings:[]}:yRe(e)}function yRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${i7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...i7],warnings:r}}function a7(e,t){let r=new Set(g_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as ERe}from"node:crypto";function c7(e){return ERe("sha256").update(JSON.stringify(e)).digest("hex")}function u7(e,t){return e.filter(r=>t[r.id]!==c7(r))}function S_(e,t){let r={...e};for(let n of t)r[n.id]=c7(n);return r}import{createHash as _Re}from"node:crypto";function d7(e){return`${e.session_id}\0${e.tool_call_id}`}function l7(e){let{row_id:t,...r}=e;return _Re("sha256").update(JSON.stringify(r)).digest("hex")}function y_(e,t){return e.filter(r=>t[d7(r)]!==l7(r))}function E_(e,t){let r={...e};for(let n of t)r[d7(n)]=l7(n);return r}var __=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},p7=()=>import("node:sqlite");async function ORe(e=p7){let t;try{t=await e()}catch(r){throw new __(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new __("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function m7(e,t=p7){let{DatabaseSync:r}=await ORe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return vRe(e,r,n)}}function vRe(e,t,r){try{return IRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function IRe(e,t){let r=ARe(f7(xRe(),"devin-session-sync-snapshot-")),n=f7(r,TRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;RRe(i)&&wRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),bRe(r,{recursive:!0,force:!0})}}}function h7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function C_(e,t,r=[]){return e.prepare(t).all(...r)}function kRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=C_(e,"SELECT * FROM sessions ORDER BY id");return u7(n,r)}function PRe(e,t,r){return t.knownTables.includes("message_nodes")?m_(C_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function DRe(e,t,r){return t.knownTables.includes("prompt_history")?C_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function NRe(e,t,r){return t.knownTables.includes("tool_call_state")?y_(C_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function MRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function LRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?CRe("sha256").update(r.sql).digest("hex"):null}function $Re(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function BRe(e,t){let r=[];for(let n of t){let s=a7(n,$Re(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function g7(e,t=null){let r=TO(h7(e)),n={};for(let s of Object.keys(g_))n[s]=LRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:MRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...BRe(e,r.knownTables)]}}function S7(e,t){let r=TO(h7(e));return{tables:{sessions:kRe(e,r,t.sessionsContentHashes),messageNodes:PRe(e,r,t.messageNodesContentHashes),promptHistory:DRe(e,r,t.promptHistoryId),toolCallStates:NRe(e,r,t.toolCallStateHashes)},schema:r}}var mo={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function URe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??y7.env,r=e.home??FRe.homedir(),n=e.cwd??y7.cwd();return p_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function E7(e={}){let t=URe(e),r=e.devinCliVersion??pf(),{db:n,close:s}=await m7(t);try{let{tables:o}=S7(n,mo),i=g7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as Fs from"node:fs/promises";import YAe from"node:os";import yf from"node:path";import JAe from"node:process";var C7="sal/synthetic_subagent_kind",jRe="sal/synthetic_subagent_rawinput_profile",HRe="sal/synthetic_subagent_tool_call_id",GRe="sal/synthetic_subagent_source_node_id",qRe="sal/synthetic_subagent_is_background";function hf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w_(e){if(!e)return null;try{let t=JSON.parse(e);return hf(t)?t:null}catch{return null}}function zRe(e){let t=e._meta;if(!hf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function VRe(e){let t=[];for(let r of e){let n=w_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||zRe(n)!=="run_subagent")continue;let s=hf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function w7(e){let t=w_(e);if(!t)return null;let r=t.metadata;if(!hf(r))return null;let n=r.extensions;return hf(n)?n:null}function OO(e){let t=w_(e);return t&&typeof t.content=="string"?t.content:null}function WRe(e){let t=w_(e);return t&&typeof t.role=="string"?t.role:null}function KRe(e,t){return e?.includes(JSON.stringify(t))??!1}function YRe(e){let t=[];for(let r of e){let s=w7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var JRe="Background subagent started";function XRe(e,t){let r=e.find(s=>{if(WRe(s.chat_message)!=="system")return!1;let o=OO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=OO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=OO(t.node.chat_message);return n===null||n.startsWith(JRe)?null:{node:t.node,content:n,isBackground:!1}}function QRe(e){return w7(e)??{}}function R7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var _7=Number.MAX_SAFE_INTEGER;function ZRe(e,t){let r=YRe(e),n=[];for(let s of VRe(t)){if(s.task===null)continue;let o=r.find(i=>KRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function eAe(e,t){return R7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[C7]:"prompt",[jRe]:e.invocation.profile,[HRe]:e.invocation.toolCallId})}function tAe(e,t,r,n){let s=XRe(e,t.tagged);return s===null?null:R7(t.tagged.node,r,n,"assistant",s.content,QRe(t.tagged.node.chat_message),{[C7]:"result",[GRe]:s.node.node_id,[qRe]:s.isBackground})}function A7(e,t){let r=[];for(let n of ZRe(e,t)){let s=_7-n.tagged.node.node_id*2,o=_7-n.tagged.node.node_id*2-1;r.push(eAe(n,s));let i=tAe(e,n,o,s);i&&r.push(i)}return r}function b7(e,t={}){let r=new Map(e.sessions.map(f=>[f.id,f])),n=gf(e.messageNodes,f=>f.session_id),s=gf(e.promptHistory,f=>f.session_id),o=gf(e.toolCallStates,f=>f.session_id),i=rAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let f of sAe(e))a=oAe(c,a,r.get(f),{nodes:n.get(f)??[],prompts:s.get(f)??[],toolCalls:o.get(f)??[]},nAe(i,f));let u=t.priorWatermarks??mo;return{lines:c,text:SAe(c),watermarks:hAe(e,u)}}function rAe(e){if(e)return{nodesBySession:gf(e.messageNodes,t=>t.session_id),toolCallsBySession:gf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function nAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function sAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function oAe(e,t,r,n,s){let o=t;return r&&(e.push(pAe(r,o)),o+=1),o=dAe(e,o,n.nodes,n.toolCalls),o=iAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=fAe(e,o,n.prompts),o}function iAe(e,t,r,n,s){let o=t;for(let i of A7(r,n))s?.has(i.node_id)||(e.push(x7(i,o)),o+=1);return o}function aAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function cAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&uAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function uAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function dAe(e,t,r,n){let s=t,o=new Set;for(let i of aAe(r)){e.push(x7(i,s)),s+=1;for(let a of cAe(i,n,o))e.push(T7(a,s)),s+=1}return s=lAe(e,s,n,o),s}function lAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(T7(i,s)),s+=1;return s}function fAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(mAe(s,n)),n+=1;return n}function pAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function x7(e,t){return{type:"message",ts:null,order:t,...e}}function T7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function mAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function gf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function hAe(e,t){return{messageNodesContentHashes:h_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:E_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:gAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:S_(t.sessionsContentHashes,e.sessions)}}function gAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function SAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
122
+ `;function pRe(e,t){return{local:xO.join(e,".devin","config.local.json"),project:xO.join(e,".devin","config.json"),userGlobal:xO.join(t,".config","devin","config.json")}}var mf={profile:hi,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:pRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:hi.harness,helpText:fRe};function t7(e,t=mRe.cwd()){return f_(mf,e,t)}import r7 from"node:process";async function n7(e=r7.cwd(),t=r7.env,r=mf.profile.securityBlocklist){return du(mf,e,t,r)}import FRe from"node:os";import y7 from"node:process";import{existsSync as hRe}from"node:fs";import{join as ca}from"node:path";function gRe(e){return[{label:"home-devin",path:ca(e.home,".devin")},{label:"home-devin-shared",path:ca(e.home,".devin-shared")},{label:"home-codeium",path:ca(e.home,".codeium")},{label:"home-windsurf",path:ca(e.home,".windsurf")},{label:"project-devin",path:ca(e.cwd,".devin")},{label:"project-windsurf",path:ca(e.cwd,".windsurf")}]}function p_(e,t=hRe){let r=ff(e),n=gRe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:ca(r,"sessions.db"),probes:n}}import{createHash as CRe}from"node:crypto";import{copyFileSync as wRe,existsSync as RRe,mkdtempSync as ARe,rmSync as bRe}from"node:fs";import{tmpdir as xRe}from"node:os";import{basename as TRe,join as f7}from"node:path";import{createHash as SRe}from"node:crypto";function s7(e){return`${e.session_id}\0${e.node_id}`}function o7(e){let{row_id:t,created_at:r,...n}=e;return SRe("sha256").update(JSON.stringify(n)).digest("hex")}function m_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[s7(r)]!==o7(r))}function h_(e,t){let r={...e};for(let n of t)r[s7(n)]=o7(n);return r}var g_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},i7=["sessions","message_nodes","prompt_history"];function TO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(g_),warnings:[]}:yRe(e)}function yRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${i7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...i7],warnings:r}}function a7(e,t){let r=new Set(g_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as ERe}from"node:crypto";function c7(e){return ERe("sha256").update(JSON.stringify(e)).digest("hex")}function u7(e,t){return e.filter(r=>t[r.id]!==c7(r))}function S_(e,t){let r={...e};for(let n of t)r[n.id]=c7(n);return r}import{createHash as _Re}from"node:crypto";function d7(e){return`${e.session_id}\0${e.tool_call_id}`}function l7(e){let{row_id:t,...r}=e;return _Re("sha256").update(JSON.stringify(r)).digest("hex")}function y_(e,t){return e.filter(r=>t[d7(r)]!==l7(r))}function E_(e,t){let r={...e};for(let n of t)r[d7(n)]=l7(n);return r}var __=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},p7=()=>import("node:sqlite");async function ORe(e=p7){let t;try{t=await e()}catch(r){throw new __(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new __("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function m7(e,t=p7){let{DatabaseSync:r}=await ORe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return vRe(e,r,n)}}function vRe(e,t,r){try{return IRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function IRe(e,t){let r=ARe(f7(xRe(),"devin-session-sync-snapshot-")),n=f7(r,TRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;RRe(i)&&wRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),bRe(r,{recursive:!0,force:!0})}}}function h7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function C_(e,t,r=[]){return e.prepare(t).all(...r)}function kRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=C_(e,"SELECT * FROM sessions ORDER BY id");return u7(n,r)}function PRe(e,t,r){return t.knownTables.includes("message_nodes")?m_(C_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function DRe(e,t,r){return t.knownTables.includes("prompt_history")?C_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function NRe(e,t,r){return t.knownTables.includes("tool_call_state")?y_(C_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function MRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function LRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?CRe("sha256").update(r.sql).digest("hex"):null}function $Re(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function BRe(e,t){let r=[];for(let n of t){let s=a7(n,$Re(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function g7(e,t=null){let r=TO(h7(e)),n={};for(let s of Object.keys(g_))n[s]=LRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:MRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...BRe(e,r.knownTables)]}}function S7(e,t){let r=TO(h7(e));return{tables:{sessions:kRe(e,r,t.sessionsContentHashes),messageNodes:PRe(e,r,t.messageNodesContentHashes),promptHistory:DRe(e,r,t.promptHistoryId),toolCallStates:NRe(e,r,t.toolCallStateHashes)},schema:r}}var mo={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function URe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??y7.env,r=e.home??FRe.homedir(),n=e.cwd??y7.cwd();return p_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function E7(e={}){let t=URe(e),r=e.devinCliVersion??pf(),{db:n,close:s}=await m7(t);try{let{tables:o}=S7(n,mo),i=g7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as Fs from"node:fs/promises";import YAe from"node:os";import yf from"node:path";import JAe from"node:process";var C7="sal/synthetic_subagent_kind",jRe="sal/synthetic_subagent_rawinput_profile",HRe="sal/synthetic_subagent_tool_call_id",GRe="sal/synthetic_subagent_source_node_id",qRe="sal/synthetic_subagent_is_background";function hf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w_(e){if(!e)return null;try{let t=JSON.parse(e);return hf(t)?t:null}catch{return null}}function zRe(e){let t=e._meta;if(!hf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function VRe(e){let t=[];for(let r of e){let n=w_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||zRe(n)!=="run_subagent")continue;let s=hf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function w7(e){let t=w_(e);if(!t)return null;let r=t.metadata;if(!hf(r))return null;let n=r.extensions;return hf(n)?n:null}function OO(e){let t=w_(e);return t&&typeof t.content=="string"?t.content:null}function WRe(e){let t=w_(e);return t&&typeof t.role=="string"?t.role:null}function KRe(e,t){return e?.includes(JSON.stringify(t))??!1}function YRe(e){let t=[];for(let r of e){let s=w7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var JRe="Background subagent started";function XRe(e,t){let r=e.find(s=>{if(WRe(s.chat_message)!=="system")return!1;let o=OO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=OO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=OO(t.node.chat_message);return n===null||n.startsWith(JRe)?null:{node:t.node,content:n,isBackground:!1}}function QRe(e){return w7(e)??{}}function R7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var _7=Number.MAX_SAFE_INTEGER;function ZRe(e,t){let r=YRe(e),n=[];for(let s of VRe(t)){if(s.task===null)continue;let o=r.find(i=>KRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function eAe(e,t){return R7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[C7]:"prompt",[jRe]:e.invocation.profile,[HRe]:e.invocation.toolCallId})}function tAe(e,t,r,n){let s=XRe(e,t.tagged);return s===null?null:R7(t.tagged.node,r,n,"assistant",s.content,QRe(t.tagged.node.chat_message),{[C7]:"result",[GRe]:s.node.node_id,[qRe]:s.isBackground})}function A7(e,t){let r=[];for(let n of ZRe(e,t)){let s=_7-n.tagged.node.node_id*2,o=_7-n.tagged.node.node_id*2-1;r.push(eAe(n,s));let i=tAe(e,n,o,s);i&&r.push(i)}return r}function b7(e,t={}){let r=new Map(e.sessions.map(h=>[h.id,h])),n=gf(e.messageNodes,h=>h.session_id),s=gf(e.promptHistory,h=>h.session_id),o=gf(e.toolCallStates,h=>h.session_id),i=rAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let h of sAe(e))a=oAe(c,a,r.get(h),{nodes:n.get(h)??[],prompts:s.get(h)??[],toolCalls:o.get(h)??[]},nAe(i,h));let u=t.priorWatermarks??mo,f=t.skipText?"":SAe(c);return{lines:c,text:f,watermarks:hAe(e,u)}}function rAe(e){if(e)return{nodesBySession:gf(e.messageNodes,t=>t.session_id),toolCallsBySession:gf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function nAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function sAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function oAe(e,t,r,n,s){let o=t;return r&&(e.push(pAe(r,o)),o+=1),o=dAe(e,o,n.nodes,n.toolCalls),o=iAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=fAe(e,o,n.prompts),o}function iAe(e,t,r,n,s){let o=t;for(let i of A7(r,n))s?.has(i.node_id)||(e.push(x7(i,o)),o+=1);return o}function aAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function cAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&uAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function uAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function dAe(e,t,r,n){let s=t,o=new Set;for(let i of aAe(r)){e.push(x7(i,s)),s+=1;for(let a of cAe(i,n,o))e.push(T7(a,s)),s+=1}return s=lAe(e,s,n,o),s}function lAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(T7(i,s)),s+=1;return s}function fAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(mAe(s,n)),n+=1;return n}function pAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function x7(e,t){return{type:"message",ts:null,order:t,...e}}function T7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function mAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function gf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function hAe(e,t){return{messageNodesContentHashes:h_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:E_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:gAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:S_(t.sessionsContentHashes,e.sessions)}}function gAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function SAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
123
123
  `)}
124
124
  `}function O7(e){let t=e.split(`
125
- `).filter(n=>n.length>0),r=t.map(EAe).filter(_Ae);return r.length===0?{watermarks:mo,lineCount:0,messageNodeIds:new Set}:{watermarks:vAe(r),lineCount:t.length,messageNodeIds:yAe(r)}}function yAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function EAe(e){try{return JSON.parse(e)}catch{return}}function _Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vO(e){let{type:t,ts:r,order:n,...s}=e;return s}function CAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function wAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function RAe(e){return typeof e.id=="string"}function AAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function bAe(e,t){let r=vO(t);return wAe(r)?{...e,toolCallStateHashes:E_(e.toolCallStateHashes,[r])}:e}function xAe(e,t){let r=vO(t);return RAe(r)?{...e,sessionsContentHashes:S_(e.sessionsContentHashes,[r])}:e}function TAe(e,t){let r=vO(t);return AAe(r)?{...e,messageNodesContentHashes:h_(e.messageNodesContentHashes,[r])}:e}function OAe(e,t){switch(t.type){case"message":return TAe(e,t);case"prompt":return{...e,promptHistoryId:CAe(e.promptHistoryId,t.id)};case"tool_call":return bAe(e,t);case"session":return xAe(e,t);default:return e}}function vAe(e){let t=mo;for(let r of e)t=OAe(t,r);return t}import{execFile as $Ae}from"node:child_process";import*as D7 from"node:fs/promises";import N7 from"node:path";import{promisify as BAe}from"node:util";function I7(e){try{let t=JSON.parse(e);return IAe(t)?t.families.flatMap(r=>PAe(r)):[]}catch{return[]}}function IAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function kAe(e){return k7(e)&&Array.isArray(e.variants)}function PAe(e){return kAe(e)?e.variants.filter(t=>k7(t)).map(t=>DAe(e,t)):[]}function DAe(e,t){let r={modelUid:R_(t.model_uid),label:R_(t.label),familyUid:R_(e.family_uid),costTier:R_(t.cost_tier),maxContextTokens:v7(t.max_context_tokens),maxOutputTokens:v7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=NAe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function k7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R_(e){return typeof e=="string"?e:""}function v7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function NAe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=MAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function MAe(e){let t=IO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=IO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=IO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function IO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${LAe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function LAe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var FAe=BAe($Ae),UAe=1,jAe=9e5;async function HAe(e){let t=e.dataDir,r=GAe(t),n=qAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??jAe,i=e.devinCliVersion??zAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await WAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??VAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await yi(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function M7(e){let t=await HAe(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=I7(t.raw);return{candidates:[P7(e,"native/models-list.raw.json",t.raw),P7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function GAe(e){return N7.join(e,"devin","models-cache.json")}function qAe(e){return N7.join(e,"devin","models-cache.lock")}function zAe(e){return e.resolveVersion?e.resolveVersion():pf()}async function VAe(){let{stdout:e}=await FAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function WAe(e){try{let t=await D7.readFile(e,"utf8"),r=JSON.parse(t);if(KAe(r))return r}catch(t){let r=t.code}return{version:UAe,entries:{}}}function KAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function P7(e,t,r){let n=_i({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function XAe(e){return e.failed>0||e.errors.length>0}function Sf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function QAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ZAe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function ebe(e){try{return await Fs.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tbe(e,t){return{sessions:e.sessions,messageNodes:m_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:y_(e.toolCallStates,t.toolCallStateHashes)}}async function rbe(e,t,r){let n=yf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>nbe(e,t,n))}async function nbe(e,t,r){let n=ZAe(e,t),s=await ebe(r),o=s?O7(s):{watermarks:mo,lineCount:0,messageNodeIds:new Set},i=tbe(n,o.watermarks),{text:a}=b7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});return await Fs.mkdir(yf.dirname(r),{recursive:!0}),await Fs.appendFile(r,a,"utf8"),r}function L7(e){let t=e.replace(/\\/g,"/");return QY.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function sbe(e){let t=e.artifacts.filter(s=>L7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!L7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function kO(e,t,r,n,s){let o=_i({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function obe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function ibe(e){let t;try{t=await Fs.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await Fs.readFile(yf.join(e,n),"utf8")})}catch{}return r}async function abe(e,t,r){return(await ibe(yf.join(e,".devin","plans"))).filter(o=>obe(o.content)===t).map(o=>kO(r,t,"session",`plans/${o.fileName}`,o.content))}async function cbe(e,t,r){let n=yf.join(e,"transcripts",`${t}.json`),s;try{s=await Fs.readFile(n,"utf8")}catch{return}return kO(r,t,"session","native/atif-transcript.json",s)}function ube(e,t,r){let n=JSON.stringify(e,null,2);return kO(t,r,"runtime","native/schema-descriptor.json",n)}function dbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??JAe.env;return p_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function lbe(e,t,r){let n=await Cu({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return sbe(n)}async function fbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await abe(r,e.sessionId,o),c=await cbe(n,e.sessionId,o),u=ube(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function pbe(e,t){let r=await M7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&Sf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function mbe(e,t){return JSON.stringify([e,t])}async function hbe(e,t,r){let n=mbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function gbe(e,t,r,n){let s=[...r.errors];try{await cu({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=uu(o);s.includes(i)||s.push(i)}return s}async function Sbe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await hbe(e,n,r),o=t.map(f=>f.candidate),i=VY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts})),c=au(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await gbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function $7(e){let t=e.profile??hi,r=e.homeDir??YAe.homedir(),n=dbe(e,r);Sf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await rbe(e.tables,e.sessionId,e.dataDir);Sf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await lbe(e,t,s),{candidates:i,error:a}=await pbe(e,t),c=await fbe(e,o,r,n,i);Sf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Sbe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),Sf(e,XAe(u)?"failure":"success",QAe(u)),u}function Ebe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
125
+ `).filter(n=>n.length>0),r=t.map(EAe).filter(_Ae);return r.length===0?{watermarks:mo,lineCount:0,messageNodeIds:new Set}:{watermarks:vAe(r),lineCount:t.length,messageNodeIds:yAe(r)}}function yAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function EAe(e){try{return JSON.parse(e)}catch{return}}function _Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vO(e){let{type:t,ts:r,order:n,...s}=e;return s}function CAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function wAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function RAe(e){return typeof e.id=="string"}function AAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function bAe(e,t){let r=vO(t);return wAe(r)?{...e,toolCallStateHashes:E_(e.toolCallStateHashes,[r])}:e}function xAe(e,t){let r=vO(t);return RAe(r)?{...e,sessionsContentHashes:S_(e.sessionsContentHashes,[r])}:e}function TAe(e,t){let r=vO(t);return AAe(r)?{...e,messageNodesContentHashes:h_(e.messageNodesContentHashes,[r])}:e}function OAe(e,t){switch(t.type){case"message":return TAe(e,t);case"prompt":return{...e,promptHistoryId:CAe(e.promptHistoryId,t.id)};case"tool_call":return bAe(e,t);case"session":return xAe(e,t);default:return e}}function vAe(e){let t=mo;for(let r of e)t=OAe(t,r);return t}import{execFile as $Ae}from"node:child_process";import*as D7 from"node:fs/promises";import N7 from"node:path";import{promisify as BAe}from"node:util";function I7(e){try{let t=JSON.parse(e);return IAe(t)?t.families.flatMap(r=>PAe(r)):[]}catch{return[]}}function IAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function kAe(e){return k7(e)&&Array.isArray(e.variants)}function PAe(e){return kAe(e)?e.variants.filter(t=>k7(t)).map(t=>DAe(e,t)):[]}function DAe(e,t){let r={modelUid:R_(t.model_uid),label:R_(t.label),familyUid:R_(e.family_uid),costTier:R_(t.cost_tier),maxContextTokens:v7(t.max_context_tokens),maxOutputTokens:v7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=NAe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function k7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R_(e){return typeof e=="string"?e:""}function v7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function NAe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=MAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function MAe(e){let t=IO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=IO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=IO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function IO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${LAe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function LAe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var FAe=BAe($Ae),UAe=1,jAe=9e5;async function HAe(e){let t=e.dataDir,r=GAe(t),n=qAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??jAe,i=e.devinCliVersion??zAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await WAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??VAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await yi(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function M7(e){let t=await HAe(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=I7(t.raw);return{candidates:[P7(e,"native/models-list.raw.json",t.raw),P7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function GAe(e){return N7.join(e,"devin","models-cache.json")}function qAe(e){return N7.join(e,"devin","models-cache.lock")}function zAe(e){return e.resolveVersion?e.resolveVersion():pf()}async function VAe(){let{stdout:e}=await FAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function WAe(e){try{let t=await D7.readFile(e,"utf8"),r=JSON.parse(t);if(KAe(r))return r}catch(t){let r=t.code}return{version:UAe,entries:{}}}function KAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function P7(e,t,r){let n=_i({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function XAe(e){return e.failed>0||e.errors.length>0}function Sf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function QAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ZAe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function ebe(e){try{return await Fs.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tbe(e,t){return{sessions:e.sessions,messageNodes:m_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:y_(e.toolCallStates,t.toolCallStateHashes)}}async function rbe(e,t,r){let n=yf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>nbe(e,t,n))}async function nbe(e,t,r){let n=ZAe(e,t),s=await ebe(r),o=s?O7(s):{watermarks:mo,lineCount:0,messageNodeIds:new Set},i=tbe(n,o.watermarks),{lines:a}=b7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,skipText:!0,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});if(await Fs.mkdir(yf.dirname(r),{recursive:!0}),a.length>0){let c=await Fs.open(r,"a");try{for(let u of a)await c.write(JSON.stringify(u)),await c.write(`
126
+ `);await c.sync()}finally{await c.close()}}return r}function L7(e){let t=e.replace(/\\/g,"/");return QY.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function sbe(e){let t=e.artifacts.filter(s=>L7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!L7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function kO(e,t,r,n,s){let o=_i({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function obe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function ibe(e){let t;try{t=await Fs.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await Fs.readFile(yf.join(e,n),"utf8")})}catch{}return r}async function abe(e,t,r){return(await ibe(yf.join(e,".devin","plans"))).filter(o=>obe(o.content)===t).map(o=>kO(r,t,"session",`plans/${o.fileName}`,o.content))}async function cbe(e,t,r){let n=yf.join(e,"transcripts",`${t}.json`),s;try{s=await Fs.readFile(n,"utf8")}catch{return}return kO(r,t,"session","native/atif-transcript.json",s)}function ube(e,t,r){let n=JSON.stringify(e,null,2);return kO(t,r,"runtime","native/schema-descriptor.json",n)}function dbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??JAe.env;return p_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function lbe(e,t,r){let n=await Cu({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return sbe(n)}async function fbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await abe(r,e.sessionId,o),c=await cbe(n,e.sessionId,o),u=ube(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function pbe(e,t){let r=await M7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&Sf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function mbe(e,t){return JSON.stringify([e,t])}async function hbe(e,t,r){let n=mbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function gbe(e,t,r,n){let s=[...r.errors];try{await cu({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=uu(o);s.includes(i)||s.push(i)}return s}async function Sbe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await hbe(e,n,r),o=t.map(f=>f.candidate),i=VY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts}));for(let f of t)f.candidate.content="";let c=au(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await gbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function $7(e){let t=e.profile??hi,r=e.homeDir??YAe.homedir(),n=dbe(e,r);Sf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await rbe(e.tables,e.sessionId,e.dataDir);e.releaseTablesAfterMaterialization&&(e.tables.sessions=[],e.tables.messageNodes=[],e.tables.promptHistory=[],e.tables.toolCallStates=[]),Sf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await lbe(e,t,s),{candidates:i,error:a}=await pbe(e,t),c=await fbe(e,o,r,n,i);Sf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Sbe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),Sf(e,XAe(u)?"failure":"success",QAe(u)),u}function Ebe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
126
127
  `)}async function _be(e,t){let r=e.env??await n7(e.cwd),n=t7(r,e.cwd);if(!n.ok||!n.config){t.write(`devin-session-sync: ${n.errorMessage??"configuration error"}
127
128
  `);return}return{env:r,config:n.config}}async function B7(e,t){let r=t.stderr??ybe.stderr,n=await _be(t,r);if(!n)return{ok:!1,reason:"config"};let{env:s,config:o}=n,i=t.harnessProfile??hi;try{let a=await E7({env:s,cwd:t.cwd,devinCliVersion:i.harnessVersion,sessionsDbPath:t.sessionsDbPath,home:t.homeDir});return{ok:!0,outcome:await $7({tables:a.tables,schemaDescriptor:a.schemaDescriptor,sessionId:t.sessionId,cwd:t.cwd,config:o,dataDir:mi(s),storageAdapter:t.storageAdapter??aa(o),trigger:t.trigger,profile:i,env:s,homeDir:t.homeDir,models:t.models,onProgress:u=>Ebe(r,e,u)})}}catch(a){let c=a instanceof Error?a.message:String(a);return r.write(`devin-session-sync ${e} error: ${c}
128
129
  `),{ok:!1,reason:c}}}function Cbe(e){let t=[];e.uploaded>0&&t.push(`${e.uploaded} files uploaded`),e.skipped>0&&t.push(`${e.skipped} files skipped (unchanged)`),e.failed>0&&t.push(`${e.failed} files failed`),t.length>0&&gi.stderr.write(`devin-session-sync: ${t.join(", ")}.
package/bin/session-start CHANGED
@@ -119,10 +119,11 @@ Configuration is resolved in precedence order (highest first):
119
119
  Security: SAL_STORAGE_ENDPOINT, SAL_STORAGE_ACCESS_KEY_ID, and
120
120
  SAL_STORAGE_SECRET_ACCESS_KEY are only read from process.env or
121
121
  .devin/config.local.json \u2014 never from a file that might be committed to git.
122
- `;function pRe(e,t){return{local:OO.join(e,".devin","config.local.json"),project:OO.join(e,".devin","config.json"),userGlobal:OO.join(t,".config","devin","config.json")}}var pf={profile:Us,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:pRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:Us.harness,helpText:fRe};function p_(e,t=mRe.cwd()){return f_(pf,e,t)}import r7 from"node:process";async function m_(e=r7.cwd(),t=r7.env,r=pf.profile.securityBlocklist){return uu(pf,e,t,r)}import hRe from"node:process";function n7(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,missing:["session_id"],raw:e};let t=e,r=t.session_id;return typeof r!="string"||r.trim()===""?{ok:!1,missing:["session_id"],raw:e}:{ok:!0,input:t}}function s7(e,t=hRe.cwd()){return{harness:TO,sessionId:e.session_id,cwd:typeof e.cwd=="string"&&e.cwd.trim()!==""?e.cwd:t,startedAt:e.started_at,endedAt:e.ended_at,endReason:e.reason,model:e.model}}import ybe from"node:process";import URe from"node:os";import E7 from"node:process";import{existsSync as gRe}from"node:fs";import{join as aa}from"node:path";function SRe(e){return[{label:"home-devin",path:aa(e.home,".devin")},{label:"home-devin-shared",path:aa(e.home,".devin-shared")},{label:"home-codeium",path:aa(e.home,".codeium")},{label:"home-windsurf",path:aa(e.home,".windsurf")},{label:"project-devin",path:aa(e.cwd,".devin")},{label:"project-windsurf",path:aa(e.cwd,".windsurf")}]}function h_(e,t=gRe){let r=lf(e),n=SRe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:aa(r,"sessions.db"),probes:n}}import{createHash as wRe}from"node:crypto";import{copyFileSync as RRe,existsSync as ARe,mkdtempSync as bRe,rmSync as xRe}from"node:fs";import{tmpdir as TRe}from"node:os";import{basename as ORe,join as p7}from"node:path";import{createHash as yRe}from"node:crypto";function o7(e){return`${e.session_id}\0${e.node_id}`}function i7(e){let{row_id:t,created_at:r,...n}=e;return yRe("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[o7(r)]!==i7(r))}function S_(e,t){let r={...e};for(let n of t)r[o7(n)]=i7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},a7=["sessions","message_nodes","prompt_history"];function vO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:ERe(e)}function ERe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${a7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...a7],warnings:r}}function c7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as _Re}from"node:crypto";function u7(e){return _Re("sha256").update(JSON.stringify(e)).digest("hex")}function d7(e,t){return e.filter(r=>t[r.id]!==u7(r))}function E_(e,t){let r={...e};for(let n of t)r[n.id]=u7(n);return r}import{createHash as CRe}from"node:crypto";function l7(e){return`${e.session_id}\0${e.tool_call_id}`}function f7(e){let{row_id:t,...r}=e;return CRe("sha256").update(JSON.stringify(r)).digest("hex")}function __(e,t){return e.filter(r=>t[l7(r)]!==f7(r))}function C_(e,t){let r={...e};for(let n of t)r[l7(n)]=f7(n);return r}var w_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},m7=()=>import("node:sqlite");async function vRe(e=m7){let t;try{t=await e()}catch(r){throw new w_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new w_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function h7(e,t=m7){let{DatabaseSync:r}=await vRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return IRe(e,r,n)}}function IRe(e,t,r){try{return kRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function kRe(e,t){let r=bRe(p7(TRe(),"devin-session-sync-snapshot-")),n=p7(r,ORe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;ARe(i)&&RRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),xRe(r,{recursive:!0,force:!0})}}}function g7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function R_(e,t,r=[]){return e.prepare(t).all(...r)}function PRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=R_(e,"SELECT * FROM sessions ORDER BY id");return d7(n,r)}function DRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(R_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function NRe(e,t,r){return t.knownTables.includes("prompt_history")?R_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function MRe(e,t,r){return t.knownTables.includes("tool_call_state")?__(R_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function LRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function $Re(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?wRe("sha256").update(r.sql).digest("hex"):null}function BRe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function FRe(e,t){let r=[];for(let n of t){let s=c7(n,BRe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function S7(e,t=null){let r=vO(g7(e)),n={};for(let s of Object.keys(y_))n[s]=$Re(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:LRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...FRe(e,r.knownTables)]}}function y7(e,t){let r=vO(g7(e));return{tables:{sessions:PRe(e,r,t.sessionsContentHashes),messageNodes:DRe(e,r,t.messageNodesContentHashes),promptHistory:NRe(e,r,t.promptHistoryId),toolCallStates:MRe(e,r,t.toolCallStateHashes)},schema:r}}var go={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function jRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??E7.env,r=e.home??URe.homedir(),n=e.cwd??E7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function _7(e={}){let t=jRe(e),r=e.devinCliVersion??ff(),{db:n,close:s}=await h7(t);try{let{tables:o}=y7(n,go),i=S7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as js from"node:fs/promises";import YAe from"node:os";import Sf from"node:path";import JAe from"node:process";var w7="sal/synthetic_subagent_kind",HRe="sal/synthetic_subagent_rawinput_profile",GRe="sal/synthetic_subagent_tool_call_id",qRe="sal/synthetic_subagent_source_node_id",zRe="sal/synthetic_subagent_is_background";function mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A_(e){if(!e)return null;try{let t=JSON.parse(e);return mf(t)?t:null}catch{return null}}function VRe(e){let t=e._meta;if(!mf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function WRe(e){let t=[];for(let r of e){let n=A_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||VRe(n)!=="run_subagent")continue;let s=mf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function R7(e){let t=A_(e);if(!t)return null;let r=t.metadata;if(!mf(r))return null;let n=r.extensions;return mf(n)?n:null}function IO(e){let t=A_(e);return t&&typeof t.content=="string"?t.content:null}function KRe(e){let t=A_(e);return t&&typeof t.role=="string"?t.role:null}function YRe(e,t){return e?.includes(JSON.stringify(t))??!1}function JRe(e){let t=[];for(let r of e){let s=R7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var XRe="Background subagent started";function QRe(e,t){let r=e.find(s=>{if(KRe(s.chat_message)!=="system")return!1;let o=IO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=IO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=IO(t.node.chat_message);return n===null||n.startsWith(XRe)?null:{node:t.node,content:n,isBackground:!1}}function ZRe(e){return R7(e)??{}}function A7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var C7=Number.MAX_SAFE_INTEGER;function eAe(e,t){let r=JRe(e),n=[];for(let s of WRe(t)){if(s.task===null)continue;let o=r.find(i=>YRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function tAe(e,t){return A7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[w7]:"prompt",[HRe]:e.invocation.profile,[GRe]:e.invocation.toolCallId})}function rAe(e,t,r,n){let s=QRe(e,t.tagged);return s===null?null:A7(t.tagged.node,r,n,"assistant",s.content,ZRe(t.tagged.node.chat_message),{[w7]:"result",[qRe]:s.node.node_id,[zRe]:s.isBackground})}function b7(e,t){let r=[];for(let n of eAe(e,t)){let s=C7-n.tagged.node.node_id*2,o=C7-n.tagged.node.node_id*2-1;r.push(tAe(n,s));let i=rAe(e,n,o,s);i&&r.push(i)}return r}function x7(e,t={}){let r=new Map(e.sessions.map(f=>[f.id,f])),n=hf(e.messageNodes,f=>f.session_id),s=hf(e.promptHistory,f=>f.session_id),o=hf(e.toolCallStates,f=>f.session_id),i=nAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let f of oAe(e))a=iAe(c,a,r.get(f),{nodes:n.get(f)??[],prompts:s.get(f)??[],toolCalls:o.get(f)??[]},sAe(i,f));let u=t.priorWatermarks??go;return{lines:c,text:yAe(c),watermarks:gAe(e,u)}}function nAe(e){if(e)return{nodesBySession:hf(e.messageNodes,t=>t.session_id),toolCallsBySession:hf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function sAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function oAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function iAe(e,t,r,n,s){let o=t;return r&&(e.push(mAe(r,o)),o+=1),o=lAe(e,o,n.nodes,n.toolCalls),o=aAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=pAe(e,o,n.prompts),o}function aAe(e,t,r,n,s){let o=t;for(let i of b7(r,n))s?.has(i.node_id)||(e.push(T7(i,o)),o+=1);return o}function cAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function uAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&dAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function dAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function lAe(e,t,r,n){let s=t,o=new Set;for(let i of cAe(r)){e.push(T7(i,s)),s+=1;for(let a of uAe(i,n,o))e.push(O7(a,s)),s+=1}return s=fAe(e,s,n,o),s}function fAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(O7(i,s)),s+=1;return s}function pAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(hAe(s,n)),n+=1;return n}function mAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function T7(e,t){return{type:"message",ts:null,order:t,...e}}function O7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function hAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function hf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function gAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:C_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:SAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:E_(t.sessionsContentHashes,e.sessions)}}function SAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function yAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
122
+ `;function pRe(e,t){return{local:OO.join(e,".devin","config.local.json"),project:OO.join(e,".devin","config.json"),userGlobal:OO.join(t,".config","devin","config.json")}}var pf={profile:Us,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:pRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:Us.harness,helpText:fRe};function p_(e,t=mRe.cwd()){return f_(pf,e,t)}import r7 from"node:process";async function m_(e=r7.cwd(),t=r7.env,r=pf.profile.securityBlocklist){return uu(pf,e,t,r)}import hRe from"node:process";function n7(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,missing:["session_id"],raw:e};let t=e,r=t.session_id;return typeof r!="string"||r.trim()===""?{ok:!1,missing:["session_id"],raw:e}:{ok:!0,input:t}}function s7(e,t=hRe.cwd()){return{harness:TO,sessionId:e.session_id,cwd:typeof e.cwd=="string"&&e.cwd.trim()!==""?e.cwd:t,startedAt:e.started_at,endedAt:e.ended_at,endReason:e.reason,model:e.model}}import ybe from"node:process";import URe from"node:os";import E7 from"node:process";import{existsSync as gRe}from"node:fs";import{join as aa}from"node:path";function SRe(e){return[{label:"home-devin",path:aa(e.home,".devin")},{label:"home-devin-shared",path:aa(e.home,".devin-shared")},{label:"home-codeium",path:aa(e.home,".codeium")},{label:"home-windsurf",path:aa(e.home,".windsurf")},{label:"project-devin",path:aa(e.cwd,".devin")},{label:"project-windsurf",path:aa(e.cwd,".windsurf")}]}function h_(e,t=gRe){let r=lf(e),n=SRe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:aa(r,"sessions.db"),probes:n}}import{createHash as wRe}from"node:crypto";import{copyFileSync as RRe,existsSync as ARe,mkdtempSync as bRe,rmSync as xRe}from"node:fs";import{tmpdir as TRe}from"node:os";import{basename as ORe,join as p7}from"node:path";import{createHash as yRe}from"node:crypto";function o7(e){return`${e.session_id}\0${e.node_id}`}function i7(e){let{row_id:t,created_at:r,...n}=e;return yRe("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[o7(r)]!==i7(r))}function S_(e,t){let r={...e};for(let n of t)r[o7(n)]=i7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},a7=["sessions","message_nodes","prompt_history"];function vO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:ERe(e)}function ERe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${a7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...a7],warnings:r}}function c7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as _Re}from"node:crypto";function u7(e){return _Re("sha256").update(JSON.stringify(e)).digest("hex")}function d7(e,t){return e.filter(r=>t[r.id]!==u7(r))}function E_(e,t){let r={...e};for(let n of t)r[n.id]=u7(n);return r}import{createHash as CRe}from"node:crypto";function l7(e){return`${e.session_id}\0${e.tool_call_id}`}function f7(e){let{row_id:t,...r}=e;return CRe("sha256").update(JSON.stringify(r)).digest("hex")}function __(e,t){return e.filter(r=>t[l7(r)]!==f7(r))}function C_(e,t){let r={...e};for(let n of t)r[l7(n)]=f7(n);return r}var w_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},m7=()=>import("node:sqlite");async function vRe(e=m7){let t;try{t=await e()}catch(r){throw new w_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new w_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function h7(e,t=m7){let{DatabaseSync:r}=await vRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return IRe(e,r,n)}}function IRe(e,t,r){try{return kRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function kRe(e,t){let r=bRe(p7(TRe(),"devin-session-sync-snapshot-")),n=p7(r,ORe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;ARe(i)&&RRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),xRe(r,{recursive:!0,force:!0})}}}function g7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function R_(e,t,r=[]){return e.prepare(t).all(...r)}function PRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=R_(e,"SELECT * FROM sessions ORDER BY id");return d7(n,r)}function DRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(R_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function NRe(e,t,r){return t.knownTables.includes("prompt_history")?R_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function MRe(e,t,r){return t.knownTables.includes("tool_call_state")?__(R_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function LRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function $Re(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?wRe("sha256").update(r.sql).digest("hex"):null}function BRe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function FRe(e,t){let r=[];for(let n of t){let s=c7(n,BRe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function S7(e,t=null){let r=vO(g7(e)),n={};for(let s of Object.keys(y_))n[s]=$Re(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:LRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...FRe(e,r.knownTables)]}}function y7(e,t){let r=vO(g7(e));return{tables:{sessions:PRe(e,r,t.sessionsContentHashes),messageNodes:DRe(e,r,t.messageNodesContentHashes),promptHistory:NRe(e,r,t.promptHistoryId),toolCallStates:MRe(e,r,t.toolCallStateHashes)},schema:r}}var go={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function jRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??E7.env,r=e.home??URe.homedir(),n=e.cwd??E7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function _7(e={}){let t=jRe(e),r=e.devinCliVersion??ff(),{db:n,close:s}=await h7(t);try{let{tables:o}=y7(n,go),i=S7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import*as js from"node:fs/promises";import YAe from"node:os";import Sf from"node:path";import JAe from"node:process";var w7="sal/synthetic_subagent_kind",HRe="sal/synthetic_subagent_rawinput_profile",GRe="sal/synthetic_subagent_tool_call_id",qRe="sal/synthetic_subagent_source_node_id",zRe="sal/synthetic_subagent_is_background";function mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A_(e){if(!e)return null;try{let t=JSON.parse(e);return mf(t)?t:null}catch{return null}}function VRe(e){let t=e._meta;if(!mf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function WRe(e){let t=[];for(let r of e){let n=A_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||VRe(n)!=="run_subagent")continue;let s=mf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function R7(e){let t=A_(e);if(!t)return null;let r=t.metadata;if(!mf(r))return null;let n=r.extensions;return mf(n)?n:null}function IO(e){let t=A_(e);return t&&typeof t.content=="string"?t.content:null}function KRe(e){let t=A_(e);return t&&typeof t.role=="string"?t.role:null}function YRe(e,t){return e?.includes(JSON.stringify(t))??!1}function JRe(e){let t=[];for(let r of e){let s=R7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var XRe="Background subagent started";function QRe(e,t){let r=e.find(s=>{if(KRe(s.chat_message)!=="system")return!1;let o=IO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=IO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=IO(t.node.chat_message);return n===null||n.startsWith(XRe)?null:{node:t.node,content:n,isBackground:!1}}function ZRe(e){return R7(e)??{}}function A7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var C7=Number.MAX_SAFE_INTEGER;function eAe(e,t){let r=JRe(e),n=[];for(let s of WRe(t)){if(s.task===null)continue;let o=r.find(i=>YRe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function tAe(e,t){return A7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[w7]:"prompt",[HRe]:e.invocation.profile,[GRe]:e.invocation.toolCallId})}function rAe(e,t,r,n){let s=QRe(e,t.tagged);return s===null?null:A7(t.tagged.node,r,n,"assistant",s.content,ZRe(t.tagged.node.chat_message),{[w7]:"result",[qRe]:s.node.node_id,[zRe]:s.isBackground})}function b7(e,t){let r=[];for(let n of eAe(e,t)){let s=C7-n.tagged.node.node_id*2,o=C7-n.tagged.node.node_id*2-1;r.push(tAe(n,s));let i=rAe(e,n,o,s);i&&r.push(i)}return r}function x7(e,t={}){let r=new Map(e.sessions.map(h=>[h.id,h])),n=hf(e.messageNodes,h=>h.session_id),s=hf(e.promptHistory,h=>h.session_id),o=hf(e.toolCallStates,h=>h.session_id),i=nAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let h of oAe(e))a=iAe(c,a,r.get(h),{nodes:n.get(h)??[],prompts:s.get(h)??[],toolCalls:o.get(h)??[]},sAe(i,h));let u=t.priorWatermarks??go,f=t.skipText?"":yAe(c);return{lines:c,text:f,watermarks:gAe(e,u)}}function nAe(e){if(e)return{nodesBySession:hf(e.messageNodes,t=>t.session_id),toolCallsBySession:hf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function sAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function oAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function iAe(e,t,r,n,s){let o=t;return r&&(e.push(mAe(r,o)),o+=1),o=lAe(e,o,n.nodes,n.toolCalls),o=aAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=pAe(e,o,n.prompts),o}function aAe(e,t,r,n,s){let o=t;for(let i of b7(r,n))s?.has(i.node_id)||(e.push(T7(i,o)),o+=1);return o}function cAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function uAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&dAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function dAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function lAe(e,t,r,n){let s=t,o=new Set;for(let i of cAe(r)){e.push(T7(i,s)),s+=1;for(let a of uAe(i,n,o))e.push(O7(a,s)),s+=1}return s=fAe(e,s,n,o),s}function fAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(O7(i,s)),s+=1;return s}function pAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(hAe(s,n)),n+=1;return n}function mAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function T7(e,t){return{type:"message",ts:null,order:t,...e}}function O7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function hAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function hf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function gAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:C_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:SAe(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:E_(t.sessionsContentHashes,e.sessions)}}function SAe(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function yAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
123
123
  `)}
124
124
  `}function v7(e){let t=e.split(`
125
- `).filter(n=>n.length>0),r=t.map(_Ae).filter(CAe);return r.length===0?{watermarks:go,lineCount:0,messageNodeIds:new Set}:{watermarks:IAe(r),lineCount:t.length,messageNodeIds:EAe(r)}}function EAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function _Ae(e){try{return JSON.parse(e)}catch{return}}function CAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kO(e){let{type:t,ts:r,order:n,...s}=e;return s}function wAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function RAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function AAe(e){return typeof e.id=="string"}function bAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function xAe(e,t){let r=kO(t);return RAe(r)?{...e,toolCallStateHashes:C_(e.toolCallStateHashes,[r])}:e}function TAe(e,t){let r=kO(t);return AAe(r)?{...e,sessionsContentHashes:E_(e.sessionsContentHashes,[r])}:e}function OAe(e,t){let r=kO(t);return bAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function vAe(e,t){switch(t.type){case"message":return OAe(e,t);case"prompt":return{...e,promptHistoryId:wAe(e.promptHistoryId,t.id)};case"tool_call":return xAe(e,t);case"session":return TAe(e,t);default:return e}}function IAe(e){let t=go;for(let r of e)t=vAe(t,r);return t}import{execFile as BAe}from"node:child_process";import*as N7 from"node:fs/promises";import M7 from"node:path";import{promisify as FAe}from"node:util";function k7(e){try{let t=JSON.parse(e);return kAe(t)?t.families.flatMap(r=>DAe(r)):[]}catch{return[]}}function kAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function PAe(e){return P7(e)&&Array.isArray(e.variants)}function DAe(e){return PAe(e)?e.variants.filter(t=>P7(t)).map(t=>NAe(e,t)):[]}function NAe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:I7(t.max_context_tokens),maxOutputTokens:I7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=MAe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function P7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function I7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function MAe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=LAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function LAe(e){let t=PO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=PO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=PO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function PO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${$Ae(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function $Ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var UAe=FAe(BAe),jAe=1,HAe=9e5;async function DO(e){let t=e.dataDir,r=GAe(t),n=qAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??HAe,i=e.devinCliVersion??zAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await WAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??VAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function L7(e){let t=await DO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=k7(t.raw);return{candidates:[D7(e,"native/models-list.raw.json",t.raw),D7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function GAe(e){return M7.join(e,"devin","models-cache.json")}function qAe(e){return M7.join(e,"devin","models-cache.lock")}function zAe(e){return e.resolveVersion?e.resolveVersion():ff()}async function VAe(){let{stdout:e}=await UAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function WAe(e){try{let t=await N7.readFile(e,"utf8"),r=JSON.parse(t);if(KAe(r))return r}catch(t){let r=t.code}return{version:jAe,entries:{}}}function KAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function D7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function XAe(e){return e.failed>0||e.errors.length>0}function gf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function QAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ZAe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function ebe(e){try{return await js.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:__(e.toolCallStates,t.toolCallStateHashes)}}async function rbe(e,t,r){let n=Sf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>nbe(e,t,n))}async function nbe(e,t,r){let n=ZAe(e,t),s=await ebe(r),o=s?v7(s):{watermarks:go,lineCount:0,messageNodeIds:new Set},i=tbe(n,o.watermarks),{text:a}=x7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});return await js.mkdir(Sf.dirname(r),{recursive:!0}),await js.appendFile(r,a,"utf8"),r}function $7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function sbe(e){let t=e.artifacts.filter(s=>$7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!$7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function obe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function ibe(e){let t;try{t=await js.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await js.readFile(Sf.join(e,n),"utf8")})}catch{}return r}async function abe(e,t,r){return(await ibe(Sf.join(e,".devin","plans"))).filter(o=>obe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function cbe(e,t,r){let n=Sf.join(e,"transcripts",`${t}.json`),s;try{s=await js.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function ube(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function dbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??JAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function lbe(e,t,r){let n=await _u({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return sbe(n)}async function fbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await abe(r,e.sessionId,o),c=await cbe(n,e.sessionId,o),u=ube(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function pbe(e,t){let r=await L7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&gf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function mbe(e,t){return JSON.stringify([e,t])}async function hbe(e,t,r){let n=mbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function gbe(e,t,r,n){let s=[...r.errors];try{await au({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=cu(o);s.includes(i)||s.push(i)}return s}async function Sbe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await hbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts})),c=iu(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await gbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function B7(e){let t=e.profile??Us,r=e.homeDir??YAe.homedir(),n=dbe(e,r);gf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await rbe(e.tables,e.sessionId,e.dataDir);gf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await lbe(e,t,s),{candidates:i,error:a}=await pbe(e,t),c=await fbe(e,o,r,n,i);gf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Sbe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),gf(e,XAe(u)?"failure":"success",QAe(u)),u}function Ebe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
125
+ `).filter(n=>n.length>0),r=t.map(_Ae).filter(CAe);return r.length===0?{watermarks:go,lineCount:0,messageNodeIds:new Set}:{watermarks:IAe(r),lineCount:t.length,messageNodeIds:EAe(r)}}function EAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function _Ae(e){try{return JSON.parse(e)}catch{return}}function CAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kO(e){let{type:t,ts:r,order:n,...s}=e;return s}function wAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function RAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function AAe(e){return typeof e.id=="string"}function bAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function xAe(e,t){let r=kO(t);return RAe(r)?{...e,toolCallStateHashes:C_(e.toolCallStateHashes,[r])}:e}function TAe(e,t){let r=kO(t);return AAe(r)?{...e,sessionsContentHashes:E_(e.sessionsContentHashes,[r])}:e}function OAe(e,t){let r=kO(t);return bAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function vAe(e,t){switch(t.type){case"message":return OAe(e,t);case"prompt":return{...e,promptHistoryId:wAe(e.promptHistoryId,t.id)};case"tool_call":return xAe(e,t);case"session":return TAe(e,t);default:return e}}function IAe(e){let t=go;for(let r of e)t=vAe(t,r);return t}import{execFile as BAe}from"node:child_process";import*as N7 from"node:fs/promises";import M7 from"node:path";import{promisify as FAe}from"node:util";function k7(e){try{let t=JSON.parse(e);return kAe(t)?t.families.flatMap(r=>DAe(r)):[]}catch{return[]}}function kAe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function PAe(e){return P7(e)&&Array.isArray(e.variants)}function DAe(e){return PAe(e)?e.variants.filter(t=>P7(t)).map(t=>NAe(e,t)):[]}function NAe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:I7(t.max_context_tokens),maxOutputTokens:I7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=MAe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function P7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function I7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function MAe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=LAe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function LAe(e){let t=PO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=PO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=PO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function PO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${$Ae(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function $Ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var UAe=FAe(BAe),jAe=1,HAe=9e5;async function DO(e){let t=e.dataDir,r=GAe(t),n=qAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??HAe,i=e.devinCliVersion??zAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await WAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??VAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function L7(e){let t=await DO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=k7(t.raw);return{candidates:[D7(e,"native/models-list.raw.json",t.raw),D7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function GAe(e){return M7.join(e,"devin","models-cache.json")}function qAe(e){return M7.join(e,"devin","models-cache.lock")}function zAe(e){return e.resolveVersion?e.resolveVersion():ff()}async function VAe(){let{stdout:e}=await UAe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function WAe(e){try{let t=await N7.readFile(e,"utf8"),r=JSON.parse(t);if(KAe(r))return r}catch(t){let r=t.code}return{version:jAe,entries:{}}}function KAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function D7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}function XAe(e){return e.failed>0||e.errors.length>0}function gf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function QAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ZAe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function ebe(e){try{return await js.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:__(e.toolCallStates,t.toolCallStateHashes)}}async function rbe(e,t,r){let n=Sf.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>nbe(e,t,n))}async function nbe(e,t,r){let n=ZAe(e,t),s=await ebe(r),o=s?v7(s):{watermarks:go,lineCount:0,messageNodeIds:new Set},i=tbe(n,o.watermarks),{lines:a}=x7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,skipText:!0,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});if(await js.mkdir(Sf.dirname(r),{recursive:!0}),a.length>0){let c=await js.open(r,"a");try{for(let u of a)await c.write(JSON.stringify(u)),await c.write(`
126
+ `);await c.sync()}finally{await c.close()}}return r}function $7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function sbe(e){let t=e.artifacts.filter(s=>$7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!$7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function obe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function ibe(e){let t;try{t=await js.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await js.readFile(Sf.join(e,n),"utf8")})}catch{}return r}async function abe(e,t,r){return(await ibe(Sf.join(e,".devin","plans"))).filter(o=>obe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function cbe(e,t,r){let n=Sf.join(e,"transcripts",`${t}.json`),s;try{s=await js.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function ube(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function dbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??JAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function lbe(e,t,r){let n=await _u({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return sbe(n)}async function fbe(e,t,r,n,s){let o=e.config.projectId,i=await d_(t,e.config,{projectRoot:e.cwd}),a=await abe(r,e.sessionId,o),c=await cbe(n,e.sessionId,o),u=ube(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function pbe(e,t){let r=await L7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&gf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function mbe(e,t){return JSON.stringify([e,t])}async function hbe(e,t,r){let n=mbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function gbe(e,t,r,n){let s=[...r.errors];try{await au({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=cu(o);s.includes(i)||s.push(i)}return s}async function Sbe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await hbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>qf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts}));for(let f of t)f.candidate.content="";let c=iu(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await gbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function B7(e){let t=e.profile??Us,r=e.homeDir??YAe.homedir(),n=dbe(e,r);gf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await rbe(e.tables,e.sessionId,e.dataDir);e.releaseTablesAfterMaterialization&&(e.tables.sessions=[],e.tables.messageNodes=[],e.tables.promptHistory=[],e.tables.toolCallStates=[]),gf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await lbe(e,t,s),{candidates:i,error:a}=await pbe(e,t),c=await fbe(e,o,r,n,i);gf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await Sbe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),gf(e,XAe(u)?"failure":"success",QAe(u)),u}function Ebe(e,t,r){e.write(`devin-session-sync ${t}: ${r.timestamp} ${r.message}
126
127
  `)}async function _be(e,t){let r=e.env??await m_(e.cwd),n=p_(r,e.cwd);if(!n.ok||!n.config){t.write(`devin-session-sync: ${n.errorMessage??"configuration error"}
127
128
  `);return}return{env:r,config:n.config}}async function F7(e,t){let r=t.stderr??ybe.stderr,n=await _be(t,r);if(!n)return{ok:!1,reason:"config"};let{env:s,config:o}=n,i=t.harnessProfile??Us;try{let a=await _7({env:s,cwd:t.cwd,devinCliVersion:i.harnessVersion,sessionsDbPath:t.sessionsDbPath,home:t.homeDir});return{ok:!0,outcome:await B7({tables:a.tables,schemaDescriptor:a.schemaDescriptor,sessionId:t.sessionId,cwd:t.cwd,config:o,dataDir:Fs(s),storageAdapter:t.storageAdapter??ia(o),trigger:t.trigger,profile:i,env:s,homeDir:t.homeDir,models:t.models,onProgress:u=>Ebe(r,e,u)})}}catch(a){let c=a instanceof Error?a.message:String(a);return r.write(`devin-session-sync ${e} error: ${c}
128
129
  `),{ok:!1,reason:c}}}async function Cbe(e,t={}){let r=n7(e);if(!r.ok)return 0;let n=t.cwd??yf.cwd(),s=t.env??await m_(n),o=s7(r.input,n);if(o.startedAt=o.startedAt??new Date().toISOString(),p_(s,n).ok){let a=Fs(s),c=t.harnessProfile??Us,u=await DO({dataDir:a,devinCliVersion:c.harnessVersion});u.error&&(t.stderr??yf.stderr).write(`devin-session-sync session-start: models capture warning: ${u.error}
package/bin/watcher CHANGED
@@ -119,10 +119,11 @@ Configuration is resolved in precedence order (highest first):
119
119
  Security: SAL_STORAGE_ENDPOINT, SAL_STORAGE_ACCESS_KEY_ID, and
120
120
  SAL_STORAGE_SECRET_ACCESS_KEY are only read from process.env or
121
121
  .devin/config.local.json \u2014 never from a file that might be committed to git.
122
- `;function gRe(e,t){return{local:TO.join(e,".devin","config.local.json"),project:TO.join(e,".devin","config.json"),userGlobal:TO.join(t,".config","devin","config.json")}}var hf={profile:aa,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:gRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:aa.harness,helpText:hRe};function r7(e,t=SRe.cwd()){return m_(hf,e,t)}import n7 from"node:process";async function s7(e=n7.cwd(),t=n7.env,r=hf.profile.securityBlocklist){return du(hf,e,t,r)}import HRe from"node:os";import y7 from"node:process";import{existsSync as yRe}from"node:fs";import{join as ca}from"node:path";function ERe(e){return[{label:"home-devin",path:ca(e.home,".devin")},{label:"home-devin-shared",path:ca(e.home,".devin-shared")},{label:"home-codeium",path:ca(e.home,".codeium")},{label:"home-windsurf",path:ca(e.home,".windsurf")},{label:"project-devin",path:ca(e.cwd,".devin")},{label:"project-windsurf",path:ca(e.cwd,".windsurf")}]}function h_(e,t=yRe){let r=pf(e),n=ERe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:ca(r,"sessions.db"),probes:n}}import{createHash as ARe}from"node:crypto";import{copyFileSync as bRe,existsSync as xRe,mkdtempSync as TRe,rmSync as ORe}from"node:fs";import{tmpdir as vRe}from"node:os";import{basename as IRe,join as f7}from"node:path";import{createHash as _Re}from"node:crypto";function o7(e){return`${e.session_id}\0${e.node_id}`}function i7(e){let{row_id:t,created_at:r,...n}=e;return _Re("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[o7(r)]!==i7(r))}function S_(e,t){let r={...e};for(let n of t)r[o7(n)]=i7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},a7=["sessions","message_nodes","prompt_history"];function OO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:CRe(e)}function CRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${a7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...a7],warnings:r}}function c7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as wRe}from"node:crypto";function E_(e){return wRe("sha256").update(JSON.stringify(e)).digest("hex")}function u7(e,t){return e.filter(r=>t[r.id]!==E_(r))}function __(e,t){let r={...e};for(let n of t)r[n.id]=E_(n);return r}import{createHash as RRe}from"node:crypto";function d7(e){return`${e.session_id}\0${e.tool_call_id}`}function l7(e){let{row_id:t,...r}=e;return RRe("sha256").update(JSON.stringify(r)).digest("hex")}function C_(e,t){return e.filter(r=>t[d7(r)]!==l7(r))}function w_(e,t){let r={...e};for(let n of t)r[d7(n)]=l7(n);return r}var R_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},p7=()=>import("node:sqlite");async function kRe(e=p7){let t;try{t=await e()}catch(r){throw new R_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new R_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function m7(e,t=p7){let{DatabaseSync:r}=await kRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return PRe(e,r,n)}}function PRe(e,t,r){try{return DRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function DRe(e,t){let r=TRe(f7(vRe(),"devin-session-sync-snapshot-")),n=f7(r,IRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;xRe(i)&&bRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),ORe(r,{recursive:!0,force:!0})}}}function h7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function A_(e,t,r=[]){return e.prepare(t).all(...r)}function NRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=A_(e,"SELECT * FROM sessions ORDER BY id");return u7(n,r)}function MRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(A_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function LRe(e,t,r){return t.knownTables.includes("prompt_history")?A_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function $Re(e,t,r){return t.knownTables.includes("tool_call_state")?C_(A_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function BRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function FRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?ARe("sha256").update(r.sql).digest("hex"):null}function URe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function jRe(e,t){let r=[];for(let n of t){let s=c7(n,URe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function g7(e,t=null){let r=OO(h7(e)),n={};for(let s of Object.keys(y_))n[s]=FRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:BRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...jRe(e,r.knownTables)]}}function S7(e,t){let r=OO(h7(e));return{tables:{sessions:NRe(e,r,t.sessionsContentHashes),messageNodes:MRe(e,r,t.messageNodesContentHashes),promptHistory:LRe(e,r,t.promptHistoryId),toolCallStates:$Re(e,r,t.toolCallStateHashes)},schema:r}}var ho={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function GRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??y7.env,r=e.home??HRe.homedir(),n=e.cwd??y7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function E7(e={}){let t=GRe(e),r=e.devinCliVersion??mf(),{db:n,close:s}=await m7(t);try{let{tables:o}=S7(n,ho),i=g7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import{execFile as XRe}from"node:child_process";import*as A7 from"node:fs/promises";import b7 from"node:path";import{promisify as QRe}from"node:util";function C7(e){try{let t=JSON.parse(e);return qRe(t)?t.families.flatMap(r=>VRe(r)):[]}catch{return[]}}function qRe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function zRe(e){return w7(e)&&Array.isArray(e.variants)}function VRe(e){return zRe(e)?e.variants.filter(t=>w7(t)).map(t=>WRe(e,t)):[]}function WRe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:_7(t.max_context_tokens),maxOutputTokens:_7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=KRe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function w7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function _7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function KRe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=YRe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function YRe(e){let t=vO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=vO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=vO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function vO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${JRe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function JRe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ZRe=QRe(XRe),eAe=1,tAe=9e5;async function IO(e){let t=e.dataDir,r=rAe(t),n=nAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??tAe,i=e.devinCliVersion??sAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await iAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??oAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function x7(e){let t=await IO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=C7(t.raw);return{candidates:[R7(e,"native/models-list.raw.json",t.raw),R7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function rAe(e){return b7.join(e,"devin","models-cache.json")}function nAe(e){return b7.join(e,"devin","models-cache.lock")}function sAe(e){return e.resolveVersion?e.resolveVersion():mf()}async function oAe(){let{stdout:e}=await ZRe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function iAe(e){try{let t=await A7.readFile(e,"utf8"),r=JSON.parse(t);if(aAe(r))return r}catch(t){let r=t.code}return{version:eAe,entries:{}}}function aAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function R7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}import*as Us from"node:fs/promises";import XAe from"node:os";import Ef from"node:path";import QAe from"node:process";var O7="sal/synthetic_subagent_kind",cAe="sal/synthetic_subagent_rawinput_profile",uAe="sal/synthetic_subagent_tool_call_id",dAe="sal/synthetic_subagent_source_node_id",lAe="sal/synthetic_subagent_is_background";function gf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x_(e){if(!e)return null;try{let t=JSON.parse(e);return gf(t)?t:null}catch{return null}}function fAe(e){let t=e._meta;if(!gf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function pAe(e){let t=[];for(let r of e){let n=x_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||fAe(n)!=="run_subagent")continue;let s=gf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function v7(e){let t=x_(e);if(!t)return null;let r=t.metadata;if(!gf(r))return null;let n=r.extensions;return gf(n)?n:null}function kO(e){let t=x_(e);return t&&typeof t.content=="string"?t.content:null}function mAe(e){let t=x_(e);return t&&typeof t.role=="string"?t.role:null}function hAe(e,t){return e?.includes(JSON.stringify(t))??!1}function gAe(e){let t=[];for(let r of e){let s=v7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var SAe="Background subagent started";function yAe(e,t){let r=e.find(s=>{if(mAe(s.chat_message)!=="system")return!1;let o=kO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=kO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=kO(t.node.chat_message);return n===null||n.startsWith(SAe)?null:{node:t.node,content:n,isBackground:!1}}function EAe(e){return v7(e)??{}}function I7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var T7=Number.MAX_SAFE_INTEGER;function _Ae(e,t){let r=gAe(e),n=[];for(let s of pAe(t)){if(s.task===null)continue;let o=r.find(i=>hAe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function CAe(e,t){return I7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[O7]:"prompt",[cAe]:e.invocation.profile,[uAe]:e.invocation.toolCallId})}function wAe(e,t,r,n){let s=yAe(e,t.tagged);return s===null?null:I7(t.tagged.node,r,n,"assistant",s.content,EAe(t.tagged.node.chat_message),{[O7]:"result",[dAe]:s.node.node_id,[lAe]:s.isBackground})}function k7(e,t){let r=[];for(let n of _Ae(e,t)){let s=T7-n.tagged.node.node_id*2,o=T7-n.tagged.node.node_id*2-1;r.push(CAe(n,s));let i=wAe(e,n,o,s);i&&r.push(i)}return r}function P7(e,t={}){let r=new Map(e.sessions.map(f=>[f.id,f])),n=Sf(e.messageNodes,f=>f.session_id),s=Sf(e.promptHistory,f=>f.session_id),o=Sf(e.toolCallStates,f=>f.session_id),i=RAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let f of bAe(e))a=xAe(c,a,r.get(f),{nodes:n.get(f)??[],prompts:s.get(f)??[],toolCalls:o.get(f)??[]},AAe(i,f));let u=t.priorWatermarks??ho;return{lines:c,text:BAe(c),watermarks:LAe(e,u)}}function RAe(e){if(e)return{nodesBySession:Sf(e.messageNodes,t=>t.session_id),toolCallsBySession:Sf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function AAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function bAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function xAe(e,t,r,n,s){let o=t;return r&&(e.push(NAe(r,o)),o+=1),o=kAe(e,o,n.nodes,n.toolCalls),o=TAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=DAe(e,o,n.prompts),o}function TAe(e,t,r,n,s){let o=t;for(let i of k7(r,n))s?.has(i.node_id)||(e.push(D7(i,o)),o+=1);return o}function OAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function vAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&IAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function IAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function kAe(e,t,r,n){let s=t,o=new Set;for(let i of OAe(r)){e.push(D7(i,s)),s+=1;for(let a of vAe(i,n,o))e.push(N7(a,s)),s+=1}return s=PAe(e,s,n,o),s}function PAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(N7(i,s)),s+=1;return s}function DAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(MAe(s,n)),n+=1;return n}function NAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function D7(e,t){return{type:"message",ts:null,order:t,...e}}function N7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function MAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function Sf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function LAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:w_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:$Ae(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:__(t.sessionsContentHashes,e.sessions)}}function $Ae(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function BAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
122
+ `;function gRe(e,t){return{local:TO.join(e,".devin","config.local.json"),project:TO.join(e,".devin","config.json"),userGlobal:TO.join(t,".config","devin","config.json")}}var hf={profile:aa,binName:"devin-sync",packageName:"@lucasschirm/devin-session-sync",logFolderEnvVar:"DEVIN_SYNC_LOG_PATH_FOLDER",resolveConfigPaths:gRe,localConfigDisplayPath:".devin/config.local.json",migrateManifestHarness:aa.harness,helpText:hRe};function r7(e,t=SRe.cwd()){return m_(hf,e,t)}import n7 from"node:process";async function s7(e=n7.cwd(),t=n7.env,r=hf.profile.securityBlocklist){return du(hf,e,t,r)}import HRe from"node:os";import y7 from"node:process";import{existsSync as yRe}from"node:fs";import{join as ca}from"node:path";function ERe(e){return[{label:"home-devin",path:ca(e.home,".devin")},{label:"home-devin-shared",path:ca(e.home,".devin-shared")},{label:"home-codeium",path:ca(e.home,".codeium")},{label:"home-windsurf",path:ca(e.home,".windsurf")},{label:"project-devin",path:ca(e.cwd,".devin")},{label:"project-windsurf",path:ca(e.cwd,".windsurf")}]}function h_(e,t=yRe){let r=pf(e),n=ERe(e).map(({label:s,path:o})=>({label:s,path:o,exists:t(o)}));return{dataRoot:r,sessionsDbPath:ca(r,"sessions.db"),probes:n}}import{createHash as ARe}from"node:crypto";import{copyFileSync as bRe,existsSync as xRe,mkdtempSync as TRe,rmSync as ORe}from"node:fs";import{tmpdir as vRe}from"node:os";import{basename as IRe,join as f7}from"node:path";import{createHash as _Re}from"node:crypto";function o7(e){return`${e.session_id}\0${e.node_id}`}function i7(e){let{row_id:t,created_at:r,...n}=e;return _Re("sha256").update(JSON.stringify(n)).digest("hex")}function g_(e,t){return Object.keys(t).length===0?[...e]:e.filter(r=>t[o7(r)]!==i7(r))}function S_(e,t){let r={...e};for(let n of t)r[o7(n)]=i7(n);return r}var y_={sessions:["id","working_directory","backend_type","model","agent_mode","created_at","last_activity_at","title","main_chain_id","cogs_json","workspace_dirs","hidden","metadata"],message_nodes:["row_id","session_id","node_id","parent_node_id","chat_message","created_at","metadata"],prompt_history:["id","content","timestamp","session_id","is_shell"],tool_call_state:["session_id","tool_call_id","tool_call_json","tool_call_update_json"]},a7=["sessions","message_nodes","prompt_history"];function OO(e){return e===16?{observedVersion:e,supported:!0,knownTables:Object.keys(y_),warnings:[]}:CRe(e)}function CRe(e){let t=e>16?"newer":"older",r=[`Unrecognized Devin sessions.db schema: refinery version ${e} is ${t} than the last verified version (16). Degrading to best-effort extraction of ${a7.join(", ")}; tool_call_state is skipped.`];return{observedVersion:e,supported:!1,knownTables:[...a7],warnings:r}}function c7(e,t){let r=new Set(y_[e]??[]);return t.filter(n=>!r.has(n))}import{createHash as wRe}from"node:crypto";function E_(e){return wRe("sha256").update(JSON.stringify(e)).digest("hex")}function u7(e,t){return e.filter(r=>t[r.id]!==E_(r))}function __(e,t){let r={...e};for(let n of t)r[n.id]=E_(n);return r}import{createHash as RRe}from"node:crypto";function d7(e){return`${e.session_id}\0${e.tool_call_id}`}function l7(e){let{row_id:t,...r}=e;return RRe("sha256").update(JSON.stringify(r)).digest("hex")}function C_(e,t){return e.filter(r=>t[d7(r)]!==l7(r))}function w_(e,t){let r={...e};for(let n of t)r[d7(n)]=l7(n);return r}var R_=class extends Error{constructor(t){super(`devin-session-sync requires Node.js >=22.13.0 (or >=23.4.0) for the built-in node:sqlite module, used to read Devin CLI's sessions.db. ${t} Upgrade Node.js to sync Devin sessions.`),this.name="DevinSqliteUnavailableError"}},p7=()=>import("node:sqlite");async function kRe(e=p7){let t;try{t=await e()}catch(r){throw new R_(`Failed to load node:sqlite: ${r.message}`)}if(typeof t.DatabaseSync!="function")throw new R_("node:sqlite loaded but DatabaseSync is unavailable.");return t}async function m7(e,t=p7){let{DatabaseSync:r}=await kRe(t);try{let n=new r(e,{readOnly:!0});return{db:n,close:()=>n.close()}}catch(n){return PRe(e,r,n)}}function PRe(e,t,r){try{return DRe(e,t)}catch(n){throw new Error(`Failed to open Devin sessions.db at ${e}: read-only open failed (${r.message}), and the snapshot-copy fallback also failed (${n.message}).`)}}function DRe(e,t){let r=TRe(f7(vRe(),"devin-session-sync-snapshot-")),n=f7(r,IRe(e));for(let o of["","-wal","-shm"]){let i=`${e}${o}`;xRe(i)&&bRe(i,`${n}${o}`)}let s=new t(n,{readOnly:!0});return{db:s,close:()=>{s.close(),ORe(r,{recursive:!0,force:!0})}}}function h7(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get())return 0;let r=e.prepare("SELECT MAX(version) AS max_version FROM refinery_schema_history").get();return Number(r?.max_version??0)}function A_(e,t,r=[]){return e.prepare(t).all(...r)}function NRe(e,t,r){if(!t.knownTables.includes("sessions"))return[];let n=A_(e,"SELECT * FROM sessions ORDER BY id");return u7(n,r)}function MRe(e,t,r){return t.knownTables.includes("message_nodes")?g_(A_(e,"SELECT * FROM message_nodes ORDER BY row_id"),r):[]}function LRe(e,t,r){return t.knownTables.includes("prompt_history")?A_(e,"SELECT * FROM prompt_history WHERE id > ? ORDER BY id",[r??-1]):[]}function $Re(e,t,r){return t.knownTables.includes("tool_call_state")?C_(A_(e,"SELECT rowid AS row_id, * FROM tool_call_state ORDER BY rowid"),r):[]}function BRe(e){return e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='refinery_schema_history'").get()?e.prepare("SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version").all().map(n=>({version:n.version,name:n.name,appliedOn:n.applied_on,checksum:n.checksum})):[]}function FRe(e,t){let r=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(t);return r?ARe("sha256").update(r.sql).digest("hex"):null}function URe(e,t){return e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}function jRe(e,t){let r=[];for(let n of t){let s=c7(n,URe(e,n));s.length>0&&r.push(`${n}: column(s) ${s.join(", ")} are captured (SELECT * always reads everything) but not yet listed in KNOWN_TABLE_COLUMNS \u2014 update it for documentation.`)}return r}function g7(e,t=null){let r=OO(h7(e)),n={};for(let s of Object.keys(y_))n[s]=FRe(e,s);return{devinCliVersion:t,refineryVersion:r.observedVersion,refineryMigrations:BRe(e),tableChecksums:n,supported:r.supported,warnings:[...r.warnings,...jRe(e,r.knownTables)]}}function S7(e,t){let r=OO(h7(e));return{tables:{sessions:NRe(e,r,t.sessionsContentHashes),messageNodes:MRe(e,r,t.messageNodesContentHashes),promptHistory:LRe(e,r,t.promptHistoryId),toolCallStates:$Re(e,r,t.toolCallStateHashes)},schema:r}}var ho={messageNodesContentHashes:{},toolCallStateHashes:{},promptHistoryId:null,sessionsContentHashes:{}};function GRe(e){if(e.sessionsDbPath)return e.sessionsDbPath;let t=e.env??y7.env,r=e.home??HRe.homedir(),n=e.cwd??y7.cwd();return h_({xdgDataHome:t.XDG_DATA_HOME,home:r,cwd:n}).sessionsDbPath}async function E7(e={}){let t=GRe(e),r=e.devinCliVersion??mf(),{db:n,close:s}=await m7(t);try{let{tables:o}=S7(n,ho),i=g7(n,r);return{tables:o,schemaDescriptor:i}}finally{s()}}import{execFile as XRe}from"node:child_process";import*as A7 from"node:fs/promises";import b7 from"node:path";import{promisify as QRe}from"node:util";function C7(e){try{let t=JSON.parse(e);return qRe(t)?t.families.flatMap(r=>VRe(r)):[]}catch{return[]}}function qRe(e){return typeof e=="object"&&e!==null&&"families"in e&&Array.isArray(e.families)}function zRe(e){return w7(e)&&Array.isArray(e.variants)}function VRe(e){return zRe(e)?e.variants.filter(t=>w7(t)).map(t=>WRe(e,t)):[]}function WRe(e,t){let r={modelUid:b_(t.model_uid),label:b_(t.label),familyUid:b_(e.family_uid),costTier:b_(t.cost_tier),maxContextTokens:_7(t.max_context_tokens),maxOutputTokens:_7(t.max_output_tokens)};if(typeof t.cost_summary=="string"&&t.cost_summary.length>0){let n=KRe(t.cost_summary);n.ok?r.pricing=n.value:(r.pricingUnavailableReason=n.reason,r.costSummaryRaw=t.cost_summary)}return r}function w7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:""}function _7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function KRe(e){let t=e.split("\xB7").map(n=>n.trim()),r={};for(let n of t){let s=YRe(n);s&&(s.kind==="Input"&&(r.inputPerMTok=s.value),s.kind==="Cached input"&&(r.cachedInputPerMTok=s.value),s.kind==="Output"&&(r.outputPerMTok=s.value))}return typeof r.inputPerMTok=="number"&&typeof r.cachedInputPerMTok=="number"&&typeof r.outputPerMTok=="number"?{ok:!0,value:r}:{ok:!1,reason:"unparsed-format"}}function YRe(e){let t=vO(e,"Input");if(t!==void 0)return{kind:"Input",value:t};let r=vO(e,"Cached input");if(r!==void 0)return{kind:"Cached input",value:r};let n=vO(e,"Output");if(n!==void 0)return{kind:"Output",value:n}}function vO(e,t){let r=new RegExp(`^\\$\\s*([0-9]+(?:\\.[0-9]+)?)\\s*/\\s*1M\\s+${JRe(t)}$`),n=e.match(r);if(!n)return;let s=Number(n[1]);if(Number.isFinite(s))return s}function JRe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ZRe=QRe(XRe),eAe=1,tAe=9e5;async function IO(e){let t=e.dataDir,r=rAe(t),n=nAe(t),s=e.now?.()??Date.now(),o=e.ttlMs??tAe,i=e.devinCliVersion??sAe(e),a=new Sr(n);try{return await a.withLock(async()=>{let c=await iAe(r),u=c.entries[i];if(u&&s-u.capturedAt<=o)return{...u};try{let g={raw:await(e.runModelsList??oAe)(),devinCliVersion:i,capturedAt:s};return c.entries[i]=g,await Si(r,JSON.stringify(c,null,2)),{...g}}catch(f){let h=f instanceof Error?f.message:String(f);return{raw:"",devinCliVersion:i,capturedAt:s,error:h}}})}catch(c){let u=c instanceof Error?c.message:String(c);return{raw:"",devinCliVersion:i,capturedAt:s,error:u}}}async function x7(e){let t=await IO(e);if(t.error)return{candidates:[],devinCliVersion:t.devinCliVersion,error:t.error};let r=C7(t.raw);return{candidates:[R7(e,"native/models-list.raw.json",t.raw),R7(e,"native/models.json",JSON.stringify(r,null,2))],devinCliVersion:t.devinCliVersion}}function rAe(e){return b7.join(e,"devin","models-cache.json")}function nAe(e){return b7.join(e,"devin","models-cache.lock")}function sAe(e){return e.resolveVersion?e.resolveVersion():mf()}async function oAe(){let{stdout:e}=await ZRe("devin",["models","list","--format","json"],{encoding:"utf8"});return e}async function iAe(e){try{let t=await A7.readFile(e,"utf8"),r=JSON.parse(t);if(aAe(r))return r}catch(t){let r=t.code}return{version:eAe,entries:{}}}function aAe(e){return typeof e=="object"&&e!==null&&"version"in e&&typeof e.version=="number"&&"entries"in e&&typeof e.entries=="object"&&e.entries!==null}function R7(e,t,r){let n=Ei({projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:r,sanitizer:s=>s});return{candidate:{projectId:e.projectId,sessionId:e.sessionId,scope:"runtime",relativePath:t,content:n.sanitized,sanitizer:s=>s},size:n.size,sha256:n.artifact.sha256}}import*as Us from"node:fs/promises";import XAe from"node:os";import Ef from"node:path";import QAe from"node:process";var O7="sal/synthetic_subagent_kind",cAe="sal/synthetic_subagent_rawinput_profile",uAe="sal/synthetic_subagent_tool_call_id",dAe="sal/synthetic_subagent_source_node_id",lAe="sal/synthetic_subagent_is_background";function gf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x_(e){if(!e)return null;try{let t=JSON.parse(e);return gf(t)?t:null}catch{return null}}function fAe(e){let t=e._meta;if(!gf(t))return null;let r=t["cognition.ai/inferenceToolName"];return typeof r=="string"?r:null}function pAe(e){let t=[];for(let r of e){let n=x_(r.tool_call_json);if(!n||typeof n.toolCallId!="string"||fAe(n)!=="run_subagent")continue;let s=gf(n.rawInput)?n.rawInput:null;t.push({toolCallId:n.toolCallId,task:s&&typeof s.task=="string"?s.task:null,profile:s&&typeof s.profile=="string"?s.profile:null})}return t}function v7(e){let t=x_(e);if(!t)return null;let r=t.metadata;if(!gf(r))return null;let n=r.extensions;return gf(n)?n:null}function kO(e){let t=x_(e);return t&&typeof t.content=="string"?t.content:null}function mAe(e){let t=x_(e);return t&&typeof t.role=="string"?t.role:null}function hAe(e,t){return e?.includes(JSON.stringify(t))??!1}function gAe(e){let t=[];for(let r of e){let s=v7(r.chat_message)?.["subagent/agent_id"];typeof s=="string"&&t.push({node:r,agentId:s})}return t}var SAe="Background subagent started";function yAe(e,t){let r=e.find(s=>{if(mAe(s.chat_message)!=="system")return!1;let o=kO(s.chat_message);return o===null?!1:o.startsWith("<subagent_completion_notification>")&&o.includes(`agent_id=${t.agentId}`)});if(r){let s=kO(r.chat_message);return s!==null?{node:r,content:s,isBackground:!0}:null}let n=kO(t.node.chat_message);return n===null||n.startsWith(SAe)?null:{node:t.node,content:n,isBackground:!1}}function EAe(e){return v7(e)??{}}function I7(e,t,r,n,s,o,i){return{row_id:-1,session_id:e.session_id,node_id:t,parent_node_id:r,chat_message:JSON.stringify({role:n,content:s,metadata:{extensions:o}}),created_at:e.created_at,metadata:JSON.stringify(i)}}var T7=Number.MAX_SAFE_INTEGER;function _Ae(e,t){let r=gAe(e),n=[];for(let s of pAe(t)){if(s.task===null)continue;let o=r.find(i=>hAe(i.node.chat_message,s.toolCallId));o&&n.push({invocation:s,tagged:o})}return n.sort((s,o)=>s.tagged.node.node_id-o.tagged.node.node_id)}function CAe(e,t){return I7(e.tagged.node,t,null,"user",e.invocation.task,{"subagent/agent_id":e.tagged.agentId},{[O7]:"prompt",[cAe]:e.invocation.profile,[uAe]:e.invocation.toolCallId})}function wAe(e,t,r,n){let s=yAe(e,t.tagged);return s===null?null:I7(t.tagged.node,r,n,"assistant",s.content,EAe(t.tagged.node.chat_message),{[O7]:"result",[dAe]:s.node.node_id,[lAe]:s.isBackground})}function k7(e,t){let r=[];for(let n of _Ae(e,t)){let s=T7-n.tagged.node.node_id*2,o=T7-n.tagged.node.node_id*2-1;r.push(CAe(n,s));let i=wAe(e,n,o,s);i&&r.push(i)}return r}function P7(e,t={}){let r=new Map(e.sessions.map(h=>[h.id,h])),n=Sf(e.messageNodes,h=>h.session_id),s=Sf(e.promptHistory,h=>h.session_id),o=Sf(e.toolCallStates,h=>h.session_id),i=RAe(t.subagentContext),a=t.orderOffset??0,c=[];for(let h of bAe(e))a=xAe(c,a,r.get(h),{nodes:n.get(h)??[],prompts:s.get(h)??[],toolCalls:o.get(h)??[]},AAe(i,h));let u=t.priorWatermarks??ho,f=t.skipText?"":BAe(c);return{lines:c,text:f,watermarks:LAe(e,u)}}function RAe(e){if(e)return{nodesBySession:Sf(e.messageNodes,t=>t.session_id),toolCallsBySession:Sf(e.toolCallStates,t=>t.session_id),excludeNodeIds:e.excludeNodeIds}}function AAe(e,t){if(e)return{nodes:e.nodesBySession.get(t)??[],toolCalls:e.toolCallsBySession.get(t)??[],excludeNodeIds:e.excludeNodeIds}}function bAe(e){let t=new Set;for(let r of e.sessions)t.add(r.id);for(let r of e.messageNodes)t.add(r.session_id);for(let r of e.promptHistory)t.add(r.session_id);for(let r of e.toolCallStates)t.add(r.session_id);return[...t].sort()}function xAe(e,t,r,n,s){let o=t;return r&&(e.push(NAe(r,o)),o+=1),o=kAe(e,o,n.nodes,n.toolCalls),o=TAe(e,o,s?.nodes??n.nodes,s?.toolCalls??n.toolCalls,s?.excludeNodeIds),o=DAe(e,o,n.prompts),o}function TAe(e,t,r,n,s){let o=t;for(let i of k7(r,n))s?.has(i.node_id)||(e.push(D7(i,o)),o+=1);return o}function OAe(e){let t=new Set(e.map(o=>o.node_id)),r=new Map;for(let o of e){if(o.parent_node_id===null)continue;let i=r.get(o.parent_node_id);i?i.push(o):r.set(o.parent_node_id,[o])}let n=e.filter(o=>o.parent_node_id===null||!t.has(o.parent_node_id)),s=[];for(;n.length>0;){n.sort((i,a)=>i.node_id-a.node_id);let o=n.shift();s.push(o),n.push(...r.get(o.node_id)??[])}return s}function vAe(e,t,r){let n=e.chat_message;if(!n)return[];let s=t.filter(o=>!r.has(o.tool_call_id)&&IAe(n,o)).sort((o,i)=>o.row_id-i.row_id);for(let o of s)r.add(o.tool_call_id);return s}function IAe(e,t){return e.includes(JSON.stringify(t.tool_call_id))}function kAe(e,t,r,n){let s=t,o=new Set;for(let i of OAe(r)){e.push(D7(i,s)),s+=1;for(let a of vAe(i,n,o))e.push(N7(a,s)),s+=1}return s=PAe(e,s,n,o),s}function PAe(e,t,r,n){let s=t,o=r.filter(i=>!n.has(i.tool_call_id)).sort((i,a)=>i.row_id-a.row_id);for(let i of o)e.push(N7(i,s)),s+=1;return s}function DAe(e,t,r){let n=t;for(let s of[...r].sort((o,i)=>o.id-i.id))e.push(MAe(s,n)),n+=1;return n}function NAe(e,t){return{type:"session",ts:e.last_activity_at??null,order:t,...e}}function D7(e,t){return{type:"message",ts:null,order:t,...e}}function N7(e,t){return{type:"tool_call",ts:null,order:t,...e}}function MAe(e,t){return{type:"prompt",ts:e.timestamp??null,order:t,...e}}function Sf(e,t){let r=new Map;for(let n of e){let s=t(n),o=r.get(s);o?o.push(n):r.set(s,[n])}return r}function LAe(e,t){return{messageNodesContentHashes:S_(t.messageNodesContentHashes,e.messageNodes),toolCallStateHashes:w_(t.toolCallStateHashes,e.toolCallStates),promptHistoryId:$Ae(t.promptHistoryId,e.promptHistory.map(r=>r.id)),sessionsContentHashes:__(t.sessionsContentHashes,e.sessions)}}function $Ae(e,t){let r=t.length===0?null:Math.max(...t);return e===null?r:r===null?e:Math.max(e,r)}function BAe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
123
123
  `)}
124
124
  `}function M7(e){let t=e.split(`
125
- `).filter(n=>n.length>0),r=t.map(UAe).filter(jAe);return r.length===0?{watermarks:ho,lineCount:0,messageNodeIds:new Set}:{watermarks:JAe(r),lineCount:t.length,messageNodeIds:FAe(r)}}function FAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function UAe(e){try{return JSON.parse(e)}catch{return}}function jAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function PO(e){let{type:t,ts:r,order:n,...s}=e;return s}function HAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function GAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function qAe(e){return typeof e.id=="string"}function zAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function VAe(e,t){let r=PO(t);return GAe(r)?{...e,toolCallStateHashes:w_(e.toolCallStateHashes,[r])}:e}function WAe(e,t){let r=PO(t);return qAe(r)?{...e,sessionsContentHashes:__(e.sessionsContentHashes,[r])}:e}function KAe(e,t){let r=PO(t);return zAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function YAe(e,t){switch(t.type){case"message":return KAe(e,t);case"prompt":return{...e,promptHistoryId:HAe(e.promptHistoryId,t.id)};case"tool_call":return VAe(e,t);case"session":return WAe(e,t);default:return e}}function JAe(e){let t=ho;for(let r of e)t=YAe(t,r);return t}function DO(e){return e.failed>0||e.errors.length>0}function yf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function ZAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ebe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function tbe(e){try{return await Us.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function rbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:C_(e.toolCallStates,t.toolCallStateHashes)}}async function nbe(e,t,r){let n=Ef.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>sbe(e,t,n))}async function sbe(e,t,r){let n=ebe(e,t),s=await tbe(r),o=s?M7(s):{watermarks:ho,lineCount:0,messageNodeIds:new Set},i=rbe(n,o.watermarks),{text:a}=P7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});return await Us.mkdir(Ef.dirname(r),{recursive:!0}),await Us.appendFile(r,a,"utf8"),r}function L7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function obe(e){let t=e.artifacts.filter(s=>L7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!L7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function ibe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function abe(e){let t;try{t=await Us.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await Us.readFile(Ef.join(e,n),"utf8")})}catch{}return r}async function cbe(e,t,r){return(await abe(Ef.join(e,".devin","plans"))).filter(o=>ibe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function ube(e,t,r){let n=Ef.join(e,"transcripts",`${t}.json`),s;try{s=await Us.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function dbe(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function lbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??QAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function fbe(e,t,r){let n=await wu({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return obe(n)}async function pbe(e,t,r,n,s){let o=e.config.projectId,i=await f_(t,e.config,{projectRoot:e.cwd}),a=await cbe(r,e.sessionId,o),c=await ube(n,e.sessionId,o),u=dbe(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function mbe(e,t){let r=await x7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&yf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function hbe(e,t){return JSON.stringify([e,t])}async function gbe(e,t,r){let n=hbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function Sbe(e,t,r,n){let s=[...r.errors];try{await cu({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=uu(o);s.includes(i)||s.push(i)}return s}async function ybe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await gbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>Vf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts})),c=au(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await Sbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function $7(e){let t=e.profile??aa,r=e.homeDir??XAe.homedir(),n=lbe(e,r);yf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await nbe(e.tables,e.sessionId,e.dataDir);yf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await fbe(e,t,s),{candidates:i,error:a}=await mbe(e,t),c=await pbe(e,o,r,n,i);yf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await ybe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),yf(e,DO(u)?"failure":"success",ZAe(u)),u}var U7=15e3;function j7(e){return F7.join(e,"devin","watcher-state.json")}async function _be(e){try{let t=await lu.readFile(j7(e),"utf8"),r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}async function Cbe(e,t){let r=j7(e);await lu.mkdir(F7.dirname(r),{recursive:!0}),await lu.writeFile(r,JSON.stringify(t,null,2),"utf8")}function B7(e){return e.length===0?-1:Math.max(...e.map(t=>t.row_id))}function wbe(e,t){let r=e.sessions.find(a=>a.id===t),n=B7(e.messageNodes.filter(a=>a.session_id===t)),s=B7(e.toolCallStates.filter(a=>a.session_id===t)),o=e.promptHistory.filter(a=>a.session_id===t).reduce((a,c)=>Math.max(a,c.id),-1),i=r?E_(r):null;return JSON.stringify([i,n,s,o])}function _f(e,t){e.write(`${new Date().toISOString()} devin-watcher: ${t}
125
+ `).filter(n=>n.length>0),r=t.map(UAe).filter(jAe);return r.length===0?{watermarks:ho,lineCount:0,messageNodeIds:new Set}:{watermarks:JAe(r),lineCount:t.length,messageNodeIds:FAe(r)}}function FAe(e){let t=new Set;for(let r of e)r.type==="message"&&typeof r.node_id=="number"&&t.add(r.node_id);return t}function UAe(e){try{return JSON.parse(e)}catch{return}}function jAe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function PO(e){let{type:t,ts:r,order:n,...s}=e;return s}function HAe(e,t){return typeof t!="number"||t<0?e:e===null?t:Math.max(e,t)}function GAe(e){return typeof e.row_id=="number"&&typeof e.session_id=="string"&&typeof e.tool_call_id=="string"}function qAe(e){return typeof e.id=="string"}function zAe(e){return typeof e.row_id=="number"&&e.row_id>=0&&typeof e.session_id=="string"&&typeof e.node_id=="number"}function VAe(e,t){let r=PO(t);return GAe(r)?{...e,toolCallStateHashes:w_(e.toolCallStateHashes,[r])}:e}function WAe(e,t){let r=PO(t);return qAe(r)?{...e,sessionsContentHashes:__(e.sessionsContentHashes,[r])}:e}function KAe(e,t){let r=PO(t);return zAe(r)?{...e,messageNodesContentHashes:S_(e.messageNodesContentHashes,[r])}:e}function YAe(e,t){switch(t.type){case"message":return KAe(e,t);case"prompt":return{...e,promptHistoryId:HAe(e.promptHistoryId,t.id)};case"tool_call":return VAe(e,t);case"session":return WAe(e,t);default:return e}}function JAe(e){let t=ho;for(let r of e)t=YAe(t,r);return t}function DO(e){return e.failed>0||e.errors.length>0}function yf(e,t,r){e.onProgress?.({type:t,timestamp:new Date().toISOString(),sessionId:e.sessionId,message:r})}function ZAe(e){let t=[];return e.uploaded>0&&t.push(`${e.uploaded} uploaded`),e.skipped>0&&t.push(`${e.skipped} skipped`),e.failed>0&&t.push(`${e.failed} failed`),e.errors.length>0&&t.push(`${e.errors.length} error(s)`),e.warnings.length>0&&t.push(`${e.warnings.length} warning(s)`),`session ${e.sessionId}: ${t.length>0?t.join(", "):"no changes"}`}function ebe(e,t){return{sessions:e.sessions.filter(r=>r.id===t),messageNodes:e.messageNodes.filter(r=>r.session_id===t),promptHistory:e.promptHistory.filter(r=>r.session_id===t),toolCallStates:e.toolCallStates.filter(r=>r.session_id===t)}}async function tbe(e){try{return await Us.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function rbe(e,t){return{sessions:e.sessions,messageNodes:g_(e.messageNodes,t.messageNodesContentHashes),promptHistory:e.promptHistory.filter(r=>r.id>(t.promptHistoryId??-1)),toolCallStates:C_(e.toolCallStates,t.toolCallStateHashes)}}async function nbe(e,t,r){let n=Ef.join(r,"devin","transcripts",`${t}.jsonl`);return new Sr(`${n}.lock`).withLock(()=>sbe(e,t,n))}async function sbe(e,t,r){let n=ebe(e,t),s=await tbe(r),o=s?M7(s):{watermarks:ho,lineCount:0,messageNodeIds:new Set},i=rbe(n,o.watermarks),{lines:a}=P7(i,{orderOffset:o.lineCount,priorWatermarks:o.watermarks,skipText:!0,subagentContext:{messageNodes:n.messageNodes,toolCallStates:n.toolCallStates,excludeNodeIds:o.messageNodeIds}});if(await Us.mkdir(Ef.dirname(r),{recursive:!0}),a.length>0){let c=await Us.open(r,"a");try{for(let u of a)await c.write(JSON.stringify(u)),await c.write(`
126
+ `);await c.sync()}finally{await c.close()}}return r}function L7(e){let t=e.replace(/\\/g,"/");return t7.some(r=>{if(r.endsWith("/**")){let n=r.slice(0,-3);return t===n||t.startsWith(`${n}/`)}return t===r||t.endsWith(`/${r}`)})}function obe(e){let t=e.artifacts.filter(s=>L7(s.relativePath));if(t.length===0)return e;let r=t.reduce((s,o)=>s+o.size,0),n=e.artifacts.filter(s=>!L7(s.relativePath));return{artifacts:n,errors:e.errors,totalBytes:e.totalBytes-r,filesDiscovered:n.length}}function NO(e,t,r,n,s){let o=Ei({projectId:e,sessionId:t,scope:r,relativePath:n,content:s});return{candidate:{projectId:e,sessionId:t,scope:r,relativePath:n,content:o.sanitized,sanitizer:i=>i},size:o.size,sha256:o.artifact.sha256}}function ibe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return;let r=(t[1]??"").split(/\r?\n/).find(n=>/^session:\s*/.test(n));if(r)return r.replace(/^session:\s*/,"").trim().replace(/^["']|["']$/g,"")}async function abe(e){let t;try{t=await Us.readdir(e)}catch{return[]}let r=[];for(let n of t)if(n.endsWith(".md"))try{r.push({fileName:n,content:await Us.readFile(Ef.join(e,n),"utf8")})}catch{}return r}async function cbe(e,t,r){return(await abe(Ef.join(e,".devin","plans"))).filter(o=>ibe(o.content)===t).map(o=>NO(r,t,"session",`plans/${o.fileName}`,o.content))}async function ube(e,t,r){let n=Ef.join(e,"transcripts",`${t}.json`),s;try{s=await Us.readFile(n,"utf8")}catch{return}return NO(r,t,"session","native/atif-transcript.json",s)}function dbe(e,t,r){let n=JSON.stringify(e,null,2);return NO(t,r,"runtime","native/schema-descriptor.json",n)}function lbe(e,t){if(e.dataRoot)return e.dataRoot;let r=e.env??QAe.env;return h_({xdgDataHome:r.XDG_DATA_HOME,home:t,cwd:e.cwd}).dataRoot}async function fbe(e,t,r){let n=await wu({projectId:e.config.projectId,sessionId:e.sessionId,workspaceRoot:e.cwd,transcriptPath:r,captureTranscripts:e.config.captureTranscripts,limits:e.config.limits,env:e.env,homeDir:e.homeDir},t);return obe(n)}async function pbe(e,t,r,n,s){let o=e.config.projectId,i=await f_(t,e.config,{projectRoot:e.cwd}),a=await cbe(r,e.sessionId,o),c=await ube(n,e.sessionId,o),u=dbe(e.schemaDescriptor,o,e.sessionId);return[...i,...a,...c?[c]:[],u,...s]}async function mbe(e,t){let r=await x7({dataDir:e.dataDir,projectId:e.config.projectId,sessionId:e.sessionId,devinCliVersion:e.models?.devinCliVersion??t.harnessVersion,resolveVersion:e.models?.resolveVersion,runModelsList:e.models?.runModelsList,ttlMs:e.models?.ttlMs,now:e.models?.now});return r.error&&yf(e,"progress",`warning: devin models capture failed: ${r.error}`),{candidates:r.candidates,error:r.error}}function hbe(e,t){return JSON.stringify([e,t])}async function gbe(e,t,r){let n=hbe(e.config.projectId,e.sessionId),s=await t.getSession(n);if(s)return s;let o={sessionId:e.sessionId,projectId:e.config.projectId,harness:r.harness,harnessVersion:r.harnessVersion,startedAt:new Date().toISOString()};return await t.setSession(n,o),o}async function Sbe(e,t,r,n){let s=[...r.errors];try{await cu({dataDir:e.dataDir,session:t,run:{...r,trigger:e.trigger},manifestArtifacts:n,storageAdapter:e.storageAdapter,captureTranscripts:e.config.captureTranscripts})}catch(o){let i=uu(o);s.includes(i)||s.push(i)}return s}async function ybe(e,t,r){let n=new xr(e.dataDir);await n.ensureDirectories();let s=await gbe(e,n,r),o=t.map(f=>f.candidate),i=YY({storageAdapter:e.storageAdapter,timeoutMs:e.config.timeouts.syncTimeoutMs}),a=await n.withState(f=>Vf({state:f,trigger:e.trigger,candidates:o,uploader:i,storageAdapter:e.storageAdapter,session:s,transcriptsCaptured:e.config.captureTranscripts}));for(let f of t)f.candidate.content="";let c=au(t,{uploaded:a.uploaded,skipped:a.skipped,failed:a.failed}),u=await Sbe(e,s,a,c);return{sessionId:e.sessionId,uploaded:a.filesUploaded,skipped:a.filesSkipped,failed:a.filesFailed,errors:u,warnings:[]}}async function $7(e){let t=e.profile??aa,r=e.homeDir??XAe.homedir(),n=lbe(e,r);yf(e,"progress",`extracting transcript for session ${e.sessionId}`);let s=await nbe(e.tables,e.sessionId,e.dataDir);e.releaseTablesAfterMaterialization&&(e.tables.sessions=[],e.tables.messageNodes=[],e.tables.promptHistory=[],e.tables.toolCallStates=[]),yf(e,"progress",`discovering artifacts for session ${e.sessionId}`);let o=await fbe(e,t,s),{candidates:i,error:a}=await mbe(e,t),c=await pbe(e,o,r,n,i);yf(e,"progress",`uploading ${c.length} artifact(s)`);let u=await ybe(e,c,t);return a&&!u.warnings.includes(a)&&u.warnings.push(a),yf(e,DO(u)?"failure":"success",ZAe(u)),u}var U7=15e3;function j7(e){return F7.join(e,"devin","watcher-state.json")}async function _be(e){try{let t=await lu.readFile(j7(e),"utf8"),r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}async function Cbe(e,t){let r=j7(e);await lu.mkdir(F7.dirname(r),{recursive:!0}),await lu.writeFile(r,JSON.stringify(t,null,2),"utf8")}function B7(e){return e.length===0?-1:Math.max(...e.map(t=>t.row_id))}function wbe(e,t){let r=e.sessions.find(a=>a.id===t),n=B7(e.messageNodes.filter(a=>a.session_id===t)),s=B7(e.toolCallStates.filter(a=>a.session_id===t)),o=e.promptHistory.filter(a=>a.session_id===t).reduce((a,c)=>Math.max(a,c.id),-1),i=r?E_(r):null;return JSON.stringify([i,n,s,o])}function _f(e,t){e.write(`${new Date().toISOString()} devin-watcher: ${t}
126
127
  `)}async function Rbe(e,t,r,n,s,o,i,a){try{return await $7({tables:t.tables,schemaDescriptor:t.schemaDescriptor,sessionId:e.id,cwd:e.working_directory??$n.cwd(),config:r,dataDir:n,storageAdapter:s,trigger:"file-changed",profile:o,env:i,onProgress:c=>_f(a,c.message)})}catch(c){let u=c instanceof Error?c.message:String(c);return _f(a,`session ${e.id} failed: ${u}`),{sessionId:e.id,uploaded:0,skipped:0,failed:1,errors:[u],warnings:[]}}}async function Abe(e,t,r){let n=await IO({dataDir:e.dataDir,devinCliVersion:e.profile.harnessVersion});n.error&&e.stderr.write(`devin-watcher: models capture warning: ${n.error}
127
128
  `);let s=await E7({env:e.env,devinCliVersion:e.profile.harnessVersion,sessionsDbPath:e.sessionsDbPath,home:e.homeDir}),o=0,i=0;for(let a of s.tables.sessions){let c=wbe(s.tables,a.id);if(t[a.id]===c)continue;o+=1;let u=await Rbe(a,s,e.config,e.dataDir,e.storageAdapter,e.profile,e.env,r);DO(u)?i+=1:t[a.id]=c}return{checked:s.tables.sessions.length,changed:o,failed:i}}async function bbe(e){let t=e.cwd??$n.cwd(),r=e.env??await s7(t),n=r7(r,t);if(!n.ok||!n.config)return{errorMessage:n.errorMessage??"configuration error"};let s=n.config,o=e.profile??aa;return{config:s,dataDir:e.dataDir??hi(r),env:r,storageAdapter:e.storageAdapter??ia(s),profile:o,stderr:e.stderr??$n.stderr,sessionsDbPath:e.sessionsDbPath,homeDir:e.homeDir}}function xbe(e){return $n.on("SIGTERM",e),$n.on("SIGINT",e),()=>{$n.off("SIGTERM",e),$n.off("SIGINT",e)}}async function Tbe(e,t,r,n){let s=t.pollIntervalMs??U7,o=await _be(e.dataDir),i=!1,a=xbe(()=>{i=!0}),c=0;try{for(;!i;){c+=1;try{let u=await Abe(e,o,r);await Cbe(e.dataDir,o),_f(r,`poll #${c}: ${u.checked} session(s) checked, ${u.changed} changed, ${u.failed} failed`)}catch(u){let f=u instanceof Error?u.message:String(u);n.write(`devin-watcher: poll #${c} failed: ${f}
128
129
  `)}if(t.maxPolls!==void 0&&c>=t.maxPolls||i)break;await Ebe(s)}}finally{a()}_f(r,"stopped")}async function Obe(e={}){let t=e.stdout??$n.stdout,r=e.stderr??$n.stderr,n=await bbe(e);return"errorMessage"in n?(r.write(`devin-watcher: ${n.errorMessage}
package/package.json CHANGED
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "name": "@lucasschirm/devin-session-sync",
3
- "version": "0.1.1",
4
- "private": false,
3
+ "version": "0.1.2",
5
4
  "type": "module",
6
5
  "license": "ISC",
7
6
  "description": "Devin CLI plugin adapter for the @lucasschirm/sal-sync session data sync engine (SQLite->JSONL extractor, devin-sync CLI, and sessions.db-watermark watcher).",