agentix-cli 0.213.2 → 0.214.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-2GK32HCI.js → agent-KUCECPSZ.js} +2 -2
- package/dist/{board-dashboard-6JUASBDZ.js → board-dashboard-SHU4BWRO.js} +3 -3
- package/dist/{board-dashboard-6JUASBDZ.js.map → board-dashboard-SHU4BWRO.js.map} +1 -1
- package/dist/{chunk-WAVO3U3I.js → chunk-2KNI7ZRN.js} +87 -147
- package/dist/chunk-2KNI7ZRN.js.map +1 -0
- package/dist/chunk-4NZ4T3TQ.js +3 -0
- package/dist/{chunk-MNG2AMKZ.js.map → chunk-4NZ4T3TQ.js.map} +1 -1
- package/dist/{chunk-ZMGDHLZD.js → chunk-4ZD2C76P.js} +2 -2
- package/dist/{chunk-GJOKXP5D.js → chunk-6UTOBSEA.js} +2 -2
- package/dist/{chunk-2CO3NK6Z.js → chunk-C3O2ER6D.js} +2 -2
- package/dist/chunk-CSC45PA7.js +62 -0
- package/dist/chunk-CSC45PA7.js.map +1 -0
- package/dist/{chunk-NERO7F3J.js → chunk-M4H2RYP4.js} +2 -2
- package/dist/{chunk-7T5Y4H2J.js → chunk-OQNJIIR2.js} +3 -3
- package/dist/{chunk-7T5Y4H2J.js.map → chunk-OQNJIIR2.js.map} +1 -1
- package/dist/chunk-OQQTV3OF.js +12 -0
- package/dist/chunk-OQQTV3OF.js.map +1 -0
- package/dist/{chunk-EUJT7JT3.js → chunk-SBFMNAJG.js} +3 -3
- package/dist/{chunk-3JH3HUHX.js → chunk-UNVZUWOY.js} +2 -2
- package/dist/{chunk-UPWNWSK3.js → chunk-Z4WM7MKP.js} +297 -297
- package/dist/chunk-Z4WM7MKP.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{doctor-ABJSFSMM.js → doctor-GP2KVKWE.js} +2 -2
- package/dist/{grants-TWDH3Z4K.js → grants-U2734ZHZ.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{program-VCNJHSWN.js → program-L3BX5FJ3.js} +284 -282
- package/dist/program-L3BX5FJ3.js.map +1 -0
- package/dist/{registry-QTFATS6J.js → registry-D727ZQUP.js} +2 -2
- package/dist/{tool-Z2YLBCN7.js → tool-L3CQUOAZ.js} +2 -2
- package/dist/{tool-2VRNH43W.js → tool-ZCSGJ2ZF.js} +9 -9
- package/dist/tool-ZCSGJ2ZF.js.map +1 -0
- package/dist/{workspace-setup-PIPGUMLG.js → workspace-setup-VGXHYCD5.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-MNG2AMKZ.js +0 -3
- package/dist/chunk-UPWNWSK3.js.map +0 -1
- package/dist/chunk-WAVO3U3I.js.map +0 -1
- package/dist/chunk-XL7UWG36.js +0 -12
- package/dist/chunk-XL7UWG36.js.map +0 -1
- package/dist/program-VCNJHSWN.js.map +0 -1
- package/dist/tool-2VRNH43W.js.map +0 -1
- /package/dist/{agent-2GK32HCI.js.map → agent-KUCECPSZ.js.map} +0 -0
- /package/dist/{chunk-ZMGDHLZD.js.map → chunk-4ZD2C76P.js.map} +0 -0
- /package/dist/{chunk-GJOKXP5D.js.map → chunk-6UTOBSEA.js.map} +0 -0
- /package/dist/{chunk-2CO3NK6Z.js.map → chunk-C3O2ER6D.js.map} +0 -0
- /package/dist/{chunk-NERO7F3J.js.map → chunk-M4H2RYP4.js.map} +0 -0
- /package/dist/{chunk-EUJT7JT3.js.map → chunk-SBFMNAJG.js.map} +0 -0
- /package/dist/{chunk-3JH3HUHX.js.map → chunk-UNVZUWOY.js.map} +0 -0
- /package/dist/{doctor-ABJSFSMM.js.map → doctor-GP2KVKWE.js.map} +0 -0
- /package/dist/{grants-TWDH3Z4K.js.map → grants-U2734ZHZ.js.map} +0 -0
- /package/dist/{registry-QTFATS6J.js.map → registry-D727ZQUP.js.map} +0 -0
- /package/dist/{tool-Z2YLBCN7.js.map → tool-L3CQUOAZ.js.map} +0 -0
- /package/dist/{workspace-setup-PIPGUMLG.js.map → workspace-setup-VGXHYCD5.js.map} +0 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var i={count:3,label:120,draft:2e3,say:160,context:600,text:4e3},g="{choice}";function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function l(e){return typeof e=="string"?e.replace(/\r\n?/g,`
|
|
2
|
+
`).trim():""}function p(e){let n={};if(e.choices!==void 0&&e.choices!==null){if(!Array.isArray(e.choices))return{ok:!1,error:"choices must be a list of short labels"};let t=e.choices.map(a).filter(Boolean);if(t.length!==e.choices.length)return{ok:!1,error:"every choice must be a non-empty label"};if(t.length>i.count)return{ok:!1,error:`at most ${i.count} choices`};if(t.some(c=>c.length>i.label))return{ok:!1,error:`a choice is longer than ${i.label} characters`};if(new Set(t).size!==t.length)return{ok:!1,error:"choices must be different from each other"};t.length&&(n.choices=t)}let r=l(e.draft);if(r){if(r.length>i.draft)return{ok:!1,error:`draft is longer than ${i.draft} characters`};n.draft=r}let o=a(e.say);if(o){if(o.length>i.say)return{ok:!1,error:`say is longer than ${i.say} characters`};n.say=o}let s=l(e.context);if(s){if(s.length>i.context)return{ok:!1,error:`context is longer than ${i.context} characters`};n.context=s}return{ok:!0,value:n}}function d(e,n){return e?n?e.split(g).join(n):e:""}function x(e){let n=(e.recommend??"").trim(),r=n.toLowerCase(),o=e.choices??[],s=-1;if(o.forEach((c,h)=>{!r.startsWith(c.toLowerCase())||!/^\s*($|[:,.;–—-](\s|$))/.test(n.slice(c.length))||(s<0||c.length>o[s].length)&&(s=h)}),s<0)return{index:s,why:n};let t=n.slice(o[s].length).replace(/^[\s:,.;–—-]+/,"");return{index:s,why:t.slice(0,1).toUpperCase()+t.slice(1)}}function y(e,n,r){if(n==="no")return{ok:!0};let o,s=!1,t=e.choices??[];if(r.choice!==void 0&&r.choice!==""){if(!t.length)return{ok:!1,error:"this card has no choices"};let h=typeof r.choice=="number"?r.choice:Number(r.choice);if(Number.isInteger(h)&&h>=1&&h<=t.length)o=t[h-1];else if(t.includes(a(r.choice)))o=a(r.choice);else return{ok:!1,error:`choice must be 1-${t.length} or one of the labels`}}else if(t.length){let h=x({recommend:e.recommend,choices:t});if(h.index<0)return{ok:!1,error:`this card offers choices and suggests none: pick one of ${t.map((f,u)=>`${u+1}. ${f}`).join(", ")} (\`agentx approvals approve <key> --choice <n>\`)`};o=t[h.index],s=!0}let c=l(r.text);return!c&&e.draft&&(c=d(e.draft,o)),c.length>i.text?{ok:!1,error:`text is longer than ${i.text} characters`}:{ok:!0,...o?{choice:o}:{},...c?{text:c}:{},...s?{suggested:!0}:{}}}var m=/^(don['’]?t|do not|no|not|never|cancel|skip|decline|reject)\b/i;function C(e){return!!e&&m.test(e.trim())}function b(e){let n=[];return e.choice&&n.push(`Chosen: ${e.choice}${e.choice_suggested?" (a plain yes, taken as the suggested option)":""}`),e.text&&n.push("Approved text (send exactly this, the operator may have edited it):",e.text),n}export{i as a,g as b,p as c,d,x as e,y as f,C as g,b as h};
|
|
3
|
+
//# sourceMappingURL=chunk-4NZ4T3TQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/approvals/choices.ts"],"sourcesContent":["// --- Ready-made answers on a decision card ---\n//\n// A card can offer a few choices (say, three free meeting slots), a\n// suggested message the operator may edit before it goes, and a short\n// context (what the other person said) shown above the question. The operator's\n// pick and the final text are stored on the card and handed to the agent\n// that raised it; the agent does the sending. Nothing here sends anything.\n//\n// All optional: a card without them is the plain yes/no card it always was.\n\nexport const CHOICE_LIMITS = {\n /** Most options a card may offer. More is a form, not a choice; the\n * screen gate (#394) allows 3. */\n count: 3,\n label: 120,\n draft: 2000,\n say: 160,\n context: 600,\n /** The operator's final text, after editing. */\n text: 4000,\n} as const\n\n/** The spot in `draft` that takes the picked label. */\nexport const CHOICE_PLACEHOLDER = \"{choice}\"\n\nexport interface CardChoices {\n choices?: string[]\n draft?: string\n say?: string\n /** A few lines of background, shown above the question. */\n context?: string\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/** A draft keeps its line breaks: it is a message, not a label. */\nfunction block(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\r\\n?/g, \"\\n\").trim() : \"\"\n}\n\n/** Validate what an agent sent. Empty input gives an empty object. */\nexport function buildChoices(input: { choices?: unknown; draft?: unknown; say?: unknown; context?: unknown }): { ok: true; value: CardChoices } | { ok: false; error: string } {\n const value: CardChoices = {}\n if (input.choices !== undefined && input.choices !== null) {\n if (!Array.isArray(input.choices)) return { ok: false, error: \"choices must be a list of short labels\" }\n const labels = input.choices.map(oneLine).filter(Boolean)\n if (labels.length !== input.choices.length) return { ok: false, error: \"every choice must be a non-empty label\" }\n if (labels.length > CHOICE_LIMITS.count) return { ok: false, error: `at most ${CHOICE_LIMITS.count} choices` }\n if (labels.some((l) => l.length > CHOICE_LIMITS.label)) return { ok: false, error: `a choice is longer than ${CHOICE_LIMITS.label} characters` }\n if (new Set(labels).size !== labels.length) return { ok: false, error: \"choices must be different from each other\" }\n if (labels.length) value.choices = labels\n }\n const draft = block(input.draft)\n if (draft) {\n if (draft.length > CHOICE_LIMITS.draft) return { ok: false, error: `draft is longer than ${CHOICE_LIMITS.draft} characters` }\n value.draft = draft\n }\n const say = oneLine(input.say)\n if (say) {\n if (say.length > CHOICE_LIMITS.say) return { ok: false, error: `say is longer than ${CHOICE_LIMITS.say} characters` }\n value.say = say\n }\n const context = block(input.context)\n if (context) {\n if (context.length > CHOICE_LIMITS.context) return { ok: false, error: `context is longer than ${CHOICE_LIMITS.context} characters` }\n value.context = context\n }\n return { ok: true, value }\n}\n\n/** The suggested message for a pick, with `{choice}` filled in. */\nexport function draftFor(draft: string | undefined, choice: string | undefined): string {\n if (!draft) return \"\"\n return choice ? draft.split(CHOICE_PLACEHOLDER).join(choice) : draft\n}\n\n/**\n * The option the recommendation names, and the reason that is left. The\n * card stores its advice as one line (\"Thursday 10:00: your calendar is\n * free\"); when that line starts with an option, the card marks that option\n * and starts with it picked. The option must be the whole start: the line\n * ends there, or a separator and a space follow (\"No: ...\" names No; \"Not\n * yet\", \"No strong view\" and \"No-one\" name nothing, and \"Thu 10\" is not\n * named by \"Thu 10:30\"). An option only mentioned further on is\n * not the advice (\"do not approve\"). No match: nothing is picked, the line\n * shows whole.\n */\nexport function recommended(card: { recommend?: string; choices?: string[] }): { index: number; why: string } {\n const text = (card.recommend ?? \"\").trim()\n const low = text.toLowerCase()\n const choices = card.choices ?? []\n let index = -1\n choices.forEach((c, i) => {\n if (!low.startsWith(c.toLowerCase()) || !/^\\s*($|[:,.;–—-](\\s|$))/.test(text.slice(c.length))) return\n if (index < 0 || c.length > choices[index].length) index = i\n })\n if (index < 0) return { index, why: text }\n const why = text.slice(choices[index].length).replace(/^[\\s:,.;–—-]+/, \"\")\n return { index, why: why.slice(0, 1).toUpperCase() + why.slice(1) }\n}\n\n/**\n * Check the operator's answer against the card. A yes on a card with\n * choices must say which one: approving \"the meeting\" without a date would\n * leave the agent to guess, which is the thing the card exists to avoid.\n * A plain yes (a Yes/No surface, or the CLI without --choice) is a yes to\n * the card's advice, so it takes the option the recommendation names\n * (#1064). With no such option it is refused, naming the options.\n */\nexport function resolveAnswer(\n card: CardChoices & { recommend?: string },\n verdict: \"yes\" | \"no\",\n answer: { choice?: string | number; text?: string },\n): { ok: true; choice?: string; text?: string; suggested?: true } | { ok: false; error: string } {\n if (verdict === \"no\") return { ok: true }\n let choice: string | undefined\n let suggested = false\n const list = card.choices ?? []\n if (answer.choice !== undefined && answer.choice !== \"\") {\n if (!list.length) return { ok: false, error: \"this card has no choices\" }\n const n = typeof answer.choice === \"number\" ? answer.choice : Number(answer.choice)\n if (Number.isInteger(n) && n >= 1 && n <= list.length) choice = list[n - 1]\n else if (list.includes(oneLine(answer.choice))) choice = oneLine(answer.choice)\n else return { ok: false, error: `choice must be 1-${list.length} or one of the labels` }\n } else if (list.length) {\n const rec = recommended({ recommend: card.recommend, choices: list })\n if (rec.index < 0) {\n const options = list.map((l, i) => `${i + 1}. ${l}`).join(\", \")\n return { ok: false, error: `this card offers choices and suggests none: pick one of ${options} (\\`agentx approvals approve <key> --choice <n>\\`)` }\n }\n choice = list[rec.index]\n suggested = true\n }\n let text = block(answer.text)\n if (!text && card.draft) text = draftFor(card.draft, choice)\n if (text.length > CHOICE_LIMITS.text) return { ok: false, error: `text is longer than ${CHOICE_LIMITS.text} characters` }\n return { ok: true, ...(choice ? { choice } : {}), ...(text ? { text } : {}), ...(suggested ? { suggested: true as const } : {}) }\n}\n\n/** Lines for the agent's result message. Empty for a plain card. */\nexport function answerLines(card: { choice?: string; text?: string; choice_suggested?: boolean }): string[] {\n const lines: string[] = []\n if (card.choice) lines.push(`Chosen: ${card.choice}${card.choice_suggested ? \" (a plain yes, taken as the suggested option)\" : \"\"}`)\n if (card.text) lines.push(\"Approved text (send exactly this, the operator may have edited it):\", card.text)\n return lines\n}\n"],"mappings":"AAUO,IAAMA,EAAgB,CAG3B,MAAO,EACP,MAAO,IACP,MAAO,IACP,IAAK,IACL,QAAS,IAET,KAAM,GACR,EAGaC,EAAqB,WAUlC,SAASC,EAAQC,EAAoB,CACnC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAI,EACjE,CAGA,SAASC,EAAMD,EAAoB,CACjC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,SAAU;AAAA,CAAI,EAAE,KAAK,EAAI,EACpE,CAGO,SAASE,EAAaC,EAAkJ,CAC7K,IAAMC,EAAqB,CAAC,EAC5B,GAAID,EAAM,UAAY,QAAaA,EAAM,UAAY,KAAM,CACzD,GAAI,CAAC,MAAM,QAAQA,EAAM,OAAO,EAAG,MAAO,CAAE,GAAI,GAAO,MAAO,wCAAyC,EACvG,IAAME,EAASF,EAAM,QAAQ,IAAIJ,CAAO,EAAE,OAAO,OAAO,EACxD,GAAIM,EAAO,SAAWF,EAAM,QAAQ,OAAQ,MAAO,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A,EAAI,MAAMZ,GAAG,EAAE,KAAK,IAAI,qDACoF,EAEpJK,EAASa,EAAKE,EAAI,KAAK,EACvBH,EAAY,GAEd,IAAIT,EAAOb,EAAMqB,EAAO,IAAI,EAE5B,MADI,CAACR,GAAQD,EAAK,QAAOC,EAAOJ,EAASG,EAAK,MAAOF,CAAM,GACvDG,EAAK,OAASjB,EAAc,KAAa,CAAE,GAAI,GAAO,MAAO,uBAAuBA,EAAc,iBAAkB,EACjH,CAAE,GAAI,GAAM,GAAIc,EAAS,CAAE,OAAAA,CAAO,EAAI,CAAC,EAAI,GAAIG,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EAAI,GAAIS,EAAY,CAAE,UAAW,EAAc,EAAI,CAAC,CAAG,CAClI,CAGO,SAASI,EAAYd,EAAgF,CAC1G,IAAMe,EAAkB,CAAC,EACzB,OAAIf,EAAK,QAAQe,EAAM,KAAK,WAAWf,EAAK,SAASA,EAAK,iBAAmB,gDAAkD,IAAI,EAC/HA,EAAK,MAAMe,EAAM,KAAK,sEAAuEf,EAAK,IAAI,EACnGe,CACT","names":["CHOICE_LIMITS","CHOICE_PLACEHOLDER","oneLine","v","block","buildChoices","input","value","labels","l","draft","say","context","draftFor","choice","recommended","card","text","low","choices","index","i","why","resolveAnswer","verdict","answer","suggested","list","n","rec","answerLines","lines"]}
|
|
1
|
+
{"version":3,"sources":["../src/approvals/choices.ts"],"sourcesContent":["// --- Ready-made answers on a decision card ---\n//\n// A card can offer a few choices (say, three free meeting slots), a\n// suggested message the operator may edit before it goes, and a short\n// context (what the other person said) shown above the question. The operator's\n// pick and the final text are stored on the card and handed to the agent\n// that raised it; the agent does the sending. Nothing here sends anything.\n//\n// All optional: a card without them is the plain yes/no card it always was.\n\nexport const CHOICE_LIMITS = {\n /** Most options a card may offer. More is a form, not a choice; the\n * screen gate (#394) allows 3. */\n count: 3,\n label: 120,\n draft: 2000,\n say: 160,\n context: 600,\n /** The operator's final text, after editing. */\n text: 4000,\n} as const\n\n/** The spot in `draft` that takes the picked label. */\nexport const CHOICE_PLACEHOLDER = \"{choice}\"\n\nexport interface CardChoices {\n choices?: string[]\n draft?: string\n say?: string\n /** A few lines of background, shown above the question. */\n context?: string\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/** A draft keeps its line breaks: it is a message, not a label. */\nfunction block(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\r\\n?/g, \"\\n\").trim() : \"\"\n}\n\n/** Validate what an agent sent. Empty input gives an empty object. */\nexport function buildChoices(input: { choices?: unknown; draft?: unknown; say?: unknown; context?: unknown }): { ok: true; value: CardChoices } | { ok: false; error: string } {\n const value: CardChoices = {}\n if (input.choices !== undefined && input.choices !== null) {\n if (!Array.isArray(input.choices)) return { ok: false, error: \"choices must be a list of short labels\" }\n const labels = input.choices.map(oneLine).filter(Boolean)\n if (labels.length !== input.choices.length) return { ok: false, error: \"every choice must be a non-empty label\" }\n if (labels.length > CHOICE_LIMITS.count) return { ok: false, error: `at most ${CHOICE_LIMITS.count} choices` }\n if (labels.some((l) => l.length > CHOICE_LIMITS.label)) return { ok: false, error: `a choice is longer than ${CHOICE_LIMITS.label} characters` }\n if (new Set(labels).size !== labels.length) return { ok: false, error: \"choices must be different from each other\" }\n if (labels.length) value.choices = labels\n }\n const draft = block(input.draft)\n if (draft) {\n if (draft.length > CHOICE_LIMITS.draft) return { ok: false, error: `draft is longer than ${CHOICE_LIMITS.draft} characters` }\n value.draft = draft\n }\n const say = oneLine(input.say)\n if (say) {\n if (say.length > CHOICE_LIMITS.say) return { ok: false, error: `say is longer than ${CHOICE_LIMITS.say} characters` }\n value.say = say\n }\n const context = block(input.context)\n if (context) {\n if (context.length > CHOICE_LIMITS.context) return { ok: false, error: `context is longer than ${CHOICE_LIMITS.context} characters` }\n value.context = context\n }\n return { ok: true, value }\n}\n\n/** The suggested message for a pick, with `{choice}` filled in. */\nexport function draftFor(draft: string | undefined, choice: string | undefined): string {\n if (!draft) return \"\"\n return choice ? draft.split(CHOICE_PLACEHOLDER).join(choice) : draft\n}\n\n/**\n * The option the recommendation names, and the reason that is left. The\n * card stores its advice as one line (\"Thursday 10:00: your calendar is\n * free\"); when that line starts with an option, the card marks that option\n * and starts with it picked. The option must be the whole start: the line\n * ends there, or a separator and a space follow (\"No: ...\" names No; \"Not\n * yet\", \"No strong view\" and \"No-one\" name nothing, and \"Thu 10\" is not\n * named by \"Thu 10:30\"). An option only mentioned further on is\n * not the advice (\"do not approve\"). No match: nothing is picked, the line\n * shows whole.\n */\nexport function recommended(card: { recommend?: string; choices?: string[] }): { index: number; why: string } {\n const text = (card.recommend ?? \"\").trim()\n const low = text.toLowerCase()\n const choices = card.choices ?? []\n let index = -1\n choices.forEach((c, i) => {\n if (!low.startsWith(c.toLowerCase()) || !/^\\s*($|[:,.;–—-](\\s|$))/.test(text.slice(c.length))) return\n if (index < 0 || c.length > choices[index].length) index = i\n })\n if (index < 0) return { index, why: text }\n const why = text.slice(choices[index].length).replace(/^[\\s:,.;–—-]+/, \"\")\n return { index, why: why.slice(0, 1).toUpperCase() + why.slice(1) }\n}\n\n/**\n * Check the operator's answer against the card. A yes on a card with\n * choices must say which one: approving \"the meeting\" without a date would\n * leave the agent to guess, which is the thing the card exists to avoid.\n * A plain yes (a Yes/No surface, or the CLI without --choice) is a yes to\n * the card's advice, so it takes the option the recommendation names\n * (#1064). With no such option it is refused, naming the options.\n */\nexport function resolveAnswer(\n card: CardChoices & { recommend?: string },\n verdict: \"yes\" | \"no\",\n answer: { choice?: string | number; text?: string },\n): { ok: true; choice?: string; text?: string; suggested?: true } | { ok: false; error: string } {\n if (verdict === \"no\") return { ok: true }\n let choice: string | undefined\n let suggested = false\n const list = card.choices ?? []\n if (answer.choice !== undefined && answer.choice !== \"\") {\n if (!list.length) return { ok: false, error: \"this card has no choices\" }\n const n = typeof answer.choice === \"number\" ? answer.choice : Number(answer.choice)\n if (Number.isInteger(n) && n >= 1 && n <= list.length) choice = list[n - 1]\n else if (list.includes(oneLine(answer.choice))) choice = oneLine(answer.choice)\n else return { ok: false, error: `choice must be 1-${list.length} or one of the labels` }\n } else if (list.length) {\n const rec = recommended({ recommend: card.recommend, choices: list })\n if (rec.index < 0) {\n const options = list.map((l, i) => `${i + 1}. ${l}`).join(\", \")\n return { ok: false, error: `this card offers choices and suggests none: pick one of ${options} (\\`agentx approvals approve <key> --choice <n>\\`)` }\n }\n choice = list[rec.index]\n suggested = true\n }\n let text = block(answer.text)\n if (!text && card.draft) text = draftFor(card.draft, choice)\n if (text.length > CHOICE_LIMITS.text) return { ok: false, error: `text is longer than ${CHOICE_LIMITS.text} characters` }\n return { ok: true, ...(choice ? { choice } : {}), ...(text ? { text } : {}), ...(suggested ? { suggested: true as const } : {}) }\n}\n\n/**\n * An option that means no: \"Don't send\", \"Do not book\", \"No\", \"Not now\",\n * \"Skip\", \"Cancel\". The card's Send button returns yes with whatever\n * option is picked, so a yes with one of these is recorded as a no and\n * never reaches the agent as \"send exactly this\" (#1788). It errs toward\n * no: a label like \"No changes, merge\" also counts as no.\n */\nconst NO_CHOICE = /^(don['’]?t|do not|no|not|never|cancel|skip|decline|reject)\\b/i\n\nexport function isNoChoice(label: string | undefined): boolean {\n return !!label && NO_CHOICE.test(label.trim())\n}\n\n/** Lines for the agent's result message. Empty for a plain card. */\nexport function answerLines(card: { choice?: string; text?: string; choice_suggested?: boolean }): string[] {\n const lines: string[] = []\n if (card.choice) lines.push(`Chosen: ${card.choice}${card.choice_suggested ? \" (a plain yes, taken as the suggested option)\" : \"\"}`)\n if (card.text) lines.push(\"Approved text (send exactly this, the operator may have edited it):\", card.text)\n return lines\n}\n"],"mappings":"AAUO,IAAMA,EAAgB,CAG3B,MAAO,EACP,MAAO,IACP,MAAO,IACP,IAAK,IACL,QAAS,IAET,KAAM,GACR,EAGaC,EAAqB,WAUlC,SAASC,EAAQC,EAAoB,CACnC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,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AuElB,EAAK,IAAI,EACnGkB,CACT","names":["CHOICE_LIMITS","CHOICE_PLACEHOLDER","oneLine","v","block","buildChoices","input","value","labels","l","draft","say","context","draftFor","choice","recommended","card","text","low","choices","index","i","why","resolveAnswer","verdict","answer","suggested","list","n","rec","NO_CHOICE","isNoChoice","label","answerLines","lines"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as q}from"./chunk-WMZ4TGMR.js";import{a as D,b as F}from"./chunk-2YDG5CSS.js";import{A as S,G as H,I as b,K as _,N as M,q as A,x as W}from"./chunk-
|
|
1
|
+
import{a as q}from"./chunk-WMZ4TGMR.js";import{a as D,b as F}from"./chunk-2YDG5CSS.js";import{A as S,G as H,I as b,K as _,N as M,q as A,x as W}from"./chunk-OQNJIIR2.js";import{c as P}from"./chunk-LY4G7PCW.js";import{a as L}from"./chunk-OSH2PEBH.js";import{Tb as T,bc as K,xb as E}from"./chunk-KAM4ZWRE.js";K();import{Command as V}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as z,constants as G,existsSync as k,readFileSync as $,readdirSync as N,statSync as Q}from"fs";import{join as B,resolve as w}from"path";import{homedir as Y}from"os";import{createRequire as ee}from"module";var C='run agentx notify "Hello" --title "Test"';function U(t,n){return t==="windows"?{fallback:"Windows PowerShell, and show its name",settings:"Open Settings \u203A System \u203A Notifications, turn notifications on, then turn on AgentX Helper and its banners.",missingFix:`${A(n)} Then ${C}.`,updateFix:`${A(n).replace(/^Put /,"Put a newer ")}`,osName:"Windows"}:{fallback:"Script Editor and show its icon",settings:"Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.",missingFix:`Run agentx desktop install, then ${C} and click Allow.`,updateFix:"Run agentx desktop install to update it.",osName:"macOS"}}async function X(t={}){let n=t.platform??process.platform,e=t.helper===void 0?H():t.helper,i=b({},{platform:n,io:{capture:t.run,helper:e}}),s=i.banner;if(!s)return{state:"unsupported",message:"Desktop banners are only shown on macOS and Windows."};let o=U(i.os,n),a=await s.status();return a==="missing"?{state:"missing",message:`AgentX Helper is not installed, so banners come from ${o.fallback}.`,fix:o.missingFix}:a==="outdated"?{state:"outdated",path:e,message:"AgentX Helper is too old to report whether it may notify.",fix:o.updateFix}:a==="not-asked"?{state:"not-asked",path:e,message:`${o.osName} has not asked yet whether AgentX Helper may notify; banners come from ${o.fallback} until it does.`,fix:`${C[0].toUpperCase()}${C.slice(1)} and click Allow when ${o.osName} asks.`}:a==="not-allowed"?{state:"not-allowed",path:e,message:`${o.osName} does not allow AgentX Helper to notify, so banners come from ${o.fallback}.`,fix:o.settings}:a==="hidden"?{state:"hidden",path:e,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:o.settings}:{state:"ready",path:e,message:"AgentX Helper posts banners with the AgentX icon."}}async function te(t={}){let n=[];await re(n),ae(n);let e=le(n);return e&&ce(n,e),e&&fe(n,e),e&&he(n,e),e&&me(n,e),e&&ue(n,e),e&&n.push(...ge(e)),e&&we(n,e),e&&await ne(n,e),e&&oe(n,e),e&&await ie(n,e),e&&se(n,e),t.running!==!1&&e&&await ve(n,e),{checks:n,summary:J(n)}}var qe=new V().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 te({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ke(n),process.exit(e.errors>0?1:0)});async function ne(t,n,e=X){if(!_(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})}async function ie(t,n,e){let i;try{i=await(e??b(n)).describe()}catch(o){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:o?.message??String(o)});return}let s=["tasks","notes","banner","sound","focus"].filter(o=>i[o]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${s.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function se(t,n,e=process.cwd(),i=b(n)){let s=n.native?.mirror;if(!s?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let o=M(e),a=Object.values(o.items),l=a.filter(g=>g.state==="open").length,p=a.filter(g=>g.state==="failed").length;t.push({severity:o.lastError||p?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${s.list}"${p?`, ${p} could not be added`:""}`,detail:o.lastError?`Last error ${o.lastError.at}: ${o.lastError.message}`:void 0,fix:o.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function oe(t,n,e=process.platform,i=s=>{try{return z(s,G.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 o=s.command||"remindctl",a=o.includes("/")?i(o)?o:null:S(o,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:`${o} 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 re(t){let n=L(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 m(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=m("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 o=e("codex");if(o){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:o})}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=m("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{ee(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 ae(t){if(process.platform!=="darwin")return;let n=B(Y(),"Library/LaunchAgents"),e=[];try{e=N(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return z(s,G.X_OK),!0}catch{return!1}};for(let s of e){let o=W($(B(n,s),"utf-8")),a=S("ffmpeg",o,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 ${o}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function le(t){let n=w(process.cwd(),"agentx.json");if(!k(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($(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{T(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 m(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 m(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 o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function ce(t,n){let e=new Set;if(j(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=R(),s=[],o=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?s.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&o.push(a)}s.length===0&&o.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(s.length>0&&t.push({severity:"fail",group:"Secrets",title:`${s.length} env var(s) referenced in agentx.json but missing`,detail:s.join(", "),fix:`Add to .env \u2014 e.g. ${s[0]}=<value>`}),o.length>0&&t.push({severity:"warn",group:"Secrets",title:`${o.length} env var(s) set but empty`,detail:o.join(", ")}))}function R(){let t=w(process.cwd(),".env"),n={};if(k(t))for(let e of $(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function de(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",s=[];for(let o of t){let a=(o.token??"").trim();a?n&&a===n&&s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&s.length===0&&s.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),s}function ue(t,n){t.push(...pe(n))}function pe(t,n=process.env,e=R()){let i=a=>(n[a]||e[a]||"").trim(),s=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,p)=>i(p)):void 0,o=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:s(a.token)}));return de(o,i("MESH_TOKEN")||void 0)}function ge(t,n=process.env,e=R()){let i=[],s=0;for(let[o,a]of Object.entries(t.agents||{}))for(let[l,p]of Object.entries(a?.mcp||{})){let g=P(p??{});if(g.length===0)continue;s++;let y=g.filter(r=>!(n[r]||e[r]||"").trim());y.length>0&&i.push({severity:"fail",group:"Secrets",title:`MCP server "${l}" of ${o}: header variable(s) not set`,detail:y.join(", "),fix:`Add to .env \u2014 e.g. ${y[0]}=<value>, then restart the daemon`})}return s>0&&i.length===0&&i.push({severity:"ok",group:"Secrets",title:`${s} MCP server(s) with header variables, all set`}),i}function j(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)j(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))j(e,n)}function fe(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let o=s.workspace.startsWith("/")?s.workspace:w(process.cwd(),s.workspace);try{Q(o).isDirectory()||e.push(`${i}: ${o} (exists but not a directory)`)}catch{e.push(`${i}: ${o}`)}}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 he(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let a=o.workspace.startsWith("/")?o.workspace:w(process.cwd(),o.workspace);for(let l of["settings.json","settings.local.json"]){let p=w(a,".claude",l);if(!k(p))continue;let g;try{g=JSON.parse($(p,"utf-8"))}catch(u){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${u.message}`});continue}let y=g.env||{};for(let[u,h]of Object.entries(y)){if(typeof h!="string")continue;let c=h.match(e);c&&i.push({severity:"fail",agent:s,msg:`${l} env.${u} contains unexpanded ${[...new Set(c)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=y.PATH;if(typeof r=="string"){let u=r.split(":").filter(Boolean);u.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),u.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let u=d.allow,h=d.deny;Array.isArray(u)&&u.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${h.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 me(t,n){let e=n.webhooks??[],i=[],s=w(process.cwd(),n.workflows?.dir||".agentx/workflows"),o=new Set;try{if(k(s))for(let r of N(s))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&o.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.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 r of e)if(!(!r.enabled||!r.triggers)){for(let[d,u]of Object.entries(r.triggers))o.size>0&&!o.has(u)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${u}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&o.size>0&&!o.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(k(s)){for(let r of N(s))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse($(w(s,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" 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(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let p=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,u=p.get(d);u?i.push({severity:"warn",title:`webhook entries "${u}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):p.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.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[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let y=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",...E,...Object.keys(D)]);for(let[r,d]of Object.entries(n.agents??{})){let u=d.integrations??[];if(!u.length)continue;let h=new Set;for(let c of u){let O=`${c.kind}::${c.label}`;h.has(O)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${c.kind}, ${c.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(O),y.has(c.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${c.kind}" on integration "${c.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let Z=c.credentials||{};for(let[x,v]of Object.entries(Z))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${c.kind}/${c.label}].${x} -> $${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.`});let I=c.enabled===!1?null:F(c.kind);if(I){let x=q(r,c,I);for(let v of x.problems)/env var .* is unset/.test(v)||i.push({severity:"warn",title:`agents.${r}.integrations[${c.kind}/${c.label}]: ${v}`,fix:x.connected?`Run agentx agent integrations status ${r} for details.`:`Run agentx agent integrations connect ${r} ${c.kind}${c.label!==c.kind?` --label "${c.label}"`:""}.`})}}}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 r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function ye(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 ve(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,o=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(o),!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 p=ye(l.voice);p&&t.push(p)}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 we(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=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=m("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,o]of e){if(!o.workspace||!k(o.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${o.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=w(o.workspace,".codegraph","codegraph.db");k(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 ${o.workspace}\` to build it now.`})}}function J(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 ke(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 o of s){let a=o.severity==="ok"?f.green("\u2713"):o.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${o.title}`),o.detail&&console.log(f.dim(" "+o.detail.replace(/\n/g,`
|
|
6
6
|
`))),o.fix&&console.log(f.dim(" \u2192 "+o.fix))}console.log()}let e=J(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{X as a,te as b,qe as c,ne as d,ie as e,se as f,oe as g,de as h,pe as i,ge as j,ye as k};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-4ZD2C76P.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as x,t as A}from"./chunk-
|
|
1
|
+
import{r as x,t as A}from"./chunk-OQQTV3OF.js";import{a as w,e as D}from"./chunk-VQRY4IDI.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-6UTOBSEA.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{
|
|
1
|
+
import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Fb as Ge,Ra as Ke,Sa as Ye,Ta as Je,Va as Xe,c as Le,pa as _,ua as qe}from"./chunk-2KNI7ZRN.js";import{a as V}from"./chunk-IMLAPB7G.js";import{k as Be}from"./chunk-PSYHAO57.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-ACPGDZOV.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{ga as G}from"./chunk-FR4DTMCA.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-N476XZD3.js";import{r as ge,t as Oe}from"./chunk-OQQTV3OF.js";import{a as He}from"./chunk-RMXG5GNW.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Ia as et,Pb as pe,Sb as q,Tb as Re,bc as xe,g as le,j as F,lb as Ee,p as Za,sb as at,wa as ce,xa as Pe}from"./chunk-KAM4ZWRE.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
|
|
2
2
|
/* --- Brand (agentina) --------------------------------------------- */
|
|
3
3
|
--ax-blue: #2979FF;
|
|
4
4
|
--ax-blue-d: #1B5FD9;
|
|
@@ -2903,4 +2903,4 @@ tr:hover td { background: var(--bg-hover); }
|
|
|
2903
2903
|
${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Ne/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${We(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
|
|
2904
2904
|
`)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=Oe(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ge(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ge(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
|
|
2905
2905
|
`)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:Le(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
|
|
2906
|
-
//# sourceMappingURL=chunk-
|
|
2906
|
+
//# sourceMappingURL=chunk-C3O2ER6D.js.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{Ea as p,Ia as g}from"./chunk-KAM4ZWRE.js";import{q as d,r as N}from"./chunk-N47Y5ADQ.js";g();N();var m=["done","skipped"];function I(t,e=Date.now()){return t.state==="active"&&typeof t.waitUntil=="number"&&t.waitUntil>e?` waits until ${new Date(t.waitUntil).toISOString().slice(0,16).replace("T"," ")}Z`:""}var A=1e3;function h(t){t.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS request_plans (
|
|
3
|
+
request_id TEXT PRIMARY KEY,
|
|
4
|
+
created_by TEXT NOT NULL,
|
|
5
|
+
created_at INTEGER NOT NULL,
|
|
6
|
+
state TEXT NOT NULL,
|
|
7
|
+
finished_at INTEGER,
|
|
8
|
+
notified_at INTEGER,
|
|
9
|
+
FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
|
|
10
|
+
);
|
|
11
|
+
CREATE INDEX IF NOT EXISTS idx_request_plans_state ON request_plans(state);
|
|
12
|
+
CREATE TABLE IF NOT EXISTS request_plan_steps (
|
|
13
|
+
request_id TEXT NOT NULL,
|
|
14
|
+
idx INTEGER NOT NULL,
|
|
15
|
+
name TEXT NOT NULL,
|
|
16
|
+
kind TEXT NOT NULL,
|
|
17
|
+
agent_id TEXT NOT NULL,
|
|
18
|
+
done_when TEXT NOT NULL,
|
|
19
|
+
state TEXT NOT NULL,
|
|
20
|
+
needs_approval INTEGER NOT NULL DEFAULT 0,
|
|
21
|
+
approval TEXT NOT NULL DEFAULT 'none',
|
|
22
|
+
card_id TEXT,
|
|
23
|
+
message TEXT,
|
|
24
|
+
to_channel TEXT,
|
|
25
|
+
to_chat TEXT,
|
|
26
|
+
to_account TEXT,
|
|
27
|
+
check_url TEXT,
|
|
28
|
+
check_contains TEXT,
|
|
29
|
+
stall_minutes REAL,
|
|
30
|
+
evidence TEXT,
|
|
31
|
+
note TEXT,
|
|
32
|
+
dispatched_at INTEGER,
|
|
33
|
+
updated_at INTEGER NOT NULL,
|
|
34
|
+
nudges INTEGER NOT NULL DEFAULT 0,
|
|
35
|
+
last_nudge_at INTEGER,
|
|
36
|
+
notified_at INTEGER,
|
|
37
|
+
PRIMARY KEY (request_id, idx),
|
|
38
|
+
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
39
|
+
);
|
|
40
|
+
CREATE TABLE IF NOT EXISTS request_plan_events (
|
|
41
|
+
request_id TEXT NOT NULL,
|
|
42
|
+
step INTEGER,
|
|
43
|
+
at INTEGER NOT NULL,
|
|
44
|
+
kind TEXT NOT NULL,
|
|
45
|
+
detail TEXT NOT NULL,
|
|
46
|
+
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
47
|
+
);
|
|
48
|
+
CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
|
|
49
|
+
CREATE TABLE IF NOT EXISTS request_plan_continues (
|
|
50
|
+
goal_key TEXT NOT NULL,
|
|
51
|
+
day TEXT NOT NULL,
|
|
52
|
+
turns INTEGER NOT NULL DEFAULT 0,
|
|
53
|
+
cost_usd REAL NOT NULL DEFAULT 0,
|
|
54
|
+
told_at INTEGER,
|
|
55
|
+
PRIMARY KEY (goal_key, day)
|
|
56
|
+
);
|
|
57
|
+
`),d(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]]),d(t,"request_plan_steps",[["wait_until","INTEGER"]])}function b(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function o(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function c(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null,waitUntil:t.wait_until??null}}var R={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at",waitUntil:"wait_until"},_=class{constructor(e){this.db=e;h(e)}create(e,a,n,l){let i=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),r=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
|
|
58
|
+
to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
|
|
59
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{i.run(e,a,l),n.forEach((s,u)=>{let E=u===0,T=E&&s.agentId===a&&s.kind!=="message";r.run(e,u+1,s.name,s.kind,s.agentId,s.doneWhen,E?"active":"pending",s.needsApproval?1:0,s.message??null,s.toChannel??null,s.toChat??null,s.toAccount??null,s.checkUrl??null,s.checkContains??null,s.stallMinutes??null,T?l:null,l,s.checkCount??null)}),this.event(e,null,"created",`${n.length} steps, written by ${a}`,l)})()}get(e){let a=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return a?o(a):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(c)}step(e,a){let n=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,a);return n?c(n):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(o)}updateStep(e,a,n){let l=[],i=[];for(let[r,s]of Object.entries(n)){let u=R[r];!u||s===void 0||(l.push(`${u} = ?`),i.push(typeof s=="boolean"?s?1:0:s))}l.length&&this.db.prepare(`UPDATE request_plan_steps SET ${l.join(", ")} WHERE request_id = ? AND idx = ?`).run(...i,e,a)}finish(e,a,n){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(a,n,e).changes>0}markNotified(e,a){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(a,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(o)}event(e,a,n,l,i){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,a,i,n,l.replace(/\s+/g," ").trim().slice(0,A))}continues(e,a){let n=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,a);return n?{turns:n.turns,costUsd:n.cost_usd,toldAt:n.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,a,n){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
|
|
60
|
+
ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
|
|
61
|
+
told_at = COALESCE(excluded.told_at, told_at)`).run(e,a,n.turns??0,n.costUsd??0,n.toldAt??null)}events(e,a=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,a).reverse().map(n=>({requestId:n.request_id,step:n.step??null,at:n.at,kind:n.kind,detail:n.detail}))}stepEvents(e,a,n,l=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,a,n,l).reverse().map(i=>({requestId:i.request_id,step:i.step??null,at:i.at,kind:i.kind,detail:i.detail}))}},q=p;export{m as a,I as b,b as c,_ as d,q as e};
|
|
62
|
+
//# sourceMappingURL=chunk-CSC45PA7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/requests/plan-store.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { TEXT_MAX } from \"./store\"\nimport { ensureColumns } from \"@/storage/sqlite\"\n\n// --- Tracked plans: the steps of one open request (#788) ---\n//\n// A request that takes several steps (build, deploy, check it is live,\n// tell the client) gets one plan. Each step has an owner agent and a\n// \"done when\" check; steps run in order. The daemon's plan check\n// (plan-sweep.ts) starts each step, nudges a step that went quiet, sends an\n// approved message itself, and tells the owner once at the end or when a\n// step is blocked.\n//\n// Stored beside the request in .agentx/db.sqlite. A plan is deleted with\n// its request (retention), never on its own.\n\nexport type PlanState = \"active\" | \"done\" | \"closed\"\nexport type StepState = \"pending\" | \"active\" | \"done\" | \"blocked\" | \"skipped\"\nexport type ApprovalState = \"none\" | \"pending\" | \"approved\" | \"declined\" | \"expired\"\n\nexport const FINISHED_STEP_STATES: readonly StepState[] = [\"done\", \"skipped\"]\n\nexport interface PlanRecord {\n requestId: string\n /** The agent that accepted the request and wrote the plan. */\n createdBy: string\n createdAt: number\n state: PlanState\n finishedAt: number | null\n /** When the owner was sent the summary. Sent once. */\n notifiedAt: number | null\n}\n\nexport interface PlanStep {\n requestId: string\n /** 1-based position: steps run in this order. */\n idx: number\n name: string\n /** \"message\": the daemon sends `message` itself. Any other kind is work\n * the owner agent does and reports. */\n kind: string\n agentId: string\n /** What proves the step is done, in words. */\n doneWhen: string\n state: StepState\n /** The owner approved this step when the plan was made (approveKinds). */\n needsApproval: boolean\n approval: ApprovalState\n cardId: string | null\n message: string | null\n toChannel: string | null\n toChat: string | null\n toAccount: string | null\n /** The daemon marks the step done when this address answers (and shows\n * `checkContains`, when set). */\n checkUrl: string | null\n checkContains: string | null\n /** This step's own stall time; null: the setting. */\n stallMinutes: number | null\n /** The open-count check (checkers/count.ts, #1568), as JSON: the\n * daemon marks the step done when the count is at or under its max. */\n checkCount: string | null\n /** The count the last check read, and when. */\n lastCount: number | null\n lastCountAt: number | null\n evidence: string | null\n /** Why it is blocked or skipped. */\n note: string | null\n /** When its owner agent was given the step. */\n dispatchedAt: number | null\n /** Last progress on the step. */\n updatedAt: number\n nudges: number\n lastNudgeAt: number | null\n /** The step's owner said it waits until then (#1764): no nudge and no\n * block before it; after it, the stall time counts from it. */\n waitUntil: number | null\n /** When the owner was told the step is blocked. */\n notifiedAt: number | null\n}\n\nexport interface PlanEvent {\n requestId: string\n step: number | null\n at: number\n kind: string\n detail: string\n}\n\nexport type NewStep = Pick<PlanStep, \"name\" | \"kind\" | \"agentId\" | \"doneWhen\" | \"needsApproval\">\n & Partial<Pick<PlanStep, \"message\" | \"toChannel\" | \"toChat\" | \"toAccount\" | \"checkUrl\" | \"checkContains\" | \"stallMinutes\" | \"checkCount\">>\n\n/** \" waits until <time>\" for an active step whose owner put off its nudges (#1764). */\nexport function waitsText(s: { state?: string; waitUntil?: number | null }, now = Date.now()): string {\n return s.state === \"active\" && typeof s.waitUntil === \"number\" && s.waitUntil > now\n ? ` waits until ${new Date(s.waitUntil).toISOString().slice(0, 16).replace(\"T\", \" \")}Z` : \"\"\n}\n\nconst DETAIL_MAX = 1000\n\nexport function ensurePlanTables(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS request_plans (\n request_id TEXT PRIMARY KEY,\n created_by TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n state TEXT NOT NULL,\n finished_at INTEGER,\n notified_at INTEGER,\n FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_request_plans_state ON request_plans(state);\n CREATE TABLE IF NOT EXISTS request_plan_steps (\n request_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n name TEXT NOT NULL,\n kind TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n done_when TEXT NOT NULL,\n state TEXT NOT NULL,\n needs_approval INTEGER NOT NULL DEFAULT 0,\n approval TEXT NOT NULL DEFAULT 'none',\n card_id TEXT,\n message TEXT,\n to_channel TEXT,\n to_chat TEXT,\n to_account TEXT,\n check_url TEXT,\n check_contains TEXT,\n stall_minutes REAL,\n evidence TEXT,\n note TEXT,\n dispatched_at INTEGER,\n updated_at INTEGER NOT NULL,\n nudges INTEGER NOT NULL DEFAULT 0,\n last_nudge_at INTEGER,\n notified_at INTEGER,\n PRIMARY KEY (request_id, idx),\n FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS request_plan_events (\n request_id TEXT NOT NULL,\n step INTEGER,\n at INTEGER NOT NULL,\n kind TEXT NOT NULL,\n detail TEXT NOT NULL,\n FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);\n CREATE TABLE IF NOT EXISTS request_plan_continues (\n goal_key TEXT NOT NULL,\n day TEXT NOT NULL,\n turns INTEGER NOT NULL DEFAULT 0,\n cost_usd REAL NOT NULL DEFAULT 0,\n told_at INTEGER,\n PRIMARY KEY (goal_key, day)\n );\n `)\n // The count check (#1568), added after the first version.\n ensureColumns(db, \"request_plan_steps\", [[\"check_count\", \"TEXT\"], [\"last_count\", \"INTEGER\"], [\"last_count_at\", \"INTEGER\"]])\n // A step that waits until a time its owner gave (#1764).\n ensureColumns(db, \"request_plan_steps\", [[\"wait_until\", \"INTEGER\"]])\n}\n\nexport function hasPlanTables(db: Database.Database): boolean {\n return !!db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'\").get()\n}\n\nfunction toPlan(r: any): PlanRecord {\n return {\n requestId: r.request_id, createdBy: r.created_by, createdAt: r.created_at, state: r.state,\n finishedAt: r.finished_at ?? null, notifiedAt: r.notified_at ?? null,\n }\n}\n\nfunction toStep(r: any): PlanStep {\n return {\n requestId: r.request_id, idx: r.idx, name: r.name, kind: r.kind, agentId: r.agent_id, doneWhen: r.done_when,\n state: r.state, needsApproval: !!r.needs_approval, approval: r.approval, cardId: r.card_id ?? null,\n message: r.message ?? null, toChannel: r.to_channel ?? null, toChat: r.to_chat ?? null, toAccount: r.to_account ?? null,\n checkUrl: r.check_url ?? null, checkContains: r.check_contains ?? null, stallMinutes: r.stall_minutes ?? null,\n checkCount: r.check_count ?? null, lastCount: r.last_count ?? null, lastCountAt: r.last_count_at ?? null,\n evidence: r.evidence ?? null, note: r.note ?? null, dispatchedAt: r.dispatched_at ?? null, updatedAt: r.updated_at,\n nudges: r.nudges, lastNudgeAt: r.last_nudge_at ?? null, notifiedAt: r.notified_at ?? null,\n waitUntil: r.wait_until ?? null,\n }\n}\n\n/** Fields a step update may change, by their column. */\nconst STEP_COLUMNS: Record<string, string> = {\n state: \"state\", approval: \"approval\", cardId: \"card_id\", message: \"message\", evidence: \"evidence\", note: \"note\",\n dispatchedAt: \"dispatched_at\", updatedAt: \"updated_at\", nudges: \"nudges\", lastNudgeAt: \"last_nudge_at\", notifiedAt: \"notified_at\",\n lastCount: \"last_count\", lastCountAt: \"last_count_at\", waitUntil: \"wait_until\",\n}\n\nexport type StepPatch = Partial<Pick<PlanStep,\n \"state\" | \"approval\" | \"cardId\" | \"message\" | \"evidence\" | \"note\" | \"dispatchedAt\" | \"updatedAt\" | \"nudges\" | \"lastNudgeAt\" | \"notifiedAt\" | \"lastCount\" | \"lastCountAt\" | \"waitUntil\">>\n\nexport class PlanStore {\n constructor(private db: Database.Database) {\n ensurePlanTables(db)\n }\n\n /** Record a plan for an open request. Step 1 starts active: the agent\n * that wrote the plan is in the turn and, when it owns step 1, already\n * at work on it. */\n create(requestId: string, createdBy: string, steps: NewStep[], now: number): void {\n const insertPlan = this.db.prepare(\n \"INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')\",\n )\n const insertStep = this.db.prepare(\n `INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,\n to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n this.db.transaction(() => {\n insertPlan.run(requestId, createdBy, now)\n steps.forEach((s, i) => {\n const first = i === 0\n // The writer already has step 1 when it is theirs; anyone else's\n // step 1 is handed over by the plan check.\n const own = first && s.agentId === createdBy && s.kind !== \"message\"\n insertStep.run(\n requestId, i + 1, s.name, s.kind, s.agentId, s.doneWhen, first ? \"active\" : \"pending\", s.needsApproval ? 1 : 0,\n s.message ?? null, s.toChannel ?? null, s.toChat ?? null, s.toAccount ?? null, s.checkUrl ?? null,\n s.checkContains ?? null, s.stallMinutes ?? null, own ? now : null, now, s.checkCount ?? null,\n )\n })\n this.event(requestId, null, \"created\", `${steps.length} steps, written by ${createdBy}`, now)\n })()\n }\n\n get(requestId: string): PlanRecord | null {\n const row = this.db.prepare(\"SELECT * FROM request_plans WHERE request_id = ?\").get(requestId)\n return row ? toPlan(row) : null\n }\n\n steps(requestId: string): PlanStep[] {\n return this.db.prepare(\"SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx\").all(requestId).map(toStep)\n }\n\n step(requestId: string, idx: number): PlanStep | null {\n const row = this.db.prepare(\"SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?\").get(requestId, idx)\n return row ? toStep(row) : null\n }\n\n /** Plans the check still follows, oldest first. */\n listActive(): PlanRecord[] {\n return this.db.prepare(\"SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid\").all().map(toPlan)\n }\n\n updateStep(requestId: string, idx: number, patch: StepPatch): void {\n const sets: string[] = []\n const values: unknown[] = []\n for (const [key, value] of Object.entries(patch)) {\n const col = STEP_COLUMNS[key]\n if (!col || value === undefined) continue\n sets.push(`${col} = ?`)\n values.push(typeof value === \"boolean\" ? (value ? 1 : 0) : value)\n }\n if (!sets.length) return\n this.db.prepare(`UPDATE request_plan_steps SET ${sets.join(\", \")} WHERE request_id = ? AND idx = ?`).run(...values, requestId, idx)\n }\n\n /** The plan ended: every step finished (\"done\"), or its request was\n * closed first (\"closed\"). */\n finish(requestId: string, state: Exclude<PlanState, \"active\">, now: number): boolean {\n return this.db.prepare(\n \"UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'\",\n ).run(state, now, requestId).changes > 0\n }\n\n markNotified(requestId: string, now: number | null): void {\n this.db.prepare(\"UPDATE request_plans SET notified_at = ? WHERE request_id = ?\").run(now, requestId)\n }\n\n /** Finished plans whose summary has not reached the owner yet. */\n awaitingSummary(): PlanRecord[] {\n return this.db.prepare(\"SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at\").all().map(toPlan)\n }\n\n /** What happened, in order: the plan's log. */\n event(requestId: string, step: number | null, kind: string, detail: string, now: number): void {\n this.db.prepare(\"INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)\")\n .run(requestId, step, now, kind, detail.replace(/\\s+/g, \" \").trim().slice(0, DETAIL_MAX))\n }\n\n /** Turns started on their own for a goal today (#1568): how many,\n * and what they cost. */\n continues(goalKey: string, day: string): { turns: number; costUsd: number; toldAt: number | null } {\n const row = this.db.prepare(\"SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?\").get(goalKey, day) as any\n return row ? { turns: row.turns, costUsd: row.cost_usd, toldAt: row.told_at ?? null } : { turns: 0, costUsd: 0, toldAt: null }\n }\n\n addContinue(goalKey: string, day: string, add: { turns?: number; costUsd?: number; toldAt?: number }): void {\n this.db.prepare(\n `INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,\n told_at = COALESCE(excluded.told_at, told_at)`,\n ).run(goalKey, day, add.turns ?? 0, add.costUsd ?? 0, add.toldAt ?? null)\n }\n\n /** The newest `limit` events of the plan, in order. A long log drops\n * its oldest entries, never the latest ones. */\n events(requestId: string, limit = 200): PlanEvent[] {\n return (this.db.prepare(\n \"SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?\",\n ).all(requestId, limit) as any[]).reverse().map((r) => ({ requestId: r.request_id, step: r.step ?? null, at: r.at, kind: r.kind, detail: r.detail }))\n }\n\n /** The newest `limit` events of one kind on a step, in order. */\n stepEvents(requestId: string, step: number, kind: string, limit = 200): PlanEvent[] {\n return (this.db.prepare(\n \"SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?\",\n ).all(requestId, step, kind, limit) as any[]).reverse().map((r) => ({ requestId: r.request_id, step: r.step ?? null, at: r.at, kind: r.kind, detail: r.detail }))\n }\n}\n\nexport const STEP_TEXT_MAX = TEXT_MAX\n"],"mappings":"gGACAA,IACAC,IAkBO,IAAMC,EAA6C,CAAC,OAAQ,SAAS,EAyErE,SAASC,EAAUC,EAAkDC,EAAM,KAAK,IAAI,EAAW,CACpG,OAAOD,EAAE,QAAU,UAAY,OAAOA,EAAE,WAAc,UAAYA,EAAE,UAAYC,EAC5E,gBAAgB,IAAI,KAAKD,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,EAAE,QAAQ,IAAK,GAAG,KAAO,EAC9F,CAEA,IAAME,EAAa,IAEZ,SAASC,EAAiBC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GAAI,KAAMA,EAAE,KAAM,OAAQA,EAAE,MAAO,EAAE,CAClK,CACF,EAEa4B,EAAgBC","names":["init_store","init_sqlite","FINISHED_STEP_STATES","waitsText","s","now","DETAIL_MAX","ensurePlanTables","db","ensureColumns","hasPlanTables","toPlan","r","toStep","STEP_COLUMNS","PlanStore","requestId","createdBy","steps","insertPlan","insertStep","i","first","own","row","idx","patch","sets","values","key","value","col","state","step","kind","detail","goalKey","day","add","limit","STEP_TEXT_MAX","TEXT_MAX"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as j,r as R,t as F}from"./chunk-
|
|
1
|
+
import{q as j,r as R,t as F}from"./chunk-OQQTV3OF.js";import{f as L,g as G}from"./chunk-LY4G7PCW.js";import{existsSync as y,mkdirSync as ae,writeFileSync as S,readFileSync as A}from"fs";import{resolve as m}from"path";import{createHash as Ye}from"crypto";import{readFileSync as me,existsSync as fe,unlinkSync as ye,readdirSync as mt}from"fs";import{resolve as H}from"path";function yt(e,n){let r={},s=t=>{let o=H(e,t);if(fe(o))try{return me(o,"utf-8").trim()||void 0}catch{return}};if(n){let t=s(`SOUL.${n}.md`);t?(r.soul=t,r.soulProfile=n):r.soul=s("SOUL.md")}else r.soul=s("SOUL.md");if(r.identity=s("IDENTITY.md"),r.user=s("USER.md"),r.agents=s("AGENTS.md"),r.bootstrap=s("BOOTSTRAP.md"),r.bootstrap)try{ye(H(e,"BOOTSTRAP.md"))}catch{}return r}function bt(e){let n=[];return e.identity&&n.push(`[Identity]
|
|
2
2
|
${e.identity}`),e.soul&&n.push(`[Personality & Boundaries]
|
|
3
3
|
${e.soul}`),e.user&&n.push(`[User Profile]
|
|
4
4
|
${e.user}`),e.bootstrap&&n.push(`[First-Run Instructions \u2014 one time only]
|
|
@@ -112,4 +112,4 @@ Always include:
|
|
|
112
112
|
5. Screenshots if applicable
|
|
113
113
|
`});break}return s}function ut(e,n,r="19900",s=console.error){let t=[],o=[],i=n.workspace;if(!y(i))return s(`Workspace not found: ${i}`),{created:t,skipped:o};if(n.tier!=="claude-code"&&n.tier!=="codex-cli")return{created:t,skipped:o};let a=(c,p)=>{y(c)?o.push(c):(ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c))},l=(c,p,g)=>{if(!y(c)){ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c);return}let d;try{d=A(c,"utf8")}catch{o.push(c);return}let f=Ve(d);if(f===null){o.push(c);return}if(f===g){o.push(c);return}S(c,p),t.push(`${c} (refreshed)`)};if(a(m(i,"AGENTS.md"),W({name:n.name,id:e,role:n.systemPrompt?.split(`
|
|
114
114
|
`)[0],workspace:i,tier:n.tier})),n.tier==="codex-cli")return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o};l(m(i,"CLAUDE.md"),ze(e,n,r),ce(n));let u=m(i,".claude/settings.json");a(u,JSON.stringify(it(e,n,r),null,2));let h=ct(e,n);for(let c of h){let p=m(i,".claude/rules",c.name);c.replaces&&y(p)&&c.replaces.includes(A(p,"utf8"))?(S(p,c.content),t.push(p)):a(p,c.content)}return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o}}function lt(e,n){let r=m(e,".claude/settings.json");if(!y(r))return!1;try{let s=JSON.parse(A(r,"utf-8")),t=!1;for(let[o,i]of Object.entries(n))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){s[o]||(s[o]={});for(let[a,l]of Object.entries(i))s[o][a]===void 0&&(s[o][a]=l,t=!0)}else s[o]===void 0&&(s[o]=i,t=!0);return t&&S(r,JSON.stringify(s,null,2)),t}catch{return!1}}function pt(e,n,r="19900",s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=!1,a=o.permissions??={},l=Array.isArray(a.deny)?a.deny:a.deny=[];for(let d of P)l.includes(d)||(l.push(d),i=!0);let u=o.hooks??={},c=[...Array.isArray(u.PreToolUse)?u.PreToolUse.filter(d=>!ot(d)):[],...pe(n,r,s)];JSON.stringify(u.PreToolUse??null)!==JSON.stringify(c)&&(u.PreToolUse=c,i=!0);let g=[...Array.isArray(u.PostToolUse)?u.PostToolUse.filter(d=>!rt(d)):[],de(r)];return JSON.stringify(u.PostToolUse??null)!==JSON.stringify(g)&&(u.PostToolUse=g,i=!0),i&&S(t,JSON.stringify(o,null,2)),i}catch{return!1}}function dt(e){return Array.isArray(e?.hooks)&&e.hooks.some(n=>typeof n?.command=="string"&&n.command.includes(D))}function ht(e,n,r,s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=JSON.stringify(o),a=s.enabled&&s.tools.length>0,l=`Read(/${te(s.dir,n)}/**)`,u=Array.isArray(o.hooks?.PostToolUse)?o.hooks.PostToolUse:[],h=u.filter(g=>!dt(g)),c=Array.isArray(o.permissions?.allow)?o.permissions.allow:[],p=c.filter(g=>g!==l);if(a){let d=`curl -s --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${r}${D}?agent=${encodeURIComponent(n)}`}' 2>/dev/null || true`;h.push({matcher:s.tools.join("|"),hooks:[{type:"command",command:d,timeout:10}]}),p.push(l)}return(a||u.length>0)&&((o.hooks??={}).PostToolUse=h),(a||c.length>0)&&((o.permissions??={}).allow=p),JSON.stringify(o)===i?!1:(S(t,JSON.stringify(o,null,2)),!0)}catch{return!1}}function Vt(e,n="19900",r=console.error,s){let t=0,o=0,i=0,a=0,l=0,u=0;for(let[h,c]of Object.entries(e)){if(c.tier!=="claude-code"&&c.tier!=="codex-cli")continue;let p=ut(h,c,n,r);if(t+=p.created.length,c.tier==="claude-code"&<(c.workspace,{env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}})&&o++,c.tier==="claude-code"&&pt(c.workspace,h,n,c.mcp)&&i++,c.tier==="claude-code"&&s){let g=ne(c.permissionMode);s.enabled&&!g&&u++;let d=s.enabled&&g;ht(c.workspace,h,n,{...s,enabled:d})&&(d?a++:l++)}}t>0&&r(`Workspace setup: ${t} file(s) created across agent workspaces`),o>0&&r(`Workspace patch: ${o} workspace(s) updated with agent teams support`),i>0&&r(`Guardrails: ${i} workspace(s) backfilled with deny list + PreToolUse guard hook`),a>0&&r(`ObservationPack: PostToolUse hook written to ${a} workspace(s)`),l>0&&r(`ObservationPack: PostToolUse hook removed from ${l} workspace(s)`),u>0&&r(`ObservationPack: ${u} agent(s) not packed: permissionMode is not "bypassPermissions", so they could not read a saved original back`)}export{yt as a,bt as b,kt as c,St as d,At as e,D as f,Et as g,te as h,ne as i,vt as j,Dt as k,Mt as l,We as m,M as n,Gt as o,ie as p,Ve as q,ze as r,le as s,et as t,tt as u,nt as v,ut as w,pt as x,ht as y,Vt as z};
|
|
115
|
-
//# sourceMappingURL=chunk-
|
|
115
|
+
//# sourceMappingURL=chunk-M4H2RYP4.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-
|
|
1
|
+
import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-OQQTV3OF.js";import{Da as I,Ia as Je,sa as ne,ta as re,va as oe,wa as ie}from"./chunk-KAM4ZWRE.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??X)}</string>
|
|
@@ -31,8 +31,8 @@ function run(argv) {
|
|
|
31
31
|
`)}function Ee(e){let t=e.run??y;return{async post({title:n,message:r}){let o=e.helper();return o&&await t(o,["notify","--title",n,"--message",r])||await t(N,b(wt(n,r)))?"posted":"failed"},status:()=>J(e.helper(),e.capture??m)}}var ht=["Add-Type -TypeDefinition @'","using System; using System.Runtime.InteropServices;","public static class AgentXIdle {"," [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }",' [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);'," public static long Ms() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);"," if (!GetLastInputInfo(ref i)) return -1; return (long)(uint)(Environment.TickCount - (int)i.dwTime); }","}","'@","[AgentXIdle]::Ms()"].join(`
|
|
32
32
|
`);function St(e){let t=Number(e.trim());return Number.isFinite(t)&&t>=0&&e.trim()!==""?Math.floor(t/1e3):null}function $e(e={}){let t=e.capture??m;return{async seconds(){let n=await t(N,b(ht));return n?St(n):null}}}import{win32 as xt}from"path";function Te(e,t){if(!/^[\w -]+$/.test(e))return null;let n=xt.join(t.media,`${e}.wav`);return t.exists(n)?n:null}function Oe(e){let t=e.run??y;return{async play(n,r){let o=Te(n,e);!o||!(r>0)||await t(N,b(`(New-Object Media.SoundPlayer ${A(o)}).PlaySync()`))},has:n=>Te(n,e)!==null,async names(){try{return e.list(e.media).filter(n=>/\.wav$/i.test(n)).map(n=>n.slice(0,-4)).sort()}catch{return[]}}}}function Ce(e={},t={}){let n=()=>t.helper===void 0?k():t.helper,r=t.media??bt.join(process.env.WINDIR||process.env.SystemRoot||"C:\\Windows","Media"),o=t.exists??Nt,i=t.list??(s=>At(s));return{os:"windows",banner:Ee({run:t.run,capture:t.capture,helper:n}),sound:Oe({run:t.run,media:r,exists:o,list:i}),idle:$e({capture:t.capture}),async describe(){let s=["Tasks, notes and Focus: AgentX has no Windows adapter for these yet."];return n()||s.push("Banners come from Windows PowerShell until the AgentX Windows helper is installed."),{os:"windows",tasks:!1,notes:!1,banner:!0,sound:!0,focus:!1,problems:s}}}}var vt={darwin:Ie,win32:Ce};function z(e={},t={}){if(e.native?.adapter==="none")return _('Turned off: native.adapter is "none".');let n=t.platform??process.platform,r=(t.factories??vt)[n];return r?r(e,t.io??{}):_(`AgentX has no native adapter for ${n} yet.`)}import{existsSync as kt}from"fs";import{homedir as Rt}from"os";import{isAbsolute as Pt}from"path";var Le={banner:!0,sound:!0,soundName:"Glass",volume:.4,quietWaitSeconds:15};function fr(e){return{...Le,...e??{}}}function gr(e,t={}){let n=z({native:t.native},{platform:t.platform,io:{run:t.run,capture:t.capture,helper:t.helper}});return async(r,o)=>{let i=[];if(e.banner&&n.banner&&i.push(n.banner.post({title:r,message:o})),e.sound&&n.sound){let s=n.sound;i.push(It(n.speech,(e.quietWaitSeconds??Le.quietWaitSeconds)*1e3,t.pollMs??500).then(l=>l?s.play(e.soundName,e.volume):void 0))}await Promise.all(i)}}async function It(e,t,n){if(!e||t<=0)return!0;let r=Date.now()+t;for(;;){if(!await e.othersSpeaking())return!0;if(Date.now()>=r)return!1;await new Promise(o=>setTimeout(o,n))}}function yr(e,t,n=process.platform){let r={...e??{}},o=z({},{platform:n});if("banner"in t&&(r.banner=!!t.banner),"sound"in t&&(r.sound=!!t.sound),"soundName"in t){let i=String(t.soundName).trim();if(!(o.sound?o.sound.has(i):/^[\w -]+$/.test(i)))throw new Error(`no system sound named "${i}" on this machine`);r.soundName=i}if("icon"in t){let i=String(t.icon??"").trim().replace(/^~(?=\/)/,Rt());if(!i)delete r.icon;else{if(!Pt(i)||!/\.(png|jpe?g|icns)$/i.test(i))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(o.banner&&!kt(i))throw new Error(`no icon file at ${i}`);r.icon=i}}if("volume"in t){let i=Number(t.volume);if(!Number.isFinite(i)||i<0||i>1)throw new Error("volume must be between 0 and 1");r.volume=i}return r}import{existsSync as Lt,mkdirSync as Mt,readFileSync as _t,renameSync as Dt,writeFileSync as Wt}from"fs";import{dirname as He,resolve as qt}from"path";oe();Je();oe();var Nr=["owner","agent","person"],Et=36e5,$t=e=>ie.includes(e.state);function Me(e){return t=>!e||e.get(t)?.state!=="active"?null:e.steps(t).find(n=>n.state==="active")?.agentId??null}function V(e,t){return e.state==="waiting_owner"?{group:"owner",who:I}:e.promise&&e.owedTo&&e.owedTo!==I&&!t.isAgent(e.owedTo)?{group:"person",who:e.owedTo}:e.state==="needs_attention"?{group:"owner",who:I}:{group:"agent",who:t.activeStepAgent?.(e.id)??e.agentId}}function Q(e,t,n){return $t(e)?e.state==="needs_attention"?e.attentionReason??"needs attention":e.dueAt!==null?n>e.dueAt?`past its due time (${Tt(e.dueAt)})`:null:n-e.updatedAt>t*Et?`no activity for ${t} h or more`:null:null}function Ar(e,t,n,r){let o={owner:[],agent:[],person:[]};for(let i of e){let s=Q(i,t,n);if(!s)continue;let{group:l,who:a}=V(i,r);o[l].push({request:i,group:l,who:a,why:s})}return o}function br(e,t){return e==="owner"?"you":e==="agent"?`agent ${t}`:`${t} (outside person)`}var Tt=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function vr(e){if(e==null||e==="")return;let t=typeof e=="number"?e:typeof e=="string"?Date.parse(e.trim()):NaN;return!Number.isFinite(t)||t<=0?"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds":t}function kr(e){return t=>ne(t,e())}var Ot=10;async function Rr(e,t,n){let r=e.dueForCheck(n.now-n.everyMinutes*6e4,Ot),o=0;return await Promise.all(r.map(async i=>{e.markChecked(i.id,i.verifyState,i.verifyDetail??"",n.now);let s=await t(i.closeWhen,i).catch(l=>({verdict:"unverifiable",detail:String(l?.message??l)}));if(s.verdict==="met"){e.closeVerified(i.id,s.detail,n.now)&&(o++,n.log(`[requests] ${i.id} closed by its check: ${s.detail}`));return}e.markChecked(i.id,s.verdict==="unverifiable"?"unverified":i.verifyState==="failed"?"failed":null,s.detail,n.now)})),{checked:r.length,closed:o}}var We=200,_e=4e3,De="Nothing, just so you know.";function Y(e,t=We){let n=e.headline?e.headline.length>t?`${e.headline.slice(0,t-1)}\u2026`:e.headline:w(e.text,t),r=e.state==="needs_attention"?`Hand it back to ${e.agentId}, or drop it.`:e.state==="waiting_owner"?e.need??(e.question?`Answer: ${w(e.question,150)}`:"Your answer."):e.state==="candidate"||e.state==="in_progress"||e.state==="waiting_other"?e.need??De:De;return{headline:n,need:r,said:qe(e.text)}}function qe(e){return e.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm,"").replace(/[*_~`]+/g,"").replace(/\s+/g," ").trim()}function w(e,t=We){let n=qe(e);if(n.length<=t)return n;let r=n.slice(0,t),o=Math.max(r.lastIndexOf(". "),r.lastIndexOf("? "),r.lastIndexOf("! "));return o>t/2?r.slice(0,o+1):`${r.slice(0,t-1).trimEnd()}\u2026`}function Ct(e){return e.promise||e.dueAt!==null||e.closeWhen?{owedTo:e.owedTo,promise:e.promise,dueAt:e.dueAt,check:e.closeWhen?re(e.closeWhen):null,verifyState:e.verifyState,verifyDetail:e.verifyDetail}:null}function Or(e,t,n,r){let o=n?.get(e.id),i=r?Q(e,r.staleAfterHours,r.now):null,s=t.lastAnswer(e.id),l=s&&s.text.length>_e?`${s.text.slice(0,_e)}
|
|
33
33
|
|
|
34
|
-
\u2026`:s?.text,a=Y(e);return{...e,summary:a.headline,needed:a.need,textHtml:E(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?E(e.ownerNote):null,lastAnswer:s?{agentId:s.agentId,at:s.at,html:E(l)}:null,loop:Ct(e),awaitingQa:se(e),stall:r&&i?{...V(e,{isAgent:r.isAgent,activeStepAgent:Me(n)}),why:i}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(c=>({idx:c.idx,name:c.name,kind:c.kind,agentId:c.agentId,state:c.state,approval:c.needsApproval?c.approval:null,evidence:c.evidence,note:c.note,nudges:c.nudges}))}:null}}var Z=3,Ht=30*24*36e5;function Be(e){return qt(e,".agentx","native-mirror.json")}function ee(e){try{let t=JSON.parse(_t(Be(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function Fe(e,t){let n=Be(e);Lt(He(n))||Mt(He(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Wt(r,JSON.stringify(t,null,2)+`
|
|
34
|
+
\u2026`:s?.text,a=Y(e);return{...e,summary:a.headline,needed:a.need,textHtml:E(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?E(e.ownerNote):null,lastAnswer:s?{agentId:s.agentId,at:s.at,html:E(l)}:null,loop:Ct(e),awaitingQa:se(e),stall:r&&i?{...V(e,{isAgent:r.isAgent,activeStepAgent:Me(n)}),why:i}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(c=>({idx:c.idx,name:c.name,kind:c.kind,agentId:c.agentId,state:c.state,approval:c.needsApproval?c.approval:null,evidence:c.evidence,note:c.note,nudges:c.nudges,waitUntil:c.state==="active"?c.waitUntil:null}))}:null}}var Z=3,Ht=30*24*36e5;function Be(e){return qt(e,".agentx","native-mirror.json")}function ee(e){try{let t=JSON.parse(_t(Be(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function Fe(e,t){let n=Be(e);Lt(He(n))||Mt(He(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Wt(r,JSON.stringify(t,null,2)+`
|
|
35
35
|
`),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
|
|
36
36
|
`),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
|
|
37
37
|
`),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-OQNJIIR2.js.map
|