agentix-cli 0.220.0 → 0.221.1
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-DXKDG4DQ.js} +2 -2
- package/dist/{board-dashboard-CZXKVKK7.js → board-dashboard-QV7OD4SO.js} +4 -4
- package/dist/{board-dashboard-CZXKVKK7.js.map → board-dashboard-QV7OD4SO.js.map} +1 -1
- package/dist/chunk-3323WFVK.js +13 -0
- package/dist/chunk-3323WFVK.js.map +1 -0
- package/dist/{chunk-RHNOMUYZ.js → chunk-575LJSX2.js} +3 -3
- package/dist/{chunk-XQH4LCZR.js → chunk-74MHOALB.js} +2 -2
- package/dist/{chunk-5XN2OMBS.js → chunk-AAPHOKWS.js} +2 -2
- package/dist/{chunk-3XS7M5LM.js → chunk-AAQOXNLE.js} +260 -260
- package/dist/chunk-AAQOXNLE.js.map +1 -0
- package/dist/chunk-EFXZACH4.js +2 -0
- package/dist/chunk-EFXZACH4.js.map +1 -0
- package/dist/chunk-FG2FPOML.js +2 -0
- package/dist/chunk-FG2FPOML.js.map +1 -0
- package/dist/{chunk-5RCWAXVK.js → chunk-FRYEUVYD.js} +21 -21
- package/dist/chunk-FRYEUVYD.js.map +1 -0
- package/dist/{chunk-SYIDD7CI.js → chunk-KQ3LPQ2Z.js} +2 -2
- package/dist/{chunk-M6TZ7IIJ.js → chunk-LO5A3VKY.js} +2 -2
- package/dist/{chunk-PSUOF7O5.js → chunk-O4EQAPBB.js} +2 -2
- package/dist/{chunk-E3SA7KIZ.js → chunk-RMB6G7X2.js} +2 -2
- package/dist/{chunk-5CUOKXOD.js → chunk-VYNM7HYU.js} +2 -2
- 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-Q4DXWAQU.js} +8 -8
- package/dist/{program-BRFPOZLO.js.map → program-Q4DXWAQU.js.map} +1 -1
- package/dist/registry-Q3H6QR6Q.js +2 -0
- package/dist/runner-KWSARUS4.js +2 -0
- package/dist/{sprint-tool-B2LNMNPB.js → sprint-tool-5NJYOFIZ.js} +2 -2
- package/dist/step-proof-GLY7XVPD.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-DXKDG4DQ.js.map} +0 -0
- /package/dist/{chunk-RHNOMUYZ.js.map → chunk-575LJSX2.js.map} +0 -0
- /package/dist/{chunk-XQH4LCZR.js.map → chunk-74MHOALB.js.map} +0 -0
- /package/dist/{chunk-5XN2OMBS.js.map → chunk-AAPHOKWS.js.map} +0 -0
- /package/dist/{chunk-SYIDD7CI.js.map → chunk-KQ3LPQ2Z.js.map} +0 -0
- /package/dist/{chunk-M6TZ7IIJ.js.map → chunk-LO5A3VKY.js.map} +0 -0
- /package/dist/{chunk-PSUOF7O5.js.map → chunk-O4EQAPBB.js.map} +0 -0
- /package/dist/{chunk-E3SA7KIZ.js.map → chunk-RMB6G7X2.js.map} +0 -0
- /package/dist/{chunk-5CUOKXOD.js.map → chunk-VYNM7HYU.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-Q3H6QR6Q.js.map} +0 -0
- /package/dist/{runner-56G3N7M4.js.map → runner-KWSARUS4.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-GLY7XVPD.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,13 @@
|
|
|
1
|
+
import{c as A,d as q,f as F,g as P,h as B}from"./chunk-4NZ4T3TQ.js";import{a as y,b as oe}from"./chunk-7I7IEX4S.js";import{existsSync as fe,linkSync as he,mkdirSync as ee,readdirSync as we,readFileSync as ye,renameSync as ke,unlinkSync as me,writeFileSync as te}from"fs";import{resolve as re}from"path";oe();import{appendFileSync as se,existsSync as ae,mkdirSync as ce,readFileSync as C,writeFileSync as W}from"fs";import{resolve as O}from"path";var K=500,M=200,I=e=>O(e,".agentx","approvals"),j=e=>O(I(e),"_answered.jsonl"),de=e=>O(I(e),"_answered.since"),S=e=>e&&e.length>M?e.slice(0,M-1)+"\u2026":e;function U(e,t){try{ue(e);let r={...t,title:S(t.title)??""};t.choice&&(r.choice=S(t.choice)),t.text?r.text=S(t.text):delete r.text;let n=j(e);se(n,JSON.stringify(r)+`
|
|
2
|
+
`);let i=C(n,"utf-8").split(`
|
|
3
|
+
`).filter(Boolean);i.length>K&&W(n,i.slice(-K).join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`)}catch(r){y.warn(`[approvals] answered list not written for ${t.key}: ${r?.message??r}`)}}function ue(e){let t=de(e);try{let n=C(t,"utf-8").trim();if(n)return n}catch{}let r=new Date().toISOString();try{ce(I(e),{recursive:!0}),W(t,r+`
|
|
6
|
+
`)}catch(n){y.warn(`[approvals] answered start not written: ${n?.message??n}`)}return r}function Te(e,t=50){let r=j(e);if(!ae(r))return[];let n=[],i;try{i=C(r,"utf-8").split(`
|
|
7
|
+
`).filter(Boolean)}catch(o){return y.warn(`[approvals] answered list not read: ${o?.message??o}`),[]}for(let o=i.length-1;o>=0&&n.length<t;o--)try{let s=JSON.parse(i[o]);s&&typeof s.key=="string"&&typeof s.at=="string"&&n.push(s)}catch{}return n}function Y(e,t){let r=[`This card was about the tracked number \`${e.numberId}\`, which missed its target twice in a row.`];return t.status==="decided"&&t.verdict==="yes"?(r.push("The question above gives both readings and the target. Find out why it misses, and change what you do, or propose a new target or source if those are wrong.","Say in one short message what you changed and when the next reading will show it."),e.reviewer&&e.reviewer!==t.raised_by&&r.push(`${e.reviewer} reviews your follow-up.`)):r.push("Change nothing for now. No new card comes until the number meets its target and then misses twice again."),r}function Ae(e){let t=e.origin?.kind==="number"?e.origin:void 0;if(!t?.reviewer||t.reviewer===e.raised_by||e.status!=="decided"||e.verdict!=="yes")return null;let r=[`[Number review] The operator said YES on "${e.title}" (${e.id}): ${e.raised_by} looks into why the tracked number \`${t.numberId}\` missed its target twice.`,`You are the reviewer for numbers. Check that ${e.raised_by} says what it changed, and look at the next reading of \`${t.numberId}\`.`];return e.note&&r.push(`Operator note: ${e.note}`),r.push("Do not change the number yourself; ask its owner."),{agentId:t.reviewer,text:r.join(`
|
|
8
|
+
`)}}function D(e){return e?.kind==="retro"||e?.kind==="retro-check"}var V={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function J(e,t,r){let n=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${n}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(t.status==="decided"&&t.verdict==="yes")||t.choice===V.keep||!t.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(t.choice===V.remove?`The operator chose to remove it. Delete ${n} as a pull request.`:`The operator chose to loosen it. Narrow ${n} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),t.choice_suggested&&i.push(G),r&&i.push("The operator's note:",r),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}var G="(The operator gave a plain yes, taken as the suggested option.)";function E(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==N}function z(e,t,r){let n=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!E(t))return n.push("Change nothing. Do not propose these fixes again on your own."),n;n.push(`The operator picked this fix: ${t.choice}`),t.choice_suggested&&n.push(G);let i=e.specs?.[(t.choices??[]).indexOf(t.choice)];return i&&n.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),r&&n.push("The operator's note on the fix:",r),n.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),n}var N="None of these";function H(e,t){let r=e.list?` in the "${e.list}" list`:"",n=[`This card came from the operator's reminder "${e.title}"${r} (id ${e.id}).`];return n.push(t?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),n}var d={title:120,ask:300,answers:3},R=["resurface","bring-back","weekly","cleanup"],k={perDay:5,resurface:3},le=[/\bhttps?:\/\/\S+/gi,/(?:[\w.-]+\/)*[\w.-]+[#!]\d+\b/g,/[#!]\d+\b/g,/\b[0-9A-HJKMNP-TV-Z]{26}\b/gi,/\b(?:req|dlg|snd)-[\w-]+/gi,/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\b/gi];function ge(e){return le.reduce((t,r)=>t.replace(r," "),e)}function X(e){let t=ge(e);return t===e||t.split(/\s+/).filter(n=>/\p{L}/u.test(n)).length>=2?null:`title is only a reference ("${e.trim()}"); say what it is in plain words, and put the link in the body or source`}function Q(e){let t=typeof e.title=="string"?e.title:"",r=typeof e.ask=="string"?e.ask:"";if(!t.trim())return"title is missing: say what it is in plain words";if(t.length>d.title)return`title is longer than ${d.title} characters`;let n=X(t);return n||(r.trim()?r.length>d.ask?`ask is longer than ${d.ask} characters`:(r.match(/\?/g)??[]).length>1?"ask holds more than one question: one card asks one thing":(e.choices?.length??0)>d.answers?`more than ${d.answers} choices`:null:"ask is missing: one card asks one thing")}function Fe(e,t){if(e.length>d.title)return`title is longer than ${d.title} characters`;let r=X(e);return r||(t.length>d.ask?`message is longer than ${d.ask} characters`:null)}function Pe(e,t){let r=t?.trim().replace(/\s+/g," ")||"nothing, FYI";return`${e}
|
|
9
|
+
To do: ${r}`}function pe(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Z(e,t,r){let n=pe(r),i=e.filter(o=>o.followup&&Date.parse(o.created_at)>=n);return i.length>=k.perDay?`the follow-up screen budget is used up today (${k.perDay} cards): raise it again tomorrow`:t==="resurface"&&i.filter(o=>o.followup==="resurface").length>=k.resurface?`${k.resurface} resurface cards were already raised today: raise it again tomorrow`:null}function Be(e,t){let r=e.title?.trim();return e.origin?.kind==="request"?[`[screen gate] Request ${e.id}${r?` ("${r}")`:""} was not shown to the owner: ${t}.`,`It is still on his list. Say what it is: agentx_request {action:"describe", id:"${e.id}", headline:"<a few plain words>", need:"<what you need from him>"}.`].join(" "):[`[screen gate] Your card ${e.id}${r?` ("${r}")`:""} was not shown to the owner: ${t}.`,"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:",`one question, title up to ${d.title} characters, ask up to ${d.ask}, at most ${d.answers} choices.`].join(" ")}var ne=["discard","keep","pause"];function T(e){return e==="approve"?"keep":ne.includes(e)?e:null}var g={title:120,ask:300,recommend:300,source:500,note:500,resolution:300,pendingPerAgent:25},xe={defaultExpiryDays:3,maxExpiryDays:30};function x(e){return re(e,".agentx","approvals")}var be=/^[a-z0-9][a-z0-9-]{0,80}$/;function ie(e){return be.test(e)}function L(e,t){if(!ie(t))throw new Error(`invalid card id: ${t}`);return re(x(e),`${t}.json`)}function _e(e,t){let r=new Date(e).toISOString().slice(0,10),n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${r}-${n||"card"}-${Math.random().toString(36).slice(2,6).padEnd(4,"0")}`}function b(e,t){ee(x(e),{recursive:!0});let r=L(e,t.id),n=`${r}.${process.pid}.tmp`;te(n,JSON.stringify(t,null,2)+`
|
|
10
|
+
`),ke(n,r)}function $e(e,t){ee(x(e),{recursive:!0});for(let r=1;;r++){let n=r===1?t:{...t,id:`${t.id}-${r}`},i=L(e,n.id),o=`${i}.${process.pid}.tmp`;te(o,JSON.stringify(n,null,2)+`
|
|
11
|
+
`);try{return he(o,i),n}catch(s){if(s.code!=="EEXIST")throw s}finally{me(o)}}}function _(e,t){if(!ie(t))return null;try{let r=JSON.parse(ye(L(e,t),"utf-8")),n=r.if_silent==="approve"||r.outcome==="approve";return{...r,if_silent:T(r.if_silent)??"keep",...r.outcome?{outcome:T(r.outcome)??"keep"}:{},...n?{if_silent_asked:"approve"}:{}}}catch{return null}}function m(e,t){let r=x(e);if(!fe(r))return[];let n=[];for(let i of we(r).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=_(e,i.slice(0,-5));o&&(!t||o.status===t)&&n.push(o)}return n}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function ve(e,t,r){let n=t+r.maxExpiryDays*864e5,i,o=a(e);if(!o)i=t+r.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=t+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=t?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,n)).toISOString()}}function Se(e,t={}){let r=t.now??Date.now(),n=t.settings??xe,i=a(e.title),o=a(e.ask),s=a(e.recommend),u=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!u)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>g.title)return{ok:!1,error:`title is longer than ${g.title} characters`};if(o.length>g.ask)return{ok:!1,error:`ask is longer than ${g.ask} characters`};if(s.length>g.recommend)return{ok:!1,error:`recommend is longer than ${g.recommend} characters`};let l=a(e.if_silent).toLowerCase(),p=T(l);if(!p)return{ok:!1,error:`if_silent must be one of ${ne.join(", ")}`};let c=ve(e.expires,r,n);if(!c.ok)return c;let h=a(e.source);if(h.length>g.source)return{ok:!1,error:`source is longer than ${g.source} characters`};if(h&&/^[a-z][a-z0-9+.-]*:/i.test(h)&&!/^https?:\/\//i.test(h))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let $=A(e);if(!$.ok)return $;let w=a(e.followup).toLowerCase();if(w&&!R.includes(w))return{ok:!1,error:`followup must be one of ${R.join(", ")}`};let v,f=e.reply;return f&&typeof f=="object"&&a(f.channel)&&a(f.chatId)&&(v={channel:a(f.channel),chatId:a(f.chatId),...a(f.accountId)?{accountId:a(f.accountId)}:{}}),{ok:!0,card:{id:_e(r,i),title:i,ask:o,recommend:s,if_silent:p,...l==="approve"?{if_silent_asked:"approve"}:{},expires:c.at,...h?{source:h}:{},raised_by:u,...t.node?{node:t.node}:{},created_at:new Date(r).toISOString(),...v?{reply:v}:{},...$.value,...t.origin?{origin:t.origin}:{},...w?{followup:w}:{},...t.popupOnly?{popup_only:!0}:{},status:"pending"}}}function Ce(e,t){if(!(!t.source||t.origin))return e.find(r=>!r.origin&&r.source===t.source&&r.raised_by===t.raised_by&&(r.node??"")===(t.node??""))}function Je(e,t,r={}){let n=Se(t,r);if(!n.ok)return n;let i=Q(n.card);if(i)return{ok:!1,error:i};if(n.card.followup){let c=Z(m(e),n.card.followup,r.now??Date.now());if(c)return{ok:!1,error:c}}let o=m(e,"pending"),s=Ce(o,n.card);if(s)return{ok:!1,error:`a card from you on this source is still pending: ${s.id}. Wait for its answer, or resolve it first and then raise the new one.`};let u=c=>D(c.origin),l=u(n.card),p=o.filter(c=>c.raised_by===n.card.raised_by&&u(c)===l).length;if(p>=g.pendingPerAgent){let c=l?"retro cards":"cards";return{ok:!1,error:`${n.card.raised_by} already has ${p} ${c} waiting; wait for decisions before raising more`}}return{ok:!0,card:$e(e,n.card)}}var Oe="this card takes a yes only in the popup on the home machine; here it can only be answered no";function Ge(e,t,r,n={}){let i=_(e,t);if(!i)return{ok:!1,error:`no card "${t}"`};if(i.status!=="pending")return{ok:!1,error:`card "${t}" is already ${i.status}`};if(i.popup_only&&r==="yes"&&!n.popup)return{ok:!1,error:Oe};let o=F(i,r,n);if(!o.ok)return o;let s=r==="yes"&&P(o.choice)&&!D(i.origin),u=s?"no":r,l=a(n.note).slice(0,g.note),p={...i,status:"decided",verdict:u,decided_by:n.by??"operator",...n.popup?{decided_from:"popup"}:{},decided_at:new Date(n.now??Date.now()).toISOString(),...l?{note:l}:{},...o.choice?{choice:o.choice}:{},...o.suggested?{choice_suggested:!0}:{},...o.text&&!s?{text:o.text}:{}};return b(e,p),{ok:!0,card:p}}var Ie=new Set([void 0,"reminder"]);function ze(e,t,r){let n=_(e,t);if(!n)return{ok:!1,status:404,error:`no card "${t}"`};if(n.raised_by!==r.by||(n.node??"")!==(r.node??"")){let u=n.node?`${n.raised_by} on node "${n.node}"`:n.raised_by,l=n.node?"it closes it through its own node's daemon":"it closes it from one of its running turns";return{ok:!1,status:403,error:`card "${t}" was raised by another agent (${u}): only that agent can close it (${l}), or the operator answers it in Approvals`}}if(!Ie.has(n.origin?.kind))return{ok:!1,status:409,error:`card "${t}" is answered by the operator only`};if(n.status!=="pending")return{ok:!1,status:409,error:`card "${t}" is already ${n.status}`};let i=a(r.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(r.now??Date.now()).toISOString(),s={...n,status:"resolved",decided_by:r.by,decided_at:o,resolution:i.slice(0,g.resolution),agent_notified_at:o,...r.via?{closed_via:r.via}:{}};return b(e,s),U(e,{key:`card:${t}`,kind:"card",title:n.title,raised_by:n.raised_by,answer:"closed",text:s.resolution,at:o,by:r.node?`${r.by} on ${r.node}`:r.via?`${r.by} (workflow step ${r.via.nodeId})`:r.by}),{ok:!0,card:s}}function He(e,t=Date.now()){let r=[];for(let n of m(e,"pending")){if(Date.parse(n.expires)>t)continue;let i={...n,status:"expired",outcome:n.if_silent,decided_by:"expiry",decided_at:new Date(t).toISOString()};b(e,i),r.push(i)}return r}function Xe(e){return m(e).filter(t=>t.status!=="pending"&&!t.agent_notified_at)}function Qe(e,t,r=Date.now()){let n=_(e,t);!n||n.agent_notified_at||b(e,{...n,agent_notified_at:new Date(r).toISOString()})}var De="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function Ze(e){let t=e.origin?.kind==="retro"?e.origin:void 0,r=e.status==="decided"?e.verdict==="yes"?t&&!E(e)?`The operator picked "${N}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,n=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,r],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!t&&!i&&n.push(...B(e)),e.status==="decided"&&e.verdict==="no"&&e.choice&&!t&&!i&&n.push(`Chosen: ${e.choice} (this option means no; do not send or do it)`),e.note&&n.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!t&&!i&&n.push(De),e.source&&n.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&n.push(...H(e.origin,e.status==="decided"&&e.verdict==="yes")),e.origin?.kind==="number"&&n.push(...Y(e.origin,e)),t||i){let o=l=>l.replace(/\s+/g," ").trim(),s=q(e.draft,e.choice),u=e.text&&o(e.text)!==o(s)?e.text:void 0;n.push(...t?z(t,e,u):J(i,e,u))}return e.reply&&n.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&n.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),n.push("Act on this result now. Do not raise the same card again."),n.join(`
|
|
12
|
+
`)}export{U as a,ue as b,Te as c,Ae as d,D as e,V as f,E as g,N as h,X as i,Q as j,Fe as k,Pe as l,Be as m,ne as n,g as o,x as p,ie as q,b as r,_ as s,m as t,Je as u,Ge as v,ze as w,He as x,Xe as y,Qe as z,Ze as A};
|
|
13
|
+
//# sourceMappingURL=chunk-3323WFVK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/answered.ts","../src/approvals/origin.ts","../src/approvals/screen-gate.ts"],"sourcesContent":["import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { recordAnswered } from \"./answered\"\nimport { answerLines, buildChoices, draftFor, isNoChoice, resolveAnswer, type CardChoices } from \"./choices\"\nimport { isRetroOrigin, numberLines, originLines, RETRO_NONE, retroApproved, retroCheckLines, retroLines, type CardOrigin } from \"./origin\"\nimport { cardRuleBreak, FOLLOWUP_KINDS, followupBudgetRefusal, type FollowupKind } from \"./screen-gate\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\n// \"resolved\": closed by the agent that raised it, because the owner gave the\n// same answer somewhere else (in chat, #909) and the agent already acted on\n// it. Not a verdict: nothing is approved or rejected by it.\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\" | \"resolved\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n /** \"popup\" when the answer was clicked in the daemon's popup on this\n * machine. Unset for every other way in: the dashboard (even opened\n * here), the CLI, a phone, a mesh peer or a channel reply (#1478). */\n decided_from?: \"popup\"\n /** A yes counts only from the popup (owner sign-in, #1478): every other\n * way in can say no, never yes. Set by the daemon, never from input. */\n popup_only?: true\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** Set when `choice` came from a plain yes taking the suggested option\n * (#1064), not from the operator picking it. */\n choice_suggested?: boolean\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** Why the raising agent closed it (status \"resolved\"). */\n resolution?: string\n /** Set when a running workflow step of that agent closed it (#1849). */\n closed_via?: { kind: \"workflow-step\"; runId: string; nodeId: string }\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n /** A follow-up card (#394): counted in the daily screen budget. */\n followup?: FollowupKind\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n resolution: 300,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6).padEnd(4, \"0\")}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\n/**\n * Save a card that is new. Its id is random, so two cards with the same\n * title on the same day can draw the same one: then the id gets \"-2\", \"-3\"\n * and so on, and a card already on disk is never overwritten. The link\n * fails if the file exists, so this holds across processes too.\n */\nfunction saveNewCard(root: string, card: DecisionCard): DecisionCard {\n mkdirSync(approvalsDir(root), { recursive: true })\n for (let n = 1; ; n++) {\n const saved = n === 1 ? card : { ...card, id: `${card.id}-${n}` }\n const path = fileFor(root, saved.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(saved, null, 2) + \"\\n\")\n try {\n linkSync(tmp, path)\n return saved\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e\n } finally {\n unlinkSync(tmp)\n }\n }\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n followup?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n /** Set by the daemon only: see DecisionCard.popup_only. */\n popupOnly?: boolean\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n const followup = oneLine(input.followup).toLowerCase()\n if (followup && !(FOLLOWUP_KINDS as readonly string[]).includes(followup)) {\n return { ok: false, error: `followup must be one of ${FOLLOWUP_KINDS.join(\", \")}` }\n }\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n ...(followup ? { followup: followup as FollowupKind } : {}),\n ...(opts.popupOnly ? { popup_only: true as const } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** A pending card the same agent, on the same node, raised on the same\n * source. None when the new card has no source or the daemon raised it. */\nfunction sameSourcePending(pending: DecisionCard[], card: DecisionCard): DecisionCard | undefined {\n if (!card.source || card.origin) return undefined\n return pending.find((c) =>\n !c.origin &&\n c.source === card.source &&\n c.raised_by === card.raised_by &&\n (c.node ?? \"\") === (card.node ?? \"\"))\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // The screen gate (#394): refused here, the reason goes back to the author.\n const broken = cardRuleBreak(built.card)\n if (broken) return { ok: false, error: broken }\n if (built.card.followup) {\n const full = followupBudgetRefusal(listCards(root), built.card.followup, opts.now ?? Date.now())\n if (full) return { ok: false, error: full }\n }\n const pending = listCards(root, \"pending\")\n // One open question per source: the same question raised twice comes\n // back after it was answered. Only for cards an agent raised; cards the\n // daemon raises (origin set) keep their own rules, such as a merge card\n // per pushed commit on the same PR link.\n const twin = sameSourcePending(pending, built.card)\n if (twin) {\n return { ok: false, error: `a card from you on this source is still pending: ${twin.id}. Wait for its answer, or resolve it first and then raise the new one.` }\n }\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => isRetroOrigin(c.origin)\n const retro = isRetro(built.card)\n const open = pending.filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n return { ok: true, card: saveNewCard(root, built.card) }\n}\n\nexport const POPUP_ONLY = \"this card takes a yes only in the popup on the home machine; here it can only be answered no\"\n\n/** Record the operator's answer. Refuses anything no longer pending, and a\n * yes on a popup-only card from anywhere but the popup. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string; popup?: boolean } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n if (card.popup_only && verdict === \"yes\" && !opts.popup) return { ok: false, error: POPUP_ONLY }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n // A yes with an option that means no (\"Don't send\") is a no (#1788): the\n // pick is kept, the text is dropped, so nothing reads as \"send this\".\n // Retro cards keep their own rule for their none-option (origin.ts).\n const saysNo = verdict === \"yes\" && isNoChoice(answer.choice) && !isRetroOrigin(card.origin)\n const final: Verdict = saysNo ? \"no\" : verdict\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict: final,\n decided_by: opts.by ?? \"operator\",\n ...(opts.popup ? { decided_from: \"popup\" as const } : {}),\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.suggested ? { choice_suggested: true } : {}),\n ...(answer.text && !saysNo ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Cards whose answer the daemon acts on itself (a workflow run, a plan\n * step, a retro): only the operator closes those. A reminder card is the\n * agent's own to act on, so it may close it like one it raised. */\nconst AGENT_RESOLVABLE_ORIGINS = new Set<string | undefined>([undefined, \"reminder\"])\n\n/**\n * The raising agent closes its own pending card: the owner gave the same\n * answer outside the card (in chat) and the agent has acted on it (#909).\n * The card leaves the inbox, so no check-in or popup asks again. It is not\n * a verdict, and the agent is not sent a result for it: it already knows.\n */\nexport function resolveCard(\n root: string,\n id: string,\n opts: { by: string; reason?: unknown; node?: string; now?: number; via?: DecisionCard[\"closed_via\"] },\n): { ok: true; card: DecisionCard } | { ok: false; status: 400 | 403 | 404 | 409; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, status: 404, error: `no card \"${id}\"` }\n if (card.raised_by !== opts.by || (card.node ?? \"\") !== (opts.node ?? \"\")) {\n // Name the raiser, so the caller knows who can close it (#1405).\n const who = card.node ? `${card.raised_by} on node \"${card.node}\"` : card.raised_by\n const how = card.node ? \"it closes it through its own node's daemon\" : \"it closes it from one of its running turns\"\n return { ok: false, status: 403, error: `card \"${id}\" was raised by another agent (${who}): only that agent can close it (${how}), or the operator answers it in Approvals` }\n }\n if (!AGENT_RESOLVABLE_ORIGINS.has(card.origin?.kind)) {\n return { ok: false, status: 409, error: `card \"${id}\" is answered by the operator only` }\n }\n if (card.status !== \"pending\") return { ok: false, status: 409, error: `card \"${id}\" is already ${card.status}` }\n const reason = oneLine(opts.reason)\n if (!reason) return { ok: false, status: 400, error: \"reason is required: say where the owner answered and what you did\" }\n const at = new Date(opts.now ?? Date.now()).toISOString()\n const resolved: DecisionCard = {\n ...card,\n status: \"resolved\",\n decided_by: opts.by,\n decided_at: at,\n resolution: reason.slice(0, CARD_LIMITS.resolution),\n agent_notified_at: at,\n ...(opts.via ? { closed_via: opts.via } : {}),\n }\n saveCard(root, resolved)\n // On the Wall's Answered tab too, whichever way the close came (#1440).\n recordAnswered(root, {\n key: `card:${id}`, kind: \"card\", title: card.title, raised_by: card.raised_by, answer: \"closed\",\n text: resolved.resolution, at,\n by: opts.node ? `${opts.by} on ${opts.node}` : opts.via ? `${opts.by} (workflow step ${opts.via.nodeId})` : opts.by,\n })\n return { ok: true, card: resolved }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\nexport const NO_UNDO_LINE =\n \"A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.\"\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n const check = card.origin?.kind === \"retro-check\" ? card.origin : undefined\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro && !check) lines.push(...answerLines(card))\n if (card.status === \"decided\" && card.verdict === \"no\" && card.choice && !retro && !check) lines.push(`Chosen: ${card.choice} (this option means no; do not send or do it)`)\n if (card.note) lines.push(`Operator note: ${card.note}`)\n // A late no on something the owner already approved in chat must not\n // quietly undo work that is done (#909).\n if (card.status === \"decided\" && card.verdict === \"no\" && !retro && !check) lines.push(NO_UNDO_LINE)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (card.origin?.kind === \"number\") lines.push(...numberLines(card.origin, card))\n if (retro || check) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...(retro ? retroLines(retro, card, edited) : retroCheckLines(check!, card, edited)))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { logger } from \"@/utils/logger\"\n\n// --- What the owner answered, across every kind (#1440) ---\n//\n// Each source keeps its own decision (the card file, the schedule, the\n// memory fact, the wiki proposal, the draft). This is only the list the\n// Wall's Answered tab reads: one line per yes or no that went through\n// decide() (inbox.ts), whichever surface sent it, and one per card its\n// agent closed (resolveCard, cards.ts). A close is the agent's word: the\n// owner may have answered elsewhere, or the agent may have withdrawn the\n// card. Reviews and request replies do not pass through decide() and are\n// not listed. \"Later\" is not an answer. It starts empty: `_answered.since` keeps the\n// day it started, so the page can say so.\n\nexport interface AnsweredItem {\n key: string\n kind: string\n title: string\n raised_by: string\n /** \"closed\": the agent that raised the card closed it (resolveCard). */\n answer: \"yes\" | \"no\" | \"closed\"\n /** Cards with choices: the one picked. */\n choice?: string\n /** The short answer: the owner's text, or the agent's reason for closing. */\n text?: string\n by: string\n at: string\n}\n\n/** Lines kept: the oldest go once the file passes this. */\nconst KEEP = 500\n/** Free text kept per line. */\nconst TEXT_MAX = 200\n\n// approvalsDir (cards.ts), not imported: cards.ts records here.\nconst dir = (root: string) => resolve(root, \".agentx\", \"approvals\")\nconst answeredFile = (root: string) => resolve(dir(root), \"_answered.jsonl\")\nconst sinceFile = (root: string) => resolve(dir(root), \"_answered.since\")\nconst cap = (s: string | undefined) => (s && s.length > TEXT_MAX ? s.slice(0, TEXT_MAX - 1) + \"…\" : s)\n\n/** Never throws: the answer stands, the list is only a view of it. */\nexport function recordAnswered(root: string, item: AnsweredItem): void {\n try {\n answeredSince(root)\n const line: AnsweredItem = { ...item, title: cap(item.title) ?? \"\" }\n if (item.choice) line.choice = cap(item.choice)\n if (item.text) line.text = cap(item.text)\n else delete line.text\n const path = answeredFile(root)\n appendFileSync(path, JSON.stringify(line) + \"\\n\")\n const lines = readFileSync(path, \"utf-8\").split(\"\\n\").filter(Boolean)\n if (lines.length > KEEP) writeFileSync(path, lines.slice(-KEEP).join(\"\\n\") + \"\\n\")\n } catch (e: any) {\n logger.warn(`[approvals] answered list not written for ${item.key}: ${e?.message ?? e}`)\n }\n}\n\n/** The day the list started: written by the first answer or the first read. */\nexport function answeredSince(root: string): string {\n const path = sinceFile(root)\n try {\n const at = readFileSync(path, \"utf-8\").trim()\n if (at) return at\n } catch {\n // Not written yet: this is the start.\n }\n const at = new Date().toISOString()\n try {\n mkdirSync(dir(root), { recursive: true })\n writeFileSync(path, at + \"\\n\")\n } catch (e: any) {\n logger.warn(`[approvals] answered start not written: ${e?.message ?? e}`)\n }\n return at\n}\n\n/** Newest first, at most `limit`. A line that does not parse is skipped. */\nexport function readAnswered(root: string, limit = 50): AnsweredItem[] {\n const path = answeredFile(root)\n if (!existsSync(path)) return []\n const out: AnsweredItem[] = []\n let lines: string[]\n try {\n lines = readFileSync(path, \"utf-8\").split(\"\\n\").filter(Boolean)\n } catch (e: any) {\n logger.warn(`[approvals] answered list not read: ${e?.message ?? e}`)\n return []\n }\n for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {\n try {\n const v = JSON.parse(lines[i])\n if (v && typeof v.key === \"string\" && typeof v.at === \"string\") out.push(v)\n } catch {\n // A torn last line from a crash mid-write: the rest still reads.\n }\n }\n return out\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\n/** A monthly review of a check a retro added (src/retro/checks.ts): a\n * guard rule tagged `retro:<taskId>` that fires often on runs that went\n * well. The answer goes back to the agent that built it, which keeps,\n * loosens or removes it for a second review. */\nexport interface RetroCheckOrigin {\n kind: \"retro-check\"\n /** The guard rule's id. */\n ruleId: string\n /** The run whose retro asked for the rule. */\n taskId: string\n /** The policy file that holds the rule, relative to the daemon's folder. */\n file: string\n}\n\n/** A step of a workflow run asks the owner (src/workflows, #788): an\n * owner.ask step, a person.message to approve, or a run's approval at\n * start. The answer resumes the run; the agent that started it is not\n * told separately, the run is. */\nexport interface WorkflowOrigin {\n kind: \"workflow\"\n runId: string\n nodeId: string\n}\n\n/** An agent proposed a reusable workflow (#788). Yes turns it on. */\nexport interface WorkflowProposalOrigin {\n kind: \"workflow-proposal\"\n workflowId: string\n}\n\n/** A step of a tracked plan the owner approves when the plan is made\n * (src/requests/plan-sweep.ts, #788). The plan check reads the answer\n * and acts on it; the agent is not sent a result turn. */\nexport interface PlanStepOrigin {\n kind: \"plan-step\"\n requestId: string\n step: number\n}\n\n/** A pull request that changes core paths waits for the owner (merge\n * policy, #1047). YES approves that one commit; the policy reads the\n * answer and updates the PR's status. No agent is sent a result turn. */\nexport interface MergePolicyOrigin {\n kind: \"merge-policy\"\n repo: string\n pr: number\n sha: string\n}\n\n/** The owner asked an agent in chat to change the org chart (#1678). The\n * changes are kept beside the card (business/org-proposals.ts); YES makes\n * the daemon apply them, and the agent is told what happened. */\nexport interface OrgProposalOrigin {\n kind: \"org-proposal\"\n}\n\n/** A write tool of an MCP server with an allow list waits for the owner\n * (agent/mcp-confirm.ts, #1736). The waiting call reads the answer; the\n * agent is not sent a result turn. */\nexport interface McpWriteOrigin {\n kind: \"mcp-write\"\n server: string\n tool: string\n}\n\n/** A tracked number missed its target twice in a row (src/numbers/\n * review.ts, #1826). Raised for the number's owner agent, which is told\n * the answer; a reviewer set in `numbers.reviewer` is told a yes too. */\nexport interface NumberOrigin {\n kind: \"number\"\n numberId: string\n /** Start of the window of the first miss of the run (UTC ms). */\n streakStart: number\n /** The agent that checks the owner's follow-up, when set. */\n reviewer?: string\n}\n\n/** Lines for the owner agent told the result of a missed-twice card. */\nexport function numberLines(origin: NumberOrigin, card: { status: string; verdict?: string; raised_by: string }): string[] {\n const lines = [`This card was about the tracked number \\`${origin.numberId}\\`, which missed its target twice in a row.`]\n if (card.status === \"decided\" && card.verdict === \"yes\") {\n lines.push(\n \"The question above gives both readings and the target. Find out why it misses, and change what you do, or propose a new target or source if those are wrong.\",\n \"Say in one short message what you changed and when the next reading will show it.\",\n )\n if (origin.reviewer && origin.reviewer !== card.raised_by) lines.push(`${origin.reviewer} reviews your follow-up.`)\n } else {\n lines.push(\"Change nothing for now. No new card comes until the number meets its target and then misses twice again.\")\n }\n return lines\n}\n\n/** The turn told to a number's reviewer when the operator said yes on its\n * missed-twice card. Null when there is nothing to review. */\nexport function numberReviewerMessage(card: { id: string; title: string; status: string; verdict?: string; raised_by: string; note?: string; origin?: CardOrigin }): { agentId: string; text: string } | null {\n const origin = card.origin?.kind === \"number\" ? card.origin : undefined\n if (!origin?.reviewer || origin.reviewer === card.raised_by) return null\n if (card.status !== \"decided\" || card.verdict !== \"yes\") return null\n const lines = [\n `[Number review] The operator said YES on \"${card.title}\" (${card.id}): ${card.raised_by} looks into why the tracked number \\`${origin.numberId}\\` missed its target twice.`,\n `You are the reviewer for numbers. Check that ${card.raised_by} says what it changed, and look at the next reading of \\`${origin.numberId}\\`.`,\n ]\n if (card.note) lines.push(`Operator note: ${card.note}`)\n lines.push(\"Do not change the number yourself; ask its owner.\")\n return { agentId: origin.reviewer, text: lines.join(\"\\n\") }\n}\n\nexport type CardOrigin = NumberOrigin | McpWriteOrigin | ReminderOrigin | RequestOrigin | RetroOrigin | RetroCheckOrigin | PlanStepOrigin | WorkflowOrigin | WorkflowProposalOrigin | MergePolicyOrigin | OrgProposalOrigin\n\n/** Retro cards of either kind: raised for an agent, not by it. */\nexport function isRetroOrigin(origin: CardOrigin | undefined): origin is RetroOrigin | RetroCheckOrigin {\n return origin?.kind === \"retro\" || origin?.kind === \"retro-check\"\n}\n\n/** The choices on a check review card, in this order. */\nexport const CHECK_CHOICES = { keep: \"Keep it\", loosen: \"Loosen it\", remove: \"Remove it\" } as const\n\n/** Lines for the agent told the result of a check review card. Keep, NO\n * and silence all leave the rule as it is. */\nexport function retroCheckLines(\n origin: RetroCheckOrigin,\n card: { status: string; verdict?: string; choice?: string; choice_suggested?: boolean },\n edited?: string,\n): string[] {\n const rule = `guard rule \\`${origin.ruleId}\\` in \\`${origin.file}\\``\n const lines = [`This was a monthly review of ${rule}, added by the retro on run ${origin.taskId}. It fires often on runs that went well.`]\n const yes = card.status === \"decided\" && card.verdict === \"yes\"\n if (!yes || card.choice === CHECK_CHOICES.keep || !card.choice) {\n lines.push(\"Change nothing: the rule stays as it is.\")\n return lines\n }\n lines.push(card.choice === CHECK_CHOICES.remove\n ? `The operator chose to remove it. Delete ${rule} as a pull request.`\n : `The operator chose to loosen it. Narrow ${rule} (a tighter match, or \\`applies_to\\`) so it stops firing on good work, keep its \\`retro:${origin.taskId}\\` tag, and open it as a pull request.`)\n if (card.choice_suggested) lines.push(SUGGESTED_NOTE)\n if (edited) lines.push(\"The operator's note:\", edited)\n lines.push(\"Do not change the live policy directly: the operator reviews the pull request first.\")\n return lines\n}\n\n/** Told to the agent when the choice came from a plain yes (#1064): the\n * operator accepted the suggestion rather than picking it by hand. */\nconst SUGGESTED_NOTE = \"(The operator gave a plain yes, taken as the suggested option.)\"\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[]; choice_suggested?: boolean },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n if (card.choice_suggested) lines.push(SUGGESTED_NOTE)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n","// --- The screen gatekeeper (#394, plan section 1b) ---\n//\n// What the fleet puts on the owner's screen passes one check, by script,\n// no model:\n// - one question per card; a title and an ask short enough to read in\n// about ten seconds (title 120, ask 300 characters);\n// - at most 3 ready-made answers (a plain card has Yes, No, Not now);\n// - follow-up cards (resurface, bring-back, weekly, clean-up) share a\n// budget of 5 a day, at most 3 of them resurface cards;\n// - a title says what it is in words: a bare reference (\"#402\", a hash,\n// a request id) means nothing to someone glancing at a screen.\n// A card that fails is returned to its author with the reason: refused\n// when it is written, or not shown and told when the popup comes to it.\n// Nothing here rewrites, removes or answers a card. The call and Focus\n// hold is notify/hold.ts; the popup window takes no focus (card-window.ts).\n\nexport const SCREEN_LIMITS = { title: 120, ask: 300, answers: 3 } as const\n\nexport const FOLLOWUP_KINDS = [\"resurface\", \"bring-back\", \"weekly\", \"cleanup\"] as const\nexport type FollowupKind = (typeof FOLLOWUP_KINDS)[number]\n\nexport const SCREEN_BUDGET = { perDay: 5, resurface: 3 } as const\n\n// References an agent reads easily and the owner does not: links, issue\n// and merge request numbers (with or without their project), ULID-like\n// ids, request, delegation and send ids, and commit hashes. A hex run\n// needs a digit and a letter a-f, so neither a word made of a-f letters\n// nor a plain long number (a phone number, an amount) is taken for one.\nconst REFERENCES: RegExp[] = [\n /\\bhttps?:\\/\\/\\S+/gi,\n /(?:[\\w.-]+\\/)*[\\w.-]+[#!]\\d+\\b/g,\n /[#!]\\d+\\b/g,\n /\\b[0-9A-HJKMNP-TV-Z]{26}\\b/gi,\n /\\b(?:req|dlg|snd)-[\\w-]+/gi,\n /\\b(?=[0-9a-f]*\\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\\b/gi,\n]\n\n/** The title with every reference taken out. */\nexport function stripReferences(text: string): string {\n return REFERENCES.reduce((t, re) => t.replace(re, \" \"), text)\n}\n\n/** Why a title that is only a reference may not go on screen, or null.\n * A title with a reference must keep at least 2 words of letters once\n * the references are out; a title with none is left to the other rules. */\nexport function referenceOnlyTitle(title: string): string | null {\n const rest = stripReferences(title)\n if (rest === title) return null\n const words = rest.split(/\\s+/).filter((w) => /\\p{L}/u.test(w))\n if (words.length >= 2) return null\n return `title is only a reference (\"${title.trim()}\"); say what it is in plain words, and put the link in the body or source`\n}\n\n/** Why this card may not go on the owner's screen, or null. */\nexport function cardRuleBreak(card: { title?: string; ask?: string; choices?: string[]; origin?: { kind: string } }): string | null {\n // A card file written by hand or by an older build may miss either:\n // returned to its author, never a crash of the popup.\n const title = typeof card.title === \"string\" ? card.title : \"\"\n const ask = typeof card.ask === \"string\" ? card.ask : \"\"\n if (!title.trim()) return \"title is missing: say what it is in plain words\"\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n // A request's card is held to the rule too (#1126): it is titled with\n // its headline, which its agent can write (agentx_request describe).\n const bare = referenceOnlyTitle(title)\n if (bare) return bare\n if (!ask.trim()) return \"ask is missing: one card asks one thing\"\n if (ask.length > SCREEN_LIMITS.ask) return `ask is longer than ${SCREEN_LIMITS.ask} characters`\n if ((ask.match(/\\?/g) ?? []).length > 1) return \"ask holds more than one question: one card asks one thing\"\n if ((card.choices?.length ?? 0) > SCREEN_LIMITS.answers) return `more than ${SCREEN_LIMITS.answers} choices`\n return null\n}\n\n/** Why an agent's `agentx notify` may not go on the owner's screen, or\n * null: the same ten-second rule, title 120 and message 300 (the message\n * as shown, with its \"To do:\" line), and a title in words. */\nexport function noticeRuleBreak(title: string, message: string): string | null {\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n const bare = referenceOnlyTitle(title)\n if (bare) return bare\n if (message.length > SCREEN_LIMITS.ask) return `message is longer than ${SCREEN_LIMITS.ask} characters`\n return null\n}\n\n/** An agent's notice as the owner reads it: the message, then the\n * \"To do:\" line. With nothing to do, it says so, so the owner never has\n * to guess whether a notice wants something. Last, so a banner that\n * shows only the first line still shows the message. */\nexport function withTodo(message: string, todo?: string): string {\n const what = todo?.trim().replace(/\\s+/g, \" \") || \"nothing, FYI\"\n return `${message}\\nTo do: ${what}`\n}\n\n/** Local midnight before `now`: the budget's day. */\nfunction dayStart(now: number): number {\n const d = new Date(now)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/** Why a follow-up card of this kind cannot be raised today, or null.\n * `cards` is every card, of any status: an answered one was on screen too. */\nexport function followupBudgetRefusal(\n cards: Array<{ followup?: FollowupKind; created_at: string }>,\n kind: FollowupKind,\n now: number,\n): string | null {\n const from = dayStart(now)\n const today = cards.filter((c) => c.followup && Date.parse(c.created_at) >= from)\n if (today.length >= SCREEN_BUDGET.perDay) {\n return `the follow-up screen budget is used up today (${SCREEN_BUDGET.perDay} cards): raise it again tomorrow`\n }\n if (kind === \"resurface\" && today.filter((c) => c.followup === \"resurface\").length >= SCREEN_BUDGET.resurface) {\n return `${SCREEN_BUDGET.resurface} resurface cards were already raised today: raise it again tomorrow`\n }\n return null\n}\n\n/** What the author hears when the popup does not show its card. */\nexport function returnedText(card: { id: string; title?: string; origin?: { kind: string } }, reason: string): string {\n const title = card.title?.trim()\n if (card.origin?.kind === \"request\") {\n return [\n `[screen gate] Request ${card.id}${title ? ` (\"${title}\")` : \"\"} was not shown to the owner: ${reason}.`,\n `It is still on his list. Say what it is: agentx_request {action:\"describe\", id:\"${card.id}\", headline:\"<a few plain words>\", need:\"<what you need from him>\"}.`,\n ].join(\" \")\n }\n return [\n `[screen gate] Your card ${card.id}${title ? ` (\"${title}\")` : \"\"} was not shown to the owner: ${reason}.`,\n \"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:\",\n `one question, title up to ${SCREEN_LIMITS.title} characters, ask up to ${SCREEN_LIMITS.ask}, at most ${SCREEN_LIMITS.answers} choices.`,\n ].join(\" \")\n}\n"],"mappings":"oHAAA,OAAS,cAAAA,GAAY,YAAAC,GAAU,aAAAC,GAAW,eAAAC,GAAa,gBAAAC,GAAc,cAAAC,GAAY,cAAAC,GAAY,iBAAAC,OAAqB,KAClH,OAAS,WAAAC,OAAe,OCCxBC,KAFA,OAAS,kBAAAC,GAAgB,cAAAC,GAAY,aAAAC,GAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KACnF,OAAS,WAAAC,MAAe,OA+BxB,IAAMC,EAAO,IAEPC,EAAW,IAGXC,EAAOC,GAAiBJ,EAAQI,EAAM,UAAW,WAAW,EAC5DC,EAAgBD,GAAiBJ,EAAQG,EAAIC,CAAI,EAAG,iBAAiB,EACrEE,GAAaF,GAAiBJ,EAAQG,EAAIC,CAAI,EAAG,iBAAiB,EAClEG,EAAOC,GAA2BA,GAAKA,EAAE,OAASN,EAAWM,EAAE,MAAM,EAAGN,EAAW,CAAC,EAAI,SAAMM,EAG7F,SAASC,EAAeL,EAAcM,EAA0B,CACrE,GAAI,CACFC,GAAcP,CAAI,EAClB,IAAMQ,EAAqB,CAAE,GAAGF,EAAM,MAAOH,EAAIG,EAAK,KA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M,EAGnDA,EAAK,SAAW,WAAaA,EAAK,UAAY,MAAQ,CAACyD,GAAS,CAAC8B,GAAOD,EAAM,KAAKL,EAAY,EAC/FjF,EAAK,QAAQsF,EAAM,KAAK,WAAWtF,EAAK,QAAQ,EAChDA,EAAK,QAAQ,OAAS,YAAYsF,EAAM,KAAK,GAAGG,EAAYzF,EAAK,OAAQA,EAAK,SAAW,WAAaA,EAAK,UAAY,KAAK,CAAC,EAC7HA,EAAK,QAAQ,OAAS,UAAUsF,EAAM,KAAK,GAAGI,EAAY1F,EAAK,OAAQA,CAAI,CAAC,EAC5EyD,GAAS8B,EAAO,CAGlB,IAAMI,EAAUC,GAAcA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACpDC,EAAQC,EAAS9F,EAAK,MAAOA,EAAK,MAAM,EACxC+F,EAAS/F,EAAK,MAAQ2F,EAAO3F,EAAK,IAAI,IAAM2F,EAAOE,CAAK,EAAI7F,EAAK,KAAO,OAC9EsF,EAAM,KAAK,GAAI7B,EAAQuC,EAAWvC,EAAOzD,EAAM+F,CAAM,EAAIE,EAAgBV,EAAQvF,EAAM+F,CAAM,CAAE,EAEjG,OAAI/F,EAAK,OAAOsF,EAAM,KAAK,sBAAsBtF,EAAK,MAAM,gBAAgBA,EAAK,MAAM,mDAAmD,EACtIA,EAAK,MAAMsF,EAAM,KAAK,4EAA4EtF,EAAK,OAAO,EAClHsF,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","linkSync","mkdirSync","readdirSync","readFileSync","renameSync","unlinkSync","writeFileSync","resolve","init_logger","appendFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","KEEP","TEXT_MAX","dir","root","answeredFile","sinceFile","cap","s","recordAnswered","item","answeredSince","line","path","lines","e","logger","at","readAnswered","limit","out","i","v","numberLines","origin","card","lines","numberReviewerMessage","isRetroOrigin","CHECK_CHOICES","retroCheckLines","edited","rule","SUGGESTED_NOTE","retroApproved","RETRO_NONE","retroLines","spec","originLines","approved","where","SCREEN_LIMITS","FOLLOWUP_KINDS","SCREEN_BUDGET","REFERENCES","stripReferences","text","re","referenceOnlyTitle","title","rest","w","cardRuleBreak","card","ask","bare","noticeRuleBreak","message","withTodo","todo","what","dayStart","now","d","followupBudgetRefusal","cards","kind","from","today","c","returnedText","reason","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","saveNewCard","n","saved","linkSync","e","unlinkSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","followup","FOLLOWUP_KINDS","reply","r","sameSourcePending","pending","createCard","built","broken","cardRuleBreak","full","followupBudgetRefusal","twin","isRetro","isRetroOrigin","retro","open","what","POPUP_ONLY","decideCard","verdict","answer","resolveAnswer","saysNo","isNoChoice","final","note","decided","AGENT_RESOLVABLE_ORIGINS","resolveCard","who","how","reason","resolved","recordAnswered","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","NO_UNDO_LINE","verdictMessage","result","retroApproved","RETRO_NONE","lines","check","answerLines","originLines","numberLines","squash","s","draft","draftFor","edited","retroLines","retroCheckLines"]}
|
|
@@ -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-FRYEUVYD.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-DXKDG4DQ.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-DXKDG4DQ.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-575LJSX2.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as j,s as R,u as F}from"./chunk-
|
|
1
|
+
import{r as j,s as R,u as F}from"./chunk-3323WFVK.js";import{f as L,g as G}from"./chunk-LY4G7PCW.js";import{existsSync as y,mkdirSync as ae,writeFileSync as S,readFileSync as A}from"fs";import{resolve as m}from"path";import{createHash as Ye}from"crypto";import{readFileSync as me,existsSync as fe,unlinkSync as ye,readdirSync as mt}from"fs";import{resolve as H}from"path";function yt(e,n){let r={},s=t=>{let o=H(e,t);if(fe(o))try{return me(o,"utf-8").trim()||void 0}catch{return}};if(n){let t=s(`SOUL.${n}.md`);t?(r.soul=t,r.soulProfile=n):r.soul=s("SOUL.md")}else r.soul=s("SOUL.md");if(r.identity=s("IDENTITY.md"),r.user=s("USER.md"),r.agents=s("AGENTS.md"),r.bootstrap=s("BOOTSTRAP.md"),r.bootstrap)try{ye(H(e,"BOOTSTRAP.md"))}catch{}return r}function bt(e){let n=[];return e.identity&&n.push(`[Identity]
|
|
2
2
|
${e.identity}`),e.soul&&n.push(`[Personality & Boundaries]
|
|
3
3
|
${e.soul}`),e.user&&n.push(`[User Profile]
|
|
4
4
|
${e.user}`),e.bootstrap&&n.push(`[First-Run Instructions \u2014 one time only]
|
|
@@ -112,4 +112,4 @@ Always include:
|
|
|
112
112
|
5. Screenshots if applicable
|
|
113
113
|
`});break}return s}function ut(e,n,r="19900",s=console.error){let t=[],o=[],i=n.workspace;if(!y(i))return s(`Workspace not found: ${i}`),{created:t,skipped:o};if(n.tier!=="claude-code"&&n.tier!=="codex-cli")return{created:t,skipped:o};let a=(c,p)=>{y(c)?o.push(c):(ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c))},l=(c,p,g)=>{if(!y(c)){ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c);return}let d;try{d=A(c,"utf8")}catch{o.push(c);return}let f=Ve(d);if(f===null){o.push(c);return}if(f===g){o.push(c);return}S(c,p),t.push(`${c} (refreshed)`)};if(a(m(i,"AGENTS.md"),W({name:n.name,id:e,role:n.systemPrompt?.split(`
|
|
114
114
|
`)[0],workspace:i,tier:n.tier})),n.tier==="codex-cli")return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o};l(m(i,"CLAUDE.md"),ze(e,n,r),ce(n));let u=m(i,".claude/settings.json");a(u,JSON.stringify(it(e,n,r),null,2));let h=ct(e,n);for(let c of h){let p=m(i,".claude/rules",c.name);c.replaces&&y(p)&&c.replaces.includes(A(p,"utf8"))?(S(p,c.content),t.push(p)):a(p,c.content)}return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o}}function lt(e,n){let r=m(e,".claude/settings.json");if(!y(r))return!1;try{let s=JSON.parse(A(r,"utf-8")),t=!1;for(let[o,i]of Object.entries(n))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){s[o]||(s[o]={});for(let[a,l]of Object.entries(i))s[o][a]===void 0&&(s[o][a]=l,t=!0)}else s[o]===void 0&&(s[o]=i,t=!0);return t&&S(r,JSON.stringify(s,null,2)),t}catch{return!1}}function pt(e,n,r="19900",s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=!1,a=o.permissions??={},l=Array.isArray(a.deny)?a.deny:a.deny=[];for(let d of P)l.includes(d)||(l.push(d),i=!0);let u=o.hooks??={},c=[...Array.isArray(u.PreToolUse)?u.PreToolUse.filter(d=>!ot(d)):[],...pe(n,r,s)];JSON.stringify(u.PreToolUse??null)!==JSON.stringify(c)&&(u.PreToolUse=c,i=!0);let g=[...Array.isArray(u.PostToolUse)?u.PostToolUse.filter(d=>!rt(d)):[],de(r)];return JSON.stringify(u.PostToolUse??null)!==JSON.stringify(g)&&(u.PostToolUse=g,i=!0),i&&S(t,JSON.stringify(o,null,2)),i}catch{return!1}}function dt(e){return Array.isArray(e?.hooks)&&e.hooks.some(n=>typeof n?.command=="string"&&n.command.includes(D))}function ht(e,n,r,s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=JSON.stringify(o),a=s.enabled&&s.tools.length>0,l=`Read(/${te(s.dir,n)}/**)`,u=Array.isArray(o.hooks?.PostToolUse)?o.hooks.PostToolUse:[],h=u.filter(g=>!dt(g)),c=Array.isArray(o.permissions?.allow)?o.permissions.allow:[],p=c.filter(g=>g!==l);if(a){let d=`curl -s --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${r}${D}?agent=${encodeURIComponent(n)}`}' 2>/dev/null || true`;h.push({matcher:s.tools.join("|"),hooks:[{type:"command",command:d,timeout:10}]}),p.push(l)}return(a||u.length>0)&&((o.hooks??={}).PostToolUse=h),(a||c.length>0)&&((o.permissions??={}).allow=p),JSON.stringify(o)===i?!1:(S(t,JSON.stringify(o,null,2)),!0)}catch{return!1}}function Vt(e,n="19900",r=console.error,s){let t=0,o=0,i=0,a=0,l=0,u=0;for(let[h,c]of Object.entries(e)){if(c.tier!=="claude-code"&&c.tier!=="codex-cli")continue;let p=ut(h,c,n,r);if(t+=p.created.length,c.tier==="claude-code"&<(c.workspace,{env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}})&&o++,c.tier==="claude-code"&&pt(c.workspace,h,n,c.mcp)&&i++,c.tier==="claude-code"&&s){let g=ne(c.permissionMode);s.enabled&&!g&&u++;let d=s.enabled&&g;ht(c.workspace,h,n,{...s,enabled:d})&&(d?a++:l++)}}t>0&&r(`Workspace setup: ${t} file(s) created across agent workspaces`),o>0&&r(`Workspace patch: ${o} workspace(s) updated with agent teams support`),i>0&&r(`Guardrails: ${i} workspace(s) backfilled with deny list + PreToolUse guard hook`),a>0&&r(`ObservationPack: PostToolUse hook written to ${a} workspace(s)`),l>0&&r(`ObservationPack: PostToolUse hook removed from ${l} workspace(s)`),u>0&&r(`ObservationPack: ${u} agent(s) not packed: permissionMode is not "bypassPermissions", so they could not read a saved original back`)}export{yt as a,bt as b,kt as c,St as d,At as e,D as f,Et as g,te as h,ne as i,vt as j,Dt as k,Mt as l,We as m,M as n,Gt as o,ie as p,Ve as q,ze as r,le as s,et as t,tt as u,nt as v,ut as w,pt as x,ht as y,Vt as z};
|
|
115
|
-
//# sourceMappingURL=chunk-
|
|
115
|
+
//# sourceMappingURL=chunk-74MHOALB.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-
|
|
1
|
+
import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-RMB6G7X2.js";import{a as V}from"./chunk-IMLAPB7G.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{k as Be}from"./chunk-GO4J44UD.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-4UJDRI7W.js";import{ia as G}from"./chunk-FRYEUVYD.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-5BT4VPJC.js";import{s as ge,u as Oe}from"./chunk-3323WFVK.js";import{b as He}from"./chunk-JMRFYGET.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Cc as xe,J as le,Lb as Ee,M as F,S as Za,Sb as at,Va as ce,Wa as Pe,gb as et,nc as pe,rc as q,sc as Re}from"./chunk-VOVDWFFP.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
|
|
2
2
|
/* --- Brand (agentina) --------------------------------------------- */
|
|
3
3
|
--ax-blue: #2979FF;
|
|
4
4
|
--ax-blue-d: #1B5FD9;
|
|
@@ -2903,4 +2903,4 @@ tr:hover td { background: var(--bg-hover); }
|
|
|
2903
2903
|
${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Ne/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${We(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
|
|
2904
2904
|
`)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=Oe(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ge(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ge(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
|
|
2905
2905
|
`)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:Le(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
|
|
2906
|
-
//# sourceMappingURL=chunk-
|
|
2906
|
+
//# sourceMappingURL=chunk-AAPHOKWS.js.map
|