UNPKG

@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) • 8.25 kB
// (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.314 //! 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{c,s,l,r,n,ne,Be,L,st,at,z,Te,Ke,lt,je,we,W}from"./core-a9vq6p1m.mjs";import{randomUUID as D}from"crypto";import{constants as v}from"fs";import{open as Q,readdir as x,rm as _,stat as ee}from"fs/promises";import{join as g}from"path";class I{available=void 0;probing=void 0;procUnreadableLogged=!1}var Ve=new s(()=>new I);var j=["commands","agents","output-styles","skills","workflows","routines","themes","rules","session-env","uploads","mcp-skill-archives","usage-data","mcp-discovery-cache"];var pn=new Set(j),mn=`must be one of the userConfigDir directory names (${j.join(", ")})`,k=["installed","marketplaces","flagged","catalog","inUseSweep"];var gn=new Set(k),hn=`must be one of the pluginRegistry files (${k.join(", ")})`,R=["manifest","catalog"];var yn=new Set(R),Sn=`must be one of the marketplaceCache forms (${R.join(", ")})`;var w=["world"];var bn=new Set(w),En=`must be one of the session journal names (${w.join(", ")})`;var P=["backup","corrupted"];var In=new Set(P),jn=`must be one of the global-config copy kinds (${P.join(", ")})`;var B="cloud-snapshots";var J=new Set(["memory","tiny_memory","bagel",B,"bridge-pointer.json",".session-aliases"]);var C=".cast",kn=`<stamp>${C} inside a session's folder is that session's terminal recording stream: address it as keys.recording(projectKey, sessionId, stamp)`;var q=[".ccr-tip.json",".precompact.json",C],Rn=`must not end with ${q.join(", ")}: those name a session's project-level sibling files`;var X=".dir-sync.json",wn=`must not end with ${X}: that name is reserved for a cloud session's record at the project level`;var Pn=`${[...J].join(", ")} are reserved: they name project-level entries, not sessions`;var Z="timeline.jsonl",Cn=`${Z} is the job's timeline stream: address it as keys.jobTimeline(jobId)`;function y(e){return e===void 0?void 0:{source:e,hoverRestOn:c()}}var re=64;function E(e){return c()?e:void 0}async function K(e,t,a={},o){if(!L(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let i=n({type:"custom-title",customTitle:t.trim(),sessionId:e})+` `;await T(e,i,a,E(o))}async function A(e,t,a={},o){if(!L(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let u=ne(t).trim();if(!u)throw Error("tag must be non-empty (use null to clear)");t=u}let i=n({type:"tag",tag:t??"",sessionId:e})+` `;await T(e,i,a,E(o))}async function F(e,t={},a){if(!L(e))throw Error(`Invalid sessionId: ${e}`);let o=E(a);for(let i of await ae(t,o)){if(c()&&o!==void 0){let d=Ke(i,o.isKeySegment);if(d!==void 0){if(await te(d,e,o))return;continue}}let u=g(i,`${e}.jsonl`),f;try{({size:f}=await ee(u))}catch(d){let p=r(d);if(p==="ENOENT"||p==="ENOTDIR")continue;throw d}if(f===0)continue;await _(u,{force:!0}),await _(g(i,e),{recursive:!0,force:!0});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 te(e,t,a){let{backend:o,transcriptKey:i}=a,u=i(e,t),f=await o.statMeta(u);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;for(let p of["transcript","sidecar"]){let m=await o.deleteScope({namespace:p,projectKey:e,sessionId:t});if(!m.ok)throw Error("Session delete: session directory not deletable via storage",{cause:m.error})}let d=await o.delete(u);if(!d.ok)throw Error("Session delete: transcript not deletable via storage",{cause:d.error});return!0}async function ae(e,t){if(e.dir){let o=await lt(e.dir,st(t,c())),i=await O(o,t),u;try{u=await Be(o)}catch{u=[]}for(let f of u){if(f===o)continue;i.push(...await O(f,t))}return i}let a=z();if(c()&&t!==void 0){let o=await N(t);if(o===void 0)return[];if(o.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return o.names.map((i)=>g(a,i))}try{return(await x(a,{withFileTypes:!0})).filter((i)=>i.isDirectory()||i.isSymbolicLink()).map((i)=>g(a,i.name))}catch{return[]}}async function O(e,t){let a=y(t);if(a===void 0||!a.hoverRestOn)return we(e);let o=await we(e,a),i=Te(e),u=process.platform==="win32",f=[];for(let d of o)if(d===i||await je(d,e,u,a))f.push(d);return f}async function N(e){let t=[],a,o=0;try{do{let i=await e.backend.listEntries({namespace:"transcript"},{skipScopeStats:!0,...a!==void 0&&{cursor:a}});if(!i.ok)return o===0?void 0:{names:t,laterPageFailed:!0};for(let u of i.value.items){let f=at(u,e.isKeySegment);if(f!==void 0)t.push(f)}a=i.value.cursor}while(a&&++o<re);return{names:t,laterPageFailed:Boolean(a)}}catch{return o===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function T(e,t,a,o){let i=`${e}.jsonl`;if(a.dir){let d=await lt(a.dir,st(o,c()));for(let m of await we(d,y(o)))if(await S(g(m,i),t,b(m,e,o)))return;let p;try{p=await Be(d)}catch{p=[]}for(let m of p){if(m===d)continue;for(let h of await we(m,y(o)))if(await S(g(h,i),t,b(h,e,o)))return}throw Error(`Session ${e} not found in project directory for ${a.dir}`)}let u=z();if(c()&&o!==void 0){let d=await N(o);if(d===void 0)throw new l(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:p}=d;for(let m of p){let h=g(u,m);if(await S(g(h,i),t,b(h,e,o)))return}throw new l(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let f;try{f=await x(u)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let d of f)if(await S(g(u,d,i),t))return;throw Error(`Session ${e} not found in any project directory`)}async function S(e,t,a){if(c()&&a!==void 0)return se(a,t);let o;try{o=await Q(e,v.O_WRONLY|v.O_APPEND)}catch(i){let u=r(i);if(u==="ENOENT"||u==="ENOTDIR")return!1;throw i}try{let{size:i}=await o.stat();if(i===0)return!1;let u=process.platform==="win32"?i:void 0,f=Buffer.from(t,"utf8"),d=0;while(d<f.length){let{bytesWritten:p}=await o.write(f,d,f.length-d,u);if(p<=0)throw new l(`tryAppend: short write to ${e} stalled with ${f.length-d} bytes remaining`,"tryAppend: zero-progress short write");if(d+=p,u!==void 0)u+=p}return!0}finally{await o.close()}}async function se({backend:e,key:t},a){let o=await e.append(t,[{data:a}],{precondition:{type:"ifExists",nonEmpty:!0}});if(!o.ok){if(o.error.code==="NotFound")return!1;throw Error("Session append: transcript not writable via storage",{cause:o.error})}return!0}function b(e,t,a){if(!c()||a===void 0)return;let o=Ke(e,a.isKeySegment);return o===void 0?void 0:{backend:a.backend,key:a.transcriptKey(o,t)}}async function sr(e,t,a){if(a?.sessionStore)return oe(a.sessionStore,e,t,a.dir);return K(e,t,a)}async function or(e,t,a){if(a?.sessionStore)return ie(a.sessionStore,e,t,a.dir);return A(e,t,a)}async function ir(e,t){if(!L(e))throw new l(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let a=W(t.dir);await t.sessionStore.delete({projectKey:a,sessionId:e});return}return F(e,t)}async function oe(e,t,a,o){if(!L(t))throw new l(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!a.trim())throw Error("title must be non-empty");let i=W(o);await e.append({projectKey:i,sessionId:t},[{type:"custom-title",customTitle:a.trim(),sessionId:t,uuid:D(),timestamp:new Date().toISOString()}])}async function ie(e,t,a,o){if(!L(t))throw new l(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(a!==null){let u=ne(a).trim();if(!u)throw Error("tag must be non-empty (use null to clear)");a=u}let i=W(o);await e.append({projectKey:i,sessionId:t},[{type:"tag",tag:a??"",sessionId:t,uuid:D(),timestamp:new Date().toISOString()}])}export{ir as deleteSession,sr as renameSession,or as tagSession};