@anthropic-ai/claude-agent-sdk
Version:
SDK for building AI agents with Claude Code's capabilities. Programmatically interact with Claude to build autonomous agents that can understand codebases, edit files, and execute workflows.
19 lines (16 loc) • 9.11 kB
JavaScript
// (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
// Version: 0.3.333
//! symbol-dispose-prelude: defines Symbol.dispose and Symbol.asyncDispose if missing, for this bundle's `using`.
if (typeof Symbol.dispose !== 'symbol') {
try {
Symbol.dispose = Symbol.for('Symbol.dispose')
} catch {}
}
if (typeof Symbol.asyncDispose !== 'symbol') {
try {
Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose')
} catch {}
}
import{p,c,n,ht,g,R,o,je,D,G}from"./core-7ryne2zb.mjs";import{Nt,Mt,P,qe,ct,Ut,Ft,Ne,cn,Oe,pn,fn}from"./core-kczvrs8s.mjs";import{It}from"./core-qykjj4yw.mjs";import{pt}from"./core-4k0vthr8.mjs";import{Ye,le,Pe,sn}from"./core-snkzgbs5.mjs";import{randomUUID as B}from"crypto";import{constants as A}from"fs";import{open as Z,readdir as _,rm as ee,stat as te}from"fs/promises";import{dirname as re,join as w}from"path";import{mkdir as V}from"fs/promises";import{dirname as L}from"path";async function O(e,t,r,i){let s=sn(e,t),a=o({archived:r.archived,at:new Date().toISOString(),by:r.by});if(p()&&i!==void 0){let d=Pe(s);if(d!==void 0){let f=await i.write(d,a,{mode:384});if(!f.ok)throw Error("Session archive: record not writable via storage",{cause:f.error});return}}if(g())throw Error("Session archive: this process keeps no files");await V(L(s),{recursive:!0,mode:448}),await pt(s,a,384)}import{lstat as W,lutimes as J,mkdir as X,readFile as Ee,stat as Me,writeFile as Y}from"fs/promises";import{basename as h,dirname as q,join as j,resolve as Fe,sep as $e}from"path";function k(){return j(R(),"state","deleted-transcripts")}function T(e){return j(k(),Oe(e.toLowerCase()))}function E(e){return T(`${h(q(e))}/${h(e)}`)}function Q(e){return T(h(e))}async function y(e){if(e.length===0||g())return;await X(k(),{recursive:!0,mode:448}).catch(()=>{});for(let t of e.flatMap((r)=>[E(r),Q(r)])){await Y(t,"",{flag:"wx",mode:384}).catch(()=>{});let r=new Date;await J(t,r,r).catch(()=>{})}}async function M(e){return g()?void 0:W(E(e)).then(({mtimeMs:t})=>t,()=>{return})}var ne=64;function b(e){return p()?e:void 0}async function x(e,t,r={},i){if(!D(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let s=o({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
`;await z(e,s,r,b(i))}async function I(e,t,r={},i){if(!D(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let a=je(t).trim();if(!a)throw Error("tag must be non-empty (use null to clear)");t=a}let s=o({type:"tag",tag:t??"",sessionId:e})+`
`;await z(e,s,r,b(i))}async function N(e,t,r={},i){if(!D(e))throw new c(`Invalid sessionId: ${e}`,"setSessionArchived: invalid sessionId (must be a UUID)");let s=p(),a=s?i:void 0,d=new Set;for await(let{filePath:u}of cn(e,r.dir,Ye(a),s))d.add(u);if(d.size===0)throw new c(r.dir?`Session ${e} not found in project directory for ${r.dir}`:`Session ${e} not found in any project directory`,"setSessionArchived: session not found");let l=(await Promise.allSettled([...d].map((u)=>O(u,e,{archived:t,by:"sdk"},a)))).find((u)=>u.status==="rejected");if(l)throw l.reason}async function K(e,t={},r){if(!D(e))throw Error(`Invalid sessionId: ${e}`);let i=b(r),s=await oe(t,i);for(let d of s){let f=w(d,`${e}.jsonl`);if(p()&&i!==void 0){let u=ct(d,i.isKeySegment);if(u!==void 0){if(await ie(u,e,i,f))return;continue}}let l;try{({size:l}=await te(f))}catch(u){let m=n(u);if(m==="ENOENT"||m==="ENOTDIR")continue;throw u}if(l===0)continue;await y([f]),await ee(f,{force:!0}),await pn(w(d,e));return}let a=!1;for(let d of s){let f=w(d,`${e}.jsonl`);if(await M(f)===void 0)continue;if((await Promise.all([re(d),d].map(ht))).every(({kind:u})=>u==="directory"||u==="absent"))await pn(w(d,e),fn),a=!0}if(a)return;throw Error(t.dir?`Session ${e} not found in project directory for ${t.dir}`:`Session ${e} not found in any project directory`)}async function ie(e,t,r,i){let{backend:s,transcriptKey:a}=r,d=a(e,t),f=await s.statMeta(d);if(!f.ok){if(f.error.code==="NotFound")return!1;throw Error("Session delete: transcript unreadable via storage",{cause:f.error})}if((f.value.storedBytes??f.value.size)===0)return!1;await y([i]);for(let u of["transcript","sidecar"]){let m=await s.deleteScope({namespace:u,projectKey:e,sessionId:t});if(!m.ok)throw Error("Session delete: session directory not deletable via storage",{cause:m.error})}let l=await s.delete(d);if(!l.ok)throw Error("Session delete: transcript not deletable via storage",{cause:l.error});return!0}async function oe(e,t){if(e.dir){let i=await Ut(e.dir,Nt(t,p())),s=await F(i,t),a;try{a=await It(i)}catch{a=[]}for(let d of a){if(d===i)continue;s.push(...await F(d,t))}return s}let r=P();if(p()&&t!==void 0){let i=await U(t);if(i===void 0)return[];if(i.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return i.names.map((s)=>w(r,s))}try{return(await _(r,{withFileTypes:!0})).filter((s)=>s.isDirectory()||s.isSymbolicLink()).map((s)=>w(r,s.name))}catch{return[]}}async function F(e,t){let r=le(t);if(r===void 0||!r.hoverRestOn)return Ne(e);let i=await Ne(e,r),s=qe(e),a=process.platform==="win32",d=[];for(let f of i)if(f===s||await Ft(f,e,a,r))d.push(f);return d}async function U(e){let t=[],r,i=0;try{do{let s=await e.backend.listEntries({namespace:"transcript"},{skipScopeStats:!0,...r!==void 0&&{cursor:r}});if(!s.ok)return i===0?void 0:{names:t,laterPageFailed:!0};for(let a of s.value.items){let d=Mt(a,e.isKeySegment);if(d!==void 0)t.push(d)}r=s.value.cursor}while(r&&++i<ne);return{names:t,laterPageFailed:Boolean(r)}}catch{return i===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function z(e,t,r,i){let s=`${e}.jsonl`;if(r.dir){let f=await Ut(r.dir,Nt(i,p()));for(let u of await Ne(f,le(i)))if(await S(w(u,s),t,v(u,e,i)))return;let l;try{l=await It(f)}catch{l=[]}for(let u of l){if(u===f)continue;for(let m of await Ne(u,le(i)))if(await S(w(m,s),t,v(m,e,i)))return}throw Error(`Session ${e} not found in project directory for ${r.dir}`)}let a=P();if(p()&&i!==void 0){let f=await U(i);if(f===void 0)throw new c(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:l}=f;for(let u of l){let m=w(a,u);if(await S(w(m,s),t,v(m,e,i)))return}throw new c(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let d;try{d=await _(a)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let f of d)if(await S(w(a,f,s),t))return;throw Error(`Session ${e} not found in any project directory`)}async function S(e,t,r){if(p()&&r!==void 0)return se(r,t);let i;try{i=await Z(e,A.O_WRONLY|A.O_APPEND)}catch(s){let a=n(s);if(a==="ENOENT"||a==="ENOTDIR")return!1;throw s}try{let{size:s}=await i.stat();if(s===0)return!1;let a=process.platform==="win32"?s:void 0,d=Buffer.from(t,"utf8"),f=0;while(f<d.length){let{bytesWritten:l}=await i.write(d,f,d.length-f,a);if(l<=0)throw new c(`tryAppend: short write to ${e} stalled with ${d.length-f} bytes remaining`,"tryAppend: zero-progress short write");if(f+=l,a!==void 0)a+=l}return!0}finally{await i.close()}}async function se({backend:e,key:t},r){let i=await e.append(t,[{data:r}],{precondition:{type:"ifExists",nonEmpty:!0}});if(!i.ok){if(i.error.code==="NotFound")return!1;throw Error("Session append: transcript not writable via storage",{cause:i.error})}return!0}function v(e,t,r){if(!p()||r===void 0)return;let i=ct(e,r.isKeySegment);return i===void 0?void 0:{backend:r.backend,key:r.transcriptKey(i,t)}}async function wt(e,t,r){if(r?.sessionStore)return ae(r.sessionStore,e,t,r.dir);return x(e,t,r)}async function St(e,t,r){if(r?.sessionStore)return ce(r.sessionStore,e,t,r.dir);return I(e,t,r)}async function gt(e,t){return C(e,!0,t)}async function yt(e,t){return C(e,!1,t)}async function vt(e,t){if(!D(e))throw new c(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let r=G(t.dir);await t.sessionStore.delete({projectKey:r,sessionId:e});return}return K(e,t)}async function C(e,t,r){if(r?.sessionStore)throw new c("Archiving is not supported with sessionStore: a SessionStore holds transcript entries, and the archived mark is not one","setSessionArchived: sessionStore is not supported");return N(e,t,r)}async function ae(e,t,r,i){if(!D(t))throw new c(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!r.trim())throw Error("title must be non-empty");let s=G(i);await e.append({projectKey:s,sessionId:t},[{type:"custom-title",customTitle:r.trim(),sessionId:t,uuid:B(),timestamp:new Date().toISOString()}])}async function ce(e,t,r,i){if(!D(t))throw new c(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(r!==null){let a=je(r).trim();if(!a)throw Error("tag must be non-empty (use null to clear)");r=a}let s=G(i);await e.append({projectKey:s,sessionId:t},[{type:"tag",tag:r??"",sessionId:t,uuid:B(),timestamp:new Date().toISOString()}])}export{gt as archiveSession,vt as deleteSession,wt as renameSession,St as tagSession,yt as unarchiveSession};