agentix-cli 0.121.1 → 0.123.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-AMIGKAXO.js → App-NOCRE5SN.js} +2 -2
- package/dist/{ChatApp-WMI4HQSY.js → ChatApp-SETNTMED.js} +2 -2
- package/dist/{agent-KR4B2G24.js → agent-YII7XBL4.js} +2 -2
- package/dist/{board-dashboard-WBIQPRHQ.js → board-dashboard-BBLEP7OA.js} +338 -238
- package/dist/board-dashboard-BBLEP7OA.js.map +1 -0
- package/dist/{chunk-Y4PR5LR3.js → chunk-22SWFBSL.js} +2 -2
- package/dist/{chunk-MSYBNVY3.js → chunk-27FYNGDW.js} +2 -2
- package/dist/{chunk-FIB5LD6R.js → chunk-5HK3YJEQ.js} +257 -251
- package/dist/chunk-5HK3YJEQ.js.map +1 -0
- package/dist/{chunk-H5Z42X7W.js → chunk-AIYI2MFV.js} +2 -2
- package/dist/{chunk-6FVFD5WU.js → chunk-AKLZ4YO2.js} +4 -4
- package/dist/{chunk-6FVFD5WU.js.map → chunk-AKLZ4YO2.js.map} +1 -1
- package/dist/{chunk-HVYS5ZBQ.js → chunk-DTSKSYEO.js} +2 -2
- package/dist/{chunk-BLEW5WQL.js → chunk-EV2WPHHS.js} +2 -2
- package/dist/chunk-EYIQVQMA.js +37 -0
- package/dist/chunk-EYIQVQMA.js.map +1 -0
- package/dist/{chunk-ELUEF4NC.js → chunk-FQQHUCFN.js} +2 -2
- package/dist/{chunk-CAS2IWSM.js → chunk-GOCYZJMS.js} +2 -2
- package/dist/{chunk-6TUQHOO3.js → chunk-JA6MVY7J.js} +2 -2
- package/dist/{chunk-KFSA2ZI7.js → chunk-KQW2U5MY.js} +2 -2
- package/dist/{chunk-EI7D5V2L.js → chunk-LJ6ORTLS.js} +2 -2
- package/dist/{chunk-25XR6QK2.js → chunk-LRMUK6DC.js} +2 -2
- package/dist/chunk-M6WY53GO.js +532 -0
- package/dist/chunk-M6WY53GO.js.map +1 -0
- package/dist/{chunk-D7LGD7ZI.js → chunk-ODGGGU5J.js} +71 -69
- package/dist/chunk-ODGGGU5J.js.map +1 -0
- package/dist/{chunk-IKBWV7YJ.js → chunk-PGXACYDY.js} +2 -2
- package/dist/{chunk-OPNZWQ6Y.js → chunk-TEXZEXQZ.js} +11 -11
- package/dist/chunk-TEXZEXQZ.js.map +1 -0
- package/dist/{chunk-4GDLXWCH.js → chunk-TJLTPONY.js} +2 -2
- package/dist/{chunk-2IMK3NGJ.js → chunk-UNWXKBRF.js} +2 -2
- package/dist/{chunk-43CLFC4B.js → chunk-W3DCOYAE.js} +2 -2
- package/dist/{chunk-7ZABMMSW.js → chunk-WEPON4FP.js} +2 -2
- package/dist/{chunk-PAWCJIPZ.js → chunk-WXABFPX7.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-ICDRAZBU.js → client-S67ZQ5FC.js} +2 -2
- package/dist/config-3AX5MHPN.js +2 -0
- package/dist/config-mutator-BYFMZQBT.js +2 -0
- package/dist/doctor-KFZLZRUN.js +2 -0
- package/dist/{editor-chat-4MLCP5D2.js → editor-chat-ELKNLXM6.js} +10 -3
- package/dist/{editor-chat-4MLCP5D2.js.map → editor-chat-ELKNLXM6.js.map} +1 -1
- package/dist/follow-up-tool-ZVEYUJ6U.js +6 -0
- package/dist/follow-up-tool-ZVEYUJ6U.js.map +1 -0
- package/dist/{grants-ZMHSJMYE.js → grants-HIFE6L5N.js} +2 -2
- package/dist/index.d.ts +216 -79
- package/dist/index.js +1 -1
- package/dist/{program-4J6WMXLI.js → program-VXR3YD5R.js} +211 -209
- package/dist/{program-4J6WMXLI.js.map → program-VXR3YD5R.js.map} +1 -1
- package/dist/{promote-4LW53AMH.js → promote-BQTJNRTG.js} +2 -2
- package/dist/push-bridge-325SXDGN.js +1 -1
- package/dist/{query-4OPS5PET.js → query-6YBM4TPV.js} +2 -2
- package/dist/{registry-XK2FTQZV.js → registry-B7OS4AOM.js} +2 -2
- package/dist/{request-planner-GDXSBNN4.js → request-planner-BLULDFMJ.js} +2 -2
- package/dist/{review-candidates-TUVDG2LR.js → review-candidates-HMQ6ZXBT.js} +2 -2
- package/dist/routing-WW56ZXGS.js +2 -0
- package/dist/schedule-tool-Y6RMN6ZT.js +2 -0
- package/dist/scheduler-4GB47SDH.js +2 -0
- package/dist/{seat-K6FNHYMY.js → seat-XGANYYMU.js} +2 -2
- package/dist/{select-QMJXHNUP.js → select-2HW6Q7UX.js} +2 -2
- package/dist/{set-enabled-I77LPL6Q.js → set-enabled-N5AGU5AH.js} +2 -2
- package/dist/tool-RJHDRV4X.js +6 -0
- package/dist/tool-RJHDRV4X.js.map +1 -0
- package/dist/{tool-QTGNWXUA.js → tool-XRV6IQ2J.js} +2 -2
- package/dist/web/workflow-editor.global.js +1 -1
- package/dist/web/workflow-editor.global.js.map +1 -1
- package/dist/wiki-ZA4FU3PW.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-WBIQPRHQ.js.map +0 -1
- package/dist/chunk-7KY7EEEI.js +0 -28
- package/dist/chunk-7KY7EEEI.js.map +0 -1
- package/dist/chunk-BWHHZJNJ.js +0 -482
- package/dist/chunk-BWHHZJNJ.js.map +0 -1
- package/dist/chunk-D7LGD7ZI.js.map +0 -1
- package/dist/chunk-FIB5LD6R.js.map +0 -1
- package/dist/chunk-OPNZWQ6Y.js.map +0 -1
- package/dist/config-K4UYPR7W.js +0 -2
- package/dist/config-mutator-IGA6D4S5.js +0 -2
- package/dist/doctor-LRTOOCM6.js +0 -2
- package/dist/routing-OKDZ4VYH.js +0 -2
- package/dist/schedule-tool-MJLXMXN5.js +0 -2
- package/dist/scheduler-E5SASFAH.js +0 -2
- package/dist/tool-BQUKONSF.js +0 -4
- package/dist/tool-BQUKONSF.js.map +0 -1
- package/dist/wiki-PAMLP6WO.js +0 -2
- /package/dist/{App-AMIGKAXO.js.map → App-NOCRE5SN.js.map} +0 -0
- /package/dist/{ChatApp-WMI4HQSY.js.map → ChatApp-SETNTMED.js.map} +0 -0
- /package/dist/{agent-KR4B2G24.js.map → agent-YII7XBL4.js.map} +0 -0
- /package/dist/{chunk-Y4PR5LR3.js.map → chunk-22SWFBSL.js.map} +0 -0
- /package/dist/{chunk-MSYBNVY3.js.map → chunk-27FYNGDW.js.map} +0 -0
- /package/dist/{chunk-H5Z42X7W.js.map → chunk-AIYI2MFV.js.map} +0 -0
- /package/dist/{chunk-HVYS5ZBQ.js.map → chunk-DTSKSYEO.js.map} +0 -0
- /package/dist/{chunk-BLEW5WQL.js.map → chunk-EV2WPHHS.js.map} +0 -0
- /package/dist/{chunk-ELUEF4NC.js.map → chunk-FQQHUCFN.js.map} +0 -0
- /package/dist/{chunk-CAS2IWSM.js.map → chunk-GOCYZJMS.js.map} +0 -0
- /package/dist/{chunk-6TUQHOO3.js.map → chunk-JA6MVY7J.js.map} +0 -0
- /package/dist/{chunk-KFSA2ZI7.js.map → chunk-KQW2U5MY.js.map} +0 -0
- /package/dist/{chunk-EI7D5V2L.js.map → chunk-LJ6ORTLS.js.map} +0 -0
- /package/dist/{chunk-25XR6QK2.js.map → chunk-LRMUK6DC.js.map} +0 -0
- /package/dist/{chunk-IKBWV7YJ.js.map → chunk-PGXACYDY.js.map} +0 -0
- /package/dist/{chunk-4GDLXWCH.js.map → chunk-TJLTPONY.js.map} +0 -0
- /package/dist/{chunk-2IMK3NGJ.js.map → chunk-UNWXKBRF.js.map} +0 -0
- /package/dist/{chunk-43CLFC4B.js.map → chunk-W3DCOYAE.js.map} +0 -0
- /package/dist/{chunk-7ZABMMSW.js.map → chunk-WEPON4FP.js.map} +0 -0
- /package/dist/{chunk-PAWCJIPZ.js.map → chunk-WXABFPX7.js.map} +0 -0
- /package/dist/{client-ICDRAZBU.js.map → client-S67ZQ5FC.js.map} +0 -0
- /package/dist/{config-K4UYPR7W.js.map → config-3AX5MHPN.js.map} +0 -0
- /package/dist/{config-mutator-IGA6D4S5.js.map → config-mutator-BYFMZQBT.js.map} +0 -0
- /package/dist/{doctor-LRTOOCM6.js.map → doctor-KFZLZRUN.js.map} +0 -0
- /package/dist/{grants-ZMHSJMYE.js.map → grants-HIFE6L5N.js.map} +0 -0
- /package/dist/{promote-4LW53AMH.js.map → promote-BQTJNRTG.js.map} +0 -0
- /package/dist/{query-4OPS5PET.js.map → query-6YBM4TPV.js.map} +0 -0
- /package/dist/{registry-XK2FTQZV.js.map → registry-B7OS4AOM.js.map} +0 -0
- /package/dist/{request-planner-GDXSBNN4.js.map → request-planner-BLULDFMJ.js.map} +0 -0
- /package/dist/{review-candidates-TUVDG2LR.js.map → review-candidates-HMQ6ZXBT.js.map} +0 -0
- /package/dist/{routing-OKDZ4VYH.js.map → routing-WW56ZXGS.js.map} +0 -0
- /package/dist/{schedule-tool-MJLXMXN5.js.map → schedule-tool-Y6RMN6ZT.js.map} +0 -0
- /package/dist/{scheduler-E5SASFAH.js.map → scheduler-4GB47SDH.js.map} +0 -0
- /package/dist/{seat-K6FNHYMY.js.map → seat-XGANYYMU.js.map} +0 -0
- /package/dist/{select-QMJXHNUP.js.map → select-2HW6Q7UX.js.map} +0 -0
- /package/dist/{set-enabled-I77LPL6Q.js.map → set-enabled-N5AGU5AH.js.map} +0 -0
- /package/dist/{tool-QTGNWXUA.js.map → tool-XRV6IQ2J.js.map} +0 -0
- /package/dist/{wiki-PAMLP6WO.js.map → wiki-ZA4FU3PW.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{
|
|
1
|
+
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{ma as tt,na as nt}from"./chunk-TEXZEXQZ.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Ot(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-TJLTPONY.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ia as m,ja as $,na as x}from"./chunk-TEXZEXQZ.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
|
|
4
4
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-UNWXKBRF.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{
|
|
1
|
+
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{ka as S,na as L}from"./chunk-TEXZEXQZ.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
6
|
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,J as b,ke as c,G as d,V as e,ne as f};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-W3DCOYAE.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{i as x,k as A}from"./chunk-
|
|
1
|
+
import{i as x,k as A}from"./chunk-AKLZ4YO2.js";import{a as w,e as D}from"./chunk-2QNT5JDS.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
|
|
2
2
|
`)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-WEPON4FP.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-EV2WPHHS.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-UNWXKBRF.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
2
|
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-WXABFPX7.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-VXR3YD5R.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-LJ6ORTLS.js";import"./chunk-TEXZEXQZ.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-S67ZQ5FC.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{$ as b,_ as a,aa as c,ba as d,ca as e,da as f,ea as g,fa as h,ga as i,ha as j,ia as k,ja as l,ka as m,la as n,na as o}from"./chunk-TEXZEXQZ.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";o();export{a as INTEGRATION_KINDS,j as approvalsConfigSchema,d as callsSchema,c as cameraBotSchema,k as daemonConfigSchema,b as eventSubscriptionSchema,l as expandEnvVars,m as loadDaemonConfig,h as membersConfigSchema,g as peopleConfigSchema,f as personSchema,i as requestStatusConfigSchema,e as requestsConfigSchema,n as validateWorkspaces};
|
|
2
|
+
//# sourceMappingURL=config-3AX5MHPN.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-UNWXKBRF.js";import"./chunk-TEXZEXQZ.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-BYFMZQBT.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-W3DCOYAE.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-TEXZEXQZ.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-KFZLZRUN.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import"./chunk-QIJLFPWE.js";function c(o){let
|
|
2
|
-
`)}function u(o){let
|
|
1
|
+
import"./chunk-QIJLFPWE.js";function c(o){let n=o.store.list().map(t=>({id:t.id,title:t.title})),e=[];if(e.push(a),e.push(""),e.push(i),e.push(""),e.push("# Environment \u2014 only reference values that exist"),e.push(""),e.push("## Available agents (for `agent` nodes)"),o.availableAgents.length===0)e.push(" (none registered \u2014 the user must add an agent first for `agent` nodes to work)");else for(let t of o.availableAgents)e.push(` - \`${t.id}\`${t.description?` \u2014 ${t.description}`:""}`);if(e.push(""),e.push("## Assignees (for `userTask.assignTo`)"),e.push(" Any agent id above, or a plain string naming the person responsible."),e.push(""),e.push("## Available roles (for `userTask.assignTo`)"),e.push(""),e.push("## Available channels (for `action.*` and `trigger.channel`)"),e.push(` ${o.availableChannels.length?o.availableChannels.map(t=>`\`${t}\``).join(", "):"(none live on this node)"}`),e.push(""),e.push("## Existing workflows (for `subProcess.workflowId`)"),n.length===0)e.push(" (no other workflows defined)");else for(let t of n)e.push(` - \`${t.id}\` \u2014 ${t.title}`);e.push(""),o.currentWorkflow&&(e.push("# Current workflow on canvas"),e.push(""),e.push("The user is editing this workflow. Build on it \u2014 do NOT replace it unless they explicitly ask."),e.push(""),e.push("```json"),e.push(JSON.stringify(o.currentWorkflow,null,2)),e.push("```"),e.push("")),e.push("# Conversation"),e.push("");for(let t of o.messages){let r=t.role==="user"?"USER":"ASSISTANT";e.push(`${r}: ${t.content}`),e.push("")}return e.push(l),e.join(`
|
|
2
|
+
`)}function u(o){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(o),e=[];n&&e.push(n[1]);let t=o.match(/\{[\s\S]*\}/);t&&e.push(t[0]);for(let r of e)try{let s=JSON.parse(r);if(s&&typeof s=="object"&&"id"in s&&"nodes"in s)return s}catch{}return null}var a=`You are AgentX's workflow author. The user describes a business process in
|
|
3
3
|
plain language; you return a valid V2 workflow JSON that implements it.
|
|
4
4
|
|
|
5
5
|
Read the node catalog below. Prefer the BPM primitives (userTask,
|
|
@@ -65,6 +65,13 @@ for simple message-in \u2192 reply-out automations.`,i=`# V2 Node catalog
|
|
|
65
65
|
- \`signal.wait\` \u2014 pause until matching signal arrives. config: { "name": "approved", "scope": "workflow", "match": { "grantId": "{{trigger.id}}" } }
|
|
66
66
|
- \`timer.boundary\` \u2014 pause for a duration. config: { "after": "PT2H" | "P1D" | 60 (minutes) }
|
|
67
67
|
|
|
68
|
+
## The owner and other people (follow-up steps)
|
|
69
|
+
An edge without fromPort leaves on the main port (yes / sent / reply); add edges with fromPort for the others.
|
|
70
|
+
- \`owner.notify\` \u2014 tell the owner. config: { "text": "Deployed: {{deploy.reply}}" }
|
|
71
|
+
- \`owner.ask\` \u2014 a decision card for the owner; ports yes / no / expired. config: { "ask": "Ship it?", "recommend": "\u2026", "draft"?: "\u2026", "choices"?: ["a","b"] }. Output: { port, choice, text, note }
|
|
72
|
+
- \`person.message\` \u2014 message an employee or client once the owner approves the text (at start or on its own card); ports sent / declined. config: { "to": "Sam", "channel": "telegram", "chatId": "\u2026", "text": "\u2026" }
|
|
73
|
+
- \`person.wait\` \u2014 wait for that person's reply; ports reply / timeout. config: { "reminds": "<person.message id>", "timeout": "2d", "remindAfter": "1d" } (or channel + chatId). Output: { text, from, media }
|
|
74
|
+
|
|
68
75
|
## Actions \u2014 side-effect sinks
|
|
69
76
|
- \`action.send\` \u2014 post a message to any channel. config: { "channel": "telegram"|"whatsapp"|\u2026, "chatId": "{{trigger.chatId}}", "text": "Hi {{classify.reply}}", "accountId"?: "\u2026" }
|
|
70
77
|
- \`action.createIssue\` \u2014 open a GitLab issue. config: { "channel": "gitlab", "project": "acme/web", "title": "\u2026", "description": "\u2026", "labels": ["x"], "assignees": ["user"] }
|
|
@@ -136,4 +143,4 @@ Only reference agent ids, actor ids, role ids, and channel names that
|
|
|
136
143
|
appear in the Environment section above. If the user asks for an agent
|
|
137
144
|
that doesn't exist, tell them which agent to register first. Never
|
|
138
145
|
invent workflowIds for subProcess that aren't in the existing list.`;export{c as buildWorkflowAuthorPrompt,u as extractWorkflowJson};
|
|
139
|
-
//# sourceMappingURL=editor-chat-
|
|
146
|
+
//# sourceMappingURL=editor-chat-ELKNLXM6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/workflows/editor-chat.ts"],"sourcesContent":["import type { Workflow } from \"./types\"\nimport type { WorkflowStore } from \"./store\"\n\n// --- Workflow-builder chat context ---\n//\n// Produces the plain-text prompt the authoring agent reads. Packs\n// *everything* the agent needs to generate a valid V2 workflow JSON on\n// its first try: node catalog with config examples, available agent\n// ids, actor + role ids, channel adapter names, the user's existing\n// workflow list (for subProcess targets), and — when the author is\n// editing — the current workflow JSON as a starting point.\n//\n// The output is deliberately text, not JSON. Agents (LLMs) produce\n// better structured output when the schema is described as prose +\n// examples rather than as raw JSON Schema. The explicit \"reply with a\n// ```json block```\" instruction at the tail is what the API endpoint\n// parses back.\n\nexport interface ChatMessage {\n role: \"user\" | \"assistant\"\n content: string\n}\n\nexport interface BuildContextArgs {\n messages: ChatMessage[]\n store: WorkflowStore\n /** Full list of agent ids + optional descriptions. */\n availableAgents: Array<{ id: string; description?: string; tags?: string[] }>\n /** Adapter names the daemon has live (telegram, whatsapp, gitlab, ...). */\n availableChannels: string[]\n /** The workflow the user is currently editing (if any). */\n currentWorkflow?: Workflow\n}\n\n/** Build the single-string prompt the agent executes. */\nexport function buildWorkflowAuthorPrompt(args: BuildContextArgs): string {\n const workflows = args.store.list().map((w) => ({ id: w.id, title: w.title }))\n\n const parts: string[] = []\n\n parts.push(SYSTEM_HEADER)\n parts.push(\"\")\n parts.push(NODE_CATALOG)\n parts.push(\"\")\n parts.push(\"# Environment — only reference values that exist\")\n parts.push(\"\")\n parts.push(`## Available agents (for \\`agent\\` nodes)`)\n if (args.availableAgents.length === 0) {\n parts.push(\" (none registered — the user must add an agent first for `agent` nodes to work)\")\n } else {\n for (const a of args.availableAgents) {\n parts.push(` - \\`${a.id}\\`${a.description ? ` — ${a.description}` : \"\"}`)\n }\n }\n parts.push(\"\")\n parts.push(\"## Assignees (for `userTask.assignTo`)\")\n parts.push(\" Any agent id above, or a plain string naming the person responsible.\")\n parts.push(\"\")\n parts.push(\"## Available roles (for `userTask.assignTo`)\")\n parts.push(\"\")\n parts.push(\"## Available channels (for `action.*` and `trigger.channel`)\")\n parts.push(` ${args.availableChannels.length ? args.availableChannels.map((c) => `\\`${c}\\``).join(\", \") : \"(none live on this node)\"}`)\n parts.push(\"\")\n parts.push(\"## Existing workflows (for `subProcess.workflowId`)\")\n if (workflows.length === 0) parts.push(\" (no other workflows defined)\")\n else for (const w of workflows) parts.push(` - \\`${w.id}\\` — ${w.title}`)\n parts.push(\"\")\n\n if (args.currentWorkflow) {\n parts.push(\"# Current workflow on canvas\")\n parts.push(\"\")\n parts.push(\"The user is editing this workflow. Build on it — do NOT replace it unless they explicitly ask.\")\n parts.push(\"\")\n parts.push(\"```json\")\n parts.push(JSON.stringify(args.currentWorkflow, null, 2))\n parts.push(\"```\")\n parts.push(\"\")\n }\n\n parts.push(\"# Conversation\")\n parts.push(\"\")\n for (const m of args.messages) {\n const tag = m.role === \"user\" ? \"USER\" : \"ASSISTANT\"\n parts.push(`${tag}: ${m.content}`)\n parts.push(\"\")\n }\n\n parts.push(RESPONSE_RULES)\n return parts.join(\"\\n\")\n}\n\n/** Try to extract a workflow-shaped JSON block from an agent reply. Returns\n * null if no JSON block is present OR the JSON doesn't have the minimum\n * workflow fields (id, nodes). The caller still runs full zod validation\n * before writing. */\nexport function extractWorkflowJson(reply: string): Record<string, unknown> | null {\n // Prefer fenced ```json blocks; fall back to the largest {...} block.\n const fenced = /```(?:json)?\\s*\\n([\\s\\S]*?)```/.exec(reply)\n const candidates: string[] = []\n if (fenced) candidates.push(fenced[1])\n const braceMatch = reply.match(/\\{[\\s\\S]*\\}/)\n if (braceMatch) candidates.push(braceMatch[0])\n\n for (const raw of candidates) {\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && \"id\" in parsed && \"nodes\" in parsed) {\n return parsed as Record<string, unknown>\n }\n } catch { /* try next */ }\n }\n return null\n}\n\nconst SYSTEM_HEADER = `You are AgentX's workflow author. The user describes a business process in\nplain language; you return a valid V2 workflow JSON that implements it.\n\nRead the node catalog below. Prefer the BPM primitives (userTask,\nsubProcess, signal.emit/wait, timer.boundary, gateway.parallel, rule)\nwhen modelling processes with humans, deadlines, parallel streams, or\nnested activities. Prefer the bot primitives (agent, branch, action.*)\nfor simple message-in → reply-out automations.`\n\nconst NODE_CATALOG = `# V2 Node catalog\n\n## Triggers (exactly one per workflow)\n- \\`trigger.channel\\` — inbound channel event.\n config: { \"source\": \"whatsapp-message\" | \"telegram-message\" | \"slack-message\" | \"discord-message\" | \"gitlab-issue\" | \"gitlab-pipeline\", \"filter\": { \"chat\"?: \"*\", \"project\"?: \"acme/web\", \"labels\"?: [\"x\"] } }\n- \\`trigger.cron\\` — scheduled. config: { \"spec\": \"0 9 * * *\", \"timezone\": \"UTC\" }\n- \\`trigger.hook\\` — subscribes to any on:* hook event. config: { \"event\": \"on:gitlab-issue\" }\n- \\`trigger.poll\\` — runs a registered action every N seconds; one run per NEW item it prints (one JSON object per line). The item is the trigger payload.\n config: { \"actionId\": \"my-list-action\", \"everySeconds\": 60, \"key\": \"id\", \"filter\"?: [ { \"kind\": \"matches\", \"params\": { \"path\": \"text\", \"regex\": \"^@bot\" } } ] }\n- \\`trigger.manual\\` — kicked off by CLI or API. config: {}\n- \\`trigger.form\\` — human fills a form to start. config: { \"form\": FormSchema, \"startableBy\": \"role:public\" }\n\n## Compute\n- \\`agent\\` — run an agent with a templated prompt. Output: { reply, result (parsed RESULT: token), json?, durationMs }.\n config: { \"agentId\": \"<id>\", \"prompt\": \"Classify {{trigger.text}} — reply on one line: RESULT: a|b|c\", \"resultParser\": \"acme-result-token\" | \"json\", \"timeoutMinutes\": 2 }\n- \\`transform\\` — reshape upstream context.\n config: { \"path\": \"trigger.contact.phone\" } OR { \"template\": { \"key\": \"{{trigger.text}}\" } }\n\n## Control flow\n- \\`branch\\` — N-way switch (first match wins).\n config: { \"cases\": [{ \"when\": { \"kind\": \"equals\"|\"contains\"|\"matches\"|\"exists\", \"params\": { \"path\": \"classify.result\", \"value\": \"ok\" } }, \"to\": \"port1\" }], \"default\": \"fallbackPort\" }\n Wire with edges: { \"from\": \"branchId\", \"fromPort\": \"port1\", \"to\": \"nextNode\" }\n- \\`gateway.parallel\\` — fan-out (one → many) or join (many → one).\n config: { \"mode\": \"fanOut\" } — splits to every outgoing edge\n config: { \"mode\": \"join\" } — waits until every incoming edge arrives, then fires once\n- \\`rule\\` — DMN decision table, first matching row wins.\n config: {\n \"inputs\": [\"{{trigger.tier}}\", \"{{trigger.amount}}\"],\n \"rules\": [\n { \"when\": [\"gold\", \">100\"], \"to\": \"vip\", \"output\": { \"route\": \"vip\" } },\n { \"when\": [\"*\", \">50\"], \"to\": \"high\", \"output\": { \"route\": \"high\" } }\n ],\n \"default\": { \"to\": \"low\", \"output\": { \"route\": \"low\" } }\n }\n Cell syntax: \"*\" wildcard, exact \"value\", \">N\" \"<N\" \">=N\" \"<=N\", \"!=x\", \"/regex/\".\n- \\`checkpoint\\` — pause until a matching event.\n config: { \"name\": \"await-x\", \"waitFor\": { \"source\": \"manual\" }, \"resumeMatch\": {} }\n\n## BPM\n- \\`userTask\\` — assign a form to an actor or role; pauses until submission.\n config: {\n \"assignTo\": \"actor:alice\" | \"role:reviewers\",\n \"title\": \"Review expense {{trigger.values.amount}}\",\n \"description\": \"…\",\n \"dueIn\": \"P2D\" | \"PT2H\" | { \"minutes\": 60 },\n \"form\": FormSchema\n }\n Output: { submittedBy, submittedAt, values: { fieldKey: value }, action: \"primary\" | \"secondary\" }\n- \\`subProcess\\` — spawn a child workflow; parent pauses until child reaches end.\n config: {\n \"workflowId\": \"<other workflow id>\",\n \"inputMap\": { \"trigger\": { \"grantee\": \"{{trigger.values.name}}\" } } (or \"*\" for full inherit),\n \"awaitCompletion\": true\n }\n Output: { childRunId, status, output: <child's last bundle> }\n- \\`signal.emit\\` — publish an event. config: { \"name\": \"approved\", \"scope\": \"workflow\"|\"global\", \"payload\": {} }\n- \\`signal.wait\\` — pause until matching signal arrives. config: { \"name\": \"approved\", \"scope\": \"workflow\", \"match\": { \"grantId\": \"{{trigger.id}}\" } }\n- \\`timer.boundary\\` — pause for a duration. config: { \"after\": \"PT2H\" | \"P1D\" | 60 (minutes) }\n\n## Actions — side-effect sinks\n- \\`action.send\\` — post a message to any channel. config: { \"channel\": \"telegram\"|\"whatsapp\"|…, \"chatId\": \"{{trigger.chatId}}\", \"text\": \"Hi {{classify.reply}}\", \"accountId\"?: \"…\" }\n- \\`action.createIssue\\` — open a GitLab issue. config: { \"channel\": \"gitlab\", \"project\": \"acme/web\", \"title\": \"…\", \"description\": \"…\", \"labels\": [\"x\"], \"assignees\": [\"user\"] }\n- \\`action.setLabel\\` / \\`action.readLabel\\` / \\`action.react\\` / \\`action.editMessage\\` / \\`action.logTime\\` — self-explanatory; each maps 1:1 to a channel adapter method.\n- \\`action.callHTTP\\` — outbound HTTP. config: { \"method\": \"POST\"|\"GET\"|…, \"url\": \"https://…\", \"headers\": {}, \"body\": {}, \"timeoutMs\": 30000 }\n\n## Terminal\n- \\`end\\` — completes the run. config: { \"status\": \"completed\" | \"failed\" | \"canceled\" }\n\n## FormSchema (used by userTask + trigger.form)\n{\n \"title\": \"Review application\",\n \"description\": \"…\",\n \"fields\": [\n { \"key\": \"score\", \"label\": \"Score\", \"type\": \"number\", \"required\": true, \"validate\": { \"min\": 1, \"max\": 10 } },\n { \"key\": \"verdict\", \"label\": \"Verdict\", \"type\": \"select\", \"required\": true, \"options\": [\"approve\", \"reject\"] },\n { \"key\": \"notes\", \"label\": \"Notes\", \"type\": \"long-text\" }\n ],\n \"submitLabel\": \"Approve\",\n \"secondaryAction\": { \"key\": \"reject\", \"label\": \"Reject\" }\n}\nField types: text, long-text, number, boolean, date, select, multi-select, file.\nA form with a \\`secondaryAction\\` and no required-unfilled fields renders as one-tap Approve/Reject buttons in chat.\n\n## Templates\nEvery prompt + config value can reference \\`{{nodeId.path}}\\` against the run context. Examples:\n {{trigger.values.amount}} — field from the start form\n {{classify.result}} — parsed RESULT: token from an agent node\n {{review.values.score}} — submitted userTask field\n {{env.GITLAB_TOKEN}} — env var (must be listed in workflow.envAllow)\n\n## Edges\n[{ \"from\": \"nodeId\", \"to\": \"nodeId\" }, { \"from\": \"branchId\", \"fromPort\": \"case-label\", \"to\": \"nodeId\" }]\nEvery edge's from/to must reference an existing node. Branch + rule nodes MUST have outgoing edges whose fromPort matches a declared case/rule/default.\n\n## Workflow shell\n{\n \"id\": \"lower-kebab-id\",\n \"version\": 2,\n \"title\": \"Human readable\",\n \"description\": \"optional\",\n \"priority\": 0,\n \"fanOut\": false,\n \"envAllow\": [],\n \"maxChildDepth\": 5,\n \"retention\": { \"maxRuns\": 500, \"maxDays\": 90 },\n \"nodes\": [...],\n \"edges\": [...]\n}\n\n## Lint rules (all enforced on save)\n- exactly one trigger.* node\n- every edge references an existing node\n- every node is reachable from the trigger\n- at least one end/checkpoint/userTask/subProcess/signal.wait/timer.boundary is reachable\n- branch + rule outgoing fromPort values match declared cases (or default)\n- cycles are only allowed when the cycle crosses an agent/checkpoint/userTask/subProcess/signal.wait/timer.boundary`\n\nconst RESPONSE_RULES = `# Your reply\n\nRespond in ONE of two ways:\n\n1. **Clarification**: if the user's request is ambiguous, ask exactly ONE short follow-up question. No JSON.\n\n2. **Workflow**: if you have enough to produce a workflow, reply with:\n - 1–3 short lines explaining what you built\n - a \\`\\`\\`json code block containing the complete, valid V2 workflow\n - (no prose after the JSON block)\n\nOnly reference agent ids, actor ids, role ids, and channel names that\nappear in the Environment section above. If the user asks for an agent\nthat doesn't exist, tell them which agent to register first. Never\ninvent workflowIds for subProcess that aren't in the existing list.`"],"mappings":"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","names":["buildWorkflowAuthorPrompt","args","workflows","w","parts","SYSTEM_HEADER","NODE_CATALOG","a","c","m","tag","RESPONSE_RULES","extractWorkflowJson","reply","fenced","candidates","braceMatch","raw","parsed"]}
|
|
1
|
+
{"version":3,"sources":["../src/workflows/editor-chat.ts"],"sourcesContent":["import type { Workflow } from \"./types\"\nimport type { WorkflowStore } from \"./store\"\n\n// --- Workflow-builder chat context ---\n//\n// Produces the plain-text prompt the authoring agent reads. Packs\n// *everything* the agent needs to generate a valid V2 workflow JSON on\n// its first try: node catalog with config examples, available agent\n// ids, actor + role ids, channel adapter names, the user's existing\n// workflow list (for subProcess targets), and — when the author is\n// editing — the current workflow JSON as a starting point.\n//\n// The output is deliberately text, not JSON. Agents (LLMs) produce\n// better structured output when the schema is described as prose +\n// examples rather than as raw JSON Schema. The explicit \"reply with a\n// ```json block```\" instruction at the tail is what the API endpoint\n// parses back.\n\nexport interface ChatMessage {\n role: \"user\" | \"assistant\"\n content: string\n}\n\nexport interface BuildContextArgs {\n messages: ChatMessage[]\n store: WorkflowStore\n /** Full list of agent ids + optional descriptions. */\n availableAgents: Array<{ id: string; description?: string; tags?: string[] }>\n /** Adapter names the daemon has live (telegram, whatsapp, gitlab, ...). */\n availableChannels: string[]\n /** The workflow the user is currently editing (if any). */\n currentWorkflow?: Workflow\n}\n\n/** Build the single-string prompt the agent executes. */\nexport function buildWorkflowAuthorPrompt(args: BuildContextArgs): string {\n const workflows = args.store.list().map((w) => ({ id: w.id, title: w.title }))\n\n const parts: string[] = []\n\n parts.push(SYSTEM_HEADER)\n parts.push(\"\")\n parts.push(NODE_CATALOG)\n parts.push(\"\")\n parts.push(\"# Environment — only reference values that exist\")\n parts.push(\"\")\n parts.push(`## Available agents (for \\`agent\\` nodes)`)\n if (args.availableAgents.length === 0) {\n parts.push(\" (none registered — the user must add an agent first for `agent` nodes to work)\")\n } else {\n for (const a of args.availableAgents) {\n parts.push(` - \\`${a.id}\\`${a.description ? ` — ${a.description}` : \"\"}`)\n }\n }\n parts.push(\"\")\n parts.push(\"## Assignees (for `userTask.assignTo`)\")\n parts.push(\" Any agent id above, or a plain string naming the person responsible.\")\n parts.push(\"\")\n parts.push(\"## Available roles (for `userTask.assignTo`)\")\n parts.push(\"\")\n parts.push(\"## Available channels (for `action.*` and `trigger.channel`)\")\n parts.push(` ${args.availableChannels.length ? args.availableChannels.map((c) => `\\`${c}\\``).join(\", \") : \"(none live on this node)\"}`)\n parts.push(\"\")\n parts.push(\"## Existing workflows (for `subProcess.workflowId`)\")\n if (workflows.length === 0) parts.push(\" (no other workflows defined)\")\n else for (const w of workflows) parts.push(` - \\`${w.id}\\` — ${w.title}`)\n parts.push(\"\")\n\n if (args.currentWorkflow) {\n parts.push(\"# Current workflow on canvas\")\n parts.push(\"\")\n parts.push(\"The user is editing this workflow. Build on it — do NOT replace it unless they explicitly ask.\")\n parts.push(\"\")\n parts.push(\"```json\")\n parts.push(JSON.stringify(args.currentWorkflow, null, 2))\n parts.push(\"```\")\n parts.push(\"\")\n }\n\n parts.push(\"# Conversation\")\n parts.push(\"\")\n for (const m of args.messages) {\n const tag = m.role === \"user\" ? \"USER\" : \"ASSISTANT\"\n parts.push(`${tag}: ${m.content}`)\n parts.push(\"\")\n }\n\n parts.push(RESPONSE_RULES)\n return parts.join(\"\\n\")\n}\n\n/** Try to extract a workflow-shaped JSON block from an agent reply. Returns\n * null if no JSON block is present OR the JSON doesn't have the minimum\n * workflow fields (id, nodes). The caller still runs full zod validation\n * before writing. */\nexport function extractWorkflowJson(reply: string): Record<string, unknown> | null {\n // Prefer fenced ```json blocks; fall back to the largest {...} block.\n const fenced = /```(?:json)?\\s*\\n([\\s\\S]*?)```/.exec(reply)\n const candidates: string[] = []\n if (fenced) candidates.push(fenced[1])\n const braceMatch = reply.match(/\\{[\\s\\S]*\\}/)\n if (braceMatch) candidates.push(braceMatch[0])\n\n for (const raw of candidates) {\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && \"id\" in parsed && \"nodes\" in parsed) {\n return parsed as Record<string, unknown>\n }\n } catch { /* try next */ }\n }\n return null\n}\n\nconst SYSTEM_HEADER = `You are AgentX's workflow author. The user describes a business process in\nplain language; you return a valid V2 workflow JSON that implements it.\n\nRead the node catalog below. Prefer the BPM primitives (userTask,\nsubProcess, signal.emit/wait, timer.boundary, gateway.parallel, rule)\nwhen modelling processes with humans, deadlines, parallel streams, or\nnested activities. Prefer the bot primitives (agent, branch, action.*)\nfor simple message-in → reply-out automations.`\n\nconst NODE_CATALOG = `# V2 Node catalog\n\n## Triggers (exactly one per workflow)\n- \\`trigger.channel\\` — inbound channel event.\n config: { \"source\": \"whatsapp-message\" | \"telegram-message\" | \"slack-message\" | \"discord-message\" | \"gitlab-issue\" | \"gitlab-pipeline\", \"filter\": { \"chat\"?: \"*\", \"project\"?: \"acme/web\", \"labels\"?: [\"x\"] } }\n- \\`trigger.cron\\` — scheduled. config: { \"spec\": \"0 9 * * *\", \"timezone\": \"UTC\" }\n- \\`trigger.hook\\` — subscribes to any on:* hook event. config: { \"event\": \"on:gitlab-issue\" }\n- \\`trigger.poll\\` — runs a registered action every N seconds; one run per NEW item it prints (one JSON object per line). The item is the trigger payload.\n config: { \"actionId\": \"my-list-action\", \"everySeconds\": 60, \"key\": \"id\", \"filter\"?: [ { \"kind\": \"matches\", \"params\": { \"path\": \"text\", \"regex\": \"^@bot\" } } ] }\n- \\`trigger.manual\\` — kicked off by CLI or API. config: {}\n- \\`trigger.form\\` — human fills a form to start. config: { \"form\": FormSchema, \"startableBy\": \"role:public\" }\n\n## Compute\n- \\`agent\\` — run an agent with a templated prompt. Output: { reply, result (parsed RESULT: token), json?, durationMs }.\n config: { \"agentId\": \"<id>\", \"prompt\": \"Classify {{trigger.text}} — reply on one line: RESULT: a|b|c\", \"resultParser\": \"acme-result-token\" | \"json\", \"timeoutMinutes\": 2 }\n- \\`transform\\` — reshape upstream context.\n config: { \"path\": \"trigger.contact.phone\" } OR { \"template\": { \"key\": \"{{trigger.text}}\" } }\n\n## Control flow\n- \\`branch\\` — N-way switch (first match wins).\n config: { \"cases\": [{ \"when\": { \"kind\": \"equals\"|\"contains\"|\"matches\"|\"exists\", \"params\": { \"path\": \"classify.result\", \"value\": \"ok\" } }, \"to\": \"port1\" }], \"default\": \"fallbackPort\" }\n Wire with edges: { \"from\": \"branchId\", \"fromPort\": \"port1\", \"to\": \"nextNode\" }\n- \\`gateway.parallel\\` — fan-out (one → many) or join (many → one).\n config: { \"mode\": \"fanOut\" } — splits to every outgoing edge\n config: { \"mode\": \"join\" } — waits until every incoming edge arrives, then fires once\n- \\`rule\\` — DMN decision table, first matching row wins.\n config: {\n \"inputs\": [\"{{trigger.tier}}\", \"{{trigger.amount}}\"],\n \"rules\": [\n { \"when\": [\"gold\", \">100\"], \"to\": \"vip\", \"output\": { \"route\": \"vip\" } },\n { \"when\": [\"*\", \">50\"], \"to\": \"high\", \"output\": { \"route\": \"high\" } }\n ],\n \"default\": { \"to\": \"low\", \"output\": { \"route\": \"low\" } }\n }\n Cell syntax: \"*\" wildcard, exact \"value\", \">N\" \"<N\" \">=N\" \"<=N\", \"!=x\", \"/regex/\".\n- \\`checkpoint\\` — pause until a matching event.\n config: { \"name\": \"await-x\", \"waitFor\": { \"source\": \"manual\" }, \"resumeMatch\": {} }\n\n## BPM\n- \\`userTask\\` — assign a form to an actor or role; pauses until submission.\n config: {\n \"assignTo\": \"actor:alice\" | \"role:reviewers\",\n \"title\": \"Review expense {{trigger.values.amount}}\",\n \"description\": \"…\",\n \"dueIn\": \"P2D\" | \"PT2H\" | { \"minutes\": 60 },\n \"form\": FormSchema\n }\n Output: { submittedBy, submittedAt, values: { fieldKey: value }, action: \"primary\" | \"secondary\" }\n- \\`subProcess\\` — spawn a child workflow; parent pauses until child reaches end.\n config: {\n \"workflowId\": \"<other workflow id>\",\n \"inputMap\": { \"trigger\": { \"grantee\": \"{{trigger.values.name}}\" } } (or \"*\" for full inherit),\n \"awaitCompletion\": true\n }\n Output: { childRunId, status, output: <child's last bundle> }\n- \\`signal.emit\\` — publish an event. config: { \"name\": \"approved\", \"scope\": \"workflow\"|\"global\", \"payload\": {} }\n- \\`signal.wait\\` — pause until matching signal arrives. config: { \"name\": \"approved\", \"scope\": \"workflow\", \"match\": { \"grantId\": \"{{trigger.id}}\" } }\n- \\`timer.boundary\\` — pause for a duration. config: { \"after\": \"PT2H\" | \"P1D\" | 60 (minutes) }\n\n## The owner and other people (follow-up steps)\nAn edge without fromPort leaves on the main port (yes / sent / reply); add edges with fromPort for the others.\n- \\`owner.notify\\` — tell the owner. config: { \"text\": \"Deployed: {{deploy.reply}}\" }\n- \\`owner.ask\\` — a decision card for the owner; ports yes / no / expired. config: { \"ask\": \"Ship it?\", \"recommend\": \"…\", \"draft\"?: \"…\", \"choices\"?: [\"a\",\"b\"] }. Output: { port, choice, text, note }\n- \\`person.message\\` — message an employee or client once the owner approves the text (at start or on its own card); ports sent / declined. config: { \"to\": \"Sam\", \"channel\": \"telegram\", \"chatId\": \"…\", \"text\": \"…\" }\n- \\`person.wait\\` — wait for that person's reply; ports reply / timeout. config: { \"reminds\": \"<person.message id>\", \"timeout\": \"2d\", \"remindAfter\": \"1d\" } (or channel + chatId). Output: { text, from, media }\n\n## Actions — side-effect sinks\n- \\`action.send\\` — post a message to any channel. config: { \"channel\": \"telegram\"|\"whatsapp\"|…, \"chatId\": \"{{trigger.chatId}}\", \"text\": \"Hi {{classify.reply}}\", \"accountId\"?: \"…\" }\n- \\`action.createIssue\\` — open a GitLab issue. config: { \"channel\": \"gitlab\", \"project\": \"acme/web\", \"title\": \"…\", \"description\": \"…\", \"labels\": [\"x\"], \"assignees\": [\"user\"] }\n- \\`action.setLabel\\` / \\`action.readLabel\\` / \\`action.react\\` / \\`action.editMessage\\` / \\`action.logTime\\` — self-explanatory; each maps 1:1 to a channel adapter method.\n- \\`action.callHTTP\\` — outbound HTTP. config: { \"method\": \"POST\"|\"GET\"|…, \"url\": \"https://…\", \"headers\": {}, \"body\": {}, \"timeoutMs\": 30000 }\n\n## Terminal\n- \\`end\\` — completes the run. config: { \"status\": \"completed\" | \"failed\" | \"canceled\" }\n\n## FormSchema (used by userTask + trigger.form)\n{\n \"title\": \"Review application\",\n \"description\": \"…\",\n \"fields\": [\n { \"key\": \"score\", \"label\": \"Score\", \"type\": \"number\", \"required\": true, \"validate\": { \"min\": 1, \"max\": 10 } },\n { \"key\": \"verdict\", \"label\": \"Verdict\", \"type\": \"select\", \"required\": true, \"options\": [\"approve\", \"reject\"] },\n { \"key\": \"notes\", \"label\": \"Notes\", \"type\": \"long-text\" }\n ],\n \"submitLabel\": \"Approve\",\n \"secondaryAction\": { \"key\": \"reject\", \"label\": \"Reject\" }\n}\nField types: text, long-text, number, boolean, date, select, multi-select, file.\nA form with a \\`secondaryAction\\` and no required-unfilled fields renders as one-tap Approve/Reject buttons in chat.\n\n## Templates\nEvery prompt + config value can reference \\`{{nodeId.path}}\\` against the run context. Examples:\n {{trigger.values.amount}} — field from the start form\n {{classify.result}} — parsed RESULT: token from an agent node\n {{review.values.score}} — submitted userTask field\n {{env.GITLAB_TOKEN}} — env var (must be listed in workflow.envAllow)\n\n## Edges\n[{ \"from\": \"nodeId\", \"to\": \"nodeId\" }, { \"from\": \"branchId\", \"fromPort\": \"case-label\", \"to\": \"nodeId\" }]\nEvery edge's from/to must reference an existing node. Branch + rule nodes MUST have outgoing edges whose fromPort matches a declared case/rule/default.\n\n## Workflow shell\n{\n \"id\": \"lower-kebab-id\",\n \"version\": 2,\n \"title\": \"Human readable\",\n \"description\": \"optional\",\n \"priority\": 0,\n \"fanOut\": false,\n \"envAllow\": [],\n \"maxChildDepth\": 5,\n \"retention\": { \"maxRuns\": 500, \"maxDays\": 90 },\n \"nodes\": [...],\n \"edges\": [...]\n}\n\n## Lint rules (all enforced on save)\n- exactly one trigger.* node\n- every edge references an existing node\n- every node is reachable from the trigger\n- at least one end/checkpoint/userTask/subProcess/signal.wait/timer.boundary is reachable\n- branch + rule outgoing fromPort values match declared cases (or default)\n- cycles are only allowed when the cycle crosses an agent/checkpoint/userTask/subProcess/signal.wait/timer.boundary`\n\nconst RESPONSE_RULES = `# Your reply\n\nRespond in ONE of two ways:\n\n1. **Clarification**: if the user's request is ambiguous, ask exactly ONE short follow-up question. No JSON.\n\n2. **Workflow**: if you have enough to produce a workflow, reply with:\n - 1–3 short lines explaining what you built\n - a \\`\\`\\`json code block containing the complete, valid V2 workflow\n - (no prose after the JSON block)\n\nOnly reference agent ids, actor ids, role ids, and channel names that\nappear in the Environment section above. If the user asks for an agent\nthat doesn't exist, tell them which agent to register first. Never\ninvent workflowIds for subProcess that aren't in the existing list.`"],"mappings":"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","names":["buildWorkflowAuthorPrompt","args","workflows","w","parts","SYSTEM_HEADER","NODE_CATALOG","a","c","m","tag","RESPONSE_RULES","extractWorkflowJson","reply","fenced","candidates","braceMatch","raw","parsed"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{b as h}from"./chunk-WXABFPX7.js";import"./chunk-RKPAVWXF.js";import{b as m}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-EV2WPHHS.js";import"./chunk-LRMUK6DC.js";import"./chunk-UNWXKBRF.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-TEXZEXQZ.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function k(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(r=>`- ${String(r.at).slice(0,16).replace("T"," ")} ${r.step} ${r.status}${r.note?`: ${r.note}`:""}`)].filter(Boolean).join(`
|
|
2
|
+
`)}async function T(t,u){let r=u.fetch??fetch,$=u.daemonUrl.replace(/\/$/,""),a=(p(t.action)||"list").toLowerCase(),f=u.env??process.env,w=async i=>{let l=await r(`${$}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(a==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(c=>[`${c.tag}:`,...c.rows.map(s=>`- ${s.runId} "${s.title}" on ${s.step}: waiting on ${s.waitingOn} (since ${String(s.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
|
+
`)).join(`
|
|
4
|
+
`):"No follow-up workflows are running."}if(a==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),c=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!c.ok)return`Error: ${c.data?.error||`HTTP ${c.status}`}`;let s=c.data.matches??[];return s.length?["Saved workflows, best fit first (confidence 0-1):",...s.map(d=>`- ${d.workflowId} "${d.title}" (${d.confidence}${d.autoStart?", starts without asking":""}): ${d.steps.map(I=>I.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
|
+
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(a==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?k(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await r(`${$}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...m(f)},body:JSON.stringify({action:a,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(a==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return a==="done"?`Step recorded as done. ${n.run?k(n.run):""}`.trim():a==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
6
|
+
//# sourceMappingURL=follow-up-tool-ZVEYUJ6U.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflows/follow-up-tool.ts"],"sourcesContent":["import { resolveScheduleCaller } from \"@/crons/schedule-tool\"\nimport { callerHeaders } from \"@/calls/service\"\n\n// --- Agent-facing `agentx_workflow` tool (#788) ---\n//\n// A request with several steps is run as a workflow, not by hand:\n// match saved workflows that fit the request in front of you\n// start start one (workflowId), or build one from the owner's words\n// (title + steps) and run it; tags say what it concerns\n// status one run: the step it is on and what it waits on\n// list every follow-up still going, grouped by tag\n// done the step you own is finished (evidence)\n// blocked your step cannot go on without the owner (reason)\n// propose ask the owner to keep a workflow as a reusable template\n// It talks to the daemon's /follow-up endpoints.\n\nexport interface WorkflowToolDeps {\n daemonUrl: string\n fetch?: typeof fetch\n env?: NodeJS.ProcessEnv\n}\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\")\n\nfunction describe(run: any): string {\n const lines = [\n `Run ${run.runId} \"${run.title}\" [${run.status}] on step ${run.step}: waiting on ${run.waitingOn}.`,\n run.tags?.length ? `Tags: ${run.tags.join(\", \")}` : \"\",\n ...(run.steps ?? []).slice(-8).map((s: any) => `- ${String(s.at).slice(0, 16).replace(\"T\", \" \")} ${s.step} ${s.status}${s.note ? `: ${s.note}` : \"\"}`),\n ]\n return lines.filter(Boolean).join(\"\\n\")\n}\n\n/** Returns the text the agent sees. Every refusal is text, never a throw. */\nexport async function runWorkflowTool(args: Record<string, unknown>, deps: WorkflowToolDeps): Promise<string> {\n const doFetch = deps.fetch ?? fetch\n const base = deps.daemonUrl.replace(/\\/$/, \"\")\n const action = (str(args.action) || \"list\").toLowerCase()\n const env = deps.env ?? process.env\n const read = async (path: string) => {\n const res = await doFetch(`${base}${path}`, { signal: AbortSignal.timeout(10_000) })\n const data = await res.json().catch(() => ({})) as any\n return { ok: res.ok, status: res.status, data }\n }\n\n try {\n if (action === \"list\") {\n const r = await read(\"/follow-up\")\n if (!r.ok) return `Error: ${r.data?.error || `HTTP ${r.status}`}`\n const groups = r.data.groups ?? []\n if (!groups.length) return \"No follow-up workflows are running.\"\n return groups.map((g: any) => [`${g.tag}:`, ...g.rows.map((row: any) => `- ${row.runId} \"${row.title}\" on ${row.step}: waiting on ${row.waitingOn} (since ${String(row.since).slice(0, 16).replace(\"T\", \" \")} UTC)`)].join(\"\\n\")).join(\"\\n\")\n }\n if (action === \"match\") {\n const q = str(args.request) || str(args.title)\n if (!q) return \"Error: match needs `request`: the owner's request in their words.\"\n const caller = resolveScheduleCaller(args, env)\n const r = await read(`/follow-up/match?q=${encodeURIComponent(q)}${caller ? `&agentId=${encodeURIComponent(caller.agentId)}` : \"\"}`)\n if (!r.ok) return `Error: ${r.data?.error || `HTTP ${r.status}`}`\n const matches = r.data.matches ?? []\n if (!matches.length) return \"No saved workflow fits. If the request has several steps, build one: start with title and steps.\"\n return [\n \"Saved workflows, best fit first (confidence 0-1):\",\n ...matches.map((x: any) => `- ${x.workflowId} \"${x.title}\" (${x.confidence}${x.autoStart ? \", starts without asking\" : \"\"}): ${x.steps.map((s: any) => s.id).join(\" → \")}`),\n `Start one with {action:\"start\", workflowId:\"<id>\", title:\"…\", tags:[\"client:<name>\"]}. Run its steps through the workflow, not by hand.`,\n ].join(\"\\n\")\n }\n if (action === \"status\") {\n const runId = str(args.runId)\n if (!runId) return \"Error: status needs runId.\"\n const r = await read(`/follow-up/${encodeURIComponent(runId)}`)\n if (!r.ok) return `Error: ${r.data?.error || `HTTP ${r.status}`}`\n return describe(r.data.run)\n }\n\n const caller = resolveScheduleCaller(args, env)\n if (!caller) return \"Error: couldn't tell which agent you are. Pass callerAgentId.\"\n const res = await doFetch(`${base}/follow-up`, {\n method: \"POST\",\n // The headers name this run: the daemon refuses a write that does\n // not come from a running turn of the agent.\n headers: { \"Content-Type\": \"application/json\", ...callerHeaders(env) },\n body: JSON.stringify({\n action, agentId: caller.agentId,\n workflowId: args.workflowId, title: args.title, description: args.description, tags: args.tags, inputs: args.inputs,\n steps: args.steps, edges: args.edges, approval: args.approval, autoStart: args.autoStart, requestId: args.requestId,\n runId: args.runId, step: args.step, evidence: args.evidence, note: args.note, reason: args.reason, fromRun: args.fromRun,\n }),\n signal: AbortSignal.timeout(20_000),\n })\n const data = await res.json().catch(() => ({})) as any\n if (!res.ok) return `Error: ${data?.error || `HTTP ${res.status}`}`\n if (action === \"start\") {\n const run = data.run\n return [\n `Started run ${run.runId} \"${run.title}\"${data.built ? \" (built from the steps you gave; propose it with fromRun to keep it)\" : \"\"}.`,\n data.awaitingApproval ? \"It waits for the owner's approval before the first step.\" : `It is on step ${run.step}: ${run.waitingOn}.`,\n \"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.\",\n ...(data.warning ? [`Note: ${data.warning}`] : []),\n ].join(\" \")\n }\n if (action === \"done\") return `Step recorded as done. ${data.run ? describe(data.run) : \"\"}`.trim()\n if (action === \"blocked\") return \"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.\"\n return `Saved ${data.workflowId} switched off, and asked the owner (card ${data.cardId}) whether to keep it as a reusable workflow.`\n } catch (e: any) {\n return `Error: couldn't reach the daemon (${e?.message ?? e}).`\n }\n}\n"],"mappings":"gaAsBA,IAAMA,EAAOC,GAAgB,OAAOA,GAAM,SAAWA,EAAE,KAAK,EAAI,GAEhE,SAASC,EAASC,EAAkB,CAMlC,MALc,CACZ,OAAOA,EAAI,UAAUA,EAAI,WAAWA,EAAI,mBAAmBA,EAAI,oBAAoBA,EAAI,aACvFA,EAAI,MAAM,OAAS,SAASA,EAAI,KAAK,KAAK,IAAI,IAAM,GACpD,IAAIA,EAAI,OAAS,CAAC,GAAG,MAAM,EAAE,EAAE,IAAKC,GAAW,KAAK,OAAOA,EAAE,EAAE,EAAE,MAAM,EAAG,EAAE,EAAE,QAAQ,IAAK,GAAG,KAAKA,EAAE,QAAQA,EAAE,SAASA,EAAE,KAAO,KAAKA,EAAE,OAAS,IAAI,CACvJ,EACa,OAAO,OAAO,EAAE,KAAK;AAAA,CAAI,CACxC,CAGA,eAAsBC,EAAgBC,EAA+BC,EAAyC,CAC5G,IAAMC,EAAUD,EAAK,OAAS,MACxBE,EAAOF,EAAK,UAAU,QAAQ,MAAO,EAAE,EACvCG,GAAUV,EAAIM,EAAK,MAAM,GAAK,QAAQ,YAAY,EAClDK,EAAMJ,EAAK,KAAO,QAAQ,IAC1BK,EAAO,MAAOC,GAAiB,CACnC,IAAMC,EAAM,MAAMN,EAAQ,GAAGC,IAAOI,IAAQ,CAAE,OAAQ,YAAY,QAAQ,GAAM,CAAE,CAAC,EAC7EE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,MAAO,CAAE,GAAIA,EAAI,GAAI,OAAQA,EAAI,OAAQ,KAAAC,CAAK,CAChD,EAEA,GAAI,CACF,GAAIL,IAAW,OAAQ,CACrB,IAAMM,EAAI,MAAMJ,EAAK,YAAY,EACjC,GAAI,CAACI,EAAE,GAAI,MAAO,UAAUA,EAAE,MAAM,OAAS,QAAQA,EAAE,WACvD,IAAMC,EAASD,EAAE,KAAK,QAAU,CAAC,EACjC,OAAKC,EAAO,OACLA,EAAO,IAAKC,GAAW,CAAC,GAAGA,EAAE,OAAQ,GAAGA,EAAE,KAAK,IAAKC,GAAa,KAAKA,EAAI,UAAUA,EAAI,aAAaA,EAAI,oBAAoBA,EAAI,oBAAoB,OAAOA,EAAI,KAAK,EAAE,MAAM,EAAG,EAAE,EAAE,QAAQ,IAAK,GAAG,QAAQ,CAAC,EAAE,KAAK;AAAA,CAAI,CAAC,EAAE,KAAK;AAAA,CAAI,EADhN,sCAG7B,GAAIT,IAAW,QAAS,CACtB,IAAMU,EAAIpB,EAAIM,EAAK,OAAO,GAAKN,EAAIM,EAAK,KAAK,EAC7C,GAAI,CAACc,EAAG,MAAO,oEACf,IAAMC,EAASC,EAAsBhB,EAAMK,CAAG,EACxCK,EAAI,MAAMJ,EAAK,sBAAsB,mBAAmBQ,CAAC,IAAIC,EAAS,YAAY,mBAAmBA,EAAO,OAAO,IAAM,IAAI,EACnI,GAAI,CAACL,EAAE,GAAI,MAAO,UAAUA,EAAE,MAAM,OAAS,QAAQA,EAAE,WACvD,IAAMO,EAAUP,EAAE,KAAK,SAAW,CAAC,EACnC,OAAKO,EAAQ,OACN,CACL,oDACA,GAAGA,EAAQ,IAAKC,GAAW,KAAKA,EAAE,eAAeA,EAAE,WAAWA,EAAE,aAAaA,EAAE,UAAY,0BAA4B,QAAQA,EAAE,MAAM,IAAKpB,GAAWA,EAAE,EAAE,EAAE,KAAK,UAAK,GAAG,EAC1K,8IACF,EAAE,KAAK;AAAA,CAAI,EALiB,mGAO9B,GAAIM,IAAW,SAAU,CACvB,IAAMe,EAAQzB,EAAIM,EAAK,KAAK,EAC5B,GAAI,CAACmB,EAAO,MAAO,6BACnB,IAAMT,EAAI,MAAMJ,EAAK,cAAc,mBAAmBa,CAAK,GAAG,EAC9D,OAAKT,EAAE,GACAd,EAASc,EAAE,KAAK,GAAG,EADR,UAAUA,EAAE,MAAM,OAAS,QAAQA,EAAE,WAIzD,IAAMK,EAASC,EAAsBhB,EAAMK,CAAG,EAC9C,GAAI,CAACU,EAAQ,MAAO,gEACpB,IAAMP,EAAM,MAAMN,EAAQ,GAAGC,cAAkB,CAC7C,OAAQ,OAGR,QAAS,CAAE,eAAgB,mBAAoB,GAAGiB,EAAcf,CAAG,CAAE,EACrE,KAAM,KAAK,UAAU,CACnB,OAAAD,EAAQ,QAASW,EAAO,QACxB,WAAYf,EAAK,WAAY,MAAOA,EAAK,MAAO,YAAaA,EAAK,YAAa,KAAMA,EAAK,KAAM,OAAQA,EAAK,OAC7G,MAAOA,EAAK,MAAO,MAAOA,EAAK,MAAO,SAAUA,EAAK,SAAU,UAAWA,EAAK,UAAW,UAAWA,EAAK,UAC1G,MAAOA,EAAK,MAAO,KAAMA,EAAK,KAAM,SAAUA,EAAK,SAAU,KAAMA,EAAK,KAAM,OAAQA,EAAK,OAAQ,QAASA,EAAK,OACnH,CAAC,EACD,OAAQ,YAAY,QAAQ,GAAM,CACpC,CAAC,EACKS,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,MAAO,UAAUC,GAAM,OAAS,QAAQD,EAAI,WACzD,GAAIJ,IAAW,QAAS,CACtB,IAAMP,EAAMY,EAAK,IACjB,MAAO,CACL,eAAeZ,EAAI,UAAUA,EAAI,SAASY,EAAK,MAAQ,uEAAyE,MAChIA,EAAK,iBAAmB,2DAA6D,iBAAiBZ,EAAI,SAASA,EAAI,aACvH,6IACA,GAAIY,EAAK,QAAU,CAAC,SAASA,EAAK,SAAS,EAAI,CAAC,CAClD,EAAE,KAAK,GAAG,EAEZ,OAAIL,IAAW,OAAe,0BAA0BK,EAAK,IAAMb,EAASa,EAAK,GAAG,EAAI,KAAK,KAAK,EAC9FL,IAAW,UAAkB,mGAC1B,SAASK,EAAK,sDAAsDA,EAAK,oDAClF,OAASY,EAAP,CACA,MAAO,qCAAqCA,GAAG,SAAWA,KAC5D,CACF","names":["str","v","describe","run","s","runWorkflowTool","args","deps","doFetch","base","action","env","read","path","res","data","r","groups","g","row","q","caller","resolveScheduleCaller","matches","x","runId","callerHeaders","e"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=grants-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-WEPON4FP.js";import"./chunk-AKLZ4YO2.js";import"./chunk-Y4CYQV7G.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_GRANT_DAYS,a as GUEST_SCOPE_PREFIX,b as JOIN_CARD_BY,h as JOIN_FAILED,d as MAX_GRANT_DAYS,j as NO_GRANT,l as PAUSED,k as WAITING_HOST,s as endGrant,o as grantBrief,u as grantForGuest,e as grantIdOf,n as guestAccess,p as guestTask,g as inviteGuest,i as joinGuest,f as newGrantId,q as pauseGrant,r as resumeGrant,m as settleGrant,t as updateGrant};
|
|
2
|
+
//# sourceMappingURL=grants-HIFE6L5N.js.map
|