@xeno-corporation/xeno-agent-sdk 0.6.1 → 0.6.3
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/dist/agents/index.js +6 -5
- package/dist/control-plane/index.js +2 -2
- package/dist/electron/index.js +90 -90
- package/dist/hooks/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +198 -197
- package/dist/mcp/index.js +2 -2
- package/dist/session/index.js +9 -9
- package/dist/utils/index.js +16 -12
- package/package.json +5 -3
package/dist/agents/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`)}}
|
|
1
|
+
import{existsSync as D,mkdirSync as M,readFileSync as B,readdirSync as N,writeFileSync as F}from"fs";import{homedir as C}from"os";import{basename as W,dirname as Y,join as g,parse as U,resolve as _}from"path";function $(n){let t=O(n);return{frontmatter:t.frontmatter,content:t.content.trim()}}function O(n){let t=n.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:n};let r=t.search(/\r?\n/);if(r<0||t.slice(0,r).trim()!=="---")return{frontmatter:{},content:n};let e=t.slice(r+(t[r]==="\r"?2:1)),i=e.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=e.slice(0,i.index),s=i[0],l=i.index+s.length;return{frontmatter:S(o),content:e.slice(l)}}function S(n){let t={},r=n.split(/\r?\n/);for(let e=0;e<r.length;e+=1){let i=r[e];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${e+1}.`);let o=L(i,e+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=b(o.value,e+1);continue}let s=R(r,e+1);t[o.key]=s.value,e=s.nextIndex-1}return t}function R(n,t){let r=[],e=t;for(;e<n.length;e+=1){let o=n[e];if(!o.trim()){r.push(o);continue}if(!/^\s/.test(o))break;r.push(o.replace(/^ {2}/,""))}let i=r.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:e}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>b(o.trimStart().slice(2),t+s+1)),nextIndex:e}:{value:S(r.join(`
|
|
2
|
+
`)),nextIndex:e}}function L(n,t){let r=n.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${t}.`);let e=n.slice(0,r).trim(),i=n.slice(r+1).trim();if(!e)throw new Error(`Invalid YAML key at line ${t}.`);return{key:e,value:i}}function b(n,t){if(n==="")return"";if(n==="[]")return[];if(n==="{}")return{};if(n==="true")return!0;if(n==="false")return!1;if(n==="null"||n==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(n))return Number(n);if(n.startsWith('"'))return x(n,t);if(n.startsWith("'")){if(!n.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return n.slice(1,-1).replace(/''/g,"'")}if(n.startsWith("[")||n.startsWith("{"))return x(n,t);if(n.includes("[")||n.includes("]")||n.includes("{")||n.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return n}function x(n,t){try{return JSON.parse(n)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}var v=/^[a-z][a-z0-9_-]{0,63}$/;function z(){return process.env.XENO_AGENT_HOME?.trim()||g(C(),".xeno-agent")}function j(n=z()){return g(n,"agents")}function T(n){return _(n)}function H(n){let t=Y(n);return t===n?n:t}function J(n=process.cwd()){let t=T(n),r=[],e=t;for(;;){let i=g(e,".xeno","agents");D(i)&&r.push(i);let o=H(e);if(o===e)break;e=o}return r.reverse()}function q(n=process.cwd()){return g(T(n),".xeno","agents")}function G(n){return D(n)?N(n,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".md")).map(t=>g(n,t.name)).sort((t,r)=>t.localeCompare(r)):[]}function w(n){if(typeof n!="string")return;let t=n.trim();return t.length>0?t:void 0}function h(n){return Array.isArray(n)?n.map(t=>String(t).trim()).filter(Boolean):typeof n=="string"?n.split(",").map(t=>t.trim()).filter(Boolean):[]}function V(n){return U(W(n)).name.toLowerCase()}function E(n){return v.test(n)}function K(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function X(n){if(typeof n!="string")return;let t=n.trim().toLowerCase();if(t==="inherit")return"inherit";if(t==="none"||t==="off"||t==="disabled")return"none";if(t==="read"||t==="readonly"||t==="read-only")return"readOnly";if(t==="default"||t==="standard")return"default";if(t==="full"||t==="fullaccess"||t==="full-access")return"fullAccess"}function Q(n){if(n===void 0)return;if(typeof n=="string"||Array.isArray(n)){let o=h(n);return o.length>0?{allow:o}:void 0}if(!K(n))return;let t=h(n.allow),r=h(n.deny),e=X(n.mode),i={};return e&&(i.mode=e),t.length>0&&(i.allow=t),r.length>0&&(i.deny=r),Object.keys(i).length>0?i:void 0}function Z(n){let t=[];return E(n.name)||t.push(`Invalid agent name "${n.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),n.prompt.trim().length===0&&t.push("Agent definition body is empty."),t}function nn(n,t,r){let e=B(n,"utf8"),i=$(e),o=i.frontmatter,s=V(n),l=w(o.name)?.toLowerCase()??s,u=i.content.trim(),p=Z({name:l,prompt:u});if(p.length>0)throw new Error(p.join(" "));let d=w(o.description),c=w(o.model),a=Q(o.tools);return{name:l,scope:t,path:n,...d?{description:d}:{},...c?{model:c}:{},tags:h(o.tags),prompt:u,active:!0,priority:r,...a?{toolPolicy:a}:{}}}function m(n,t,r,e,i){for(let o of G(n))try{e.push(nn(o,t,r))}catch(s){i.push({path:o,scope:t,message:s instanceof Error?s.message:String(s)})}}function tn(n){let t=new Map;for(let r of n){let e=t.get(r.name);(!e||r.priority>e.priority)&&t.set(r.name,r)}return t}function en(n,t){let r=t.get(n.name),e=r?.path===n.path;return{name:n.name,scope:n.scope,path:n.path,...n.description?{description:n.description}:{},...n.model?{model:n.model}:{},tags:n.tags,prompt:n.prompt,active:e,...n.toolPolicy?{toolPolicy:n.toolPolicy}:{},...!e&&r?{shadowedBy:{name:r.name,scope:r.scope,path:r.path}}:{}}}function I(n=process.cwd(),t={}){let r=t.cwd??n,e=t.userDir??j(t.agentHome),i=t.projectDirs??J(r),o=t.pluginDirs??[],s=t.builtInDirs??[],l=[],u=[];t.includeUser!==!1&&m(e,"user",0,l,u),t.includeProject!==!1&&i.forEach((c,a)=>m(c,"project",100+a,l,u)),t.includePlugins&&o.forEach((c,a)=>m(c,"plugin",1e3+a,l,u)),t.includeBuiltIns&&s.forEach((c,a)=>m(c,"built-in",2e3+a,l,u));let p=tn(l),d=l.map(c=>en(c,p));return d.sort((c,a)=>{if(c.active!==a.active)return c.active?-1:1;let P=c.name.localeCompare(a.name);return P!==0?P:c.path.localeCompare(a.path)}),{definitions:d,issues:u,searchPaths:{...t.includeUser!==!1?{user:e}:{},project:t.includeProject===!1?[]:i,plugin:t.includePlugins?o:[],builtIn:t.includeBuiltIns?s:[]}}}function fn(n,t=process.cwd(),r={}){let e=n.trim().toLowerCase(),i=I(t,r);return{definition:i.definitions.find(o=>o.active&&o.name===e)??null,scan:i}}var A=class{constructor(t={}){this.options=t}options;scan(t=this.options.cwd??process.cwd()){return I(t,this.options)}},k=class{constructor(t=new A){this.loader=t}loader;resolve(t,r=process.cwd()){let e=this.loader.scan(r),i=t.trim().toLowerCase();return{definition:e.definitions.find(o=>o.active&&o.name===i)??null,scan:e}}};function y(n){if(!n||n.length===0)return;let t=Array.from(new Set(n.map(r=>r.trim()).filter(Boolean)));return t.length>0?t:void 0}function rn(n,t){if(!n&&!t)return;if(!n)return y(t);if(!t)return y(n);let r=new Set(t);return y(n.filter(e=>r.has(e)))}function on(n,t){let r={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},e=t??"inherit",i=n??"inherit";return r[e]<=r[i]?e:i}function gn(n,t={}){let r=n.toolPolicy??{},e={mode:on(r.mode,t.mode)},i=rn(t.allow,r.allow),o=y([...t.deny??[],...r.deny??[]]);return i&&(e.allow=i),o&&(e.deny=o),e}function dn(n){return{name:`custom-agent:${n.name}`,order:20,provide(){let t=["","","# Custom Agent",`Active agent: ${n.name}`,`Definition scope: ${n.scope}`,`Definition path: ${n.path}`];return n.description&&t.push(`Description: ${n.description}`),t.push("",n.prompt),t.join(`
|
|
3
|
+
`)}}}function pn(n){return{name:n.name,scope:n.scope,path:n.path,...n.description?{description:n.description}:{},...n.model?{model:n.model}:{},tags:n.tags,active:n.active,...n.toolPolicy?{toolPolicy:n.toolPolicy}:{},...n.shadowedBy?{shadowedBy:n.shadowedBy}:{}}}function f(n,t){return n.length>=t?n:n+" ".repeat(t-n.length)}function mn(n,t){let r=[];if(n.length===0)r.push("No custom agent definitions found.");else{r.push(`${f("name",22)} ${f("scope",8)} ${f("status",9)} description`),r.push(`${"-".repeat(22)} ${"-".repeat(8)} ${"-".repeat(9)} ${"-".repeat(32)}`);for(let e of n){let i=e.active?"active":"shadowed";r.push(`${f(e.name,22)} ${f(e.scope,8)} ${f(i,9)} ${e.description??""}`)}}if(t.length>0){r.push("","Invalid definitions:");for(let e of t)r.push(`- ${e.path}: ${e.message}`)}return r.join(`
|
|
3
4
|
`)+`
|
|
4
|
-
`}function
|
|
5
|
-
`)}function
|
|
6
|
-
`);return
|
|
5
|
+
`}function hn(n){let t=[`Agent: ${n.name}`,`Scope: ${n.scope}`,`Path: ${n.path}`,`Status: ${n.active?"active":"shadowed"}`];return n.description&&t.push(`Description: ${n.description}`),n.model&&t.push(`Model: ${n.model}`),n.tags.length>0&&t.push(`Tags: ${n.tags.join(", ")}`),n.toolPolicy&&t.push(`Tools: ${JSON.stringify(n.toolPolicy)}`),n.shadowedBy&&t.push(`Shadowed by: ${n.shadowedBy.scope} ${n.shadowedBy.path}`),t.push("",n.prompt,""),t.join(`
|
|
6
|
+
`)}function yn(n){let t=n.name.trim().toLowerCase();if(!E(t))throw new Error(`Invalid agent name "${n.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`);let r=n.scope==="user"?j(n.agentHome):q(n.cwd??process.cwd());M(r,{recursive:!0});let e=g(r,`${t}.md`);if(D(e)&&!n.force)throw new Error(`Agent definition already exists: ${e}`);let i=n.description?.trim()||`${t} custom agent`,o=["---",`name: ${t}`,`description: ${JSON.stringify(i)}`,"tags: []","---","",`You are ${t}. Replace this paragraph with precise operating instructions, constraints, tools policy, verification expectations, and the kind of work this agent should own.`,""].join(`
|
|
7
|
+
`);return F(e,o,"utf8"),e}export{A as AgentDefinitionLoader,k as AgentDefinitionResolver,yn as createAgentDefinitionFile,dn as createAgentDefinitionPromptSection,J as getProjectAgentDefinitionDirs,q as getProjectAgentDefinitionsDir,j as getUserAgentDefinitionsDir,E as isValidAgentDefinitionName,hn as renderAgentDefinition,mn as renderAgentDefinitions,fn as resolveAgentDefinition,gn as resolveAgentToolPolicy,I as scanAgentDefinitions,pn as toAgentDefinitionMetadata,Z as validateAgentDefinition};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as J}from"crypto";import{appendFileSync as M,existsSync as y,mkdirSync as d,readFileSync as x,readdirSync as U,renameSync as z,rmSync as j,writeFileSync as l}from"fs";import{homedir as q}from"os";import{basename as P,dirname as L,join as u,resolve as B}from"path";var f="0.6.
|
|
1
|
+
import{randomUUID as J}from"crypto";import{appendFileSync as M,existsSync as y,mkdirSync as d,readFileSync as x,readdirSync as U,renameSync as z,rmSync as j,writeFileSync as l}from"fs";import{homedir as q}from"os";import{basename as P,dirname as L,join as u,resolve as B}from"path";var f="0.6.3";import{mkdirSync as O,readFileSync as V,rmSync as v,writeFileSync as _}from"fs";import{hostname as k}from"os";import{dirname as N}from"path";function b(){return new Date().toISOString()}function I(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function w(r){try{return JSON.parse(V(r,"utf8"))}catch{return null}}function T(r){if(!r||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function F(r){return r.hostname!==k()?!0:T(r.pid)}function h(r,t){O(N(r),{recursive:!0}),_(r,JSON.stringify(t,null,2)+`
|
|
2
2
|
`,{encoding:"utf8",flag:"wx"})}function $(r,t){let e=w(r);e?.pid!==t.pid||e.hostname!==t.hostname||v(r,{force:!0})}function S(r,t,e){let n=b(),s={schemaVersion:1,name:t,pid:process.pid,hostname:k(),processStartedAt:I(),version:e,acquiredAt:n,updatedAt:n};try{h(r,s)}catch(a){if(a.code!=="EEXIST")throw a;let c=w(r);if(c&&F(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);v(r,{force:!0}),h(r,s)}return{record:s,release:()=>{$(r,s)}}}var D=1,H=u(q(),".xeno-agent"),W=u(process.env.XENO_AGENT_HOME??H,"daemon"),A=u(W,"runs");function i(){return new Date().toISOString()}function G(r=new Date){return r.toISOString().replace(/[^0-9]/g,"").slice(0,14)}function R(r){return r.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)}function p(r){return B(r)}function g(r){return p(r).toLowerCase()}function C(r,t){let e=g(r),n=g(t);return e===n||e.startsWith(`${n}\\`)||e.startsWith(`${n}/`)}function K(r,t){return!!(g(r.cwd)===g(t)||r.git?.root&&C(t,r.git.root)||r.git?.worktree&&C(t,r.git.worktree))}function X(r){return R(Buffer.from(p(r)).toString("base64url"))}function Z(){return{input:0,output:0,total:0}}function m(r){try{return JSON.parse(x(r,"utf8"))}catch{return null}}function Q(r,t){d(L(r),{recursive:!0});let e=`${r}.${process.pid}.${Date.now()}.tmp`;l(e,JSON.stringify(t,null,2)+`
|
|
3
|
-
`,"utf8"),z(e,r)}function Y(r){if(!r||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function tt(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="interrupted"}function et(r,t){return r.pinned!==t.pinned?r.pinned?-1:1:Date.parse(t.updatedAt)-Date.parse(r.updatedAt)}function mt(){return A}function Rt(r){return u(A,r)}function rt(r=new Date){return`run_${G(r)}_${J().slice(0,8)}`}var E=class{constructor(t=A){this.runsDir=t;d(this.runsDir,{recursive:!0})}create(t){let e=rt(),n=u(this.runsDir,e);d(n,{recursive:!0});let s=i(),a=u(n,"events.jsonl"),o={schemaVersion:D,runId:e,sessionId:e,rootRunId:e,cwd:p(t.cwd),workspaceId:X(t.cwd),prompt:t.prompt,...t.title?{title:t.title}:{},status:"starting",model:t.model,...t.effort?{effort:t.effort}:{},...t.agent?{agent:t.agent}:{},...t.git?{git:t.git}:{},permissionMode:t.permissionMode,...t.cliVersion?{createdByCliVersion:t.cliVersion}:{},createdBySdkVersion:t.sdkVersion??f,createdAt:s,updatedAt:s,lastActivityAt:s,pinned:!!t.pinned,attachedClients:0,...t.cliVersion?{cliVersion:t.cliVersion}:{},...t.sdkVersion?{sdkVersion:t.sdkVersion}:{},stdoutPath:u(n,"stdout.log"),stderrPath:u(n,"stderr.log"),eventsPath:a,usage:Z(),children:[],tags:[]};return l(o.stdoutPath,"","utf8"),l(o.stderrPath,"","utf8"),l(o.eventsPath,"","utf8"),this.write(o),this.appendEvent(e,"run_created",{cwd:o.cwd,model:o.model,...o.agent?{agent:o.agent}:{},...o.git?{git:o.git}:{},permissionMode:o.permissionMode,pinned:o.pinned}),o}get(t){let e=m(this.recordPath(t));return e?this.refreshRecordStatus(e):null}list(t={}){if(!y(this.runsDir))return[];let e=U(this.runsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>this.get(n.name)).filter(n=>n!==null).filter(n=>t.all||!t.cwd||K(n,t.cwd)).filter(n=>!t.status||t.status.includes(n.status)).sort(et);return typeof t.limit=="number"&&t.limit>0?e.slice(0,t.limit):e}markSpawned(t,e,n){return this.update(t,s=>({...s,status:"running",workerPid:e,...n?{workerVersion:n}:{},startedAt:s.startedAt??i(),lastActivityAt:i()}))}markStarted(t,e){return this.update(t,n=>({...n,status:"running",workerPid:e.pid,...e.workerVersion?{workerVersion:e.workerVersion}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},startedAt:n.startedAt??i(),lastActivityAt:i()}))}markCompleted(t,e){return this.update(t,n=>({...n,status:e.status,...e.statusReason?{statusReason:e.statusReason}:{},exitCode:e.exitCode??null,usage:e.usage??n.usage,endedAt:i(),lastActivityAt:i()}))}markCancelled(t,e){return this.update(t,n=>({...n,status:"cancelled",statusReason:e,endedAt:i(),lastActivityAt:i()}))}markPaused(t,e="Paused by user."){let n=this.update(t,s=>({...s,status:"paused",statusReason:e,lastActivityAt:i()}));return n&&this.appendEvent(t,"run_paused",{reason:e}),n}markResumed(t,e="Resumed by user."){let n=this.update(t,s=>{let a={...s,status:"running",statusReason:e,lastActivityAt:i()};return delete a.endedAt,delete a.exitCode,a});return n&&this.appendEvent(t,"run_resumed",{reason:e}),n}setPinned(t,e){let n=this.update(t,s=>({...s,pinned:e,lastActivityAt:i()}));return n&&this.appendEvent(t,e?"run_pinned":"run_unpinned",{pinned:e}),n}appendEvent(t,e,n={}){let s=m(this.recordPath(t)),a=s?.eventsPath??u(this.runsDir,t,"events.jsonl");d(L(a),{recursive:!0});let o={schemaVersion:D,runId:t,type:e,timestamp:i(),payload:n};M(a,JSON.stringify(o)+`
|
|
3
|
+
`,"utf8"),z(e,r)}function Y(r){if(!r||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function tt(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="interrupted"}function et(r,t){return r.pinned!==t.pinned?r.pinned?-1:1:Date.parse(t.updatedAt)-Date.parse(r.updatedAt)}function mt(){return A}function Rt(r){return u(A,r)}function rt(r=new Date){return`run_${G(r)}_${J().slice(0,8)}`}var E=class{constructor(t=A){this.runsDir=t;d(this.runsDir,{recursive:!0})}runsDir;create(t){let e=rt(),n=u(this.runsDir,e);d(n,{recursive:!0});let s=i(),a=u(n,"events.jsonl"),o={schemaVersion:D,runId:e,sessionId:e,rootRunId:e,cwd:p(t.cwd),workspaceId:X(t.cwd),prompt:t.prompt,...t.title?{title:t.title}:{},status:"starting",model:t.model,...t.effort?{effort:t.effort}:{},...t.agent?{agent:t.agent}:{},...t.git?{git:t.git}:{},permissionMode:t.permissionMode,...t.cliVersion?{createdByCliVersion:t.cliVersion}:{},createdBySdkVersion:t.sdkVersion??f,createdAt:s,updatedAt:s,lastActivityAt:s,pinned:!!t.pinned,attachedClients:0,...t.cliVersion?{cliVersion:t.cliVersion}:{},...t.sdkVersion?{sdkVersion:t.sdkVersion}:{},stdoutPath:u(n,"stdout.log"),stderrPath:u(n,"stderr.log"),eventsPath:a,usage:Z(),children:[],tags:[]};return l(o.stdoutPath,"","utf8"),l(o.stderrPath,"","utf8"),l(o.eventsPath,"","utf8"),this.write(o),this.appendEvent(e,"run_created",{cwd:o.cwd,model:o.model,...o.agent?{agent:o.agent}:{},...o.git?{git:o.git}:{},permissionMode:o.permissionMode,pinned:o.pinned}),o}get(t){let e=m(this.recordPath(t));return e?this.refreshRecordStatus(e):null}list(t={}){if(!y(this.runsDir))return[];let e=U(this.runsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>this.get(n.name)).filter(n=>n!==null).filter(n=>t.all||!t.cwd||K(n,t.cwd)).filter(n=>!t.status||t.status.includes(n.status)).sort(et);return typeof t.limit=="number"&&t.limit>0?e.slice(0,t.limit):e}markSpawned(t,e,n){return this.update(t,s=>({...s,status:"running",workerPid:e,...n?{workerVersion:n}:{},startedAt:s.startedAt??i(),lastActivityAt:i()}))}markStarted(t,e){return this.update(t,n=>({...n,status:"running",workerPid:e.pid,...e.workerVersion?{workerVersion:e.workerVersion}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},startedAt:n.startedAt??i(),lastActivityAt:i()}))}markCompleted(t,e){return this.update(t,n=>({...n,status:e.status,...e.statusReason?{statusReason:e.statusReason}:{},exitCode:e.exitCode??null,usage:e.usage??n.usage,endedAt:i(),lastActivityAt:i()}))}markCancelled(t,e){return this.update(t,n=>({...n,status:"cancelled",statusReason:e,endedAt:i(),lastActivityAt:i()}))}markPaused(t,e="Paused by user."){let n=this.update(t,s=>({...s,status:"paused",statusReason:e,lastActivityAt:i()}));return n&&this.appendEvent(t,"run_paused",{reason:e}),n}markResumed(t,e="Resumed by user."){let n=this.update(t,s=>{let a={...s,status:"running",statusReason:e,lastActivityAt:i()};return delete a.endedAt,delete a.exitCode,a});return n&&this.appendEvent(t,"run_resumed",{reason:e}),n}setPinned(t,e){let n=this.update(t,s=>({...s,pinned:e,lastActivityAt:i()}));return n&&this.appendEvent(t,e?"run_pinned":"run_unpinned",{pinned:e}),n}appendEvent(t,e,n={}){let s=m(this.recordPath(t)),a=s?.eventsPath??u(this.runsDir,t,"events.jsonl");d(L(a),{recursive:!0});let o={schemaVersion:D,runId:t,type:e,timestamp:i(),payload:n};M(a,JSON.stringify(o)+`
|
|
4
4
|
`,"utf8"),s&&this.update(t,c=>({...c,lastActivityAt:o.timestamp}))}readEvents(t){let e=this.get(t);return!e||!y(e.eventsPath)?[]:x(e.eventsPath,"utf8").split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}delete(t){j(u(this.runsDir,t),{recursive:!0,force:!0})}refreshRecordStatus(t){if(tt(t.status))return t;if(t.workerPid&&!Y(t.workerPid)){let e={...t,status:"failed",statusReason:"Worker process is no longer running and did not record a terminal status.",endedAt:t.endedAt??i(),updatedAt:i()};return this.write(e),e}return t}update(t,e){let n=m(this.recordPath(t));if(!n)return null;let s=e(n);return s.updatedAt=i(),this.write(s),s}write(t){let e=S(u(this.runDir(t.runId),"run.lock"),`run:${t.runId}`,f);try{Q(this.recordPath(t.runId),t)}finally{e.release()}}recordPath(t){return u(this.runsDir,R(P(t)),"run.json")}runDir(t){return u(this.runsDir,R(P(t)))}};export{E as AgentRunStore,S as acquireControlPlaneLock,rt as createAgentRunId,Rt as getAgentRunDir,mt as getAgentRunStoreDir};
|