agentix-cli 0.220.0 → 0.221.0
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/{agent-UDKXN4QV.js → agent-5FVRGDGM.js} +2 -2
- package/dist/{board-dashboard-CZXKVKK7.js → board-dashboard-ZJLIP2L4.js} +4 -4
- package/dist/{board-dashboard-CZXKVKK7.js.map → board-dashboard-ZJLIP2L4.js.map} +1 -1
- package/dist/chunk-3323WFVK.js +13 -0
- package/dist/chunk-3323WFVK.js.map +1 -0
- package/dist/{chunk-XQH4LCZR.js → chunk-74MHOALB.js} +2 -2
- package/dist/{chunk-5RCWAXVK.js → chunk-AX6CCD5P.js} +21 -21
- package/dist/chunk-AX6CCD5P.js.map +1 -0
- package/dist/{chunk-E3SA7KIZ.js → chunk-B5QQ4IH2.js} +2 -2
- package/dist/{chunk-M6TZ7IIJ.js → chunk-BX4RQ2IZ.js} +2 -2
- package/dist/{chunk-5XN2OMBS.js → chunk-F6LT3DHK.js} +2 -2
- package/dist/{chunk-SYIDD7CI.js → chunk-KQ3LPQ2Z.js} +2 -2
- package/dist/chunk-LIY6X3LU.js +2 -0
- package/dist/chunk-LIY6X3LU.js.map +1 -0
- package/dist/{chunk-PSUOF7O5.js → chunk-O4EQAPBB.js} +2 -2
- package/dist/{chunk-3XS7M5LM.js → chunk-RFVXW6F2.js} +248 -248
- package/dist/chunk-RFVXW6F2.js.map +1 -0
- package/dist/chunk-TCM3UOEQ.js +2 -0
- package/dist/chunk-TCM3UOEQ.js.map +1 -0
- package/dist/{chunk-5CUOKXOD.js → chunk-VYNM7HYU.js} +2 -2
- package/dist/{chunk-RHNOMUYZ.js → chunk-ZWD4ADV4.js} +3 -3
- package/dist/cli.js +1 -1
- package/dist/{doctor-PLN3QJE4.js → doctor-AW53DQDU.js} +2 -2
- package/dist/{follow-up-tool-LS4OUMLZ.js → follow-up-tool-N5U7U5WN.js} +2 -2
- package/dist/{grants-ZA35QVTX.js → grants-AIUWETYP.js} +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{org-tool-NVCSDX4I.js → org-tool-VNDHR7WM.js} +2 -2
- package/dist/{program-BRFPOZLO.js → program-YGEXHPRD.js} +8 -8
- package/dist/{program-BRFPOZLO.js.map → program-YGEXHPRD.js.map} +1 -1
- package/dist/registry-KYCXXPEA.js +2 -0
- package/dist/runner-I4ZB37JE.js +2 -0
- package/dist/{sprint-tool-B2LNMNPB.js → sprint-tool-5NJYOFIZ.js} +2 -2
- package/dist/step-proof-NMKY7T5A.js +2 -0
- package/dist/{tool-OVW6DDOO.js → tool-2DOU5XCQ.js} +2 -2
- package/dist/tool-AR4BLSYC.js +1 -1
- package/dist/{tool-EG6PL6NM.js → tool-ZSNE7YWS.js} +2 -2
- package/dist/{workspace-setup-CQ5FMT2B.js → workspace-setup-W32C7WXN.js} +2 -2
- package/dist/workspace-setup-W32C7WXN.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-3XS7M5LM.js.map +0 -1
- package/dist/chunk-5RCWAXVK.js.map +0 -1
- package/dist/chunk-BXK5S2KK.js +0 -13
- package/dist/chunk-BXK5S2KK.js.map +0 -1
- package/dist/chunk-SZDACK6O.js +0 -2
- package/dist/chunk-SZDACK6O.js.map +0 -1
- package/dist/registry-3J5U67DS.js +0 -2
- package/dist/runner-56G3N7M4.js +0 -2
- /package/dist/{agent-UDKXN4QV.js.map → agent-5FVRGDGM.js.map} +0 -0
- /package/dist/{chunk-XQH4LCZR.js.map → chunk-74MHOALB.js.map} +0 -0
- /package/dist/{chunk-E3SA7KIZ.js.map → chunk-B5QQ4IH2.js.map} +0 -0
- /package/dist/{chunk-M6TZ7IIJ.js.map → chunk-BX4RQ2IZ.js.map} +0 -0
- /package/dist/{chunk-5XN2OMBS.js.map → chunk-F6LT3DHK.js.map} +0 -0
- /package/dist/{chunk-SYIDD7CI.js.map → chunk-KQ3LPQ2Z.js.map} +0 -0
- /package/dist/{chunk-PSUOF7O5.js.map → chunk-O4EQAPBB.js.map} +0 -0
- /package/dist/{chunk-5CUOKXOD.js.map → chunk-VYNM7HYU.js.map} +0 -0
- /package/dist/{chunk-RHNOMUYZ.js.map → chunk-ZWD4ADV4.js.map} +0 -0
- /package/dist/{doctor-PLN3QJE4.js.map → doctor-AW53DQDU.js.map} +0 -0
- /package/dist/{follow-up-tool-LS4OUMLZ.js.map → follow-up-tool-N5U7U5WN.js.map} +0 -0
- /package/dist/{grants-ZA35QVTX.js.map → grants-AIUWETYP.js.map} +0 -0
- /package/dist/{org-tool-NVCSDX4I.js.map → org-tool-VNDHR7WM.js.map} +0 -0
- /package/dist/{registry-3J5U67DS.js.map → registry-KYCXXPEA.js.map} +0 -0
- /package/dist/{runner-56G3N7M4.js.map → runner-I4ZB37JE.js.map} +0 -0
- /package/dist/{sprint-tool-B2LNMNPB.js.map → sprint-tool-5NJYOFIZ.js.map} +0 -0
- /package/dist/{workspace-setup-CQ5FMT2B.js.map → step-proof-NMKY7T5A.js.map} +0 -0
- /package/dist/{tool-OVW6DDOO.js.map → tool-2DOU5XCQ.js.map} +0 -0
- /package/dist/{tool-EG6PL6NM.js.map → tool-ZSNE7YWS.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as g,c as R}from"./chunk-LIY6X3LU.js";import{exec as k}from"child_process";var p=32*1024;function d(n,o){return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(r,e)=>{let t=o[e];return t==null?"":String(t)}).replace(/\$\{?([A-Z_][A-Z0-9_]*)\}?/g,(r,e)=>process.env[e]??"")}function b(n,o){let r={};for(let e of n.inputs){let t=o[e.name]??e.defaultValue;if(t===void 0||t===""){if(e.required)throw new Error(`input "${e.name}" is required`);continue}if(e.type==="number"){let s=typeof t=="number"?t:Number(t);if(!Number.isFinite(s))throw new Error(`input "${e.name}" must be a number`);t=s}else e.type==="boolean"?t=t===!0||t==="true"||t==="1"||t===1:t=String(t);r[e.name]=t}return r}async function S(n,o={},r={}){let e=Date.now(),t=b(n,o);if(n.kind==="shell")return E(n,t,e,r.stepProof);if(n.kind==="http")return y(n,t,e,r.stepProof);throw new Error(`unsupported action kind: ${n.kind}`)}function E(n,o,r,e){let t=d(n.command,o),s={...process.env};if(n.env)for(let[a,c]of Object.entries(n.env))s[a]=d(c,o);delete s[g],e&&(s[g]=e);let l=n.cwd?d(n.cwd,o):process.cwd();return new Promise(a=>{let c=!1,m=i=>{c||(c=!0,a(i))};k(t,{cwd:l,env:s,timeout:n.timeoutMs,maxBuffer:p},(i,u,f)=>{let A=String(u||"").slice(0,p),h=String(f||"").slice(0,p),w=i?i.code??1:0;m({ok:!i,output:A,errors:h||(i?i.message:void 0),status:typeof w=="number"?w:1,durationMs:Date.now()-r})})})}async function y(n,o,r,e){let t=d(n.url,o),s={},l=e&&x(t)?e:"",a={...o,[R]:l};if(n.headers)for(let[u,f]of Object.entries(n.headers))s[u]=d(f,a);let c=n.method==="GET"||n.method==="DELETE"?void 0:n.body?d(n.body,o):void 0,m=new AbortController,i=setTimeout(()=>m.abort(),n.timeoutMs);try{let u=await fetch(t,{method:n.method,headers:s,body:c,signal:m.signal,...l?{redirect:"manual"}:{}}),f=(await u.text()).slice(0,p);return{ok:u.ok,output:f,status:u.status,durationMs:Date.now()-r}}catch(u){return{ok:!1,output:"",errors:u?.message||String(u),status:0,durationMs:Date.now()-r}}finally{clearTimeout(i)}}function x(n){try{let o=new URL(n).hostname.replace(/^\[|\]$/g,"");return o==="127.0.0.1"||o==="localhost"||o==="::1"}catch{return!1}}export{d as a,b,S as c,x as d};
|
|
2
|
+
//# sourceMappingURL=chunk-TCM3UOEQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/actions/runner.ts"],"sourcesContent":["import { exec } from \"child_process\"\nimport type { Action, ActionRunResult, ActionInput } from \"./types\"\nimport { STEP_PROOF_ENV, STEP_PROOF_TEMPLATE } from \"../workflows/step-proof\"\n\n// --- Action runner ---\n//\n// Resolves {{name}} markers from `inputs` and ${VAR} from process.env,\n// then dispatches by kind:\n// - \"shell\" — exec the command (cwd-aware, env-merge)\n// - \"http\" — fetch the url with method/headers/body\n//\n// Output is capped at ~32KB so a runaway command doesn't blow up the\n// dashboard JSON response.\n\nconst MAX_OUTPUT = 32 * 1024\n\n/** Fill {{name}} markers from values; ${VAR} from process.env. */\nexport function template(s: string, values: Record<string, unknown>): string {\n return s\n .replace(/\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\}\\}/g, (_, name) => {\n const v = values[name]\n return v === undefined || v === null ? \"\" : String(v)\n })\n .replace(/\\$\\{?([A-Z_][A-Z0-9_]*)\\}?/g, (_, name) => process.env[name] ?? \"\")\n}\n\n/** Validate inputs against the action's declared schema, applying defaults\n * and rejecting missing required fields. Returns the cleaned values\n * (booleans/numbers coerced from string CLI input). */\nexport function resolveInputs(action: Action, raw: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const def of action.inputs as ActionInput[]) {\n let v: unknown = raw[def.name] ?? def.defaultValue\n if (v === undefined || v === \"\") {\n if (def.required) throw new Error(`input \"${def.name}\" is required`)\n continue\n }\n if (def.type === \"number\") {\n const n = typeof v === \"number\" ? v : Number(v)\n if (!Number.isFinite(n)) throw new Error(`input \"${def.name}\" must be a number`)\n v = n\n } else if (def.type === \"boolean\") {\n v = v === true || v === \"true\" || v === \"1\" || v === 1\n } else {\n v = String(v)\n }\n out[def.name] = v\n }\n return out\n}\n\nexport interface RunActionOptions {\n /** A workflow step's proof (#1849): the env var AGENTX_STEP_PROOF of a\n * shell action, `{{agentx_step_proof}}` in an http action's headers.\n * Never put into the command, url, body or output. */\n stepProof?: string\n}\n\nexport async function runAction(action: Action, rawInputs: Record<string, unknown> = {}, opts: RunActionOptions = {}): Promise<ActionRunResult> {\n const start = Date.now()\n const values = resolveInputs(action, rawInputs)\n if (action.kind === \"shell\") return runShell(action, values, start, opts.stepProof)\n if (action.kind === \"http\") return runHttp(action, values, start, opts.stepProof)\n throw new Error(`unsupported action kind: ${(action as Action).kind}`)\n}\n\nfunction runShell(action: Extract<Action, { kind: \"shell\" }>, values: Record<string, unknown>, start: number, stepProof?: string): Promise<ActionRunResult> {\n const cmd = template(action.command, values)\n const env: NodeJS.ProcessEnv = { ...process.env }\n if (action.env) {\n for (const [k, v] of Object.entries(action.env)) env[k] = template(v, values)\n }\n // Set last, so the action's own env cannot stand in for the daemon's.\n delete env[STEP_PROOF_ENV]\n if (stepProof) env[STEP_PROOF_ENV] = stepProof\n const cwd = action.cwd ? template(action.cwd, values) : process.cwd()\n\n return new Promise<ActionRunResult>((resolve) => {\n let settled = false\n const finish = (r: ActionRunResult) => { if (settled) return; settled = true; resolve(r) }\n exec(cmd, { cwd, env, timeout: action.timeoutMs, maxBuffer: MAX_OUTPUT }, (err, stdout, stderr) => {\n const out = String(stdout || \"\").slice(0, MAX_OUTPUT)\n const errs = String(stderr || \"\").slice(0, MAX_OUTPUT)\n const status = err ? (err as NodeJS.ErrnoException & { code?: number }).code ?? 1 : 0\n finish({\n ok: !err,\n output: out,\n errors: errs || (err ? err.message : undefined),\n status: typeof status === \"number\" ? status : 1,\n durationMs: Date.now() - start,\n })\n })\n })\n}\n\nasync function runHttp(action: Extract<Action, { kind: \"http\" }>, values: Record<string, unknown>, start: number, stepProof?: string): Promise<ActionRunResult> {\n const url = template(action.url, values)\n const headers: Record<string, string> = {}\n // The proof is offered to headers only, so it never lands in a url or\n // body that may be logged; an input of the same name cannot fake it.\n // Only to this machine, so it cannot be sent off to a host a run input\n // names; and no redirect may carry it elsewhere.\n const proof = stepProof && isLoopbackUrl(url) ? stepProof : \"\"\n const headerValues = { ...values, [STEP_PROOF_TEMPLATE]: proof }\n if (action.headers) for (const [k, v] of Object.entries(action.headers)) headers[k] = template(v, headerValues)\n const body = action.method === \"GET\" || action.method === \"DELETE\" ? undefined : (action.body ? template(action.body, values) : undefined)\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), action.timeoutMs)\n try {\n const res = await fetch(url, { method: action.method, headers, body, signal: ac.signal, ...(proof ? { redirect: \"manual\" as const } : {}) })\n const text = (await res.text()).slice(0, MAX_OUTPUT)\n return {\n ok: res.ok,\n output: text,\n status: res.status,\n durationMs: Date.now() - start,\n }\n } catch (e: any) {\n return {\n ok: false,\n output: \"\",\n errors: e?.message || String(e),\n status: 0,\n durationMs: Date.now() - start,\n }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** True for an http(s) url on this machine's loopback address. */\nexport function isLoopbackUrl(url: string): boolean {\n try {\n const h = new URL(url).hostname.replace(/^\\[|\\]$/g, \"\")\n return h === \"127.0.0.1\" || h === \"localhost\" || h === \"::1\"\n } catch {\n return false\n }\n}\n"],"mappings":"+CAAA,OAAS,QAAAA,MAAY,gBAcrB,IAAMC,EAAa,GAAK,KAGjB,SAASC,EAASC,EAAWC,EAAyC,CAC3E,OAAOD,EACJ,QAAQ,0CAA2C,CAACE,EAAGC,IAAS,CAC/D,IAAMC,EAAIH,EAAOE,CAAI,EACrB,OAA0BC,GAAM,KAAO,GAAK,OAAOA,CAAC,CACtD,CAAC,EACA,QAAQ,8BAA+B,CAACF,EAAGC,IAAS,QAAQ,IAAIA,CAAI,GAAK,EAAE,CAChF,CAKO,SAASE,EAAcC,EAAgBC,EAAuD,CACnG,IAAMC,EAA+B,CAAC,EACtC,QAAWC,KAAOH,EAAO,OAAyB,CAChD,IAAIF,EAAaG,EAAIE,EAAI,IAAI,GAAKA,EAAI,aACtC,GAAIL,IAAM,QAAaA,IAAM,GAAI,CAC/B,GAAIK,EAAI,SAAU,MAAM,IAAI,MAAM,UAAUA,EAAI,mBAAmB,EACnE,SAEF,GAAIA,EAAI,OAAS,SAAU,CACzB,IAAMC,EAAI,OAAON,GAAM,SAAWA,EAAI,OAAOA,CAAC,EAC9C,GAAI,CAAC,OAAO,SAASM,CAAC,EAAG,MAAM,IAAI,MAAM,UAAUD,EAAI,wBAAwB,EAC/EL,EAAIM,OACKD,EAAI,OAAS,UACtBL,EAAIA,IAAM,IAAQA,IAAM,QAAUA,IAAM,KAAOA,IAAM,EAErDA,EAAI,OAAOA,CAAC,EAEdI,EAAIC,EAAI,IAAI,EAAIL,EAElB,OAAOI,CACT,CASA,eAAsBG,EAAUL,EAAgBM,EAAqC,CAAC,EAAGC,EAAyB,CAAC,EAA6B,CAC9I,IAAMC,EAAQ,KAAK,IAAI,EACjBb,EAASI,EAAcC,EAAQM,CAAS,EAC9C,GAAIN,EAAO,OAAS,QAAS,OAAOS,EAAST,EAAQL,EAAQa,EAAOD,EAAK,SAAS,EAClF,GAAIP,EAAO,OAAS,OAAQ,OAAOU,EAAQV,EAAQL,EAAQa,EAAOD,EAAK,SAAS,EAChF,MAAM,IAAI,MAAM,4BAA6BP,EAAkB,MAAM,CACvE,CAEA,SAASS,EAAST,EAA4CL,EAAiCa,EAAeG,EAA8C,CAC1J,IAAMC,EAAMnB,EAASO,EAAO,QAASL,CAAM,EACrCkB,EAAyB,CAAE,GAAG,QAAQ,GAAI,EAChD,GAAIb,EAAO,IACT,OAAW,CAACc,EAAGhB,CAAC,IAAK,OAAO,QAAQE,EAAO,GAAG,EAAGa,EAAIC,CAAC,EAAIrB,EAASK,EAAGH,CAAM,EAG9E,OAAOkB,EAAIE,CAAc,EACrBJ,IAAWE,EAAIE,CAAc,EAAIJ,GACrC,IAAMK,EAAMhB,EAAO,IAAMP,EAASO,EAAO,IAAKL,CAAM,EAAI,QAAQ,IAAI,EAEpE,OAAO,IAAI,QAA0BsB,GAAY,CAC/C,IAAIC,EAAU,GACRC,EAAUC,GAAuB,CAAMF,IAAiBA,EAAU,GAAMD,EAAQG,CAAC,EAAE,EACzFC,EAAKT,EAAK,CAAE,IAAAI,EAAK,IAAAH,EAAK,QAASb,EAAO,UAAW,UAAWR,CAAW,EAAG,CAAC8B,EAAKC,EAAQC,IAAW,CACjG,IAAMtB,EAAM,OAAOqB,GAAU,EAAE,EAAE,MAAM,EAAG/B,CAAU,EAC9CiC,EAAO,OAAOD,GAAU,EAAE,EAAE,MAAM,EAAGhC,CAAU,EAC/CkC,EAASJ,EAAOA,EAAkD,MAAQ,EAAI,EACpFH,EAAO,CACL,GAAI,CAACG,EACL,OAAQpB,EACR,OAAQuB,IAASH,EAAMA,EAAI,QAAU,QACrC,OAAQ,OAAOI,GAAW,SAAWA,EAAS,EAC9C,WAAY,KAAK,IAAI,EAAIlB,CAC3B,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAEA,eAAeE,EAAQV,EAA2CL,EAAiCa,EAAeG,EAA8C,CAC9J,IAAMgB,EAAMlC,EAASO,EAAO,IAAKL,CAAM,EACjCiC,EAAkC,CAAC,EAKnCC,EAAQlB,GAAamB,EAAcH,CAAG,EAAIhB,EAAY,GACtDoB,EAAe,CAAE,GAAGpC,EAAQ,CAACqC,CAAmB,EAAGH,CAAM,EAC/D,GAAI7B,EAAO,QAAS,OAAW,CAACc,EAAGhB,CAAC,IAAK,OAAO,QAAQE,EAAO,OAAO,EAAG4B,EAAQd,CAAC,EAAIrB,EAASK,EAAGiC,CAAY,EAC9G,IAAME,EAAOjC,EAAO,SAAW,OAASA,EAAO,SAAW,SAAW,OAAaA,EAAO,KAAOP,EAASO,EAAO,KAAML,CAAM,EAAI,OAC1HuC,EAAK,IAAI,gBACTC,EAAQ,WAAW,IAAMD,EAAG,MAAM,EAAGlC,EAAO,SAAS,EAC3D,GAAI,CACF,IAAMoC,EAAM,MAAM,MAAMT,EAAK,CAAE,OAAQ3B,EAAO,OAAQ,QAAA4B,EAAS,KAAAK,EAAM,OAAQC,EAAG,OAAQ,GAAIL,EAAQ,CAAE,SAAU,QAAkB,EAAI,CAAC,CAAG,CAAC,EACrIQ,GAAQ,MAAMD,EAAI,KAAK,GAAG,MAAM,EAAG5C,CAAU,EACnD,MAAO,CACL,GAAI4C,EAAI,GACR,OAAQC,EACR,OAAQD,EAAI,OACZ,WAAY,KAAK,IAAI,EAAI5B,CAC3B,CACF,OAAS8B,EAAP,CACA,MAAO,CACL,GAAI,GACJ,OAAQ,GACR,OAAQA,GAAG,SAAW,OAAOA,CAAC,EAC9B,OAAQ,EACR,WAAY,KAAK,IAAI,EAAI9B,CAC3B,CACF,QAAE,CACA,aAAa2B,CAAK,CACpB,CACF,CAGO,SAASL,EAAcH,EAAsB,CAClD,GAAI,CACF,IAAMY,EAAI,IAAI,IAAIZ,CAAG,EAAE,SAAS,QAAQ,WAAY,EAAE,EACtD,OAAOY,IAAM,aAAeA,IAAM,aAAeA,IAAM,KACzD,MAAE,CACA,MAAO,EACT,CACF","names":["exec","MAX_OUTPUT","template","s","values","_","name","v","resolveInputs","action","raw","out","def","n","runAction","rawInputs","opts","start","runShell","runHttp","stepProof","cmd","env","k","STEP_PROOF_ENV","cwd","resolve","settled","finish","r","exec","err","stdout","stderr","errs","status","url","headers","proof","isLoopbackUrl","headerValues","STEP_PROOF_TEMPLATE","body","ac","timer","res","text","e","h"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as I}from"./chunk-IMLAPB7G.js";import{d as le}from"./chunk-QPABR72X.js";import{b as ue}from"./chunk-KP7KDLZ2.js";import{o as k}from"./chunk-
|
|
1
|
+
import{a as I}from"./chunk-IMLAPB7G.js";import{d as le}from"./chunk-QPABR72X.js";import{b as ue}from"./chunk-KP7KDLZ2.js";import{o as k}from"./chunk-3323WFVK.js";import{Ra as oe,Sa as se,Ua as ie,Va as ae,ab as $,gb as ot,o as B,r as rt}from"./chunk-VOVDWFFP.js";import{accessSync as lt,closeSync as ut,constants as ct,existsSync as fe,openSync as pt,readFileSync as dt,readSync as ft,statSync as mt}from"node:fs";import{dirname as O,join as L}from"node:path";import{fileURLToPath as gt}from"node:url";import{homedir as ht}from"node:os";import{join as ce,win32 as j}from"path";function E(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var U="agentx-helper.exe";function st(e){return j.join(e,"Programs","AgentX",U)}var pe="AgentX Helper.app";function X(e){return ce(e,"Applications",pe,"Contents/MacOS/agentx-mac-helper")}function it(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&E(e)==="macos"?r:void 0}function de(e){let t=it(e.platform,e.env);if(t)return t;let n=E(e.platform);if(n==="macos"){let r=X(e.home);return e.exists(r)||!e.root?r:ce(e.root,"apps/mac-helper/build",pe,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||j.join(e.home,"AppData","Local"),o=st(r);return e.exists(o)||!e.root?o:j.join(e.root,"apps","win-helper","build",U)}return null}function at(e){let t=E(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${U} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function fn(e){let t=E(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=at(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var J="tn.acme.agentx.voice",bn="AgentX Desktop.app",kn="AgentX Helper.app";function xn(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function vn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function G(e){return`'${e.replace(/'/g,"'\\''")}'`}var me="/usr/bin:/bin:/usr/sbin:/sbin";function An(e,t){return t||[...new Set([...e?[O(e)]:[],...me.split(":")])].join(":")}function T(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function Nn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?T(t[1]):me}var Pn=e=>/agentx\.voice.*\.plist$/.test(e);function Rn(e,t){let n=null,r=[];for(let{file:o,plist:s}of[...t].sort((i,a)=>i.file<a.file?-1:1)){let i=s.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],a=s.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!i||!a||!T(a).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:T(i)}):n={file:o,label:T(i)})}return{keep:n??{file:L(e,`${J}.plist`),label:J},remove:r}}function ge(e,t,n){for(let r of t.split(":"))if(r&&n(L(r,e)))return L(r,e);return null}function Cn(e){try{if(lt(e,ct.X_OK),!mt(e).isFile())return!1;let t=pt(e,"r"),n=Buffer.alloc(2);try{ft(t,n,0,2,0)}finally{ut(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function $n(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${G(e.cwd)} && ${G(e.node)} ${G(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??J)}</string>
|
|
@@ -36,4 +36,4 @@ function run(argv) {
|
|
|
36
36
|
`),on(r,n)}var un=5*6e4;function fo(e,t,n=Date.now()){let r=ne(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=un)?!1:r.items[`card:${t}`]?.state!=="failed"}var re=24*36e5;function et(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function cn(e,t,n,r){let o=Date.parse(e.expires),s=[w(e.ask,k.ask)];return e.choices?.length&&s.push(...e.choices.map((i,a)=>`${a+1}. ${i}`)),e.recommend&&s.push(`Recommended: ${w(e.recommend,k.recommend)}`),s.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,k.title),notes:s.join(`
|
|
37
37
|
`),due:et(r,t,o),priority:Number.isFinite(o)&&o-r<=re?"high":"none"}}function pn(e,t,n,r){let o=[w(e.question||e.text,k.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],s=e.dueAt??void 0;return{key:`request:${e.id}`,title:ee(e,k.title).headline,notes:o.join(`
|
|
38
38
|
`),due:et(r,t,s),priority:s!==void 0&&s-r<=re?"high":"none"}}async function mo(e){let{root:t,settings:n,tasks:r,log:o}=e,s=e.now??Date.now(),i=new Date(s).toISOString(),a={created:0,completed:0,dismissed:0,failed:0},l=ne(t);delete l.lastError;let c=u=>{l.lastError={at:i,message:u}},f=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>s&&f.set(`card:${u.id}`,cn(u,n,e.answerUrl,s));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&f.set(`request:${u.id}`,pn(u,n,e.answerUrl,s))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Qe(t,l),a}let h=!0,S=new Map,tt=async u=>{if(!S.has(u))try{S.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),S.set(u,null),h=!1}return S.get(u)};for(let[u,p]of Object.entries(l.items)){if(p.state!=="open"||!p.id)continue;let d=await tt(p.list);if(d)if(f.has(u))d.has(p.id)||(l.items[u]={...p,state:"dismissed",at:i},a.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(b){o(`[mirror] ${u}: could not complete its task: ${b?.message??b}`),c(String(b?.message??b));continue}l.items[u]={...p,state:"completed",at:i},a.completed++}}let R=null,W="",F=0,N=[];for(let[u,p]of f){let d=l.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=te)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(g){o(`[mirror] could not make list "${n.list}": ${g?.message??g}`),W=String(g?.message??g),c(W),R=!1}let b=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:g}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});l.items[u]={id:g,list:n.list,state:"open",at:i,createdAt:i,failures:0},a.created++}catch(g){let C=String(g?.message??g);u.startsWith("card:")&&F++;let H=b+1;l.items[u]={list:n.list,state:"failed",at:i,failures:H,lastError:C},c(C),a.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${te}): ${C}`),H===te&&N.push({title:p.title,message:C})}}F&&o(`[mirror] ${F} card(s) could not be added to Reminders; the Mac popup shows them instead`);let nt=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(N.length&&!(s-nt<re)){let u=N[0],p=N.length>1?` (and ${N.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),l.failureToldAt=i}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}h&&(l.checkedAt=i,l.cards=n.include.includes("card"));for(let[u,p]of Object.entries(l.items))p.state!=="open"&&!f.has(u)&&s-Date.parse(p.at)>ln&&delete l.items[u];return Qe(t,l),a}var Ye=5*6e4;function go(e,t,n,r,o=Date.now()){let s=ne(e),i=l=>{let c=l?Date.parse(l):NaN;return c>=n&&c<r},a={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[l,c]of Object.entries(s.items))!c.id||!i(c.createdAt)||(l.startsWith("card:")?a.created.cards++:a.created.requests++);for(let l of t){if(!i(l.created_at))continue;a.raised++;let c=s.items[`card:${l.id}`];if(c?.id)continue;let f=Date.parse(l.created_at);if((l.status==="pending"?NaN:Date.parse(l.decided_at??""))-f<=Ye){a.closedFast++;continue}if(l.status==="pending"&&o-f<=Ye){a.tooNew++;continue}let S=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";a.missed.push({id:l.id,title:l.title,reason:S})}return a}function ho(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Hr as a,Br as b,jt as c,jr as d,Be as e,Jt as f,Ue as g,Ur as h,zr as i,Xe as j,Y as k,Z as l,Vr as m,Qr as n,Yt as o,Yr as p,Zr as q,eo as r,ee as s,w as t,en as u,io as v,E as w,de as x,at as y,fn as z,bn as A,kn as B,xn as C,vn as D,An as E,Nn as F,Pn as G,Rn as H,ge as I,Cn as J,$n as K,In as L,En as M,yt as N,P as O,ke as P,Q,Me as R,Dr as S,Mr as T,_r as U,ne as V,fo as W,mo as X,go as Y,ho as Z};
|
|
39
|
-
//# sourceMappingURL=chunk-
|
|
39
|
+
//# sourceMappingURL=chunk-VYNM7HYU.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-
|
|
1
|
+
import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-AX6CCD5P.js";import{b as co}from"./chunk-MEFPXHQJ.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as oo}from"./chunk-IH65GDJR.js";import{b as lo,d as Wn,e as po,f as st,i as mo}from"./chunk-NW7B53KD.js";import{a as Hn,b as uo}from"./chunk-J3SOEFRE.js";import{a as jn,b as go}from"./chunk-SIU6STB2.js";import{e as fo,i as ho,j as yo,k as wo}from"./chunk-X5C5W3E4.js";import{d as bo}from"./chunk-KWWBDLE6.js";import{f as xo,g as So}from"./chunk-HVMUYEQP.js";import{h as so,i as ro}from"./chunk-BE64IJWM.js";import{a as Ur,c as Fr}from"./chunk-MYVHVJWZ.js";import{a as Hr,b as jr,c as Wr,d as qr,l as Jr,q as zr}from"./chunk-74MHOALB.js";import{a as Gr,b as Kr}from"./chunk-LY4G7PCW.js";import{a as Qr,b as Zr}from"./chunk-DPG6VHPX.js";import{c as Xr}from"./chunk-BERWTVG2.js";import{a as Yr,b as Un}from"./chunk-A7JSRDJL.js";import{d as Vr}from"./chunk-Z5CMA4JN.js";import{b as no}from"./chunk-JMRFYGET.js";import{g as eo,h as to}from"./chunk-5QXRGX2F.js";import{c as br,d as xr}from"./chunk-AHWWJ7AF.js";import{c as Or,f as Lr}from"./chunk-JD5TCX4X.js";import{s as Er,v as Bt,w as Dr,y as Ie,z as Bn}from"./chunk-Y6KR7NXL.js";import{a as nt,b as He,f as Nt}from"./chunk-72SZI2UW.js";import{a as Fe,b as Dn}from"./chunk-FCPTN6NF.js";import{d as Br}from"./chunk-7IW25T4K.js";import{e as je,h as Nr,i as Ee}from"./chunk-QUFIUXMQ.js";import{e as Pe}from"./chunk-DSYKYZMT.js";import{Ba as vr,Cb as $r,Cc as Yc,Ea as Jc,Hb as Xc,Nb as Cr,Ob as Lt,Pb as Mr,Qb as tt,Rb as Rr,Sb as _r,Yb as Pr,ub as Ar,xb as Nn,zb as Qc}from"./chunk-VOVDWFFP.js";import{f as kr,g as et,h as Kc}from"./chunk-KEUW6YLL.js";import{j as Ln,r as zc}from"./chunk-N47Y5ADQ.js";import{a as Sr,b as fe,c as Tr,d as Ir,e as On}from"./chunk-VQRY4IDI.js";var Zc="[agentx:mid-turn",Wo="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",qo="Got it, I passed that on to the work in progress.";function qt(n,e,t){return`${n}\0${e}\0${t}`}var Vc=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function eu(n){return!!n&&!Vc.has(n)}function Go(n,e){return!eu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Wt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function tu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Zc} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
|
|
2
2
|
`)}function pf(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:tu(n)}}):""}Bn();Nt();var Gt="tool-set",Ko=["answer","code","full"],Jo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},nu=.1;function Qo(n){return{task:zo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:zo(n.agentPrompt,600)}:{}}}var Xo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Yo(n,e=nu){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Gn(s.answer),o=Gn(s.code),i=Gn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Zo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Jo.answer.includes(t))?"answer":e.every(t=>Jo.code.includes(t))?"code":"full"}function Vo(n,e){return Ko.indexOf(n)<Ko.indexOf(e)}function Gn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function zo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ei=!1;function ti(n,e){let t=Bt(Gt);if(t!=="off")return t==="active"&&!ei&&(ei=!0,e(`[decisions] seat "${Gt}" is set to active, but only shadow is built: it records and changes nothing`)),Ie(Gt,Qo(n),Xo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Yo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function ni(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Zo(r);Dr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Vo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function su(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function si(n,e){let t=su(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Kn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Bn();Nt();var ri="session-continuity",oi={continues:nt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:nt("Does the new request refer to something stated earlier in the conversation?")};function ii(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Jn(n.message,1200),previousRequest:n.previousMessage?Jn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Jn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function ai(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Jn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function di(n,e){let t=Br(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function kf(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=di(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function vf(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:di(n,e).token}var ci=null;function Af(n){ci=n}function Kt(n,e){let t;try{t=ci?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as en}from"execa";import{spawn as ru}from"node:child_process";import{createHash as ou}from"node:crypto";import{createInterface as iu}from"node:readline";var ke=class extends Error{},au=n=>ru("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),zn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),iu({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
3
3
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Qn=class{constructor(e=au,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=ou("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[P])=>x.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ke("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,P])=>!P.connection.busy);if(!x)throw new ke("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new zn(e,this.launchProcess)}}catch{throw new ke("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),I=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(I),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((w,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?w():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return U.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await U,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new ke(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(I),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ui=new Qn;import{execFile as Mu}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as Ci,readFileSync as Mi,rmSync as Ri}from"fs";import{join as Zt}from"path";import{tmpdir as _i}from"os";function Jt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function zt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Qt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var De=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var li=null;function rt(){return li}function Of(n){li=n}function he(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function du(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},gi=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=he(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=du(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new qe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new qe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=he(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=he(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as cu}from"child_process";import{randomUUID as uu}from"crypto";import{existsSync as lu,readFileSync as gu}from"fs";import{resolve as pu}from"path";function mu(n){let e=pu(n,"CLAUDE.md");if(!lu(e))return null;try{let t=gu(e,"utf8");return zr(t)}catch{return null}}var fu=20*60*1e3,hu=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function yu(n,e){return n.AGENTX_AGENT_ID=e.agentId,Kt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var pi=class{constructor(e={}){this.opts=e}spawn(e,t){return new Xn(e,t,this.opts)}},Xn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=cu(r,o,{cwd:t.workspace,env:Ee(yu({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:mu(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new De;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=uu(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
4
4
|
`);let c=e.deadlineMs??fu,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new ot(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},hu);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
@@ -32,7 +32,7 @@ ${n}`}function _u(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
32
32
|
`,l)}};w.stdout?.on("data",v=>{L+=j.write(v);let S=L.split(`
|
|
33
33
|
`);L=S.pop()||"";for(let B of S)J(B)}),w.stderr?.on("data",v=>{N+=q.write(v)});let $=await w;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=vi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return I=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(P?.message||"")?vi():P?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(I)}}async function ju(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ve(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Wu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let I=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(I))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let I=n.provider||"claude-code",x=s?`${s}
|
|
34
34
|
|
|
35
|
-
${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-
|
|
35
|
+
${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-5FVRGDGM.js"),$="",v,S,B,W;for await(let E of J(M)){if(c)try{c(E)}catch{}if(E.type==="text_delta")$+=E.text,r(E.text,$);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}v=E.result.tokensUsed,E.result.inputTokens!=null&&(S=E.result.inputTokens),E.result.outputTokens!=null&&(B=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}E.result.tokensUsed!=null&&(v=E.result.tokensUsed)}else E.type==="error"&&(W=E.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-5FVRGDGM.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(I){return p?y():I?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${I.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var qu=1e3;async function Gu(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),qu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=ut(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&ts(e.agentId,n,e.model,s,"persistent");let h=ve(n,e,t),y="",I,x,P,U,w,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
|
|
36
36
|
`)?`
|
|
37
37
|
|
|
38
38
|
${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");I=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(P={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(w=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Qt(S.modelUsage)||_}}}catch($){if(j)I="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)I=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);I=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);I=v.error,x=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!I&&(I="task cancelled by operator",x="cancelled"),{content:j?"":y,error:I,errorKind:x,duration:Date.now()-c,usage:P,contextTokens:U,numTurns:w,billedModel:_,claudeSessionId:R}}function Hi(n){let e=fe(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?wi(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Ii(t.args,n.taskId,n.agentId)}function Ju(n){return fe(n.autonomy)||!!n.personLimits}async function zu(n,e,t,s,r,o,i){let a=fe(e.autonomy)?e.autonomy:void 0,c=a&&bi(a,n.tier)||e.personLimits&&ki(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${Ir(a)}
|
|
@@ -189,4 +189,4 @@ ${Re}`),m+=Re.length}catch{}}}let Uc=Mn.length>0?Mn.join(`
|
|
|
189
189
|
|
|
190
190
|
Agent: ${C.content}`,meta:rf(ee,e.context)})},ue=>this.log(ue)),Zr(e.agentId,e.message,C.content,{channel:b,chatId:T,sender:vn},this.memoryStore).catch(()=>{}),fa(e.agentId,e.message,C.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Ue=e.context?.channel,me=Ue&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ue}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,pe,Ue,me),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${O()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Jt(g.message);return se={content:"",error:zt(m),errorKind:m.kind},se}finally{if(yr.stop(),wr&&ce&&Ce)try{let g=se?.usage,m=No(Ce,ce,{error:se?se.error||void 0:R.signal.aborted?Be(R.signal).message:"run ended before completion",canceled:Bo(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Pn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Us(se),Hs(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?Zm(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Uo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||qm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Km(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Ye,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of be(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let I=Math.floor((s-y)/36e5),x=t-1-I;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of be(e)){let r=G(e,s),o;try{o=be(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=be(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(xt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=sf){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of be(t)){let i=G(t,o),a;try{a=be(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Gm(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=be(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=be(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(xt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=be(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(xt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Ut(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=qn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){Qm.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=ut(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!Go(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(c=>c.channel===s&&c.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(qt(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(qt(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Cr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function gf(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
191
191
|
`)}export{pf as a,di as b,kf as c,vf as d,Af as e,ui as f,Of as g,gi as h,mu as i,pi as j,Xt as k,Xf as l,eh as m,th as n,ih as o,ut as p,Lu as q,Ui as r,Hu as s,ju as t,Wu as u,ji as v,sn as w,zi as x,Bh as y,rn as z,pl as A,Wh as B,qh as C,Kh as D,an as E,Sl as F,Qh as G,cs as H,V as I,Sa as J,Fl as K,ql as L,ka as M,my as N,va as O,Pa as P,Cy as Q,My as R,Ba as S,Ry as T,Ua as U,pn as V,Uy as W,Fy as X,mt as Y,tp as Z,np as _,sp as $,rp as aa,op as ba,Ss as ca,yn as da,hw as ea,bn as fa,wn as ga,Ed as ha,ht as ia,Dd as ja,Iw as ka,kw as la,vw as ma,Aw as na,$w as oa,Cw as pa,Mw as qa,Np as ra,Kd as sa,Xe as ta,ic as ua,Ls as va,Ww as wa,Gw as xa,Kw as ya,Xm as za,Ym as Aa,kx as Ba,vx as Ca,Zm as Da,nf as Ea,rf as Fa,of as Ga,df as Ha,Ns as Ia,hc as Ja,yc as Ka,uf as La,wc as Ma,bc as Na,gf as Oa};
|
|
192
|
-
//# sourceMappingURL=chunk-
|
|
192
|
+
//# sourceMappingURL=chunk-ZWD4ADV4.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-YGEXHPRD.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j}from"./chunk-O4EQAPBB.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import"./chunk-VYNM7HYU.js";import"./chunk-IMLAPB7G.js";import"./chunk-QPABR72X.js";import"./chunk-KP7KDLZ2.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-7I7IEX4S.js";import"./chunk-VOVDWFFP.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-QIJLFPWE.js";export{j as daemonVoiceCheck,b as doctor,i as mcpHeaderEnvChecks,g as meshPeerTokenChecks,h as meshTokenChecksFromConfig,a as runDoctorChecks,e as runMirrorChecks,d as runNativeChecks,c as runNotificationChecks,f as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-AW53DQDU.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{d as h}from"./chunk-CIW37UJT.js";import{b as I}from"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-CIW37UJT.js";import"./chunk-AEFO6ES5.js";import{b as I}from"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-NW7B53KD.js";import"./chunk-5BT4VPJC.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-VOVDWFFP.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
|
|
2
2
|
`)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
3
|
`)).join(`
|
|
4
4
|
`):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
5
|
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
|
|
6
6
|
`):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
7
|
-
//# sourceMappingURL=follow-up-tool-
|
|
7
|
+
//# sourceMappingURL=follow-up-tool-N5U7U5WN.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=grants-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-KQ3LPQ2Z.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-7I7IEX4S.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_GRANT_DAYS,a as GUEST_SCOPE_PREFIX,b as JOIN_CARD_BY,h as JOIN_FAILED,d as MAX_GRANT_DAYS,j as NO_GRANT,l as PAUSED,k as WAITING_HOST,s as endGrant,o as grantBrief,u as grantForGuest,e as grantIdOf,n as guestAccess,p as guestTask,g as inviteGuest,i as joinGuest,f as newGrantId,q as pauseGrant,r as resumeGrant,m as settleGrant,t as updateGrant};
|
|
2
|
+
//# sourceMappingURL=grants-AIUWETYP.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -15160,6 +15160,8 @@ declare class AgentXDaemon {
|
|
|
15160
15160
|
* reload that changes native.adapter or reminders.command applies. */
|
|
15161
15161
|
private get native();
|
|
15162
15162
|
private registry;
|
|
15163
|
+
/** Live proofs of running action.run steps (#1849). Memory only. */
|
|
15164
|
+
private readonly stepProofs;
|
|
15163
15165
|
/** What the node reports about its own environment (#1531). */
|
|
15164
15166
|
private nodeEnv;
|
|
15165
15167
|
private router;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-RFVXW6F2.js";import"./chunk-B5QQ4IH2.js";import"./chunk-GTJIKXDB.js";import"./chunk-NCMPJPXG.js";import"./chunk-VYNM7HYU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-GO4J44UD.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-4UJDRI7W.js";import"./chunk-A5GYG56I.js";import"./chunk-XC3466Z4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-D5LIMOI6.js";import"./chunk-SQP6A5AG.js";import"./chunk-QPABR72X.js";import"./chunk-AEFO6ES5.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Na as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-ZWD4ADV4.js";import"./chunk-AX6CCD5P.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-BX4RQ2IZ.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-TCM3UOEQ.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{u as ut}from"./chunk-NW7B53KD.js";import"./chunk-5BT4VPJC.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-LIY6X3LU.js";import"./chunk-VWTBHLMX.js";import"./chunk-6EJJKOMW.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-JMRFYGET.js";import{a as ht}from"./chunk-ABMDDRZL.js";import{f as gt,g as ft}from"./chunk-5QXRGX2F.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-JD5TCX4X.js";import{j as it,k as rt,l as at}from"./chunk-Y6KR7NXL.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Cc as nt,qc as tt,sc as st,vc as ot}from"./chunk-VOVDWFFP.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|