agentix-cli 0.65.0 → 0.66.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/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +29 -8
- package/apps/mac-voice/Sources/AgentXVoice/MiniOrbs.swift +219 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +32 -3
- package/apps/mac-voice/Sources/AgentXVoice/PillBusy.swift +126 -0
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +53 -12
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +49 -3
- package/dist/{agent-HUKCS3AK.js → agent-BQ5CCARE.js} +2 -2
- package/dist/{board-dashboard-S4V4WR2N.js → board-dashboard-K3P2M7A7.js} +813 -366
- package/dist/board-dashboard-K3P2M7A7.js.map +1 -0
- package/dist/{chunk-WWMFNLKD.js → chunk-2NYP4OQU.js} +3 -3
- package/dist/chunk-2NYP4OQU.js.map +1 -0
- package/dist/{chunk-AVDWFQZ5.js → chunk-6CFAF5CH.js} +2 -2
- package/dist/{chunk-OTTAKMGC.js → chunk-AWKZ3BF2.js} +3 -3
- package/dist/{chunk-HSJRI3NW.js → chunk-BBXBSM4R.js} +148 -148
- package/dist/chunk-BBXBSM4R.js.map +1 -0
- package/dist/{chunk-LEFRNHZF.js → chunk-EPTZ6JMA.js} +4 -4
- package/dist/chunk-JWDJMFU6.js +4 -0
- package/dist/chunk-JWDJMFU6.js.map +1 -0
- package/dist/{chunk-EOKOGQZG.js → chunk-YDHI2CJG.js} +2 -2
- package/dist/{chunk-ECBKTFTL.js → chunk-ZIEUP56T.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/{program-DZCKFNHD.js → program-4W45H3J2.js} +2 -2
- package/dist/push-announce-PM5FZJRW.js +3 -0
- package/dist/push-announce-PM5FZJRW.js.map +1 -0
- package/dist/push-prefs-YOJNTOJF.js +2 -0
- package/dist/push-store-5VJ4FNI4.js +2 -0
- package/dist/{registry-P7IAAFCX.js → registry-TERSIHOC.js} +2 -2
- package/dist/registry-TERSIHOC.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-S4V4WR2N.js.map +0 -1
- package/dist/chunk-HSJRI3NW.js.map +0 -1
- package/dist/chunk-WWMFNLKD.js.map +0 -1
- package/dist/push-store-LXTYULUF.js +0 -2
- /package/dist/{agent-HUKCS3AK.js.map → agent-BQ5CCARE.js.map} +0 -0
- /package/dist/{chunk-AVDWFQZ5.js.map → chunk-6CFAF5CH.js.map} +0 -0
- /package/dist/{chunk-OTTAKMGC.js.map → chunk-AWKZ3BF2.js.map} +0 -0
- /package/dist/{chunk-LEFRNHZF.js.map → chunk-EPTZ6JMA.js.map} +0 -0
- /package/dist/{chunk-EOKOGQZG.js.map → chunk-YDHI2CJG.js.map} +0 -0
- /package/dist/{chunk-ECBKTFTL.js.map → chunk-ZIEUP56T.js.map} +0 -0
- /package/dist/{program-DZCKFNHD.js.map → program-4W45H3J2.js.map} +0 -0
- /package/dist/{push-store-LXTYULUF.js.map → push-prefs-YOJNTOJF.js.map} +0 -0
- /package/dist/{registry-P7IAAFCX.js.map → push-store-5VJ4FNI4.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var d=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS push_subscriptions (
|
|
1
|
+
import{b as s}from"./chunk-JWDJMFU6.js";var d=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS push_subscriptions (
|
|
2
2
|
endpoint TEXT PRIMARY KEY, p256dh TEXT NOT NULL, auth TEXT NOT NULL,
|
|
3
3
|
device_id TEXT NOT NULL, device_name TEXT NOT NULL, public_key TEXT NOT NULL,
|
|
4
4
|
created_at INTEGER NOT NULL);
|
|
5
5
|
CREATE INDEX IF NOT EXISTS push_subscriptions_device ON push_subscriptions(device_id);
|
|
6
6
|
CREATE TABLE IF NOT EXISTS push_log (
|
|
7
7
|
id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, title TEXT NOT NULL,
|
|
8
|
-
body TEXT NOT NULL, url TEXT, delivered INTEGER NOT NULL, device_id TEXT);`)}subscribe(e,t=Date.now()){this.db.prepare(`INSERT OR REPLACE INTO push_subscriptions
|
|
8
|
+
body TEXT NOT NULL, url TEXT, delivered INTEGER NOT NULL, device_id TEXT);`),this.prefs=new s(e)}prefs;chatFinishOn(e){return this.prefs.on(e,"finish")}setChatFinish(e,t,i=Date.now()){this.prefs.set(e,"finish",t,i)}subscribe(e,t=Date.now()){this.db.prepare(`INSERT OR REPLACE INTO push_subscriptions
|
|
9
9
|
(endpoint, p256dh, auth, device_id, device_name, public_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(e.endpoint,e.p256dh,e.auth,e.deviceId,e.deviceName,e.publicKey,t)}unsubscribe(e,t){return(t===void 0?this.db.prepare("DELETE FROM push_subscriptions WHERE endpoint = ?").run(e):this.db.prepare("DELETE FROM push_subscriptions WHERE endpoint = ? AND device_id = ?").run(e,t)).changes>0}list(e){return(e===void 0?this.db.prepare("SELECT * FROM push_subscriptions ORDER BY created_at").all():this.db.prepare("SELECT * FROM push_subscriptions WHERE device_id = ? ORDER BY created_at").all(e)).map(i=>({endpoint:i.endpoint,p256dh:i.p256dh,auth:i.auth,deviceId:i.device_id,deviceName:i.device_name,publicKey:i.public_key,createdAt:i.created_at}))}log(e,t,i=Date.now()){this.db.prepare("INSERT INTO push_log (at, title, body, url, delivered, device_id) VALUES (?, ?, ?, ?, ?, ?)").run(i,e.title,e.body,e.url,e.delivered,e.deviceId),this.db.prepare("DELETE FROM push_log WHERE id NOT IN (SELECT id FROM push_log ORDER BY id DESC LIMIT ?)").run(Math.max(0,t))}recent(e,t){let i="id, at, title, body, url, delivered, device_id AS deviceId";return t===void 0?this.db.prepare(`SELECT ${i} FROM push_log ORDER BY id DESC LIMIT ?`).all(Math.max(0,e)):this.db.prepare(`SELECT ${i} FROM push_log WHERE device_id IS NULL OR device_id = ? ORDER BY id DESC LIMIT ?`).all(t,Math.max(0,e))}};export{d as a};
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
//# sourceMappingURL=chunk-2NYP4OQU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/channels/push-store.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { PushPrefs } from \"./push-prefs\"\n\n// --- Web Push subscriptions and recent pushes (SQLite) ---\n//\n// Shared by two processes on the node that hosts the phone app: the\n// dashboard writes subscriptions when a phone turns notifications on\n// (/api/app/push/*), and the daemon's PushAdapter reads them to deliver,\n// prunes the ones the push service reports gone, and logs what it sent for\n// the app's Alerts tab. Both open the same .agentx/db.sqlite; WAL lets one\n// write while the other reads.\n//\n// Tables are created here with IF NOT EXISTS rather than as a numbered\n// migration, so a branch that claims the same migration number elsewhere\n// can't make a database skip them.\n\nexport interface PushSubscriptionRow {\n endpoint: string\n p256dh: string\n auth: string\n /** Token id of the paired phone (TokenRecord.id). */\n deviceId: string\n deviceName: string\n /** VAPID public key the browser subscribed with. After\n * `agentx app push-keys --force` older rows can never be delivered. */\n publicKey: string\n createdAt: number\n}\n\nexport interface PushLogRow {\n id: number\n at: number\n title: string\n body: string\n url: string | null\n /** Phones the push service accepted it for. */\n delivered: number\n /** Set when the push was addressed to one phone; null for every phone. */\n deviceId: string | null\n}\n\nexport class PushStore {\n constructor(private db: Database.Database) {\n db.exec(`CREATE TABLE IF NOT EXISTS push_subscriptions (\n endpoint TEXT PRIMARY KEY, p256dh TEXT NOT NULL, auth TEXT NOT NULL,\n device_id TEXT NOT NULL, device_name TEXT NOT NULL, public_key TEXT NOT NULL,\n created_at INTEGER NOT NULL);\n CREATE INDEX IF NOT EXISTS push_subscriptions_device ON push_subscriptions(device_id);\n CREATE TABLE IF NOT EXISTS push_log (\n id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, title TEXT NOT NULL,\n body TEXT NOT NULL, url TEXT, delivered INTEGER NOT NULL, device_id TEXT);`)\n this.prefs = new PushPrefs(db)\n }\n\n /** Per-phone switches for each kind of notification (push-prefs.ts). */\n readonly prefs: PushPrefs\n\n /** Whether this phone is told when a chat answer finishes while it looks\n * elsewhere (#265). On unless the phone turned it off. */\n chatFinishOn(deviceId: string): boolean {\n return this.prefs.on(deviceId, \"finish\")\n }\n\n setChatFinish(deviceId: string, on: boolean, now = Date.now()): void {\n this.prefs.set(deviceId, \"finish\", on, now)\n }\n\n /** Adds or refreshes a subscription. A browser that re-subscribes keeps\n * its endpoint, so the row is replaced, not duplicated. */\n subscribe(row: Omit<PushSubscriptionRow, \"createdAt\">, now = Date.now()): void {\n this.db.prepare(`INSERT OR REPLACE INTO push_subscriptions\n (endpoint, p256dh, auth, device_id, device_name, public_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`)\n .run(row.endpoint, row.p256dh, row.auth, row.deviceId, row.deviceName, row.publicKey, now)\n }\n\n /** Removes one subscription, only if it belongs to `deviceId` when given. */\n unsubscribe(endpoint: string, deviceId?: string): boolean {\n const r = deviceId === undefined\n ? this.db.prepare(\"DELETE FROM push_subscriptions WHERE endpoint = ?\").run(endpoint)\n : this.db.prepare(\"DELETE FROM push_subscriptions WHERE endpoint = ? AND device_id = ?\").run(endpoint, deviceId)\n return r.changes > 0\n }\n\n list(deviceId?: string): PushSubscriptionRow[] {\n const rows = (deviceId === undefined\n ? this.db.prepare(\"SELECT * FROM push_subscriptions ORDER BY created_at\").all()\n : this.db.prepare(\"SELECT * FROM push_subscriptions WHERE device_id = ? ORDER BY created_at\").all(deviceId)) as any[]\n return rows.map((r) => ({\n endpoint: r.endpoint, p256dh: r.p256dh, auth: r.auth,\n deviceId: r.device_id, deviceName: r.device_name, publicKey: r.public_key, createdAt: r.created_at,\n }))\n }\n\n /** Records a sent push and keeps only the newest `keep` rows. */\n log(entry: Omit<PushLogRow, \"id\" | \"at\">, keep: number, now = Date.now()): void {\n this.db.prepare(\"INSERT INTO push_log (at, title, body, url, delivered, device_id) VALUES (?, ?, ?, ?, ?, ?)\")\n .run(now, entry.title, entry.body, entry.url, entry.delivered, entry.deviceId)\n this.db.prepare(\"DELETE FROM push_log WHERE id NOT IN (SELECT id FROM push_log ORDER BY id DESC LIMIT ?)\").run(Math.max(0, keep))\n }\n\n /** Newest first. With `deviceId`, only pushes sent to every phone or to\n * that one, so one phone never sees another's messages. */\n recent(limit: number, deviceId?: string): PushLogRow[] {\n const cols = \"id, at, title, body, url, delivered, device_id AS deviceId\"\n return (deviceId === undefined\n ? this.db.prepare(`SELECT ${cols} FROM push_log ORDER BY id DESC LIMIT ?`).all(Math.max(0, limit))\n : this.db.prepare(`SELECT ${cols} FROM push_log WHERE device_id IS NULL OR device_id = ? ORDER BY id DESC LIMIT ?`)\n .all(deviceId, Math.max(0, limit))) as PushLogRow[]\n }\n}\n"],"mappings":"wCAyCO,IAAMA,EAAN,KAAgB,CACrB,YAAoBC,EAAuB,CAAvB,QAAAA,EAClBA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iFAOqE,EAC7E,KAAK,MAAQ,IAAIC,EAAUD,CAAE,CAC/B,CAGS,MAIT,aAAaE,EAA2B,CACtC,OAAO,KAAK,MAAM,GAAGA,EAAU,QAAQ,CACzC,CAEA,cAAcA,EAAkBC,EAAaC,EAAM,KAAK,IAAI,EAAS,CACnE,KAAK,MAAM,IAAIF,EAAU,SAAUC,EAAIC,CAAG,CAC5C,CAIA,UAAUC,EAA6CD,EAAM,KAAK,IAAI,EAAS,CAC7E,KAAK,GAAG,QAAQ;AAAA,4GACwF,EACrG,IAAIC,EAAI,SAAUA,EAAI,OAAQA,EAAI,KAAMA,EAAI,SAAUA,EAAI,WAAYA,EAAI,UAAWD,CAAG,CAC7F,CAGA,YAAYE,EAAkBJ,EAA4B,CAIxD,OAHUA,IAAa,OACnB,KAAK,GAAG,QAAQ,mDAAmD,EAAE,IAAII,CAAQ,EACjF,KAAK,GAAG,QAAQ,qEAAqE,EAAE,IAAIA,EAAUJ,CAAQ,GACxG,QAAU,CACrB,CAEA,KAAKA,EAA0C,CAI7C,OAHcA,IAAa,OACvB,KAAK,GAAG,QAAQ,sDAAsD,EAAE,IAAI,EAC5E,KAAK,GAAG,QAAQ,0EAA0E,EAAE,IAAIA,CAAQ,GAChG,IAAKK,IAAO,CACtB,SAAUA,EAAE,SAAU,OAAQA,EAAE,OAAQ,KAAMA,EAAE,KAChD,SAAUA,EAAE,UAAW,WAAYA,EAAE,YAAa,UAAWA,EAAE,WAAY,UAAWA,EAAE,UAC1F,EAAE,CACJ,CAGA,IAAIC,EAAsCC,EAAcL,EAAM,KAAK,IAAI,EAAS,CAC9E,KAAK,GAAG,QAAQ,6FAA6F,EAC1G,IAAIA,EAAKI,EAAM,MAAOA,EAAM,KAAMA,EAAM,IAAKA,EAAM,UAAWA,EAAM,QAAQ,EAC/E,KAAK,GAAG,QAAQ,yFAAyF,EAAE,IAAI,KAAK,IAAI,EAAGC,CAAI,CAAC,CAClI,CAIA,OAAOC,EAAeR,EAAiC,CACrD,IAAMS,EAAO,6DACb,OAAQT,IAAa,OACjB,KAAK,GAAG,QAAQ,UAAUS,0CAA6C,EAAE,IAAI,KAAK,IAAI,EAAGD,CAAK,CAAC,EAC/F,KAAK,GAAG,QAAQ,UAAUC,mFAAsF,EAC/G,IAAIT,EAAU,KAAK,IAAI,EAAGQ,CAAK,CAAC,CACvC,CACF","names":["PushStore","db","PushPrefs","deviceId","on","now","row","endpoint","r","entry","keep","limit","cols"]}
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-TERSIHOC.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-6CFAF5CH.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Wn,b as Kn,h as ss,n as rs,t as os,v as is}from"./chunk-
|
|
1
|
+
import{a as Wn,b as Kn,h as ss,n as rs,t as os,v as is}from"./chunk-ZIEUP56T.js";import{a as kt}from"./chunk-N6EWZGIX.js";import{a as Bn}from"./chunk-WP6KLXTP.js";import{b as qn}from"./chunk-DP7RTNDM.js";import{b as Jn,c as vt,d as Qn,e as Xn,h as Yn}from"./chunk-BHE5TJSN.js";import{a as It,b as Gn}from"./chunk-J3SOEFRE.js";import{a as St,b as zn}from"./chunk-SIU6STB2.js";import{e as Vn,i as Zn,j as es,k as ts}from"./chunk-X5C5W3E4.js";import{a as ns}from"./chunk-W4YR2RO2.js";import{a as Pn}from"./chunk-LQ5J6COO.js";import{a as _n,b as En,c as Dn,d as On,f as Nn}from"./chunk-DWADWDMU.js";import{a as Ln,b as Fn}from"./chunk-NO2HOK4B.js";import{a as Un}from"./chunk-AZBOYKQA.js";import{b as Hn,c as jn}from"./chunk-WGWNVLVW.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as $n,t as Mn,v as we,w as Rn}from"./chunk-PTB2TPOC.js";import{a as Pe,b as Ye,f as Tt}from"./chunk-72SZI2UW.js";import{a as be,b as wt}from"./chunk-FCPTN6NF.js";import{c as kn,d as In}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as Sn,e as oe,f as vn,g as Cn,h as xt,s as An,z as go}from"./chunk-OVF37EXJ.js";Rn();Tt();var as="session-continuity",cs={continues:Pe("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:Pe("Does the new request refer to something stated earlier in the conversation?")};function ds(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Ct(s.message,1200),previousRequest:s.previousMessage?Ct(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Ct(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function us(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Ct(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as po,execFile as ho}from"node:child_process";import{createHash as mo,randomBytes as fo}from"node:crypto";import{createInterface as yo}from"node:readline";import{promisify as bo}from"node:util";var wo=bo(ho),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},At=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=wo("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=mo("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:fo(32).toString("hex")},l=po("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=yo({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(d=!1)=>{c||(c=!0,a.busy=!1,d||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},ls=new At;import{execa as rt}from"execa";import{spawn as xo}from"node:child_process";import{createHash as To}from"node:crypto";import{createInterface as ko}from"node:readline";var ae=class extends Error{},Io=s=>xo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),$t=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(),ko({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)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Mt=class{constructor(e=Io,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}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 n=To("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("Conversation already running");r&&(r.fingerprint!==n||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 w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new $t(e,this.launchProcess)}}catch{throw new ae("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,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=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 w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,R)=>{if(R?.threadId!==l)return;let N=R.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),v==="thread/tokenUsage/updated"){let O=R.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(R.turn.status==="completed"?_():A(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),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())}}},gs=new Mt;import{execFile as Lo}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as Cs,readFileSync as As,rmSync as $s}from"fs";import{join as nt}from"path";import{tmpdir as Ms}from"os";function Ze(s){let e=(s||"").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]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,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 et(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ps=null;function tt(){return ps}function tc(s){ps=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},hs=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 n=Ee(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 xe(`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 xe(`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(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Ee(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=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().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Ee(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,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as So}from"child_process";import{existsSync as vo,readFileSync as Co}from"fs";import{resolve as Ao}from"path";function $o(s){let e=Ao(s,"CLAUDE.md");if(!vo(e))return null;try{let t=Co(e,"utf8");return Nn(t)}catch{return null}}var Mo=20*60*1e3,Ro=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},ms=class{constructor(e={}){this.opts=e}spawn(e,t){return new Rt(e,t,this.opts)}},Rt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=So(r,o,{cwd:t.workspace,env:_e({...process.env},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:$o(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();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),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=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??Mo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{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 n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ro);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];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),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};xt();import{resolve as fs,join as ys}from"path";wt();var Po=4e3;function bs(s){try{let e=ys(fs(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,Po):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Fo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};A.stdout?.on("data",g=>{M+=F.write(g);let T=M.split(`
|
|
28
28
|
`);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=Is():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...q(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?Is():k?.message;return{content:u,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function Qo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Xo(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=s.provider||"claude-code",I=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-BQ5CCARE.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(m)}catch{}if(m.type==="text_delta")C+=m.text,r(m.text,C);else if(m.type==="thinking_delta")m.text&&i&&i(m.text);else if(m.type==="generate_result"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-BQ5CCARE.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function Yo(s,e,t,n,r,o,i){let a=tt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Nt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=q(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(R=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=q(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=q(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:R}}function Fs(s){return oe(s.autonomy)?s.taskId?xs(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Vo(s,e,t,n,r,o,i){let a=e.autonomy,c=Ts(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Cn(a)}
|
|
@@ -148,4 +148,4 @@ ${$}`),f+=$.length}catch{}}}let io=mt.length>0?mt.join(`
|
|
|
148
148
|
|
|
149
149
|
Agent: ${$.content}`,meta:Na(Y,e.context)})}catch{}Fn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),nr(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=Ze(h.message);return le={content:"",error:et(f),errorKind:f.kind},le}finally{Tn.stop(),C(le)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;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:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=B(process.cwd(),Ae,this.safe(e.agentId),t);V(n)||Ma(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Pa(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=B(process.cwd(),Ae,this.safe(e));if(!V(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Oa){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Ra(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(n).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=B(n,i),c;try{c=ne(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ns();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:u,pending:p}}async continueFinishedTask(e,t,n,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 l=!1,u=p=>{l||(l=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Ba(s,e){return s===!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(`
|
|
150
150
|
`)}export{ls as a,gs as b,tc as c,hs as d,$o as e,ms as f,bs as g,pc as h,yc as i,bc as j,Wo as k,Ns as l,zo as m,Qo as n,Xo as o,Hs as p,it as q,at as r,Jc as s,Bt as t,ee as u,sr as v,$i as w,_i as x,ir as y,ud as z,ar as A,je as B,fa as C,ya as D,ba as E,wa as F,xa as G,zt as H,Bu as I,Wu as J,Na as K,La as L,Fa as M,en as N,jr as O,Ur as P,ja as Q,Br as R,Wr as S,Ba as T};
|
|
151
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
//# sourceMappingURL=chunk-AWKZ3BF2.js.map
|