nodal-agents 0.7.0 → 0.7.2

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.
Files changed (165) hide show
  1. package/cli.js +335 -35
  2. package/migrations/0054_audit2_db_integrity.sql +52 -0
  3. package/migrations/0055_entity_settings.sql +22 -0
  4. package/migrations/0056_agents_skills_entity_scoped_unique.sql +23 -0
  5. package/migrations/0057_telegram_allowed_chats.sql +34 -0
  6. package/migrations/meta/_journal.json +28 -0
  7. package/package.json +1 -1
  8. package/runner.js +47123 -35332
  9. package/web/.next/BUILD_ID +1 -1
  10. package/web/.next/app-path-routes-manifest.json +4 -4
  11. package/web/.next/build-manifest.json +2 -2
  12. package/web/.next/prerender-manifest.json +3 -3
  13. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page.js +3 -3
  14. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page.js.nft.json +1 -1
  15. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page_client-reference-manifest.js +1 -1
  16. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page.js +2 -2
  17. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page.js.nft.json +1 -1
  18. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page_client-reference-manifest.js +1 -1
  19. package/web/.next/server/app/(dashboard)/agents/page.js +2 -2
  20. package/web/.next/server/app/(dashboard)/agents/page.js.nft.json +1 -1
  21. package/web/.next/server/app/(dashboard)/agents/page_client-reference-manifest.js +1 -1
  22. package/web/.next/server/app/(dashboard)/approvals/page.js +2 -2
  23. package/web/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  24. package/web/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  25. package/web/.next/server/app/(dashboard)/automations/page.js +2 -2
  26. package/web/.next/server/app/(dashboard)/automations/page.js.nft.json +1 -1
  27. package/web/.next/server/app/(dashboard)/automations/page_client-reference-manifest.js +1 -1
  28. package/web/.next/server/app/(dashboard)/chat/page.js +2 -2
  29. package/web/.next/server/app/(dashboard)/chat/page.js.nft.json +1 -1
  30. package/web/.next/server/app/(dashboard)/chat/page_client-reference-manifest.js +1 -1
  31. package/web/.next/server/app/(dashboard)/connectors/page.js +1 -1
  32. package/web/.next/server/app/(dashboard)/connectors/page.js.nft.json +1 -1
  33. package/web/.next/server/app/(dashboard)/connectors/page_client-reference-manifest.js +1 -1
  34. package/web/.next/server/app/(dashboard)/credentials/page.js +1 -1
  35. package/web/.next/server/app/(dashboard)/credentials/page.js.nft.json +1 -1
  36. package/web/.next/server/app/(dashboard)/credentials/page_client-reference-manifest.js +1 -1
  37. package/web/.next/server/app/(dashboard)/jobs/[id]/page.js +2 -2
  38. package/web/.next/server/app/(dashboard)/jobs/[id]/page.js.nft.json +1 -1
  39. package/web/.next/server/app/(dashboard)/jobs/[id]/page_client-reference-manifest.js +1 -1
  40. package/web/.next/server/app/(dashboard)/jobs/page.js +2 -2
  41. package/web/.next/server/app/(dashboard)/jobs/page.js.nft.json +1 -1
  42. package/web/.next/server/app/(dashboard)/jobs/page_client-reference-manifest.js +1 -1
  43. package/web/.next/server/app/(dashboard)/learned-skills/page.js +2 -2
  44. package/web/.next/server/app/(dashboard)/learned-skills/page.js.nft.json +1 -1
  45. package/web/.next/server/app/(dashboard)/learned-skills/page_client-reference-manifest.js +1 -1
  46. package/web/.next/server/app/(dashboard)/llm-providers/page.js +1 -1
  47. package/web/.next/server/app/(dashboard)/llm-providers/page.js.nft.json +1 -1
  48. package/web/.next/server/app/(dashboard)/llm-providers/page_client-reference-manifest.js +1 -1
  49. package/web/.next/server/app/(dashboard)/logs/page.js +2 -2
  50. package/web/.next/server/app/(dashboard)/logs/page.js.nft.json +1 -1
  51. package/web/.next/server/app/(dashboard)/logs/page_client-reference-manifest.js +1 -1
  52. package/web/.next/server/app/(dashboard)/mcp/page.js +2 -2
  53. package/web/.next/server/app/(dashboard)/mcp/page.js.nft.json +1 -1
  54. package/web/.next/server/app/(dashboard)/mcp/page_client-reference-manifest.js +1 -1
  55. package/web/.next/server/app/(dashboard)/memories/page.js +2 -2
  56. package/web/.next/server/app/(dashboard)/memories/page.js.nft.json +1 -1
  57. package/web/.next/server/app/(dashboard)/memories/page_client-reference-manifest.js +1 -1
  58. package/web/.next/server/app/(dashboard)/page.js +2 -2
  59. package/web/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  60. package/web/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  61. package/web/.next/server/app/(dashboard)/settings/page.js +2 -2
  62. package/web/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  63. package/web/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  64. package/web/.next/server/app/(dashboard)/settings/root-context/page.js +2 -2
  65. package/web/.next/server/app/(dashboard)/settings/root-context/page.js.nft.json +1 -1
  66. package/web/.next/server/app/(dashboard)/settings/root-context/page_client-reference-manifest.js +1 -1
  67. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page.js +2 -2
  68. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page.js.nft.json +1 -1
  69. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page_client-reference-manifest.js +1 -1
  70. package/web/.next/server/app/(dashboard)/skills/new/page.js +2 -2
  71. package/web/.next/server/app/(dashboard)/skills/new/page.js.nft.json +1 -1
  72. package/web/.next/server/app/(dashboard)/skills/new/page_client-reference-manifest.js +1 -1
  73. package/web/.next/server/app/(dashboard)/skills/page.js +2 -2
  74. package/web/.next/server/app/(dashboard)/skills/page.js.nft.json +1 -1
  75. package/web/.next/server/app/(dashboard)/skills/page_client-reference-manifest.js +1 -1
  76. package/web/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  77. package/web/.next/server/app/_global-error.html +1 -1
  78. package/web/.next/server/app/_global-error.rsc +2 -2
  79. package/web/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  80. package/web/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  81. package/web/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  82. package/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  83. package/web/.next/server/app/_global-error.segments/_index.segment.rsc +2 -2
  84. package/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  85. package/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  86. package/web/.next/server/app/_not-found.html +1 -1
  87. package/web/.next/server/app/_not-found.rsc +3 -3
  88. package/web/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  89. package/web/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  90. package/web/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  91. package/web/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  92. package/web/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  93. package/web/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  94. package/web/.next/server/app/api/auth/[...all]/route.js +1 -1
  95. package/web/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
  96. package/web/.next/server/app/api/oauth/[provider]/callback/route.js +1 -1
  97. package/web/.next/server/app/api/oauth/[provider]/callback/route.js.nft.json +1 -1
  98. package/web/.next/server/app/api/oauth/[provider]/start/route.js +1 -1
  99. package/web/.next/server/app/api/oauth/[provider]/start/route.js.nft.json +1 -1
  100. package/web/.next/server/app/login/page_client-reference-manifest.js +1 -1
  101. package/web/.next/server/app/onboarding/page.js +205 -185
  102. package/web/.next/server/app/onboarding/page_client-reference-manifest.js +1 -1
  103. package/web/.next/server/app-paths-manifest.json +4 -4
  104. package/web/.next/server/chunks/2713.js +47 -27
  105. package/web/.next/server/chunks/3223.js +1 -1
  106. package/web/.next/server/chunks/4574.js +1 -1
  107. package/web/.next/server/chunks/5515.js +1 -0
  108. package/web/.next/server/chunks/6468.js +1 -0
  109. package/web/.next/server/chunks/8410.js +1 -0
  110. package/web/.next/server/chunks/{4488.js → 8810.js} +2 -2
  111. package/web/.next/server/chunks/{3154.js → 960.js} +10 -10
  112. package/web/.next/server/middleware-build-manifest.js +1 -1
  113. package/web/.next/server/pages/404.html +1 -1
  114. package/web/.next/server/pages/500.html +1 -1
  115. package/web/.next/server/server-reference-manifest.js +1 -1
  116. package/web/.next/server/server-reference-manifest.json +1 -1
  117. package/web/.next/static/chunks/4964-c6711d3d479b6085.js +1 -0
  118. package/web/.next/static/chunks/{9836-6830cb9d49ad261f.js → 9836-177f6ca2f15ff703.js} +1 -1
  119. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/edit/page-cfce874f4acede5e.js +6 -0
  120. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/telegram/page-9249c2839f551ba1.js +1 -0
  121. package/web/.next/static/chunks/app/(dashboard)/agents/page-7d784d737acedccf.js +1 -0
  122. package/web/.next/static/chunks/app/(dashboard)/approvals/{page-9a01cb723a6ccff0.js → page-b3a838ecbc94a030.js} +1 -1
  123. package/web/.next/static/chunks/app/(dashboard)/automations/page-b1b548de4f52696c.js +1 -0
  124. package/web/.next/static/chunks/app/(dashboard)/chat/{page-a6cc7a58986c0340.js → page-bcf6dcc73b370eb0.js} +1 -1
  125. package/web/.next/static/chunks/app/(dashboard)/connectors/{page-21d6c042800c8cd3.js → page-2c6f913cc6aea4b7.js} +1 -1
  126. package/web/.next/static/chunks/app/(dashboard)/jobs/[id]/page-43f033251eddcc4b.js +1 -0
  127. package/web/.next/static/chunks/app/(dashboard)/jobs/page-1f892f950bb30403.js +1 -0
  128. package/web/.next/static/chunks/app/(dashboard)/layout-e184673151ff8a05.js +1 -0
  129. package/web/.next/static/chunks/app/(dashboard)/learned-skills/page-f873bb6f8539e47e.js +1 -0
  130. package/web/.next/static/chunks/app/(dashboard)/llm-providers/page-64adda30176f4ccb.js +1 -0
  131. package/web/.next/static/chunks/app/(dashboard)/logs/page-79cfd9141c39d8ef.js +1 -0
  132. package/web/.next/static/chunks/app/(dashboard)/mcp/page-d276d7bab25286a1.js +1 -0
  133. package/web/.next/static/chunks/app/(dashboard)/memories/page-c66720494a340503.js +1 -0
  134. package/web/.next/static/chunks/app/(dashboard)/page-3649204dd27a0ad0.js +1 -0
  135. package/web/.next/static/chunks/app/(dashboard)/settings/page-1cab404d2eccfd80.js +1 -0
  136. package/web/.next/static/chunks/app/(dashboard)/settings/root-context/page-b5898c5444f88c9a.js +1 -0
  137. package/web/.next/static/chunks/app/(dashboard)/skills/[id]/edit/page-82d91fc6b6acc161.js +1 -0
  138. package/web/.next/static/chunks/app/(dashboard)/skills/new/page-58b5ed04583ca7d4.js +1 -0
  139. package/web/.next/static/chunks/app/(dashboard)/skills/page-312bd4ae8ddc8114.js +1 -0
  140. package/web/.next/static/chunks/app/onboarding/{page-a4116e2f430eaff8.js → page-f2f04878e81fdf23.js} +2 -2
  141. package/web/.next/static/css/{eff119dd24f92093.css → 4d808b91d7b58fce.css} +1 -1
  142. package/web/.next/server/chunks/4626.js +0 -1
  143. package/web/.next/server/chunks/8971.js +0 -1
  144. package/web/.next/server/chunks/9043.js +0 -1
  145. package/web/.next/static/chunks/4964-08171c654e41b0a4.js +0 -1
  146. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/edit/page-fa5717f0d0450659.js +0 -6
  147. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/telegram/page-73012222871598aa.js +0 -1
  148. package/web/.next/static/chunks/app/(dashboard)/agents/page-7e9616b28c098e9e.js +0 -1
  149. package/web/.next/static/chunks/app/(dashboard)/automations/page-85c985cd687406ed.js +0 -1
  150. package/web/.next/static/chunks/app/(dashboard)/jobs/[id]/page-f6b993a88c70a2fe.js +0 -1
  151. package/web/.next/static/chunks/app/(dashboard)/jobs/page-d0d6b9db1b68451f.js +0 -1
  152. package/web/.next/static/chunks/app/(dashboard)/layout-d2ac2646967496bb.js +0 -1
  153. package/web/.next/static/chunks/app/(dashboard)/learned-skills/page-ec6312f6dfd7ee23.js +0 -1
  154. package/web/.next/static/chunks/app/(dashboard)/llm-providers/page-1fb26463eddf509c.js +0 -1
  155. package/web/.next/static/chunks/app/(dashboard)/logs/page-0bca733315e8a208.js +0 -1
  156. package/web/.next/static/chunks/app/(dashboard)/mcp/page-ff56ecf2f65f5466.js +0 -1
  157. package/web/.next/static/chunks/app/(dashboard)/memories/page-fe4d9438c93750d6.js +0 -1
  158. package/web/.next/static/chunks/app/(dashboard)/page-9402fe2931216f4b.js +0 -1
  159. package/web/.next/static/chunks/app/(dashboard)/settings/page-995662f10ebff365.js +0 -1
  160. package/web/.next/static/chunks/app/(dashboard)/settings/root-context/page-785b6ce3e4c5890b.js +0 -1
  161. package/web/.next/static/chunks/app/(dashboard)/skills/[id]/edit/page-2106201c4df8b5a4.js +0 -1
  162. package/web/.next/static/chunks/app/(dashboard)/skills/new/page-0135bcb86ab60dc2.js +0 -1
  163. package/web/.next/static/chunks/app/(dashboard)/skills/page-54e939d40c8b5b6d.js +0 -1
  164. /package/web/.next/static/{KFac7DQ7gdp9XPQ2bnb-2 → SgnP_MouhUmw0bBf-lUmD}/_buildManifest.js +0 -0
  165. /package/web/.next/static/{KFac7DQ7gdp9XPQ2bnb-2 → SgnP_MouhUmw0bBf-lUmD}/_ssgManifest.js +0 -0
@@ -1,23 +1,27 @@
1
- exports.id=2713,exports.ids=[2713],exports.modules={3808:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(1887),f=c(64565);function g({placeholder:a="Search agents, skills, runs…",keyboardShortcut:b=!0,onSubmit:c,className:h=""}){let i=(0,f.useRef)(null);return(0,d.jsxs)("form",{onSubmit:a=>{a.preventDefault(),c?.(i.current?.value??"")},className:`flex h-[34px] min-w-[280px] items-center gap-2 rounded-md border border-rule-2 bg-paper px-3 text-[13px] text-ink-4 ${h}`,children:[(0,d.jsx)(e.e,{size:13,className:"shrink-0"}),(0,d.jsx)("input",{ref:i,type:"search",placeholder:a,className:"flex-1 border-0 bg-transparent text-[14px] leading-none text-ink outline-none placeholder:text-ink-4"}),(0,d.jsx)("span",{className:"rounded-[5px] border border-rule bg-black/5 px-1.5 py-[1px] font-mono text-[12px] leading-none text-ink-4 dark:bg-white/[0.06]",children:"/"})]})}},7316:(a,b,c)=>{Promise.resolve().then(c.bind(c,55053))},11405:a=>{function b(a){return Promise.resolve().then(()=>{var b=Error("Cannot find module '"+a+"'");throw b.code="MODULE_NOT_FOUND",b})}b.keys=()=>[],b.resolve=b,b.id=11405,a.exports=b},17030:(a,b,c)=>{"use strict";c.d(b,{Y:()=>d.YT});var d=c(64190)},19259:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,67448,23)),Promise.resolve().then(c.t.bind(c,2667,23)),Promise.resolve().then(c.t.bind(c,10903,23)),Promise.resolve().then(c.t.bind(c,11162,23)),Promise.resolve().then(c.t.bind(c,23838,23)),Promise.resolve().then(c.t.bind(c,83466,23)),Promise.resolve().then(c.t.bind(c,12127,23)),Promise.resolve().then(c.bind(c,26698))},28659:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(64565),f=c(44625);function g(){let[a,b]=(0,e.useState)(!1);async function c(){b(!0);try{let a=await fetch("/api/auth/sign-out",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",credentials:"same-origin"});a.ok||console.error("sign-out failed",a.status,await a.text().catch(()=>""))}catch(a){console.error("sign-out network error",a)}window.location.replace("/login")}return(0,d.jsx)("button",{type:"button",onClick:c,disabled:a,"data-testid":"user-menu-sign-out","aria-label":"Sign out",title:"Sign out",className:"inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-ink-3 transition-colors hover:bg-hover hover:text-ink disabled:cursor-not-allowed disabled:opacity-40 lg:h-8 lg:w-8 lg:rounded-md",children:(0,d.jsx)(f.M,{size:15,className:"h-[18px] w-[18px] lg:h-[15px] lg:w-[15px]"})})}},35245:(a,b,c)=>{"use strict";c.d(b,{default:()=>n});var d=c(10476),e=c(64565),f=c(88831),g=c.n(f),h=c(9599),i=c(48082),j=c(72134),k=c(61166);function l({item:a,onApproved:b}){let[c,f]=(0,e.useTransition)();return(0,d.jsx)("button",{type:"button",onClick:c=>{c.preventDefault(),c.stopPropagation(),f(async()=>{let c=await (0,j.C)({approvalRequestId:a.id,decision:"approve"});c.ok?(i.oR.success("Approved"),b()):i.oR.error(c.message)})},disabled:c,className:"shrink-0 rounded-md bg-ok px-2.5 py-1 text-[12px] font-semibold text-canvas transition-[filter] hover:brightness-[0.92] disabled:opacity-40",children:c?"…":"Approve"})}function m({items:a,onClose:b,onApproved:c}){let f=(0,e.useRef)(null);return(0,d.jsxs)("div",{ref:f,className:"absolute right-0 top-full z-50 mt-1.5 w-[340px] rounded-xl border border-rule-2 bg-paper shadow-lg",role:"dialog","aria-label":"Pending approvals",children:[(0,d.jsx)("div",{className:"border-b border-rule-2 px-4 py-3",children:(0,d.jsxs)("p",{className:"text-[14px] font-semibold text-ink",children:["Pending approvals (",a.length,")"]})}),0===a.length?(0,d.jsx)("p",{className:"px-4 py-5 text-center text-[13px] text-ink-3",children:"No pending approvals."}):(0,d.jsx)("ul",{className:"max-h-[340px] divide-y divide-rule-2 overflow-y-auto",children:a.map(a=>(0,d.jsx)("li",{children:(0,d.jsxs)(g(),{href:`/jobs/${a.jobId}`,onClick:b,className:"flex items-start gap-3 px-4 py-3 transition-colors hover:bg-hover",children:[(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsxs)("p",{className:"truncate text-[13px] font-medium text-ink",children:[a.agentName??"Agent",(0,d.jsx)("span",{className:"mx-1 text-ink-4",children:"\xb7"}),(0,d.jsx)("code",{className:"rounded bg-canvas px-1 py-0.5 font-mono text-[12px] text-ink-2",children:a.toolName})]}),(0,d.jsx)("p",{className:"mt-0.5 truncate text-[12px] text-ink-3",children:function(a){if(!a)return"—";if("string"==typeof a.purpose&&a.purpose.trim()){let b=a.purpose.trim();return b.length>80?b.slice(0,77)+"…":b}if("string"==typeof a.command){let b=a.command;return b.length>60?b.slice(0,57)+"…":b}let b=JSON.stringify(a);return b.length>60?b.slice(0,57)+"…":b}(a.toolInput)}),(0,d.jsx)("p",{className:"mt-0.5 text-[11px] text-ink-4",children:function(a){if(!a)return"—";let b=Math.floor((Date.now()-new Date(a).getTime())/1e3);if(b<60)return`${b}s ago`;let c=Math.floor(b/60);if(c<60)return`${c}m ago`;let d=Math.floor(c/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}(a.requestedAt)})]}),(0,d.jsx)(l,{item:a,onApproved:c})]})},a.id))}),(0,d.jsx)("div",{className:"border-t border-rule-2 px-4 py-2.5",children:(0,d.jsx)(g(),{href:"/approvals",onClick:b,className:"text-[13px] font-medium text-ink-2 transition-colors hover:text-ink",children:"See all approvals →"})})]})}function n(){let{pending:a,refresh:b}=(0,k.e)(),[c,f]=(0,e.useState)(!1),g=(0,e.useRef)(null),i=a.length,j=(0,e.useCallback)(()=>f(!1),[]),l=(0,e.useCallback)(()=>f(a=>!a),[]),n=(0,e.useCallback)(()=>{b()},[b]);return(0,d.jsxs)("div",{ref:g,className:"relative",children:[(0,d.jsxs)("button",{type:"button","aria-label":"Notifications",title:"Notifications",onClick:l,className:"relative flex h-[34px] w-[34px] shrink-0 items-center justify-center rounded-md border border-rule-2 bg-paper text-ink-2 transition-colors hover:text-ink",children:[(0,d.jsx)(h.I,{size:15}),i>0&&(0,d.jsx)("span",{className:"absolute -top-1 -right-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-err px-1 text-[11px] font-bold leading-none text-canvas",children:i>99?"99+":i})]}),c&&(0,d.jsx)(m,{items:a,onClose:j,onApproved:n})]})}},36069:(a,b,c)=>{"use strict";c.d(b,{default:()=>_});var d=c(10476),e=c(64565),f=c(12418),g=c(77568),h=c(3521),i=c(82271),j=c(13028),k=c(83588),l=c(92607),m=c(33478),n=c(1282),o=c(73836),p=c(11145),q=c(66442),r=c(63473),s=c(84132),t=c(64945),u=c(55234),v=c(93720),w=c(11745),x=c(4870);function y(){return(0,d.jsx)("div",{className:"px-4 pb-3.5",children:(0,d.jsxs)("div",{className:"flex items-center gap-2 text-[16px] font-medium leading-none tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-[22px] w-[22px] items-center justify-center rounded-md bg-ink text-[12px] font-semibold leading-none tracking-[0.04em] text-canvas font-mono",children:"N"}),(0,d.jsx)("span",{children:"Nodal-Agents"})]})})}function z({children:a}){return(0,d.jsx)("div",{className:"px-[22px] pt-4 pb-1.5 font-mono text-[11px] uppercase tracking-[0.14em] text-ink-4 lg:pt-3.5 lg:pb-1 lg:text-[11px]",children:a})}var A=c(88831),B=c.n(A);let C={agent:"bg-agent-vivid",skill:"bg-skill-vivid",conn:"bg-conn-vivid"};function D({href:a,label:b,icon:c,dot:e,count:g,pill:h,isActive:i}){let j=(0,f.usePathname)(),k=i??(j===a||j.startsWith(a+"/"));return(0,d.jsxs)(B(),{href:a,className:`group mx-3 flex h-12 items-center gap-3 rounded-xl px-3 text-[16px] transition-colors lg:h-[30px] lg:gap-2.5 lg:rounded-lg lg:px-3 lg:text-[13px] lg:leading-none ${k?"bg-paper text-ink font-medium shadow-[0_1px_2px_rgba(0,0,0,0.04)]":"text-ink-2 hover:bg-hover"}`,children:[e?(0,d.jsxs)("span",{className:"relative flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5",children:[(0,d.jsx)("span",{className:`lg:hidden ${k?"text-ink":"text-ink-3 group-hover:text-ink-2"}`,children:c}),(0,d.jsx)("span",{className:`absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-sidebar lg:static lg:h-2 lg:w-2 lg:ring-0 ${C[e]}`})]}):(0,d.jsx)("span",{className:`flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5 ${k?"text-ink":"text-ink-3 group-hover:text-ink-2"}`,children:c}),(0,d.jsx)("span",{className:"flex-1 truncate",children:b}),void 0!==h?(0,d.jsx)("span",{className:"rounded-full bg-err/12 px-2 py-0.5 text-[13px] font-medium text-err lg:px-1.5 lg:py-0 lg:text-[11px]",children:h>99?"99+":h}):void 0!==g&&(0,d.jsx)("span",{className:"font-mono text-[13px] tracking-[0.02em] text-ink-4 lg:text-[11px]",children:g})]})}var E=c(44100);function F({runningAgents:a,throughput:b,fill:c=.36}){if(void 0===a)return null;let e=100*Math.max(0,Math.min(1,c));return(0,d.jsxs)("div",{className:"mx-3 mt-2.5 rounded-[10px] border border-rule-2 bg-paper px-3 pt-2.5 pb-3",children:[(0,d.jsxs)("div",{className:"flex items-center gap-1.5 font-mono text-[11px] uppercase leading-none tracking-[0.14em] text-ink-3",children:[(0,d.jsx)(E.A,{variant:"lime"}),"Live"]}),(0,d.jsxs)("div",{className:"mt-1.5 text-[13px] leading-[1.35] text-ink-2",children:[(0,d.jsxs)("b",{className:"font-semibold text-ink",children:[a," agents"]}),b?` running \xb7 ${b}`:" running"]}),(0,d.jsx)("div",{className:"mt-2.5 h-[3px] overflow-hidden rounded-[2px] bg-black/[0.06] dark:bg-white/[0.06]",children:(0,d.jsx)("i",{className:"block h-full bg-agent-vivid",style:{width:`${e}%`}})})]})}var G=c(48082),H=c(45616),I=c(14199),J=c(9376),K=c(74708),L=c(47092);L.callServer,L.findSourceMapURL;let M="nodal-agents update";function N(){let[a,b]=(0,e.useState)(null),[c,f]=(0,e.useState)(!1);if(!a?.current)return null;let{current:g,latest:h,updateAvailable:i}=a;async function j(){try{await navigator.clipboard.writeText(M),G.oR.success("Command copied")}catch{G.oR.error("Could not copy")}}return(0,d.jsxs)("div",{className:"mx-2 mt-1",children:[i?(0,d.jsxs)("button",{type:"button",onClick:()=>f(!0),className:"flex w-full items-center gap-2 rounded-lg border border-agent-vivid/40 bg-agent-vivid/10 px-2.5 py-1.5 text-left transition-colors hover:bg-agent-vivid/20",children:[(0,d.jsx)(H.S,{size:14,weight:"bold",className:"shrink-0 text-ink-2"}),(0,d.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,d.jsx)("span",{className:"block text-[11.5px] font-medium leading-tight text-ink",children:"Update available"}),(0,d.jsxs)("span",{className:"block font-mono text-[10px] leading-tight text-ink-3",children:["v",g," → v",h]})]})]}):(0,d.jsxs)("div",{className:"flex items-center gap-1.5 px-2.5 py-1 text-ink-4",children:[(0,d.jsx)(I.r,{size:12,className:"shrink-0"}),(0,d.jsxs)("span",{className:"font-mono text-[10.5px]",children:["Nodal v",g]})]}),(0,d.jsx)(K.A,{open:c,onClose:()=>f(!1),title:"Update Nodal-Agents",children:(0,d.jsxs)("div",{className:"space-y-4",children:[(0,d.jsxs)("p",{className:"text-[13px] leading-relaxed text-ink-2",children:["A new version is available — ",(0,d.jsxs)("span",{className:"font-mono text-ink-3",children:["v",g]})," →"," ",(0,d.jsxs)("span",{className:"font-mono font-medium text-ink",children:["v",h]}),". Run this in your terminal, then restart Nodal-Agents:"]}),(0,d.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-rule-2 bg-hover px-3 py-2.5",children:[(0,d.jsx)("code",{className:"flex-1 font-mono text-[13px] text-ink",children:M}),(0,d.jsxs)("button",{type:"button",onClick:j,className:"inline-flex h-[28px] shrink-0 items-center gap-1.5 rounded-md border border-rule-2 bg-paper px-2.5 text-[12px] font-medium text-ink-3 transition-colors hover:text-ink",children:[(0,d.jsx)(J.Q,{size:13})," Copy"]})]}),(0,d.jsxs)("p",{className:"text-[12px] leading-relaxed text-ink-4",children:["On macOS/Linux, prefix with ",(0,d.jsx)("span",{className:"font-mono",children:"sudo"})," if the global install needs elevated permissions."]})]})})]})}var O=c(23586),P=c(42199);function Q({fleets:a,activeId:b,disabled:c,onChange:f,onNewWorkspace:g}){let[h,i]=(0,e.useState)(!1),j=(0,e.useRef)(null),k=a.find(a=>a.id===b)??a[0];return k?(0,d.jsxs)("div",{ref:j,className:"relative mx-3.5 mt-3.5 mb-1",children:[(0,d.jsxs)("button",{type:"button",onClick:()=>!c&&i(a=>!a),"aria-haspopup":"listbox","aria-expanded":h,"aria-disabled":c||void 0,className:`flex h-12 w-full items-center gap-3 rounded-xl border border-rule-2 bg-paper px-3 text-[15px] leading-none text-ink lg:h-[38px] lg:gap-2.5 lg:rounded-[9px] lg:px-2.5 lg:text-[13px] ${c?"cursor-default":"cursor-pointer hover:bg-hover-2/40"}`,children:[(0,d.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md font-mono text-[12px] font-semibold leading-none tracking-[0.04em] text-[#0a0a0a] lg:h-[22px] lg:w-[22px] lg:rounded-[5px] lg:text-[10.5px]",style:{background:k.color},children:k.icon??k.tag.slice(0,2)}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate text-left text-[15px] font-medium text-ink lg:text-[12.5px]",children:k.name}),!c&&(0,d.jsx)(O.a,{size:12,className:"h-4 w-4 shrink-0 text-ink-3 lg:h-3 lg:w-3"})]}),h&&!c&&(0,d.jsxs)("div",{role:"listbox",className:"absolute inset-x-0 top-[calc(100%+6px)] z-30 rounded-[9px] border border-rule-2 bg-paper p-1.5 shadow-[0_12px_32px_rgba(0,0,0,0.10)]",children:[a.map(a=>{let c=a.id===b;return(0,d.jsxs)("div",{role:"option","aria-selected":c,onClick:()=>{f?.(a.id),i(!1)},className:`flex cursor-pointer items-center gap-3 rounded-lg px-2.5 py-2.5 text-[15px] leading-[1.2] text-ink-2 hover:bg-hover lg:gap-2.5 lg:rounded-md lg:px-2 lg:py-1.5 lg:text-[12.5px] ${c?"bg-hover-2":""}`,children:[(0,d.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md font-mono text-[12px] font-semibold leading-none tracking-[0.04em] text-[#0a0a0a] lg:h-5 lg:w-5 lg:rounded-[5px] lg:text-[10px]",style:{background:a.color},children:a.icon??a.tag.slice(0,2)}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium text-ink",children:a.name}),(0,d.jsx)(P.J,{size:12,weight:"bold",className:`h-4 w-4 text-ink lg:h-3 lg:w-3 ${c?"opacity-100":"opacity-0"}`})]},a.id)}),g&&(0,d.jsxs)("button",{type:"button",onClick:()=>{i(!1),g()},className:"mt-1 flex w-full items-center gap-3 rounded-lg border-t border-rule px-2.5 py-2.5 text-[15px] font-medium text-ink-3 transition-colors hover:bg-hover hover:text-ink-2 lg:gap-2 lg:rounded-md lg:px-2 lg:py-1.5 lg:text-[12px]",children:[(0,d.jsx)("span",{className:"flex h-5 w-5 items-center justify-center rounded text-[16px] leading-none lg:h-4 lg:w-4 lg:text-[12px]",children:"+"}),"New workspace"]})]})]}):null}var R=c(69679),S=c(49677),T=c(64609);let U=["#d4ff2e","#74b9ff","#a29bfe","#fd79a8","#55efc4","#fdcb6e","#e17055","#6c5ce7"];function V(a){return{id:a.id,name:a.name,tag:a.name.replace(/[^a-zA-Z0-9]/g,"").slice(0,3).toUpperCase()||"WS",color:function(a){let b=0;for(let c=0;c<a.length;c+=1)b=31*b+a.charCodeAt(c)>>>0;return U[b%U.length]??U[0]}(a.slug),icon:a.icon??void 0}}function W({workspaces:a}){let b=(0,f.useRouter)(),[c,g]=(0,e.useTransition)(),[h,i]=(0,e.useTransition)(),[j,k]=(0,e.useState)(!1),[l,m]=(0,e.useState)(""),[n,o]=(0,e.useState)(R.S[0]),p=(0,e.useRef)(null),q=a.map(V),r=a.find(a=>a.active),s=r?.id??q[0]?.id??"";return(0,d.jsxs)("div",{children:[(0,d.jsx)(Q,{fleets:q,activeId:s,onChange:function(a){a===s||c||g(async()=>{let c=await (0,S.W)({id:a});c.ok?b.refresh():G.oR.error(c.message)})},disabled:c||0===q.length,onNewWorkspace:function(){k(!0),m(""),o(R.S[0]),requestAnimationFrame(()=>p.current?.focus())}}),j&&(0,d.jsxs)("form",{onSubmit:function(a){a.preventDefault();let c=l.trim();c&&i(async()=>{let a=await (0,T.O)({name:c,icon:n});if(!a.ok)return void G.oR.error(a.message);let d=await (0,S.W)({id:a.data.id});d.ok?(k(!1),m(""),G.oR.success(`Workspace "${c}" created`),b.refresh()):G.oR.error(d.message)})},className:"mx-3.5 mt-1 rounded-[9px] border border-rule-2 bg-paper p-2.5",children:[(0,d.jsx)("p",{className:"mb-1.5 font-mono text-[11px] uppercase tracking-[0.1em] text-ink-4",children:"New workspace"}),(0,d.jsx)("div",{className:"mb-2",children:(0,d.jsx)(R.A,{value:n,onChange:o,disabled:h})}),(0,d.jsxs)("div",{className:"flex gap-1.5",children:[(0,d.jsx)("input",{ref:p,type:"text",value:l,onChange:a=>m(a.target.value),placeholder:"Name…",maxLength:60,disabled:h,className:"min-w-0 flex-1 rounded-md border border-rule bg-canvas px-2.5 py-1.5 text-[13px] text-ink placeholder:text-ink-4 focus:border-ink-3 focus:outline-none disabled:opacity-50"}),(0,d.jsx)("button",{type:"submit",disabled:h||!l.trim(),className:"shrink-0 rounded-md bg-ink px-3 py-1.5 text-[13px] font-medium text-canvas hover:brightness-90 disabled:cursor-not-allowed disabled:opacity-50",children:h?"…":"Create"}),(0,d.jsx)("button",{type:"button",onClick:()=>k(!1),disabled:h,className:"shrink-0 rounded-md border border-rule px-2.5 py-1.5 text-[13px] text-ink-3 hover:border-rule-2 hover:text-ink-2 disabled:opacity-50",children:"✕"})]})]})]})}var X=c(43136),Y=c(35245),Z=c(61166);let $=[{section:"Overview",items:[{href:"/",label:"Home",icon:g.t},{href:"/chat",label:"Chat",icon:h.x},{href:"/jobs",label:"Runs",icon:i.T},{href:"/llm-providers",label:"LLM Providers",icon:j.R}]},{section:"Build",items:[{href:"/agents",label:"Agents",icon:k.n,dot:"agent"},{href:"/skills",label:"Skills",icon:l.f,dot:"skill"},{href:"/learned-skills",label:"Learned Skills",icon:m.g},{href:"/connectors",label:"API Connectors",icon:n.F,dot:"conn"},{href:"/mcp",label:"MCP Connectors",icon:o.X,dot:"conn"},{href:"/credentials",label:"Credentials",icon:p.U},{href:"/memories",label:"Memory",icon:q.j}]},{section:"Operate",items:[{href:"/automations",label:"Automation",icon:r.E},{href:"/approvals",label:"Approvals",icon:s.o},{href:"/logs",label:"Logs",icon:t.m}]},{section:"Workspace",items:[{href:"https://discord.gg/7UZsvZPgU",label:"Join Discord",external:!0},{href:"/settings",label:"Settings",icon:u._}]}];function _({workspaces:a,userMenu:b}){let c=(0,f.usePathname)(),[g,h]=(0,e.useState)(!1),{pending:i}=(0,Z.e)(),j=i.length;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("header",{className:"fixed top-0 right-0 left-0 z-40 flex h-16 items-center gap-1 border-b border-rule-2 bg-sidebar px-2 lg:hidden",children:[(0,d.jsx)("button",{type:"button",onClick:()=>h(!0),className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl text-ink-2 transition-colors hover:bg-hover hover:text-ink active:bg-hover","aria-label":"Open menu","aria-controls":"primary-nav","aria-expanded":g,children:(0,d.jsx)(v.B,{size:26})}),(0,d.jsxs)("div",{className:"flex min-w-0 items-center gap-2 pl-1 text-[15px] font-medium tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-md bg-ink font-mono text-[11px] font-semibold text-canvas",children:"N"}),(0,d.jsx)("span",{className:"truncate",children:"Nodal-Agents"})]}),(0,d.jsx)("div",{className:"flex-1"}),(0,d.jsxs)("div",{className:"flex items-center gap-1",children:[(0,d.jsx)(Y.default,{}),(0,d.jsx)(X.default,{})]})]}),(0,d.jsxs)("aside",{id:"primary-nav","aria-label":"Main navigation",className:`fixed top-0 left-0 z-50 flex h-full w-full flex-col border-r border-rule-2 bg-sidebar pt-4 pb-3 transition-transform duration-200 ease-out lg:z-40 lg:w-[244px] lg:translate-x-0 ${g?"translate-x-0":"-translate-x-full"}`,children:[(0,d.jsxs)("div",{className:"flex items-center justify-between px-4 pb-1 lg:hidden",children:[(0,d.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-[16px] font-medium tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-ink font-mono text-[12px] font-semibold text-canvas",children:"N"}),(0,d.jsx)("span",{className:"truncate",children:"Nodal-Agents"})]}),(0,d.jsx)("button",{type:"button",onClick:()=>h(!1),className:"-mr-2 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl text-ink-2 transition-colors hover:bg-hover hover:text-ink active:bg-hover","aria-label":"Close menu",children:(0,d.jsx)(w.X,{size:24})})]}),(0,d.jsx)("div",{className:"hidden lg:block",children:(0,d.jsx)(y,{})}),(0,d.jsx)(W,{workspaces:a??[]}),(0,d.jsx)("nav",{className:"flex flex-1 flex-col overflow-y-auto py-1.5",children:$.map((a,b)=>(0,d.jsxs)("div",{children:[a.section&&(0,d.jsx)(z,{children:a.section}),a.items.map(a=>{var b;return a.external?(0,d.jsxs)("a",{href:a.href,target:"_blank",rel:"noopener noreferrer",className:"group mx-3 flex h-12 items-center gap-3 rounded-xl bg-[#5865F2] px-3 text-[15px] font-medium text-white transition-[filter] hover:brightness-110 lg:h-[30px] lg:gap-2.5 lg:rounded-lg lg:px-3 lg:text-[12.5px] lg:leading-none",children:[(0,d.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5",children:(0,d.jsx)(x.B,{size:20,weight:"bold",className:"h-5 w-5 lg:h-3.5 lg:w-3.5"})}),(0,d.jsx)("span",{className:"flex-1 truncate",children:a.label})]},a.href):(0,d.jsx)(D,{href:a.href,label:a.label,icon:a.icon?(0,d.jsx)(a.icon,{size:20,className:"h-5 w-5 lg:h-3.5 lg:w-3.5"}):void 0,dot:a.dot,count:"/approvals"===a.href?void 0:a.count,pill:"/approvals"===a.href&&j>0?j:void 0,isActive:(b=a.href,"/"===b?"/"===c:c===b||c.startsWith(b+"/"))},a.href)})]},b))}),(0,d.jsx)(N,{}),(0,d.jsx)(F,{runningAgents:void 0}),b&&(0,d.jsx)("div",{className:"mt-2 border-t border-rule-2 px-3 pt-3","data-testid":"user-menu",children:b})]})]})}},36105:()=>{},36770:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>u});var d=c(99386),e=c(66402),f=c(95809),g=c(42112),h=c(62952),i=c(81590),j=c(35675),k=c(44888),l=c(95488),m=c(75224),n=c(97173);async function o(){let a=m._.AUTH_MODE;if("local-trust"===a)return(0,d.jsx)(q,{icon:(0,d.jsx)(i.o,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"}),label:"Local trust",hint:"No auth — single-user install"});if("bearer-token"===a)return(0,d.jsx)(q,{icon:(0,d.jsx)(i.o,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"}),label:"API token"});let b=await p();return b?(0,d.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-rule-2 bg-paper px-3 py-2.5 lg:gap-2 lg:rounded-lg lg:px-2.5 lg:py-2",children:[(0,d.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-hover text-ink-3 lg:h-7 lg:w-7",children:(0,d.jsx)(j.K,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"})}),(0,d.jsx)("div",{className:"min-w-0 flex-1","data-testid":"user-menu-email",children:(0,d.jsx)("p",{className:"truncate text-sm font-medium text-ink lg:text-xs",title:b,children:b})}),(0,d.jsx)(n.default,{})]}):null}async function p(){try{let a=await (0,e.headers)(),b=new Request("http://localhost/",{headers:a}),c=await (0,l.sj)(b),d=await (0,l.Lf)().select({email:k.VV.email}).from(k.VV).where((0,k.eq)(k.VV.id,c.userId)).limit(1);return d[0]?.email??null}catch{return null}}function q({icon:a,label:b,hint:c}){return(0,d.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-rule-2 bg-paper px-3 py-2.5 lg:gap-2 lg:rounded-lg lg:px-2.5 lg:py-2",children:[(0,d.jsx)("div",{className:"shrink-0 text-ok",children:a}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"text-sm font-medium leading-tight text-ink lg:text-xs",children:b}),c&&(0,d.jsx)("p",{className:"mt-0.5 truncate text-[12px] text-ink-3 lg:text-[10px]",children:c})]})]})}var r=c(93690),s=c(81955),t=c(50798);async function u({children:a}){try{let a=await (0,e.headers)(),b=new Request("http://localhost/",{headers:a});await (0,l.sj)(b)}catch(a){throw a instanceof g.lR&&(0,f.redirect)("/login"),a instanceof g.vB&&(0,f.redirect)("/onboarding"),a}let b=await (0,t.dO)();b.ok&&0===b.data.agentCount&&(0,f.redirect)("/onboarding");let c=[],i=await (0,t.zh)();i.ok&&(c=i.data);let j=[],k=await (0,t.By)({status:"pending"});return k.ok&&(j=k.data.map(a=>({id:a.id,jobId:a.jobId,toolName:a.toolName,agentName:a.agentName,toolInput:a.toolInput,requestedAt:a.requestedAt}))),(0,d.jsx)(s.ApprovalsProvider,{initial:j,children:(0,d.jsxs)("div",{className:"flex min-h-screen bg-canvas text-ink",children:[(0,d.jsx)(h.default,{workspaces:c,userMenu:(0,d.jsx)(o,{})}),(0,d.jsx)("main",{className:"flex min-w-0 flex-1 flex-col pt-16 lg:ml-[244px] lg:pt-0",children:(0,d.jsx)("div",{className:"flex-1 overflow-x-hidden",children:a})}),(0,d.jsx)(r.default,{})]})})}},43136:(a,b,c)=>{"use strict";c.d(b,{default:()=>h});var d=c(10476),e=c(64565),f=c(62515),g=c(2447);function h(){let[a,b]=(0,e.useState)("light"),[c,h]=(0,e.useState)(!1),i="dark"===a?f.b:g.A,j="dark"===a?"Switch to light theme":"Switch to dark theme";return(0,d.jsx)("button",{type:"button",onClick:()=>{let c="dark"===a?"light":"dark";document.documentElement.setAttribute("data-theme",c);try{localStorage.setItem("nodal.theme",c)}catch{}b(c)},"aria-label":j,title:j,className:"flex h-[34px] w-[34px] items-center justify-center rounded-md border border-rule-2 bg-paper text-ink-2 transition-colors hover:text-ink",suppressHydrationWarning:!0,children:c?(0,d.jsx)(i,{size:15}):(0,d.jsx)(g.A,{size:15})})}},44100:(a,b,c)=>{"use strict";c.d(b,{A:()=>g});var d=c(10476);let e={ok:"bg-ok",lime:"bg-agent-vivid",coral:"bg-skill-vivid",blue:"bg-conn-vivid"},f={ok:"animate-[blip_1.4s_ease-out_infinite]",lime:"animate-[blip-lime_1.5s_ease-out_infinite]",coral:"animate-[blip-coral_1.4s_ease-out_infinite]",blue:"animate-[blip-blue_1.4s_ease-out_infinite]"};function g({variant:a="ok",size:b="sm",animate:c=!0,className:h=""}){return(0,d.jsx)("span",{className:`inline-block shrink-0 rounded-full ${"sm"===b?"h-[7px] w-[7px]":"h-2 w-2"} ${e[a]} ${c?f[a]:""} ${h}`})}},49269:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>g});var d=c(99386),e=c(85598),f=c.n(e);function g(){return(0,d.jsx)("div",{className:"flex min-h-screen w-full items-center justify-center bg-canvas px-4",children:(0,d.jsxs)("div",{className:"text-center space-y-4",children:[(0,d.jsx)("h1",{className:"text-2xl font-bold text-ink",children:"404 — Page not found"}),(0,d.jsx)("p",{className:"text-sm text-ink-3",children:"This page doesn't exist."}),(0,d.jsx)(f(),{href:"/",className:"inline-block rounded-lg bg-agent-vivid text-canvas px-4 py-2 text-sm font-semibold hover:bg-agent-vivid transition-colors",children:"Go to dashboard"})]})})}},49677:(a,b,c)=>{"use strict";c.d(b,{W:()=>e});var d=c(47092);let e=(0,d.createServerReference)("40a4aa24576354b17648a91aa1f592381a155e25d3",d.callServer,void 0,d.findSourceMapURL,"switchWorkspaceAction")},50798:(a,b,c)=>{"use strict";c.d(b,{ch:()=>d2,iU:()=>er,dd:()=>eM,f_:()=>e8,S2:()=>eh,bN:()=>ek,Cy:()=>dY,Ql:()=>f9,LN:()=>fQ,PD:()=>eD,ML:()=>eq,Jc:()=>eN,AS:()=>fw,Ev:()=>e1,Og:()=>dN,rT:()=>dZ,hP:()=>eA,xV:()=>ga,Mo:()=>fT,hl:()=>eJ,t3:()=>ew,X1:()=>fB,TD:()=>e2,Hp:()=>dS,z_:()=>d9,P7:()=>el,Hl:()=>fx,VZ:()=>fq,g$:()=>fe,Ro:()=>ea,lV:()=>ej,UR:()=>ge,bm:()=>fp,dO:()=>fm,dS:()=>fZ,rf:()=>ee,_N:()=>ef,GY:()=>eY,gE:()=>eG,M3:()=>fG,JD:()=>f4,aG:()=>f_,WD:()=>f2,oA:()=>fD,cj:()=>fr,cu:()=>fc,Hu:()=>ft,$4:()=>fo,jj:()=>dQ,kh:()=>e4,wI:()=>eT,iu:()=>fY,Ko:()=>dW,ei:()=>eK,Sh:()=>d1,$z:()=>dV,By:()=>eQ,ZA:()=>gb,Le:()=>ex,BO:()=>f8,ND:()=>ed,Jb:()=>ec,Wq:()=>fX,oG:()=>fP,pD:()=>eB,y4:()=>en,Hy:()=>fu,EA:()=>e7,$5:()=>e_,c6:()=>fk,Zz:()=>fl,vu:()=>d8,zh:()=>dM,PH:()=>d3,yU:()=>eO,qo:()=>eE,oC:()=>dP,Ke:()=>dX,JH:()=>fb,CV:()=>eS,HO:()=>fC,cr:()=>ez,KI:()=>eo,WH:()=>gd,e4:()=>eb,p5:()=>eV,AH:()=>f3,wj:()=>eL,FS:()=>f$,Ir:()=>e$,Ru:()=>fS,Sb:()=>f6,mJ:()=>eX,lg:()=>fi,LW:()=>fg,tS:()=>dR,D5:()=>dO,fl:()=>fW,eP:()=>fA,ZG:()=>ev,_x:()=>fd,bV:()=>e5,E4:()=>eu,fG:()=>d0,pu:()=>fF,dl:()=>eP,QT:()=>fR,c2:()=>eF,f2:()=>eI,PC:()=>et,rv:()=>fI,Hq:()=>f1,fI:()=>fz,Rz:()=>fa,Oc:()=>d7});var d=c(43607),e=c(87388),f=c(66402),g=c(61989),h=c(51455),i=c(76760),j=c(48161),k=c(73136),l=c(77598),m=c(44888);class n extends Error{constructor(a,b){super(b??a),this.name="DeliveryError",this.code=a}}async function o(a,b,c,d,e=1e4){let f,g=`https://api.telegram.org/bot${a}/${b}`,h=new AbortController,i=setTimeout(()=>h.abort(),e);d?.addEventListener("abort",()=>h.abort(),{once:!0});try{f=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json"},body:void 0!==c?JSON.stringify(c):"{}",signal:h.signal})}catch(c){if(c instanceof Error&&"AbortError"===c.name)throw new n("telegram_request_failed",`telegram_timeout: Telegram API did not respond within ${e/1e3}s`);let b=String(c.message??c).replaceAll(a,"[REDACTED]");throw new n("telegram_request_failed",`telegram_request_failed: network error: ${b}`)}finally{clearTimeout(i)}let j=await f.json().catch(()=>({}));if(!f.ok||!j.ok){let a=j.description??"";if(401===f.status||404===f.status)throw new n("telegram_invalid_token",`telegram_invalid_token: ${a}`);throw new n("telegram_request_failed",`telegram_request_failed: ${a}`)}if(void 0===j.result)throw new n("telegram_request_failed","telegram_request_failed: no result in response");return j.result}async function p(a){let b=await o(a,"getMe");return{id:b.id,username:b.username,firstName:b.first_name,canJoinGroups:b.can_join_groups??!1,canReadAllGroupMessages:b.can_read_all_group_messages??!1}}async function q(a){let b=a.timeout??25,c={offset:a.offset,timeout:b,allowed_updates:["message","callback_query"]};void 0!==a.limit&&(c.limit=a.limit);let d=1e3*b+5e3;return await o(a.botToken,"getUpdates",c,a.signal,d)}class r extends Error{constructor(a,b,c){super(b),this.name="MemoryError",this.code=a,void 0!==c&&(this.cause=c)}}class s extends r{constructor(a){super("MEMORY_NOT_FOUND",`memory.not_found:${a}`),this.name="MemoryNotFoundError"}}class t extends r{constructor(a,b){super("MEMORY_SANITATION",`memory.sanitation_blocked:${a}`),this.name="MemorySanitationError",this.threatId=a,this.detail=b}}class u extends r{constructor(a){super("MEMORY_DUPLICATE",`memory.duplicate:${a}`),this.name="MemoryDuplicateError",this.existingId=a}}var v=c(64190);let w=[[/ignore\s+(previous|all|above|prior)(\s+\w+)?\s+instructions/i,"prompt_injection"],[/you\s+are\s+now\s+/i,"role_hijack"],[/do\s+not\s+tell\s+the\s+user/i,"deception_hide"],[/system\s+prompt\s+override/i,"sys_prompt_override"],[/disregard\s+(your|all|any)\s+(instructions|rules|guidelines)/i,"disregard_rules"],[/act\s+as\s+(if|though)\s+you\s+(have\s+no|don't\s+have)\s+(restrictions|limits|rules)/i,"bypass_restrictions"],[/curl\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i,"exfil_curl"],[/wget\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i,"exfil_wget"],[/cat\s+[^\n]*(\.env|credentials|\.netrc|\.pgpass|\.npmrc|\.pypirc)/i,"read_secrets"],[/authorized_keys/i,"ssh_backdoor"],[/(\$HOME|~)\/\.ssh/i,"ssh_access"],[/(\$HOME|~)\/\.nodalai\/(\.env|secrets\.key)/i,"nodalai_secrets"]],x=["​","‌","‍","⁠","\uFEFF","‪","‫","‬","‭","‮"];async function y(a,b,c){let d=v.r_.parse(b);var e,f=d.fact;if(f.length>5e3)throw new t("too_long",`Memory fact exceeds 5000 characters (${f.length}).`);for(let a of x)if(f.includes(a)){let b=a.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")??"????";throw new t("invisible_unicode",`Memory fact contains invisible unicode character U+${b} (possible injection).`)}for(let[a,b]of w)if(a.test(f))throw new t(b,`Memory fact matches threat pattern '${b}'. Memory entries are injected into the system prompt and must not contain injection or exfiltration payloads.`);let g=(e=d.fact,(0,l.createHash)("sha256").update(e.toLowerCase().trim().replace(/\s+/g," ")).digest("hex"));if(d.entity_id){let b=await a.select({id:m.RK.id}).from(m.RK).where((0,m.Uo)((0,m.eq)(m.RK.entityId,d.entity_id),(0,m.eq)(m.RK.factHash,g),(0,m.eq)(m.RK.archived,!1))).limit(1);if(b[0])throw new u(b[0].id)}let h=null;c&&(h=await c.embed(d.fact));let i=(await a.insert(m.RK).values({entityId:d.entity_id??null,agentId:d.agent_id??null,fact:d.fact,category:d.category,importance:d.importance,source:d.source,skillTags:d.skill_tags,memoryLayer:d.memory_layer??null,factHash:g,embedding:h}).returning())[0];if(!i)throw Error("memory.create_failed");return B(i)}async function z(a,b,c,d){let e={updatedAt:new Date};void 0!==d.fact&&(e.fact=d.fact),void 0!==d.category&&(e.category=d.category),void 0!==d.importance&&(e.importance=d.importance),void 0!==d.importance_locked&&(e.importanceLocked=d.importance_locked),void 0!==d.skill_tags&&(e.skillTags=d.skill_tags),void 0!==d.archived&&(e.archived=d.archived),void 0!==d.valid_to&&(e.validTo=d.valid_to?new Date(d.valid_to):null);let f=(await a.update(m.RK).set(e).where((0,m.Uo)((0,m.eq)(m.RK.id,b),(0,m.eq)(m.RK.entityId,c))).returning())[0];if(!f)throw new s(b);return B(f)}async function A(a,b,c){if(0===(await a.delete(m.RK).where((0,m.Uo)((0,m.eq)(m.RK.id,b),(0,m.eq)(m.RK.entityId,c))).returning()).length)throw new s(b)}function B(a){return{id:a.id,entity_id:a.entityId??null,agent_id:a.agentId??null,fact:a.fact,category:a.category??"context",importance:a.importance??3,source:a.source??"agent",skill_tags:a.skillTags??[],memory_layer:a.memoryLayer??null,valid_from:a.validFrom?.toISOString()??null,valid_to:a.validTo?.toISOString()??null,fact_hash:a.factHash??null,archived:a.archived??!1,importance_locked:a.importanceLocked??!1,last_accessed_at:a.lastAccessedAt?.toISOString()??null,access_count:a.accessCount??0,created_at:a.createdAt?.toISOString()??new Date().toISOString(),updated_at:a.updatedAt?.toISOString()??new Date().toISOString()}}async function C(a,b){var c;let d,e,{entityId:f}=b;if(!f)throw new r("INVALID_ENTITY","memory.list.entity_id_required");let g=b.page??1,h=g<=0?1:g,i=Math.min(Math.max(1,b.pageSize??50),200),j=(h-1)*i,k=(c=b,d=[(0,m.eq)(m.RK.entityId,c.entityId),(0,m.eq)(m.RK.archived,c.archived??!1)],c.agentId&&d.push((0,m.eq)(m.RK.agentId,c.agentId)),c.category&&d.push((0,m.eq)(m.RK.category,c.category)),c.tags&&c.tags.length>0&&d.push((0,m.ll)`${m.RK.skillTags} && ${m.ll.raw((e=c.tags.map(a=>`'${a.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`).join(","),`ARRAY[${e}]`))}::text[]`),(0,m.Uo)(...d)),l=function(a="recent"){switch(a){case"importance":return(0,m.i8)(m.RK.importance);case"last_accessed":return(0,m.i8)(m.RK.lastAccessedAt);default:return(0,m.i8)(m.RK.updatedAt)}}(b.sort),n=await a.select({count:(0,m.ll)`count(*)`}).from(m.RK).where(k),o=Number(n[0]?.count??0),p=(await a.select().from(m.RK).where(k).orderBy(l).limit(i).offset(j)).map(a=>B(a));return{items:p,page:h,pageSize:i,totalCount:o,hasMore:j+p.length<o}}async function D(a,b,c){await a.update(m.RK).set({lastAccessedAt:(0,m.ll)`now()`,accessCount:(0,m.ll)`${m.RK.accessCount} + 1`}).where((0,m.Uo)((0,m.eq)(m.RK.id,b),(0,m.eq)(m.RK.entityId,c)))}async function E(a,b,c){0!==b.length&&await Promise.allSettled(b.map(b=>D(a,b,c)))}async function F(a,b,c,d="importance"){let{entityId:e,agentId:f,skillTags:g,category:h,limit:i}=c,j=b.replace(/[^\w\s]/g," ").split(/\s+/).filter(a=>a.length>2).slice(0,8).map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).filter(a=>a.length>0),k=function(a){let{entityId:b,agentId:c,skillTags:d,category:e}=a,f=[(0,m.eq)(m.RK.entityId,b),(0,m.eq)(m.RK.archived,!1)];if(c&&f.push((0,m.eq)(m.RK.agentId,c)),e&&f.push((0,m.eq)(m.RK.category,e)),d&&d.length>0){let a,b=(a=d.map(a=>`'${a.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`).join(","),`ARRAY[${a}]`);f.push((0,m.ll)`(
2
- ${m.RK.skillTags} = '{}'::text[]
3
- OR ${m.RK.skillTags} IS NULL
4
- OR ${m.RK.skillTags} && ${m.ll.raw(b)}::text[]
5
- )`)}return f}({entityId:e,agentId:f,skillTags:g,category:h}),l="recent"===d?[(0,m.i8)(m.RK.updatedAt),(0,m.i8)(m.RK.importance)]:[(0,m.i8)(m.RK.importance),(0,m.i8)(m.RK.updatedAt)];if(j.length>0){let b=(0,m.ll)`"agent_memory"."search_tsv"`,c=(0,m.ll)`to_tsquery('english', ${j.join(" | ")})`;return await a.select().from(m.RK).where((0,m.Uo)(...k,(0,m.ll)`${b} @@ ${c}`)).orderBy((0,m.ll)`ts_rank(${b}, ${c}) DESC`,...l).limit(i)}return await a.select().from(m.RK).where((0,m.Uo)(...k)).orderBy(...l).limit(i)}async function G(a,b){let{query:c,entityId:d,agentId:e,skillTags:f,category:g,limit:h=10,sort:i="importance",touch:j=!0}=b,k=(await F(a,c,{entityId:d,agentId:e,skillTags:f,category:g,limit:h},i)).map(a=>B(a));return j&&k.length>0&&await E(a,k.map(a=>a.id),d),k}let H=new Set(["the","and","for","are","was","were","but","not","you","your","his","her","its","our","their","this","that","these","those","with","from","into","out","can","could","will","would","should","shall","may","might","must","has","have","had","been","being","then","than","them","they","what","when","where","which","who","why","how","all","any","some","such","only","too","very","just","also","per","via","about","les","des","une","est","\xe9t\xe9","pour","avec","dans","par","sur","que","qui","quoi","dont","pas","plus","mais","son","ses","mes","tes","nos","vos","leur","leurs","mon","ton","cette","ces","cet","aux","vers","chez","sans","sous","entre","tout","tous","toute","comme","donc","alors","ainsi","une","deux","ce","la","le"]);function I(a){if(!a)return[];let b=new Set;for(let c of a.toLowerCase().split(/[^\p{L}\p{N}]+/u))c.length>2&&!H.has(c)&&b.add(c);return[...b]}function J(a,b){if(b<=0)return[];let c=[],d=0;for(let e of a){let a=e.fact.length+20;d+a>b||(c.push(e),d+=a)}return c}async function K(a,b){if(b.maxChars<=0)return[];let c=(0,m.Uo)((0,m.eq)(m.RK.entityId,b.entityId),(0,m.eq)(m.RK.archived,!1),(0,m.ll)`(${m.RK.validTo} IS NULL OR ${m.RK.validTo} > now())`),d=b.query??"";if(I(d).length>0){let e=(0,m.ll)`"agent_memory"."search_tsv"`,f=(0,m.ll)`plainto_tsquery('english', ${d})`;return J((await a.select().from(m.RK).where(c).orderBy((0,m.ll)`ts_rank(${e}, ${f}) DESC`,(0,m.i8)(m.RK.importance),(0,m.i8)(m.RK.lastAccessedAt)).limit(200)).map(a=>B(a)),b.maxChars)}return function(a,b,c){if(b<=0)return[];let d=I(c),e=a=>a.importance+2*Math.min(function(a,b){if(0===b.length)return 0;let c=a.toLowerCase(),d=0;for(let a of b)c.includes(a)&&d++;return d}(a.fact,d),2);return J([...a].sort((a,b)=>{let c=e(b),d=e(a);if(c!==d)return c-d;let f=a.last_accessed_at??a.created_at,g=b.last_accessed_at??b.created_at;return f!==g?g.localeCompare(f):a.id.localeCompare(b.id)}),b)}((await a.select().from(m.RK).where(c).orderBy((0,m.i8)(m.RK.importance),(0,m.i8)(m.RK.lastAccessedAt)).limit(200)).map(a=>B(a)),b.maxChars,b.query)}var L=c(98472),M=c(38496);class N extends Error{constructor(a,b,c){super(b),this.name="NotionAdapterError",this.code=a,this.status=c}}function O(a){if(a instanceof M.APIResponseError){let b,c=a.status;switch(c){case 400:b="notion_validation_error";break;case 401:b="notion_unauthorized";break;case 403:b="notion_forbidden";break;case 404:b="notion_not_found";break;case 409:b="notion_conflict";break;case 429:b="notion_rate_limited";break;case 503:b="notion_service_unavailable";break;default:b="notion_unknown"}return new N(b,a.message,c)}return a instanceof Error?new N("notion_unknown",a.message):new N("notion_unknown",String(a))}function P(a,b){let c=null==a?"":String(a);if(!c)return[{type:"text",text:{content:""}}];let d=[],e=[],f=0;for(let a of c){let c=a.codePointAt(0)>65535?2:1;if(f+c>2e3){let g={type:"text",text:{content:e.join("")}};b&&(g.annotations=b),d.push(g),e.length=0,e.push(a),f=c}else e.push(a),f+=c}if(e.length>0){let a={type:"text",text:{content:e.join("")}};b&&(a.annotations=b),d.push(a)}return d}function Q(a){let b=a.type;if("title"===b)return(a.title??[]).map(a=>a.plain_text).join("");if("rich_text"===b)return(a.rich_text??[]).map(a=>a.plain_text).join("");if("select"===b){let b=a.select;return b?.name??""}if("multi_select"===b)return(a.multi_select??[]).map(a=>a.name).join(", ");if("status"===b){let b=a.status;return b?.name??""}if("number"===b||"checkbox"===b||"url"===b||"email"===b||"phone_number"===b){let c=a[b];return null!=c?String(c):""}if("date"===b){let b=a.date;return b?b.end?`${b.start} → ${b.end}`:b.start:""}if("relation"===b)return(a.relation??[]).map(a=>a.id).join(", ");if("formula"===b){let b=a.formula;return b?String(b[b.type]??""):""}if("rollup"===b){let b=a.rollup;return b?String(b[b.type]??""):""}return"people"===b?(a.people??[]).map(a=>a.name??a.id).join(", "):"created_time"===b?String(a.created_time??""):"last_edited_time"===b?String(a.last_edited_time??""):""}function R(a,b,c){let d=c?.[a]?.type;switch(d||("boolean"==typeof b?"checkbox":"number"==typeof b?"number":"string"==typeof b&&b.startsWith("http")?"url":"rich_text")){case"title":return{title:P(String(b??""))};case"rich_text":default:return{rich_text:P(String(b??""))};case"number":{let a=Number(b);return isNaN(a)?{rich_text:P(String(b))}:{number:a}}case"checkbox":return{checkbox:!!b};case"url":return{url:null!=b?String(b).slice(0,2e3):null};case"select":return{select:{name:String(b).slice(0,100)}};case"multi_select":return{multi_select:(Array.isArray(b)?b:String(b).split(",")).map(a=>({name:String(a).trim().slice(0,100)}))};case"date":return{date:{start:String(b)}};case"email":return{email:String(b)};case"phone_number":return{phone_number:String(b)}}}function S(a){for(let b of Object.values(a.properties??{}))if("title"===b.type)return(b.title??[]).map(a=>a.plain_text).join("");let b=a.title;return Array.isArray(b)?b.map(a=>a.plain_text).join(""):"(untitled)"}let T=g.Ik({query:g.Yj().describe("Text to search for in page and database titles."),limit:g.ai().int().min(1).max(100).optional().default(10).describe("Max results to return (1–100, default 10)."),filter_type:g.k5(["page","database"]).optional().describe("Optional: restrict results to pages or databases only.")});async function U(a,b=100,c=500){let d,e=[];for(let f=0;f<20;f++){let f=await a(d,Math.min(b,100));if(e.push(...f.results),e.length>=c||!f.has_more||!f.next_cursor)break;d=f.next_cursor}return e.slice(0,c)}async function V(a,b,c=300){return U(async(c,d)=>{let e=await a.blocks.children.list({block_id:b,start_cursor:c,page_size:d});return{results:e.results.filter(a=>"block"===a.object),has_more:e.has_more,next_cursor:e.next_cursor}},100,c)}function W(a){return a.map(a=>a.plain_text).join("")}function X(a){switch(a.type){case"paragraph":return W(a.paragraph.rich_text);case"heading_1":return`# ${W(a.heading_1.rich_text)}`;case"heading_2":return`## ${W(a.heading_2.rich_text)}`;case"heading_3":return`### ${W(a.heading_3.rich_text)}`;case"bulleted_list_item":return`- ${W(a.bulleted_list_item.rich_text)}`;case"numbered_list_item":return`1. ${W(a.numbered_list_item.rich_text)}`;case"to_do":{let b=a.to_do.checked;return`[${b?"x":" "}] ${W(a.to_do.rich_text)}`}case"code":{let b=a.code.language,c=W(a.code.rich_text);return`\`\`\`${b}
1
+ exports.id=2713,exports.ids=[2713],exports.modules={3808:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(1887),f=c(64565);function g({placeholder:a="Search agents, skills, runs…",keyboardShortcut:b=!0,onSubmit:c,className:h=""}){let i=(0,f.useRef)(null);return(0,d.jsxs)("form",{onSubmit:a=>{a.preventDefault(),c?.(i.current?.value??"")},className:`flex h-[34px] min-w-[280px] items-center gap-2 rounded-md border border-rule-2 bg-paper px-3 text-[13px] text-ink-4 ${h}`,children:[(0,d.jsx)(e.e,{size:13,className:"shrink-0"}),(0,d.jsx)("input",{ref:i,type:"search",placeholder:a,className:"flex-1 border-0 bg-transparent text-[14px] leading-none text-ink outline-none placeholder:text-ink-4"}),(0,d.jsx)("span",{className:"rounded-[5px] border border-rule bg-black/5 px-1.5 py-[1px] font-mono text-[12px] leading-none text-ink-4 dark:bg-white/[0.06]",children:"/"})]})}},4112:(a,b,c)=>{"use strict";c.d(b,{O:()=>e});var d=c(47092);let e=(0,d.createServerReference)("407c0c65975bbce8f37884b7f13cbd9fc7d01702a6",d.callServer,void 0,d.findSourceMapURL,"createWorkspaceAction")},6833:(a,b,c)=>{"use strict";c.d(b,{ApprovalsProvider:()=>i,e:()=>k});var d=c(10476),e=c(64565),f=c(47092);let g=(0,f.createServerReference)("4097f6d231fec2cd16168a9412d1b68b03b108fe6a",f.callServer,void 0,f.findSourceMapURL,"listApprovalsAction"),h=(0,e.createContext)(null);function i({initial:a,children:b}){let[c,f]=(0,e.useState)(a),j=(0,e.useCallback)(async()=>{let a=await g({status:"pending"});a.ok&&f(a.data.map(a=>({id:a.id,jobId:a.jobId,toolName:a.toolName,agentName:a.agentName,toolInput:a.toolInput,requestedAt:a.requestedAt})))},[]),k=(0,e.useCallback)(()=>{j()},[j]);return(0,d.jsx)(h.Provider,{value:{pending:c,refresh:k},children:b})}let j={pending:[],refresh:()=>{}};function k(){let a=(0,e.useContext)(h);return a||(console.warn("[useApprovals] called outside <ApprovalsProvider> — returning empty state."),j)}},7316:(a,b,c)=>{Promise.resolve().then(c.bind(c,55053))},11405:a=>{function b(a){return Promise.resolve().then(()=>{var b=Error("Cannot find module '"+a+"'");throw b.code="MODULE_NOT_FOUND",b})}b.keys=()=>[],b.resolve=b,b.id=11405,a.exports=b},17030:(a,b,c)=>{"use strict";c.d(b,{Y:()=>d.YT});var d=c(98648)},19259:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,67448,23)),Promise.resolve().then(c.t.bind(c,2667,23)),Promise.resolve().then(c.t.bind(c,10903,23)),Promise.resolve().then(c.t.bind(c,11162,23)),Promise.resolve().then(c.t.bind(c,23838,23)),Promise.resolve().then(c.t.bind(c,83466,23)),Promise.resolve().then(c.t.bind(c,12127,23)),Promise.resolve().then(c.bind(c,26698))},28659:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(64565),f=c(44625);function g(){let[a,b]=(0,e.useState)(!1);async function c(){b(!0);try{let a=await fetch("/api/auth/sign-out",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",credentials:"same-origin"});a.ok||console.error("sign-out failed",a.status,await a.text().catch(()=>""))}catch(a){console.error("sign-out network error",a)}window.location.replace("/login")}return(0,d.jsx)("button",{type:"button",onClick:c,disabled:a,"data-testid":"user-menu-sign-out","aria-label":"Sign out",title:"Sign out",className:"inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-ink-3 transition-colors hover:bg-hover hover:text-ink disabled:cursor-not-allowed disabled:opacity-40 lg:h-8 lg:w-8 lg:rounded-md",children:(0,d.jsx)(f.M,{size:15,className:"h-[18px] w-[18px] lg:h-[15px] lg:w-[15px]"})})}},35245:(a,b,c)=>{"use strict";c.d(b,{default:()=>n});var d=c(10476),e=c(64565),f=c(88831),g=c.n(f),h=c(9599),i=c(48082),j=c(84807),k=c(6833);function l({item:a,onApproved:b}){let[c,f]=(0,e.useTransition)();return(0,d.jsx)("button",{type:"button",onClick:c=>{c.preventDefault(),c.stopPropagation(),f(async()=>{let c=await (0,j.C)({approvalRequestId:a.id,decision:"approve"});c.ok?(i.oR.success("Approved"),b()):i.oR.error(c.message)})},disabled:c,className:"shrink-0 rounded-md bg-ok px-2.5 py-1 text-[12px] font-semibold text-canvas transition-[filter] hover:brightness-[0.92] disabled:opacity-40",children:c?"…":"Approve"})}function m({items:a,onClose:b,onApproved:c}){let f=(0,e.useRef)(null);return(0,d.jsxs)("div",{ref:f,className:"absolute right-0 top-full z-50 mt-1.5 w-[340px] rounded-xl border border-rule-2 bg-paper shadow-lg",role:"dialog","aria-label":"Pending approvals",children:[(0,d.jsx)("div",{className:"border-b border-rule-2 px-4 py-3",children:(0,d.jsxs)("p",{className:"text-[14px] font-semibold text-ink",children:["Pending approvals (",a.length,")"]})}),0===a.length?(0,d.jsx)("p",{className:"px-4 py-5 text-center text-[13px] text-ink-3",children:"No pending approvals."}):(0,d.jsx)("ul",{className:"max-h-[340px] divide-y divide-rule-2 overflow-y-auto",children:a.map(a=>(0,d.jsx)("li",{children:(0,d.jsxs)(g(),{href:`/jobs/${a.jobId}`,onClick:b,className:"flex items-start gap-3 px-4 py-3 transition-colors hover:bg-hover",children:[(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsxs)("p",{className:"truncate text-[13px] font-medium text-ink",children:[a.agentName??"Agent",(0,d.jsx)("span",{className:"mx-1 text-ink-4",children:"\xb7"}),(0,d.jsx)("code",{className:"rounded bg-canvas px-1 py-0.5 font-mono text-[12px] text-ink-2",children:a.toolName})]}),(0,d.jsx)("p",{className:"mt-0.5 truncate text-[12px] text-ink-3",children:function(a){if(!a)return"—";if("string"==typeof a.purpose&&a.purpose.trim()){let b=a.purpose.trim();return b.length>80?b.slice(0,77)+"…":b}if("string"==typeof a.command){let b=a.command;return b.length>60?b.slice(0,57)+"…":b}let b=JSON.stringify(a);return b.length>60?b.slice(0,57)+"…":b}(a.toolInput)}),(0,d.jsx)("p",{className:"mt-0.5 text-[11px] text-ink-4",children:function(a){if(!a)return"—";let b=Math.floor((Date.now()-new Date(a).getTime())/1e3);if(b<60)return`${b}s ago`;let c=Math.floor(b/60);if(c<60)return`${c}m ago`;let d=Math.floor(c/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}(a.requestedAt)})]}),(0,d.jsx)(l,{item:a,onApproved:c})]})},a.id))}),(0,d.jsx)("div",{className:"border-t border-rule-2 px-4 py-2.5",children:(0,d.jsx)(g(),{href:"/approvals",onClick:b,className:"text-[13px] font-medium text-ink-2 transition-colors hover:text-ink",children:"See all approvals →"})})]})}function n(){let{pending:a,refresh:b}=(0,k.e)(),[c,f]=(0,e.useState)(!1),g=(0,e.useRef)(null),i=a.length,j=(0,e.useCallback)(()=>f(!1),[]),l=(0,e.useCallback)(()=>f(a=>!a),[]),n=(0,e.useCallback)(()=>{b()},[b]);return(0,d.jsxs)("div",{ref:g,className:"relative",children:[(0,d.jsxs)("button",{type:"button","aria-label":"Notifications",title:"Notifications",onClick:l,className:"relative flex h-[34px] w-[34px] shrink-0 items-center justify-center rounded-md border border-rule-2 bg-paper text-ink-2 transition-colors hover:text-ink",children:[(0,d.jsx)(h.I,{size:15}),i>0&&(0,d.jsx)("span",{className:"absolute -top-1 -right-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-err px-1 text-[11px] font-bold leading-none text-canvas",children:i>99?"99+":i})]}),c&&(0,d.jsx)(m,{items:a,onClose:j,onApproved:n})]})}},36105:()=>{},36143:(a,b,c)=>{"use strict";c.d(b,{W:()=>e});var d=c(47092);let e=(0,d.createServerReference)("40397bed6f0cf2b3ba461e8e47ec7d4b6880ea452c",d.callServer,void 0,d.findSourceMapURL,"switchWorkspaceAction")},36770:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>u});var d=c(99386),e=c(66402),f=c(95809),g=c(57638),h=c(62952),i=c(81590),j=c(35675),k=c(69747),l=c(95488),m=c(75224),n=c(97173);async function o(){let a=m._.AUTH_MODE;if("local-trust"===a)return(0,d.jsx)(q,{icon:(0,d.jsx)(i.o,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"}),label:"Local trust",hint:"No auth — single-user install"});if("bearer-token"===a)return(0,d.jsx)(q,{icon:(0,d.jsx)(i.o,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"}),label:"API token"});let b=await p();return b?(0,d.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-rule-2 bg-paper px-3 py-2.5 lg:gap-2 lg:rounded-lg lg:px-2.5 lg:py-2",children:[(0,d.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-hover text-ink-3 lg:h-7 lg:w-7",children:(0,d.jsx)(j.K,{weight:"fill",className:"h-[18px] w-[18px] lg:h-[13px] lg:w-[13px]"})}),(0,d.jsx)("div",{className:"min-w-0 flex-1","data-testid":"user-menu-email",children:(0,d.jsx)("p",{className:"truncate text-sm font-medium text-ink lg:text-xs",title:b,children:b})}),(0,d.jsx)(n.default,{})]}):null}async function p(){try{let a=await (0,e.headers)(),b=new Request("http://localhost/",{headers:a}),c=await (0,l.sj)(b),d=await (0,l.Lf)().select({email:k.VV.email}).from(k.VV).where((0,k.eq)(k.VV.id,c.userId)).limit(1);return d[0]?.email??null}catch{return null}}function q({icon:a,label:b,hint:c}){return(0,d.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-rule-2 bg-paper px-3 py-2.5 lg:gap-2 lg:rounded-lg lg:px-2.5 lg:py-2",children:[(0,d.jsx)("div",{className:"shrink-0 text-ok",children:a}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"text-sm font-medium leading-tight text-ink lg:text-xs",children:b}),c&&(0,d.jsx)("p",{className:"mt-0.5 truncate text-[12px] text-ink-3 lg:text-[10px]",children:c})]})]})}var r=c(93690),s=c(81955),t=c(63245);async function u({children:a}){try{let a=await (0,e.headers)(),b=new Request("http://localhost/",{headers:a});await (0,l.sj)(b)}catch(a){throw a instanceof g.lR&&(0,f.redirect)("/login"),a instanceof g.vB&&(0,f.redirect)("/onboarding"),a}let b=await (0,t.dO)();b.ok&&0===b.data.agentCount&&(0,f.redirect)("/onboarding");let c=[],i=await (0,t.zh)();i.ok&&(c=i.data);let j=[],k=await (0,t.By)({status:"pending"});return k.ok&&(j=k.data.map(a=>({id:a.id,jobId:a.jobId,toolName:a.toolName,agentName:a.agentName,toolInput:a.toolInput,requestedAt:a.requestedAt}))),(0,d.jsx)(s.ApprovalsProvider,{initial:j,children:(0,d.jsxs)("div",{className:"flex min-h-screen bg-canvas text-ink",children:[(0,d.jsx)(h.default,{workspaces:c,userMenu:(0,d.jsx)(o,{})}),(0,d.jsx)("main",{className:"flex min-w-0 flex-1 flex-col pt-16 lg:ml-[244px] lg:pt-0",children:(0,d.jsx)("div",{className:"flex-1 overflow-x-hidden",children:a})}),(0,d.jsx)(r.default,{})]})})}},43136:(a,b,c)=>{"use strict";c.d(b,{default:()=>h});var d=c(10476),e=c(64565),f=c(62515),g=c(2447);function h(){let[a,b]=(0,e.useState)("light"),[c,h]=(0,e.useState)(!1),i="dark"===a?f.b:g.A,j="dark"===a?"Switch to light theme":"Switch to dark theme";return(0,d.jsx)("button",{type:"button",onClick:()=>{let c="dark"===a?"light":"dark";document.documentElement.setAttribute("data-theme",c);try{localStorage.setItem("nodal.theme",c)}catch{}b(c)},"aria-label":j,title:j,className:"flex h-[34px] w-[34px] items-center justify-center rounded-md border border-rule-2 bg-paper text-ink-2 transition-colors hover:text-ink",suppressHydrationWarning:!0,children:c?(0,d.jsx)(i,{size:15}):(0,d.jsx)(g.A,{size:15})})}},44100:(a,b,c)=>{"use strict";c.d(b,{A:()=>g});var d=c(10476);let e={ok:"bg-ok",lime:"bg-agent-vivid",coral:"bg-skill-vivid",blue:"bg-conn-vivid"},f={ok:"animate-[blip_1.4s_ease-out_infinite]",lime:"animate-[blip-lime_1.5s_ease-out_infinite]",coral:"animate-[blip-coral_1.4s_ease-out_infinite]",blue:"animate-[blip-blue_1.4s_ease-out_infinite]"};function g({variant:a="ok",size:b="sm",animate:c=!0,className:h=""}){return(0,d.jsx)("span",{className:`inline-block shrink-0 rounded-full ${"sm"===b?"h-[7px] w-[7px]":"h-2 w-2"} ${e[a]} ${c?f[a]:""} ${h}`})}},49269:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>g});var d=c(99386),e=c(85598),f=c.n(e);function g(){return(0,d.jsx)("div",{className:"flex min-h-screen w-full items-center justify-center bg-canvas px-4",children:(0,d.jsxs)("div",{className:"text-center space-y-4",children:[(0,d.jsx)("h1",{className:"text-2xl font-bold text-ink",children:"404 — Page not found"}),(0,d.jsx)("p",{className:"text-sm text-ink-3",children:"This page doesn't exist."}),(0,d.jsx)(f(),{href:"/",className:"inline-block rounded-lg bg-agent-vivid text-canvas px-4 py-2 text-sm font-semibold hover:bg-agent-vivid transition-colors",children:"Go to dashboard"})]})})}},54580:(a,b,c)=>{Promise.resolve().then(c.bind(c,84327))},54620:()=>{},54792:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,61186,23)),Promise.resolve().then(c.t.bind(c,6621,23)),Promise.resolve().then(c.t.bind(c,41837,23)),Promise.resolve().then(c.t.bind(c,85060,23)),Promise.resolve().then(c.t.bind(c,43484,23)),Promise.resolve().then(c.t.bind(c,8376,23)),Promise.resolve().then(c.t.bind(c,74625,23)),Promise.resolve().then(c.t.bind(c,51080,23))},55053:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>e});var d=c(10476);function e({error:a,reset:b}){return(0,d.jsx)("div",{className:"flex min-h-screen w-full items-center justify-center bg-canvas px-4",children:(0,d.jsxs)("div",{className:"max-w-sm space-y-4 text-center",children:[(0,d.jsx)("h1",{className:"text-2xl font-bold text-ink",children:"Something went wrong"}),(0,d.jsx)("p",{className:"text-sm text-ink-3",children:"An unexpected error occurred. Try again, or refresh the page — the details have been logged."}),(0,d.jsx)("button",{onClick:b,className:"rounded-lg bg-agent-vivid px-4 py-2 text-sm font-semibold text-canvas transition-[filter] hover:brightness-[0.92]",children:"Try again"}),a.digest&&(0,d.jsxs)("p",{className:"font-mono text-[12px] text-ink-4",children:["Reference: ",a.digest]})]})})}c(64565)},57712:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(64565),f=c(48082);function g(){let[a,b]=(0,e.useState)("light");return(0,d.jsx)(f.l$,{theme:a,position:"bottom-right",richColors:!0,closeButton:!0})}},59166:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,88831,23))},59234:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,61186,23))},62952:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\Sidebar.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\Sidebar.tsx","default")},63245:(a,b,c)=>{"use strict";c.d(b,{ch:()=>ej,iU:()=>eL,dd:()=>e4,f_:()=>fs,S2:()=>ey,bN:()=>eB,Cy:()=>ed,Ql:()=>gy,LN:()=>f7,PD:()=>eX,ML:()=>eK,Jc:()=>e5,AS:()=>fQ,Ev:()=>fl,Og:()=>d2,rT:()=>ee,hP:()=>eU,xV:()=>gz,Mo:()=>ga,hl:()=>e1,t3:()=>eQ,X1:()=>fV,TD:()=>fm,Hp:()=>d7,z_:()=>eq,P7:()=>eC,Hl:()=>fR,VZ:()=>fK,g$:()=>fy,Ro:()=>er,lV:()=>eA,UR:()=>gD,bm:()=>fJ,dO:()=>fG,dS:()=>gm,rf:()=>ev,_N:()=>ew,GY:()=>fg,gE:()=>e$,M3:()=>f$,JD:()=>gt,aG:()=>go,WD:()=>gr,oA:()=>fX,cj:()=>fL,cu:()=>fw,V8:()=>eD,Hu:()=>fN,$4:()=>fI,jj:()=>d5,kh:()=>fo,wI:()=>fb,iu:()=>gl,Ko:()=>eb,ei:()=>e2,Sh:()=>ei,$z:()=>ea,By:()=>e8,ZA:()=>gA,Le:()=>eR,BO:()=>gx,ND:()=>eu,Jb:()=>et,Wq:()=>gk,oG:()=>f6,pD:()=>eV,y4:()=>eH,Hy:()=>fO,EA:()=>fr,$5:()=>fj,c6:()=>fE,Zz:()=>fF,vu:()=>ep,zh:()=>d1,PH:()=>ek,yU:()=>e6,qo:()=>eY,oC:()=>d4,Ke:()=>ec,JH:()=>fv,CV:()=>fa,cD:()=>eF,Yn:()=>eE,HO:()=>fW,cr:()=>eT,KI:()=>eI,WH:()=>gC,e4:()=>es,p5:()=>fd,AH:()=>gs,wj:()=>e3,FS:()=>gn,Ir:()=>fi,Ru:()=>f9,Sb:()=>gv,mJ:()=>ff,lg:()=>fC,LW:()=>fA,tS:()=>d6,D5:()=>d3,fl:()=>gj,eP:()=>fU,ZG:()=>eP,_x:()=>fx,bV:()=>fp,E4:()=>eO,fG:()=>eh,pu:()=>fZ,dl:()=>e7,QT:()=>f8,c2:()=>eZ,f2:()=>e0,PC:()=>eN,rv:()=>f0,Hq:()=>gq,fI:()=>fT,Rz:()=>fu,Oc:()=>eo});var d=c(43607),e=c(87388),f=c(66402),g=c(61989),h=c(51455),i=c(76760),j=c(48161),k=c(73136),l=c(77598),m=c(71553),n=c(17473),o=c.n(n),p=c(69747);class q extends Error{constructor(a,b){super(b??a),this.name="DeliveryError",this.code=a}}async function r(a,b,c,d,e=1e4){let f,g=`https://api.telegram.org/bot${a}/${b}`,h=new AbortController,i=setTimeout(()=>h.abort(),e);d?.addEventListener("abort",()=>h.abort(),{once:!0});try{f=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json"},body:void 0!==c?JSON.stringify(c):"{}",signal:h.signal})}catch(c){if(c instanceof Error&&"AbortError"===c.name)throw new q("telegram_request_failed",`telegram_timeout: Telegram API did not respond within ${e/1e3}s`);let b=String(c.message??c).replaceAll(a,"[REDACTED]");throw new q("telegram_request_failed",`telegram_request_failed: network error: ${b}`)}finally{clearTimeout(i)}let j=await f.json().catch(()=>({}));if(!f.ok||!j.ok){let a=j.description??"";if(401===f.status||404===f.status)throw new q("telegram_invalid_token",`telegram_invalid_token: ${a}`);throw new q("telegram_request_failed",`telegram_request_failed: ${a}`)}if(void 0===j.result)throw new q("telegram_request_failed","telegram_request_failed: no result in response");return j.result}async function s(a){let b=await r(a,"getMe");return{id:b.id,username:b.username,firstName:b.first_name,canJoinGroups:b.can_join_groups??!1,canReadAllGroupMessages:b.can_read_all_group_messages??!1}}async function t(a){let b=a.timeout??25,c={offset:a.offset,timeout:b,allowed_updates:["message","callback_query"]};void 0!==a.limit&&(c.limit=a.limit);let d=1e3*b+5e3;return await r(a.botToken,"getUpdates",c,a.signal,d)}class u extends Error{constructor(a,b,c){super(b),this.name="MemoryError",this.code=a,void 0!==c&&(this.cause=c)}}class v extends u{constructor(a){super("MEMORY_NOT_FOUND",`memory.not_found:${a}`),this.name="MemoryNotFoundError"}}class w extends u{constructor(a,b){super("MEMORY_SANITATION",`memory.sanitation_blocked:${a}`),this.name="MemorySanitationError",this.threatId=a,this.detail=b}}class x extends u{constructor(a){super("MEMORY_DUPLICATE",`memory.duplicate:${a}`),this.name="MemoryDuplicateError",this.existingId=a}}var y=c(98648);let z=[[/ignore\s+(previous|all|above|prior)(\s+\w+)?\s+instructions/i,"prompt_injection"],[/you\s+are\s+now\s+/i,"role_hijack"],[/do\s+not\s+tell\s+the\s+user/i,"deception_hide"],[/system\s+prompt\s+override/i,"sys_prompt_override"],[/disregard\s+(your|all|any)\s+(instructions|rules|guidelines)/i,"disregard_rules"],[/act\s+as\s+(if|though)\s+you\s+(have\s+no|don't\s+have)\s+(restrictions|limits|rules)/i,"bypass_restrictions"],[/curl\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i,"exfil_curl"],[/wget\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i,"exfil_wget"],[/cat\s+[^\n]*(\.env|credentials|\.netrc|\.pgpass|\.npmrc|\.pypirc)/i,"read_secrets"],[/authorized_keys/i,"ssh_backdoor"],[/(\$HOME|~)\/\.ssh/i,"ssh_access"],[/(\$HOME|~)\/\.nodalai\/(\.env|secrets\.key)/i,"nodalai_secrets"]],A=["​","‌","‍","⁠","\uFEFF","‪","‫","‬","‭","‮"];async function B(a,b,c){let d=y.r_.parse(b);var e,f=d.fact;if(f.length>5e3)throw new w("too_long",`Memory fact exceeds 5000 characters (${f.length}).`);for(let a of A)if(f.includes(a)){let b=a.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")??"????";throw new w("invisible_unicode",`Memory fact contains invisible unicode character U+${b} (possible injection).`)}for(let[a,b]of z)if(a.test(f))throw new w(b,`Memory fact matches threat pattern '${b}'. Memory entries are injected into the system prompt and must not contain injection or exfiltration payloads.`);let g=(e=d.fact,(0,l.createHash)("sha256").update(e.toLowerCase().trim().replace(/\s+/g," ")).digest("hex"));if(d.entity_id){let b=await a.select({id:p.RK.id}).from(p.RK).where((0,p.Uo)((0,p.eq)(p.RK.entityId,d.entity_id),(0,p.eq)(p.RK.factHash,g),(0,p.eq)(p.RK.archived,!1))).limit(1);if(b[0])throw new x(b[0].id)}let h=null;c&&(h=await c.embed(d.fact));let i=(await a.insert(p.RK).values({entityId:d.entity_id??null,agentId:d.agent_id??null,fact:d.fact,category:d.category,importance:d.importance,source:d.source,skillTags:d.skill_tags,memoryLayer:d.memory_layer??null,factHash:g,embedding:h}).returning())[0];if(!i)throw Error("memory.create_failed");return E(i)}async function C(a,b,c,d){let e={updatedAt:new Date};void 0!==d.fact&&(e.fact=d.fact),void 0!==d.category&&(e.category=d.category),void 0!==d.importance&&(e.importance=d.importance),void 0!==d.importance_locked&&(e.importanceLocked=d.importance_locked),void 0!==d.skill_tags&&(e.skillTags=d.skill_tags),void 0!==d.archived&&(e.archived=d.archived),void 0!==d.valid_to&&(e.validTo=d.valid_to?new Date(d.valid_to):null);let f=(await a.update(p.RK).set(e).where((0,p.Uo)((0,p.eq)(p.RK.id,b),(0,p.eq)(p.RK.entityId,c))).returning())[0];if(!f)throw new v(b);return E(f)}async function D(a,b,c){if(0===(await a.delete(p.RK).where((0,p.Uo)((0,p.eq)(p.RK.id,b),(0,p.eq)(p.RK.entityId,c))).returning()).length)throw new v(b)}function E(a){return{id:a.id,entity_id:a.entityId??null,agent_id:a.agentId??null,fact:a.fact,category:a.category??"context",importance:a.importance??3,source:a.source??"agent",skill_tags:a.skillTags??[],memory_layer:a.memoryLayer??null,valid_from:a.validFrom?.toISOString()??null,valid_to:a.validTo?.toISOString()??null,fact_hash:a.factHash??null,archived:a.archived??!1,importance_locked:a.importanceLocked??!1,last_accessed_at:a.lastAccessedAt?.toISOString()??null,access_count:a.accessCount??0,created_at:a.createdAt?.toISOString()??new Date().toISOString(),updated_at:a.updatedAt?.toISOString()??new Date().toISOString()}}async function F(a,b){var c;let d,e,{entityId:f}=b;if(!f)throw new u("INVALID_ENTITY","memory.list.entity_id_required");let g=b.page??1,h=g<=0?1:g,i=Math.min(Math.max(1,b.pageSize??50),200),j=(h-1)*i,k=(c=b,d=[(0,p.eq)(p.RK.entityId,c.entityId),(0,p.eq)(p.RK.archived,c.archived??!1)],c.agentId&&d.push((0,p.eq)(p.RK.agentId,c.agentId)),c.category&&d.push((0,p.eq)(p.RK.category,c.category)),c.tags&&c.tags.length>0&&d.push((0,p.EI)`${p.RK.skillTags} && ${p.EI.raw((e=c.tags.map(a=>`'${a.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`).join(","),`ARRAY[${e}]`))}::text[]`),(0,p.Uo)(...d)),l=function(a="recent"){switch(a){case"importance":return(0,p.i8)(p.RK.importance);case"last_accessed":return(0,p.i8)(p.RK.lastAccessedAt);default:return(0,p.i8)(p.RK.updatedAt)}}(b.sort),m=await a.select({count:(0,p.EI)`count(*)`}).from(p.RK).where(k),n=Number(m[0]?.count??0),o=(await a.select().from(p.RK).where(k).orderBy(l).limit(i).offset(j)).map(a=>E(a));return{items:o,page:h,pageSize:i,totalCount:n,hasMore:j+o.length<n}}async function G(a,b,c){await a.update(p.RK).set({lastAccessedAt:(0,p.EI)`now()`,accessCount:(0,p.EI)`${p.RK.accessCount} + 1`}).where((0,p.Uo)((0,p.eq)(p.RK.id,b),(0,p.eq)(p.RK.entityId,c)))}async function H(a,b,c){0!==b.length&&await Promise.allSettled(b.map(b=>G(a,b,c)))}async function I(a,b,c,d="importance"){let{entityId:e,agentId:f,skillTags:g,category:h,limit:i}=c,j=b.replace(/[^\w\s]/g," ").split(/\s+/).filter(a=>a.length>2).slice(0,8).map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).filter(a=>a.length>0),k=function(a){let{entityId:b,agentId:c,skillTags:d,category:e}=a,f=[(0,p.eq)(p.RK.entityId,b),(0,p.eq)(p.RK.archived,!1)];if(c&&f.push((0,p.eq)(p.RK.agentId,c)),e&&f.push((0,p.eq)(p.RK.category,e)),d&&d.length>0){let a,b=(a=d.map(a=>`'${a.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`).join(","),`ARRAY[${a}]`);f.push((0,p.EI)`(
2
+ ${p.RK.skillTags} = '{}'::text[]
3
+ OR ${p.RK.skillTags} IS NULL
4
+ OR ${p.RK.skillTags} && ${p.EI.raw(b)}::text[]
5
+ )`)}return f}({entityId:e,agentId:f,skillTags:g,category:h}),l="recent"===d?[(0,p.i8)(p.RK.updatedAt),(0,p.i8)(p.RK.importance)]:[(0,p.i8)(p.RK.importance),(0,p.i8)(p.RK.updatedAt)];if(j.length>0){let b=(0,p.EI)`"agent_memory"."search_tsv"`,c=(0,p.EI)`to_tsquery('english', ${j.join(" | ")})`;return await a.select().from(p.RK).where((0,p.Uo)(...k,(0,p.EI)`${b} @@ ${c}`)).orderBy((0,p.EI)`ts_rank(${b}, ${c}) DESC`,...l).limit(i)}return await a.select().from(p.RK).where((0,p.Uo)(...k)).orderBy(...l).limit(i)}async function J(a,b){let{query:c,entityId:d,agentId:e,skillTags:f,category:g,limit:h=10,sort:i="importance",touch:j=!0}=b,k=(await I(a,c,{entityId:d,agentId:e,skillTags:f,category:g,limit:h},i)).map(a=>E(a));return j&&k.length>0&&await H(a,k.map(a=>a.id),d),k}let K=new Set(["the","and","for","are","was","were","but","not","you","your","his","her","its","our","their","this","that","these","those","with","from","into","out","can","could","will","would","should","shall","may","might","must","has","have","had","been","being","then","than","them","they","what","when","where","which","who","why","how","all","any","some","such","only","too","very","just","also","per","via","about","les","des","une","est","\xe9t\xe9","pour","avec","dans","par","sur","que","qui","quoi","dont","pas","plus","mais","son","ses","mes","tes","nos","vos","leur","leurs","mon","ton","cette","ces","cet","aux","vers","chez","sans","sous","entre","tout","tous","toute","comme","donc","alors","ainsi","une","deux","ce","la","le"]);function L(a){if(!a)return[];let b=new Set;for(let c of a.toLowerCase().split(/[^\p{L}\p{N}]+/u))c.length>2&&!K.has(c)&&b.add(c);return[...b]}function M(a,b){if(b<=0)return[];let c=[],d=0;for(let e of a){let a=e.fact.length+20;d+a>b||(c.push(e),d+=a)}return c}async function N(a,b){if(b.maxChars<=0)return[];let c=(0,p.Uo)((0,p.eq)(p.RK.entityId,b.entityId),(0,p.eq)(p.RK.archived,!1),(0,p.EI)`(${p.RK.validTo} IS NULL OR ${p.RK.validTo} > now())`),d=b.query??"";if(L(d).length>0){let e=(0,p.EI)`"agent_memory"."search_tsv"`,f=(0,p.EI)`plainto_tsquery('english', ${d})`;return M((await a.select().from(p.RK).where(c).orderBy((0,p.EI)`ts_rank(${e}, ${f}) DESC`,(0,p.i8)(p.RK.importance),(0,p.i8)(p.RK.lastAccessedAt)).limit(200)).map(a=>E(a)),b.maxChars)}return function(a,b,c){if(b<=0)return[];let d=L(c),e=a=>a.importance+2*Math.min(function(a,b){if(0===b.length)return 0;let c=a.toLowerCase(),d=0;for(let a of b)c.includes(a)&&d++;return d}(a.fact,d),2);return M([...a].sort((a,b)=>{let c=e(b),d=e(a);if(c!==d)return c-d;let f=a.last_accessed_at??a.created_at,g=b.last_accessed_at??b.created_at;return f!==g?g.localeCompare(f):a.id.localeCompare(b.id)}),b)}((await a.select().from(p.RK).where(c).orderBy((0,p.i8)(p.RK.importance),(0,p.i8)(p.RK.lastAccessedAt)).limit(200)).map(a=>E(a)),b.maxChars,b.query)}var O=c(98472),P=c(38496);class Q extends Error{constructor(a,b,c){super(b),this.name="NotionAdapterError",this.code=a,this.status=c}}function R(a){if(a instanceof P.APIResponseError){let b,c=a.status;switch(c){case 400:b="notion_validation_error";break;case 401:b="notion_unauthorized";break;case 403:b="notion_forbidden";break;case 404:b="notion_not_found";break;case 409:b="notion_conflict";break;case 429:b="notion_rate_limited";break;case 503:b="notion_service_unavailable";break;default:b="notion_unknown"}return new Q(b,a.message,c)}return a instanceof Error?new Q("notion_unknown",a.message):new Q("notion_unknown",String(a))}function S(a,b){let c=null==a?"":String(a);if(!c)return[{type:"text",text:{content:""}}];let d=[],e=[],f=0;for(let a of c){let c=a.codePointAt(0)>65535?2:1;if(f+c>2e3){let g={type:"text",text:{content:e.join("")}};b&&(g.annotations=b),d.push(g),e.length=0,e.push(a),f=c}else e.push(a),f+=c}if(e.length>0){let a={type:"text",text:{content:e.join("")}};b&&(a.annotations=b),d.push(a)}return d}function T(a){let b=a.type;if("title"===b)return(a.title??[]).map(a=>a.plain_text).join("");if("rich_text"===b)return(a.rich_text??[]).map(a=>a.plain_text).join("");if("select"===b){let b=a.select;return b?.name??""}if("multi_select"===b)return(a.multi_select??[]).map(a=>a.name).join(", ");if("status"===b){let b=a.status;return b?.name??""}if("number"===b||"checkbox"===b||"url"===b||"email"===b||"phone_number"===b){let c=a[b];return null!=c?String(c):""}if("date"===b){let b=a.date;return b?b.end?`${b.start} → ${b.end}`:b.start:""}if("relation"===b)return(a.relation??[]).map(a=>a.id).join(", ");if("formula"===b){let b=a.formula;return b?String(b[b.type]??""):""}if("rollup"===b){let b=a.rollup;return b?String(b[b.type]??""):""}return"people"===b?(a.people??[]).map(a=>a.name??a.id).join(", "):"created_time"===b?String(a.created_time??""):"last_edited_time"===b?String(a.last_edited_time??""):""}function U(a,b,c){let d=c?.[a]?.type;switch(d||("boolean"==typeof b?"checkbox":"number"==typeof b?"number":"string"==typeof b&&b.startsWith("http")?"url":"rich_text")){case"title":return{title:S(String(b??""))};case"rich_text":default:return{rich_text:S(String(b??""))};case"number":{let a=Number(b);return isNaN(a)?{rich_text:S(String(b))}:{number:a}}case"checkbox":return{checkbox:!!b};case"url":return{url:null!=b?String(b).slice(0,2e3):null};case"select":return{select:{name:String(b).slice(0,100)}};case"multi_select":return{multi_select:(Array.isArray(b)?b:String(b).split(",")).map(a=>({name:String(a).trim().slice(0,100)}))};case"date":return{date:{start:String(b)}};case"email":return{email:String(b)};case"phone_number":return{phone_number:String(b)}}}function V(a){for(let b of Object.values(a.properties??{}))if("title"===b.type)return(b.title??[]).map(a=>a.plain_text).join("");let b=a.title;return Array.isArray(b)?b.map(a=>a.plain_text).join(""):"(untitled)"}let W=g.Ik({query:g.Yj().describe("Text to search for in page and database titles."),limit:g.ai().int().min(1).max(100).optional().default(10).describe("Max results to return (1–100, default 10)."),filter_type:g.k5(["page","database"]).optional().describe("Optional: restrict results to pages or databases only.")});async function X(a,b=100,c=500){let d,e=[];for(let f=0;f<20;f++){let f=await a(d,Math.min(b,100));if(e.push(...f.results),e.length>=c||!f.has_more||!f.next_cursor)break;d=f.next_cursor}return e.slice(0,c)}async function Y(a,b,c=300){return X(async(c,d)=>{let e=await a.blocks.children.list({block_id:b,start_cursor:c,page_size:d});return{results:e.results.filter(a=>"block"===a.object),has_more:e.has_more,next_cursor:e.next_cursor}},100,c)}function Z(a){return a.map(a=>a.plain_text).join("")}function $(a){switch(a.type){case"paragraph":return Z(a.paragraph.rich_text);case"heading_1":return`# ${Z(a.heading_1.rich_text)}`;case"heading_2":return`## ${Z(a.heading_2.rich_text)}`;case"heading_3":return`### ${Z(a.heading_3.rich_text)}`;case"bulleted_list_item":return`- ${Z(a.bulleted_list_item.rich_text)}`;case"numbered_list_item":return`1. ${Z(a.numbered_list_item.rich_text)}`;case"to_do":{let b=a.to_do.checked;return`[${b?"x":" "}] ${Z(a.to_do.rich_text)}`}case"code":{let b=a.code.language,c=Z(a.code.rich_text);return`\`\`\`${b}
6
6
  ${c}
7
- \`\`\``}case"quote":return`> ${W(a.quote.rich_text)}`;case"callout":{let b=W(a.callout.rich_text),c=a.callout.icon,d=c?.type==="emoji"?c.emoji:"";return d?`${d} ${b}`:b}case"divider":return"---";case"toggle":return W(a.toggle.rich_text);case"table_of_contents":return"[table of contents]";case"child_page":return`[child page: ${a.child_page.title}]`;case"child_database":return`[child database: ${a.child_database.title}]`;case"image":{let b="external"===a.image.type?a.image.external.url:a.image.file.url;return`[image: ${b}]`}case"video":{let b="external"===a.video.type?a.video.external.url:a.video.file.url;return`[video: ${b}]`}case"file":{let b="external"===a.file.type?a.file.external.url:a.file.file.url;return`[file: ${b}]`}case"pdf":{let b="external"===a.pdf.type?a.pdf.external.url:a.pdf.file.url;return`[pdf: ${b}]`}case"bookmark":return`[bookmark: ${a.bookmark.url}]`;case"embed":return`[embed: ${a.embed.url}]`;default:return null}}let Y=g.Ik({page_id:g.Yj().describe("Notion page ID (UUID or dashed UUID).")}),Z=g.Ik({page_id:g.Yj().describe("Notion page or block ID whose content to read."),max_blocks:g.ai().int().min(1).max(1e3).optional().default(300).describe("Maximum number of blocks to fetch (default 300).")}),$=g.Ik({parent_page_id:g.Yj().optional().describe("ID of the parent PAGE. Use when creating a sub-page inside another page. Mutually exclusive with parent_database_id."),parent_database_id:g.Yj().optional().describe("ID of the parent DATABASE. Use when creating a new row inside a database. Mutually exclusive with parent_page_id."),title:g.Yj().describe("Title of the new page."),content:g.Yj().optional().describe("Optional paragraph text to add as the first block. Auto-chunked if >2000 chars.")}),_=g.Ik({page_id:g.Yj().describe("Page ID to update."),properties:g.g1(g.Yj(),g.L5()).describe('Properties to update as key-value pairs. Example: {"Status": "Done", "Priority": "High", "Score": 95}')}),aa=g.Ik({page_id:g.Yj().describe("Page ID to archive.")}),ab=g.Ik({block_id:g.Yj().describe("Block ID to retrieve.")}),ac=g.Ik({type:g.k5(["paragraph","heading_1","heading_2","heading_3","bulleted_list_item","numbered_list_item","to_do","code","quote","callout","toggle","divider"]).describe("Block type."),content:g.Yj().optional().default("").describe("Text content for the block (not used for divider)."),language:g.Yj().optional().describe('Programming language for code blocks (e.g. "python", "javascript").'),checked:g.zM().optional().default(!1).describe("Whether a to_do block is checked.")}),ad=g.Ik({page_id:g.Yj().describe("Page or block ID to append content to."),blocks:g.YO(ac).min(1).max(100).describe('Array of blocks to add. Example: [{"type": "heading_2", "content": "Summary"}, {"type": "paragraph", "content": "The results show..."}]')});function ae(a){if("divider"===a.type)return{object:"block",type:"divider",divider:{}};let b=P(a.content??"");return"code"===a.type?{object:"block",type:"code",code:{rich_text:b,language:a.language??"plain text"}}:"to_do"===a.type?{object:"block",type:"to_do",to_do:{rich_text:b,checked:a.checked??!1}}:{object:"block",type:a.type,[a.type]:{rich_text:b}}}let af=g.Ik({block_id:g.Yj().describe("Block ID to update."),content:g.Yj().describe("New text content for the block.")}),ag=g.Ik({block_id:g.Yj().describe("Block ID to delete (archive).")}),ah=g.Ik({database_id:g.Yj().describe("Notion database ID (UUID)."),filter:g.g1(g.Yj(),g.L5()).optional().describe('Optional Notion filter object. Example: {"property": "Status", "select": {"equals": "Applied"}}'),page_size:g.ai().int().min(1).max(100).optional().default(50).describe("Rows per request (1–100, default 50)."),max_rows:g.ai().int().min(1).max(1e3).optional().default(500).describe("Total rows to collect across pagination (default 500, max 1000).")}),ai=g.Ik({database_id:g.Yj().describe("Notion database ID (UUID).")}),aj=g.Ik({database_id:g.Yj().describe("Notion database ID to add a row to."),properties:g.g1(g.Yj(),g.L5()).describe('Row properties as key-value pairs. Example: {"Name": "Acme Corp", "Status": "Applied", "Score": 95}')}),ak=g.Ik({page_id:g.Yj().describe("Page ID of the database row to update."),database_id:g.Yj().optional().describe("Optional: database ID to fetch schema for type coercion. If omitted, types are inferred from values."),properties:g.g1(g.Yj(),g.L5()).describe('Properties to update as key-value pairs. Example: {"Status": "Done", "Score": 100}')}),al=g.k5(["title","rich_text","number","checkbox","url","email","phone_number","date","select","multi_select","status"]),am=g.Ik({parent_page_id:g.Yj().describe("Page ID that will contain the new database."),title:g.Yj().describe("Database title."),columns:g.g1(g.Yj(),al).describe('Column definitions as {name: type}. One must be "title". Example: {"Name": "title", "Status": "select", "URL": "url", "Score": "number"}')});function an(a){switch(a){case"title":return{title:{}};case"select":return{select:{options:[]}};case"multi_select":return{multi_select:{options:[]}};case"status":return{status:{}};default:return{[a]:{}}}}let ao=g.Ik({database_id:g.Yj().describe("Database ID to update."),title:g.Yj().optional().describe("Optional new title for the database."),new_columns:g.g1(g.Yj(),al).optional().describe("New columns to add as {name: type}. Same types as notion_create_database. Cannot modify existing column types (Notion API limitation).")}),ap=g.Ik({block_id:g.Yj().describe("Page or block ID to list comments for."),page_size:g.ai().int().min(1).max(50).optional().default(50).describe("Max comments to return (default 50).")}),aq=g.Ik({page_id:g.Yj().describe("Page ID to comment on."),text:g.Yj().describe("Comment text.")}),ar=g.Ik({page_size:g.ai().int().min(1).max(100).optional().default(100).describe("Max users to return (default 100).")}),as=g.Ik({user_id:g.Yj().describe("Notion user ID.")}),at=[{slug:"notion_search",name:"Search",risk:"read",requiresApproval:!1,description:"Search pages and databases by title."},{slug:"notion_get_page",name:"Get page",risk:"read",requiresApproval:!1,description:"Retrieve page properties by ID."},{slug:"notion_get_page_content",name:"Get page content",risk:"read",requiresApproval:!1,description:"Read all blocks inside a page."},{slug:"notion_get_block",name:"Get block",risk:"read",requiresApproval:!1,description:"Retrieve a single block and its children."},{slug:"notion_query_database",name:"Query database",risk:"read",requiresApproval:!1,description:"Filter and sort rows in a Notion database."},{slug:"notion_get_database",name:"Get database",risk:"read",requiresApproval:!1,description:"Retrieve database schema and properties."},{slug:"notion_list_comments",name:"List comments",risk:"read",requiresApproval:!1,description:"List all comments on a page or block."},{slug:"notion_list_users",name:"List users",risk:"read",requiresApproval:!1,description:"List workspace members."},{slug:"notion_get_user",name:"Get user",risk:"read",requiresApproval:!1,description:"Retrieve a workspace member by ID."},{slug:"notion_create_page",name:"Create page",risk:"write",requiresApproval:!1,description:"Create a new page inside a parent page or database."},{slug:"notion_update_page",name:"Update page",risk:"write",requiresApproval:!1,description:"Update page properties."},{slug:"notion_append_blocks",name:"Append blocks",risk:"write",requiresApproval:!1,description:"Append content blocks to a page or block."},{slug:"notion_update_block",name:"Update block",risk:"write",requiresApproval:!1,description:"Update an existing block content."},{slug:"notion_create_database_entry",name:"Create database entry",risk:"write",requiresApproval:!1,description:"Add a new row to a Notion database."},{slug:"notion_update_database_entry",name:"Update database entry",risk:"write",requiresApproval:!1,description:"Update properties on an existing database row."},{slug:"notion_create_database",name:"Create database",risk:"write",requiresApproval:!1,description:"Create a new database inside a parent page."},{slug:"notion_update_database",name:"Update database",risk:"write",requiresApproval:!1,description:"Update database title or property schema."},{slug:"notion_add_comment",name:"Add comment",risk:"write",requiresApproval:!1,description:"Add a comment to a page or block."},{slug:"notion_archive_page",name:"Archive page",risk:"destructive",requiresApproval:!0,description:"Archive (soft-delete) a page."},{slug:"notion_delete_block",name:"Delete block",risk:"destructive",requiresApproval:!0,description:"Permanently delete a block."}];function au(a){var b;let c=(b=function(a){if("apiKey"in a&&a.apiKey)return a.apiKey;if(!a.accessToken)throw Error("NotionAdapterOptions: either apiKey or accessToken must be a non-empty string.");return a.accessToken}(a),new M.Client({auth:b}));return[{name:"notion_search",description:"Search across all pages and databases in Notion. Returns matching page titles, IDs, and URLs.",inputSchema:T,riskLevel:"read",async execute(a){try{let b={query:a.query,page_size:a.limit};a.filter_type&&(b.filter={property:"object",value:a.filter_type});let d=(await c.search(b)).results.map(a=>{let b=a.object,c=a.id,d="url"in a?a.url:"",e=S(a);return{object:b,id:c,title:e,url:d}});return{total:d.length,results:d}}catch(a){throw O(a)}}},{name:"notion_get_page",description:"Retrieve a Notion page by its ID. Returns the page title and a summary of its properties.",inputSchema:Y,riskLevel:"read",async execute(a){try{let b=await c.pages.retrieve({page_id:a.page_id});if(!("properties"in b))throw O(Error("notion_not_found"));let d=S(b),e="url"in b?b.url:"",f={};for(let[a,c]of Object.entries(b.properties)){if("title"===c.type)continue;let b=Q(c);b&&(f[a]=b.slice(0,200))}return{id:b.id,title:d,url:e,created_time:"created_time"in b?String(b.created_time):"",last_edited_time:"last_edited_time"in b?String(b.last_edited_time):"",properties:f}}catch(a){throw O(a)}}},{name:"notion_get_page_content",description:"Read the full text content of a Notion page (paragraphs, headings, lists, code, etc.). Use this after notion_search or notion_get_page to read what is actually written on the page.",inputSchema:Z,riskLevel:"read",async execute(a){try{let b=await c.pages.retrieve({page_id:a.page_id}),d=S(b),e=await V(c,a.page_id,a.max_blocks),f=function(a,b=15e3){let c=[];for(let b of a){let a=X(b);null!==a&&c.push(a)}let d=c.join("\n\n");return d.length>b?d.slice(0,b)+"\n\n[...content truncated...]":d}(e);return{id:a.page_id,title:d,content:f||"(no extractable text content)",block_count:e.length}}catch(a){throw O(a)}}},{name:"notion_get_block",description:"Retrieve a specific Notion block by ID. Returns the block type and its text content.",inputSchema:ab,riskLevel:"read",async execute(a){try{let b=await c.blocks.retrieve({block_id:a.block_id});return{id:b.id,type:"type"in b?String(b.type):"unknown",text:X(b),has_children:"has_children"in b&&!!b.has_children}}catch(a){throw O(a)}}},{name:"notion_query_database",description:"Query a Notion database with optional filters. Without a filter, returns all entries. Returns rows with their properties.",inputSchema:ah,riskLevel:"read",async execute(a){try{let b=!1,d=await U(async(b,d)=>{let e={database_id:a.database_id,page_size:d};a.filter&&(e.filter=a.filter),b&&(e.start_cursor=b);let f=await c.databases.query(e);return{results:f.results,has_more:f.has_more,next_cursor:f.next_cursor}},a.page_size,a.max_rows);d.length>=a.max_rows&&(b=!0);let e=d.map(a=>{let b={id:a.id,url:"url"in a?String(a.url):""};if("properties"in a)for(let[c,d]of Object.entries(a.properties)){let a=Q(d);a&&(b[c]=a)}return b});return{total:e.length,has_more:b,rows:e}}catch(a){throw O(a)}}},{name:"notion_get_database",description:"Get the schema of a Notion database (column names, types, and select/multi_select options). Call this to discover database structure before querying or creating rows.",inputSchema:ai,riskLevel:"read",async execute(a){try{let b=await c.databases.retrieve({database_id:a.database_id}),d=("title"in b?b.title:[]).map(a=>a.plain_text).join("")||"(untitled)",e="url"in b?String(b.url):"",f=Object.entries(b.properties).map(([a,b])=>{let c={name:a,type:b.type};return"select"===b.type?c.options=(b.select?.options??[]).slice(0,20).map(a=>a.name):"multi_select"===b.type?c.options=(b.multi_select?.options??[]).slice(0,20).map(a=>a.name):"status"===b.type&&(c.options=(b.status?.options??[]).slice(0,20).map(a=>a.name)),c});return{id:b.id,title:d,url:e,columns:f}}catch(a){throw O(a)}}},{name:"notion_list_comments",description:"List comments on a Notion page or block.",inputSchema:ap,riskLevel:"read",async execute(a){try{let b=(await c.comments.list({block_id:a.block_id,page_size:a.page_size})).results.map(a=>{let b=a.rich_text.map(a=>a.plain_text).join(""),c=a.created_by;return{id:a.id,author_id:c?.id??"",author_name:c?.name??"",text:b.slice(0,500),created_time:a.created_time}});return{total:b.length,comments:b}}catch(a){throw O(a)}}},{name:"notion_list_users",description:"List all users in the Notion workspace.",inputSchema:ar,riskLevel:"read",async execute(a){try{let b=(await c.users.list({page_size:a.page_size})).results.map(a=>{let b="person"===a.type&&"person"in a?a.person:null;return{id:a.id,name:a.name??"",type:a.type??"unknown",email:b?.email??"",avatar_url:a.avatar_url??""}});return{total:b.length,users:b}}catch(a){throw O(a)}}},{name:"notion_get_user",description:"Get details about a specific Notion user by their ID.",inputSchema:as,riskLevel:"read",async execute(a){try{let b=await c.users.retrieve({user_id:a.user_id}),d="person"===b.type&&"person"in b?b.person:null;return{id:b.id,name:b.name??"",type:b.type??"unknown",email:d?.email??"",avatar_url:b.avatar_url??""}}catch(a){throw O(a)}}},{name:"notion_create_page",description:"Create a new Notion page. Provide EITHER parent_page_id (to nest under a page) OR parent_database_id (to create a row in a database) — not both.",inputSchema:$,riskLevel:"write",async execute(a){if(a.parent_page_id&&a.parent_database_id)throw O(Error("Provide either parent_page_id OR parent_database_id, not both."));if(!a.parent_page_id&&!a.parent_database_id)throw O(Error("Must provide parent_page_id or parent_database_id."));try{let b,d="title";if(a.parent_database_id){b={database_id:a.parent_database_id};try{let b=await c.databases.retrieve({database_id:a.parent_database_id});for(let[a,c]of Object.entries(b.properties))if("title"===c.type){d=a;break}}catch{}}else b={type:"page_id",page_id:a.parent_page_id};let e={[d]:{title:P(a.title)}},f=[];a.content&&f.push({object:"block",type:"paragraph",paragraph:{rich_text:P(a.content)}});let g=await c.pages.create({parent:b,properties:e,...f.length>0&&{children:f}});return{id:g.id,url:"url"in g?String(g.url):"",title:a.title}}catch(a){throw O(a)}}},{name:"notion_update_page",description:"Update properties of a Notion page (title, status, select, text, number, etc.). Use notion_query_database first to discover the correct property names and types.",inputSchema:_,riskLevel:"write",async execute(a){try{let b=null;try{let d=await c.pages.retrieve({page_id:a.page_id}),e="parent"in d?d.parent:null;if(e?.type==="database_id"&&e.database_id){let a=await c.databases.retrieve({database_id:e.database_id});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}}catch{}let d={};for(let[c,e]of Object.entries(a.properties))null!=e&&(d[c]=R(c,e,b));return await c.pages.update({page_id:a.page_id,properties:d}),{id:a.page_id,updated_properties:Object.keys(d).length}}catch(a){throw O(a)}}},{name:"notion_append_blocks",description:"Add content blocks to an existing Notion page. Supports paragraphs, headings, lists, code blocks, quotes, and dividers.",inputSchema:ad,riskLevel:"write",async execute(a){try{let b=a.blocks.map(ae);return await c.blocks.children.append({block_id:a.page_id,children:b}),{page_id:a.page_id,appended_count:b.length}}catch(a){throw O(a)}}},{name:"notion_update_block",description:"Update the text content of an existing Notion block. The block type is preserved.",inputSchema:af,riskLevel:"write",async execute(a){try{let b=await c.blocks.retrieve({block_id:a.block_id}),d="type"in b?String(b.type):"paragraph",e=P(a.content),f={block_id:a.block_id,[d]:{rich_text:e}};return await c.blocks.update(f),{id:a.block_id}}catch(a){throw O(a)}}},{name:"notion_create_database_entry",description:"Create a new row (entry) in a Notion database. Use notion_get_database first to discover property names and types.",inputSchema:aj,riskLevel:"write",async execute(a){try{let b=null,d="Name";try{let e=await c.databases.retrieve({database_id:a.database_id});for(let[a,c]of(b={},Object.entries(e.properties))){let e=c.type;b[a]={type:e},"title"===e&&(d=a)}}catch{}let e={};for(let[c,d]of Object.entries(a.properties))null!=d&&(e[c]=R(c,d,b));if(!e[d]){let b=Object.entries(a.properties).find(([,a])=>"string"==typeof a&&a);b&&(e[d]={title:P(b[1])})}let f=await c.pages.create({parent:{database_id:a.database_id},properties:e});return{id:f.id,url:"url"in f?String(f.url):""}}catch(a){throw O(a)}}},{name:"notion_update_database_entry",description:"Update properties of a Notion database row. Use notion_get_database to discover property names and types.",inputSchema:ak,riskLevel:"write",async execute(a){try{let b=null,d=a.database_id;if(d)try{let a=await c.databases.retrieve({database_id:d});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}catch{}else try{let d=await c.pages.retrieve({page_id:a.page_id}),e="parent"in d?d.parent:null;if(e?.type==="database_id"&&e.database_id){let a=await c.databases.retrieve({database_id:e.database_id});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}}catch{}let e={};for(let[c,d]of Object.entries(a.properties))null!=d&&(e[c]=R(c,d,b));return await c.pages.update({page_id:a.page_id,properties:e}),{id:a.page_id,updated_properties:Object.keys(e).length}}catch(a){throw O(a)}}},{name:"notion_create_database",description:"Create a new database inside a Notion page. Define columns with their types (title, rich_text, select, multi_select, number, checkbox, url, date, email).",inputSchema:am,riskLevel:"write",async execute(a){try{let b={};for(let[c,d]of Object.entries(a.columns))b[c]=an(d);let d=await c.databases.create({parent:{type:"page_id",page_id:a.parent_page_id},title:[{type:"text",text:{content:a.title}}],properties:b});return{id:d.id,url:"url"in d?String(d.url):"",title:a.title}}catch(a){throw O(a)}}},{name:"notion_update_database",description:"Update a database schema — add new columns or rename the database. Cannot modify existing column types (Notion API limitation).",inputSchema:ao,riskLevel:"write",async execute(a){if(!a.title&&!a.new_columns)throw O(Error("Provide title and/or new_columns to update."));try{let b={},d=[];if(a.title&&(b.title=[{type:"text",text:{content:a.title}}],d.push(`title → "${a.title}"`)),a.new_columns&&Object.keys(a.new_columns).length>0){let c={};for(let[b,d]of Object.entries(a.new_columns))c[b]=an(d);b.properties=c,d.push(`${Object.keys(a.new_columns).length} column(s) added`)}return await c.databases.update({database_id:a.database_id,...b}),{id:a.database_id,changes:d}}catch(a){throw O(a)}}},{name:"notion_add_comment",description:"Add a comment to a Notion page.",inputSchema:aq,riskLevel:"write",async execute(a){try{return{id:(await c.comments.create({parent:{page_id:a.page_id},rich_text:P(a.text)})).id,page_id:a.page_id}}catch(a){throw O(a)}}},{name:"notion_archive_page",description:"Archive (soft-delete) a Notion page. The page can be restored from trash.",inputSchema:aa,riskLevel:"destructive",async execute(a){try{return await c.pages.update({page_id:a.page_id,archived:!0}),{id:a.page_id,archived:!0}}catch(a){throw O(a)}}},{name:"notion_delete_block",description:"Delete (archive) a specific block from a Notion page.",inputSchema:ag,riskLevel:"destructive",async execute(a){try{return await c.blocks.delete({block_id:a.block_id}),{id:a.block_id,deleted:!0}}catch(a){throw O(a)}}}]}class av extends Error{constructor(a,b,c){super(b),this.name="AirtableApiError",this.code=a,this.status=c}}function aw(a){return a instanceof av?a:a instanceof Error?new av("airtable_unknown",a.message):new av("airtable_unknown",String(a))}let ax="https://api.airtable.com/v0",ay=g.Ik({}),az=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it.")}),aA=g.Ik({field:g.Yj().describe("Field name to sort by."),direction:g.k5(["asc","desc"]).optional().describe("Sort direction (default asc).")}),aB=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID (tblXXXXXXXX) or name within the base. Use airtable_list_tables to find it."),view:g.Yj().optional().describe("Name or ID of the view to use."),pageSize:g.ai().int().min(1).max(100).optional().default(100).describe("Number of records per page (1–100, default 100)."),offset:g.Yj().optional().describe("Pagination offset token from a previous response."),fields:g.YO(g.Yj()).optional().describe("List of field names to return. Omit to return all fields."),filterByFormula:g.Yj().optional().describe("Airtable formula to filter records. Example: \"AND({Status}='Active',{Score}>80)\""),sort:g.YO(aA).optional().describe("List of sort objects with field and optional direction.")}),aC=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to retrieve.")}),aD=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),records:g.YO(g.Ik({fields:g.g1(g.Yj(),g.L5())})).min(1).max(10).describe('Array of records to create, each with a fields object. Max 10 per call. Example: [{"fields": {"Name": "Alice", "Status": "Active"}}]'),typecast:g.zM().optional().describe("If true, Airtable will attempt to convert string values to the appropriate field type. Default false.")}),aE=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to update."),fields:g.g1(g.Yj(),g.L5()).describe('Fields to update as key-value pairs. Only specified fields are changed (PATCH semantics). Example: {"Status": "Done", "Score": 95}'),typecast:g.zM().optional().describe("If true, attempt to convert string values to the appropriate field type.")}),aF=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to replace."),fields:g.g1(g.Yj(),g.L5()).describe("Complete field set to write. Fields NOT included will be cleared (PUT semantics). Use airtable_update_record for partial updates."),typecast:g.zM().optional().describe("If true, attempt to convert string values to the appropriate field type.")}),aG=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to delete. This action is permanent and cannot be undone.")}),aH=[{slug:"airtable_list_bases",name:"List bases",risk:"read",requiresApproval:!1,description:"List all Airtable bases the integration has access to."},{slug:"airtable_list_tables",name:"List tables",risk:"read",requiresApproval:!1,description:"List all tables and field schemas in a base."},{slug:"airtable_list_records",name:"List records",risk:"read",requiresApproval:!1,description:"List records in a table with optional filtering, sorting, and pagination."},{slug:"airtable_get_record",name:"Get record",risk:"read",requiresApproval:!1,description:"Retrieve a single record by its ID."},{slug:"airtable_create_records",name:"Create records",risk:"write",requiresApproval:!1,description:"Create one or more records in a table (max 10 per call)."},{slug:"airtable_update_record",name:"Update record",risk:"write",requiresApproval:!1,description:"Update specific fields on a record (PATCH — unlisted fields unchanged)."},{slug:"airtable_replace_record",name:"Replace record",risk:"write",requiresApproval:!1,description:"Fully replace all fields on a record (PUT — unlisted fields cleared)."},{slug:"airtable_delete_record",name:"Delete record",risk:"destructive",requiresApproval:!0,description:"Permanently delete a single record. This action is irreversible."}];function aI(a){if(!a.accessToken)throw Error("AirtableAdapterOptions: accessToken must be a non-empty string.");let b=function(a){async function b(b,c,d){let e,f;try{e=await fetch(c,{method:b,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},...void 0!==d&&{body:JSON.stringify(d)}})}catch(a){throw aw(a)}try{f=await e.json()}catch{f={}}if(!e.ok){let a,b=f;throw a="object"==typeof b?.error&&null!==b.error?b.error.message??e.statusText:"string"==typeof b?.error?b.error:b?.message?b.message:e.statusText,function(a,b){let c;switch(!0){case 401===a:c="airtable_unauthorized";break;case 403===a:c="airtable_forbidden";break;case 404===a:c="airtable_not_found";break;case 422===a:c="airtable_validation_error";break;case 429===a:c="airtable_rate_limited";break;case a>=500:c="airtable_transient";break;default:c="airtable_client_error"}return new av(c,b,a)}(e.status,a)}return f}return{get:(a,c)=>b("GET",function(a,b,c){let d=new URL(`${a}${b}`);if(c)for(let[a,b]of Object.entries(c))if(Array.isArray(b))for(let c of b)d.searchParams.append(a,String(c));else null!=b&&d.searchParams.set(a,String(b));return d.toString()}(ax,a,c)),post:(a,c)=>b("POST",`${ax}${a}`,c),patch:(a,c)=>b("PATCH",`${ax}${a}`,c),put:(a,c)=>b("PUT",`${ax}${a}`,c),delete:a=>b("DELETE",`${ax}${a}`)}}(a.accessToken);return[{name:"airtable_list_bases",description:"List all Airtable bases the integration has access to. Returns base IDs and names needed for other airtable_ tools.",inputSchema:ay,riskLevel:"read",async execute(a){try{return{bases:((await b.get("/meta/bases")).bases??[]).map(a=>({id:a.id,name:a.name,permissionLevel:a.permissionLevel}))}}catch(a){throw aw(a)}}},{name:"airtable_list_tables",description:"List all tables in an Airtable base including their field schemas. Use this to discover table IDs and field names before reading or writing records.",inputSchema:az,riskLevel:"read",async execute(a){try{return{tables:((await b.get(`/meta/bases/${a.baseId}/tables`)).tables??[]).map(a=>({id:a.id,name:a.name,primaryFieldId:a.primaryFieldId,fields:(a.fields??[]).map(a=>({id:a.id,name:a.name,type:a.type}))}))}}catch(a){throw aw(a)}}},{name:"airtable_list_records",description:"List records in an Airtable table. Supports filtering by formula, sorting, field selection, and pagination via offset token.",inputSchema:aB,riskLevel:"read",async execute(a){try{let c={pageSize:a.pageSize??100};if(a.view&&(c.view=a.view),a.offset&&(c.offset=a.offset),a.filterByFormula&&(c.filterByFormula=a.filterByFormula),a.fields&&a.fields.length>0&&(c["fields[]"]=a.fields),a.sort&&a.sort.length>0)for(let b=0;b<a.sort.length;b++){let d=a.sort[b];d&&(c[`sort[${b}][field]`]=d.field,d.direction&&(c[`sort[${b}][direction]`]=d.direction))}let d=await b.get(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}`,c);return{records:(d.records??[]).map(a=>({id:a.id,fields:a.fields??{},createdTime:a.createdTime})),offset:d.offset}}catch(a){throw aw(a)}}},{name:"airtable_get_record",description:"Retrieve a single record from an Airtable table by its record ID. Returns all field values.",inputSchema:aC,riskLevel:"read",async execute(a){try{let c=await b.get(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`);return{id:c.id,fields:c.fields??{},createdTime:c.createdTime}}catch(a){throw aw(a)}}},{name:"airtable_create_records",description:"Create one or more records in an Airtable table. Max 10 records per call. Field names must match the table schema exactly.",inputSchema:aD,riskLevel:"write",async execute(a){try{let c={records:a.records};return a.typecast&&(c.typecast=!0),{records:((await b.post(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}`,c)).records??[]).map(a=>({id:a.id,fields:a.fields??{},createdTime:a.createdTime}))}}catch(a){throw aw(a)}}},{name:"airtable_update_record",description:"Update specific fields on a single Airtable record (PATCH — only listed fields are changed, others remain). Use airtable_replace_record to overwrite all fields.",inputSchema:aE,riskLevel:"write",async execute(a){try{let c={fields:a.fields};a.typecast&&(c.typecast=!0);let d=await b.patch(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`,c);return{id:d.id,fields:d.fields??{},createdTime:d.createdTime}}catch(a){throw aw(a)}}},{name:"airtable_replace_record",description:"Fully replace all fields on a single Airtable record (PUT — fields not listed are cleared to empty). Use airtable_update_record for partial field updates.",inputSchema:aF,riskLevel:"write",async execute(a){try{let c={fields:a.fields};a.typecast&&(c.typecast=!0);let d=await b.put(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`,c);return{id:d.id,fields:d.fields??{},createdTime:d.createdTime}}catch(a){throw aw(a)}}},{name:"airtable_delete_record",description:"Permanently delete a single record from an Airtable table. This is irreversible — confirm the record ID with airtable_get_record before deleting.",inputSchema:aG,riskLevel:"destructive",async execute(a){try{return{id:(await b.delete(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`)).id,deleted:!0}}catch(a){throw aw(a)}}}]}var aJ=c(63850);class aK extends Error{constructor(a,b,c){super(b),this.name="DriveAdapterError",this.code=a,this.status=c}}function aL(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="drive_validation_error";break;case 401:a="drive_unauthorized";break;case 403:a="drive_forbidden";break;case 404:a="drive_not_found";break;case 409:a="drive_conflict";break;case 429:a="drive_rate_limited";break;case 503:a="drive_service_unavailable";break;default:a="drive_unknown"}return new aK(a,c,b)}}return a instanceof aK?a:a instanceof Error?new aK("drive_unknown",a.message):new aK("drive_unknown",String(a))}async function aM(a,b=100,c=100){let d,e=[],f=Math.min(c,1e3);for(let c=0;c<20;c++){let c=Math.min(b,1e3,f-e.length),g=await a(d,c);if(e.push(...g.items),e.length>=f||!g.nextPageToken||0===g.items.length)break;d=g.nextPageToken}return e.slice(0,f)}let aN=g.Ik({query:g.Yj().optional().describe("Google Drive search query. Examples: 'name contains \"resume\"' or '\"folder-id\" in parents' or 'mimeType=\"application/pdf\"'. Leave empty to list recent files."),max_results:g.ai().int().min(1).max(1e3).optional().describe("Max files to return (1–1000, default 20)."),order_by:g.Yj().optional().describe("Sort order. Examples: 'modifiedTime desc', 'name', 'createdTime'. Default: 'modifiedTime desc'.")});var aO=c(17393),aP=c.n(aO);async function aQ(a){return(await aP().extractRawText({buffer:a})).value}var aR=c(20416);async function aS(a){let b=new aR.PDFParse({data:a});return(await b.getText()).text}var aT=c(78608),aU=c.n(aT);async function aV(a){let b=new(aU()).Workbook;await b.xlsx.load(a);let c=[];return b.eachSheet(a=>{c.push(`--- Sheet: ${a.name} ---`);let b=0;a.eachRow(a=>{if(b>=200)return;let d=[];a.eachCell({includeEmpty:!1},a=>{let b=a.value;null==b?d.push(""):"object"==typeof b&&"result"in b?d.push(String(b.result??"")):"object"==typeof b&&b instanceof Date?d.push(b.toISOString().slice(0,10)):d.push(String(b))}),d.length>0&&(c.push(d.join(" ")),b++)}),b>=200&&c.push("[sheet truncated at 200 rows]")}),c.join("\n")}function aW(a){return a.toString("utf-8")}async function aX(a,b,c){if(a.byteLength>0x1900000)throw new aK("drive_file_too_large",`File exceeds the 25 MB extraction limit (${Math.round(a.byteLength/1024/1024)} MB).`);let d=b.toLowerCase(),e=c.toLowerCase();if("application/vnd.openxmlformats-officedocument.wordprocessingml.document"===d||e.endsWith(".docx"))return aQ(a);if("application/pdf"===d||e.endsWith(".pdf"))return aS(a);if("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"===d||e.endsWith(".xlsx"))return aV(a);if("application/vnd.openxmlformats-officedocument.presentationml.presentation"===d||e.endsWith(".pptx"))throw new aK("drive_pptx_extraction_unsupported","PPTX text extraction is not yet supported. Export the file to Google Slides or PDF first.");if("application/json"===d||e.endsWith(".json"))try{let b=a.toString("utf-8"),c=JSON.parse(b);return JSON.stringify(c,null,2)}catch{return aW(a)}if(d.startsWith("text/")||"application/xml"===d||"application/javascript"===d||"application/typescript"===d)return aW(a);try{if((a.slice(0,1e3).toString("utf-8").match(/�/g)??[]).length>20)throw new aK("drive_unknown",`Binary file format (${b||"unknown"}) — cannot extract text.`);return aW(a)}catch(a){if(a instanceof aK)throw a;throw new aK("drive_unknown",`Binary file format (${b||"unknown"}) — cannot extract text.`)}}let aY=g.Ik({file_id:g.Yj().describe("The Google Drive file ID (from drive_list_files or drive_get_file_info).")}),aZ=g.Ik({name:g.Yj().describe("File name including extension, e.g. 'cover_letter.txt'."),content:g.Yj().describe("Text content of the file."),folder_id:g.Yj().optional().describe("Optional Drive folder ID to place the file in."),mime_type:g.Yj().optional().describe("MIME type of the file. Default: 'text/plain'.")}),a$=g.Ik({file_id:g.Yj().describe("Google Drive file ID.")}),a_=g.Ik({name:g.Yj().describe("Folder name."),parent_id:g.Yj().optional().describe("Optional parent folder ID. Creates in root if omitted.")}),a0=g.Ik({file_id:g.Yj().describe("File ID to move."),new_parent_id:g.Yj().describe("Destination folder ID.")}),a1=g.Ik({file_id:g.Yj().describe("File ID to rename."),new_name:g.Yj().describe("New file name (including extension).")}),a2=g.Ik({file_id:g.Yj().describe("File ID to copy."),new_name:g.Yj().optional().describe("Optional name for the copy."),folder_id:g.Yj().optional().describe("Optional destination folder ID for the copy.")}),a3=g.Ik({file_id:g.Yj().describe("File ID to move to trash.")}),a4=g.Ik({file_id:g.Yj().describe("File ID to share."),email:g.Yj().optional().describe("Email address to share with. Omit for link sharing (anyone with link)."),role:g.k5(["reader","writer","commenter","owner"]).optional().describe("Permission role: 'reader', 'writer', 'commenter', or 'owner'. Default: 'reader'."),type:g.k5(["user","group","domain","anyone"]).optional().describe("Permission type: 'user', 'group', 'domain', or 'anyone'. Defaults to 'user' if email provided, 'anyone' otherwise.")}),a5=g.Ik({file_id:g.Yj().describe("File ID to list permissions for.")}),a6=g.Ik({file_id:g.Yj().describe("Google Drive file ID. Must be a Google Workspace file (Doc, Sheet, Slide, etc.)."),mime_type:g.Yj().describe("Target MIME type. Examples: 'text/plain', 'text/csv', 'application/pdf', 'text/html', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'.")});class a7 extends Error{constructor(a,b,c){super(b),this.name="GmailAdapterError",this.code=a,this.status=c}}function a8(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="gmail_validation_error";break;case 401:a="gmail_unauthorized";break;case 403:a="gmail_forbidden";break;case 404:a="gmail_message_not_found";break;case 429:a="gmail_quota_exceeded";break;case 503:a="gmail_service_unavailable";break;default:a="gmail_unknown"}return new a7(a,c,b)}}return a instanceof a7?a:a instanceof Error?new a7("gmail_unknown",a.message):new a7("gmail_unknown",String(a))}async function a9(a,b=100,c=100){let d,e=[],f=Math.min(c,500);for(let c=0;c<20;c++){let c=Math.min(b,500,f-e.length),g=await a(d,c);if(e.push(...g.items),e.length>=f||!g.nextPageToken||0===g.items.length)break;d=g.nextPageToken}return e.slice(0,f)}function ba(a){let b=a.body?.data;if(!b)return"";if(!b)return"";let c=b.replace(/-/g,"+").replace(/_/g,"/"),d=(4-c.length%4)%4,e=c+"=".repeat(d);try{return Buffer.from(e,"base64").toString("utf-8")}catch{return""}}function bb(a){if(!a)return"";let b=a.mimeType??"";if(b.startsWith("text/plain"))return ba(a);if(b.startsWith("text/html"))return ba(a).replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/[ \t]+/g," ").replace(/\n\s*\n\s*\n/g,"\n\n").trim();if(b.startsWith("multipart/")){let b=a.parts??[];for(let a of b)if((a.mimeType??"").startsWith("text/plain")){let b=bb(a);if(b.trim())return b}for(let a of b)if((a.mimeType??"").startsWith("text/html")){let b=bb(a);if(b.trim())return b}for(let a of b)if((a.mimeType??"").startsWith("multipart/")){let b=bb(a);if(b.trim())return b}}return""}function bc(a){let b={};for(let c of a?.headers??[])c.name&&null!=c.value&&(b[c.name.toLowerCase()]=c.value);return b}let bd={".html":"text/html",".htm":"text/html",".csv":"text/csv",".tsv":"text/tab-separated-values",".json":"application/json",".xml":"application/xml",".md":"text/markdown",".markdown":"text/markdown",".txt":"text/plain",".log":"text/plain",".js":"text/javascript",".css":"text/css",".yaml":"application/yaml",".yml":"application/yaml"};function be(a){if(![...a].some(a=>a.charCodeAt(0)>127))return a;let b=Buffer.from(a,"utf-8").toString("base64");return`=?utf-8?B?${b}?=`}function bf(a){let b,{to:c,subject:d,body:e,from:f,cc:g,bcc:h,replyTo:i,inReplyTo:j,references:k,attachments:l}=a,m=l&&l.length>0,n=e.includes("<")&&e.includes(">")&&/<[a-zA-Z][^>]*>/.test(e);if(m){let a=`nodalai_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`,m=Buffer.from(e,"utf-8").toString("base64"),p=[];f&&p.push(`From: ${f}`),p.push(`To: ${c}`),g&&p.push(`Cc: ${g}`),h&&p.push(`Bcc: ${h}`),i&&p.push(`Reply-To: ${i}`),p.push(`Subject: ${be(d)}`),j&&p.push(`In-Reply-To: ${j}`),k&&p.push(`References: ${k}`),p.push("MIME-Version: 1.0"),p.push(`Content-Type: multipart/mixed; boundary="${a}"`);let q=[];for(let b of(q.push([`--${a}`,`Content-Type: ${n?"text/html; charset=utf-8":"text/plain; charset=utf-8"}`,"Content-Transfer-Encoding: base64","",m.match(/.{1,76}/g)?.join("\r\n")??m].join("\r\n")),l)){var o;let c=b.mimeType??bd[(o=b.filename).includes(".")?"."+o.split(".").pop().toLowerCase():""]??"application/octet-stream",d=be(b.filename),e=("base64"===b.encoding?Buffer.from(b.content,"base64"):Buffer.from(b.content,"utf-8")).toString("base64");q.push([`--${a}`,`Content-Type: ${c}; name="${d}"`,"Content-Transfer-Encoding: base64",`Content-Disposition: attachment; filename="${d}"`,"",e.match(/.{1,76}/g)?.join("\r\n")??e].join("\r\n"))}b=p.join("\r\n")+"\r\n\r\n"+q.join("\r\n")+`\r
8
- --${a}--`}else{let a=Buffer.from(e,"utf-8").toString("base64"),l=[];f&&l.push(`From: ${f}`),l.push(`To: ${c}`),g&&l.push(`Cc: ${g}`),h&&l.push(`Bcc: ${h}`),i&&l.push(`Reply-To: ${i}`),l.push(`Subject: ${be(d)}`),j&&l.push(`In-Reply-To: ${j}`),k&&l.push(`References: ${k}`),l.push("MIME-Version: 1.0"),l.push(`Content-Type: ${n?"text/html; charset=utf-8":"text/plain; charset=utf-8"}`),l.push("Content-Transfer-Encoding: base64"),l.push(""),l.push(a.match(/.{1,76}/g)?.join("\r\n")??a),b=l.join("\r\n")}return Buffer.from(b).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}let bg=g.Ik({filename:g.Yj().describe("File name shown in the email, e.g. 'report.html'."),content:g.Yj().describe("File content as a string (plain text by default, or base64 if encoding is base64)."),mimeType:g.Yj().optional().describe("MIME type, e.g. 'text/html'. Inferred from filename if omitted."),encoding:g.k5(["text","base64"]).optional().describe("How content is encoded. Default 'text'. Use 'base64' for pre-encoded binaries.")}),bh=g.Ik({to:g.Yj().describe("Recipient email address or comma-separated list."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),reply_to:g.Yj().optional().describe("Reply-To header."),attachments:g.YO(bg).optional().describe("Optional file attachments. Each item: {filename, content, mimeType?, encoding?}. Default encoding is 'text' — pass the file content as a plain string. Use encoding='base64' only when you hold pre-encoded binary content.")}),bi=g.Ik({query:g.Yj().optional().describe("Gmail search query. Examples: 'is:unread', 'from:alice@example.com', 'subject:invoice newer_than:7d'. Default: lists recent messages in inbox."),max_results:g.ai().int().min(1).max(500).optional().describe("Max messages to return (1–500, default 20)."),include_spam_trash:g.zM().optional().describe("Include messages from SPAM and TRASH (default false).")}),bj=g.Ik({message_id:g.Yj().describe("Gmail message ID (from gmail_list_messages).")}),bk=g.Ik({message_id:g.Yj().describe("ID of the message to reply to."),body:g.Yj().describe("Reply body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),attachments:g.YO(bg).optional().describe("Optional attachments to include with the reply.")}),bl=g.Ik({message_id:g.Yj().describe("ID of the message to forward."),to:g.Yj().describe("Recipient(s), comma-separated."),note:g.Yj().optional().describe("Optional note prepended before the forwarded body."),cc:g.Yj().optional().describe("CC address(es), comma-separated.")}),bm=g.Ik({message_id:g.Yj().describe("Gmail message ID."),add_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to add, e.g. ['STARRED', 'IMPORTANT']."),remove_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to remove, e.g. ['UNREAD', 'INBOX'].")}),bn=g.Ik({message_id:g.Yj().describe("Gmail message ID to move to Trash.")}),bo=g.Ik({message_id:g.Yj().describe("Gmail message ID to restore from Trash.")}),bp=g.Ik({message_id:g.Yj().describe("Gmail message ID to permanently delete.")}),bq=g.Ik({query:g.Yj().optional().describe("Gmail search query. Examples: 'is:unread', 'from:alice@example.com label:work'."),max_results:g.ai().int().min(1).max(500).optional().describe("Max threads to return (1–500, default 20)."),include_spam_trash:g.zM().optional().describe("Include threads from SPAM and TRASH (default false).")}),br=g.Ik({thread_id:g.Yj().describe("Gmail thread ID (from gmail_list_threads or gmail_list_messages).")}),bs=g.Ik({thread_id:g.Yj().describe("Gmail thread ID."),add_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to add to all messages in the thread, e.g. ['STARRED']."),remove_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to remove from all messages, e.g. ['UNREAD'].")}),bt=g.Ik({thread_id:g.Yj().describe("Gmail thread ID to move to Trash.")}),bu=g.Ik({}),bv=g.Ik({label_id:g.Yj().describe("Label ID (from gmail_list_labels). System labels: 'INBOX', 'SENT', etc.")}),bw=g.Ik({name:g.Yj().describe("Label name. Use '/' for nesting, e.g. 'Clients/Acme'."),label_list_visibility:g.k5(["labelShow","labelShowIfUnread","labelHide"]).optional().describe("Sidebar visibility (default labelShow)."),message_list_visibility:g.k5(["show","hide"]).optional().describe("Visibility in message list (default show).")}),bx=g.Ik({label_id:g.Yj().describe("Label ID to update (from gmail_list_labels)."),name:g.Yj().optional().describe("New label name."),label_list_visibility:g.k5(["labelShow","labelShowIfUnread","labelHide"]).optional().describe("Sidebar visibility."),message_list_visibility:g.k5(["show","hide"]).optional().describe("Message list visibility.")}),by=g.Ik({label_id:g.Yj().describe("Label ID to permanently delete (cannot delete system labels like INBOX).")}),bz=g.Ik({filename:g.Yj().describe("File name shown in the email, e.g. 'report.html'."),content:g.Yj().describe("File content as a string (plain text by default)."),mimeType:g.Yj().optional().describe("MIME type. Inferred from filename if omitted."),encoding:g.k5(["text","base64"]).optional().describe("'text' (default) or 'base64' for binaries.")}),bA=g.Ik({max_results:g.ai().int().min(1).max(500).optional().describe("Max drafts to return (default 20)."),query:g.Yj().optional().describe("Optional Gmail search query.")}),bB=g.Ik({to:g.Yj().describe("Recipient email address."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),reply_to_message_id:g.Yj().optional().describe("If provided, sets In-Reply-To and threadId so this draft is a reply in-thread."),attachments:g.YO(bz).optional().describe("Optional file attachments.")}),bC=g.Ik({draft_id:g.Yj().describe("Draft ID to update (from gmail_list_drafts or gmail_create_draft)."),to:g.Yj().describe("Recipient email address."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),attachments:g.YO(bz).optional().describe("Optional file attachments.")}),bD=g.Ik({draft_id:g.Yj().describe("Draft ID to send (from gmail_list_drafts or gmail_create_draft).")}),bE=g.Ik({draft_id:g.Yj().describe("Draft ID to permanently delete.")}),bF=g.Ik({message_id:g.Yj().describe("Gmail message ID containing the attachment."),attachment_id:g.Yj().describe("Attachment ID (from gmail_get_message attachments list)."),filename:g.Yj().optional().describe("Filename hint (for display only, not required).")}),bG=g.Ik({start_history_id:g.Yj().describe("The historyId to start listing changes from. Get an initial historyId from gmail_list_messages or gmail_get_message (historyId field)."),max_results:g.ai().int().min(1).max(500).optional().describe("Max history records to return (default 100)."),label_id:g.Yj().optional().describe("Filter history records by label ID.")});class bH extends Error{constructor(a,b,c){super(b),this.name="GoogleCalendarAdapterError",this.code=a,this.status=c}}function bI(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="gcal_validation_error";break;case 401:a="gcal_unauthorized";break;case 403:a="gcal_forbidden";break;case 404:a="gcal_event_not_found";break;case 429:a="gcal_quota_exceeded";break;case 503:a="gcal_service_unavailable";break;default:a="gcal_unknown"}return new bH(a,c,b)}}return a instanceof bH?a:a instanceof Error?new bH("gcal_unknown",a.message):new bH("gcal_unknown",String(a))}function bJ(a){let b=a.start?.dateTime??a.start?.date??"",c=a.end?.dateTime??a.end?.date??"";return{id:a.id??"",summary:a.summary??"",description:a.description??"",location:a.location??"",status:a.status??"",start:b,end:c,allDay:!!a.start?.date&&!a.start?.dateTime,htmlLink:a.htmlLink??"",attendees:(a.attendees??[]).map(a=>a.email??"").filter(a=>""!==a),organizer:a.organizer?.email??""}}let bK=g.Yj().optional().describe("Calendar ID (from gcal_list_calendars). Defaults to 'primary'."),bL=g.Ik({calendar_id:bK,time_min:g.Yj().optional().describe("ISO 8601 lower bound (inclusive). Defaults to now — i.e. upcoming events."),time_max:g.Yj().optional().describe("ISO 8601 upper bound (exclusive)."),query:g.Yj().optional().describe("Free-text search over event fields."),max_results:g.ai().int().min(1).max(250).optional().describe("Max events to return (default 25).")}),bM=g.Ik({calendar_id:bK,event_id:g.Yj().describe("Event ID (from gcal_list_events).")}),bN=g.Ik({calendar_id:bK,summary:g.Yj().describe("Event title."),start:g.Yj().describe("Start time. ISO 8601 datetime (e.g. 2026-07-01T14:00:00+02:00) or YYYY-MM-DD for an all-day event."),end:g.Yj().describe("End time. ISO 8601 datetime or YYYY-MM-DD (exclusive) for an all-day event."),description:g.Yj().optional().describe("Event description/notes."),location:g.Yj().optional().describe("Event location."),attendees:g.YO(g.Yj()).optional().describe("Attendee email addresses to invite."),time_zone:g.Yj().optional().describe("IANA time zone for the times (e.g. 'Europe/Paris').")});function bO(a,b){return/^\d{4}-\d{2}-\d{2}$/.test(a)?{date:a}:b?{dateTime:a,timeZone:b}:{dateTime:a}}let bP=g.Ik({calendar_id:bK,event_id:g.Yj().describe("Event ID to update (from gcal_list_events)."),summary:g.Yj().optional().describe("New event title."),start:g.Yj().optional().describe("New start (ISO 8601 datetime or YYYY-MM-DD)."),end:g.Yj().optional().describe("New end (ISO 8601 datetime or YYYY-MM-DD)."),description:g.Yj().optional().describe("New description."),location:g.Yj().optional().describe("New location."),attendees:g.YO(g.Yj()).optional().describe("Replace the attendee email list."),time_zone:g.Yj().optional().describe("IANA time zone for the times.")}),bQ=g.Ik({calendar_id:bK,event_id:g.Yj().describe("Event ID to permanently delete.")}),bR=g.Ik({}),bS=g.Ik({time_min:g.Yj().describe("ISO 8601 start of the window to check."),time_max:g.Yj().describe("ISO 8601 end of the window to check."),calendar_ids:g.YO(g.Yj()).optional().describe("Calendar IDs to check (default ['primary']).")});class bT extends Error{constructor(a,b,c){super(b),this.name="SheetsAdapterError",this.code=a,this.status=c}}function bU(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:{let b=c.toLowerCase();a=b.includes("range")||b.includes("a1 notation")||b.includes("unable to parse")?"sheets_invalid_range":"sheets_validation_error";break}case 401:a="sheets_unauthorized";break;case 403:a="sheets_forbidden";break;case 404:a="sheets_not_found";break;case 429:a="sheets_rate_limited";break;case 503:a="sheets_service_unavailable";break;default:a="sheets_unknown"}return new bT(a,c,b)}}return a instanceof bT?a:a instanceof Error?new bT("sheets_unknown",a.message):new bT("sheets_unknown",String(a))}function bV(a){return null==a?"":"number"==typeof a||"boolean"==typeof a||"string"==typeof a?a:String(a)}function bW(a){return a.map(bV)}function bX(a){return a?a.map(bW):[]}function bY(a){let b,c,d,e=a.trim();if(!e)throw new bT("sheets_invalid_range","Empty range string");let f=e.indexOf("!");if(-1!==f){let a=e.slice(0,f);c=e.slice(f+1),a.startsWith("'")&&a.endsWith("'")&&(a=a.slice(1,-1).replace(/''/g,"'")),b=a}else c=e,b=void 0;if(!c||!/^[A-Za-z0-9:$]+$/.test(c))throw new bT("sheets_invalid_range",`Invalid cell range portion: '${c}' in '${a}'`);if(void 0!==b){let a=/[\s!'"\\]/.test(b)?`'${b.replace(/'/g,"''")}'`:b;d=`${a}!${c}`}else d=c;return{sheetName:b,cellRange:c,canonical:d}}let bZ=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range, e.g. 'Sheet1!A1:D10' or 'A:A' for a full column."),value_render_option:g.k5(["FORMATTED_VALUE","UNFORMATTED_VALUE","FORMULA"]).optional().describe("How values are rendered. FORMATTED_VALUE (default) returns display strings. UNFORMATTED_VALUE returns raw numbers/booleans. FORMULA returns formula strings.")}),b$=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_name:g.Yj().optional().describe("Sheet tab name (default: first sheet).")}),b_=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),ranges:g.YO(g.Yj()).min(1).max(50).describe("Array of A1-notation ranges to read in a single API call (max 50)."),value_render_option:g.k5(["FORMATTED_VALUE","UNFORMATTED_VALUE","FORMULA"]).optional().describe("How values are rendered (default FORMATTED_VALUE).")}),b0=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range. The top-left cell anchors the write, e.g. 'Sheet1!A1'."),values:g.YO(g.YO(g.L5())).describe("2D array of values to write. Example: [['Name','Score'],['Alice',95]]."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas like a human typing (default).")}),b1=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("Sheet name or range that identifies where to append, e.g. 'Sheet1' or 'Sheet1!A:Z'. Sheets auto-detects the last row with data and appends after it."),values:g.YO(g.YO(g.L5())).describe("2D array of rows to append. For a single row: [['Name','Score']]. For multiple: [['Alice',95],['Bob',87]]."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas (default).")}),b2=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range to clear, e.g. 'Sheet1!A2:Z100'. Formatting is preserved.")}),b3=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),updates:g.YO(g.Ik({range:g.Yj().describe("A1-notation range, e.g. 'Sheet1!A1'."),values:g.YO(g.YO(g.L5())).describe("2D array of values to write.")})).min(1).max(50).describe("Array of range+values pairs to write in a single API call (max 50)."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas (default).")}),b4=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_name:g.Yj().optional().describe("Sheet tab name (default: first sheet)."),column:g.Yj().describe("Header name of the column to search (from row 1)."),equals:g.Yj().optional().describe("Return rows where the column value exactly equals this string."),contains:g.Yj().optional().describe("Return rows where the column value contains this substring (case-sensitive)."),limit:g.ai().int().min(1).max(1e3).optional().describe("Max matching rows to return (default 100, max 1000).")}),b5=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit).")}),b6=g.Ik({title:g.Yj().describe("Title for the new spreadsheet."),sheet_title:g.Yj().optional().describe("Title for the first sheet tab (default: 'Sheet1').")}),b7=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),title:g.Yj().describe("Title for the new sheet tab."),index:g.ai().int().min(0).optional().describe("Zero-based position to insert the sheet (default: appended at end).")}),b8=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID (not the tab name). Get it from sheets_get_metadata.")}),b9=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),source_sheet_id:g.ai().int().describe("Numeric ID of the sheet to duplicate. Get it from sheets_get_metadata."),new_sheet_name:g.Yj().optional().describe('Name for the duplicated sheet (defaults to "Copy of <original>").'),insert_sheet_index:g.ai().int().min(0).optional().describe("Zero-based position to insert the duplicate (default: appended at end).")}),ca=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),new_title:g.Yj().describe("New tab name for the sheet.")}),cb=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive)."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive). E.g. rows 0–1 → endRowIndex=1."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive). E.g. columns 0–3 → endColumnIndex=3."),bold:g.zM().optional().describe("Set bold text."),italic:g.zM().optional().describe("Set italic text."),font_size:g.ai().int().min(1).optional().describe("Font size in points."),background_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Background fill color (RGB, each channel 0–1)."),foreground_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Text foreground color (RGB, each channel 0–1)."),number_format:g.Ik({type:g.k5(["TEXT","NUMBER","PERCENT","CURRENCY","DATE","TIME","DATE_TIME","SCIENTIFIC"]).describe("Number format type."),pattern:g.Yj().optional().describe("Optional format pattern, e.g. '#,##0.00' for currency.")}).optional().describe("Number format to apply."),horizontal_alignment:g.k5(["LEFT","CENTER","RIGHT"]).optional().describe("Horizontal text alignment.")}),cc=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive). E.g. columns 0–3 → endColumnIndex=3."),pixel_size:g.ai().int().min(0).optional().describe("Column width in pixels. Omit to auto-resize to fit content.")}),cd=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),frozen_row_count:g.ai().int().min(0).optional().describe("Number of rows to freeze at the top (0 to unfreeze, default 0)."),frozen_column_count:g.ai().int().min(0).optional().describe("Number of columns to freeze at the left (0 to unfreeze, default 0).")}),ce=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive). Usually 0 for the header row."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive)."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive).")}),cf=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata.")}),cg=g.Ik({dimension_index:g.ai().int().min(0).describe("Zero-based column index to sort by."),sort_order:g.k5(["ASCENDING","DESCENDING"]).describe("Sort direction: 'ASCENDING' or 'DESCENDING'.")}),ch=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive). Set to 1 to exclude the header row."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive)."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive)."),sort_specs:g.YO(cg).min(1).describe("Array of sort specs (primary, secondary, ...). Each: { dimension_index, sort_order }. Example: [{ dimension_index: 2, sort_order: 'DESCENDING' }].")});class ci extends Error{constructor(a,b,c){super(b),this.name="DocsAdapterError",this.code=a,this.status=c}}function cj(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="docs_invalid_request";break;case 401:a="docs_unauthorized";break;case 403:a="docs_forbidden";break;case 404:a="docs_not_found";break;case 429:a="docs_rate_limited";break;case 503:a="docs_service_unavailable";break;default:a="docs_unknown"}return new ci(a,c,b)}}return a instanceof ci?a:a instanceof Error?new ci("docs_unknown",a.message):new ci("docs_unknown",String(a))}function ck(a){let b=[];for(let c of a.content??[])c.paragraph?b.push(cl(c.paragraph)):c.table?b.push(function(a){let b=[];for(let c of a.tableRows??[]){let a=[];for(let b of c.tableCells??[]){let c=(b.content??[]).map(a=>a.paragraph?cl(a.paragraph):"").join("").replace(/\n$/,"");a.push(c)}b.push(a.join(" ")+"\n")}return b.join("")}(c.table)):c.sectionBreak&&b.push("\n");return b.join("")}function cl(a){let b=[];for(let c of a.elements??[])c.textRun?.content?b.push(c.textRun.content):c.inlineObjectElement?b.push("[image]"):c.horizontalRule&&b.push("\n---\n");return b.join("")}function cm(a){return{insertText:{endOfSegmentLocation:{segmentId:""},text:a}}}function cn(a,b,c){return{updateParagraphStyle:{range:{startIndex:a,endIndex:b},paragraphStyle:{namedStyleType:c},fields:"namedStyleType"}}}let co=g.Ik({title:g.Yj().describe("Title for the new document."),content:g.Yj().optional().describe("Optional initial text content to insert into the document body.")}),cp=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit).")}),cq=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit).")}),cr=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Text to insert."),index:g.ai().int().min(1).describe("Document body index at which to insert text. Index 1 = beginning of body. Use docs_get to inspect element indices. Insertions shift all subsequent content.")}),cs=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Text to append at the end of the document. Use \\n for line breaks.")}),ct=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),find:g.Yj().describe("The exact text string to find in the document."),replace:g.Yj().describe("The text to replace all found occurrences with."),match_case:g.zM().optional().describe("Whether to match case exactly (default: true).")}),cu=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the range to delete (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the range to delete (exclusive). Content at [startIndex, endIndex) is removed.")}),cv=g.k5(["NORMAL_TEXT","TITLE","SUBTITLE","HEADING_1","HEADING_2","HEADING_3","HEADING_4","HEADING_5","HEADING_6"]),cw=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Paragraph text. A newline is appended automatically if not present."),index:g.ai().int().min(1).describe("Document body index at which to insert the paragraph. Index 1 = beginning of body. Use docs_get to find indices."),named_style:cv.optional().describe("Optional named paragraph style to apply after inserting (e.g. HEADING_1, NORMAL_TEXT).")}),cx=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),index:g.ai().int().min(1).describe("Document body index at which to insert the page break.")}),cy=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),index:g.ai().int().min(1).describe("Document body index at which to insert the table."),rows:g.ai().int().min(1).max(100).describe("Number of rows in the table (1–100)."),columns:g.ai().int().min(1).max(20).describe("Number of columns in the table (1–20).")}),cz=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),image_uri:g.Yj().url().describe("Public URL of the image to insert (must be publicly accessible)."),index:g.ai().int().min(1).describe("Document body index at which to insert the image."),width_pt:g.ai().positive().optional().describe("Optional image width in points (1pt ≈ 1.333px). Omit to use source dimensions."),height_pt:g.ai().positive().optional().describe("Optional image height in points. Omit to use source dimensions.")}),cA=g.k5(["NORMAL_TEXT","TITLE","SUBTITLE","HEADING_1","HEADING_2","HEADING_3","HEADING_4","HEADING_5","HEADING_6"]),cB=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the text range to format (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the text range to format (exclusive)."),bold:g.zM().optional().describe("Apply bold formatting."),italic:g.zM().optional().describe("Apply italic formatting."),underline:g.zM().optional().describe("Apply underline formatting."),strikethrough:g.zM().optional().describe("Apply strikethrough formatting."),font_size_pt:g.ai().positive().optional().describe("Font size in points (e.g. 12, 14, 18)."),foreground_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Text foreground color (RGB, each channel 0–1)."),font_family:g.Yj().optional().describe('Font family name (e.g. "Arial", "Times New Roman", "Roboto").')}),cC=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the paragraph range (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the paragraph range (exclusive)."),named_style:cA.describe("The paragraph style to apply: NORMAL_TEXT, TITLE, SUBTITLE, HEADING_1 through HEADING_6.")}),cD=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),requests:g.YO(g.g1(g.Yj(),g.L5())).min(1).describe("Array of Google Docs API Request objects. Each object must have exactly one key matching a Docs API operation (e.g. insertText, deleteContentRange, updateParagraphStyle, replaceAllText, etc.). See https://developers.google.com/docs/api/reference/rest/v1/documents/request for the full schema.")});var cE=c(19199);class cF extends Error{constructor(a,b,c){super(b),this.name="FirecrawlApiError",this.code=a,this.status=c}}function cG(a){return a instanceof cF?a:a instanceof Error?new cF("firecrawl_unknown",a.message):new cF("firecrawl_unknown",String(a))}let cH=g.Ik({url:g.Yj().url().describe("The URL to scrape."),formats:g.YO(g.k5(["markdown","html","links"])).optional().default(["markdown"]).describe("Content formats to return. Defaults to ['markdown'].")}),cI=g.Ik({url:g.Yj().url().describe("The root URL whose site to map."),search:g.Yj().optional().describe("Optional keyword filter — only return URLs matching this term.")}),cJ=g.Ik({query:g.Yj().min(1).describe("The search query to send to Firecrawl."),limit:g.ai().int().min(1).max(100).optional().describe("Maximum number of results to return (1–100).")}),cK=g.Ik({url:g.Yj().url().describe("The root URL to crawl."),limit:g.ai().int().min(1).max(100).optional().describe("Maximum number of pages to crawl (1–100).")}),cL=g.Ik({id:g.Yj().min(1).describe("The crawl job ID returned by firecrawl_crawl_start.")});var cM=c(25459),cN=c(99740);let cO=g.Ik({query:g.Yj().min(1).describe("A web page URL to scrape, OR free-text search terms. A URL returns that page; search terms return the top results."),maxResults:g.ai().int().min(1).max(10).optional().describe("For a search query, how many results to return (default 3). Ignored for a single URL.")});function cP(a){return Array.from(a).filter(a=>{let b=a.charCodeAt(0);return 9===b||10===b||13===b||b>=32&&127!==b}).join("")}function cQ(a){let b=a??{},c=b.metadata??{},d=b.searchResult??{},e=b.crawl??{},f=a=>"string"==typeof a?a:"";return{url:f(c.url)||f(d.url)||f(e.loadedUrl)||f(b.url),title:cP(f(c.title)||f(d.title)||f(b.title)),content:cP(f(b.text)||f(b.markdown)||"")}}let cR=g.Ik({actorId:g.Yj().describe('The actor ID or name in the format "owner/actor-name" (e.g. "apify/web-scraper") or just the actor ID.'),input:g.g1(g.Yj(),g.L5()).optional().describe("Input object to pass to the actor. Structure depends on the actor. Omit to use actor defaults.")}),cS=g.Ik({runId:g.Yj().describe("The Apify run ID to retrieve metadata for.")}),cT=g.Ik({limit:g.ai().int().min(1).max(1e3).optional().default(100).describe("Maximum number of datasets to return (default 100, max 1000)."),offset:g.ai().int().min(0).optional().default(0).describe("Number of datasets to skip (for pagination). Default 0.")}),cU=g.Ik({datasetId:g.Yj().describe("The Apify dataset ID to read from. Use apify_run_actor to get the datasetId from a run, or apify_list_datasets to browse existing datasets."),limit:g.ai().int().min(1).max(1e3).optional().default(100).describe("Maximum number of items to return (default 100, max 1000)."),offset:g.ai().int().min(0).optional().default(0).describe("Number of items to skip (for pagination). Default 0.")});var cV=c(43845);class cW extends Error{constructor(a,b,c){super(b),this.name="TavilyApiError",this.code=a,this.status=c}}function cX(a){if(a instanceof cW)return a;if(a instanceof Error){let d=/status[:\s]+(\d{3})/i.exec(a.message);if(d){let e;var b=parseInt(d[1]??"0",10),c=a.message;switch(!0){case 401===b:e="tavily_unauthorized";break;case 403===b:e="tavily_forbidden";break;case 404===b:e="tavily_not_found";break;case 422===b:e="tavily_validation_error";break;case 429===b:e="tavily_rate_limited";break;case b>=500:e="tavily_transient";break;default:e="tavily_client_error"}return new cW(e,c,b)}return new cW("tavily_unknown",a.message)}return new cW("tavily_unknown",String(a))}let cY=g.Ik({query:g.Yj().min(1).describe("The search query to send to Tavily."),searchDepth:g.k5(["basic","advanced"]).optional().describe('Search depth: "basic" is faster, "advanced" is more thorough. Default: "basic".'),maxResults:g.ai().int().min(1).max(20).optional().describe("Maximum number of results to return (1–20, default 5)."),includeImages:g.zM().optional().describe("Whether to include image results. Default: false."),topic:g.k5(["general","news"]).optional().describe('Search topic category: "general" or "news". Default: "general".')}),cZ=g.Ik({urls:g.YO(g.Yj().url()).min(1).max(20).describe("Array of URLs to extract content from (max 20)."),extractDepth:g.k5(["basic","advanced"]).optional().describe('Extraction depth: "basic" or "advanced". Default: "basic".')}),c$=g.Ik({url:g.Yj().url().describe("The seed URL to start crawling from."),maxDepth:g.ai().int().min(1).max(5).optional().describe("Maximum link depth to follow from the seed URL (1–5, default 1)."),limit:g.ai().int().min(1).max(50).optional().describe("Maximum number of pages to scrape (1–50, default 10).")});class c_ extends Error{constructor(a,b,c){super(b),this.name="PoyoApiError",this.code=a,this.status=c}}function c0(a,b){let c;switch(!0){case 401===a:c="poyo_unauthorized";break;case 403===a:c="poyo_forbidden";break;case 404===a:c="poyo_not_found";break;case 422===a:c="poyo_validation_error";break;case 429===a:c="poyo_rate_limited";break;case a>=500:c="poyo_transient";break;default:c="poyo_client_error"}return new c_(c,b,a)}async function c1(a){try{return await a.text()}catch{return`HTTP ${a.status}`}}let c2={intervalMs:4e3,maxAttempts:45},c3=g.Ik({prompt:g.Yj().min(1).describe("Text description of the image to generate."),model:g.Yj().min(1).optional().describe('Poyo image model id. Default "gpt-4o-image". Pass another Poyo image model id (see poyo.ai) to switch model.'),size:g.Yj().min(1).optional().describe('Aspect ratio of the image, e.g. "1:1", "16:9", "9:16", "4:3". Default "1:1".')}),c4=a=>new Promise(b=>setTimeout(b,a)),c5={"google-drive":{credentialType:"google-oauth",toolFactory:a=>{let b,d;return(b=new aJ.google.auth.OAuth2).setCredentials({access_token:a}),[(d=aJ.google.drive({version:"v3",auth:b}),{name:"drive_list_files",description:"List files in Google Drive. Optionally filter by folder or search query. Returns file names and IDs needed for drive_read_file.",inputSchema:aN,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,1e3),c=await aM(async(b,c)=>{let e={pageSize:c,fields:"nextPageToken,files(id,name,mimeType,modifiedTime,size)",orderBy:a.order_by??"modifiedTime desc",...b&&{pageToken:b},...a.query&&{q:a.query}},f=await d.files.list(e);return{items:f.data.files??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b);return{total:c.length,files:c.map(a=>({id:a.id??"",name:a.name??"",mimeType:a.mimeType??"",modifiedTime:a.modifiedTime??"",size:null!=a.size?Number(a.size):null}))}}catch(a){throw aL(a)}}}),{name:"drive_read_file",description:"Read the text content of a file from Google Drive. Handles Google Docs (exported as plain text), plain text, DOCX, PDF, XLSX. Use drive_list_files first to get the file ID.",inputSchema:aY,riskLevel:"read",async execute(a){try{let b,c=(await d.files.get({fileId:a.file_id,fields:"id,name,mimeType,size"})).data,e=c.mimeType??"",f=c.name??"",g=null!=c.size?Number(c.size):null;if(null!=g&&g>0x1900000)throw new aK("drive_file_too_large",`File exceeds the 25 MB extraction limit (${Math.round(g/1024/1024)} MB).`);if(e.startsWith("application/vnd.google-apps.")){let c;c="application/vnd.google-apps.document"===e?"text/plain":"application/vnd.google-apps.spreadsheet"===e?"text/csv":"text/plain";let f=await d.files.export({fileId:a.file_id,mimeType:c},{responseType:"text"});b="string"==typeof f.data?f.data:String(f.data)}else{let c=await d.files.get({fileId:a.file_id,alt:"media"},{responseType:"arraybuffer"}),g=Buffer.from(c.data);b=await aX(g,e,f)}let h=b.length>15e3,i=h?b.slice(0,15e3)+"\n\n[...file truncated at 15000 chars...]":b;return{file_id:a.file_id,name:f,mimeType:e,content:i,truncated:h,char_count:i.length}}catch(a){throw aL(a)}}},{name:"drive_get_file_info",description:"Get detailed metadata for a file: size, owner, sharing status, dates, MIME type, parent folders.",inputSchema:a$,riskLevel:"read",async execute(a){try{let b=(await d.files.get({fileId:a.file_id,fields:"id,name,mimeType,size,createdTime,modifiedTime,owners,shared,webViewLink,parents"})).data,c=(b.owners??[]).map(a=>a.displayName??a.emailAddress??"");return{id:b.id??"",name:b.name??"",mimeType:b.mimeType??"",sizeBytes:null!=b.size?Number(b.size):null,createdTime:b.createdTime??"",modifiedTime:b.modifiedTime??"",owners:c,shared:b.shared??!1,webViewLink:b.webViewLink??"",parents:b.parents??[]}}catch(a){throw aL(a)}}},{name:"drive_list_permissions",description:"List who has access to a file and their permission levels.",inputSchema:a5,riskLevel:"read",async execute(a){try{let b=((await d.permissions.list({fileId:a.file_id,fields:"permissions(id,role,type,emailAddress,displayName)"})).data.permissions??[]).map(a=>({id:a.id??"",role:a.role??"",type:a.type??"",email:a.emailAddress??null,displayName:a.displayName??null}));return{total:b.length,permissions:b}}catch(a){throw aL(a)}}},{name:"drive_export_file",description:"Export a Google Workspace file (Doc, Sheet, Slide) to a different format. Common: Google Doc → text/plain or application/pdf, Google Sheet → text/csv, Google Slides → application/pdf. Use drive_read_file for regular (non-Workspace) files.",inputSchema:a6,riskLevel:"read",async execute(a){try{if(a.mime_type.startsWith("text/")||"application/json"===a.mime_type){let b=await d.files.export({fileId:a.file_id,mimeType:a.mime_type},{responseType:"text"}),c="string"==typeof b.data?b.data:String(b.data),e=c.length>15e3,f=e?c.slice(0,15e3)+"\n\n[...export truncated at 15000 chars...]":c;return{file_id:a.file_id,mime_type:a.mime_type,content:f,truncated:e,byte_size:Buffer.byteLength(c,"utf-8")}}{let b=(await d.files.export({fileId:a.file_id,mimeType:a.mime_type},{responseType:"arraybuffer"})).data.byteLength;return{file_id:a.file_id,mime_type:a.mime_type,content:`Binary export complete (${b} bytes). Use a text-based MIME type (e.g. text/plain, text/csv) to get readable content.`,truncated:!1,byte_size:b}}}catch(a){throw aL(a)}}},{name:"drive_upload_file",description:"Create a new file in Google Drive with text content.",inputSchema:aZ,riskLevel:"write",async execute(a){try{let b=a.mime_type??"text/plain",e={name:a.name,mimeType:b,...a.folder_id&&{parents:[a.folder_id]}},{Readable:f}=await Promise.resolve().then(c.t.bind(c,27910,23)),g={mimeType:b,body:f.from([Buffer.from(a.content,"utf-8")])},h=await d.files.create({requestBody:e,media:g,fields:"id,name,webViewLink"});return{id:h.data.id??"",name:h.data.name??a.name,webViewLink:h.data.webViewLink??""}}catch(a){throw aL(a)}}},{name:"drive_create_folder",description:"Create a new folder in Google Drive.",inputSchema:a_,riskLevel:"write",async execute(a){try{let b={name:a.name,mimeType:"application/vnd.google-apps.folder",...a.parent_id&&{parents:[a.parent_id]}},c=await d.files.create({requestBody:b,fields:"id,name,webViewLink"});return{id:c.data.id??"",name:c.data.name??a.name,webViewLink:c.data.webViewLink??""}}catch(a){throw aL(a)}}},{name:"drive_move_file",description:"Move a file to a different folder in Google Drive.",inputSchema:a0,riskLevel:"write",async execute(a){try{let b=((await d.files.get({fileId:a.file_id,fields:"id,name,parents"})).data.parents??[]).join(","),c=await d.files.update({fileId:a.file_id,addParents:a.new_parent_id,removeParents:b||void 0,fields:"id,name,parents"});return{id:c.data.id??"",name:c.data.name??"",parents:c.data.parents??[]}}catch(a){throw aL(a)}}},{name:"drive_rename_file",description:"Rename a file in Google Drive.",inputSchema:a1,riskLevel:"write",async execute(a){try{let b=await d.files.update({fileId:a.file_id,requestBody:{name:a.new_name},fields:"id,name"});return{id:b.data.id??"",name:b.data.name??a.new_name}}catch(a){throw aL(a)}}},{name:"drive_copy_file",description:"Create a copy of a file in Google Drive.",inputSchema:a2,riskLevel:"write",async execute(a){try{let b={};a.new_name&&(b.name=a.new_name),a.folder_id&&(b.parents=[a.folder_id]);let c=await d.files.copy({fileId:a.file_id,requestBody:Object.keys(b).length>0?b:void 0,fields:"id,name,webViewLink"});return{id:c.data.id??"",name:c.data.name??"",webViewLink:c.data.webViewLink??""}}catch(a){throw aL(a)}}},{name:"drive_share_file",description:"Share a file with a user or make it accessible via link. Provide email for user sharing, or omit for anyone-with-link sharing.",inputSchema:a4,riskLevel:"write",async execute(a){try{let b=a.role??"reader",c=a.type??(a.email?"user":"anyone"),e={role:b,type:c,...a.email&&{emailAddress:a.email}},f=await d.permissions.create({fileId:a.file_id,requestBody:e,fields:"id,role,type,emailAddress",sendNotificationEmail:"user"===c||"group"===c});return{permission_id:f.data.id??"",role:f.data.role??b,type:f.data.type??c,email:f.data.emailAddress??null}}catch(a){throw aL(a)}}},{name:"drive_delete_file",description:"Move a file to trash in Google Drive. This is reversible — the file can be restored from the Drive trash.",inputSchema:a3,riskLevel:"destructive",async execute(a){try{let b=await d.files.update({fileId:a.file_id,requestBody:{trashed:!0},fields:"id,name,trashed"});return{id:b.data.id??"",name:b.data.name??"",trashed:b.data.trashed??!0}}catch(a){throw aL(a)}}}]},operations:[{slug:"drive_list_files",name:"List files",risk:"read",requiresApproval:!1,description:"Search and list files in Google Drive."},{slug:"drive_read_file",name:"Read file",risk:"read",requiresApproval:!1,description:"Download and read file content."},{slug:"drive_get_file_info",name:"Get file info",risk:"read",requiresApproval:!1,description:"Retrieve file metadata (name, size, mimeType, owners)."},{slug:"drive_list_permissions",name:"List permissions",risk:"read",requiresApproval:!1,description:"List sharing permissions on a file or folder."},{slug:"drive_export_file",name:"Export file",risk:"read",requiresApproval:!1,description:"Export a Google Workspace file (Docs, Sheets) to a target format."},{slug:"drive_upload_file",name:"Upload file",risk:"write",requiresApproval:!1,description:"Upload a new file to Google Drive."},{slug:"drive_create_folder",name:"Create folder",risk:"write",requiresApproval:!1,description:"Create a new folder."},{slug:"drive_move_file",name:"Move file",risk:"write",requiresApproval:!1,description:"Move a file to a different folder."},{slug:"drive_rename_file",name:"Rename file",risk:"write",requiresApproval:!1,description:"Rename a file or folder."},{slug:"drive_copy_file",name:"Copy file",risk:"write",requiresApproval:!1,description:"Make a copy of a file."},{slug:"drive_share_file",name:"Share file",risk:"write",requiresApproval:!1,description:"Add or update sharing permissions on a file."},{slug:"drive_delete_file",name:"Delete file",risk:"destructive",requiresApproval:!0,description:"Permanently delete a file or folder from Google Drive."}]},gmail:{credentialType:"google-oauth",toolFactory:a=>{let b,c;return(b=new aJ.google.auth.OAuth2).setCredentials({access_token:a}),[(c=aJ.google.gmail({version:"v1",auth:b}),{name:"gmail_list_messages",description:"List Gmail messages matching a query. Returns message IDs, thread IDs, sender, subject, date and snippet. Use gmail_get_message to read the full body, or gmail_get_thread for the full conversation.",inputSchema:bi,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),d=await a9(async(b,d)=>{let e={userId:"me",maxResults:d,includeSpamTrash:a.include_spam_trash??!1,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await c.users.messages.list(e);return{items:f.data.messages??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b),e=await Promise.all(d.map(async a=>{try{let b=await c.users.messages.get({userId:"me",id:a.id,format:"metadata",metadataHeaders:["Subject","From","Date"]}),d=bc(b.data.payload??void 0);return{messageId:b.data.id??a.id??"",threadId:b.data.threadId??a.threadId??"",from:d.from??"",subject:d.subject??"",date:d.date??"",snippet:b.data.snippet??"",labelIds:b.data.labelIds??[]}}catch{return{messageId:a.id??"",threadId:a.threadId??"",from:"",subject:"",date:"",snippet:"",labelIds:[]}}}));return{total:e.length,messages:e}}catch(a){throw a8(a)}}}),{name:"gmail_get_message",description:"Get the full content of a Gmail message including decoded body and attachment metadata. Use gmail_get_attachment to download an attachment by its ID.",inputSchema:bj,riskLevel:"read",async execute(a){try{let b=(await c.users.messages.get({userId:"me",id:a.message_id,format:"full"})).data,d=b.payload??void 0,e=bc(d),f=bb(d).trim(),g=f.length>1e4;g&&(f=f.slice(0,1e4)+"\n\n[...body truncated]");let h=function a(b,c=[]){if(!b)return c;let d=b.body?.attachmentId;for(let e of(d&&b.filename&&c.push({attachmentId:d,filename:b.filename,mimeType:b.mimeType??"application/octet-stream",size:b.body?.size??0}),b.parts??[]))a(e,c);return c}(d);return{messageId:b.id??"",threadId:b.threadId??"",from:e.from??"",to:e.to??"",cc:e.cc??"",subject:e.subject??"",date:e.date??"",body:f,truncated:g,labelIds:b.labelIds??[],attachments:h}}catch(a){throw a8(a)}}},{name:"gmail_list_threads",description:"List Gmail conversation threads matching a query. Returns thread IDs and snippets. Use gmail_get_thread to read the full conversation.",inputSchema:bq,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),d=await a9(async(b,d)=>{let e={userId:"me",maxResults:d,includeSpamTrash:a.include_spam_trash??!1,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await c.users.threads.list(e);return{items:f.data.threads??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b);return{total:d.length,threads:d.map(a=>({threadId:a.id??"",snippet:a.snippet??"",historyId:a.historyId??""}))}}catch(a){throw a8(a)}}},{name:"gmail_get_thread",description:"Fetch a full Gmail conversation thread with all messages, decoded bodies and headers.",inputSchema:br,riskLevel:"read",async execute(a){try{let b=(await c.users.threads.get({userId:"me",id:a.thread_id,format:"full"})).data,d=(b.messages??[]).map(a=>{let b=a.payload??void 0,c=bc(b),d=bb(b).trim();return d.length>5e3&&(d=d.slice(0,5e3)+"\n\n[...truncated]"),{messageId:a.id??"",from:c.from??"",to:c.to??"",subject:c.subject??"",date:c.date??"",snippet:a.snippet??"",body:d,labelIds:a.labelIds??[]}});return{threadId:b.id??"",messages:d}}catch(a){throw a8(a)}}},{name:"gmail_list_labels",description:"List all Gmail labels — both system labels (INBOX, SENT, TRASH, SPAM, etc.) and user-created labels. Returns label IDs needed for gmail_modify_labels.",inputSchema:bu,riskLevel:"read",async execute(){try{let a=((await c.users.labels.list({userId:"me"})).data.labels??[]).map(a=>({id:a.id??"",name:a.name??"",type:a.type??"",messageListVisibility:a.messageListVisibility??"",labelListVisibility:a.labelListVisibility??"",messagesTotal:a.messagesTotal??0,messagesUnread:a.messagesUnread??0,threadsTotal:a.threadsTotal??0,threadsUnread:a.threadsUnread??0}));return{total:a.length,labels:a}}catch(a){throw a8(a)}}},{name:"gmail_get_label",description:"Get details and message counts for a specific Gmail label.",inputSchema:bv,riskLevel:"read",async execute(a){try{let b=(await c.users.labels.get({userId:"me",id:a.label_id})).data;return{id:b.id??"",name:b.name??"",type:b.type??"",messagesTotal:b.messagesTotal??0,messagesUnread:b.messagesUnread??0,threadsTotal:b.threadsTotal??0,threadsUnread:b.threadsUnread??0}}catch(a){throw a8(a)}}},{name:"gmail_list_drafts",description:"List Gmail drafts with their IDs, subjects and snippets. Use draft_id with gmail_send_draft to send or gmail_update_draft to edit.",inputSchema:bA,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),d=await a9(async(b,d)=>{let e={userId:"me",maxResults:d,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await c.users.drafts.list(e);return{items:f.data.drafts??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b),e=await Promise.all(d.map(async a=>{let b=a.id??"";try{let a=(await c.users.drafts.get({userId:"me",id:b,format:"metadata"})).data.message??{},d=bc(a.payload??void 0);return{draftId:b,messageId:a.id??"",to:d.to??"",subject:d.subject??"",snippet:a.snippet??""}}catch{return{draftId:b,messageId:a.message?.id??"",to:"",subject:"",snippet:""}}}));return{total:e.length,drafts:e}}catch(a){throw a8(a)}}},{name:"gmail_get_attachment",description:"Download an email attachment by message ID and attachment ID. Returns base64url-encoded content. Get attachment IDs from gmail_get_message. Size cap: 25 MB.",inputSchema:bF,riskLevel:"read",async execute(a){try{let b=(await c.users.messages.attachments.get({userId:"me",messageId:a.message_id,id:a.attachment_id})).data,d=b.size??0;if(d>0x1900000)throw new a7("gmail_attachment_too_large",`Attachment exceeds the 25 MB limit (${Math.round(d/1024/1024)} MB).`);return{attachmentId:a.attachment_id,messageId:a.message_id,filename:a.filename??"",sizeBytes:d,data:b.data??""}}catch(a){throw a8(a)}}},{name:"gmail_list_history",description:"List Gmail mailbox changes since a given historyId. Useful for incremental sync — only fetch changes since last check. Returns the latest historyId to use in subsequent calls.",inputSchema:bG,riskLevel:"read",async execute(a){try{let b={userId:"me",startHistoryId:a.start_history_id,maxResults:Math.min(a.max_results??100,500),historyTypes:["messageAdded","messageDeleted","labelAdded","labelRemoved"],...a.label_id&&{labelId:a.label_id}},d=(await c.users.history.list(b)).data,e=(d.history??[]).map(a=>({id:a.id??"",messages:(a.messages??[]).map(a=>({messageId:a.id??"",threadId:a.threadId??""})),messagesAdded:(a.messagesAdded??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.message?.labelIds??[]})),messagesDeleted:(a.messagesDeleted??[]).map(a=>({messageId:a.message?.id??""})),labelsAdded:(a.labelsAdded??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.labelIds??[]})),labelsRemoved:(a.labelsRemoved??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.labelIds??[]}))}));return{historyId:d.historyId??"",history:e}}catch(a){throw a8(a)}}},{name:"gmail_send_email",description:"Send an email via Gmail. Supports plain text and HTML bodies, CC, BCC, Reply-To, and file attachments. Use attachments to send reports, CSVs, or HTML files as real files rather than pasting content inline.",inputSchema:bh,riskLevel:"write",async execute(a){try{let b=bf({to:a.to,subject:a.subject,body:a.body,cc:a.cc,bcc:a.bcc,replyTo:a.reply_to,attachments:a.attachments}),d=await c.users.messages.send({userId:"me",requestBody:{raw:b}});return{messageId:d.data.id??"",threadId:d.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_reply_message",description:"Reply to a Gmail message in-thread. Automatically sets In-Reply-To, References, subject (Re: prefix), and threadId. Fetches the original message headers to build correct threading.",inputSchema:bk,riskLevel:"write",async execute(a){try{let b=(await c.users.messages.get({userId:"me",id:a.message_id,format:"metadata",metadataHeaders:["Subject","From","To","Message-ID","Message-Id","References"]})).data,d=bc(b.payload??void 0),e=b.threadId??void 0,f=d.subject??"",g=f.toLowerCase().startsWith("re:")?f:`Re: ${f}`,h=d.from??"",i=d["message-id"]??d["message-id"]??"",j=d.references??"",k=i?j?`${j} ${i}`:i:j,l={raw:bf({to:h,subject:g,body:a.body,cc:a.cc,inReplyTo:i||void 0,references:k||void 0,attachments:a.attachments})};e&&(l.threadId=e);let m=await c.users.messages.send({userId:"me",requestBody:l});return{messageId:m.data.id??"",threadId:m.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_forward_message",description:"Forward a Gmail message to new recipients. Quotes the original body and prepends Fwd: to the subject.",inputSchema:bl,riskLevel:"write",async execute(a){try{let b=(await c.users.messages.get({userId:"me",id:a.message_id,format:"full"})).data.payload??void 0,d=bc(b),e=d.subject??"",f=e.toLowerCase().startsWith("fwd:")?e:`Fwd: ${e}`,g=bb(b).trim(),h=a.note?`${a.note}
7
+ \`\`\``}case"quote":return`> ${Z(a.quote.rich_text)}`;case"callout":{let b=Z(a.callout.rich_text),c=a.callout.icon,d=c?.type==="emoji"?c.emoji:"";return d?`${d} ${b}`:b}case"divider":return"---";case"toggle":return Z(a.toggle.rich_text);case"table_of_contents":return"[table of contents]";case"child_page":return`[child page: ${a.child_page.title}]`;case"child_database":return`[child database: ${a.child_database.title}]`;case"image":{let b="external"===a.image.type?a.image.external.url:a.image.file.url;return`[image: ${b}]`}case"video":{let b="external"===a.video.type?a.video.external.url:a.video.file.url;return`[video: ${b}]`}case"file":{let b="external"===a.file.type?a.file.external.url:a.file.file.url;return`[file: ${b}]`}case"pdf":{let b="external"===a.pdf.type?a.pdf.external.url:a.pdf.file.url;return`[pdf: ${b}]`}case"bookmark":return`[bookmark: ${a.bookmark.url}]`;case"embed":return`[embed: ${a.embed.url}]`;default:return null}}let _=g.Ik({page_id:g.Yj().describe("Notion page ID (UUID or dashed UUID).")}),aa=g.Ik({page_id:g.Yj().describe("Notion page or block ID whose content to read."),max_blocks:g.ai().int().min(1).max(1e3).optional().default(300).describe("Maximum number of blocks to fetch (default 300).")}),ab=g.Ik({parent_page_id:g.Yj().optional().describe("ID of the parent PAGE. Use when creating a sub-page inside another page. Mutually exclusive with parent_database_id."),parent_database_id:g.Yj().optional().describe("ID of the parent DATABASE. Use when creating a new row inside a database. Mutually exclusive with parent_page_id."),title:g.Yj().describe("Title of the new page."),content:g.Yj().optional().describe("Optional paragraph text to add as the first block. Auto-chunked if >2000 chars.")}),ac=g.Ik({page_id:g.Yj().describe("Page ID to update."),properties:g.g1(g.Yj(),g.L5()).describe('Properties to update as key-value pairs. Example: {"Status": "Done", "Priority": "High", "Score": 95}')}),ad=g.Ik({page_id:g.Yj().describe("Page ID to archive.")}),ae=g.Ik({block_id:g.Yj().describe("Block ID to retrieve.")}),af=g.Ik({type:g.k5(["paragraph","heading_1","heading_2","heading_3","bulleted_list_item","numbered_list_item","to_do","code","quote","callout","toggle","divider"]).describe("Block type."),content:g.Yj().optional().default("").describe("Text content for the block (not used for divider)."),language:g.Yj().optional().describe('Programming language for code blocks (e.g. "python", "javascript").'),checked:g.zM().optional().default(!1).describe("Whether a to_do block is checked.")}),ag=g.Ik({page_id:g.Yj().describe("Page or block ID to append content to."),blocks:g.YO(af).min(1).max(100).describe('Array of blocks to add. Example: [{"type": "heading_2", "content": "Summary"}, {"type": "paragraph", "content": "The results show..."}]')});function ah(a){if("divider"===a.type)return{object:"block",type:"divider",divider:{}};let b=S(a.content??"");return"code"===a.type?{object:"block",type:"code",code:{rich_text:b,language:a.language??"plain text"}}:"to_do"===a.type?{object:"block",type:"to_do",to_do:{rich_text:b,checked:a.checked??!1}}:{object:"block",type:a.type,[a.type]:{rich_text:b}}}let ai=g.Ik({block_id:g.Yj().describe("Block ID to update."),content:g.Yj().describe("New text content for the block.")}),aj=g.Ik({block_id:g.Yj().describe("Block ID to delete (archive).")}),ak=g.Ik({database_id:g.Yj().describe("Notion database ID (UUID)."),filter:g.g1(g.Yj(),g.L5()).optional().describe('Optional Notion filter object. Example: {"property": "Status", "select": {"equals": "Applied"}}'),page_size:g.ai().int().min(1).max(100).optional().default(50).describe("Rows per request (1–100, default 50)."),max_rows:g.ai().int().min(1).max(1e3).optional().default(500).describe("Total rows to collect across pagination (default 500, max 1000).")}),al=g.Ik({database_id:g.Yj().describe("Notion database ID (UUID).")}),am=g.Ik({database_id:g.Yj().describe("Notion database ID to add a row to."),properties:g.g1(g.Yj(),g.L5()).describe('Row properties as key-value pairs. Example: {"Name": "Acme Corp", "Status": "Applied", "Score": 95}')}),an=g.Ik({page_id:g.Yj().describe("Page ID of the database row to update."),database_id:g.Yj().optional().describe("Optional: database ID to fetch schema for type coercion. If omitted, types are inferred from values."),properties:g.g1(g.Yj(),g.L5()).describe('Properties to update as key-value pairs. Example: {"Status": "Done", "Score": 100}')}),ao=g.k5(["title","rich_text","number","checkbox","url","email","phone_number","date","select","multi_select","status"]),ap=g.Ik({parent_page_id:g.Yj().describe("Page ID that will contain the new database."),title:g.Yj().describe("Database title."),columns:g.g1(g.Yj(),ao).describe('Column definitions as {name: type}. One must be "title". Example: {"Name": "title", "Status": "select", "URL": "url", "Score": "number"}')});function aq(a){switch(a){case"title":return{title:{}};case"select":return{select:{options:[]}};case"multi_select":return{multi_select:{options:[]}};case"status":return{status:{}};default:return{[a]:{}}}}let ar=g.Ik({database_id:g.Yj().describe("Database ID to update."),title:g.Yj().optional().describe("Optional new title for the database."),new_columns:g.g1(g.Yj(),ao).optional().describe("New columns to add as {name: type}. Same types as notion_create_database. Cannot modify existing column types (Notion API limitation).")}),as=g.Ik({block_id:g.Yj().describe("Page or block ID to list comments for."),page_size:g.ai().int().min(1).max(50).optional().default(50).describe("Max comments to return (default 50).")}),at=g.Ik({page_id:g.Yj().describe("Page ID to comment on."),text:g.Yj().describe("Comment text.")}),au=g.Ik({page_size:g.ai().int().min(1).max(100).optional().default(100).describe("Max users to return (default 100).")}),av=g.Ik({user_id:g.Yj().describe("Notion user ID.")}),aw=[{slug:"notion_search",name:"Search",risk:"read",requiresApproval:!1,description:"Search pages and databases by title."},{slug:"notion_get_page",name:"Get page",risk:"read",requiresApproval:!1,description:"Retrieve page properties by ID."},{slug:"notion_get_page_content",name:"Get page content",risk:"read",requiresApproval:!1,description:"Read all blocks inside a page."},{slug:"notion_get_block",name:"Get block",risk:"read",requiresApproval:!1,description:"Retrieve a single block and its children."},{slug:"notion_query_database",name:"Query database",risk:"read",requiresApproval:!1,description:"Filter and sort rows in a Notion database."},{slug:"notion_get_database",name:"Get database",risk:"read",requiresApproval:!1,description:"Retrieve database schema and properties."},{slug:"notion_list_comments",name:"List comments",risk:"read",requiresApproval:!1,description:"List all comments on a page or block."},{slug:"notion_list_users",name:"List users",risk:"read",requiresApproval:!1,description:"List workspace members."},{slug:"notion_get_user",name:"Get user",risk:"read",requiresApproval:!1,description:"Retrieve a workspace member by ID."},{slug:"notion_create_page",name:"Create page",risk:"write",requiresApproval:!1,description:"Create a new page inside a parent page or database."},{slug:"notion_update_page",name:"Update page",risk:"write",requiresApproval:!1,description:"Update page properties."},{slug:"notion_append_blocks",name:"Append blocks",risk:"write",requiresApproval:!1,description:"Append content blocks to a page or block."},{slug:"notion_update_block",name:"Update block",risk:"write",requiresApproval:!1,description:"Update an existing block content."},{slug:"notion_create_database_entry",name:"Create database entry",risk:"write",requiresApproval:!1,description:"Add a new row to a Notion database."},{slug:"notion_update_database_entry",name:"Update database entry",risk:"write",requiresApproval:!1,description:"Update properties on an existing database row."},{slug:"notion_create_database",name:"Create database",risk:"write",requiresApproval:!1,description:"Create a new database inside a parent page."},{slug:"notion_update_database",name:"Update database",risk:"write",requiresApproval:!1,description:"Update database title or property schema."},{slug:"notion_add_comment",name:"Add comment",risk:"write",requiresApproval:!1,description:"Add a comment to a page or block."},{slug:"notion_archive_page",name:"Archive page",risk:"destructive",requiresApproval:!0,description:"Archive (soft-delete) a page."},{slug:"notion_delete_block",name:"Delete block",risk:"destructive",requiresApproval:!0,description:"Permanently delete a block."}];function ax(a){var b;let c=(b=function(a){if("apiKey"in a&&a.apiKey)return a.apiKey;if(!a.accessToken)throw Error("NotionAdapterOptions: either apiKey or accessToken must be a non-empty string.");return a.accessToken}(a),new P.Client({auth:b}));return[{name:"notion_search",description:"Search across all pages and databases in Notion. Returns matching page titles, IDs, and URLs.",inputSchema:W,riskLevel:"read",async execute(a){try{let b={query:a.query,page_size:a.limit};a.filter_type&&(b.filter={property:"object",value:a.filter_type});let d=(await c.search(b)).results.map(a=>{let b=a.object,c=a.id,d="url"in a?a.url:"",e=V(a);return{object:b,id:c,title:e,url:d}});return{total:d.length,results:d}}catch(a){throw R(a)}}},{name:"notion_get_page",description:"Retrieve a Notion page by its ID. Returns the page title and a summary of its properties.",inputSchema:_,riskLevel:"read",async execute(a){try{let b=await c.pages.retrieve({page_id:a.page_id});if(!("properties"in b))throw R(Error("notion_not_found"));let d=V(b),e="url"in b?b.url:"",f={};for(let[a,c]of Object.entries(b.properties)){if("title"===c.type)continue;let b=T(c);b&&(f[a]=b.slice(0,200))}return{id:b.id,title:d,url:e,created_time:"created_time"in b?String(b.created_time):"",last_edited_time:"last_edited_time"in b?String(b.last_edited_time):"",properties:f}}catch(a){throw R(a)}}},{name:"notion_get_page_content",description:"Read the full text content of a Notion page (paragraphs, headings, lists, code, etc.). Use this after notion_search or notion_get_page to read what is actually written on the page.",inputSchema:aa,riskLevel:"read",async execute(a){try{let b=await c.pages.retrieve({page_id:a.page_id}),d=V(b),e=await Y(c,a.page_id,a.max_blocks),f=function(a,b=15e3){let c=[];for(let b of a){let a=$(b);null!==a&&c.push(a)}let d=c.join("\n\n");return d.length>b?d.slice(0,b)+"\n\n[...content truncated...]":d}(e);return{id:a.page_id,title:d,content:f||"(no extractable text content)",block_count:e.length}}catch(a){throw R(a)}}},{name:"notion_get_block",description:"Retrieve a specific Notion block by ID. Returns the block type and its text content.",inputSchema:ae,riskLevel:"read",async execute(a){try{let b=await c.blocks.retrieve({block_id:a.block_id});return{id:b.id,type:"type"in b?String(b.type):"unknown",text:$(b),has_children:"has_children"in b&&!!b.has_children}}catch(a){throw R(a)}}},{name:"notion_query_database",description:"Query a Notion database with optional filters. Without a filter, returns all entries. Returns rows with their properties.",inputSchema:ak,riskLevel:"read",async execute(a){try{let b=!1,d=await X(async(b,d)=>{let e={database_id:a.database_id,page_size:d};a.filter&&(e.filter=a.filter),b&&(e.start_cursor=b);let f=await c.databases.query(e);return{results:f.results,has_more:f.has_more,next_cursor:f.next_cursor}},a.page_size,a.max_rows);d.length>=a.max_rows&&(b=!0);let e=d.map(a=>{let b={id:a.id,url:"url"in a?String(a.url):""};if("properties"in a)for(let[c,d]of Object.entries(a.properties)){let a=T(d);a&&(b[c]=a)}return b});return{total:e.length,has_more:b,rows:e}}catch(a){throw R(a)}}},{name:"notion_get_database",description:"Get the schema of a Notion database (column names, types, and select/multi_select options). Call this to discover database structure before querying or creating rows.",inputSchema:al,riskLevel:"read",async execute(a){try{let b=await c.databases.retrieve({database_id:a.database_id}),d=("title"in b?b.title:[]).map(a=>a.plain_text).join("")||"(untitled)",e="url"in b?String(b.url):"",f=Object.entries(b.properties).map(([a,b])=>{let c={name:a,type:b.type};return"select"===b.type?c.options=(b.select?.options??[]).slice(0,20).map(a=>a.name):"multi_select"===b.type?c.options=(b.multi_select?.options??[]).slice(0,20).map(a=>a.name):"status"===b.type&&(c.options=(b.status?.options??[]).slice(0,20).map(a=>a.name)),c});return{id:b.id,title:d,url:e,columns:f}}catch(a){throw R(a)}}},{name:"notion_list_comments",description:"List comments on a Notion page or block.",inputSchema:as,riskLevel:"read",async execute(a){try{let b=(await c.comments.list({block_id:a.block_id,page_size:a.page_size})).results.map(a=>{let b=a.rich_text.map(a=>a.plain_text).join(""),c=a.created_by;return{id:a.id,author_id:c?.id??"",author_name:c?.name??"",text:b.slice(0,500),created_time:a.created_time}});return{total:b.length,comments:b}}catch(a){throw R(a)}}},{name:"notion_list_users",description:"List all users in the Notion workspace.",inputSchema:au,riskLevel:"read",async execute(a){try{let b=(await c.users.list({page_size:a.page_size})).results.map(a=>{let b="person"===a.type&&"person"in a?a.person:null;return{id:a.id,name:a.name??"",type:a.type??"unknown",email:b?.email??"",avatar_url:a.avatar_url??""}});return{total:b.length,users:b}}catch(a){throw R(a)}}},{name:"notion_get_user",description:"Get details about a specific Notion user by their ID.",inputSchema:av,riskLevel:"read",async execute(a){try{let b=await c.users.retrieve({user_id:a.user_id}),d="person"===b.type&&"person"in b?b.person:null;return{id:b.id,name:b.name??"",type:b.type??"unknown",email:d?.email??"",avatar_url:b.avatar_url??""}}catch(a){throw R(a)}}},{name:"notion_create_page",description:"Create a new Notion page. Provide EITHER parent_page_id (to nest under a page) OR parent_database_id (to create a row in a database) — not both.",inputSchema:ab,riskLevel:"write",async execute(a){if(a.parent_page_id&&a.parent_database_id)throw R(Error("Provide either parent_page_id OR parent_database_id, not both."));if(!a.parent_page_id&&!a.parent_database_id)throw R(Error("Must provide parent_page_id or parent_database_id."));try{let b,d="title";if(a.parent_database_id){b={database_id:a.parent_database_id};try{let b=await c.databases.retrieve({database_id:a.parent_database_id});for(let[a,c]of Object.entries(b.properties))if("title"===c.type){d=a;break}}catch{}}else b={type:"page_id",page_id:a.parent_page_id};let e={[d]:{title:S(a.title)}},f=[];a.content&&f.push({object:"block",type:"paragraph",paragraph:{rich_text:S(a.content)}});let g=await c.pages.create({parent:b,properties:e,...f.length>0&&{children:f}});return{id:g.id,url:"url"in g?String(g.url):"",title:a.title}}catch(a){throw R(a)}}},{name:"notion_update_page",description:"Update properties of a Notion page (title, status, select, text, number, etc.). Use notion_query_database first to discover the correct property names and types.",inputSchema:ac,riskLevel:"write",async execute(a){try{let b=null;try{let d=await c.pages.retrieve({page_id:a.page_id}),e="parent"in d?d.parent:null;if(e?.type==="database_id"&&e.database_id){let a=await c.databases.retrieve({database_id:e.database_id});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}}catch{}let d={};for(let[c,e]of Object.entries(a.properties))null!=e&&(d[c]=U(c,e,b));return await c.pages.update({page_id:a.page_id,properties:d}),{id:a.page_id,updated_properties:Object.keys(d).length}}catch(a){throw R(a)}}},{name:"notion_append_blocks",description:"Add content blocks to an existing Notion page. Supports paragraphs, headings, lists, code blocks, quotes, and dividers.",inputSchema:ag,riskLevel:"write",async execute(a){try{let b=a.blocks.map(ah);return await c.blocks.children.append({block_id:a.page_id,children:b}),{page_id:a.page_id,appended_count:b.length}}catch(a){throw R(a)}}},{name:"notion_update_block",description:"Update the text content of an existing Notion block. The block type is preserved.",inputSchema:ai,riskLevel:"write",async execute(a){try{let b=await c.blocks.retrieve({block_id:a.block_id}),d="type"in b?String(b.type):"paragraph",e=S(a.content),f={block_id:a.block_id,[d]:{rich_text:e}};return await c.blocks.update(f),{id:a.block_id}}catch(a){throw R(a)}}},{name:"notion_create_database_entry",description:"Create a new row (entry) in a Notion database. Use notion_get_database first to discover property names and types.",inputSchema:am,riskLevel:"write",async execute(a){try{let b=null,d="Name";try{let e=await c.databases.retrieve({database_id:a.database_id});for(let[a,c]of(b={},Object.entries(e.properties))){let e=c.type;b[a]={type:e},"title"===e&&(d=a)}}catch{}let e={};for(let[c,d]of Object.entries(a.properties))null!=d&&(e[c]=U(c,d,b));if(!e[d]){let b=Object.entries(a.properties).find(([,a])=>"string"==typeof a&&a);b&&(e[d]={title:S(b[1])})}let f=await c.pages.create({parent:{database_id:a.database_id},properties:e});return{id:f.id,url:"url"in f?String(f.url):""}}catch(a){throw R(a)}}},{name:"notion_update_database_entry",description:"Update properties of a Notion database row. Use notion_get_database to discover property names and types.",inputSchema:an,riskLevel:"write",async execute(a){try{let b=null,d=a.database_id;if(d)try{let a=await c.databases.retrieve({database_id:d});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}catch{}else try{let d=await c.pages.retrieve({page_id:a.page_id}),e="parent"in d?d.parent:null;if(e?.type==="database_id"&&e.database_id){let a=await c.databases.retrieve({database_id:e.database_id});for(let[c,d]of(b={},Object.entries(a.properties)))b[c]={type:d.type}}}catch{}let e={};for(let[c,d]of Object.entries(a.properties))null!=d&&(e[c]=U(c,d,b));return await c.pages.update({page_id:a.page_id,properties:e}),{id:a.page_id,updated_properties:Object.keys(e).length}}catch(a){throw R(a)}}},{name:"notion_create_database",description:"Create a new database inside a Notion page. Define columns with their types (title, rich_text, select, multi_select, number, checkbox, url, date, email).",inputSchema:ap,riskLevel:"write",async execute(a){try{let b={};for(let[c,d]of Object.entries(a.columns))b[c]=aq(d);let d=await c.databases.create({parent:{type:"page_id",page_id:a.parent_page_id},title:[{type:"text",text:{content:a.title}}],properties:b});return{id:d.id,url:"url"in d?String(d.url):"",title:a.title}}catch(a){throw R(a)}}},{name:"notion_update_database",description:"Update a database schema — add new columns or rename the database. Cannot modify existing column types (Notion API limitation).",inputSchema:ar,riskLevel:"write",async execute(a){if(!a.title&&!a.new_columns)throw R(Error("Provide title and/or new_columns to update."));try{let b={},d=[];if(a.title&&(b.title=[{type:"text",text:{content:a.title}}],d.push(`title → "${a.title}"`)),a.new_columns&&Object.keys(a.new_columns).length>0){let c={};for(let[b,d]of Object.entries(a.new_columns))c[b]=aq(d);b.properties=c,d.push(`${Object.keys(a.new_columns).length} column(s) added`)}return await c.databases.update({database_id:a.database_id,...b}),{id:a.database_id,changes:d}}catch(a){throw R(a)}}},{name:"notion_add_comment",description:"Add a comment to a Notion page.",inputSchema:at,riskLevel:"write",async execute(a){try{return{id:(await c.comments.create({parent:{page_id:a.page_id},rich_text:S(a.text)})).id,page_id:a.page_id}}catch(a){throw R(a)}}},{name:"notion_archive_page",description:"Archive (soft-delete) a Notion page. The page can be restored from trash.",inputSchema:ad,riskLevel:"destructive",async execute(a){try{return await c.pages.update({page_id:a.page_id,archived:!0}),{id:a.page_id,archived:!0}}catch(a){throw R(a)}}},{name:"notion_delete_block",description:"Delete (archive) a specific block from a Notion page.",inputSchema:aj,riskLevel:"destructive",async execute(a){try{return await c.blocks.delete({block_id:a.block_id}),{id:a.block_id,deleted:!0}}catch(a){throw R(a)}}}]}class ay extends Error{constructor(a,b,c){super(b),this.name="AirtableApiError",this.code=a,this.status=c}}function az(a){return a instanceof ay?a:a instanceof Error?new ay("airtable_unknown",a.message):new ay("airtable_unknown",String(a))}let aA="https://api.airtable.com/v0",aB=g.Ik({}),aC=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it.")}),aD=g.Ik({field:g.Yj().describe("Field name to sort by."),direction:g.k5(["asc","desc"]).optional().describe("Sort direction (default asc).")}),aE=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID (tblXXXXXXXX) or name within the base. Use airtable_list_tables to find it."),view:g.Yj().optional().describe("Name or ID of the view to use."),pageSize:g.ai().int().min(1).max(100).optional().default(100).describe("Number of records per page (1–100, default 100)."),offset:g.Yj().optional().describe("Pagination offset token from a previous response."),fields:g.YO(g.Yj()).optional().describe("List of field names to return. Omit to return all fields."),filterByFormula:g.Yj().optional().describe("Airtable formula to filter records. Example: \"AND({Status}='Active',{Score}>80)\""),sort:g.YO(aD).optional().describe("List of sort objects with field and optional direction.")}),aF=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to retrieve.")}),aG=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),records:g.YO(g.Ik({fields:g.g1(g.Yj(),g.L5())})).min(1).max(10).describe('Array of records to create, each with a fields object. Max 10 per call. Example: [{"fields": {"Name": "Alice", "Status": "Active"}}]'),typecast:g.zM().optional().describe("If true, Airtable will attempt to convert string values to the appropriate field type. Default false.")}),aH=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to update."),fields:g.g1(g.Yj(),g.L5()).describe('Fields to update as key-value pairs. Only specified fields are changed (PATCH semantics). Example: {"Status": "Done", "Score": 95}'),typecast:g.zM().optional().describe("If true, attempt to convert string values to the appropriate field type.")}),aI=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to replace."),fields:g.g1(g.Yj(),g.L5()).describe("Complete field set to write. Fields NOT included will be cleared (PUT semantics). Use airtable_update_record for partial updates."),typecast:g.zM().optional().describe("If true, attempt to convert string values to the appropriate field type.")}),aJ=g.Ik({baseId:g.Yj().describe("The Airtable base ID (e.g. appXXXXXXXX). Use airtable_list_bases to find it."),tableIdOrName:g.Yj().describe("The table ID or name within the base."),recordId:g.Yj().describe("The record ID (recXXXXXXXX) to delete. This action is permanent and cannot be undone.")}),aK=[{slug:"airtable_list_bases",name:"List bases",risk:"read",requiresApproval:!1,description:"List all Airtable bases the integration has access to."},{slug:"airtable_list_tables",name:"List tables",risk:"read",requiresApproval:!1,description:"List all tables and field schemas in a base."},{slug:"airtable_list_records",name:"List records",risk:"read",requiresApproval:!1,description:"List records in a table with optional filtering, sorting, and pagination."},{slug:"airtable_get_record",name:"Get record",risk:"read",requiresApproval:!1,description:"Retrieve a single record by its ID."},{slug:"airtable_create_records",name:"Create records",risk:"write",requiresApproval:!1,description:"Create one or more records in a table (max 10 per call)."},{slug:"airtable_update_record",name:"Update record",risk:"write",requiresApproval:!1,description:"Update specific fields on a record (PATCH — unlisted fields unchanged)."},{slug:"airtable_replace_record",name:"Replace record",risk:"write",requiresApproval:!1,description:"Fully replace all fields on a record (PUT — unlisted fields cleared)."},{slug:"airtable_delete_record",name:"Delete record",risk:"destructive",requiresApproval:!0,description:"Permanently delete a single record. This action is irreversible."}];function aL(a){if("accessToken"in a&&!a.accessToken)throw Error("AirtableAdapterOptions: accessToken must be a non-empty string.");let b=function(a,b={}){let c=b.timeoutMs??3e4,d=async()=>({Authorization:`Bearer ${await a()}`,"Content-Type":"application/json"});async function e(a,b,e){for(let f=0;;f+=1){let g,h;try{g=await fetch(b,{method:a,headers:await d(),...void 0!==e&&{body:JSON.stringify(e)},signal:AbortSignal.timeout(c)})}catch(a){if(a instanceof Error&&"TimeoutError"===a.name)throw new ay("airtable_transient",`Airtable request to ${b} timed out after ${c}ms`);throw az(a)}if(429===g.status&&f<3){let a=g.headers.get("retry-after"),b=null!==a?Number(a):NaN,c=Number.isFinite(b)&&b>=0?Math.min(1e3*b,6e4):1e3*2**f;await function(a){return new Promise(b=>setTimeout(b,a))}(c);continue}try{h=await g.json()}catch{h={}}if(!g.ok){let a,b=h;throw a="object"==typeof b?.error&&null!==b.error?b.error.message??g.statusText:"string"==typeof b?.error?b.error:b?.message?b.message:g.statusText,function(a,b){let c;switch(!0){case 401===a:c="airtable_unauthorized";break;case 403===a:c="airtable_forbidden";break;case 404===a:c="airtable_not_found";break;case 422===a:c="airtable_validation_error";break;case 429===a:c="airtable_rate_limited";break;case a>=500:c="airtable_transient";break;default:c="airtable_client_error"}return new ay(c,b,a)}(g.status,a)}return h}}return{get:(a,b)=>e("GET",function(a,b,c){let d=new URL(`${a}${b}`);if(c)for(let[a,b]of Object.entries(c))if(Array.isArray(b))for(let c of b)d.searchParams.append(a,String(c));else null!=b&&d.searchParams.set(a,String(b));return d.toString()}(aA,a,b)),post:(a,b)=>e("POST",`${aA}${a}`,b),patch:(a,b)=>e("PATCH",`${aA}${a}`,b),put:(a,b)=>e("PUT",`${aA}${a}`,b),delete:a=>e("DELETE",`${aA}${a}`)}}("getAccessToken"in a?a.getAccessToken:async()=>a.accessToken);return[{name:"airtable_list_bases",description:"List all Airtable bases the integration has access to. Returns base IDs and names needed for other airtable_ tools.",inputSchema:aB,riskLevel:"read",async execute(a){try{return{bases:((await b.get("/meta/bases")).bases??[]).map(a=>({id:a.id,name:a.name,permissionLevel:a.permissionLevel}))}}catch(a){throw az(a)}}},{name:"airtable_list_tables",description:"List all tables in an Airtable base including their field schemas. Use this to discover table IDs and field names before reading or writing records.",inputSchema:aC,riskLevel:"read",async execute(a){try{return{tables:((await b.get(`/meta/bases/${a.baseId}/tables`)).tables??[]).map(a=>({id:a.id,name:a.name,primaryFieldId:a.primaryFieldId,fields:(a.fields??[]).map(a=>({id:a.id,name:a.name,type:a.type}))}))}}catch(a){throw az(a)}}},{name:"airtable_list_records",description:"List records in an Airtable table. Supports filtering by formula, sorting, field selection, and pagination via offset token.",inputSchema:aE,riskLevel:"read",async execute(a){try{let c={pageSize:a.pageSize??100};if(a.view&&(c.view=a.view),a.offset&&(c.offset=a.offset),a.filterByFormula&&(c.filterByFormula=a.filterByFormula),a.fields&&a.fields.length>0&&(c["fields[]"]=a.fields),a.sort&&a.sort.length>0)for(let b=0;b<a.sort.length;b++){let d=a.sort[b];d&&(c[`sort[${b}][field]`]=d.field,d.direction&&(c[`sort[${b}][direction]`]=d.direction))}let d=await b.get(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}`,c);return{records:(d.records??[]).map(a=>({id:a.id,fields:a.fields??{},createdTime:a.createdTime})),offset:d.offset}}catch(a){throw az(a)}}},{name:"airtable_get_record",description:"Retrieve a single record from an Airtable table by its record ID. Returns all field values.",inputSchema:aF,riskLevel:"read",async execute(a){try{let c=await b.get(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`);return{id:c.id,fields:c.fields??{},createdTime:c.createdTime}}catch(a){throw az(a)}}},{name:"airtable_create_records",description:"Create one or more records in an Airtable table. Max 10 records per call. Field names must match the table schema exactly.",inputSchema:aG,riskLevel:"write",async execute(a){try{let c={records:a.records};return a.typecast&&(c.typecast=!0),{records:((await b.post(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}`,c)).records??[]).map(a=>({id:a.id,fields:a.fields??{},createdTime:a.createdTime}))}}catch(a){throw az(a)}}},{name:"airtable_update_record",description:"Update specific fields on a single Airtable record (PATCH — only listed fields are changed, others remain). Use airtable_replace_record to overwrite all fields.",inputSchema:aH,riskLevel:"write",async execute(a){try{let c={fields:a.fields};a.typecast&&(c.typecast=!0);let d=await b.patch(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`,c);return{id:d.id,fields:d.fields??{},createdTime:d.createdTime}}catch(a){throw az(a)}}},{name:"airtable_replace_record",description:"Fully replace all fields on a single Airtable record (PUT — fields not listed are cleared to empty). Use airtable_update_record for partial field updates.",inputSchema:aI,riskLevel:"write",async execute(a){try{let c={fields:a.fields};a.typecast&&(c.typecast=!0);let d=await b.put(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`,c);return{id:d.id,fields:d.fields??{},createdTime:d.createdTime}}catch(a){throw az(a)}}},{name:"airtable_delete_record",description:"Permanently delete a single record from an Airtable table. This is irreversible — confirm the record ID with airtable_get_record before deleting.",inputSchema:aJ,riskLevel:"destructive",async execute(a){try{return{id:(await b.delete(`/${a.baseId}/${encodeURIComponent(a.tableIdOrName)}/${a.recordId}`)).id,deleted:!0}}catch(a){throw az(a)}}}]}var aM=c(63850);class aN extends Error{constructor(a,b,c){super(b),this.name="DriveAdapterError",this.code=a,this.status=c}}function aO(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="drive_validation_error";break;case 401:a="drive_unauthorized";break;case 403:a="drive_forbidden";break;case 404:a="drive_not_found";break;case 409:a="drive_conflict";break;case 429:a="drive_rate_limited";break;case 503:a="drive_service_unavailable";break;default:a="drive_unknown"}return new aN(a,c,b)}}return a instanceof aN?a:a instanceof Error?new aN("drive_unknown",a.message):new aN("drive_unknown",String(a))}async function aP(a,b=100,c=100){let d,e=[],f=Math.min(c,1e3);for(let c=0;c<20;c++){let c=Math.min(b,1e3,f-e.length),g=await a(d,c);if(e.push(...g.items),e.length>=f||!g.nextPageToken||0===g.items.length)break;d=g.nextPageToken}return e.slice(0,f)}let aQ=g.Ik({query:g.Yj().optional().describe("Google Drive search query. Examples: 'name contains \"resume\"' or '\"folder-id\" in parents' or 'mimeType=\"application/pdf\"'. Leave empty to list recent files."),max_results:g.ai().int().min(1).max(1e3).optional().describe("Max files to return (1–1000, default 20)."),order_by:g.Yj().optional().describe("Sort order. Examples: 'modifiedTime desc', 'name', 'createdTime'. Default: 'modifiedTime desc'.")});var aR=c(17393),aS=c.n(aR);async function aT(a){return(await aS().extractRawText({buffer:a})).value}var aU=c(20416);async function aV(a){let b=new aU.PDFParse({data:a});return(await b.getText()).text}var aW=c(78608),aX=c.n(aW);async function aY(a){let b=new(aX()).Workbook;await b.xlsx.load(a);let c=[];return b.eachSheet(a=>{c.push(`--- Sheet: ${a.name} ---`);let b=0;a.eachRow(a=>{if(b>=200)return;let d=[];a.eachCell({includeEmpty:!1},a=>{let b=a.value;null==b?d.push(""):"object"==typeof b&&"result"in b?d.push(String(b.result??"")):"object"==typeof b&&b instanceof Date?d.push(b.toISOString().slice(0,10)):d.push(String(b))}),d.length>0&&(c.push(d.join(" ")),b++)}),b>=200&&c.push("[sheet truncated at 200 rows]")}),c.join("\n")}function aZ(a){return a.toString("utf-8")}async function a$(a,b,c){if(a.byteLength>0x1900000)throw new aN("drive_file_too_large",`File exceeds the 25 MB extraction limit (${Math.round(a.byteLength/1024/1024)} MB).`);let d=b.toLowerCase(),e=c.toLowerCase();if("application/vnd.openxmlformats-officedocument.wordprocessingml.document"===d||e.endsWith(".docx"))return aT(a);if("application/pdf"===d||e.endsWith(".pdf"))return aV(a);if("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"===d||e.endsWith(".xlsx"))return aY(a);if("application/vnd.openxmlformats-officedocument.presentationml.presentation"===d||e.endsWith(".pptx"))throw new aN("drive_pptx_extraction_unsupported","PPTX text extraction is not yet supported. Export the file to Google Slides or PDF first.");if("application/json"===d||e.endsWith(".json"))try{let b=a.toString("utf-8"),c=JSON.parse(b);return JSON.stringify(c,null,2)}catch{return aZ(a)}if(d.startsWith("text/")||"application/xml"===d||"application/javascript"===d||"application/typescript"===d)return aZ(a);try{if((a.slice(0,1e3).toString("utf-8").match(/�/g)??[]).length>20)throw new aN("drive_unknown",`Binary file format (${b||"unknown"}) — cannot extract text.`);return aZ(a)}catch(a){if(a instanceof aN)throw a;throw new aN("drive_unknown",`Binary file format (${b||"unknown"}) — cannot extract text.`)}}let a_=g.Ik({file_id:g.Yj().describe("The Google Drive file ID (from drive_list_files or drive_get_file_info).")}),a0=g.Ik({name:g.Yj().describe("File name including extension, e.g. 'cover_letter.txt'."),content:g.Yj().describe("Text content of the file."),folder_id:g.Yj().optional().describe("Optional Drive folder ID to place the file in."),mime_type:g.Yj().optional().describe("MIME type of the file. Default: 'text/plain'.")}),a1=g.Ik({file_id:g.Yj().describe("Google Drive file ID.")}),a2=g.Ik({name:g.Yj().describe("Folder name."),parent_id:g.Yj().optional().describe("Optional parent folder ID. Creates in root if omitted.")}),a3=g.Ik({file_id:g.Yj().describe("File ID to move."),new_parent_id:g.Yj().describe("Destination folder ID.")}),a4=g.Ik({file_id:g.Yj().describe("File ID to rename."),new_name:g.Yj().describe("New file name (including extension).")}),a5=g.Ik({file_id:g.Yj().describe("File ID to copy."),new_name:g.Yj().optional().describe("Optional name for the copy."),folder_id:g.Yj().optional().describe("Optional destination folder ID for the copy.")}),a6=g.Ik({file_id:g.Yj().describe("File ID to move to trash.")}),a7=g.Ik({file_id:g.Yj().describe("File ID to share."),email:g.Yj().optional().describe("Email address to share with. Omit for link sharing (anyone with link)."),role:g.k5(["reader","writer","commenter","owner"]).optional().describe("Permission role: 'reader', 'writer', 'commenter', or 'owner'. Default: 'reader'."),type:g.k5(["user","group","domain","anyone"]).optional().describe("Permission type: 'user', 'group', 'domain', or 'anyone'. Defaults to 'user' if email provided, 'anyone' otherwise.")}),a8=g.Ik({file_id:g.Yj().describe("File ID to list permissions for.")}),a9=g.Ik({file_id:g.Yj().describe("Google Drive file ID. Must be a Google Workspace file (Doc, Sheet, Slide, etc.)."),mime_type:g.Yj().describe("Target MIME type. Examples: 'text/plain', 'text/csv', 'application/pdf', 'text/html', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'.")});function ba(a){var b;let d,e=(b="getAccessToken"in a?a.getAccessToken:async()=>a.accessToken,(d=new aM.google.auth.OAuth2).refreshHandler=async()=>({access_token:await b(),expiry_date:Date.now()-1}),aM.google.drive({version:"v3",auth:d}));return[{name:"drive_list_files",description:"List files in Google Drive. Optionally filter by folder or search query. Returns file names and IDs needed for drive_read_file.",inputSchema:aQ,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,1e3),c=await aP(async(b,c)=>{let d={pageSize:c,fields:"nextPageToken,files(id,name,mimeType,modifiedTime,size)",orderBy:a.order_by??"modifiedTime desc",...b&&{pageToken:b},...a.query&&{q:a.query}},f=await e.files.list(d);return{items:f.data.files??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b);return{total:c.length,files:c.map(a=>({id:a.id??"",name:a.name??"",mimeType:a.mimeType??"",modifiedTime:a.modifiedTime??"",size:null!=a.size?Number(a.size):null}))}}catch(a){throw aO(a)}}},{name:"drive_read_file",description:"Read the text content of a file from Google Drive. Handles Google Docs (exported as plain text), plain text, DOCX, PDF, XLSX. Use drive_list_files first to get the file ID.",inputSchema:a_,riskLevel:"read",async execute(a){try{let b,c=(await e.files.get({fileId:a.file_id,fields:"id,name,mimeType,size"})).data,d=c.mimeType??"",f=c.name??"",g=null!=c.size?Number(c.size):null;if(null!=g&&g>0x1900000)throw new aN("drive_file_too_large",`File exceeds the 25 MB extraction limit (${Math.round(g/1024/1024)} MB).`);if(d.startsWith("application/vnd.google-apps.")){let c;c="application/vnd.google-apps.document"===d?"text/plain":"application/vnd.google-apps.spreadsheet"===d?"text/csv":"text/plain";let f=await e.files.export({fileId:a.file_id,mimeType:c},{responseType:"text"});b="string"==typeof f.data?f.data:String(f.data)}else{let c=await e.files.get({fileId:a.file_id,alt:"media"},{responseType:"arraybuffer"}),g=Buffer.from(c.data);b=await a$(g,d,f)}let h=b.length>15e3,i=h?b.slice(0,15e3)+"\n\n[...file truncated at 15000 chars...]":b;return{file_id:a.file_id,name:f,mimeType:d,content:i,truncated:h,char_count:i.length}}catch(a){throw aO(a)}}},{name:"drive_get_file_info",description:"Get detailed metadata for a file: size, owner, sharing status, dates, MIME type, parent folders.",inputSchema:a1,riskLevel:"read",async execute(a){try{let b=(await e.files.get({fileId:a.file_id,fields:"id,name,mimeType,size,createdTime,modifiedTime,owners,shared,webViewLink,parents"})).data,c=(b.owners??[]).map(a=>a.displayName??a.emailAddress??"");return{id:b.id??"",name:b.name??"",mimeType:b.mimeType??"",sizeBytes:null!=b.size?Number(b.size):null,createdTime:b.createdTime??"",modifiedTime:b.modifiedTime??"",owners:c,shared:b.shared??!1,webViewLink:b.webViewLink??"",parents:b.parents??[]}}catch(a){throw aO(a)}}},{name:"drive_list_permissions",description:"List who has access to a file and their permission levels.",inputSchema:a8,riskLevel:"read",async execute(a){try{let b=((await e.permissions.list({fileId:a.file_id,fields:"permissions(id,role,type,emailAddress,displayName)"})).data.permissions??[]).map(a=>({id:a.id??"",role:a.role??"",type:a.type??"",email:a.emailAddress??null,displayName:a.displayName??null}));return{total:b.length,permissions:b}}catch(a){throw aO(a)}}},{name:"drive_export_file",description:"Export a Google Workspace file (Doc, Sheet, Slide) to a different format. Common: Google Doc → text/plain or application/pdf, Google Sheet → text/csv, Google Slides → application/pdf. Use drive_read_file for regular (non-Workspace) files.",inputSchema:a9,riskLevel:"read",async execute(a){try{if(a.mime_type.startsWith("text/")||"application/json"===a.mime_type){let b=await e.files.export({fileId:a.file_id,mimeType:a.mime_type},{responseType:"text"}),c="string"==typeof b.data?b.data:String(b.data),d=c.length>15e3,f=d?c.slice(0,15e3)+"\n\n[...export truncated at 15000 chars...]":c;return{file_id:a.file_id,mime_type:a.mime_type,content:f,truncated:d,byte_size:Buffer.byteLength(c,"utf-8")}}{let b=(await e.files.export({fileId:a.file_id,mimeType:a.mime_type},{responseType:"arraybuffer"})).data.byteLength;return{file_id:a.file_id,mime_type:a.mime_type,content:`Binary export complete (${b} bytes). Use a text-based MIME type (e.g. text/plain, text/csv) to get readable content.`,truncated:!1,byte_size:b}}}catch(a){throw aO(a)}}},{name:"drive_upload_file",description:"Create a new file in Google Drive with text content.",inputSchema:a0,riskLevel:"write",async execute(a){try{let b=a.mime_type??"text/plain",d={name:a.name,mimeType:b,...a.folder_id&&{parents:[a.folder_id]}},{Readable:f}=await Promise.resolve().then(c.t.bind(c,27910,23)),g={mimeType:b,body:f.from([Buffer.from(a.content,"utf-8")])},h=await e.files.create({requestBody:d,media:g,fields:"id,name,webViewLink"});return{id:h.data.id??"",name:h.data.name??a.name,webViewLink:h.data.webViewLink??""}}catch(a){throw aO(a)}}},{name:"drive_create_folder",description:"Create a new folder in Google Drive.",inputSchema:a2,riskLevel:"write",async execute(a){try{let b={name:a.name,mimeType:"application/vnd.google-apps.folder",...a.parent_id&&{parents:[a.parent_id]}},c=await e.files.create({requestBody:b,fields:"id,name,webViewLink"});return{id:c.data.id??"",name:c.data.name??a.name,webViewLink:c.data.webViewLink??""}}catch(a){throw aO(a)}}},{name:"drive_move_file",description:"Move a file to a different folder in Google Drive.",inputSchema:a3,riskLevel:"write",async execute(a){try{let b=((await e.files.get({fileId:a.file_id,fields:"id,name,parents"})).data.parents??[]).join(","),c=await e.files.update({fileId:a.file_id,addParents:a.new_parent_id,removeParents:b||void 0,fields:"id,name,parents"});return{id:c.data.id??"",name:c.data.name??"",parents:c.data.parents??[]}}catch(a){throw aO(a)}}},{name:"drive_rename_file",description:"Rename a file in Google Drive.",inputSchema:a4,riskLevel:"write",async execute(a){try{let b=await e.files.update({fileId:a.file_id,requestBody:{name:a.new_name},fields:"id,name"});return{id:b.data.id??"",name:b.data.name??a.new_name}}catch(a){throw aO(a)}}},{name:"drive_copy_file",description:"Create a copy of a file in Google Drive.",inputSchema:a5,riskLevel:"write",async execute(a){try{let b={};a.new_name&&(b.name=a.new_name),a.folder_id&&(b.parents=[a.folder_id]);let c=await e.files.copy({fileId:a.file_id,requestBody:Object.keys(b).length>0?b:void 0,fields:"id,name,webViewLink"});return{id:c.data.id??"",name:c.data.name??"",webViewLink:c.data.webViewLink??""}}catch(a){throw aO(a)}}},{name:"drive_share_file",description:"Share a file with a user or make it accessible via link. Provide email for user sharing, or omit for anyone-with-link sharing.",inputSchema:a7,riskLevel:"write",async execute(a){try{let b=a.role??"reader",c=a.type??(a.email?"user":"anyone"),d={role:b,type:c,...a.email&&{emailAddress:a.email}},f=await e.permissions.create({fileId:a.file_id,requestBody:d,fields:"id,role,type,emailAddress",sendNotificationEmail:"user"===c||"group"===c});return{permission_id:f.data.id??"",role:f.data.role??b,type:f.data.type??c,email:f.data.emailAddress??null}}catch(a){throw aO(a)}}},{name:"drive_delete_file",description:"Move a file to trash in Google Drive. This is reversible — the file can be restored from the Drive trash.",inputSchema:a6,riskLevel:"destructive",async execute(a){try{let b=await e.files.update({fileId:a.file_id,requestBody:{trashed:!0},fields:"id,name,trashed"});return{id:b.data.id??"",name:b.data.name??"",trashed:b.data.trashed??!0}}catch(a){throw aO(a)}}}]}class bb extends Error{constructor(a,b,c){super(b),this.name="GmailAdapterError",this.code=a,this.status=c}}function bc(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="gmail_validation_error";break;case 401:a="gmail_unauthorized";break;case 403:a="gmail_forbidden";break;case 404:a="gmail_message_not_found";break;case 429:a="gmail_quota_exceeded";break;case 503:a="gmail_service_unavailable";break;default:a="gmail_unknown"}return new bb(a,c,b)}}return a instanceof bb?a:a instanceof Error?new bb("gmail_unknown",a.message):new bb("gmail_unknown",String(a))}async function bd(a,b=100,c=100){let d,e=[],f=Math.min(c,500);for(let c=0;c<20;c++){let c=Math.min(b,500,f-e.length),g=await a(d,c);if(e.push(...g.items),e.length>=f||!g.nextPageToken||0===g.items.length)break;d=g.nextPageToken}return e.slice(0,f)}function be(a){let b=a.body?.data;if(!b)return"";if(!b)return"";let c=b.replace(/-/g,"+").replace(/_/g,"/"),d=(4-c.length%4)%4,e=c+"=".repeat(d);try{return Buffer.from(e,"base64").toString("utf-8")}catch{return""}}function bf(a){if(!a)return"";let b=a.mimeType??"";if(b.startsWith("text/plain"))return be(a);if(b.startsWith("text/html"))return be(a).replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/[ \t]+/g," ").replace(/\n\s*\n\s*\n/g,"\n\n").trim();if(b.startsWith("multipart/")){let b=a.parts??[];for(let a of b)if((a.mimeType??"").startsWith("text/plain")){let b=bf(a);if(b.trim())return b}for(let a of b)if((a.mimeType??"").startsWith("text/html")){let b=bf(a);if(b.trim())return b}for(let a of b)if((a.mimeType??"").startsWith("multipart/")){let b=bf(a);if(b.trim())return b}}return""}function bg(a){let b={};for(let c of a?.headers??[])c.name&&null!=c.value&&(b[c.name.toLowerCase()]=c.value);return b}let bh={".html":"text/html",".htm":"text/html",".csv":"text/csv",".tsv":"text/tab-separated-values",".json":"application/json",".xml":"application/xml",".md":"text/markdown",".markdown":"text/markdown",".txt":"text/plain",".log":"text/plain",".js":"text/javascript",".css":"text/css",".yaml":"application/yaml",".yml":"application/yaml"};function bi(a){if(![...a].some(a=>a.charCodeAt(0)>127))return a;let b=Buffer.from(a,"utf-8").toString("base64");return`=?utf-8?B?${b}?=`}function bj(a){let b,{to:c,subject:d,body:e,from:f,cc:g,bcc:h,replyTo:i,inReplyTo:j,references:k,attachments:l}=a,m=l&&l.length>0,n=e.includes("<")&&e.includes(">")&&/<[a-zA-Z][^>]*>/.test(e);if(m){let a=`nodalai_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`,m=Buffer.from(e,"utf-8").toString("base64"),p=[];f&&p.push(`From: ${f}`),p.push(`To: ${c}`),g&&p.push(`Cc: ${g}`),h&&p.push(`Bcc: ${h}`),i&&p.push(`Reply-To: ${i}`),p.push(`Subject: ${bi(d)}`),j&&p.push(`In-Reply-To: ${j}`),k&&p.push(`References: ${k}`),p.push("MIME-Version: 1.0"),p.push(`Content-Type: multipart/mixed; boundary="${a}"`);let q=[];for(let b of(q.push([`--${a}`,`Content-Type: ${n?"text/html; charset=utf-8":"text/plain; charset=utf-8"}`,"Content-Transfer-Encoding: base64","",m.match(/.{1,76}/g)?.join("\r\n")??m].join("\r\n")),l)){var o;let c=b.mimeType??bh[(o=b.filename).includes(".")?"."+o.split(".").pop().toLowerCase():""]??"application/octet-stream",d=bi(b.filename),e=("base64"===b.encoding?Buffer.from(b.content,"base64"):Buffer.from(b.content,"utf-8")).toString("base64");q.push([`--${a}`,`Content-Type: ${c}; name="${d}"`,"Content-Transfer-Encoding: base64",`Content-Disposition: attachment; filename="${d}"`,"",e.match(/.{1,76}/g)?.join("\r\n")??e].join("\r\n"))}b=p.join("\r\n")+"\r\n\r\n"+q.join("\r\n")+`\r
8
+ --${a}--`}else{let a=Buffer.from(e,"utf-8").toString("base64"),l=[];f&&l.push(`From: ${f}`),l.push(`To: ${c}`),g&&l.push(`Cc: ${g}`),h&&l.push(`Bcc: ${h}`),i&&l.push(`Reply-To: ${i}`),l.push(`Subject: ${bi(d)}`),j&&l.push(`In-Reply-To: ${j}`),k&&l.push(`References: ${k}`),l.push("MIME-Version: 1.0"),l.push(`Content-Type: ${n?"text/html; charset=utf-8":"text/plain; charset=utf-8"}`),l.push("Content-Transfer-Encoding: base64"),l.push(""),l.push(a.match(/.{1,76}/g)?.join("\r\n")??a),b=l.join("\r\n")}return Buffer.from(b).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}let bk=g.Ik({filename:g.Yj().describe("File name shown in the email, e.g. 'report.html'."),content:g.Yj().describe("File content as a string (plain text by default, or base64 if encoding is base64)."),mimeType:g.Yj().optional().describe("MIME type, e.g. 'text/html'. Inferred from filename if omitted."),encoding:g.k5(["text","base64"]).optional().describe("How content is encoded. Default 'text'. Use 'base64' for pre-encoded binaries.")}),bl=g.Ik({to:g.Yj().describe("Recipient email address or comma-separated list."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),reply_to:g.Yj().optional().describe("Reply-To header."),attachments:g.YO(bk).optional().describe("Optional file attachments. Each item: {filename, content, mimeType?, encoding?}. Default encoding is 'text' — pass the file content as a plain string. Use encoding='base64' only when you hold pre-encoded binary content.")}),bm=g.Ik({query:g.Yj().optional().describe("Gmail search query. Examples: 'is:unread', 'from:alice@example.com', 'subject:invoice newer_than:7d'. Default: lists recent messages in inbox."),max_results:g.ai().int().min(1).max(500).optional().describe("Max messages to return (1–500, default 20)."),include_spam_trash:g.zM().optional().describe("Include messages from SPAM and TRASH (default false).")}),bn=g.Ik({message_id:g.Yj().describe("Gmail message ID (from gmail_list_messages).")}),bo=g.Ik({message_id:g.Yj().describe("ID of the message to reply to."),body:g.Yj().describe("Reply body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),attachments:g.YO(bk).optional().describe("Optional attachments to include with the reply.")}),bp=g.Ik({message_id:g.Yj().describe("ID of the message to forward."),to:g.Yj().describe("Recipient(s), comma-separated."),note:g.Yj().optional().describe("Optional note prepended before the forwarded body."),cc:g.Yj().optional().describe("CC address(es), comma-separated.")}),bq=g.Ik({message_id:g.Yj().describe("Gmail message ID."),add_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to add, e.g. ['STARRED', 'IMPORTANT']."),remove_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to remove, e.g. ['UNREAD', 'INBOX'].")}),br=g.Ik({message_id:g.Yj().describe("Gmail message ID to move to Trash.")}),bs=g.Ik({message_id:g.Yj().describe("Gmail message ID to restore from Trash.")}),bt=g.Ik({message_id:g.Yj().describe("Gmail message ID to permanently delete.")}),bu=g.Ik({query:g.Yj().optional().describe("Gmail search query. Examples: 'is:unread', 'from:alice@example.com label:work'."),max_results:g.ai().int().min(1).max(500).optional().describe("Max threads to return (1–500, default 20)."),include_spam_trash:g.zM().optional().describe("Include threads from SPAM and TRASH (default false).")}),bv=g.Ik({thread_id:g.Yj().describe("Gmail thread ID (from gmail_list_threads or gmail_list_messages).")}),bw=g.Ik({thread_id:g.Yj().describe("Gmail thread ID."),add_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to add to all messages in the thread, e.g. ['STARRED']."),remove_labels:g.YO(g.Yj()).optional().describe("Label IDs or system labels to remove from all messages, e.g. ['UNREAD'].")}),bx=g.Ik({thread_id:g.Yj().describe("Gmail thread ID to move to Trash.")}),by=g.Ik({}),bz=g.Ik({label_id:g.Yj().describe("Label ID (from gmail_list_labels). System labels: 'INBOX', 'SENT', etc.")}),bA=g.Ik({name:g.Yj().describe("Label name. Use '/' for nesting, e.g. 'Clients/Acme'."),label_list_visibility:g.k5(["labelShow","labelShowIfUnread","labelHide"]).optional().describe("Sidebar visibility (default labelShow)."),message_list_visibility:g.k5(["show","hide"]).optional().describe("Visibility in message list (default show).")}),bB=g.Ik({label_id:g.Yj().describe("Label ID to update (from gmail_list_labels)."),name:g.Yj().optional().describe("New label name."),label_list_visibility:g.k5(["labelShow","labelShowIfUnread","labelHide"]).optional().describe("Sidebar visibility."),message_list_visibility:g.k5(["show","hide"]).optional().describe("Message list visibility.")}),bC=g.Ik({label_id:g.Yj().describe("Label ID to permanently delete (cannot delete system labels like INBOX).")}),bD=g.Ik({filename:g.Yj().describe("File name shown in the email, e.g. 'report.html'."),content:g.Yj().describe("File content as a string (plain text by default)."),mimeType:g.Yj().optional().describe("MIME type. Inferred from filename if omitted."),encoding:g.k5(["text","base64"]).optional().describe("'text' (default) or 'base64' for binaries.")}),bE=g.Ik({max_results:g.ai().int().min(1).max(500).optional().describe("Max drafts to return (default 20)."),query:g.Yj().optional().describe("Optional Gmail search query.")}),bF=g.Ik({to:g.Yj().describe("Recipient email address."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),reply_to_message_id:g.Yj().optional().describe("If provided, sets In-Reply-To and threadId so this draft is a reply in-thread."),attachments:g.YO(bD).optional().describe("Optional file attachments.")}),bG=g.Ik({draft_id:g.Yj().describe("Draft ID to update (from gmail_list_drafts or gmail_create_draft)."),to:g.Yj().describe("Recipient email address."),subject:g.Yj().describe("Email subject line."),body:g.Yj().describe("Email body — plain text or HTML."),cc:g.Yj().optional().describe("CC address(es), comma-separated."),bcc:g.Yj().optional().describe("BCC address(es), comma-separated."),attachments:g.YO(bD).optional().describe("Optional file attachments.")}),bH=g.Ik({draft_id:g.Yj().describe("Draft ID to send (from gmail_list_drafts or gmail_create_draft).")}),bI=g.Ik({draft_id:g.Yj().describe("Draft ID to permanently delete.")}),bJ=g.Ik({message_id:g.Yj().describe("Gmail message ID containing the attachment."),attachment_id:g.Yj().describe("Attachment ID (from gmail_get_message attachments list)."),filename:g.Yj().optional().describe("Filename hint (for display only, not required).")}),bK=g.Ik({start_history_id:g.Yj().describe("The historyId to start listing changes from. Get an initial historyId from gmail_list_messages or gmail_get_message (historyId field)."),max_results:g.ai().int().min(1).max(500).optional().describe("Max history records to return (default 100)."),label_id:g.Yj().optional().describe("Filter history records by label ID.")});function bL(a){var b;let c,d=(b="getAccessToken"in a?a.getAccessToken:async()=>a.accessToken,(c=new aM.google.auth.OAuth2).refreshHandler=async()=>({access_token:await b(),expiry_date:Date.now()-1}),aM.google.gmail({version:"v1",auth:c}));return[{name:"gmail_list_messages",description:"List Gmail messages matching a query. Returns message IDs, thread IDs, sender, subject, date and snippet. Use gmail_get_message to read the full body, or gmail_get_thread for the full conversation.",inputSchema:bm,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),c=await bd(async(b,c)=>{let e={userId:"me",maxResults:c,includeSpamTrash:a.include_spam_trash??!1,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await d.users.messages.list(e);return{items:f.data.messages??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b),e=await Promise.all(c.map(async a=>{try{let b=await d.users.messages.get({userId:"me",id:a.id,format:"metadata",metadataHeaders:["Subject","From","Date"]}),c=bg(b.data.payload??void 0);return{messageId:b.data.id??a.id??"",threadId:b.data.threadId??a.threadId??"",from:c.from??"",subject:c.subject??"",date:c.date??"",snippet:b.data.snippet??"",labelIds:b.data.labelIds??[]}}catch{return{messageId:a.id??"",threadId:a.threadId??"",from:"",subject:"",date:"",snippet:"",labelIds:[]}}}));return{total:e.length,messages:e}}catch(a){throw bc(a)}}},{name:"gmail_get_message",description:"Get the full content of a Gmail message including decoded body and attachment metadata. Use gmail_get_attachment to download an attachment by its ID.",inputSchema:bn,riskLevel:"read",async execute(a){try{let b=(await d.users.messages.get({userId:"me",id:a.message_id,format:"full"})).data,c=b.payload??void 0,e=bg(c),f=bf(c).trim(),g=f.length>1e4;g&&(f=f.slice(0,1e4)+"\n\n[...body truncated]");let h=function a(b,c=[]){if(!b)return c;let d=b.body?.attachmentId;for(let e of(d&&b.filename&&c.push({attachmentId:d,filename:b.filename,mimeType:b.mimeType??"application/octet-stream",size:b.body?.size??0}),b.parts??[]))a(e,c);return c}(c);return{messageId:b.id??"",threadId:b.threadId??"",from:e.from??"",to:e.to??"",cc:e.cc??"",subject:e.subject??"",date:e.date??"",body:f,truncated:g,labelIds:b.labelIds??[],attachments:h}}catch(a){throw bc(a)}}},{name:"gmail_list_threads",description:"List Gmail conversation threads matching a query. Returns thread IDs and snippets. Use gmail_get_thread to read the full conversation.",inputSchema:bu,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),c=await bd(async(b,c)=>{let e={userId:"me",maxResults:c,includeSpamTrash:a.include_spam_trash??!1,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await d.users.threads.list(e);return{items:f.data.threads??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b);return{total:c.length,threads:c.map(a=>({threadId:a.id??"",snippet:a.snippet??"",historyId:a.historyId??""}))}}catch(a){throw bc(a)}}},{name:"gmail_get_thread",description:"Fetch a full Gmail conversation thread with all messages, decoded bodies and headers.",inputSchema:bv,riskLevel:"read",async execute(a){try{let b=(await d.users.threads.get({userId:"me",id:a.thread_id,format:"full"})).data,c=(b.messages??[]).map(a=>{let b=a.payload??void 0,c=bg(b),d=bf(b).trim();return d.length>5e3&&(d=d.slice(0,5e3)+"\n\n[...truncated]"),{messageId:a.id??"",from:c.from??"",to:c.to??"",subject:c.subject??"",date:c.date??"",snippet:a.snippet??"",body:d,labelIds:a.labelIds??[]}});return{threadId:b.id??"",messages:c}}catch(a){throw bc(a)}}},{name:"gmail_list_labels",description:"List all Gmail labels — both system labels (INBOX, SENT, TRASH, SPAM, etc.) and user-created labels. Returns label IDs needed for gmail_modify_labels.",inputSchema:by,riskLevel:"read",async execute(){try{let a=((await d.users.labels.list({userId:"me"})).data.labels??[]).map(a=>({id:a.id??"",name:a.name??"",type:a.type??"",messageListVisibility:a.messageListVisibility??"",labelListVisibility:a.labelListVisibility??"",messagesTotal:a.messagesTotal??0,messagesUnread:a.messagesUnread??0,threadsTotal:a.threadsTotal??0,threadsUnread:a.threadsUnread??0}));return{total:a.length,labels:a}}catch(a){throw bc(a)}}},{name:"gmail_get_label",description:"Get details and message counts for a specific Gmail label.",inputSchema:bz,riskLevel:"read",async execute(a){try{let b=(await d.users.labels.get({userId:"me",id:a.label_id})).data;return{id:b.id??"",name:b.name??"",type:b.type??"",messagesTotal:b.messagesTotal??0,messagesUnread:b.messagesUnread??0,threadsTotal:b.threadsTotal??0,threadsUnread:b.threadsUnread??0}}catch(a){throw bc(a)}}},{name:"gmail_list_drafts",description:"List Gmail drafts with their IDs, subjects and snippets. Use draft_id with gmail_send_draft to send or gmail_update_draft to edit.",inputSchema:bE,riskLevel:"read",async execute(a){try{let b=Math.min(a.max_results??20,500),c=await bd(async(b,c)=>{let e={userId:"me",maxResults:c,...b&&{pageToken:b},...a.query&&{q:a.query}},f=await d.users.drafts.list(e);return{items:f.data.drafts??[],nextPageToken:f.data.nextPageToken}},Math.min(b,100),b),e=await Promise.all(c.map(async a=>{let b=a.id??"";try{let a=(await d.users.drafts.get({userId:"me",id:b,format:"metadata"})).data.message??{},c=bg(a.payload??void 0);return{draftId:b,messageId:a.id??"",to:c.to??"",subject:c.subject??"",snippet:a.snippet??""}}catch{return{draftId:b,messageId:a.message?.id??"",to:"",subject:"",snippet:""}}}));return{total:e.length,drafts:e}}catch(a){throw bc(a)}}},{name:"gmail_get_attachment",description:"Download an email attachment by message ID and attachment ID. Returns base64url-encoded content. Get attachment IDs from gmail_get_message. Size cap: 25 MB.",inputSchema:bJ,riskLevel:"read",async execute(a){try{let b=(await d.users.messages.attachments.get({userId:"me",messageId:a.message_id,id:a.attachment_id})).data,c=b.size??0;if(c>0x1900000)throw new bb("gmail_attachment_too_large",`Attachment exceeds the 25 MB limit (${Math.round(c/1024/1024)} MB).`);return{attachmentId:a.attachment_id,messageId:a.message_id,filename:a.filename??"",sizeBytes:c,data:b.data??""}}catch(a){throw bc(a)}}},{name:"gmail_list_history",description:"List Gmail mailbox changes since a given historyId. Useful for incremental sync — only fetch changes since last check. Returns the latest historyId to use in subsequent calls.",inputSchema:bK,riskLevel:"read",async execute(a){try{let b={userId:"me",startHistoryId:a.start_history_id,maxResults:Math.min(a.max_results??100,500),historyTypes:["messageAdded","messageDeleted","labelAdded","labelRemoved"],...a.label_id&&{labelId:a.label_id}},c=(await d.users.history.list(b)).data,e=(c.history??[]).map(a=>({id:a.id??"",messages:(a.messages??[]).map(a=>({messageId:a.id??"",threadId:a.threadId??""})),messagesAdded:(a.messagesAdded??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.message?.labelIds??[]})),messagesDeleted:(a.messagesDeleted??[]).map(a=>({messageId:a.message?.id??""})),labelsAdded:(a.labelsAdded??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.labelIds??[]})),labelsRemoved:(a.labelsRemoved??[]).map(a=>({messageId:a.message?.id??"",labelIds:a.labelIds??[]}))}));return{historyId:c.historyId??"",history:e}}catch(a){throw bc(a)}}},{name:"gmail_send_email",description:"Send an email via Gmail. Supports plain text and HTML bodies, CC, BCC, Reply-To, and file attachments. Use attachments to send reports, CSVs, or HTML files as real files rather than pasting content inline.",inputSchema:bl,riskLevel:"write",async execute(a){try{let b=bj({to:a.to,subject:a.subject,body:a.body,cc:a.cc,bcc:a.bcc,replyTo:a.reply_to,attachments:a.attachments}),c=await d.users.messages.send({userId:"me",requestBody:{raw:b}});return{messageId:c.data.id??"",threadId:c.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_reply_message",description:"Reply to a Gmail message in-thread. Automatically sets In-Reply-To, References, subject (Re: prefix), and threadId. Fetches the original message headers to build correct threading.",inputSchema:bo,riskLevel:"write",async execute(a){try{let b=(await d.users.messages.get({userId:"me",id:a.message_id,format:"metadata",metadataHeaders:["Subject","From","To","Message-ID","Message-Id","References"]})).data,c=bg(b.payload??void 0),e=b.threadId??void 0,f=c.subject??"",g=f.toLowerCase().startsWith("re:")?f:`Re: ${f}`,h=c.from??"",i=c["message-id"]??c["message-id"]??"",j=c.references??"",k=i?j?`${j} ${i}`:i:j,l={raw:bj({to:h,subject:g,body:a.body,cc:a.cc,inReplyTo:i||void 0,references:k||void 0,attachments:a.attachments})};e&&(l.threadId=e);let m=await d.users.messages.send({userId:"me",requestBody:l});return{messageId:m.data.id??"",threadId:m.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_forward_message",description:"Forward a Gmail message to new recipients. Quotes the original body and prepends Fwd: to the subject.",inputSchema:bp,riskLevel:"write",async execute(a){try{let b=(await d.users.messages.get({userId:"me",id:a.message_id,format:"full"})).data.payload??void 0,c=bg(b),e=c.subject??"",f=e.toLowerCase().startsWith("fwd:")?e:`Fwd: ${e}`,g=bf(b).trim(),h=a.note?`${a.note}
9
9
 
10
10
  `:"",i=`${h}---------- Forwarded message ----------
11
- From: ${d.from??""}
12
- Date: ${d.date??""}
11
+ From: ${c.from??""}
12
+ Date: ${c.date??""}
13
13
  Subject: ${e}
14
- To: ${d.to??""}
14
+ To: ${c.to??""}
15
15
 
16
- `+g,j=bf({to:a.to,subject:f,body:i,cc:a.cc}),k=await c.users.messages.send({userId:"me",requestBody:{raw:j}});return{messageId:k.data.id??"",threadId:k.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_modify_labels",description:"Add or remove labels on a Gmail message. System labels: INBOX, UNREAD, STARRED, IMPORTANT, TRASH, SPAM. Use to mark as read (remove UNREAD), star, archive (remove INBOX), etc.",inputSchema:bm,riskLevel:"write",async execute(a){try{if(!a.add_labels?.length&&!a.remove_labels?.length)throw new a7("gmail_validation_error","Provide at least one of add_labels or remove_labels.");let b=await c.users.messages.modify({userId:"me",id:a.message_id,requestBody:{addLabelIds:a.add_labels??[],removeLabelIds:a.remove_labels??[]}});return{messageId:b.data.id??"",labelIds:b.data.labelIds??[]}}catch(a){throw a8(a)}}},{name:"gmail_trash_message",description:"Move a Gmail message to the Trash folder. Recoverable for 30 days. Prefer this over permanent delete.",inputSchema:bn,riskLevel:"write",async execute(a){try{let b=await c.users.messages.trash({userId:"me",id:a.message_id});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_untrash_message",description:"Restore a Gmail message from the Trash folder.",inputSchema:bo,riskLevel:"write",async execute(a){try{let b=await c.users.messages.untrash({userId:"me",id:a.message_id});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_modify_thread_labels",description:"Add or remove labels on all messages in a Gmail thread at once. Use to archive a thread (remove INBOX), mark all as read (remove UNREAD), etc.",inputSchema:bs,riskLevel:"write",async execute(a){try{return{threadId:(await c.users.threads.modify({userId:"me",id:a.thread_id,requestBody:{addLabelIds:a.add_labels??[],removeLabelIds:a.remove_labels??[]}})).data.id??""}}catch(a){throw a8(a)}}},{name:"gmail_trash_thread",description:"Move an entire Gmail conversation thread to the Trash folder. Recoverable for 30 days.",inputSchema:bt,riskLevel:"write",async execute(a){try{return{threadId:(await c.users.threads.trash({userId:"me",id:a.thread_id})).data.id??""}}catch(a){throw a8(a)}}},{name:"gmail_create_label",description:"Create a new Gmail user label. Use '/' in the name to nest labels, e.g. 'Projects/Nodal-Agents'.",inputSchema:bw,riskLevel:"write",async execute(a){try{let b=await c.users.labels.create({userId:"me",requestBody:{name:a.name,labelListVisibility:a.label_list_visibility??"labelShow",messageListVisibility:a.message_list_visibility??"show"}});return{id:b.data.id??"",name:b.data.name??""}}catch(a){throw a8(a)}}},{name:"gmail_update_label",description:"Update an existing Gmail user label — rename it or change its visibility.",inputSchema:bx,riskLevel:"write",async execute(a){try{let b={};void 0!==a.name&&(b.name=a.name),void 0!==a.label_list_visibility&&(b.labelListVisibility=a.label_list_visibility),void 0!==a.message_list_visibility&&(b.messageListVisibility=a.message_list_visibility);let d=await c.users.labels.patch({userId:"me",id:a.label_id,requestBody:b});return{id:d.data.id??"",name:d.data.name??""}}catch(a){throw a8(a)}}},{name:"gmail_create_draft",description:"Create a draft email in Gmail (not sent). Use reply_to_message_id to create a reply draft in-thread with correct threading headers.",inputSchema:bB,riskLevel:"write",async execute(a){try{let b,d,e,f=a.subject;if(a.reply_to_message_id){let g=(await c.users.messages.get({userId:"me",id:a.reply_to_message_id,format:"metadata",metadataHeaders:["Subject","Message-ID","Message-Id","References"]})).data;b=g.threadId??void 0;let h=bc(g.payload??void 0),i=h.subject??"";i&&!f.toLowerCase().startsWith("re:")&&(f=i.toLowerCase().startsWith("re:")?i:`Re: ${i}`);let j=h["message-id"]??"",k=h.references??"";d=j||void 0,e=j?k?`${k} ${j}`:j:k||void 0}let g={message:{raw:bf({to:a.to,subject:f,body:a.body,cc:a.cc,bcc:a.bcc,inReplyTo:d,references:e,attachments:a.attachments}),...b&&{threadId:b}}},h=await c.users.drafts.create({userId:"me",requestBody:g});return{draftId:h.data.id??"",messageId:h.data.message?.id??""}}catch(a){throw a8(a)}}},{name:"gmail_update_draft",description:"Overwrite an existing Gmail draft with new content. Use this to revise a draft before sending.",inputSchema:bC,riskLevel:"write",async execute(a){try{let b=bf({to:a.to,subject:a.subject,body:a.body,cc:a.cc,bcc:a.bcc,attachments:a.attachments}),d=await c.users.drafts.update({userId:"me",id:a.draft_id,requestBody:{message:{raw:b}}});return{draftId:d.data.id??a.draft_id,messageId:d.data.message?.id??""}}catch(a){throw a8(a)}}},{name:"gmail_send_draft",description:"Send an existing Gmail draft. The draft is dispatched as an email and can no longer be edited.",inputSchema:bD,riskLevel:"write",async execute(a){try{let b=await c.users.drafts.send({userId:"me",requestBody:{id:a.draft_id}});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw a8(a)}}},{name:"gmail_delete_message",description:"Permanently delete a Gmail message. This is irreversible — the message cannot be recovered. Consider gmail_trash_message for recoverable deletion.",inputSchema:bp,riskLevel:"destructive",async execute(a){try{return await c.users.messages.delete({userId:"me",id:a.message_id}),{deleted:!0,messageId:a.message_id}}catch(a){throw a8(a)}}},{name:"gmail_delete_label",description:"Permanently delete a Gmail user label. Cannot delete system labels (INBOX, SENT, etc.). Messages with this label are NOT deleted — they simply lose the label.",inputSchema:by,riskLevel:"destructive",async execute(a){try{return await c.users.labels.delete({userId:"me",id:a.label_id}),{deleted:!0,labelId:a.label_id}}catch(a){throw a8(a)}}},{name:"gmail_delete_draft",description:"Permanently delete a Gmail draft. This is irreversible.",inputSchema:bE,riskLevel:"destructive",async execute(a){try{return await c.users.drafts.delete({userId:"me",id:a.draft_id}),{deleted:!0,draftId:a.draft_id}}catch(a){throw a8(a)}}}]},operations:[{slug:"gmail_list_messages",name:"List messages",risk:"read",requiresApproval:!1,description:"Search and list emails by query."},{slug:"gmail_get_message",name:"Get message",risk:"read",requiresApproval:!1,description:"Retrieve a single email by ID."},{slug:"gmail_list_threads",name:"List threads",risk:"read",requiresApproval:!1,description:"List email conversation threads."},{slug:"gmail_get_thread",name:"Get thread",risk:"read",requiresApproval:!1,description:"Retrieve all messages in a thread."},{slug:"gmail_list_labels",name:"List labels",risk:"read",requiresApproval:!1,description:"List all Gmail labels."},{slug:"gmail_get_label",name:"Get label",risk:"read",requiresApproval:!1,description:"Retrieve a single label by ID."},{slug:"gmail_list_drafts",name:"List drafts",risk:"read",requiresApproval:!1,description:"List email drafts."},{slug:"gmail_get_attachment",name:"Get attachment",risk:"read",requiresApproval:!1,description:"Download an email attachment by ID."},{slug:"gmail_list_history",name:"List history",risk:"read",requiresApproval:!1,description:"List mailbox history changes since a given historyId."},{slug:"gmail_reply_message",name:"Reply to message",risk:"write",requiresApproval:!1,description:"Send a reply in an existing thread."},{slug:"gmail_forward_message",name:"Forward message",risk:"write",requiresApproval:!1,description:"Forward an email to new recipients."},{slug:"gmail_modify_labels",name:"Modify labels",risk:"write",requiresApproval:!1,description:"Add or remove labels on a message."},{slug:"gmail_trash_message",name:"Trash message",risk:"write",requiresApproval:!1,description:"Move a message to Trash (reversible)."},{slug:"gmail_untrash_message",name:"Untrash message",risk:"write",requiresApproval:!1,description:"Restore a message from Trash."},{slug:"gmail_modify_thread_labels",name:"Modify thread labels",risk:"write",requiresApproval:!1,description:"Add or remove labels on all messages in a thread."},{slug:"gmail_trash_thread",name:"Trash thread",risk:"write",requiresApproval:!1,description:"Move an entire thread to Trash (reversible)."},{slug:"gmail_create_label",name:"Create label",risk:"write",requiresApproval:!1,description:"Create a new Gmail label."},{slug:"gmail_update_label",name:"Update label",risk:"write",requiresApproval:!1,description:"Rename or update a Gmail label."},{slug:"gmail_create_draft",name:"Create draft",risk:"write",requiresApproval:!1,description:"Compose an email draft without sending."},{slug:"gmail_update_draft",name:"Update draft",risk:"write",requiresApproval:!1,description:"Update an existing email draft."},{slug:"gmail_send_email",name:"Send email",risk:"destructive",requiresApproval:!0,description:"Send an email from the connected mailbox (irreversible)."},{slug:"gmail_send_draft",name:"Send draft",risk:"destructive",requiresApproval:!0,description:"Send a saved draft (irreversible)."},{slug:"gmail_delete_message",name:"Delete message",risk:"destructive",requiresApproval:!0,description:"Permanently delete a message (bypasses Trash)."},{slug:"gmail_delete_label",name:"Delete label",risk:"destructive",requiresApproval:!0,description:"Permanently delete a Gmail label."},{slug:"gmail_delete_draft",name:"Delete draft",risk:"destructive",requiresApproval:!0,description:"Permanently delete an email draft."}]},"google-calendar":{credentialType:"google-oauth",toolFactory:a=>{let b,c;return(b=new aJ.google.auth.OAuth2).setCredentials({access_token:a}),[(c=aJ.google.calendar({version:"v3",auth:b}),{name:"gcal_list_calendars",description:"List the calendars the user can access. Returns calendar IDs (use the id with the other gcal_* tools; 'primary' is the user's main calendar).",inputSchema:bR,riskLevel:"read",async execute(){try{let a=((await c.calendarList.list()).data.items??[]).map(a=>({id:a.id??"",summary:a.summary??"",description:a.description??"",primary:!!a.primary,accessRole:a.accessRole??"",timeZone:a.timeZone??""}));return{total:a.length,calendars:a}}catch(a){throw bI(a)}}}),{name:"gcal_list_events",description:"List calendar events in a time range. Defaults to UPCOMING events from now. Use time_min/time_max (ISO 8601) to bound, query to text-search. Returns event IDs.",inputSchema:bL,riskLevel:"read",async execute(a){try{let b=((await c.events.list({calendarId:a.calendar_id??"primary",timeMin:a.time_min??new Date().toISOString(),timeMax:a.time_max,q:a.query,singleEvents:!0,orderBy:"startTime",maxResults:a.max_results??25})).data.items??[]).map(bJ);return{total:b.length,events:b}}catch(a){throw bI(a)}}},{name:"gcal_get_event",description:"Get the full details of a single calendar event by ID.",inputSchema:bM,riskLevel:"read",async execute(a){try{let b=await c.events.get({calendarId:a.calendar_id??"primary",eventId:a.event_id});return bJ(b.data)}catch(a){throw bI(a)}}},{name:"gcal_find_free_slots",description:"Query busy intervals across one or more calendars in a time window, so you can find free slots for scheduling. Returns the BUSY ranges per calendar — gaps are free.",inputSchema:bS,riskLevel:"read",async execute(a){try{let b=a.calendar_ids??["primary"],d=await c.freebusy.query({requestBody:{timeMin:a.time_min,timeMax:a.time_max,items:b.map(a=>({id:a}))}}),e={},f=d.data.calendars??{};for(let[a,b]of Object.entries(f))e[a]=(b.busy??[]).map(a=>({start:a.start??"",end:a.end??""}));return{timeMin:a.time_min,timeMax:a.time_max,busy:e}}catch(a){throw bI(a)}}},{name:"gcal_create_event",description:"Create a new calendar event. Use ISO 8601 datetimes for timed events, or YYYY-MM-DD for all-day events. Optionally invite attendees by email.",inputSchema:bN,riskLevel:"write",async execute(a){try{let b=await c.events.insert({calendarId:a.calendar_id??"primary",requestBody:{summary:a.summary,description:a.description,location:a.location,start:bO(a.start,a.time_zone),end:bO(a.end,a.time_zone),attendees:a.attendees?.map(a=>({email:a}))}});return{id:b.data.id??"",htmlLink:b.data.htmlLink??"",summary:b.data.summary??""}}catch(a){throw bI(a)}}},{name:"gcal_update_event",description:"Update an existing calendar event. Only the fields you provide are changed (patch semantics).",inputSchema:bP,riskLevel:"write",async execute(a){try{let b={};void 0!==a.summary&&(b.summary=a.summary),void 0!==a.description&&(b.description=a.description),void 0!==a.location&&(b.location=a.location),void 0!==a.start&&(b.start=bO(a.start,a.time_zone)),void 0!==a.end&&(b.end=bO(a.end,a.time_zone)),void 0!==a.attendees&&(b.attendees=a.attendees.map(a=>({email:a})));let d=await c.events.patch({calendarId:a.calendar_id??"primary",eventId:a.event_id,requestBody:b});return{id:d.data.id??"",htmlLink:d.data.htmlLink??"",summary:d.data.summary??""}}catch(a){throw bI(a)}}},{name:"gcal_delete_event",description:"Permanently delete a calendar event. This cannot be undone.",inputSchema:bQ,riskLevel:"destructive",async execute(a){try{return await c.events.delete({calendarId:a.calendar_id??"primary",eventId:a.event_id}),{deleted:!0,eventId:a.event_id}}catch(a){throw bI(a)}}}]},operations:[{slug:"gcal_list_calendars",name:"List calendars",risk:"read",requiresApproval:!1,description:"List the calendars the user has access to."},{slug:"gcal_list_events",name:"List events",risk:"read",requiresApproval:!1,description:"List events on a calendar within a time range (defaults to upcoming)."},{slug:"gcal_get_event",name:"Get event",risk:"read",requiresApproval:!1,description:"Retrieve a single event by ID."},{slug:"gcal_find_free_slots",name:"Find free slots",risk:"read",requiresApproval:!1,description:"Query busy/free intervals across calendars for scheduling."},{slug:"gcal_create_event",name:"Create event",risk:"write",requiresApproval:!1,description:"Create a new calendar event (optionally inviting attendees)."},{slug:"gcal_update_event",name:"Update event",risk:"write",requiresApproval:!1,description:"Update an existing calendar event."},{slug:"gcal_delete_event",name:"Delete event",risk:"destructive",requiresApproval:!0,description:"Permanently delete a calendar event."}]},"google-sheets":{credentialType:"google-oauth",toolFactory:a=>{let b,c;return(b=new aJ.google.auth.OAuth2).setCredentials({access_token:a}),[(c=aJ.google.sheets({version:"v4",auth:b}),{name:"sheets_read_range",description:"Read a specific A1-notation range from a Google Sheet. Returns a 2D array of cell values. Capped at 10,000 rows — use a smaller range if exceeded.",inputSchema:bZ,riskLevel:"read",async execute(a){try{bY(a.range);let b=await c.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:a.range,valueRenderOption:a.value_render_option??"FORMATTED_VALUE"}),d=b.data.values??[];if(d.length>1e4)throw new bT("sheets_range_too_large",`Range returned ${d.length} rows which exceeds the 10000-row cap. Use a smaller range.`);let e=bX(d),f=e.reduce((a,b)=>Math.max(a,b.length),0);return{range:b.data.range??a.range,rows:e.length,cols:f,values:e}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}}),{name:"sheets_read_all",description:"Read all values from a sheet tab. Returns the full 2D array. Capped at 10,000 rows — use sheets_read_range for partial reads on large sheets.",inputSchema:b$,riskLevel:"read",async execute(a){try{let b=a.sheet_name;if(!b){let d=await c.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.title"});b=d.data.sheets?.[0]?.properties?.title??"Sheet1"}let d=`'${b.replace(/'/g,"''")}'`,e=(await c.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:d,valueRenderOption:"FORMATTED_VALUE"})).data.values??[];if(e.length>1e4)throw new bT("sheets_range_too_large",`Sheet has ${e.length} rows which exceeds the 10000-row cap. Use sheets_read_range with a smaller range.`);let f=bX(e),g=(f[0]??[]).map(a=>String(a)),h=f.slice(1);return{sheetName:b,headers:g,rowCount:h.length,values:f}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_batch_read_ranges",description:"Read multiple A1-notation ranges from a spreadsheet in a single API call. Efficient for dashboards that need data from several tabs or ranges at once.",inputSchema:b_,riskLevel:"read",async execute(a){try{for(let b of a.ranges)bY(b);return{results:((await c.spreadsheets.values.batchGet({spreadsheetId:a.spreadsheet_id,ranges:a.ranges,valueRenderOption:a.value_render_option??"FORMATTED_VALUE"})).data.valueRanges??[]).map(a=>{let b=a.values??[],c=bX(b),d=c.reduce((a,b)=>Math.max(a,b.length),0);return{range:a.range??"",rows:c.length,cols:d,values:c}})}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_get_metadata",description:"Get metadata about a Google Spreadsheet: title, list of sheet tabs with their dimensions, and named ranges. Use this to discover sheet names before reading.",inputSchema:b5,riskLevel:"read",async execute(a){try{let b=(await c.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"spreadsheetId,properties.title,spreadsheetUrl,sheets.properties,namedRanges"})).data,d=(b.sheets??[]).map(a=>({sheetId:a.properties?.sheetId??0,title:a.properties?.title??"",index:a.properties?.index??0,rowCount:a.properties?.gridProperties?.rowCount??0,colCount:a.properties?.gridProperties?.columnCount??0,hidden:a.properties?.hidden??!1})),e=(b.namedRanges??[]).map(a=>({name:a.name??"",range:a.range?`${a.range.sheetId}!R${a.range.startRowIndex}C${a.range.startColumnIndex}:R${a.range.endRowIndex}C${a.range.endColumnIndex}`:""}));return{spreadsheetId:b.spreadsheetId??a.spreadsheet_id,title:b.properties?.title??"",url:b.spreadsheetUrl??"",sheets:d,namedRanges:e}}catch(a){throw bU(a)}}},{name:"sheets_find_rows",description:"Find rows in a Google Sheet where a column matches a value. More efficient than reading all rows when you know what you are looking for. Provide exactly one of: equals or contains.",inputSchema:b4,riskLevel:"read",async execute(a){try{let b=[a.equals,a.contains].filter(a=>void 0!==a);if(1!==b.length)throw new bT("sheets_validation_error","Provide exactly one of: equals, contains.");let d=a.sheet_name;if(!d){let b=await c.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.title"});d=b.data.sheets?.[0]?.properties?.title??"Sheet1"}let e=`'${d.replace(/'/g,"''")}'`,f=(await c.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:e,valueRenderOption:"FORMATTED_VALUE"})).data.values??[];if(0===f.length)return{column:a.column,rowCount:0,headers:[],rows:[]};let g=(f[0]??[]).map(a=>String(a??"")),h=g.indexOf(a.column);if(-1===h)throw new bT("sheets_validation_error",`Column '${a.column}' not found. Available columns: ${g.join(", ")}`);let i=a.limit??100,j=f.slice(1),k=[];for(let b=0;b<j.length&&k.length<i;b++){let c=j[b]??[],d=String(c[h]??"");if(void 0!==a.equals?d===a.equals:d.includes(a.contains)){let a={_row:b+2};for(let b=0;b<g.length;b++){let d=g[b];if(void 0!==d){let e=c[b];a[d]=null==e?"":e}}k.push(a)}}return{column:a.column,rowCount:k.length,headers:g,rows:k}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_write_range",description:"Write (overwrite) a 2D array of values into a Google Sheet range. Existing values in the range are replaced. Use sheets_append_row to add rows at the end.",inputSchema:b0,riskLevel:"write",async execute(a){try{bY(a.range);let b=await c.spreadsheets.values.update({spreadsheetId:a.spreadsheet_id,range:a.range,valueInputOption:a.value_input_option??"USER_ENTERED",requestBody:{values:a.values}});return{updatedRange:b.data.updatedRange??a.range,updatedRows:b.data.updatedRows??0,updatedCols:b.data.updatedColumns??0,updatedCells:b.data.updatedCells??0}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_append_row",description:"Append one or more rows to the end of a Google Sheet (after the last row with data). Pass a 2D array — e.g. [['Alice', 95]] for one row or [['Alice',95],['Bob',87]] for multiple.",inputSchema:b1,riskLevel:"write",async execute(a){try{let b=(await c.spreadsheets.values.append({spreadsheetId:a.spreadsheet_id,range:a.range,valueInputOption:a.value_input_option??"USER_ENTERED",insertDataOption:"INSERT_ROWS",requestBody:{values:a.values}})).data.updates;return{updatedRange:b?.updatedRange??a.range,updatedRows:b?.updatedRows??0,updatedCells:b?.updatedCells??0}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_clear_range",description:"Clear values from a range in a Google Sheet. Cell formatting and structure are preserved. To delete rows entirely, use sheets_delete_sheet and recreate, or use write with empty values.",inputSchema:b2,riskLevel:"write",async execute(a){try{return bY(a.range),{clearedRange:(await c.spreadsheets.values.clear({spreadsheetId:a.spreadsheet_id,range:a.range})).data.clearedRange??a.range}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_batch_update_values",description:"Write values to multiple ranges in a single API call. More efficient than calling sheets_write_range repeatedly.",inputSchema:b3,riskLevel:"write",async execute(a){try{for(let b of a.updates)bY(b.range);let b=await c.spreadsheets.values.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{valueInputOption:a.value_input_option??"USER_ENTERED",data:a.updates.map(a=>({range:a.range,values:a.values}))}}),d=(b.data.responses??[]).map(a=>({updatedRange:a.updatedRange??"",updatedCells:a.updatedCells??0}));return{totalUpdatedCells:b.data.totalUpdatedCells??0,totalUpdatedRows:b.data.totalUpdatedRows??0,responses:d}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_create_spreadsheet",description:"Create a new Google Spreadsheet. Returns the spreadsheet ID and URL. The new spreadsheet will be placed in the root of the authenticated user Drive.",inputSchema:b6,riskLevel:"write",async execute(a){try{let b=await c.spreadsheets.create({requestBody:{properties:{title:a.title},sheets:[{properties:{title:a.sheet_title??"Sheet1"}}]}});return{spreadsheetId:b.data.spreadsheetId??"",title:b.data.properties?.title??a.title,url:b.data.spreadsheetUrl??"",firstSheetId:b.data.sheets?.[0]?.properties?.sheetId??0}}catch(a){throw bU(a)}}},{name:"sheets_add_sheet",description:"Add a new sheet tab to an existing Google Spreadsheet.",inputSchema:b7,riskLevel:"write",async execute(a){try{let b=await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{addSheet:{properties:{title:a.title,...void 0!==a.index&&{index:a.index}}}}]}}),d=b.data.replies?.[0]?.addSheet?.properties;return{sheetId:d?.sheetId??0,title:d?.title??a.title,index:d?.index??0}}catch(a){throw bU(a)}}},{name:"sheets_duplicate_sheet",description:"Copy a sheet tab within the same Google Spreadsheet. Duplicates all data, formatting, and formulas.",inputSchema:b9,riskLevel:"write",async execute(a){try{var b,d,e;let f=a.insert_sheet_index;if(void 0===f){let b=await c.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.index"});f=b.data.sheets?.length??1}let g=await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.source_sheet_id,d=f,e=a.new_sheet_name,{duplicateSheet:{sourceSheetId:b,insertSheetIndex:d,...void 0!==e&&{newSheetName:e}}})]}}),h=g.data.replies?.[0]?.duplicateSheet?.properties;return{sheetId:h?.sheetId??0,title:h?.title??a.new_sheet_name??"",index:h?.index??f}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_rename_sheet",description:"Rename a sheet tab in a Google Spreadsheet.",inputSchema:ca,riskLevel:"write",async execute(a){try{var b,d;return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,d=a.new_title,{updateSheetProperties:{properties:{sheetId:b,title:d},fields:"title"}})]}}),{sheetId:a.sheet_id,title:a.new_title}}catch(a){throw bU(a)}}},{name:"sheets_format_range",description:"Apply formatting to a cell range in a Google Sheet: bold, italic, font size, background color, text color, number format, and alignment. Uses zero-based row/column indices.",inputSchema:cb,riskLevel:"write",async execute(a){try{var b,d,e,f,g,h;let i={},j=[],k={};if(void 0!==a.bold&&(k.bold=a.bold,j.push("textFormat.bold")),void 0!==a.italic&&(k.italic=a.italic,j.push("textFormat.italic")),void 0!==a.font_size&&(k.fontSize=a.font_size,j.push("textFormat.fontSize")),void 0!==a.foreground_color&&(k.foregroundColor={red:a.foreground_color.red,green:a.foreground_color.green,blue:a.foreground_color.blue},j.push("textFormat.foregroundColor")),Object.keys(k).length>0&&(i.textFormat=k),void 0!==a.background_color&&(i.backgroundColor={red:a.background_color.red,green:a.background_color.green,blue:a.background_color.blue},j.push("backgroundColor")),void 0!==a.number_format&&(i.numberFormat={type:a.number_format.type,...void 0!==a.number_format.pattern&&{pattern:a.number_format.pattern}},j.push("numberFormat")),void 0!==a.horizontal_alignment&&(i.horizontalAlignment=a.horizontal_alignment,j.push("horizontalAlignment")),0===j.length)throw new bT("sheets_validation_error","Provide at least one formatting property.");return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,d=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,h=j.join(","),{repeatCell:{range:{sheetId:b,startRowIndex:d,endRowIndex:e,startColumnIndex:f,endColumnIndex:g},cell:{userEnteredFormat:i},fields:`userEnteredFormat(${h})`}})]}}),{formatted:!0,sheetId:a.sheet_id}}catch(a){if(a instanceof bT)throw a;throw bU(a)}}},{name:"sheets_resize_columns",description:"Resize columns in a Google Sheet. Provide pixel_size for a fixed width, or omit to auto-resize columns to fit their content.",inputSchema:cc,riskLevel:"write",async execute(a){try{var b,d,e,f,g,h,i;let j=void 0!==a.pixel_size?(b=a.sheet_id,d=a.start_column_index,e=a.end_column_index,f=a.pixel_size,{updateDimensionProperties:{range:{sheetId:b,dimension:"COLUMNS",startIndex:d,endIndex:e},properties:{pixelSize:f},fields:"pixelSize"}}):(g=a.sheet_id,h=a.start_column_index,i=a.end_column_index,{autoResizeDimensions:{dimensions:{sheetId:g,dimension:"COLUMNS",startIndex:h,endIndex:i}}});return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[j]}}),{resized:!0,sheetId:a.sheet_id,startColumnIndex:a.start_column_index,endColumnIndex:a.end_column_index}}catch(a){throw bU(a)}}},{name:"sheets_freeze_panes",description:"Freeze rows and/or columns in a Google Sheet so they stay visible while scrolling. Set frozen_row_count=1 to freeze the header row. Set to 0 to unfreeze.",inputSchema:cd,riskLevel:"write",async execute(a){try{var b;let d=a.frozen_row_count??0,e=a.frozen_column_count??0;return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,{updateSheetProperties:{properties:{sheetId:b,gridProperties:{frozenRowCount:d,frozenColumnCount:e}},fields:"gridProperties.frozenRowCount,gridProperties.frozenColumnCount"}})]}}),{frozenRowCount:d,frozenColumnCount:e,sheetId:a.sheet_id}}catch(a){throw bU(a)}}},{name:"sheets_set_basic_filter",description:"Apply a basic auto-filter to a range in a Google Sheet. Adds dropdown arrows to the header row for filtering. Uses zero-based row/column indices.",inputSchema:ce,riskLevel:"write",async execute(a){try{var b,d,e,f,g;return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,d=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,{setBasicFilter:{filter:{range:{sheetId:b,startRowIndex:d,endRowIndex:e,startColumnIndex:f,endColumnIndex:g}}}})]}}),{filterApplied:!0,sheetId:a.sheet_id}}catch(a){throw bU(a)}}},{name:"sheets_clear_basic_filter",description:"Remove the basic auto-filter from a sheet tab.",inputSchema:cf,riskLevel:"write",async execute(a){try{return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{clearBasicFilter:{sheetId:a.sheet_id}}]}}),{filterCleared:!0,sheetId:a.sheet_id}}catch(a){throw bU(a)}}},{name:"sheets_sort_range",description:"Sort a range of cells in a Google Sheet by one or more columns. Supports multi-level sort (primary + secondary columns). Uses zero-based row/column indices.",inputSchema:ch,riskLevel:"write",async execute(a){try{var b,d,e,f,g,h;return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,d=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,h=a.sort_specs.map(a=>({dimensionIndex:a.dimension_index,sortOrder:a.sort_order})),{sortRange:{range:{sheetId:b,startRowIndex:d,endRowIndex:e,startColumnIndex:f,endColumnIndex:g},sortSpecs:h}})]}}),{sorted:!0,sheetId:a.sheet_id}}catch(a){throw bU(a)}}},{name:"sheets_delete_sheet",description:"Permanently delete a sheet tab from a Google Spreadsheet. This is irreversible. Get the numeric sheetId from sheets_get_metadata (not the tab name).",inputSchema:b8,riskLevel:"destructive",async execute(a){try{return await c.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{deleteSheet:{sheetId:a.sheet_id}}]}}),{deleted:!0,sheetId:a.sheet_id}}catch(a){throw bU(a)}}}]},operations:[{slug:"sheets_read_range",name:"Read range",risk:"read",requiresApproval:!1,description:"Read values from a cell range (e.g. A1:C10)."},{slug:"sheets_read_all",name:"Read all",risk:"read",requiresApproval:!1,description:"Read all values from a sheet."},{slug:"sheets_batch_read_ranges",name:"Batch read ranges",risk:"read",requiresApproval:!1,description:"Read multiple cell ranges in a single request."},{slug:"sheets_get_metadata",name:"Get metadata",risk:"read",requiresApproval:!1,description:"Retrieve spreadsheet metadata and sheet list."},{slug:"sheets_find_rows",name:"Find rows",risk:"read",requiresApproval:!1,description:"Search rows matching a column value."},{slug:"sheets_write_range",name:"Write range",risk:"write",requiresApproval:!1,description:"Write values to a cell range."},{slug:"sheets_append_row",name:"Append row",risk:"write",requiresApproval:!1,description:"Append a new row at the end of a sheet."},{slug:"sheets_clear_range",name:"Clear range",risk:"write",requiresApproval:!1,description:"Clear values in a cell range."},{slug:"sheets_batch_update_values",name:"Batch update values",risk:"write",requiresApproval:!1,description:"Write values to multiple ranges in one request."},{slug:"sheets_create_spreadsheet",name:"Create spreadsheet",risk:"write",requiresApproval:!1,description:"Create a new Google Sheets spreadsheet."},{slug:"sheets_add_sheet",name:"Add sheet",risk:"write",requiresApproval:!1,description:"Add a new sheet tab to a spreadsheet."},{slug:"sheets_duplicate_sheet",name:"Duplicate sheet",risk:"write",requiresApproval:!1,description:"Duplicate an existing sheet tab."},{slug:"sheets_rename_sheet",name:"Rename sheet",risk:"write",requiresApproval:!1,description:"Rename a sheet tab."},{slug:"sheets_format_range",name:"Format range",risk:"write",requiresApproval:!1,description:"Apply formatting (bold, color, number format) to a cell range."},{slug:"sheets_resize_columns",name:"Resize columns",risk:"write",requiresApproval:!1,description:"Resize column widths in a sheet."},{slug:"sheets_freeze_panes",name:"Freeze panes",risk:"write",requiresApproval:!1,description:"Freeze rows or columns in a sheet."},{slug:"sheets_set_basic_filter",name:"Set basic filter",risk:"write",requiresApproval:!1,description:"Apply a basic filter to a sheet range."},{slug:"sheets_clear_basic_filter",name:"Clear basic filter",risk:"write",requiresApproval:!1,description:"Remove the basic filter from a sheet."},{slug:"sheets_sort_range",name:"Sort range",risk:"write",requiresApproval:!1,description:"Sort a range by one or more columns."},{slug:"sheets_delete_sheet",name:"Delete sheet",risk:"destructive",requiresApproval:!0,description:"Permanently delete a sheet tab from a spreadsheet."}]},"google-docs":{credentialType:"google-oauth",toolFactory:a=>{let b,c;return(b=new aJ.google.auth.OAuth2).setCredentials({access_token:a}),[(c=aJ.google.docs({version:"v1",auth:b}),{name:"docs_get",description:"Get the full structured content of a Google Document as JSON: title, body (with all paragraphs, tables, and structural elements), plus headers and footers. Capped at 100,000 characters of body text — use docs_get_text for plain text extraction.",inputSchema:cp,riskLevel:"read",async execute(a){try{let b=(await c.documents.get({documentId:a.document_id})).data;if(b.body){let a=ck(b.body);if(a.length>1e5)throw new ci("docs_document_too_large",`Document body contains ${a.length} characters which exceeds the 100000-character cap.`)}let d=Object.entries(b.headers??{}).map(([a,b])=>({headerId:a,text:b.content?ck({content:b.content}):""})),e=Object.entries(b.footers??{}).map(([a,b])=>({footerId:a,text:b.content?ck({content:b.content}):""}));return{documentId:b.documentId??a.document_id,title:b.title??"",body:b.body??{},headers:d,footers:e,revisionId:b.revisionId??""}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}}),{name:"docs_get_text",description:"Get the plain text content of a Google Document. Parses the document body, joining all paragraph runs, handling tables (tab-separated cells), and headings. Capped at 100,000 characters — throws docs_document_too_large if exceeded.",inputSchema:cq,riskLevel:"read",async execute(a){try{let b=(await c.documents.get({documentId:a.document_id})).data,d=b.body?ck(b.body):"";if(d.length>1e5)throw new ci("docs_document_too_large",`Document contains ${d.length} characters which exceeds the 100000-character cap.`);return{documentId:b.documentId??a.document_id,title:b.title??"",text:d,charCount:d.length}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_create",description:"Create a new Google Document with the given title. Optionally provide initial text content. Returns the document ID and URL. The document is placed in the authenticated user's Drive root.",inputSchema:co,riskLevel:"write",async execute(a){try{let b=await c.documents.create({requestBody:{title:a.title}}),d=b.data.documentId??"",e=b.data.title??a.title;if(a.content&&a.content.length>0){let b=a.content.endsWith("\n")?a.content:a.content+"\n";await c.documents.batchUpdate({documentId:d,requestBody:{requests:[cm(b)]}})}return{documentId:d,title:e,url:`https://docs.google.com/document/d/${d}/edit`}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_insert_text",description:"Insert text at a specific index in a Google Document body. Index 1 = start of body. Use docs_get to find element indices. This shifts all subsequent content forward.",inputSchema:cr,riskLevel:"write",async execute(a){try{var b;return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.text,{insertText:{location:{index:a.index},text:b}})]}}),{inserted:!0,documentId:a.document_id,index:a.index,charCount:a.text.length}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_append_text",description:"Append text to the end of a Google Document. Uses endOfSegmentLocation — always inserts at the very end of the body, regardless of the current document length. Use \\n for line breaks.",inputSchema:cs,riskLevel:"write",async execute(a){try{let b=a.text.endsWith("\n")?a.text:a.text+"\n";return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[cm(b)]}}),{appended:!0,documentId:a.document_id,charCount:b.length}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_replace_text",description:"Find and replace all occurrences of a text string in a Google Document. Replaces every match in the document body. Returns the number of occurrences changed (0 means the text was not found).",inputSchema:ct,riskLevel:"write",async execute(a){try{var b,d;let e=a.match_case??!0,f=await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.find,d=a.replace,{replaceAllText:{containsText:{text:b,matchCase:e},replaceText:d}})]}}),g=f.data.replies?.[0]?.replaceAllText?.occurrencesChanged??0;return{documentId:a.document_id,occurrencesChanged:g}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_insert_paragraph",description:"Insert a new paragraph at a specific index in a Google Document. Optionally apply a named paragraph style (HEADING_1…HEADING_6, TITLE, SUBTITLE, NORMAL_TEXT). A paragraph in Docs is defined by a trailing \\n — this is appended automatically.",inputSchema:cw,riskLevel:"write",async execute(a){try{var b;let d=a.text.endsWith("\n")?a.text:a.text+"\n",e=[(b=a.index,{insertText:{location:{index:b},text:d.endsWith("\n")?d:d+"\n"}})];if(a.named_style){let b=d.length;e.push(cn(a.index,a.index+b,a.named_style))}return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:e}}),{inserted:!0,documentId:a.document_id,index:a.index}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_insert_page_break",description:"Insert a page break at a specific index in a Google Document. Useful for separating sections onto distinct pages.",inputSchema:cx,riskLevel:"write",async execute(a){try{return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[{insertPageBreak:{location:{index:a.index}}}]}}),{inserted:!0,documentId:a.document_id,index:a.index}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_insert_table",description:"Insert a table with N rows \xd7 M columns at a specific index in a Google Document. After insertion, use docs_insert_text to populate individual cells.",inputSchema:cy,riskLevel:"write",async execute(a){try{var b,d,e;return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.index,d=a.rows,e=a.columns,{insertTable:{location:{index:b},rows:d,columns:e}})]}}),{inserted:!0,documentId:a.document_id,rows:a.rows,columns:a.columns,index:a.index}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_insert_image",description:"Insert an inline image from a public URL at a specific index in a Google Document. Optionally specify width/height in points. The image URL must be publicly accessible.",inputSchema:cz,riskLevel:"write",async execute(a){try{var b,d,e,f;let g;return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.index,d=a.image_uri,e=a.width_pt,f=a.height_pt,g=void 0!==e||void 0!==f?{width:void 0!==e?{magnitude:e,unit:"PT"}:void 0,height:void 0!==f?{magnitude:f,unit:"PT"}:void 0}:void 0,{insertInlineImage:{location:{index:b},uri:d,...void 0!==g&&{objectSize:g}}})]}}),{inserted:!0,documentId:a.document_id,index:a.index,imageUri:a.image_uri}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_format_text",description:"Apply character-level formatting to a text range in a Google Document: bold, italic, underline, strikethrough, font size, foreground color, and font family. Use docs_get to find the start/end indices of the text to format.",inputSchema:cB,riskLevel:"write",async execute(a){try{var b,d,e;if(a.end_index<=a.start_index)throw new ci("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);let f={},g=[];if(void 0!==a.bold&&(f.bold=a.bold,g.push("bold")),void 0!==a.italic&&(f.italic=a.italic,g.push("italic")),void 0!==a.underline&&(f.underline=a.underline,g.push("underline")),void 0!==a.strikethrough&&(f.strikethrough=a.strikethrough,g.push("strikethrough")),void 0!==a.font_size_pt&&(f.fontSize={magnitude:a.font_size_pt,unit:"PT"},g.push("fontSize")),void 0!==a.foreground_color&&(f.foregroundColor={color:{rgbColor:{red:a.foreground_color.red,green:a.foreground_color.green,blue:a.foreground_color.blue}}},g.push("foregroundColor")),void 0!==a.font_family&&(f.weightedFontFamily={fontFamily:a.font_family},g.push("weightedFontFamily")),0===g.length)throw new ci("docs_invalid_request","Provide at least one formatting property (bold, italic, underline, font_size_pt, etc.).");return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.start_index,d=a.end_index,e=g.join(","),{updateTextStyle:{range:{startIndex:b,endIndex:d},textStyle:f,fields:e}})]}}),{formatted:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_apply_named_style",description:"Apply a named paragraph style to a range in a Google Document: HEADING_1 through HEADING_6, TITLE, SUBTITLE, or NORMAL_TEXT. Use docs_get to find the paragraph start/end indices.",inputSchema:cC,riskLevel:"write",async execute(a){try{if(a.end_index<=a.start_index)throw new ci("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[cn(a.start_index,a.end_index,a.named_style)]}}),{applied:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index,namedStyle:a.named_style}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_batch_update",description:"Execute multiple Google Docs API update requests in a single call (escape hatch for advanced agents). Accepts any valid Docs API Request objects — insertText, deleteContentRange, updateTextStyle, updateParagraphStyle, replaceAllText, insertTable, insertInlineImage, and more. All requests are applied atomically in order. Use this when other docs_* tools do not cover your use case.",inputSchema:cD,riskLevel:"write",async execute(a){try{let b=await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:a.requests}});return{documentId:a.document_id,repliesCount:b.data.replies?.length??0,writeControl:b.data.writeControl??void 0}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}},{name:"docs_delete_content_range",description:"Delete a range of content from a Google Document body by index. The range [startIndex, endIndex) is removed — this is irreversible. Use docs_get to find the correct indices before deleting. To delete the whole document, use drive_delete_file from the Drive adapter instead.",inputSchema:cu,riskLevel:"destructive",async execute(a){try{var b,d;if(a.end_index<=a.start_index)throw new ci("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);return await c.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.start_index,d=a.end_index,{deleteContentRange:{range:{startIndex:b,endIndex:d}}})]}}),{deleted:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index}}catch(a){if(a instanceof ci)throw a;throw cj(a)}}}]},operations:[{slug:"docs_get",name:"Get document",risk:"read",requiresApproval:!1,description:"Retrieve full document structure and content."},{slug:"docs_get_text",name:"Get document text",risk:"read",requiresApproval:!1,description:"Extract plain text from a Google Doc."},{slug:"docs_create",name:"Create document",risk:"write",requiresApproval:!1,description:"Create a new Google Docs document."},{slug:"docs_insert_text",name:"Insert text",risk:"write",requiresApproval:!1,description:"Insert text at a specific index in the document."},{slug:"docs_append_text",name:"Append text",risk:"write",requiresApproval:!1,description:"Append text at the end of the document."},{slug:"docs_replace_text",name:"Replace text",risk:"write",requiresApproval:!1,description:"Find and replace text throughout the document."},{slug:"docs_insert_paragraph",name:"Insert paragraph",risk:"write",requiresApproval:!1,description:"Insert a new paragraph at a given index."},{slug:"docs_insert_page_break",name:"Insert page break",risk:"write",requiresApproval:!1,description:"Insert a page break at a given index."},{slug:"docs_insert_table",name:"Insert table",risk:"write",requiresApproval:!1,description:"Insert a table with specified rows and columns."},{slug:"docs_insert_image",name:"Insert image",risk:"write",requiresApproval:!1,description:"Insert an image from a URL into the document."},{slug:"docs_format_text",name:"Format text",risk:"write",requiresApproval:!1,description:"Apply text formatting (bold, italic, color) to a range."},{slug:"docs_apply_named_style",name:"Apply named style",risk:"write",requiresApproval:!1,description:"Apply a heading or paragraph style to a range."},{slug:"docs_batch_update",name:"Batch update",risk:"write",requiresApproval:!1,description:"Send multiple document update requests in a single API call."},{slug:"docs_delete_content_range",name:"Delete content range",risk:"destructive",requiresApproval:!0,description:"Delete a range of content from the document (irreversible)."}]},"notion-oauth":{credentialType:"notion-oauth",toolFactory:a=>au({accessToken:a}),operations:at},notion:{credentialType:"api_key",toolFactory:a=>au({accessToken:a}),operations:at},"airtable-oauth":{credentialType:"airtable-oauth",toolFactory:a=>aI({accessToken:a}),operations:aH},airtable:{credentialType:"api_key",toolFactory:a=>aI({accessToken:a}),operations:aH},firecrawl:{credentialType:"api_key",toolFactory:a=>(function(a){var b;if(!a.accessToken)throw Error("FirecrawlAdapterOptions: accessToken must be a non-empty string.");let c=(b=a.accessToken,new cE.FirecrawlClient({apiKey:b}));return[{name:"firecrawl_scrape",description:"Scrape a single web page and return its content. Supports markdown (default), raw HTML, and extracted links.",inputSchema:cH,riskLevel:"read",async execute(a){try{let b=await c.scrape(a.url,{formats:a.formats});return{url:a.url,...void 0!==b.markdown&&{markdown:b.markdown},...void 0!==b.html&&{html:b.html},...void 0!==b.links&&{links:b.links}}}catch(a){throw cG(a)}}},{name:"firecrawl_crawl_start",description:"Start an async crawl job for a website. Returns a job ID. Use firecrawl_crawl_status to poll for results.",inputSchema:cK,riskLevel:"read",async execute(a){try{let b=await c.startCrawl(a.url,{...void 0!==a.limit&&{limit:a.limit}});return{id:b.id,url:b.url}}catch(a){throw cG(a)}}},{name:"firecrawl_crawl_status",description:'Get the current status and partial results of a Firecrawl crawl job. Poll this until status is "completed", "failed", or "cancelled".',inputSchema:cL,riskLevel:"read",async execute(a){try{let b=await c.getCrawlStatus(a.id);return{id:b.id,status:b.status,total:b.total,completed:b.completed,data:(b.data??[]).map(a=>({...a.metadata?.url!==void 0&&{url:a.metadata.url},...void 0!==a.markdown&&{markdown:a.markdown},...void 0!==a.html&&{html:a.html}}))}}catch(a){throw cG(a)}}},{name:"firecrawl_map",description:"Discover all URLs on a website (sitemap-aware). Returns a list of links with optional titles and descriptions. Use the search param to filter results.",inputSchema:cI,riskLevel:"read",async execute(a){try{return{links:((await c.map(a.url,{...void 0!==a.search&&{search:a.search}})).links??[]).map(a=>({url:a.url,...void 0!==a.title&&{title:a.title},...void 0!==a.description&&{description:a.description}}))}}catch(a){throw cG(a)}}},{name:"firecrawl_search",description:"Search the web via Firecrawl and return a list of web results (URL, title, description).",inputSchema:cJ,riskLevel:"read",async execute(a){try{return{results:((await c.search(a.query,{...void 0!==a.limit&&{limit:a.limit}})).web??[]).map(a=>({url:a.url??"",...void 0!==a.title&&{title:a.title},...void 0!==a.description&&{description:a.description}}))}}catch(a){throw cG(a)}}}]})({accessToken:a}),operations:[{slug:"firecrawl_scrape",name:"Scrape page",risk:"read",requiresApproval:!1,description:"Scrape a single URL and return its content as markdown, HTML, and/or links."},{slug:"firecrawl_crawl_start",name:"Start crawl",risk:"read",requiresApproval:!1,description:"Start an async crawl job for a site. Returns a job ID to poll with firecrawl_crawl_status."},{slug:"firecrawl_crawl_status",name:"Get crawl status",risk:"read",requiresApproval:!1,description:"Poll the status and partial results of a Firecrawl crawl job by its ID."},{slug:"firecrawl_map",name:"Map site",risk:"read",requiresApproval:!1,description:"Discover all URLs on a site (sitemap-aware). Optionally filter by a search term."},{slug:"firecrawl_search",name:"Search web",risk:"read",requiresApproval:!1,description:"Search the web via Firecrawl and return structured results."}]},apify:{credentialType:"api_key",toolFactory:a=>(function(a){var b;if(!a.accessToken)throw Error("ApifyAdapterOptions: accessToken must be a non-empty string.");let d=(b=a.accessToken,new cM.ApifyClient({token:b}));return[{name:"apify_web_browse",description:"Scrape a web page or run a web search and get the content back in ONE call (synchronous — no polling). Pass a URL to scrape that page, or search terms to get the top results. Use this as the DEFAULT web tool. Consumes a small amount of Apify credits per call.",inputSchema:cO,riskLevel:"read",async execute(a){try{let b=await d.actor("apify/rag-web-browser").call({query:a.query,outputFormats:["text"],maxResults:a.maxResults??3}),c=((await d.dataset(b.defaultDatasetId).listItems({clean:!0})).items??[]).map(cQ).filter(a=>a.content);return{query:a.query,count:c.length,results:c}}catch(a){throw(0,cN.G)(a)}}},{name:"apify_get_run",description:"Retrieve metadata for an Apify actor run by its run ID. Returns status, actor ID, dataset ID, and timestamps.",inputSchema:cS,riskLevel:"read",async execute(a){try{let b=await d.run(a.runId).get();if(!b){let{ApifyApiError:b}=await Promise.resolve().then(c.bind(c,99740));throw new b("apify_not_found",`Run ${a.runId} not found`,404)}return{id:b.id,actId:b.actId,status:b.status,startedAt:b.startedAt?b.startedAt.toISOString():null,finishedAt:b.finishedAt?b.finishedAt.toISOString():null,defaultDatasetId:b.defaultDatasetId,defaultKeyValueStoreId:b.defaultKeyValueStoreId}}catch(a){throw(0,cN.G)(a)}}},{name:"apify_list_datasets",description:"List datasets in the user's Apify account. Returns dataset IDs and names needed for apify_get_dataset_items.",inputSchema:cT,riskLevel:"read",async execute(a){try{let b=await d.datasets().list({limit:a.limit??100,offset:a.offset??0});return{datasets:b.items.map(a=>({id:a.id,name:a.name??null,itemCount:a.itemCount??0,createdAt:a.createdAt.toISOString(),modifiedAt:a.modifiedAt.toISOString()})),total:b.total,count:b.count,offset:b.offset}}catch(a){throw(0,cN.G)(a)}}},{name:"apify_get_dataset_items",description:"Retrieve items from an Apify dataset. Use the datasetId returned by apify_run_actor or from apify_list_datasets. Supports limit/offset pagination (max 1000 items per call).",inputSchema:cU,riskLevel:"read",async execute(a){try{let b=await d.dataset(a.datasetId).listItems({limit:a.limit??100,offset:a.offset??0});return{items:b.items,total:b.total,count:b.count,offset:b.offset}}catch(a){throw(0,cN.G)(a)}}},{name:"apify_run_actor",description:"Start an Apify actor run and wait for it to finish (blocking). Returns the run ID, output dataset ID, and final status. This tool consumes Apify platform credits — use apify_get_dataset_items to retrieve results after the run succeeds.",inputSchema:cR,riskLevel:"write",async execute(a){try{let b=await d.actor(a.actorId).call(a.input);return{runId:b.id,datasetId:b.defaultDatasetId,status:b.status}}catch(a){throw(0,cN.G)(a)}}}]})({accessToken:a}),operations:[{slug:"apify_run_actor",name:"Run actor",risk:"write",requiresApproval:!1,description:"Start an Apify actor run and wait for it to finish. Consumes Apify platform credits."},{slug:"apify_web_browse",name:"Web browse",risk:"read",requiresApproval:!1,description:"Scrape a web page or run a web search and get the content back in one synchronous call (no polling). Consumes a small amount of Apify credits."},{slug:"apify_get_run",name:"Get run",risk:"read",requiresApproval:!1,description:"Retrieve metadata for an Apify actor run by its run ID."},{slug:"apify_list_datasets",name:"List datasets",risk:"read",requiresApproval:!1,description:"List datasets in the user's Apify account with optional pagination."},{slug:"apify_get_dataset_items",name:"Get dataset items",risk:"read",requiresApproval:!1,description:"Retrieve items from an Apify dataset. Supports limit and offset pagination."}]},tavily:{credentialType:"api_key",toolFactory:a=>(function(a){var b;let c;if(!a.accessToken)throw Error("TavilyAdapterOptions: accessToken must be a non-empty string.");let d=(b=a.accessToken,c=(0,cV.tavily)({apiKey:b}),{search:(a,b)=>c.search(a,b),extract:(a,b)=>c.extract(a,b),crawl:(a,b)=>c.crawl(a,b)});return[{name:"tavily_search",description:'Search the web using Tavily. Returns ranked results with titles, URLs, content snippets, and relevance scores. Use topic="news" for current events.',inputSchema:cY,riskLevel:"read",async execute(a,b){try{let b=await d.search(a.query,{searchDepth:a.searchDepth??"basic",maxResults:a.maxResults??5,includeImages:a.includeImages??!1,topic:a.topic??"general"});return{query:b.query,answer:b.answer,results:(b.results??[]).map(a=>({title:a.title,url:a.url,content:a.content,score:a.score,publishedDate:a.publishedDate})),images:(b.images??[]).map(a=>({url:a.url,description:a.description})),responseTime:b.responseTime}}catch(a){throw cX(a)}}},{name:"tavily_extract",description:"Extract the full text content from one or more URLs (max 20). Returns the raw content of each page and a list of URLs that failed to extract.",inputSchema:cZ,riskLevel:"read",async execute(a,b){try{let b=await d.extract(a.urls,{extractDepth:a.extractDepth??"basic"});return{results:(b.results??[]).map(a=>({url:a.url,title:a.title,rawContent:a.rawContent})),failedResults:(b.failedResults??[]).map(a=>({url:a.url,error:a.error})),responseTime:b.responseTime}}catch(a){throw cX(a)}}},{name:"tavily_crawl",description:"Crawl from a seed URL and return scraped content for all reachable pages up to a depth and page limit. Useful for comprehensive site content extraction.",inputSchema:c$,riskLevel:"read",async execute(a,b){try{let b=await d.crawl(a.url,{maxDepth:a.maxDepth??1,limit:a.limit??10});return{baseUrl:b.baseUrl,results:(b.results??[]).map(a=>({url:a.url,rawContent:a.rawContent})),responseTime:b.responseTime}}catch(a){throw cX(a)}}}]})({accessToken:a}),operations:[{slug:"tavily_search",name:"Web search",risk:"read",requiresApproval:!1,description:"Search the web using Tavily. Returns ranked results with titles, URLs, and content snippets."},{slug:"tavily_extract",name:"Extract content",risk:"read",requiresApproval:!1,description:"Extract the full text content from one or more URLs (max 20)."},{slug:"tavily_crawl",name:"Crawl site",risk:"read",requiresApproval:!1,description:"Crawl from a seed URL and return scraped content for all reachable pages up to a depth and limit."}]},poyo:{credentialType:"api_key",toolFactory:a=>(function(a){if(!a.accessToken)throw Error("PoyoAdapterOptions: accessToken must be a non-empty string.");return[function(a,b=c2){return{name:"poyo_generate_image",description:"Generate an image from a text prompt using Poyo. Submits the job, waits for it to finish, and returns the resulting image URL(s). Use `model` to pick a Poyo image model (default gpt-4o-image) and `size` for the aspect ratio.",inputSchema:c3,riskLevel:"write",async execute(c,d){let e=c.model??"gpt-4o-image";try{let d=await a.submit(e,{prompt:c.prompt,size:c.size??"1:1"});for(let c=0;c<b.maxAttempts;c++){let c=await a.status(d);if("finished"===c.status)return{taskId:d,status:"finished",images:c.files.map(a=>a.url),model:e};if("failed"===c.status)throw new c_("poyo_generation_failed",`Poyo generation failed for task ${d}.`);await c4(b.intervalMs)}return{taskId:d,status:"running",images:[],model:e,note:`Still processing after ${b.maxAttempts} checks; the task can be polled again later with this task id.`}}catch(a){throw a instanceof c_?a:a instanceof Error?new c_("poyo_unknown",a.message):new c_("poyo_unknown",String(a))}}}}(function(a,b={}){let c=b.baseUrl??"https://api.poyo.ai",d=b.fetchImpl??fetch,e={Authorization:`Bearer ${a}`};return{async submit(a,b){let f=await d(`${c}/api/generate/submit`,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({model:a,input:b})});if(!f.ok)throw c0(f.status,await c1(f));let g=await f.json(),h=g?.data?.task_id??g?.task_id;if("string"!=typeof h||0===h.length)throw new c_("poyo_unknown","Poyo submit response did not include a task_id.");return h},async status(a){let b=await d(`${c}/api/generate/status/${encodeURIComponent(a)}`,{method:"GET",headers:{...e}});if(!b.ok)throw c0(b.status,await c1(b));let f=await b.json(),g=f?.data??{},h=Array.isArray(g.files)?g.files.filter(a=>"string"==typeof a?.file_url).map(a=>({url:a.file_url,type:"string"==typeof a.file_type?a.file_type:"image"})):[];return{status:"string"==typeof g.status?g.status:"unknown",progress:"number"==typeof g.progress?g.progress:0,files:h}}}}(a.accessToken))]})({accessToken:a}),operations:[{slug:"poyo_generate_image",name:"Generate image",risk:"write",requiresApproval:!1,description:"Generate an image from a text prompt using Poyo. Submits the job, waits for it to finish, and returns the resulting image URL(s)."}]}};async function c6(a,b){var c;let d=await b.select({subAgentId:m.Qj.subAgentId,instructions:m.Qj.instructions,agentName:m.X6.name,agentSlug:m.X6.slug,agentRole:m.X6.role,agentActive:m.X6.active,agentPersonality:m.X6.personality,agentModel:m.X6.model}).from(m.Qj).innerJoin(m.X6,(0,m.eq)(m.Qj.subAgentId,m.X6.id)).where((0,m.Uo)((0,m.eq)(m.Qj.orchestratorId,a),(0,m.eq)(m.X6.active,!0)));if(0===d.length)return"";let e=(await b.select({role:m.X6.role,orchestratorMode:m.X6.orchestratorMode}).from(m.X6).where((0,m.eq)(m.X6.id,a)).limit(1))[0];if(!e)return"";let f=d.map(a=>({role:a.agentRole})),g=(c={role:e.role,orchestratorMode:e.orchestratorMode},"orchestrator"!==c.role?"worker":"router"===c.orchestratorMode?"router":"planner"===c.orchestratorMode?"planner":0===f.length?"worker":f.some(a=>"orchestrator"===a.role)?"router":"planner"),h=d.map(a=>a.subAgentId),i=await Promise.all(h.map(a=>b.select({agentId:m.$m.agentId,skillName:m.eK.name,skillSlug:m.eK.slug,skillDescription:m.eK.description}).from(m.$m).innerJoin(m.eK,(0,m.eq)(m.$m.skillId,m.eK.id)).where((0,m.eq)(m.$m.agentId,a)))),j=new Map;for(let a of i)for(let b of a){let a=j.get(b.agentId)??[];a.push({name:b.skillName,desc:b.skillDescription}),j.set(b.agentId,a)}let k=await Promise.all(h.map(a=>b.select({agentId:m.XT.agentId,slug:m.tK.slug,enabledOperations:m.XT.enabledOperations}).from(m.XT).innerJoin(m.tK,(0,m.eq)(m.tK.id,m.XT.connectorId)).where((0,m.eq)(m.XT.agentId,a)))),l=new Map;for(let a of k)for(let b of a){let a=c5[b.slug];if(!a)continue;let c=a.operations.map(a=>a.slug),d=null===b.enabledOperations?c:c.filter(a=>b.enabledOperations.includes(a));if(0===d.length)continue;let e=l.get(b.agentId)??[];e.push({slug:b.slug,toolNames:d}),l.set(b.agentId,e)}let n=await Promise.all(h.map(a=>b.select({agentId:m.oS.agentId,serverSlug:m.h_.slug,enabledTools:m.oS.enabledTools,availableTools:m.h_.availableTools,serverActive:m.h_.active}).from(m.oS).innerJoin(m.h_,(0,m.eq)(m.h_.id,m.oS.mcpServerId)).where((0,m.eq)(m.oS.agentId,a)))),o=new Map;for(let a of n)for(let b of a){if(!1===b.serverActive)continue;let a=b.serverSlug.replace(/-/g,"_"),c=Array.isArray(b.availableTools)?b.availableTools.map(a=>a&&"string"==typeof a.name?a.name:null).filter(a=>null!==a):[];if(0===c.length)continue;let d=Array.isArray(b.enabledTools)?new Set(b.enabledTools.filter(a=>"string"==typeof a)):null,e=null===d?c:c.filter(a=>d.has(a));if(0===e.length)continue;let f=e.map(b=>`${a}__${b}`),g=o.get(b.agentId)??[];g.push({slug:b.serverSlug,toolNames:f}),o.set(b.agentId,g)}let p=[];for(let a of(p.push("## Your team\n"),p.push("You orchestrate the agents below. You have TWO ways to delegate — choose the one that fits the request:\n"),p.push("- **`assign_<agent>` — one delegation, in-line.** Hand the request (or a single step of it) to ONE agent and get its result back before continuing. Use this for a single delegation, or when the next step depends on this one’s result (reactive / sequential work). Only one assignment per turn; after the agent returns, either finish with `return_result` or assign the next step. Do NOT delegate again unless the request needs another step."),p.push("- **`create_task` — parallel fan-out.** Create several INDEPENDENT tasks at once, each `assigned_to` an agent by its handle. They run concurrently in the background and their results are compiled and delivered automatically once all finish. Use this when the pieces of work do not depend on each other and can run in parallel. Use `depends_on` to order tasks that must run in sequence within the board. After creating the tasks, end your turn with a brief `return_result` acknowledgment — the task board runs them, so do NOT call `list_tasks` to wait (only use it to fetch a task ID for a `depends_on` reference).\n"),p.push('⚠️ THE FINAL SUMMARY TO THE USER IS AUTOMATIC — NEVER MAKE IT A TASK. Once the work tasks finish, the system composes a short summary of the whole run and sends it to the user on their original channel by itself. So even when the user says "puis fais une synth\xe8se et envoie-la moi" / "then summarize and send it to me", that final summarize-and-send step is ALREADY handled — do NOT turn it into a task and do NOT add a `depends_on` "synth\xe8se"/"summary"/"→ Telegram" task. Creating one produces a DUPLICATE and an extra useless run. Create ONLY the real work tasks, then `return_result`. If the user wants a long deliverable (a file, an Obsidian note, an email, an HTML page), make a work task that PRODUCES that artifact — but the chat reply itself is never a task.\n'),p.push("Pick ONE style per request — do not mix them in the same job. "+("router"===g?"Default lean: this team includes sub-orchestrators, so in-line `assign_*` delegation is usually the right call — reach for `create_task` only when you have genuinely independent work to run in parallel.":"Default lean: this team is independent workers, so `create_task` parallel fan-out is usually the right call for multi-part work — use `assign_*` when a single agent can handle the whole request or when steps depend on each other.")+"\n"),p.push("Your agents:"),d)){let{subAgentId:b,agentName:c,agentSlug:d,agentRole:e,instructions:f,agentPersonality:g,agentModel:h}=a,i=d.replace(/-/g,"_"),k=function(a,b=240){if(!a)return"";let c=(a.split(/\n\s*\n|\n#/)[0]??"").replace(/[*_`#>-]/g," ").replace(/\s+/g," ").trim();if(!c)return"";if(c.length<=b)return c;let d=c.slice(0,b),e=Math.max(d.lastIndexOf(". "),d.lastIndexOf("! "));return(e>60?d.slice(0,e+1):d.trimEnd()+"…").trim()}(g),m=k?`
17
- Purpose: ${k}`:"",n=(0,v.FM)(h??"")?"\n LLM: can see images (vision) — route image tasks here":"",q=j.get(b)??[],r=q.length>0?`
18
- Skills (what it can do): ${q.map(a=>{let b=a.desc?a.desc.replace(/\s+/g," ").trim():"",c=b.length>140?`${b.slice(0,139).trimEnd()}…`:b;return c?`${a.name} ${c}`:a.name}).join("; ")}`:"",s=function(a){let b=l.get(a),c=o.get(a),d=[];return(b&&d.push(...b.map(a=>a.slug)),c&&d.push(...c.map(a=>a.slug)),0===d.length)?"":`
16
+ `+g,j=bj({to:a.to,subject:f,body:i,cc:a.cc}),k=await d.users.messages.send({userId:"me",requestBody:{raw:j}});return{messageId:k.data.id??"",threadId:k.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_modify_labels",description:"Add or remove labels on a Gmail message. System labels: INBOX, UNREAD, STARRED, IMPORTANT, TRASH, SPAM. Use to mark as read (remove UNREAD), star, archive (remove INBOX), etc.",inputSchema:bq,riskLevel:"write",async execute(a){try{if(!a.add_labels?.length&&!a.remove_labels?.length)throw new bb("gmail_validation_error","Provide at least one of add_labels or remove_labels.");let b=await d.users.messages.modify({userId:"me",id:a.message_id,requestBody:{addLabelIds:a.add_labels??[],removeLabelIds:a.remove_labels??[]}});return{messageId:b.data.id??"",labelIds:b.data.labelIds??[]}}catch(a){throw bc(a)}}},{name:"gmail_trash_message",description:"Move a Gmail message to the Trash folder. Recoverable for 30 days. Prefer this over permanent delete.",inputSchema:br,riskLevel:"write",async execute(a){try{let b=await d.users.messages.trash({userId:"me",id:a.message_id});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_untrash_message",description:"Restore a Gmail message from the Trash folder.",inputSchema:bs,riskLevel:"write",async execute(a){try{let b=await d.users.messages.untrash({userId:"me",id:a.message_id});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_modify_thread_labels",description:"Add or remove labels on all messages in a Gmail thread at once. Use to archive a thread (remove INBOX), mark all as read (remove UNREAD), etc.",inputSchema:bw,riskLevel:"write",async execute(a){try{return{threadId:(await d.users.threads.modify({userId:"me",id:a.thread_id,requestBody:{addLabelIds:a.add_labels??[],removeLabelIds:a.remove_labels??[]}})).data.id??""}}catch(a){throw bc(a)}}},{name:"gmail_trash_thread",description:"Move an entire Gmail conversation thread to the Trash folder. Recoverable for 30 days.",inputSchema:bx,riskLevel:"write",async execute(a){try{return{threadId:(await d.users.threads.trash({userId:"me",id:a.thread_id})).data.id??""}}catch(a){throw bc(a)}}},{name:"gmail_create_label",description:"Create a new Gmail user label. Use '/' in the name to nest labels, e.g. 'Projects/Nodal-Agents'.",inputSchema:bA,riskLevel:"write",async execute(a){try{let b=await d.users.labels.create({userId:"me",requestBody:{name:a.name,labelListVisibility:a.label_list_visibility??"labelShow",messageListVisibility:a.message_list_visibility??"show"}});return{id:b.data.id??"",name:b.data.name??""}}catch(a){throw bc(a)}}},{name:"gmail_update_label",description:"Update an existing Gmail user label — rename it or change its visibility.",inputSchema:bB,riskLevel:"write",async execute(a){try{let b={};void 0!==a.name&&(b.name=a.name),void 0!==a.label_list_visibility&&(b.labelListVisibility=a.label_list_visibility),void 0!==a.message_list_visibility&&(b.messageListVisibility=a.message_list_visibility);let c=await d.users.labels.patch({userId:"me",id:a.label_id,requestBody:b});return{id:c.data.id??"",name:c.data.name??""}}catch(a){throw bc(a)}}},{name:"gmail_create_draft",description:"Create a draft email in Gmail (not sent). Use reply_to_message_id to create a reply draft in-thread with correct threading headers.",inputSchema:bF,riskLevel:"write",async execute(a){try{let b,c,e,f=a.subject;if(a.reply_to_message_id){let g=(await d.users.messages.get({userId:"me",id:a.reply_to_message_id,format:"metadata",metadataHeaders:["Subject","Message-ID","Message-Id","References"]})).data;b=g.threadId??void 0;let h=bg(g.payload??void 0),i=h.subject??"";i&&!f.toLowerCase().startsWith("re:")&&(f=i.toLowerCase().startsWith("re:")?i:`Re: ${i}`);let j=h["message-id"]??"",k=h.references??"";c=j||void 0,e=j?k?`${k} ${j}`:j:k||void 0}let g={message:{raw:bj({to:a.to,subject:f,body:a.body,cc:a.cc,bcc:a.bcc,inReplyTo:c,references:e,attachments:a.attachments}),...b&&{threadId:b}}},h=await d.users.drafts.create({userId:"me",requestBody:g});return{draftId:h.data.id??"",messageId:h.data.message?.id??""}}catch(a){throw bc(a)}}},{name:"gmail_update_draft",description:"Overwrite an existing Gmail draft with new content. Use this to revise a draft before sending.",inputSchema:bG,riskLevel:"write",async execute(a){try{let b=bj({to:a.to,subject:a.subject,body:a.body,cc:a.cc,bcc:a.bcc,attachments:a.attachments}),c=await d.users.drafts.update({userId:"me",id:a.draft_id,requestBody:{message:{raw:b}}});return{draftId:c.data.id??a.draft_id,messageId:c.data.message?.id??""}}catch(a){throw bc(a)}}},{name:"gmail_send_draft",description:"Send an existing Gmail draft. The draft is dispatched as an email and can no longer be edited.",inputSchema:bH,riskLevel:"write",async execute(a){try{let b=await d.users.drafts.send({userId:"me",requestBody:{id:a.draft_id}});return{messageId:b.data.id??"",threadId:b.data.threadId??""}}catch(a){throw bc(a)}}},{name:"gmail_delete_message",description:"Permanently delete a Gmail message. This is irreversible — the message cannot be recovered. Consider gmail_trash_message for recoverable deletion.",inputSchema:bt,riskLevel:"destructive",async execute(a){try{return await d.users.messages.delete({userId:"me",id:a.message_id}),{deleted:!0,messageId:a.message_id}}catch(a){throw bc(a)}}},{name:"gmail_delete_label",description:"Permanently delete a Gmail user label. Cannot delete system labels (INBOX, SENT, etc.). Messages with this label are NOT deleted — they simply lose the label.",inputSchema:bC,riskLevel:"destructive",async execute(a){try{return await d.users.labels.delete({userId:"me",id:a.label_id}),{deleted:!0,labelId:a.label_id}}catch(a){throw bc(a)}}},{name:"gmail_delete_draft",description:"Permanently delete a Gmail draft. This is irreversible.",inputSchema:bI,riskLevel:"destructive",async execute(a){try{return await d.users.drafts.delete({userId:"me",id:a.draft_id}),{deleted:!0,draftId:a.draft_id}}catch(a){throw bc(a)}}}]}class bM extends Error{constructor(a,b,c){super(b),this.name="GoogleCalendarAdapterError",this.code=a,this.status=c}}function bN(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="gcal_validation_error";break;case 401:a="gcal_unauthorized";break;case 403:a="gcal_forbidden";break;case 404:a="gcal_event_not_found";break;case 429:a="gcal_quota_exceeded";break;case 503:a="gcal_service_unavailable";break;default:a="gcal_unknown"}return new bM(a,c,b)}}return a instanceof bM?a:a instanceof Error?new bM("gcal_unknown",a.message):new bM("gcal_unknown",String(a))}function bO(a){let b=a.start?.dateTime??a.start?.date??"",c=a.end?.dateTime??a.end?.date??"";return{id:a.id??"",summary:a.summary??"",description:a.description??"",location:a.location??"",status:a.status??"",start:b,end:c,allDay:!!a.start?.date&&!a.start?.dateTime,htmlLink:a.htmlLink??"",attendees:(a.attendees??[]).map(a=>a.email??"").filter(a=>""!==a),organizer:a.organizer?.email??""}}let bP=g.Yj().optional().describe("Calendar ID (from gcal_list_calendars). Defaults to 'primary'."),bQ=g.Ik({calendar_id:bP,time_min:g.Yj().optional().describe("ISO 8601 lower bound (inclusive). Defaults to now — i.e. upcoming events."),time_max:g.Yj().optional().describe("ISO 8601 upper bound (exclusive)."),query:g.Yj().optional().describe("Free-text search over event fields."),max_results:g.ai().int().min(1).max(250).optional().describe("Max events to return (default 25).")}),bR=g.Ik({calendar_id:bP,event_id:g.Yj().describe("Event ID (from gcal_list_events).")}),bS=g.Ik({calendar_id:bP,summary:g.Yj().describe("Event title."),start:g.Yj().describe("Start time. ISO 8601 datetime (e.g. 2026-07-01T14:00:00+02:00) or YYYY-MM-DD for an all-day event."),end:g.Yj().describe("End time. ISO 8601 datetime or YYYY-MM-DD (exclusive) for an all-day event."),description:g.Yj().optional().describe("Event description/notes."),location:g.Yj().optional().describe("Event location."),attendees:g.YO(g.Yj()).optional().describe("Attendee email addresses to invite."),time_zone:g.Yj().optional().describe("IANA time zone for the times (e.g. 'Europe/Paris').")});function bT(a,b){return/^\d{4}-\d{2}-\d{2}$/.test(a)?{date:a}:b?{dateTime:a,timeZone:b}:{dateTime:a}}let bU=g.Ik({calendar_id:bP,event_id:g.Yj().describe("Event ID to update (from gcal_list_events)."),summary:g.Yj().optional().describe("New event title."),start:g.Yj().optional().describe("New start (ISO 8601 datetime or YYYY-MM-DD)."),end:g.Yj().optional().describe("New end (ISO 8601 datetime or YYYY-MM-DD)."),description:g.Yj().optional().describe("New description."),location:g.Yj().optional().describe("New location."),attendees:g.YO(g.Yj()).optional().describe("Replace the attendee email list."),time_zone:g.Yj().optional().describe("IANA time zone for the times.")}),bV=g.Ik({calendar_id:bP,event_id:g.Yj().describe("Event ID to permanently delete.")}),bW=g.Ik({}),bX=g.Ik({time_min:g.Yj().describe("ISO 8601 start of the window to check."),time_max:g.Yj().describe("ISO 8601 end of the window to check."),calendar_ids:g.YO(g.Yj()).optional().describe("Calendar IDs to check (default ['primary']).")});function bY(a){var b;let c,d=(b="getAccessToken"in a?a.getAccessToken:async()=>a.accessToken,(c=new aM.google.auth.OAuth2).refreshHandler=async()=>({access_token:await b(),expiry_date:Date.now()-1}),aM.google.calendar({version:"v3",auth:c}));return[{name:"gcal_list_calendars",description:"List the calendars the user can access. Returns calendar IDs (use the id with the other gcal_* tools; 'primary' is the user's main calendar).",inputSchema:bW,riskLevel:"read",async execute(){try{let a=((await d.calendarList.list()).data.items??[]).map(a=>({id:a.id??"",summary:a.summary??"",description:a.description??"",primary:!!a.primary,accessRole:a.accessRole??"",timeZone:a.timeZone??""}));return{total:a.length,calendars:a}}catch(a){throw bN(a)}}},{name:"gcal_list_events",description:"List calendar events in a time range. Defaults to UPCOMING events from now. Use time_min/time_max (ISO 8601) to bound, query to text-search. Returns event IDs.",inputSchema:bQ,riskLevel:"read",async execute(a){try{let b=((await d.events.list({calendarId:a.calendar_id??"primary",timeMin:a.time_min??new Date().toISOString(),timeMax:a.time_max,q:a.query,singleEvents:!0,orderBy:"startTime",maxResults:a.max_results??25})).data.items??[]).map(bO);return{total:b.length,events:b}}catch(a){throw bN(a)}}},{name:"gcal_get_event",description:"Get the full details of a single calendar event by ID.",inputSchema:bR,riskLevel:"read",async execute(a){try{let b=await d.events.get({calendarId:a.calendar_id??"primary",eventId:a.event_id});return bO(b.data)}catch(a){throw bN(a)}}},{name:"gcal_find_free_slots",description:"Query busy intervals across one or more calendars in a time window, so you can find free slots for scheduling. Returns the BUSY ranges per calendar — gaps are free.",inputSchema:bX,riskLevel:"read",async execute(a){try{let b=a.calendar_ids??["primary"],c=await d.freebusy.query({requestBody:{timeMin:a.time_min,timeMax:a.time_max,items:b.map(a=>({id:a}))}}),e={},f=c.data.calendars??{};for(let[a,b]of Object.entries(f))e[a]=(b.busy??[]).map(a=>({start:a.start??"",end:a.end??""}));return{timeMin:a.time_min,timeMax:a.time_max,busy:e}}catch(a){throw bN(a)}}},{name:"gcal_create_event",description:"Create a new calendar event. Use ISO 8601 datetimes for timed events, or YYYY-MM-DD for all-day events. Optionally invite attendees by email.",inputSchema:bS,riskLevel:"write",async execute(a){try{let b=await d.events.insert({calendarId:a.calendar_id??"primary",requestBody:{summary:a.summary,description:a.description,location:a.location,start:bT(a.start,a.time_zone),end:bT(a.end,a.time_zone),attendees:a.attendees?.map(a=>({email:a}))}});return{id:b.data.id??"",htmlLink:b.data.htmlLink??"",summary:b.data.summary??""}}catch(a){throw bN(a)}}},{name:"gcal_update_event",description:"Update an existing calendar event. Only the fields you provide are changed (patch semantics).",inputSchema:bU,riskLevel:"write",async execute(a){try{let b={};void 0!==a.summary&&(b.summary=a.summary),void 0!==a.description&&(b.description=a.description),void 0!==a.location&&(b.location=a.location),void 0!==a.start&&(b.start=bT(a.start,a.time_zone)),void 0!==a.end&&(b.end=bT(a.end,a.time_zone)),void 0!==a.attendees&&(b.attendees=a.attendees.map(a=>({email:a})));let c=await d.events.patch({calendarId:a.calendar_id??"primary",eventId:a.event_id,requestBody:b});return{id:c.data.id??"",htmlLink:c.data.htmlLink??"",summary:c.data.summary??""}}catch(a){throw bN(a)}}},{name:"gcal_delete_event",description:"Permanently delete a calendar event. This cannot be undone.",inputSchema:bV,riskLevel:"destructive",async execute(a){try{return await d.events.delete({calendarId:a.calendar_id??"primary",eventId:a.event_id}),{deleted:!0,eventId:a.event_id}}catch(a){throw bN(a)}}}]}class bZ extends Error{constructor(a,b,c){super(b),this.name="SheetsAdapterError",this.code=a,this.status=c}}function b$(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:{let b=c.toLowerCase();a=b.includes("range")||b.includes("a1 notation")||b.includes("unable to parse")?"sheets_invalid_range":"sheets_validation_error";break}case 401:a="sheets_unauthorized";break;case 403:a="sheets_forbidden";break;case 404:a="sheets_not_found";break;case 429:a="sheets_rate_limited";break;case 503:a="sheets_service_unavailable";break;default:a="sheets_unknown"}return new bZ(a,c,b)}}return a instanceof bZ?a:a instanceof Error?new bZ("sheets_unknown",a.message):new bZ("sheets_unknown",String(a))}function b_(a){return null==a?"":"number"==typeof a||"boolean"==typeof a||"string"==typeof a?a:String(a)}function b0(a){return a.map(b_)}function b1(a){return a?a.map(b0):[]}function b2(a){let b,c,d,e=a.trim();if(!e)throw new bZ("sheets_invalid_range","Empty range string");let f=e.indexOf("!");if(-1!==f){let a=e.slice(0,f);c=e.slice(f+1),a.startsWith("'")&&a.endsWith("'")&&(a=a.slice(1,-1).replace(/''/g,"'")),b=a}else c=e,b=void 0;if(!c||!/^[A-Za-z0-9:$]+$/.test(c))throw new bZ("sheets_invalid_range",`Invalid cell range portion: '${c}' in '${a}'`);if(void 0!==b){let a=/[\s!'"\\]/.test(b)?`'${b.replace(/'/g,"''")}'`:b;d=`${a}!${c}`}else d=c;return{sheetName:b,cellRange:c,canonical:d}}let b3=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range, e.g. 'Sheet1!A1:D10' or 'A:A' for a full column."),value_render_option:g.k5(["FORMATTED_VALUE","UNFORMATTED_VALUE","FORMULA"]).optional().describe("How values are rendered. FORMATTED_VALUE (default) returns display strings. UNFORMATTED_VALUE returns raw numbers/booleans. FORMULA returns formula strings.")}),b4=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_name:g.Yj().optional().describe("Sheet tab name (default: first sheet).")}),b5=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),ranges:g.YO(g.Yj()).min(1).max(50).describe("Array of A1-notation ranges to read in a single API call (max 50)."),value_render_option:g.k5(["FORMATTED_VALUE","UNFORMATTED_VALUE","FORMULA"]).optional().describe("How values are rendered (default FORMATTED_VALUE).")}),b6=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range. The top-left cell anchors the write, e.g. 'Sheet1!A1'."),values:g.YO(g.YO(g.L5())).describe("2D array of values to write. Example: [['Name','Score'],['Alice',95]]."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas like a human typing (default).")}),b7=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("Sheet name or range that identifies where to append, e.g. 'Sheet1' or 'Sheet1!A:Z'. Sheets auto-detects the last row with data and appends after it."),values:g.YO(g.YO(g.L5())).describe("2D array of rows to append. For a single row: [['Name','Score']]. For multiple: [['Alice',95],['Bob',87]]."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas (default).")}),b8=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),range:g.Yj().describe("A1-notation range to clear, e.g. 'Sheet1!A2:Z100'. Formatting is preserved.")}),b9=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),updates:g.YO(g.Ik({range:g.Yj().describe("A1-notation range, e.g. 'Sheet1!A1'."),values:g.YO(g.YO(g.L5())).describe("2D array of values to write.")})).min(1).max(50).describe("Array of range+values pairs to write in a single API call (max 50)."),value_input_option:g.k5(["RAW","USER_ENTERED"]).optional().describe("RAW stores strings as-is; USER_ENTERED parses numbers/dates/formulas (default).")}),ca=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_name:g.Yj().optional().describe("Sheet tab name (default: first sheet)."),column:g.Yj().describe("Header name of the column to search (from row 1)."),equals:g.Yj().optional().describe("Return rows where the column value exactly equals this string."),contains:g.Yj().optional().describe("Return rows where the column value contains this substring (case-sensitive)."),limit:g.ai().int().min(1).max(1e3).optional().describe("Max matching rows to return (default 100, max 1000).")}),cb=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit).")}),cc=g.Ik({title:g.Yj().describe("Title for the new spreadsheet."),sheet_title:g.Yj().optional().describe("Title for the first sheet tab (default: 'Sheet1').")}),cd=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),title:g.Yj().describe("Title for the new sheet tab."),index:g.ai().int().min(0).optional().describe("Zero-based position to insert the sheet (default: appended at end).")}),ce=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID (not the tab name). Get it from sheets_get_metadata.")}),cf=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),source_sheet_id:g.ai().int().describe("Numeric ID of the sheet to duplicate. Get it from sheets_get_metadata."),new_sheet_name:g.Yj().optional().describe('Name for the duplicated sheet (defaults to "Copy of <original>").'),insert_sheet_index:g.ai().int().min(0).optional().describe("Zero-based position to insert the duplicate (default: appended at end).")}),cg=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),new_title:g.Yj().describe("New tab name for the sheet.")}),ch=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive)."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive). E.g. rows 0–1 → endRowIndex=1."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive). E.g. columns 0–3 → endColumnIndex=3."),bold:g.zM().optional().describe("Set bold text."),italic:g.zM().optional().describe("Set italic text."),font_size:g.ai().int().min(1).optional().describe("Font size in points."),background_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Background fill color (RGB, each channel 0–1)."),foreground_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Text foreground color (RGB, each channel 0–1)."),number_format:g.Ik({type:g.k5(["TEXT","NUMBER","PERCENT","CURRENCY","DATE","TIME","DATE_TIME","SCIENTIFIC"]).describe("Number format type."),pattern:g.Yj().optional().describe("Optional format pattern, e.g. '#,##0.00' for currency.")}).optional().describe("Number format to apply."),horizontal_alignment:g.k5(["LEFT","CENTER","RIGHT"]).optional().describe("Horizontal text alignment.")}),ci=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive). E.g. columns 0–3 → endColumnIndex=3."),pixel_size:g.ai().int().min(0).optional().describe("Column width in pixels. Omit to auto-resize to fit content.")}),cj=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),frozen_row_count:g.ai().int().min(0).optional().describe("Number of rows to freeze at the top (0 to unfreeze, default 0)."),frozen_column_count:g.ai().int().min(0).optional().describe("Number of columns to freeze at the left (0 to unfreeze, default 0).")}),ck=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive). Usually 0 for the header row."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive)."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive).")}),cl=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata.")}),cm=g.Ik({dimension_index:g.ai().int().min(0).describe("Zero-based column index to sort by."),sort_order:g.k5(["ASCENDING","DESCENDING"]).describe("Sort direction: 'ASCENDING' or 'DESCENDING'.")}),cn=g.Ik({spreadsheet_id:g.Yj().describe("The spreadsheet ID from the URL (between /d/ and /edit)."),sheet_id:g.ai().int().describe("Numeric sheet ID. Get it from sheets_get_metadata."),start_row_index:g.ai().int().min(0).describe("Zero-based start row index (inclusive). Set to 1 to exclude the header row."),end_row_index:g.ai().int().min(1).describe("Zero-based end row index (exclusive)."),start_column_index:g.ai().int().min(0).describe("Zero-based start column index (inclusive)."),end_column_index:g.ai().int().min(1).describe("Zero-based end column index (exclusive)."),sort_specs:g.YO(cm).min(1).describe("Array of sort specs (primary, secondary, ...). Each: { dimension_index, sort_order }. Example: [{ dimension_index: 2, sort_order: 'DESCENDING' }].")});function co(a){var b;let c,d=(b="getAccessToken"in a?a.getAccessToken:async()=>a.accessToken,(c=new aM.google.auth.OAuth2).refreshHandler=async()=>({access_token:await b(),expiry_date:Date.now()-1}),aM.google.sheets({version:"v4",auth:c}));return[{name:"sheets_read_range",description:"Read a specific A1-notation range from a Google Sheet. Returns a 2D array of cell values. Capped at 10,000 rows — use a smaller range if exceeded.",inputSchema:b3,riskLevel:"read",async execute(a){try{b2(a.range);let b=await d.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:a.range,valueRenderOption:a.value_render_option??"FORMATTED_VALUE"}),c=b.data.values??[];if(c.length>1e4)throw new bZ("sheets_range_too_large",`Range returned ${c.length} rows which exceeds the 10000-row cap. Use a smaller range.`);let e=b1(c),f=e.reduce((a,b)=>Math.max(a,b.length),0);return{range:b.data.range??a.range,rows:e.length,cols:f,values:e}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_read_all",description:"Read all values from a sheet tab. Returns the full 2D array. Capped at 10,000 rows — use sheets_read_range for partial reads on large sheets.",inputSchema:b4,riskLevel:"read",async execute(a){try{let b=a.sheet_name;if(!b){let c=await d.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.title"});b=c.data.sheets?.[0]?.properties?.title??"Sheet1"}let c=`'${b.replace(/'/g,"''")}'`,e=(await d.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:c,valueRenderOption:"FORMATTED_VALUE"})).data.values??[];if(e.length>1e4)throw new bZ("sheets_range_too_large",`Sheet has ${e.length} rows which exceeds the 10000-row cap. Use sheets_read_range with a smaller range.`);let f=b1(e),g=(f[0]??[]).map(a=>String(a)),h=f.slice(1);return{sheetName:b,headers:g,rowCount:h.length,values:f}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_batch_read_ranges",description:"Read multiple A1-notation ranges from a spreadsheet in a single API call. Efficient for dashboards that need data from several tabs or ranges at once.",inputSchema:b5,riskLevel:"read",async execute(a){try{for(let b of a.ranges)b2(b);return{results:((await d.spreadsheets.values.batchGet({spreadsheetId:a.spreadsheet_id,ranges:a.ranges,valueRenderOption:a.value_render_option??"FORMATTED_VALUE"})).data.valueRanges??[]).map(a=>{let b=a.values??[],c=b1(b),d=c.reduce((a,b)=>Math.max(a,b.length),0);return{range:a.range??"",rows:c.length,cols:d,values:c}})}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_get_metadata",description:"Get metadata about a Google Spreadsheet: title, list of sheet tabs with their dimensions, and named ranges. Use this to discover sheet names before reading.",inputSchema:cb,riskLevel:"read",async execute(a){try{let b=(await d.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"spreadsheetId,properties.title,spreadsheetUrl,sheets.properties,namedRanges"})).data,c=(b.sheets??[]).map(a=>({sheetId:a.properties?.sheetId??0,title:a.properties?.title??"",index:a.properties?.index??0,rowCount:a.properties?.gridProperties?.rowCount??0,colCount:a.properties?.gridProperties?.columnCount??0,hidden:a.properties?.hidden??!1})),e=(b.namedRanges??[]).map(a=>({name:a.name??"",range:a.range?`${a.range.sheetId}!R${a.range.startRowIndex}C${a.range.startColumnIndex}:R${a.range.endRowIndex}C${a.range.endColumnIndex}`:""}));return{spreadsheetId:b.spreadsheetId??a.spreadsheet_id,title:b.properties?.title??"",url:b.spreadsheetUrl??"",sheets:c,namedRanges:e}}catch(a){throw b$(a)}}},{name:"sheets_find_rows",description:"Find rows in a Google Sheet where a column matches a value. More efficient than reading all rows when you know what you are looking for. Provide exactly one of: equals or contains.",inputSchema:ca,riskLevel:"read",async execute(a){try{let b=[a.equals,a.contains].filter(a=>void 0!==a);if(1!==b.length)throw new bZ("sheets_validation_error","Provide exactly one of: equals, contains.");let c=a.sheet_name;if(!c){let b=await d.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.title"});c=b.data.sheets?.[0]?.properties?.title??"Sheet1"}let e=`'${c.replace(/'/g,"''")}'`,f=(await d.spreadsheets.values.get({spreadsheetId:a.spreadsheet_id,range:e,valueRenderOption:"FORMATTED_VALUE"})).data.values??[];if(0===f.length)return{column:a.column,rowCount:0,headers:[],rows:[]};let g=(f[0]??[]).map(a=>String(a??"")),h=g.indexOf(a.column);if(-1===h)throw new bZ("sheets_validation_error",`Column '${a.column}' not found. Available columns: ${g.join(", ")}`);let i=a.limit??100,j=f.slice(1),k=[];for(let b=0;b<j.length&&k.length<i;b++){let c=j[b]??[],d=String(c[h]??"");if(void 0!==a.equals?d===a.equals:d.includes(a.contains)){let a={_row:b+2};for(let b=0;b<g.length;b++){let d=g[b];if(void 0!==d){let e=c[b];a[d]=null==e?"":e}}k.push(a)}}return{column:a.column,rowCount:k.length,headers:g,rows:k}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_write_range",description:"Write (overwrite) a 2D array of values into a Google Sheet range. Existing values in the range are replaced. Use sheets_append_row to add rows at the end.",inputSchema:b6,riskLevel:"write",async execute(a){try{b2(a.range);let b=await d.spreadsheets.values.update({spreadsheetId:a.spreadsheet_id,range:a.range,valueInputOption:a.value_input_option??"USER_ENTERED",requestBody:{values:a.values}});return{updatedRange:b.data.updatedRange??a.range,updatedRows:b.data.updatedRows??0,updatedCols:b.data.updatedColumns??0,updatedCells:b.data.updatedCells??0}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_append_row",description:"Append one or more rows to the end of a Google Sheet (after the last row with data). Pass a 2D array — e.g. [['Alice', 95]] for one row or [['Alice',95],['Bob',87]] for multiple.",inputSchema:b7,riskLevel:"write",async execute(a){try{let b=(await d.spreadsheets.values.append({spreadsheetId:a.spreadsheet_id,range:a.range,valueInputOption:a.value_input_option??"USER_ENTERED",insertDataOption:"INSERT_ROWS",requestBody:{values:a.values}})).data.updates;return{updatedRange:b?.updatedRange??a.range,updatedRows:b?.updatedRows??0,updatedCells:b?.updatedCells??0}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_clear_range",description:"Clear values from a range in a Google Sheet. Cell formatting and structure are preserved. To delete rows entirely, use sheets_delete_sheet and recreate, or use write with empty values.",inputSchema:b8,riskLevel:"write",async execute(a){try{return b2(a.range),{clearedRange:(await d.spreadsheets.values.clear({spreadsheetId:a.spreadsheet_id,range:a.range})).data.clearedRange??a.range}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_batch_update_values",description:"Write values to multiple ranges in a single API call. More efficient than calling sheets_write_range repeatedly.",inputSchema:b9,riskLevel:"write",async execute(a){try{for(let b of a.updates)b2(b.range);let b=await d.spreadsheets.values.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{valueInputOption:a.value_input_option??"USER_ENTERED",data:a.updates.map(a=>({range:a.range,values:a.values}))}}),c=(b.data.responses??[]).map(a=>({updatedRange:a.updatedRange??"",updatedCells:a.updatedCells??0}));return{totalUpdatedCells:b.data.totalUpdatedCells??0,totalUpdatedRows:b.data.totalUpdatedRows??0,responses:c}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_create_spreadsheet",description:"Create a new Google Spreadsheet. Returns the spreadsheet ID and URL. The new spreadsheet will be placed in the root of the authenticated user Drive.",inputSchema:cc,riskLevel:"write",async execute(a){try{let b=await d.spreadsheets.create({requestBody:{properties:{title:a.title},sheets:[{properties:{title:a.sheet_title??"Sheet1"}}]}});return{spreadsheetId:b.data.spreadsheetId??"",title:b.data.properties?.title??a.title,url:b.data.spreadsheetUrl??"",firstSheetId:b.data.sheets?.[0]?.properties?.sheetId??0}}catch(a){throw b$(a)}}},{name:"sheets_add_sheet",description:"Add a new sheet tab to an existing Google Spreadsheet.",inputSchema:cd,riskLevel:"write",async execute(a){try{let b=await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{addSheet:{properties:{title:a.title,...void 0!==a.index&&{index:a.index}}}}]}}),c=b.data.replies?.[0]?.addSheet?.properties;return{sheetId:c?.sheetId??0,title:c?.title??a.title,index:c?.index??0}}catch(a){throw b$(a)}}},{name:"sheets_duplicate_sheet",description:"Copy a sheet tab within the same Google Spreadsheet. Duplicates all data, formatting, and formulas.",inputSchema:cf,riskLevel:"write",async execute(a){try{var b,c,e;let f=a.insert_sheet_index;if(void 0===f){let b=await d.spreadsheets.get({spreadsheetId:a.spreadsheet_id,fields:"sheets.properties.index"});f=b.data.sheets?.length??1}let g=await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.source_sheet_id,c=f,e=a.new_sheet_name,{duplicateSheet:{sourceSheetId:b,insertSheetIndex:c,...void 0!==e&&{newSheetName:e}}})]}}),h=g.data.replies?.[0]?.duplicateSheet?.properties;return{sheetId:h?.sheetId??0,title:h?.title??a.new_sheet_name??"",index:h?.index??f}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_rename_sheet",description:"Rename a sheet tab in a Google Spreadsheet.",inputSchema:cg,riskLevel:"write",async execute(a){try{var b,c;return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,c=a.new_title,{updateSheetProperties:{properties:{sheetId:b,title:c},fields:"title"}})]}}),{sheetId:a.sheet_id,title:a.new_title}}catch(a){throw b$(a)}}},{name:"sheets_format_range",description:"Apply formatting to a cell range in a Google Sheet: bold, italic, font size, background color, text color, number format, and alignment. Uses zero-based row/column indices.",inputSchema:ch,riskLevel:"write",async execute(a){try{var b,c,e,f,g,h;let i={},j=[],k={};if(void 0!==a.bold&&(k.bold=a.bold,j.push("textFormat.bold")),void 0!==a.italic&&(k.italic=a.italic,j.push("textFormat.italic")),void 0!==a.font_size&&(k.fontSize=a.font_size,j.push("textFormat.fontSize")),void 0!==a.foreground_color&&(k.foregroundColor={red:a.foreground_color.red,green:a.foreground_color.green,blue:a.foreground_color.blue},j.push("textFormat.foregroundColor")),Object.keys(k).length>0&&(i.textFormat=k),void 0!==a.background_color&&(i.backgroundColor={red:a.background_color.red,green:a.background_color.green,blue:a.background_color.blue},j.push("backgroundColor")),void 0!==a.number_format&&(i.numberFormat={type:a.number_format.type,...void 0!==a.number_format.pattern&&{pattern:a.number_format.pattern}},j.push("numberFormat")),void 0!==a.horizontal_alignment&&(i.horizontalAlignment=a.horizontal_alignment,j.push("horizontalAlignment")),0===j.length)throw new bZ("sheets_validation_error","Provide at least one formatting property.");return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,c=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,h=j.join(","),{repeatCell:{range:{sheetId:b,startRowIndex:c,endRowIndex:e,startColumnIndex:f,endColumnIndex:g},cell:{userEnteredFormat:i},fields:`userEnteredFormat(${h})`}})]}}),{formatted:!0,sheetId:a.sheet_id}}catch(a){if(a instanceof bZ)throw a;throw b$(a)}}},{name:"sheets_resize_columns",description:"Resize columns in a Google Sheet. Provide pixel_size for a fixed width, or omit to auto-resize columns to fit their content.",inputSchema:ci,riskLevel:"write",async execute(a){try{var b,c,e,f,g,h,i;let j=void 0!==a.pixel_size?(b=a.sheet_id,c=a.start_column_index,e=a.end_column_index,f=a.pixel_size,{updateDimensionProperties:{range:{sheetId:b,dimension:"COLUMNS",startIndex:c,endIndex:e},properties:{pixelSize:f},fields:"pixelSize"}}):(g=a.sheet_id,h=a.start_column_index,i=a.end_column_index,{autoResizeDimensions:{dimensions:{sheetId:g,dimension:"COLUMNS",startIndex:h,endIndex:i}}});return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[j]}}),{resized:!0,sheetId:a.sheet_id,startColumnIndex:a.start_column_index,endColumnIndex:a.end_column_index}}catch(a){throw b$(a)}}},{name:"sheets_freeze_panes",description:"Freeze rows and/or columns in a Google Sheet so they stay visible while scrolling. Set frozen_row_count=1 to freeze the header row. Set to 0 to unfreeze.",inputSchema:cj,riskLevel:"write",async execute(a){try{var b;let c=a.frozen_row_count??0,e=a.frozen_column_count??0;return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,{updateSheetProperties:{properties:{sheetId:b,gridProperties:{frozenRowCount:c,frozenColumnCount:e}},fields:"gridProperties.frozenRowCount,gridProperties.frozenColumnCount"}})]}}),{frozenRowCount:c,frozenColumnCount:e,sheetId:a.sheet_id}}catch(a){throw b$(a)}}},{name:"sheets_set_basic_filter",description:"Apply a basic auto-filter to a range in a Google Sheet. Adds dropdown arrows to the header row for filtering. Uses zero-based row/column indices.",inputSchema:ck,riskLevel:"write",async execute(a){try{var b,c,e,f,g;return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,c=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,{setBasicFilter:{filter:{range:{sheetId:b,startRowIndex:c,endRowIndex:e,startColumnIndex:f,endColumnIndex:g}}}})]}}),{filterApplied:!0,sheetId:a.sheet_id}}catch(a){throw b$(a)}}},{name:"sheets_clear_basic_filter",description:"Remove the basic auto-filter from a sheet tab.",inputSchema:cl,riskLevel:"write",async execute(a){try{return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{clearBasicFilter:{sheetId:a.sheet_id}}]}}),{filterCleared:!0,sheetId:a.sheet_id}}catch(a){throw b$(a)}}},{name:"sheets_sort_range",description:"Sort a range of cells in a Google Sheet by one or more columns. Supports multi-level sort (primary + secondary columns). Uses zero-based row/column indices.",inputSchema:cn,riskLevel:"write",async execute(a){try{var b,c,e,f,g,h;return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[(b=a.sheet_id,c=a.start_row_index,e=a.end_row_index,f=a.start_column_index,g=a.end_column_index,h=a.sort_specs.map(a=>({dimensionIndex:a.dimension_index,sortOrder:a.sort_order})),{sortRange:{range:{sheetId:b,startRowIndex:c,endRowIndex:e,startColumnIndex:f,endColumnIndex:g},sortSpecs:h}})]}}),{sorted:!0,sheetId:a.sheet_id}}catch(a){throw b$(a)}}},{name:"sheets_delete_sheet",description:"Permanently delete a sheet tab from a Google Spreadsheet. This is irreversible. Get the numeric sheetId from sheets_get_metadata (not the tab name).",inputSchema:ce,riskLevel:"destructive",async execute(a){try{return await d.spreadsheets.batchUpdate({spreadsheetId:a.spreadsheet_id,requestBody:{requests:[{deleteSheet:{sheetId:a.sheet_id}}]}}),{deleted:!0,sheetId:a.sheet_id}}catch(a){throw b$(a)}}}]}class cp extends Error{constructor(a,b,c){super(b),this.name="DocsAdapterError",this.code=a,this.status=c}}function cq(a){if("object"==typeof a&&null!==a){let b="number"==typeof a.code?a.code:void 0,c="string"==typeof a.message?a.message:String(a);if(void 0!==b){let a;switch(b){case 400:a="docs_invalid_request";break;case 401:a="docs_unauthorized";break;case 403:a="docs_forbidden";break;case 404:a="docs_not_found";break;case 429:a="docs_rate_limited";break;case 503:a="docs_service_unavailable";break;default:a="docs_unknown"}return new cp(a,c,b)}}return a instanceof cp?a:a instanceof Error?new cp("docs_unknown",a.message):new cp("docs_unknown",String(a))}function cr(a){let b=[];for(let c of a.content??[])c.paragraph?b.push(cs(c.paragraph)):c.table?b.push(function(a){let b=[];for(let c of a.tableRows??[]){let a=[];for(let b of c.tableCells??[]){let c=(b.content??[]).map(a=>a.paragraph?cs(a.paragraph):"").join("").replace(/\n$/,"");a.push(c)}b.push(a.join(" ")+"\n")}return b.join("")}(c.table)):c.sectionBreak&&b.push("\n");return b.join("")}function cs(a){let b=[];for(let c of a.elements??[])c.textRun?.content?b.push(c.textRun.content):c.inlineObjectElement?b.push("[image]"):c.horizontalRule&&b.push("\n---\n");return b.join("")}function ct(a){return{insertText:{endOfSegmentLocation:{segmentId:""},text:a}}}function cu(a,b,c){return{updateParagraphStyle:{range:{startIndex:a,endIndex:b},paragraphStyle:{namedStyleType:c},fields:"namedStyleType"}}}let cv=g.Ik({title:g.Yj().describe("Title for the new document."),content:g.Yj().optional().describe("Optional initial text content to insert into the document body.")}),cw=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit).")}),cx=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit).")}),cy=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Text to insert."),index:g.ai().int().min(1).describe("Document body index at which to insert text. Index 1 = beginning of body. Use docs_get to inspect element indices. Insertions shift all subsequent content.")}),cz=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Text to append at the end of the document. Use \\n for line breaks.")}),cA=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),find:g.Yj().describe("The exact text string to find in the document."),replace:g.Yj().describe("The text to replace all found occurrences with."),match_case:g.zM().optional().describe("Whether to match case exactly (default: true).")}),cB=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the range to delete (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the range to delete (exclusive). Content at [startIndex, endIndex) is removed.")}),cC=g.k5(["NORMAL_TEXT","TITLE","SUBTITLE","HEADING_1","HEADING_2","HEADING_3","HEADING_4","HEADING_5","HEADING_6"]),cD=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),text:g.Yj().describe("Paragraph text. A newline is appended automatically if not present."),index:g.ai().int().min(1).describe("Document body index at which to insert the paragraph. Index 1 = beginning of body. Use docs_get to find indices."),named_style:cC.optional().describe("Optional named paragraph style to apply after inserting (e.g. HEADING_1, NORMAL_TEXT).")}),cE=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),index:g.ai().int().min(1).describe("Document body index at which to insert the page break.")}),cF=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),index:g.ai().int().min(1).describe("Document body index at which to insert the table."),rows:g.ai().int().min(1).max(100).describe("Number of rows in the table (1–100)."),columns:g.ai().int().min(1).max(20).describe("Number of columns in the table (1–20).")}),cG=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),image_uri:g.Yj().url().describe("Public URL of the image to insert (must be publicly accessible)."),index:g.ai().int().min(1).describe("Document body index at which to insert the image."),width_pt:g.ai().positive().optional().describe("Optional image width in points (1pt ≈ 1.333px). Omit to use source dimensions."),height_pt:g.ai().positive().optional().describe("Optional image height in points. Omit to use source dimensions.")}),cH=g.k5(["NORMAL_TEXT","TITLE","SUBTITLE","HEADING_1","HEADING_2","HEADING_3","HEADING_4","HEADING_5","HEADING_6"]),cI=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the text range to format (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the text range to format (exclusive)."),bold:g.zM().optional().describe("Apply bold formatting."),italic:g.zM().optional().describe("Apply italic formatting."),underline:g.zM().optional().describe("Apply underline formatting."),strikethrough:g.zM().optional().describe("Apply strikethrough formatting."),font_size_pt:g.ai().positive().optional().describe("Font size in points (e.g. 12, 14, 18)."),foreground_color:g.Ik({red:g.ai().min(0).max(1).describe("Red channel 0–1."),green:g.ai().min(0).max(1).describe("Green channel 0–1."),blue:g.ai().min(0).max(1).describe("Blue channel 0–1.")}).optional().describe("Text foreground color (RGB, each channel 0–1)."),font_family:g.Yj().optional().describe('Font family name (e.g. "Arial", "Times New Roman", "Roboto").')}),cJ=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),start_index:g.ai().int().min(1).describe("Start of the paragraph range (inclusive). Get indices from docs_get."),end_index:g.ai().int().min(2).describe("End of the paragraph range (exclusive)."),named_style:cH.describe("The paragraph style to apply: NORMAL_TEXT, TITLE, SUBTITLE, HEADING_1 through HEADING_6.")}),cK=g.Ik({document_id:g.Yj().describe("The Google Doc ID (from the URL: docs.google.com/document/d/{ID}/edit)."),requests:g.YO(g.g1(g.Yj(),g.L5())).min(1).describe("Array of Google Docs API Request objects. Each object must have exactly one key matching a Docs API operation (e.g. insertText, deleteContentRange, updateParagraphStyle, replaceAllText, etc.). See https://developers.google.com/docs/api/reference/rest/v1/documents/request for the full schema.")});function cL(a){var b;let c,d=(b="getAccessToken"in a?a.getAccessToken:async()=>a.accessToken,(c=new aM.google.auth.OAuth2).refreshHandler=async()=>({access_token:await b(),expiry_date:Date.now()-1}),aM.google.docs({version:"v1",auth:c}));return[{name:"docs_get",description:"Get the full structured content of a Google Document as JSON: title, body (with all paragraphs, tables, and structural elements), plus headers and footers. Capped at 100,000 characters of body text — use docs_get_text for plain text extraction.",inputSchema:cw,riskLevel:"read",async execute(a){try{let b=(await d.documents.get({documentId:a.document_id})).data;if(b.body){let a=cr(b.body);if(a.length>1e5)throw new cp("docs_document_too_large",`Document body contains ${a.length} characters which exceeds the 100000-character cap.`)}let c=Object.entries(b.headers??{}).map(([a,b])=>({headerId:a,text:b.content?cr({content:b.content}):""})),e=Object.entries(b.footers??{}).map(([a,b])=>({footerId:a,text:b.content?cr({content:b.content}):""}));return{documentId:b.documentId??a.document_id,title:b.title??"",body:b.body??{},headers:c,footers:e,revisionId:b.revisionId??""}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_get_text",description:"Get the plain text content of a Google Document. Parses the document body, joining all paragraph runs, handling tables (tab-separated cells), and headings. Capped at 100,000 characters — throws docs_document_too_large if exceeded.",inputSchema:cx,riskLevel:"read",async execute(a){try{let b=(await d.documents.get({documentId:a.document_id})).data,c=b.body?cr(b.body):"";if(c.length>1e5)throw new cp("docs_document_too_large",`Document contains ${c.length} characters which exceeds the 100000-character cap.`);return{documentId:b.documentId??a.document_id,title:b.title??"",text:c,charCount:c.length}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_create",description:"Create a new Google Document with the given title. Optionally provide initial text content. Returns the document ID and URL. The document is placed in the authenticated user's Drive root.",inputSchema:cv,riskLevel:"write",async execute(a){try{let b=await d.documents.create({requestBody:{title:a.title}}),c=b.data.documentId??"",e=b.data.title??a.title;if(a.content&&a.content.length>0){let b=a.content.endsWith("\n")?a.content:a.content+"\n";await d.documents.batchUpdate({documentId:c,requestBody:{requests:[ct(b)]}})}return{documentId:c,title:e,url:`https://docs.google.com/document/d/${c}/edit`}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_insert_text",description:"Insert text at a specific index in a Google Document body. Index 1 = start of body. Use docs_get to find element indices. This shifts all subsequent content forward.",inputSchema:cy,riskLevel:"write",async execute(a){try{var b;return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.text,{insertText:{location:{index:a.index},text:b}})]}}),{inserted:!0,documentId:a.document_id,index:a.index,charCount:a.text.length}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_append_text",description:"Append text to the end of a Google Document. Uses endOfSegmentLocation — always inserts at the very end of the body, regardless of the current document length. Use \\n for line breaks.",inputSchema:cz,riskLevel:"write",async execute(a){try{let b=a.text.endsWith("\n")?a.text:a.text+"\n";return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[ct(b)]}}),{appended:!0,documentId:a.document_id,charCount:b.length}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_replace_text",description:"Find and replace all occurrences of a text string in a Google Document. Replaces every match in the document body. Returns the number of occurrences changed (0 means the text was not found).",inputSchema:cA,riskLevel:"write",async execute(a){try{var b,c;let e=a.match_case??!0,f=await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.find,c=a.replace,{replaceAllText:{containsText:{text:b,matchCase:e},replaceText:c}})]}}),g=f.data.replies?.[0]?.replaceAllText?.occurrencesChanged??0;return{documentId:a.document_id,occurrencesChanged:g}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_insert_paragraph",description:"Insert a new paragraph at a specific index in a Google Document. Optionally apply a named paragraph style (HEADING_1…HEADING_6, TITLE, SUBTITLE, NORMAL_TEXT). A paragraph in Docs is defined by a trailing \\n — this is appended automatically.",inputSchema:cD,riskLevel:"write",async execute(a){try{var b;let c=a.text.endsWith("\n")?a.text:a.text+"\n",e=[(b=a.index,{insertText:{location:{index:b},text:c.endsWith("\n")?c:c+"\n"}})];if(a.named_style){let b=c.length;e.push(cu(a.index,a.index+b,a.named_style))}return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:e}}),{inserted:!0,documentId:a.document_id,index:a.index}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_insert_page_break",description:"Insert a page break at a specific index in a Google Document. Useful for separating sections onto distinct pages.",inputSchema:cE,riskLevel:"write",async execute(a){try{return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[{insertPageBreak:{location:{index:a.index}}}]}}),{inserted:!0,documentId:a.document_id,index:a.index}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_insert_table",description:"Insert a table with N rows \xd7 M columns at a specific index in a Google Document. After insertion, use docs_insert_text to populate individual cells.",inputSchema:cF,riskLevel:"write",async execute(a){try{var b,c,e;return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.index,c=a.rows,e=a.columns,{insertTable:{location:{index:b},rows:c,columns:e}})]}}),{inserted:!0,documentId:a.document_id,rows:a.rows,columns:a.columns,index:a.index}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_insert_image",description:"Insert an inline image from a public URL at a specific index in a Google Document. Optionally specify width/height in points. The image URL must be publicly accessible.",inputSchema:cG,riskLevel:"write",async execute(a){try{var b,c,e,f;let g;return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.index,c=a.image_uri,e=a.width_pt,f=a.height_pt,g=void 0!==e||void 0!==f?{width:void 0!==e?{magnitude:e,unit:"PT"}:void 0,height:void 0!==f?{magnitude:f,unit:"PT"}:void 0}:void 0,{insertInlineImage:{location:{index:b},uri:c,...void 0!==g&&{objectSize:g}}})]}}),{inserted:!0,documentId:a.document_id,index:a.index,imageUri:a.image_uri}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_format_text",description:"Apply character-level formatting to a text range in a Google Document: bold, italic, underline, strikethrough, font size, foreground color, and font family. Use docs_get to find the start/end indices of the text to format.",inputSchema:cI,riskLevel:"write",async execute(a){try{var b,c,e;if(a.end_index<=a.start_index)throw new cp("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);let f={},g=[];if(void 0!==a.bold&&(f.bold=a.bold,g.push("bold")),void 0!==a.italic&&(f.italic=a.italic,g.push("italic")),void 0!==a.underline&&(f.underline=a.underline,g.push("underline")),void 0!==a.strikethrough&&(f.strikethrough=a.strikethrough,g.push("strikethrough")),void 0!==a.font_size_pt&&(f.fontSize={magnitude:a.font_size_pt,unit:"PT"},g.push("fontSize")),void 0!==a.foreground_color&&(f.foregroundColor={color:{rgbColor:{red:a.foreground_color.red,green:a.foreground_color.green,blue:a.foreground_color.blue}}},g.push("foregroundColor")),void 0!==a.font_family&&(f.weightedFontFamily={fontFamily:a.font_family},g.push("weightedFontFamily")),0===g.length)throw new cp("docs_invalid_request","Provide at least one formatting property (bold, italic, underline, font_size_pt, etc.).");return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.start_index,c=a.end_index,e=g.join(","),{updateTextStyle:{range:{startIndex:b,endIndex:c},textStyle:f,fields:e}})]}}),{formatted:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_apply_named_style",description:"Apply a named paragraph style to a range in a Google Document: HEADING_1 through HEADING_6, TITLE, SUBTITLE, or NORMAL_TEXT. Use docs_get to find the paragraph start/end indices.",inputSchema:cJ,riskLevel:"write",async execute(a){try{if(a.end_index<=a.start_index)throw new cp("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[cu(a.start_index,a.end_index,a.named_style)]}}),{applied:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index,namedStyle:a.named_style}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_batch_update",description:"Execute multiple Google Docs API update requests in a single call (escape hatch for advanced agents). Accepts any valid Docs API Request objects — insertText, deleteContentRange, updateTextStyle, updateParagraphStyle, replaceAllText, insertTable, insertInlineImage, and more. All requests are applied atomically in order. Use this when other docs_* tools do not cover your use case.",inputSchema:cK,riskLevel:"write",async execute(a){try{let b=await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:a.requests}});return{documentId:a.document_id,repliesCount:b.data.replies?.length??0,writeControl:b.data.writeControl??void 0}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}},{name:"docs_delete_content_range",description:"Delete a range of content from a Google Document body by index. The range [startIndex, endIndex) is removed — this is irreversible. Use docs_get to find the correct indices before deleting. To delete the whole document, use drive_delete_file from the Drive adapter instead.",inputSchema:cB,riskLevel:"destructive",async execute(a){try{var b,c;if(a.end_index<=a.start_index)throw new cp("docs_invalid_request",`end_index (${a.end_index}) must be greater than start_index (${a.start_index}).`);return await d.documents.batchUpdate({documentId:a.document_id,requestBody:{requests:[(b=a.start_index,c=a.end_index,{deleteContentRange:{range:{startIndex:b,endIndex:c}}})]}}),{deleted:!0,documentId:a.document_id,startIndex:a.start_index,endIndex:a.end_index}}catch(a){if(a instanceof cp)throw a;throw cq(a)}}}]}var cM=c(19199);class cN extends Error{constructor(a,b,c){super(b),this.name="FirecrawlApiError",this.code=a,this.status=c}}function cO(a){if(a instanceof cN)return a;if(null!==a&&"object"==typeof a&&"status"in a&&"number"==typeof a.status){let c,d=a.message??`Firecrawl API error ${a.status}`;var b=a.status;switch(!0){case 401===b:c="firecrawl_unauthorized";break;case 403===b:c="firecrawl_forbidden";break;case 404===b:c="firecrawl_not_found";break;case 422===b:c="firecrawl_validation_error";break;case 429===b:c="firecrawl_rate_limited";break;case b>=500:c="firecrawl_transient";break;default:c="firecrawl_client_error"}return new cN(c,d,b)}return a instanceof Error?new cN("firecrawl_unknown",a.message):new cN("firecrawl_unknown",String(a))}function cP(a){if(void 0===a)return{truncated:!1};let b=a.length>15e3;return{content:b?a.slice(0,15e3)+`
17
+
18
+ [...content truncated at 15000 chars...]`:a,truncated:b}}let cQ=g.Ik({url:g.Yj().url().describe("The URL to scrape."),formats:g.YO(g.k5(["markdown","html","links"])).optional().default(["markdown"]).describe("Content formats to return. Defaults to ['markdown'].")}),cR=g.Ik({url:g.Yj().url().describe("The root URL whose site to map."),search:g.Yj().optional().describe("Optional keyword filter — only return URLs matching this term.")}),cS=g.Ik({query:g.Yj().min(1).describe("The search query to send to Firecrawl."),limit:g.ai().int().min(1).max(100).optional().describe("Maximum number of results to return (1–100).")}),cT=g.Ik({url:g.Yj().url().describe("The root URL to crawl."),limit:g.ai().int().min(1).max(100).optional().describe("Maximum number of pages to crawl (1–100).")}),cU=g.Ik({id:g.Yj().min(1).describe("The crawl job ID returned by firecrawl_crawl_start.")});var cV=c(25459),cW=c(99740);let cX=g.Ik({query:g.Yj().min(1).describe("A web page URL to scrape, OR free-text search terms. A URL returns that page; search terms return the top results."),maxResults:g.ai().int().min(1).max(10).optional().describe("For a search query, how many results to return (default 3). Ignored for a single URL.")});function cY(a){return Array.from(a).filter(a=>{let b=a.charCodeAt(0);return 9===b||10===b||13===b||b>=32&&127!==b}).join("")}function cZ(a){let b=a??{},c=b.metadata??{},d=b.searchResult??{},e=b.crawl??{},f=a=>"string"==typeof a?a:"";return{url:f(c.url)||f(d.url)||f(e.loadedUrl)||f(b.url),title:cY(f(c.title)||f(d.title)||f(b.title)),content:cY(f(b.text)||f(b.markdown)||"")}}let c$=g.Ik({actorId:g.Yj().describe('The actor ID or name in the format "owner/actor-name" (e.g. "apify/web-scraper") or just the actor ID.'),input:g.g1(g.Yj(),g.L5()).optional().describe("Input object to pass to the actor. Structure depends on the actor. Omit to use actor defaults."),waitSecs:g.ai().int().min(1).max(3600).optional().describe("Max seconds to wait for the run to finish before returning with its current status (default 1800, capped at 3600). The run keeps going on Apify's side even if this elapses — use apify_get_run to check on it later.")}),c_=g.Ik({runId:g.Yj().describe("The Apify run ID to retrieve metadata for.")}),c0=g.Ik({limit:g.ai().int().min(1).max(1e3).optional().default(100).describe("Maximum number of datasets to return (default 100, max 1000)."),offset:g.ai().int().min(0).optional().default(0).describe("Number of datasets to skip (for pagination). Default 0.")}),c1=g.Ik({datasetId:g.Yj().describe("The Apify dataset ID to read from. Use apify_run_actor to get the datasetId from a run, or apify_list_datasets to browse existing datasets."),limit:g.ai().int().min(1).max(1e3).optional().default(100).describe("Maximum number of items to return (default 100, max 1000)."),offset:g.ai().int().min(0).optional().default(0).describe("Number of items to skip (for pagination). Default 0.")});var c2=c(43845);class c3 extends Error{constructor(a,b,c){super(b),this.name="TavilyApiError",this.code=a,this.status=c}}function c4(a){if(a instanceof c3)return a;if(a instanceof Error){let d=/status[:\s]+(\d{3})/i.exec(a.message);if(d){let e;var b=parseInt(d[1]??"0",10),c=a.message;switch(!0){case 401===b:e="tavily_unauthorized";break;case 403===b:e="tavily_forbidden";break;case 404===b:e="tavily_not_found";break;case 422===b:e="tavily_validation_error";break;case 429===b:e="tavily_rate_limited";break;case b>=500:e="tavily_transient";break;default:e="tavily_client_error"}return new c3(e,c,b)}return new c3("tavily_unknown",a.message)}return new c3("tavily_unknown",String(a))}function c5(a){let b=a.length>15e3;return{content:b?a.slice(0,15e3)+`
19
+
20
+ [...content truncated at 15000 chars...]`:a,truncated:b}}let c6=g.Ik({query:g.Yj().min(1).describe("The search query to send to Tavily."),searchDepth:g.k5(["basic","advanced"]).optional().describe('Search depth: "basic" is faster, "advanced" is more thorough. Default: "basic".'),maxResults:g.ai().int().min(1).max(20).optional().describe("Maximum number of results to return (1–20, default 5)."),includeImages:g.zM().optional().describe("Whether to include image results. Default: false."),topic:g.k5(["general","news"]).optional().describe('Search topic category: "general" or "news". Default: "general".')}),c7=g.Ik({urls:g.YO(g.Yj().url()).min(1).max(20).describe("Array of URLs to extract content from (max 20)."),extractDepth:g.k5(["basic","advanced"]).optional().describe('Extraction depth: "basic" or "advanced". Default: "basic".')}),c8=g.Ik({url:g.Yj().url().describe("The seed URL to start crawling from."),maxDepth:g.ai().int().min(1).max(5).optional().describe("Maximum link depth to follow from the seed URL (1–5, default 1)."),limit:g.ai().int().min(1).max(50).optional().describe("Maximum number of pages to scrape (1–50, default 10).")});class c9 extends Error{constructor(a,b,c){super(b),this.name="PoyoApiError",this.code=a,this.status=c}}function da(a,b){let c;switch(!0){case 401===a:c="poyo_unauthorized";break;case 403===a:c="poyo_forbidden";break;case 404===a:c="poyo_not_found";break;case 422===a:c="poyo_validation_error";break;case 429===a:c="poyo_rate_limited";break;case a>=500:c="poyo_transient";break;default:c="poyo_client_error"}return new c9(c,b,a)}async function db(a,b,c,d){try{return await a(b,{...c,signal:AbortSignal.timeout(d)})}catch(a){if(a instanceof Error&&"TimeoutError"===a.name)throw new c9("poyo_transient",`Poyo request to ${b} timed out after ${d}ms`);throw a}}async function dc(a){try{return await a.text()}catch{return`HTTP ${a.status}`}}let dd={intervalMs:4e3,maxAttempts:45},de=g.Ik({prompt:g.Yj().min(1).describe("Text description of the image to generate."),model:g.Yj().min(1).optional().describe('Poyo image model id. Default "gpt-4o-image". Pass another Poyo image model id (see poyo.ai) to switch model.'),size:g.Yj().min(1).optional().describe('Aspect ratio of the image, e.g. "1:1", "16:9", "9:16", "4:3". Default "1:1".')}),df=a=>new Promise(b=>setTimeout(b,a)),dg={"google-drive":{credentialType:"google-oauth",toolFactory:a=>ba({accessToken:a}),toolFactoryWithResolver:a=>ba({getAccessToken:a}),operations:[{slug:"drive_list_files",name:"List files",risk:"read",requiresApproval:!1,description:"Search and list files in Google Drive."},{slug:"drive_read_file",name:"Read file",risk:"read",requiresApproval:!1,description:"Download and read file content."},{slug:"drive_get_file_info",name:"Get file info",risk:"read",requiresApproval:!1,description:"Retrieve file metadata (name, size, mimeType, owners)."},{slug:"drive_list_permissions",name:"List permissions",risk:"read",requiresApproval:!1,description:"List sharing permissions on a file or folder."},{slug:"drive_export_file",name:"Export file",risk:"read",requiresApproval:!1,description:"Export a Google Workspace file (Docs, Sheets) to a target format."},{slug:"drive_upload_file",name:"Upload file",risk:"write",requiresApproval:!1,description:"Upload a new file to Google Drive."},{slug:"drive_create_folder",name:"Create folder",risk:"write",requiresApproval:!1,description:"Create a new folder."},{slug:"drive_move_file",name:"Move file",risk:"write",requiresApproval:!1,description:"Move a file to a different folder."},{slug:"drive_rename_file",name:"Rename file",risk:"write",requiresApproval:!1,description:"Rename a file or folder."},{slug:"drive_copy_file",name:"Copy file",risk:"write",requiresApproval:!1,description:"Make a copy of a file."},{slug:"drive_share_file",name:"Share file",risk:"write",requiresApproval:!1,description:"Add or update sharing permissions on a file."},{slug:"drive_delete_file",name:"Delete file",risk:"destructive",requiresApproval:!0,description:"Permanently delete a file or folder from Google Drive."}]},gmail:{credentialType:"google-oauth",toolFactory:a=>bL({accessToken:a}),toolFactoryWithResolver:a=>bL({getAccessToken:a}),operations:[{slug:"gmail_list_messages",name:"List messages",risk:"read",requiresApproval:!1,description:"Search and list emails by query."},{slug:"gmail_get_message",name:"Get message",risk:"read",requiresApproval:!1,description:"Retrieve a single email by ID."},{slug:"gmail_list_threads",name:"List threads",risk:"read",requiresApproval:!1,description:"List email conversation threads."},{slug:"gmail_get_thread",name:"Get thread",risk:"read",requiresApproval:!1,description:"Retrieve all messages in a thread."},{slug:"gmail_list_labels",name:"List labels",risk:"read",requiresApproval:!1,description:"List all Gmail labels."},{slug:"gmail_get_label",name:"Get label",risk:"read",requiresApproval:!1,description:"Retrieve a single label by ID."},{slug:"gmail_list_drafts",name:"List drafts",risk:"read",requiresApproval:!1,description:"List email drafts."},{slug:"gmail_get_attachment",name:"Get attachment",risk:"read",requiresApproval:!1,description:"Download an email attachment by ID."},{slug:"gmail_list_history",name:"List history",risk:"read",requiresApproval:!1,description:"List mailbox history changes since a given historyId."},{slug:"gmail_reply_message",name:"Reply to message",risk:"write",requiresApproval:!1,description:"Send a reply in an existing thread."},{slug:"gmail_forward_message",name:"Forward message",risk:"write",requiresApproval:!1,description:"Forward an email to new recipients."},{slug:"gmail_modify_labels",name:"Modify labels",risk:"write",requiresApproval:!1,description:"Add or remove labels on a message."},{slug:"gmail_trash_message",name:"Trash message",risk:"write",requiresApproval:!1,description:"Move a message to Trash (reversible)."},{slug:"gmail_untrash_message",name:"Untrash message",risk:"write",requiresApproval:!1,description:"Restore a message from Trash."},{slug:"gmail_modify_thread_labels",name:"Modify thread labels",risk:"write",requiresApproval:!1,description:"Add or remove labels on all messages in a thread."},{slug:"gmail_trash_thread",name:"Trash thread",risk:"write",requiresApproval:!1,description:"Move an entire thread to Trash (reversible)."},{slug:"gmail_create_label",name:"Create label",risk:"write",requiresApproval:!1,description:"Create a new Gmail label."},{slug:"gmail_update_label",name:"Update label",risk:"write",requiresApproval:!1,description:"Rename or update a Gmail label."},{slug:"gmail_create_draft",name:"Create draft",risk:"write",requiresApproval:!1,description:"Compose an email draft without sending."},{slug:"gmail_update_draft",name:"Update draft",risk:"write",requiresApproval:!1,description:"Update an existing email draft."},{slug:"gmail_send_email",name:"Send email",risk:"destructive",requiresApproval:!0,description:"Send an email from the connected mailbox (irreversible)."},{slug:"gmail_send_draft",name:"Send draft",risk:"destructive",requiresApproval:!0,description:"Send a saved draft (irreversible)."},{slug:"gmail_delete_message",name:"Delete message",risk:"destructive",requiresApproval:!0,description:"Permanently delete a message (bypasses Trash)."},{slug:"gmail_delete_label",name:"Delete label",risk:"destructive",requiresApproval:!0,description:"Permanently delete a Gmail label."},{slug:"gmail_delete_draft",name:"Delete draft",risk:"destructive",requiresApproval:!0,description:"Permanently delete an email draft."}]},"google-calendar":{credentialType:"google-oauth",toolFactory:a=>bY({accessToken:a}),toolFactoryWithResolver:a=>bY({getAccessToken:a}),operations:[{slug:"gcal_list_calendars",name:"List calendars",risk:"read",requiresApproval:!1,description:"List the calendars the user has access to."},{slug:"gcal_list_events",name:"List events",risk:"read",requiresApproval:!1,description:"List events on a calendar within a time range (defaults to upcoming)."},{slug:"gcal_get_event",name:"Get event",risk:"read",requiresApproval:!1,description:"Retrieve a single event by ID."},{slug:"gcal_find_free_slots",name:"Find free slots",risk:"read",requiresApproval:!1,description:"Query busy/free intervals across calendars for scheduling."},{slug:"gcal_create_event",name:"Create event",risk:"write",requiresApproval:!1,description:"Create a new calendar event (optionally inviting attendees)."},{slug:"gcal_update_event",name:"Update event",risk:"write",requiresApproval:!1,description:"Update an existing calendar event."},{slug:"gcal_delete_event",name:"Delete event",risk:"destructive",requiresApproval:!0,description:"Permanently delete a calendar event."}]},"google-sheets":{credentialType:"google-oauth",toolFactory:a=>co({accessToken:a}),toolFactoryWithResolver:a=>co({getAccessToken:a}),operations:[{slug:"sheets_read_range",name:"Read range",risk:"read",requiresApproval:!1,description:"Read values from a cell range (e.g. A1:C10)."},{slug:"sheets_read_all",name:"Read all",risk:"read",requiresApproval:!1,description:"Read all values from a sheet."},{slug:"sheets_batch_read_ranges",name:"Batch read ranges",risk:"read",requiresApproval:!1,description:"Read multiple cell ranges in a single request."},{slug:"sheets_get_metadata",name:"Get metadata",risk:"read",requiresApproval:!1,description:"Retrieve spreadsheet metadata and sheet list."},{slug:"sheets_find_rows",name:"Find rows",risk:"read",requiresApproval:!1,description:"Search rows matching a column value."},{slug:"sheets_write_range",name:"Write range",risk:"write",requiresApproval:!1,description:"Write values to a cell range."},{slug:"sheets_append_row",name:"Append row",risk:"write",requiresApproval:!1,description:"Append a new row at the end of a sheet."},{slug:"sheets_clear_range",name:"Clear range",risk:"write",requiresApproval:!1,description:"Clear values in a cell range."},{slug:"sheets_batch_update_values",name:"Batch update values",risk:"write",requiresApproval:!1,description:"Write values to multiple ranges in one request."},{slug:"sheets_create_spreadsheet",name:"Create spreadsheet",risk:"write",requiresApproval:!1,description:"Create a new Google Sheets spreadsheet."},{slug:"sheets_add_sheet",name:"Add sheet",risk:"write",requiresApproval:!1,description:"Add a new sheet tab to a spreadsheet."},{slug:"sheets_duplicate_sheet",name:"Duplicate sheet",risk:"write",requiresApproval:!1,description:"Duplicate an existing sheet tab."},{slug:"sheets_rename_sheet",name:"Rename sheet",risk:"write",requiresApproval:!1,description:"Rename a sheet tab."},{slug:"sheets_format_range",name:"Format range",risk:"write",requiresApproval:!1,description:"Apply formatting (bold, color, number format) to a cell range."},{slug:"sheets_resize_columns",name:"Resize columns",risk:"write",requiresApproval:!1,description:"Resize column widths in a sheet."},{slug:"sheets_freeze_panes",name:"Freeze panes",risk:"write",requiresApproval:!1,description:"Freeze rows or columns in a sheet."},{slug:"sheets_set_basic_filter",name:"Set basic filter",risk:"write",requiresApproval:!1,description:"Apply a basic filter to a sheet range."},{slug:"sheets_clear_basic_filter",name:"Clear basic filter",risk:"write",requiresApproval:!1,description:"Remove the basic filter from a sheet."},{slug:"sheets_sort_range",name:"Sort range",risk:"write",requiresApproval:!1,description:"Sort a range by one or more columns."},{slug:"sheets_delete_sheet",name:"Delete sheet",risk:"destructive",requiresApproval:!0,description:"Permanently delete a sheet tab from a spreadsheet."}]},"google-docs":{credentialType:"google-oauth",toolFactory:a=>cL({accessToken:a}),toolFactoryWithResolver:a=>cL({getAccessToken:a}),operations:[{slug:"docs_get",name:"Get document",risk:"read",requiresApproval:!1,description:"Retrieve full document structure and content."},{slug:"docs_get_text",name:"Get document text",risk:"read",requiresApproval:!1,description:"Extract plain text from a Google Doc."},{slug:"docs_create",name:"Create document",risk:"write",requiresApproval:!1,description:"Create a new Google Docs document."},{slug:"docs_insert_text",name:"Insert text",risk:"write",requiresApproval:!1,description:"Insert text at a specific index in the document."},{slug:"docs_append_text",name:"Append text",risk:"write",requiresApproval:!1,description:"Append text at the end of the document."},{slug:"docs_replace_text",name:"Replace text",risk:"write",requiresApproval:!1,description:"Find and replace text throughout the document."},{slug:"docs_insert_paragraph",name:"Insert paragraph",risk:"write",requiresApproval:!1,description:"Insert a new paragraph at a given index."},{slug:"docs_insert_page_break",name:"Insert page break",risk:"write",requiresApproval:!1,description:"Insert a page break at a given index."},{slug:"docs_insert_table",name:"Insert table",risk:"write",requiresApproval:!1,description:"Insert a table with specified rows and columns."},{slug:"docs_insert_image",name:"Insert image",risk:"write",requiresApproval:!1,description:"Insert an image from a URL into the document."},{slug:"docs_format_text",name:"Format text",risk:"write",requiresApproval:!1,description:"Apply text formatting (bold, italic, color) to a range."},{slug:"docs_apply_named_style",name:"Apply named style",risk:"write",requiresApproval:!1,description:"Apply a heading or paragraph style to a range."},{slug:"docs_batch_update",name:"Batch update",risk:"write",requiresApproval:!1,description:"Send multiple document update requests in a single API call."},{slug:"docs_delete_content_range",name:"Delete content range",risk:"destructive",requiresApproval:!0,description:"Delete a range of content from the document (irreversible)."}]},"notion-oauth":{credentialType:"notion-oauth",toolFactory:a=>ax({accessToken:a}),operations:aw},notion:{credentialType:"api_key",toolFactory:a=>ax({accessToken:a}),operations:aw},"airtable-oauth":{credentialType:"airtable-oauth",toolFactory:a=>aL({accessToken:a}),toolFactoryWithResolver:a=>aL({getAccessToken:a}),operations:aK},airtable:{credentialType:"api_key",toolFactory:a=>aL({accessToken:a}),operations:aK},firecrawl:{credentialType:"api_key",toolFactory:a=>(function(a){var b;if(!a.accessToken)throw Error("FirecrawlAdapterOptions: accessToken must be a non-empty string.");let c=(b=a.accessToken,new cM.FirecrawlClient({apiKey:b}));return[{name:"firecrawl_scrape",description:"Scrape a single web page and return its content. Supports markdown (default), raw HTML, and extracted links.",inputSchema:cQ,riskLevel:"read",async execute(a){try{let b=await c.scrape(a.url,{formats:a.formats}),d=cP(b.markdown),e=cP(b.html);return{url:a.url,...void 0!==d.content&&{markdown:d.content},...void 0!==e.content&&{html:e.content},...void 0!==b.links&&{links:b.links},truncated:d.truncated||e.truncated}}catch(a){throw cO(a)}}},{name:"firecrawl_crawl_start",description:"Start an async crawl job for a website. Returns a job ID. Use firecrawl_crawl_status to poll for results.",inputSchema:cT,riskLevel:"read",async execute(a){try{let b=await c.startCrawl(a.url,{...void 0!==a.limit&&{limit:a.limit}});return{id:b.id,url:b.url}}catch(a){throw cO(a)}}},{name:"firecrawl_crawl_status",description:'Get the current status and partial results of a Firecrawl crawl job. Poll this until status is "completed", "failed", or "cancelled".',inputSchema:cU,riskLevel:"read",async execute(a){try{let b=await c.getCrawlStatus(a.id);return{id:b.id,status:b.status,total:b.total,completed:b.completed,data:(b.data??[]).map(a=>{let b=cP(a.markdown),c=cP(a.html);return{...a.metadata?.url!==void 0&&{url:a.metadata.url},...void 0!==b.content&&{markdown:b.content},...void 0!==c.content&&{html:c.content},truncated:b.truncated||c.truncated}})}}catch(a){throw cO(a)}}},{name:"firecrawl_map",description:"Discover all URLs on a website (sitemap-aware). Returns a list of links with optional titles and descriptions. Use the search param to filter results.",inputSchema:cR,riskLevel:"read",async execute(a){try{return{links:((await c.map(a.url,{...void 0!==a.search&&{search:a.search}})).links??[]).map(a=>({url:a.url,...void 0!==a.title&&{title:a.title},...void 0!==a.description&&{description:a.description}}))}}catch(a){throw cO(a)}}},{name:"firecrawl_search",description:"Search the web via Firecrawl and return a list of web results (URL, title, description).",inputSchema:cS,riskLevel:"read",async execute(a){try{return{results:((await c.search(a.query,{...void 0!==a.limit&&{limit:a.limit}})).web??[]).map(a=>({url:a.url??"",...void 0!==a.title&&{title:a.title},...void 0!==a.description&&{description:a.description}}))}}catch(a){throw cO(a)}}}]})({accessToken:a}),operations:[{slug:"firecrawl_scrape",name:"Scrape page",risk:"read",requiresApproval:!1,description:"Scrape a single URL and return its content as markdown, HTML, and/or links."},{slug:"firecrawl_crawl_start",name:"Start crawl",risk:"read",requiresApproval:!1,description:"Start an async crawl job for a site. Returns a job ID to poll with firecrawl_crawl_status."},{slug:"firecrawl_crawl_status",name:"Get crawl status",risk:"read",requiresApproval:!1,description:"Poll the status and partial results of a Firecrawl crawl job by its ID."},{slug:"firecrawl_map",name:"Map site",risk:"read",requiresApproval:!1,description:"Discover all URLs on a site (sitemap-aware). Optionally filter by a search term."},{slug:"firecrawl_search",name:"Search web",risk:"read",requiresApproval:!1,description:"Search the web via Firecrawl and return structured results."}]},apify:{credentialType:"api_key",toolFactory:a=>(function(a){var b;if(!a.accessToken)throw Error("ApifyAdapterOptions: accessToken must be a non-empty string.");let d=(b=a.accessToken,new cV.ApifyClient({token:b}));return[{name:"apify_web_browse",description:"Scrape a web page or run a web search and get the content back in ONE call (synchronous — no polling). Pass a URL to scrape that page, or search terms to get the top results. Use this as the DEFAULT web tool. Consumes a small amount of Apify credits per call.",inputSchema:cX,riskLevel:"read",async execute(a){try{let b=await d.actor("apify/rag-web-browser").call({query:a.query,outputFormats:["text"],maxResults:a.maxResults??3}),c=((await d.dataset(b.defaultDatasetId).listItems({clean:!0})).items??[]).map(cZ).filter(a=>a.content);return{query:a.query,count:c.length,results:c}}catch(a){throw(0,cW.G)(a)}}},{name:"apify_get_run",description:"Retrieve metadata for an Apify actor run by its run ID. Returns status, actor ID, dataset ID, and timestamps.",inputSchema:c_,riskLevel:"read",async execute(a){try{let b=await d.run(a.runId).get();if(!b){let{ApifyApiError:b}=await Promise.resolve().then(c.bind(c,99740));throw new b("apify_not_found",`Run ${a.runId} not found`,404)}return{id:b.id,actId:b.actId,status:b.status,startedAt:b.startedAt?b.startedAt.toISOString():null,finishedAt:b.finishedAt?b.finishedAt.toISOString():null,defaultDatasetId:b.defaultDatasetId,defaultKeyValueStoreId:b.defaultKeyValueStoreId}}catch(a){throw(0,cW.G)(a)}}},{name:"apify_list_datasets",description:"List datasets in the user's Apify account. Returns dataset IDs and names needed for apify_get_dataset_items.",inputSchema:c0,riskLevel:"read",async execute(a){try{let b=await d.datasets().list({limit:a.limit??100,offset:a.offset??0});return{datasets:b.items.map(a=>({id:a.id,name:a.name??null,itemCount:a.itemCount??0,createdAt:a.createdAt.toISOString(),modifiedAt:a.modifiedAt.toISOString()})),total:b.total,count:b.count,offset:b.offset}}catch(a){throw(0,cW.G)(a)}}},{name:"apify_get_dataset_items",description:"Retrieve items from an Apify dataset. Use the datasetId returned by apify_run_actor or from apify_list_datasets. Supports limit/offset pagination (max 1000 items per call).",inputSchema:c1,riskLevel:"read",async execute(a){try{let b=await d.dataset(a.datasetId).listItems({limit:a.limit??100,offset:a.offset??0});return{items:b.items,total:b.total,count:b.count,offset:b.offset}}catch(a){throw(0,cW.G)(a)}}},{name:"apify_run_actor",description:"Start an Apify actor run and wait for it to finish (blocking, bounded — default 30 min, override with waitSecs). Returns the run ID, output dataset ID, and final status (which may still be RUNNING if the wait elapsed first). This tool consumes Apify platform credits — use apify_get_dataset_items to retrieve results after the run succeeds.",inputSchema:c$,riskLevel:"write",async execute(a){try{let b=await d.actor(a.actorId).call(a.input,{waitSecs:a.waitSecs??1800});return{runId:b.id,datasetId:b.defaultDatasetId,status:b.status}}catch(a){throw(0,cW.G)(a)}}}]})({accessToken:a}),operations:[{slug:"apify_run_actor",name:"Run actor",risk:"write",requiresApproval:!1,description:"Start an Apify actor run and wait for it to finish. Consumes Apify platform credits."},{slug:"apify_web_browse",name:"Web browse",risk:"read",requiresApproval:!1,description:"Scrape a web page or run a web search and get the content back in one synchronous call (no polling). Consumes a small amount of Apify credits."},{slug:"apify_get_run",name:"Get run",risk:"read",requiresApproval:!1,description:"Retrieve metadata for an Apify actor run by its run ID."},{slug:"apify_list_datasets",name:"List datasets",risk:"read",requiresApproval:!1,description:"List datasets in the user's Apify account with optional pagination."},{slug:"apify_get_dataset_items",name:"Get dataset items",risk:"read",requiresApproval:!1,description:"Retrieve items from an Apify dataset. Supports limit and offset pagination."}]},tavily:{credentialType:"api_key",toolFactory:a=>(function(a){var b;let c;if(!a.accessToken)throw Error("TavilyAdapterOptions: accessToken must be a non-empty string.");let d=(b=a.accessToken,c=(0,c2.tavily)({apiKey:b}),{search:(a,b)=>c.search(a,b),extract:(a,b)=>c.extract(a,b),crawl:(a,b)=>c.crawl(a,b)});return[{name:"tavily_search",description:'Search the web using Tavily. Returns ranked results with titles, URLs, content snippets, and relevance scores. Use topic="news" for current events.',inputSchema:c6,riskLevel:"read",async execute(a,b){try{let b=await d.search(a.query,{searchDepth:a.searchDepth??"basic",maxResults:a.maxResults??5,includeImages:a.includeImages??!1,topic:a.topic??"general"});return{query:b.query,answer:b.answer,results:(b.results??[]).map(a=>{let b=c5(a.content);return{title:a.title,url:a.url,content:b.content,score:a.score,publishedDate:a.publishedDate,truncated:b.truncated}}),images:(b.images??[]).map(a=>({url:a.url,description:a.description})),responseTime:b.responseTime}}catch(a){throw c4(a)}}},{name:"tavily_extract",description:"Extract the full text content from one or more URLs (max 20). Returns the raw content of each page and a list of URLs that failed to extract.",inputSchema:c7,riskLevel:"read",async execute(a,b){try{let b=await d.extract(a.urls,{extractDepth:a.extractDepth??"basic"});return{results:(b.results??[]).map(a=>{let b=c5(a.rawContent);return{url:a.url,title:a.title,rawContent:b.content,truncated:b.truncated}}),failedResults:(b.failedResults??[]).map(a=>({url:a.url,error:a.error})),responseTime:b.responseTime}}catch(a){throw c4(a)}}},{name:"tavily_crawl",description:"Crawl from a seed URL and return scraped content for all reachable pages up to a depth and page limit. Useful for comprehensive site content extraction.",inputSchema:c8,riskLevel:"read",async execute(a,b){try{let b=await d.crawl(a.url,{maxDepth:a.maxDepth??1,limit:a.limit??10});return{baseUrl:b.baseUrl,results:(b.results??[]).map(a=>{let b=c5(a.rawContent);return{url:a.url,rawContent:b.content,truncated:b.truncated}}),responseTime:b.responseTime}}catch(a){throw c4(a)}}}]})({accessToken:a}),operations:[{slug:"tavily_search",name:"Web search",risk:"read",requiresApproval:!1,description:"Search the web using Tavily. Returns ranked results with titles, URLs, and content snippets."},{slug:"tavily_extract",name:"Extract content",risk:"read",requiresApproval:!1,description:"Extract the full text content from one or more URLs (max 20)."},{slug:"tavily_crawl",name:"Crawl site",risk:"read",requiresApproval:!1,description:"Crawl from a seed URL and return scraped content for all reachable pages up to a depth and limit."}]},poyo:{credentialType:"api_key",toolFactory:a=>(function(a){if(!a.accessToken)throw Error("PoyoAdapterOptions: accessToken must be a non-empty string.");return[function(a,b=dd){return{name:"poyo_generate_image",description:"Generate an image from a text prompt using Poyo. Submits the job, waits for it to finish, and returns the resulting image URL(s). Use `model` to pick a Poyo image model (default gpt-4o-image) and `size` for the aspect ratio.",inputSchema:de,riskLevel:"write",async execute(c,d){let e=c.model??"gpt-4o-image";try{let d=await a.submit(e,{prompt:c.prompt,size:c.size??"1:1"});for(let c=0;c<b.maxAttempts;c++){let c=await a.status(d);if("finished"===c.status)return{taskId:d,status:"finished",images:c.files.map(a=>a.url),model:e};if("failed"===c.status)throw new c9("poyo_generation_failed",`Poyo generation failed for task ${d}.`);await df(b.intervalMs)}return{taskId:d,status:"running",images:[],model:e,note:`Still processing after ${b.maxAttempts} checks; the task can be polled again later with this task id.`}}catch(a){throw a instanceof c9?a:a instanceof Error?new c9("poyo_unknown",a.message):new c9("poyo_unknown",String(a))}}}}(function(a,b={}){let c=b.baseUrl??"https://api.poyo.ai",d=b.fetchImpl??fetch,e=b.timeoutMs??3e4,f={Authorization:`Bearer ${a}`};return{async submit(a,b){let g=await db(d,`${c}/api/generate/submit`,{method:"POST",headers:{...f,"Content-Type":"application/json"},body:JSON.stringify({model:a,input:b})},e);if(!g.ok)throw da(g.status,await dc(g));let h=await g.json(),i=h?.data?.task_id??h?.task_id;if("string"!=typeof i||0===i.length)throw new c9("poyo_unknown","Poyo submit response did not include a task_id.");return i},async status(a){let b=await db(d,`${c}/api/generate/status/${encodeURIComponent(a)}`,{method:"GET",headers:{...f}},e);if(!b.ok)throw da(b.status,await dc(b));let g=await b.json(),h=g?.data??{},i=Array.isArray(h.files)?h.files.filter(a=>"string"==typeof a?.file_url).map(a=>({url:a.file_url,type:"string"==typeof a.file_type?a.file_type:"image"})):[];return{status:"string"==typeof h.status?h.status:"unknown",progress:"number"==typeof h.progress?h.progress:0,files:i}}}}(a.accessToken))]})({accessToken:a}),operations:[{slug:"poyo_generate_image",name:"Generate image",risk:"write",requiresApproval:!1,description:"Generate an image from a text prompt using Poyo. Submits the job, waits for it to finish, and returns the resulting image URL(s)."}]}};async function dh(a,b){var c;let d=await b.select({subAgentId:p.Qj.subAgentId,instructions:p.Qj.instructions,agentName:p.X6.name,agentSlug:p.X6.slug,agentRole:p.X6.role,agentActive:p.X6.active,agentPersonality:p.X6.personality,agentModel:p.X6.model}).from(p.Qj).innerJoin(p.X6,(0,p.eq)(p.Qj.subAgentId,p.X6.id)).where((0,p.Uo)((0,p.eq)(p.Qj.orchestratorId,a),(0,p.eq)(p.X6.active,!0)));if(0===d.length)return"";let e=(await b.select({role:p.X6.role,orchestratorMode:p.X6.orchestratorMode}).from(p.X6).where((0,p.eq)(p.X6.id,a)).limit(1))[0];if(!e)return"";let f=d.map(a=>({role:a.agentRole})),g=(c={role:e.role,orchestratorMode:e.orchestratorMode},"orchestrator"!==c.role?"worker":"router"===c.orchestratorMode?"router":"planner"===c.orchestratorMode?"planner":0===f.length?"worker":f.some(a=>"orchestrator"===a.role)?"router":"planner"),h=d.map(a=>a.subAgentId),i=await Promise.all(h.map(a=>b.select({agentId:p.$m.agentId,skillName:p.eK.name,skillSlug:p.eK.slug,skillDescription:p.eK.description}).from(p.$m).innerJoin(p.eK,(0,p.eq)(p.$m.skillId,p.eK.id)).where((0,p.eq)(p.$m.agentId,a)))),j=new Map;for(let a of i)for(let b of a){let a=j.get(b.agentId)??[];a.push({name:b.skillName,desc:b.skillDescription}),j.set(b.agentId,a)}let k=await Promise.all(h.map(a=>b.select({agentId:p.XT.agentId,slug:p.tK.slug,enabledOperations:p.XT.enabledOperations}).from(p.XT).innerJoin(p.tK,(0,p.eq)(p.tK.id,p.XT.connectorId)).where((0,p.eq)(p.XT.agentId,a)))),l=new Map;for(let a of k)for(let b of a){let a=dg[b.slug];if(!a)continue;let c=a.operations.map(a=>a.slug),d=null===b.enabledOperations?c:c.filter(a=>b.enabledOperations.includes(a));if(0===d.length)continue;let e=l.get(b.agentId)??[];e.push({slug:b.slug,toolNames:d}),l.set(b.agentId,e)}let m=await Promise.all(h.map(a=>b.select({agentId:p.oS.agentId,serverSlug:p.h_.slug,enabledTools:p.oS.enabledTools,availableTools:p.h_.availableTools,serverActive:p.h_.active}).from(p.oS).innerJoin(p.h_,(0,p.eq)(p.h_.id,p.oS.mcpServerId)).where((0,p.eq)(p.oS.agentId,a)))),n=new Map;for(let a of m)for(let b of a){if(!1===b.serverActive)continue;let a=b.serverSlug.replace(/-/g,"_"),c=Array.isArray(b.availableTools)?b.availableTools.map(a=>a&&"string"==typeof a.name?a.name:null).filter(a=>null!==a):[];if(0===c.length)continue;let d=Array.isArray(b.enabledTools)?new Set(b.enabledTools.filter(a=>"string"==typeof a)):null,e=null===d?c:c.filter(a=>d.has(a));if(0===e.length)continue;let f=e.map(b=>`${a}__${b}`),g=n.get(b.agentId)??[];g.push({slug:b.serverSlug,toolNames:f}),n.set(b.agentId,g)}let o=[];for(let a of(o.push("## Your team\n"),o.push("You orchestrate the agents below. You have TWO ways to delegate — choose the one that fits the request:\n"),o.push("- **`assign_<agent>` — one delegation, in-line.** Hand the request (or a single step of it) to ONE agent and get its result back before continuing. Use this for a single delegation, or when the next step depends on this one’s result (reactive / sequential work). Only one assignment per turn; after the agent returns, either finish with `return_result` or assign the next step. Do NOT delegate again unless the request needs another step."),o.push("- **`create_task` — parallel fan-out.** Create several INDEPENDENT tasks at once, each `assigned_to` an agent by its handle. They run concurrently in the background and their results are compiled and delivered automatically once all finish. Use this when the pieces of work do not depend on each other and can run in parallel. Use `depends_on` to order tasks that must run in sequence within the board. After creating the tasks, end your turn with a brief `return_result` acknowledgment — the task board runs them, so do NOT call `list_tasks` to wait (only use it to fetch a task ID for a `depends_on` reference).\n"),o.push('⚠️ THE FINAL SUMMARY TO THE USER IS AUTOMATIC — NEVER MAKE IT A TASK. Once the work tasks finish, the system composes a short summary of the whole run and sends it to the user on their original channel by itself. So even when the user says "puis fais une synth\xe8se et envoie-la moi" / "then summarize and send it to me", that final summarize-and-send step is ALREADY handled — do NOT turn it into a task and do NOT add a `depends_on` "synth\xe8se"/"summary"/"→ Telegram" task. Creating one produces a DUPLICATE and an extra useless run. Create ONLY the real work tasks, then `return_result`. If the user wants a long deliverable (a file, an Obsidian note, an email, an HTML page), make a work task that PRODUCES that artifact — but the chat reply itself is never a task.\n'),o.push("Pick ONE style per request — do not mix them in the same job. "+("router"===g?"Default lean: this team includes sub-orchestrators, so in-line `assign_*` delegation is usually the right call — reach for `create_task` only when you have genuinely independent work to run in parallel.":"Default lean: this team is independent workers, so `create_task` parallel fan-out is usually the right call for multi-part work — use `assign_*` when a single agent can handle the whole request or when steps depend on each other.")+"\n"),o.push("Your agents:"),d)){let{subAgentId:b,agentName:c,agentSlug:d,agentRole:e,instructions:f,agentPersonality:g,agentModel:h}=a,i=d.replace(/-/g,"_"),k=function(a,b=240){if(!a)return"";let c=(a.split(/\n\s*\n|\n#/)[0]??"").replace(/[*_`#>-]/g," ").replace(/\s+/g," ").trim();if(!c)return"";if(c.length<=b)return c;let d=c.slice(0,b),e=Math.max(d.lastIndexOf(". "),d.lastIndexOf("! "));return(e>60?d.slice(0,e+1):d.trimEnd()+"…").trim()}(g),m=k?`
21
+ Purpose: ${k}`:"",p=(0,y.FM)(h??"")?"\n LLM: can see images (vision) — route image tasks here":"",q=j.get(b)??[],r=q.length>0?`
22
+ Skills (what it can do): ${q.map(a=>{let b=a.desc?a.desc.replace(/\s+/g," ").trim():"",c=b.length>140?`${b.slice(0,139).trimEnd()}…`:b;return c?`${a.name} — ${c}`:a.name}).join("; ")}`:"",s=function(a){let b=l.get(a),c=n.get(a),d=[];return(b&&d.push(...b.map(a=>a.slug)),c&&d.push(...c.map(a=>a.slug)),0===d.length)?"":`
19
23
  Connectors: ${[...new Set(d)].join(", ")}`}(b),t="orchestrator"===e?" (orchestrator)":"",u=f?`
20
- Instructions: ${f}`:"";p.push(`- **${c}**${t} — assign tool \`assign_${i}\`, task handle \`${d}\`${m}${n}${r}${s}${u}`)}return p.push("\n⚠️ The roster above is the COMPLETE, GROUND-TRUTH list of your team and their capabilities. ONLY ever reference agents, skills, connectors, or tools that appear above — NEVER invent a teammate or a capability. Before saying you cannot do something, scan the list: if any agent’s skills/connectors match the request, delegate to it. If genuinely none match, say so plainly (and how the user could enable it, if you know) — do NOT fabricate an agent name or claim a tool you were not given."),p.join("\n")}g.Ik({task:g.Yj().describe("What this agent should do. Be specific and complete."),data:g.Yj().optional().describe("Data from a previous step to pass to this agent (e.g. spreadsheet content, search results).")}),g.Ik({title:g.Yj().max(200).describe("Short title for this task (max 200 chars)."),description:g.Yj().max(2e3).optional().describe("Detailed description of what to do."),assigned_to:g.Yj().describe("Slug of the agent to assign this task to."),priority:g.k5(["low","medium","high"]).optional().describe("Task priority (default: medium)."),depends_on:g.YO(g.Yj()).optional().describe("Array of task IDs that must complete before this task starts. Use list_tasks to get IDs."),context:g.g1(g.Yj(),g.L5()).optional().describe("Additional context key/value pairs.")}),g.Ik({status:g.k5(["todo","in_progress","done","cancelled","blocked"]).optional().describe("Filter by status. Omit to list all tasks for this job.")});var c7=c(95615);function c8(a){return{specificationVersion:"v3",wrapGenerate:async({doGenerate:b})=>{let c;try{c=await b()}catch(b){if(b instanceof c7.hL&&"Invalid JSON response"===b.message&&"string"==typeof b.responseBody&&b.responseBody.length>0){let c=function(a,b){let c;try{c=JSON.parse(a)}catch{return null}let d=function(a){if("object"!=typeof a||null===a)return null;let b=a.choices;if(!Array.isArray(b)||0===b.length)return null;let c=b[0];if("object"!=typeof c||null===c)return null;let d=c.message;if("object"!=typeof d||null===d)return null;let e=d.content;return"string"==typeof e?e:null}(c);if(!d)return null;let{text:e,toolCalls:f}=b(d);if(0===f.length)return null;let g=[];return e.length>0&&g.push({type:"text",text:e}),g.push(...f),{content:g,finishReason:{unified:"tool-calls",raw:"tool-calls"},usage:function(a){let b={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}};if("object"!=typeof a||null===a)return b;let c=a.usage;if("object"!=typeof c||null===c)return b;let d="number"==typeof c.prompt_tokens?c.prompt_tokens:void 0,e="number"==typeof c.completion_tokens?c.completion_tokens:void 0;return{inputTokens:{total:d,noCache:d,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e,text:e,reasoning:void 0}}}(c),warnings:[{type:"other",message:"Recovered tool calls from native model format after provider returned non-OpenAI-compatible JSON"}]}}(b.responseBody,a);if(c)return c}throw b}if(c.content.some(a=>"tool-call"===a.type))return c;let d=c.content.filter(a=>"text"===a.type).map(a=>a.text).join("");if(0===d.length)return c;let e=a(d);if(0===e.toolCalls.length)return c;let f=c.content.filter(a=>"text"!==a.type),g=[];return e.text.length>0&&g.push({type:"text",text:e.text}),g.push(...e.toolCalls),g.push(...f),{...c,content:g,finishReason:{unified:"tool-calls",raw:"tool-calls"}}},wrapStream:async()=>{throw new c7.b8({functionality:"streamText with text-based tool-call parsing middleware"})}}}let c9=["<|tool_calls_section_begin|>","<|tool_call_section_begin|>"],da=/<\|tool_call_begin\|>\s*([^<]+:\d+)\s*<\|tool_call_argument_begin\|>\s*((?:(?!<\|tool_call_begin\|>)[\s\S])*?)\s*<\|tool_call_end\|>/g,db=/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;c8(a=>{let b;if(!c9.some(b=>a.includes(b)))return{text:a,toolCalls:[]};let c=[];for(da.lastIndex=0;null!==(b=da.exec(a));){let a=b[1]?.trim(),d=b[2]?.trim();if(!a)continue;let e=(a.split(":")[0]??"").split(".").pop()??"";0!==e.length&&c.push({type:"tool-call",toolCallId:a,toolName:e,input:d&&d.length>0?d:"{}"})}if(0===c.length)return{text:a,toolCalls:[]};let d=a.length;for(let b of c9){let c=a.indexOf(b);c>=0&&c<d&&(d=c)}return{text:d>0?a.slice(0,d).trim():"",toolCalls:c}}),c8(a=>{let b;if(!a.includes("<tool_call>"))return{text:a,toolCalls:[]};let c=[];for(db.lastIndex=0;null!==(b=db.exec(a));){let a,d=b[1]?.trim();if(!d)continue;try{a=JSON.parse(d)}catch{continue}if("string"!=typeof a.name||0===a.name.length)continue;let e=void 0===a.arguments?"{}":"string"==typeof a.arguments?a.arguments:JSON.stringify(a.arguments);c.push({type:"tool-call",toolCallId:`call_${(0,l.randomUUID)().replace(/-/g,"").slice(0,16)}`,toolName:a.name,input:e})}if(0===c.length)return{text:a,toolCalls:[]};let d=a.indexOf("<tool_call>");return{text:d>0?a.slice(0,d).trim():"",toolCalls:c}}),(()=>{let a=process.env.LLM_TIMEOUT_MS;if(a)return Number.isFinite(Number(a))})(),(()=>{let a=process.env.LLM_TIMEOUT_RETRIES;if(a)return Number.isFinite(Number(a))})(),(()=>{let a=process.env.LLM_STALE_RETRY_TIMEOUT_MS;if(a)return Number.isFinite(Number(a))})(),g.Ik({status:g.k5(["success","blocked"]),reason:g.Yj().optional()}),g.Ik({fact:g.Yj().min(1).describe("The durable fact to remember, stated as an assertion not a narrative."),category:g.k5(v.BJ),importance:g.ai().int().min(1).max(5).optional().default(3).describe("1-5. Use 4-5 only for facts that affect how future agents operate."),skill_tags:g.YO(g.Yj().max(60)).max(20).optional().describe("Optional skill slugs this memory is associated with.")}),g.Ik({query:g.Yj().min(1).optional().describe("Optional free-text search. When set, memories are ranked by keyword match. Omit to list recent/important memories instead."),skill_tags:g.YO(g.Yj().max(60)).optional().describe("Optional skill slugs to filter memories by. Returns all non-archived memories for this entity if omitted."),sort:g.k5(["importance","recent"]).optional().describe("Result ordering: 'importance' (default) or 'recent'."),limit:g.ai().int().min(1).max(200).optional().describe("Max rows to return. Default 50.")}),g.Ik({query:g.Yj().min(2).max(200).describe('Keywords to find in past jobs/conversations of this workspace (their task, replies, and tool output). E.g. "z_image workflow port", "Airtable base id", "email sent to the client".'),limit:g.ai().int().min(1).max(20).optional().describe("Max results to return. Default 6.")}),g.Ik({fact_substring:g.Yj().min(3).describe("A unique substring of the memory fact to mark helpful. Quote a few distinctive words from the fact text shown in the Persistent memory block. Min 3 chars.")}),g.Ik({fact_substring:g.Yj().min(3).describe("A unique substring of the outdated memory fact. Quote distinctive words from the Persistent memory block. Min 3 chars."),reason:g.Yj().max(500).optional().describe("Brief justification for marking outdated — surfaces in the dashboard for the user.")}),g.Ik({query:g.Yj().min(1).describe("The search query.")});g.Ik({text:g.Yj().min(1).max(5e4).describe("The text to display as this job's result in the dashboard. Markdown supported. Stored in agent_jobs.result.")});g.Ik({path:g.Yj().min(1).describe("Path to the file, relative to the agent workspace root. Absolute paths are accepted but must resolve under the workspace."),offset:g.ai().int().min(0).optional().describe("1-based line number to start at. Default 1."),limit:g.ai().int().min(1).max(2e3).optional().describe("Max number of lines to return. Default 500.")}),g.Ik({path:g.Yj().min(1).describe("Path to the file, relative to the agent workspace root. Created if missing."),content:g.Yj().describe("Full file contents to write. Overwrites any existing file."),create_dirs:g.zM().optional().default(!1).describe("If true, create missing parent directories.")}),g.Ik({path:g.Yj().min(1).describe("Path to an existing file, relative to the workspace root."),old_string:g.Yj().min(1).describe("Exact substring to replace. Must appear in the file verbatim — whitespace and line endings count. Must be unique unless replace_all:true."),new_string:g.Yj().describe('Replacement text. Pass "" to delete the matched substring.'),replace_all:g.zM().optional().default(!1).describe("Replace every occurrence (default false: require exactly one match).")}),g.Ik({path:g.Yj().optional().describe('Directory path relative to a workspace. For a single-workspace agent, the label prefix is optional (e.g. "subdir/"). For multi-workspace agents, prefix with the workspace label (e.g. "notes/subdir/"). Omit entirely to list workspaces at the top level.'),glob:g.Yj().optional().describe('Optional glob to filter results (e.g. "*.md", "**/*.ts"). Matched against the name for non-recursive, against the relative path for recursive (** prefix).'),recursive:g.zM().optional().default(!1).describe("Walk subdirectories. Default false.")}),g.Ik({pattern:g.Yj().min(1).describe("Regex pattern to search for."),target:g.k5(["files","content"]).optional().default("content").describe('"files" matches the pattern against file paths (filename search). "content" scans each file body (grep-like). Default "content".'),path:g.Yj().optional().describe('Subdirectory to search. For multi-workspace agents, prefix with the workspace label (e.g. "notes/subdir"). Without a label, all workspaces are searched.'),file_glob:g.Yj().optional().describe('Restrict content search to files matching this glob (e.g. "*.md").'),case_sensitive:g.zM().optional().default(!1).describe("Default false — pattern is matched case-insensitively."),max_results:g.ai().int().min(1).max(500).optional().default(100).describe("Cap on matches returned. Narrow `path` or `file_glob` if you hit it.")});g.Ik({path:g.Yj().min(1).describe('Workspace-relative path to the .xlsx file. For multi-workspace agents, prefix with the workspace label (e.g. "docs/report.xlsx").'),sheet:g.Yj().optional().describe("Worksheet name. Defaults to the first sheet if omitted."),max_rows:g.ai().int().positive().optional().default(200).describe("Maximum rows to return per sheet. Default 200.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),cell:g.Yj().min(1).describe('Cell address in A1 notation (e.g. "B3"). Column letter(s) then row number.'),value:g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]).describe('New cell value. Strings starting with "=" are treated as formulae. null clears the cell.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),start_cell:g.Yj().min(1).describe('Top-left cell of the range in A1 notation (e.g. "B2"). The range expands to fit values[][].)'),values:g.YO(g.YO(g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]))).describe('Row-major 2-D array of values. values[0] = first row, values[0][0] = start_cell. null entries clear the corresponding cell. Strings starting with "=" are formulae.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),rows:g.YO(g.YO(g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]))).describe('Rows to append after the last populated row. Each entry is a cell value. null clears the cell. Strings starting with "=" are formulae.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),name:g.Yj().min(1).describe("Name of the new worksheet.")}),g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .xlsx file (e.g. "reports/q1.xlsx").'),sheet:g.Yj().optional().default("Sheet1").describe('Name of the first worksheet. Defaults to "Sheet1".'),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),start_row:g.ai().int().positive().describe("1-indexed row number of the first row to delete."),count:g.ai().int().positive().describe("Number of rows to delete.")}),c(96376),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .docx file. For multi-workspace agents, prefix with the workspace label.")});let dc=g.Ik({text:g.Yj().describe("Paragraph text content."),heading:g.ai().int().min(1).max(6).optional().describe("Heading level (1-6). Omit for normal paragraph."),bold:g.zM().optional().describe("Bold text."),italic:g.zM().optional().describe("Italic text.")});g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .docx file (e.g. "docs/report.docx").'),paragraphs:g.YO(dc).describe("Paragraphs to include in the document, in order."),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the existing .docx file to append to."),paragraphs:g.YO(dc).describe("New paragraphs to append after the existing content.")}),c(97183),c(5597),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .pptx file. For multi-workspace agents, prefix with the workspace label.")});let dd=g.Ik({title:g.Yj().optional().describe("Slide title text."),bullets:g.YO(g.Yj()).optional().describe("Bullet point lines displayed below the title."),body:g.Yj().optional().describe("Free-form text body (used instead of bullets if both provided, bullets win)."),image_path:g.Yj().optional().describe("Workspace-relative path to an image file (PNG/JPEG/GIF) to embed on the slide. The path goes through the workspace security guard.")});g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .pptx file (e.g. "presentations/deck.pptx").'),slides:g.YO(dd).min(1).describe("Array of slides to include in the presentation, in order."),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")});g.Ik({slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe('URL-safe identifier for the skill (e.g. "customer-support-v2").'),name:g.Yj().min(1).describe("Human-readable display name for the skill."),content:g.Yj().min(1).describe("The skill instructions injected into the agent system prompt when assigned."),description:g.Yj().optional().describe("Optional short description of what the skill does.")}),g.Ik({skillSlug:g.Yj().min(1).describe("The slug OR name of the skill to update."),name:g.Yj().min(1).optional().describe("New display name (optional)."),description:g.Yj().optional().describe("New short description (optional)."),content:g.Yj().min(1).optional().describe("New skill instructions, replacing the current ones (optional)."),active:g.zM().optional().describe("Enable (true) or disable (false) the skill (optional).")}),g.Ik({skillSlug:g.Yj().min(1).describe('The slug OR name of the skill to assign (e.g. "customer-support-v2").'),agentSlug:g.Yj().min(1).describe("The slug OR name of the agent to assign the skill to.")}),g.Ik({slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe('URL-safe identifier for the agent (e.g. "support-bot").'),name:g.Yj().min(1).describe("Human-readable display name for the agent."),personality:g.Yj().min(1).describe("System prompt / personality instructions for the agent."),model:g.Yj().min(1).describe('LLM model identifier (e.g. "claude-sonnet-4-6-20260217").'),role:g.k5(["worker","router","planner"]).describe("Agent role: worker = standard task-running agent; router = orchestrator that routes to sub-agents; planner = orchestrator that plans and delegates."),subAgentSlugs:g.YO(g.Yj().min(1)).optional().describe("Slugs of existing agents to assign as sub-agents (for router/planner roles). Optional.")}),g.Ik({slug:g.Yj().min(1).describe('Slug of the existing agent to edit (e.g. "java").'),model:g.Yj().min(1).optional().describe("New LLM model id. Must be valid for the agent's provider — call list_models first to get the exact id."),personality:g.Yj().min(1).optional().describe("New system prompt / personality for the agent."),name:g.Yj().min(1).optional().describe("New human-readable display name.")}),g.Ik({agentSlug:g.Yj().min(1).describe("The slug OR name of an existing agent to assign as your sub-agent.")}),g.Ik({name:g.Yj().min(1).describe("Human-readable display name for the MCP server."),slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe("URL-safe identifier; also the tool-name prefix. Must be unique in this workspace."),transport:g.k5(["http","stdio"]).describe("http = remote Streamable HTTP MCP server; stdio = local subprocess."),url:g.Yj().url().optional().describe("HTTP only: the MCP server endpoint URL."),apiKey:g.Yj().optional().describe("HTTP only: API key/token used to authenticate."),authScheme:g.k5(["header","query","bearer"]).optional().describe("HTTP only: how the key is sent — header, query param, or bearer. Defaults to header."),authParamName:g.Yj().optional().describe("HTTP only: the header or query-param name carrying the key (ignored for bearer)."),command:g.Yj().optional().describe("stdio only: the executable to spawn."),args:g.YO(g.Yj()).optional().describe("stdio only: command-line arguments."),env:g.g1(g.Yj(),g.Yj()).optional().describe("stdio only: environment variables for the subprocess (encrypted at rest)."),attachToAgentSlug:g.Yj().optional().describe("Optional: slug/name of an agent to immediately attach this MCP to, so its tools become usable by that agent. Without this, the server is registered but NOT usable by anyone — attach it later with attach_mcp.")}),g.Ik({mcpSlug:g.Yj().min(1).describe('Slug or name of the MCP server to attach (e.g. "my-mcp-server").'),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to give the MCP tools to.")}),g.Ik({slug:g.Yj().min(1).describe('Connector catalog slug — must be a known api_key connector (e.g. "notion", "airtable", "apify", "firecrawl", "tavily").'),name:g.Yj().min(1).describe("Display name for this connector instance."),apiKey:g.Yj().min(1).describe("The provider API key / token (stored encrypted at rest)."),attachToAgentSlug:g.Yj().optional().describe("Optional: slug/name of an agent to immediately attach this connector to, so its tools become usable by that agent. Without this, the connector is registered but NOT usable — attach it later with attach_connector.")}),g.Ik({connectorSlug:g.Yj().min(1).describe('Slug or name of the connector to attach (e.g. "notion").'),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to give the connector tools to.")}),g.Ik({agentSlug:g.Yj().min(1).describe("Slug or name of the sub-agent to remove from your team (un-delegate).")}),g.Ik({skillSlug:g.Yj().min(1).describe("Slug or name of the skill to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the skill from.")}),g.Ik({mcpSlug:g.Yj().min(1).describe("Slug or name of the MCP server to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the MCP from.")}),g.Ik({connectorSlug:g.Yj().min(1).describe("Slug or name of the connector to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the connector from.")});var de=c(54856);let df=g.KC([g.k5(["daily","weekdays","weekends"]),g.YO(g.ai().int().min(0).max(6))]).optional().describe('Which days to run: "daily" (default), "weekdays" (Mon-Fri), "weekends", or an array of day numbers 0=Sun..6=Sat. Only used with atTimes.');g.Ik({agentSlug:g.Yj().min(1).describe("Slug or name of the agent the schedule fires jobs for."),name:g.Yj().min(1).describe("Unique, human-readable name for the schedule."),atTimes:g.YO(g.Yj()).optional().describe('Wall-clock times as "HH:MM" (24h) — e.g. ["09:00","13:00","21:00"]. The tool builds the schedule in the user\'s timezone; you give the hours the user states (no cron, no UTC). Use this for fixed times of day.'),everyMinutes:g.ai().int().optional().describe("For interval schedules: run every N minutes (e.g. 15, 30, 60, 120). Use instead of atTimes."),days:df,task:g.Yj().min(1).describe("The task/instructions the agent runs each time it fires."),notifyOnSuccess:g.zM().optional().describe("If true, the agent confirms to the user on success (default false = runs silently).")}),g.Ik({name:g.Yj().min(1).describe("Name of the existing schedule to edit."),atTimes:g.YO(g.Yj()).optional().describe('New wall-clock times as "HH:MM" — e.g. ["09:00","21:00"]. Rebuilds the schedule.'),everyMinutes:g.ai().int().optional().describe("Switch to an interval: run every N minutes."),days:df,task:g.Yj().min(1).optional().describe("New task/instructions."),newName:g.Yj().min(1).optional().describe("Rename the schedule."),notifyOnSuccess:g.zM().optional().describe("Toggle the success notification.")}),g.Ik({name:g.Yj().min(1).describe("Name of the schedule to pause/resume."),active:g.zM().describe("true = resume (recomputes next run), false = pause.")}),g.Ik({name:g.Yj().min(1).describe("Name of the schedule to run now (see list_schedules).")});g.Ik({skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().min(1).describe("Path to a bundled file, relative to the skill's folder (e.g. 'references/x.md')."),offset:g.ai().int().min(0).optional().describe("1-based line number to start at. Default 1."),limit:g.ai().int().min(1).max(2e3).optional().describe("Max number of lines to return. Default 500.")}),g.Ik({skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().optional().describe("Subfolder to list, relative to the skill's root. Default: the skill root.")}),g.Ik({purpose:g.Yj().min(1).max(400).describe("REQUIRED. A short plain-language explanation, IN THE USER'S LANGUAGE, of what you are writing into the skill and why. Shown FIRST on the approval prompt."),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE impact, if any (overwrites an existing bundled file, changes how the skill behaves). Shown as a ⚠️ warning. OMIT when harmless."),skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().min(1).describe("Path to write, relative to the skill's folder (e.g. 'workflows/my_workflow.json'). Parent folders are created as needed. Must stay inside the skill folder."),content:g.Yj().max(1048576).describe("The full file content to write (UTF-8). Overwrites the file if it already exists.")}),c(31421),g.Ik({purpose:g.Yj().min(1).max(400).describe('REQUIRED. A short plain-language explanation, IN THE USER\'S LANGUAGE, of what this command does and why you are running it. Shown FIRST on the approval prompt so the user can decide WITHOUT reading the raw command. E.g. "Install the Python dependencies for the comfyui skill so I can generate the image."'),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE or destructive impact, if any: deletes/overwrites files, installs software, downloads from the network, spends money, long-running, or otherwise hard to undo. Shown as a ⚠️ warning on the approval prompt. OMIT entirely when the command is harmless / read-only."),command:g.Yj().min(1).max(8e3).describe('The shell command to run. May be a compound command joined with && or newlines (e.g. "npm install && node build.js") — it runs as ONE call. Executed via cmd.exe on Windows and /bin/sh on Unix.'),cwd:g.Yj().max(1e3).optional().describe('Optional working directory, relative to the agent workspace (e.g. "scripts/canvas"). Defaults to the workspace root. Must stay inside the workspace.'),timeout_seconds:g.ai().int().positive().max(1800).optional().describe("Optional timeout in seconds (default 300, max 1800). On timeout the command and its child processes are killed.")}),g.Ik({purpose:g.Yj().min(1).max(400).describe("REQUIRED. A short plain-language explanation, IN THE USER'S LANGUAGE, of what running this script does and why. Shown FIRST on the approval prompt so the user can decide without reading the raw script call."),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE or destructive impact, if any (writes files, installs software, network/GPU use, spends money, long-running). Shown as a ⚠️ warning. OMIT when the script is harmless / read-only."),skill:g.Yj().min(1).describe("Slug of an installed skill you hold and are authorized to run scripts for (e.g. 'comfyui')."),script:g.Yj().min(1).max(1e3).describe("Path to the bundled script, relative to the skill folder (e.g. 'scripts/run_workflow.py'). Discover available scripts with skill_file_list. Only .py / .sh / .js are runnable."),args:g.YO(g.Yj().max(8e3)).max(100).optional().describe('Arguments passed to the script VERBATIM — not shell-interpreted, so they are injection-safe. E.g. ["--workflow", "workflows/sdxl_txt2img.json", "--prompt", "a cat", "--server", "http://127.0.0.1:8188"].'),timeout_seconds:g.ai().int().positive().max(1800).optional().describe("Optional timeout in seconds (default 300, max 1800). On timeout the script and its child processes are killed.")}),g.Ik({slug:g.Yj().min(1).describe('Slug of the skill to read, e.g. "comfyui" or "tool-create-mcp".')});g.Ik({provider:g.Yj().optional().describe('Optional provider key (e.g. "openrouter", "deepseek"). Omit to use the entity\'s active provider.')}),g.Ik({agentSlug:g.Yj().optional().describe("Optional: only schedules for this agent (slug or name). Omit for all schedules.")});let dg=[{name:"return_result",description:'Signal that the task is complete (status="success") or blocked (status="blocked"). For content delivery to the user, use the appropriate delivery tool (`telegram_send_message`, `dashboard_publish`, etc.) — return_result carries no content. Whenever your task involves delivering an answer, emit `return_result` and the delivery tool(s) **in the same assistant turn** (parallel tool calls). The runner handles delivery failures automatically (defers finalization if a sibling tool errors), so there is no need to wait for tool results before signaling completion — splitting into separate turns doubles input token cost (the full conversation replays) for no benefit. Use status="blocked" if you cannot proceed after 2 attempts. When you set status="blocked" you MUST also set `reason` to a clear, user-facing explanation: name the SPECIFIC thing that blocked YOU on THIS task — the exact tool, credential, or input that failed and its actual error — and the concrete next step the user can take. Write it from scratch for this situation; never copy a generic example. The user sees this reason verbatim.'},{name:"skill_view",description:"Load a skill's FULL instructions by slug, on demand. Call this the moment a skill listed in your Skills index is relevant — BEFORE acting — to get its complete guidance, the exact paths of its bundled files (scripts, ready-made workflows/templates), and how to run them. Also loads a tool's usage guide right before you call that tool (e.g. skill_view('tool-create-mcp')). Follow what it returns instead of reimplementing the skill yourself."},{name:"list_models",description:"List the valid model ids for assigning to an agent (curated catalog for the provider). Call this BEFORE create_agent / update_agent and pass the exact modelId it returns — never guess a model string."},{name:"list_schedules",description:'List the cron schedules (automations) in this workspace — name, agent, cron, timezone, active/paused, next & last run. Use it to answer "what are my schedules?" or to find a schedule\'s name before update_schedule / toggle_schedule / run_schedule.'},{name:"save_memory",description:"Save a durable fact to long-term memory. Use the `save_memory` tool whenever (a) the user explicitly asks you to remember, save, or store something, OR (b) you learn a stable preference, rule, or context that will improve future unrelated tasks. Invoke `save_memory` once per fact — multiple invocations if the user gives multiple facts. Skip ephemeral details (today's weather, transient calculation results)."},{name:"query_memory",description:"Read persistent memories shared across all agents in your entity. Use before starting a task to recall relevant context, user preferences, and learned rules — including memories saved by other agents in this same workspace. Pass `query` to search by keywords, or filter by skill_tags for narrower lookups."},{name:"search_history",description:'Search this workspace\'s PAST jobs and conversations by keyword (full-text). Use it to recall what was decided, found, or done before — including by OTHER agents in this workspace (e.g. "what ComfyUI port did we use?", "the brief we wrote last week"). Returns matching past tasks with a highlighted snippet. This is durable recall with no budget limit — reach for it when the answer is likely in past work but not in your injected memory.'},{name:"mark_memory_helpful",description:"Mark a fact from your Persistent memory block as having been helpful in this job. Bumps its importance (capped at 5★) so the memory stays in your auto-injection window over time. Use sparingly — only for facts that materially shaped your answer. Identify the memory by quoting a unique substring from the fact text."},{name:"mark_memory_outdated",description:"Mark a fact from your Persistent memory block as outdated when newer information in the current job contradicts or supersedes it. The memory is archived (not deleted) and dropped from your future auto-injection blocks. Identify the memory by quoting a unique substring from the fact text. Pair with save_memory(new fact) if a replacement is appropriate."},{name:"web_search",description:"Search the web. Uses your configured Tavily/Firecrawl provider if any, otherwise a free best-effort search."},{name:"dashboard_publish",description:"Set this job's RESULT — the agent's substantive output. It becomes agent_jobs.result, shown on /jobs, AND it is the exact text handed to any task that depends on this one and to the run's final delivery. So for a task whose output another step (a synthesis) or the user will consume, put the FULL content here — not a stub like \"see below\". (If you write your answer as your final message text, it is captured automatically; this tool makes it explicit and is required when the dashboard is an intended destination.) For other surfaces, use the corresponding tool (telegram_send_message, etc.).\n\n**Same-response with return_result (CRITICAL for cost & latency)**: Always emit dashboard_publish IN THE SAME response.content array as return_result. Splitting them across consecutive responses re-prompts the LLM unnecessarily and adds latency. Correct: response.content = [{tool-call: dashboard_publish, ...}, {tool-call: return_result, ...}]."},{name:"file_read",description:"Read the contents of a file in the agent workspace. Returns lines with start_line / end_line markers. Use `offset` and `limit` to paginate large files. Files above ~1 MiB MUST be paginated — request smaller chunks. Use `file_search` first if you need to find specific content."},{name:"file_write",description:"Write (or overwrite) a file in the agent workspace. Atomic: writes to a tempfile then renames over the target, so partial-write failures never corrupt the original. Use `file_edit` instead when you only need to change part of an existing file — it preserves lines you do not touch. Max 1 MiB per write."},{name:"file_edit",description:"Edit an existing file by replacing an exact substring. Quote the chunk to change verbatim (including whitespace). Fails loud when the substring is missing (you misquoted) or matches multiple places (ambiguous — narrow the quote, or pass replace_all:true). Use this instead of file_write when you only want to change part of a file — preserves untouched lines."},{name:"file_list",description:'List entries of a directory in the agent workspace(s). With no `path` argument, returns the list of available workspace labels. With a path, lists that directory. For multi-workspace agents, prefix paths with the workspace label (e.g. "notes/subdir"). Returns name, type, size, and modified time per entry. Use `glob` to filter (e.g. "*.md"). Pass `recursive:true` to walk subdirectories. Caps at 500 entries.'},{name:"file_search",description:'Search the agent workspace(s). `target:"files"` matches the regex against file paths. `target:"content"` (default) scans file contents and returns line-level matches. Use `file_glob` to restrict content scans (e.g. "*.md"). For multi-workspace agents, prefix `path` with a workspace label to search only that workspace (e.g. "notes/subdir"), or omit to search all workspaces. Skips .git/node_modules/dist by default.'}];g.Ik({chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID to send to. Omit to reply to the chat that triggered this job."),text:g.Yj().min(1).max(4096).describe("The message text to send.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL (e.g. a ComfyUI /view?filename=... URL). The runner fetches the bytes server-side — do NOT base64-encode the file."),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars, Telegram limit)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL. The runner fetches the bytes server-side — do NOT read the file or base64-encode it."),filename:g.Yj().min(1).max(255).optional().describe('Optional filename the recipient sees (with extension, e.g. "report.md"). Defaults to the name derived from the source path/URL.'),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars, Telegram limit)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL. The runner fetches the bytes server-side — do NOT read the file or base64-encode it."),filename:g.Yj().min(1).max(255).optional().describe("Optional filename the recipient sees (keep the extension). Defaults to the source name."),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")});let dh=[{slug:"obsidian",name:"Obsidian",description:"Read, search, create, and edit notes in the Obsidian vault.",requiredBuiltins:[],content:`Skill for working on an Obsidian vault via the filesystem: read, list, search, create, edit notes, with full mastery of the Obsidian Flavored Markdown syntax.
24
+ Instructions: ${f}`:"";o.push(`- **${c}**${t} — assign tool \`assign_${i}\`, task handle \`${d}\`${m}${p}${r}${s}${u}`)}return o.push("\n⚠️ The roster above is the COMPLETE, GROUND-TRUTH list of your team and their capabilities. ONLY ever reference agents, skills, connectors, or tools that appear above — NEVER invent a teammate or a capability. Before saying you cannot do something, scan the list: if any agent’s skills/connectors match the request, delegate to it. If genuinely none match, say so plainly (and how the user could enable it, if you know) — do NOT fabricate an agent name or claim a tool you were not given."),o.join("\n")}g.Ik({task:g.Yj().describe("What this agent should do. Be specific and complete."),data:g.Yj().optional().describe("Data from a previous step to pass to this agent (e.g. spreadsheet content, search results).")}),g.Ik({title:g.Yj().max(200).describe("Short title for this task (max 200 chars)."),description:g.Yj().max(2e3).optional().describe("Detailed description of what to do."),assigned_to:g.Yj().describe("Slug of the agent to assign this task to."),priority:g.k5(["low","medium","high"]).optional().describe("Task priority (default: medium)."),depends_on:g.YO(g.Yj().uuid()).max(50).optional().describe("Array of task IDs that must complete before this task starts. Use list_tasks to get IDs."),context:g.g1(g.Yj(),g.L5()).optional().describe("Additional context key/value pairs.")}),g.Ik({status:g.k5(["todo","in_progress","done","cancelled","blocked"]).optional().describe("Filter by status. Omit to list all tasks for this job.")});var di=c(95615);function dj(a){return{specificationVersion:"v3",wrapGenerate:async({doGenerate:b})=>{let c;try{c=await b()}catch(b){if(b instanceof di.hL&&"Invalid JSON response"===b.message&&"string"==typeof b.responseBody&&b.responseBody.length>0){let c=function(a,b){let c;try{c=JSON.parse(a)}catch{return null}let d=function(a){if("object"!=typeof a||null===a)return null;let b=a.choices;if(!Array.isArray(b)||0===b.length)return null;let c=b[0];if("object"!=typeof c||null===c)return null;let d=c.message;if("object"!=typeof d||null===d)return null;let e=d.content;return"string"==typeof e?e:null}(c);if(!d)return null;let{text:e,toolCalls:f}=b(d);if(0===f.length)return null;let g=[];return e.length>0&&g.push({type:"text",text:e}),g.push(...f),{content:g,finishReason:{unified:"tool-calls",raw:"tool-calls"},usage:function(a){let b={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}};if("object"!=typeof a||null===a)return b;let c=a.usage;if("object"!=typeof c||null===c)return b;let d="number"==typeof c.prompt_tokens?c.prompt_tokens:void 0,e="number"==typeof c.completion_tokens?c.completion_tokens:void 0;return{inputTokens:{total:d,noCache:d,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e,text:e,reasoning:void 0}}}(c),warnings:[{type:"other",message:"Recovered tool calls from native model format after provider returned non-OpenAI-compatible JSON"}]}}(b.responseBody,a);if(c)return c}throw b}if(c.content.some(a=>"tool-call"===a.type))return c;let d=c.content.filter(a=>"text"===a.type).map(a=>a.text).join("");if(0===d.length)return c;let e=a(d);if(0===e.toolCalls.length)return c;let f=c.content.filter(a=>"text"!==a.type),g=[];return e.text.length>0&&g.push({type:"text",text:e.text}),g.push(...e.toolCalls),g.push(...f),{...c,content:g,finishReason:{unified:"tool-calls",raw:"tool-calls"}}},wrapStream:async()=>{throw new di.b8({functionality:"streamText with text-based tool-call parsing middleware"})}}}let dk=["<|tool_calls_section_begin|>","<|tool_call_section_begin|>"],dl=/<\|tool_call_begin\|>\s*([^<]+:\d+)\s*<\|tool_call_argument_begin\|>\s*((?:(?!<\|tool_call_begin\|>)[\s\S])*?)\s*<\|tool_call_end\|>/g,dm=/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;dj(a=>{let b;if(!dk.some(b=>a.includes(b)))return{text:a,toolCalls:[]};let c=[];for(dl.lastIndex=0;null!==(b=dl.exec(a));){let a=b[1]?.trim(),d=b[2]?.trim();if(!a)continue;let e=(a.split(":")[0]??"").split(".").pop()??"";0!==e.length&&c.push({type:"tool-call",toolCallId:a,toolName:e,input:d&&d.length>0?d:"{}"})}if(0===c.length)return{text:a,toolCalls:[]};let d=a.length;for(let b of dk){let c=a.indexOf(b);c>=0&&c<d&&(d=c)}return{text:d>0?a.slice(0,d).trim():"",toolCalls:c}}),dj(a=>{let b;if(!a.includes("<tool_call>"))return{text:a,toolCalls:[]};let c=[];for(dm.lastIndex=0;null!==(b=dm.exec(a));){let a,d=b[1]?.trim();if(!d)continue;try{a=JSON.parse(d)}catch{continue}if("string"!=typeof a.name||0===a.name.length)continue;let e=void 0===a.arguments?"{}":"string"==typeof a.arguments?a.arguments:JSON.stringify(a.arguments);c.push({type:"tool-call",toolCallId:`call_${(0,l.randomUUID)().replace(/-/g,"").slice(0,16)}`,toolName:a.name,input:e})}if(0===c.length)return{text:a,toolCalls:[]};let d=a.indexOf("<tool_call>");return{text:d>0?a.slice(0,d).trim():"",toolCalls:c}}),(()=>{let a=process.env.LLM_TIMEOUT_MS;if(a)return Number.isFinite(Number(a))})(),(()=>{let a=process.env.LLM_TIMEOUT_RETRIES;if(a)return Number.isFinite(Number(a))})(),(()=>{let a=process.env.LLM_STALE_RETRY_TIMEOUT_MS;if(a)return Number.isFinite(Number(a))})(),g.Ik({status:g.k5(["success","blocked"]),reason:g.Yj().optional()}),g.Ik({fact:g.Yj().min(1).describe("The durable fact to remember, stated as an assertion not a narrative."),category:g.k5(y.BJ),importance:g.ai().int().min(1).max(5).optional().default(3).describe("1-5. Use 4-5 only for facts that affect how future agents operate."),skill_tags:g.YO(g.Yj().max(60)).max(20).optional().describe("Optional skill slugs this memory is associated with.")}),g.Ik({query:g.Yj().min(1).optional().describe("Optional free-text search. When set, memories are ranked by keyword match. Omit to list recent/important memories instead."),skill_tags:g.YO(g.Yj().max(60)).optional().describe("Optional skill slugs to filter memories by. Returns all non-archived memories for this entity if omitted."),sort:g.k5(["importance","recent"]).optional().describe("Result ordering: 'importance' (default) or 'recent'."),limit:g.ai().int().min(1).max(200).optional().describe("Max rows to return. Default 50.")}),g.Ik({query:g.Yj().min(2).max(200).describe('Keywords to find in past jobs/conversations of this workspace (their task, replies, and tool output). E.g. "z_image workflow port", "Airtable base id", "email sent to the client".'),limit:g.ai().int().min(1).max(20).optional().describe("Max results to return. Default 6.")}),g.Ik({fact_substring:g.Yj().min(3).describe("A unique substring of the memory fact to mark helpful. Quote a few distinctive words from the fact text shown in the Persistent memory block. Min 3 chars.")}),g.Ik({fact_substring:g.Yj().min(3).describe("A unique substring of the outdated memory fact. Quote distinctive words from the Persistent memory block. Min 3 chars."),reason:g.Yj().max(500).optional().describe("Brief justification for marking outdated — surfaces in the dashboard for the user.")}),g.Ik({query:g.Yj().min(1).describe("The search query.")});g.Ik({text:g.Yj().min(1).max(5e4).describe("The text to display as this job's result in the dashboard. Markdown supported. Stored in agent_jobs.result.")});var dn=c(73024),dp=c(46193);g.Ik({path:g.Yj().min(1).describe("Path to the file, relative to the agent workspace root. Absolute paths are accepted but must resolve under the workspace."),offset:g.ai().int().min(0).optional().describe("1-based line number to start at. Default 1."),limit:g.ai().int().min(1).max(2e3).optional().describe("Max number of lines to return. Default 500.")}),g.Ik({path:g.Yj().min(1).describe("Path to the file, relative to the agent workspace root. Created if missing."),content:g.Yj().describe("Full file contents to write. Overwrites any existing file."),create_dirs:g.zM().optional().default(!1).describe("If true, create missing parent directories.")}),g.Ik({path:g.Yj().min(1).describe("Path to an existing file, relative to the workspace root."),old_string:g.Yj().min(1).describe("Exact substring to replace. Must appear in the file verbatim — whitespace and line endings count. Must be unique unless replace_all:true."),new_string:g.Yj().describe('Replacement text. Pass "" to delete the matched substring.'),replace_all:g.zM().optional().default(!1).describe("Replace every occurrence (default false: require exactly one match).")}),g.Ik({path:g.Yj().optional().describe('Directory path relative to a workspace. For a single-workspace agent, the label prefix is optional (e.g. "subdir/"). For multi-workspace agents, prefix with the workspace label (e.g. "notes/subdir/"). Omit entirely to list workspaces at the top level.'),glob:g.Yj().optional().describe('Optional glob to filter results (e.g. "*.md", "**/*.ts"). Matched against the name for non-recursive, against the relative path for recursive (** prefix).'),recursive:g.zM().optional().default(!1).describe("Walk subdirectories. Default false.")}),g.Ik({pattern:g.Yj().min(1).describe("Regex pattern to search for."),target:g.k5(["files","content"]).optional().default("content").describe('"files" matches the pattern against file paths (filename search). "content" scans each file body (grep-like). Default "content".'),path:g.Yj().optional().describe('Subdirectory to search. For multi-workspace agents, prefix with the workspace label (e.g. "notes/subdir"). Without a label, all workspaces are searched.'),file_glob:g.Yj().optional().describe('Restrict content search to files matching this glob (e.g. "*.md").'),case_sensitive:g.zM().optional().default(!1).describe("Default false — pattern is matched case-insensitively."),max_results:g.ai().int().min(1).max(500).optional().default(100).describe("Cap on matches returned. Narrow `path` or `file_glob` if you hit it.")});var dq=c(84394),dr=c.n(dq);Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]);g.Ik({path:g.Yj().min(1).describe('Workspace-relative path to the .xlsx file. For multi-workspace agents, prefix with the workspace label (e.g. "docs/report.xlsx").'),sheet:g.Yj().optional().describe("Worksheet name. Defaults to the first sheet if omitted."),max_rows:g.ai().int().positive().optional().default(200).describe("Maximum rows to return per sheet. Default 200.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),cell:g.Yj().min(1).describe('Cell address in A1 notation (e.g. "B3"). Column letter(s) then row number.'),value:g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]).describe('New cell value. Strings starting with "=" are treated as formulae. null clears the cell.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),start_cell:g.Yj().min(1).describe('Top-left cell of the range in A1 notation (e.g. "B2"). The range expands to fit values[][].)'),values:g.YO(g.YO(g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]))).describe('Row-major 2-D array of values. values[0] = first row, values[0][0] = start_cell. null entries clear the corresponding cell. Strings starting with "=" are formulae.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),rows:g.YO(g.YO(g.KC([g.Yj(),g.ai(),g.zM(),g.ch()]))).describe('Rows to append after the last populated row. Each entry is a cell value. null clears the cell. Strings starting with "=" are formulae.')}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),name:g.Yj().min(1).describe("Name of the new worksheet.")}),g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .xlsx file (e.g. "reports/q1.xlsx").'),sheet:g.Yj().optional().default("Sheet1").describe('Name of the first worksheet. Defaults to "Sheet1".'),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .xlsx file."),sheet:g.Yj().min(1).describe("Worksheet name."),start_row:g.ai().int().positive().describe("1-indexed row number of the first row to delete."),count:g.ai().int().positive().describe("Number of rows to delete.")}),c(96376),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .docx file. For multi-workspace agents, prefix with the workspace label.")});let ds=g.Ik({text:g.Yj().describe("Paragraph text content."),heading:g.ai().int().min(1).max(6).optional().describe("Heading level (1-6). Omit for normal paragraph."),bold:g.zM().optional().describe("Bold text."),italic:g.zM().optional().describe("Italic text.")});g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .docx file (e.g. "docs/report.docx").'),paragraphs:g.YO(ds).describe("Paragraphs to include in the document, in order."),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")}),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the existing .docx file to append to."),paragraphs:g.YO(ds).describe("New paragraphs to append after the existing content.")}),c(97183),c(5597),g.Ik({path:g.Yj().min(1).describe("Workspace-relative path to the .pptx file. For multi-workspace agents, prefix with the workspace label.")});let dt=g.Ik({title:g.Yj().optional().describe("Slide title text."),bullets:g.YO(g.Yj()).optional().describe("Bullet point lines displayed below the title."),body:g.Yj().optional().describe("Free-form text body (used instead of bullets if both provided, bullets win)."),image_path:g.Yj().optional().describe("Workspace-relative path to an image file (PNG/JPEG/GIF) to embed on the slide. The path goes through the workspace security guard.")});g.Ik({path:g.Yj().min(1).describe('Workspace-relative path for the new .pptx file (e.g. "presentations/deck.pptx").'),slides:g.YO(dt).min(1).describe("Array of slides to include in the presentation, in order."),overwrite:g.zM().optional().default(!1).describe("If false (default) refuse to overwrite an existing file.")});let du=[{slug:"obsidian",name:"Obsidian",description:"Read, search, create, and edit notes in the Obsidian vault.",requiredBuiltins:[],content:`Skill for working on an Obsidian vault via the filesystem: read, list, search, create, edit notes, with full mastery of the Obsidian Flavored Markdown syntax.
21
25
 
22
26
  ### Setup
23
27
 
@@ -100,7 +104,7 @@ Two approaches: (1) **anchored** via \`file_edit\` with a stable anchor as \`old
100
104
 
101
105
  ## Reference — Obsidian Flavored Markdown (kepano/obsidian-skills)
102
106
 
103
- Obsidian extends CommonMark + GFM with wikilinks, embeds, callouts, properties, comments and other syntaxes. Reference to open when you write a structured note for Quentin.
107
+ Obsidian extends CommonMark + GFM with wikilinks, embeds, callouts, properties, comments and other syntaxes. Reference to open when you write a structured note for the user.
104
108
 
105
109
  ### Note creation workflow
106
110
 
@@ -1419,15 +1423,15 @@ block in your prompt tells you the current local time. There is no UTC conversio
1419
1423
  - \`notifyOnSuccess\` defaults false → runs silently. Set true if the user should get a confirmation each run.
1420
1424
  - The agent referenced by agentSlug must exist (create it first).
1421
1425
  - Need an exotic pattern (e.g. "1st of every month")? That's a dashboard-only setup — tell the user.
1422
- `}],di=dh.map(a=>a.slug);function dj(a){return a.kind??"capability"}function dk(a){let b=dh.find(b=>b.slug===a);return b?dj(b):null}let dl=a=>dh.filter(b=>dj(b)===a).map(a=>a.slug);dl("baseline"),dl("channel"),dl("capability"),dl("agent-internal");let dm=/deepseek|minimax|qwen|glm|gemma|kimi|mistral|llama/i,dn=a=>dh.filter(b=>dj(b)===a).map(a=>a.content.trim()),dp={tavily:{label:"Web search & page extraction",setup:"a Tavily API key"},firecrawl:{label:"Web scraping / crawling",setup:"a Firecrawl API key"},apify:{label:"Web automation & scraping actors",setup:"an Apify token"},gmail:{label:"Read and send email",setup:"a connected Google account"},"google-calendar":{label:"Google Calendar events",setup:"a connected Google account"},"google-drive":{label:"Google Drive files",setup:"a connected Google account"},"google-sheets":{label:"Google Sheets",setup:"a connected Google account"},"google-docs":{label:"Google Docs",setup:"a connected Google account"},"notion-oauth":{label:"Notion pages & databases",setup:"a connected Notion account"},notion:{label:"Notion pages & databases",setup:"a Notion internal-integration key"},"airtable-oauth":{label:"Airtable bases",setup:"a connected Airtable account"},airtable:{label:"Airtable bases",setup:"an Airtable personal access token"}},dq=(a,b)=>dp[a]?.label??b;async function dr(a,b,c){var d;let e,f,g,h,i=(a.name?`You are ${a.name}, an AI agent working for the user inside Nodal-Agents. Any other agents you create, manage, delegate to, or connect are SEPARATE from you — never speak or act as if you were them.
1426
+ `}],dv=du.map(a=>a.slug);function dw(a){return a.kind??"capability"}function dx(a){let b=du.find(b=>b.slug===a);return b?dw(b):null}let dy=a=>du.filter(b=>dw(b)===a).map(a=>a.slug);dy("baseline"),dy("channel"),dy("capability"),dy("agent-internal");g.Ik({slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe('URL-safe identifier for the skill (e.g. "customer-support-v2").'),name:g.Yj().min(1).describe("Human-readable display name for the skill."),content:g.Yj().min(1).describe("The skill instructions injected into the agent system prompt when assigned."),description:g.Yj().optional().describe("Optional short description of what the skill does.")}),g.Ik({skillSlug:g.Yj().min(1).describe("The slug OR name of the skill to update."),name:g.Yj().min(1).optional().describe("New display name (optional)."),description:g.Yj().optional().describe("New short description (optional)."),content:g.Yj().min(1).optional().describe("New skill instructions, replacing the current ones (optional)."),active:g.zM().optional().describe("Enable (true) or disable (false) the skill (optional).")}),g.Ik({skillSlug:g.Yj().min(1).describe('The slug OR name of the skill to assign (e.g. "customer-support-v2").'),agentSlug:g.Yj().min(1).describe("The slug OR name of the agent to assign the skill to.")}),g.Ik({slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe('URL-safe identifier for the agent (e.g. "support-bot").'),name:g.Yj().min(1).describe("Human-readable display name for the agent."),personality:g.Yj().min(1).describe("System prompt / personality instructions for the agent."),model:g.Yj().min(1).describe('LLM model identifier (e.g. "claude-sonnet-4-6-20260217").'),role:g.k5(["worker","router","planner"]).describe("Agent role: worker = standard task-running agent; router = orchestrator that routes to sub-agents; planner = orchestrator that plans and delegates."),subAgentSlugs:g.YO(g.Yj().min(1)).optional().describe("Slugs of existing agents to assign as sub-agents (for router/planner roles). Optional.")});g.Ik({slug:g.Yj().min(1).describe('Slug of the existing agent to edit (e.g. "java").'),model:g.Yj().min(1).optional().describe("New LLM model id. Must be valid for the agent's provider — call list_models first to get the exact id."),personality:g.Yj().min(1).optional().describe("New system prompt / personality for the agent."),name:g.Yj().min(1).optional().describe("New human-readable display name.")}),g.Ik({agentSlug:g.Yj().min(1).describe("The slug OR name of an existing agent to assign as your sub-agent.")}),g.Ik({name:g.Yj().min(1).describe("Human-readable display name for the MCP server."),slug:g.Yj().regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens only.").min(1).describe("URL-safe identifier; also the tool-name prefix. Must be unique in this workspace."),transport:g.k5(["http","stdio"]).describe("http = remote Streamable HTTP MCP server; stdio = local subprocess."),url:g.Yj().url().optional().describe("HTTP only: the MCP server endpoint URL."),apiKey:g.Yj().optional().describe("HTTP only: API key/token used to authenticate."),authScheme:g.k5(["header","query","bearer"]).optional().describe("HTTP only: how the key is sent — header, query param, or bearer. Defaults to header."),authParamName:g.Yj().optional().describe("HTTP only: the header or query-param name carrying the key (ignored for bearer)."),command:g.Yj().optional().describe("stdio only: the executable to spawn."),args:g.YO(g.Yj()).optional().describe("stdio only: command-line arguments."),env:g.g1(g.Yj(),g.Yj()).optional().describe("stdio only: environment variables for the subprocess (encrypted at rest)."),attachToAgentSlug:g.Yj().optional().describe("Optional: slug/name of an agent to immediately attach this MCP to, so its tools become usable by that agent. Without this, the server is registered but NOT usable by anyone — attach it later with attach_mcp.")}),g.Ik({mcpSlug:g.Yj().min(1).describe('Slug or name of the MCP server to attach (e.g. "my-mcp-server").'),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to give the MCP tools to.")}),g.Ik({slug:g.Yj().min(1).describe('Connector catalog slug — must be a known api_key connector (e.g. "notion", "airtable", "apify", "firecrawl", "tavily").'),name:g.Yj().min(1).describe("Display name for this connector instance."),apiKey:g.Yj().min(1).describe("The provider API key / token (stored encrypted at rest)."),attachToAgentSlug:g.Yj().optional().describe("Optional: slug/name of an agent to immediately attach this connector to, so its tools become usable by that agent. Without this, the connector is registered but NOT usable — attach it later with attach_connector.")}),g.Ik({connectorSlug:g.Yj().min(1).describe('Slug or name of the connector to attach (e.g. "notion").'),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to give the connector tools to.")}),g.Ik({agentSlug:g.Yj().min(1).describe("Slug or name of the sub-agent to remove from your team (un-delegate).")}),g.Ik({skillSlug:g.Yj().min(1).describe("Slug or name of the skill to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the skill from.")}),g.Ik({mcpSlug:g.Yj().min(1).describe("Slug or name of the MCP server to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the MCP from.")}),g.Ik({connectorSlug:g.Yj().min(1).describe("Slug or name of the connector to remove from the agent."),agentSlug:g.Yj().min(1).describe("Slug or name of the agent to remove the connector from.")});var dz=c(54856);let dA=g.KC([g.k5(["daily","weekdays","weekends"]),g.YO(g.ai().int().min(0).max(6))]).optional().describe('Which days to run: "daily" (default), "weekdays" (Mon-Fri), "weekends", or an array of day numbers 0=Sun..6=Sat. Only used with atTimes.');g.Ik({agentSlug:g.Yj().min(1).describe("Slug or name of the agent the schedule fires jobs for."),name:g.Yj().min(1).describe("Unique, human-readable name for the schedule."),atTimes:g.YO(g.Yj()).optional().describe('Wall-clock times as "HH:MM" (24h) — e.g. ["09:00","13:00","21:00"]. The tool builds the schedule in the user\'s timezone; you give the hours the user states (no cron, no UTC). Use this for fixed times of day.'),everyMinutes:g.ai().int().optional().describe("For interval schedules: run every N minutes (e.g. 15, 30, 60, 120). Use instead of atTimes."),days:dA,task:g.Yj().min(1).describe("The task/instructions the agent runs each time it fires."),notifyOnSuccess:g.zM().optional().describe("If true, the agent confirms to the user on success (default false = runs silently).")}),g.Ik({name:g.Yj().min(1).describe("Name of the existing schedule to edit."),atTimes:g.YO(g.Yj()).optional().describe('New wall-clock times as "HH:MM" — e.g. ["09:00","21:00"]. Rebuilds the schedule.'),everyMinutes:g.ai().int().optional().describe("Switch to an interval: run every N minutes."),days:dA,task:g.Yj().min(1).optional().describe("New task/instructions."),newName:g.Yj().min(1).optional().describe("Rename the schedule."),notifyOnSuccess:g.zM().optional().describe("Toggle the success notification.")}),g.Ik({name:g.Yj().min(1).describe("Name of the schedule to pause/resume."),active:g.zM().describe("true = resume (recomputes next run), false = pause.")}),g.Ik({name:g.Yj().min(1).describe("Name of the schedule to run now (see list_schedules).")});g.Ik({skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().min(1).describe("Path to a bundled file, relative to the skill's folder (e.g. 'references/x.md')."),offset:g.ai().int().min(0).optional().describe("1-based line number to start at. Default 1."),limit:g.ai().int().min(1).max(2e3).optional().describe("Max number of lines to return. Default 500.")}),g.Ik({skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().optional().describe("Subfolder to list, relative to the skill's root. Default: the skill root.")}),g.Ik({purpose:g.Yj().min(1).max(400).describe("REQUIRED. A short plain-language explanation, IN THE USER'S LANGUAGE, of what you are writing into the skill and why. Shown FIRST on the approval prompt."),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE impact, if any (overwrites an existing bundled file, changes how the skill behaves). Shown as a ⚠️ warning. OMIT when harmless."),skill:g.Yj().min(1).describe("The skill's slug (its installed identifier)."),path:g.Yj().min(1).describe("Path to write, relative to the skill's folder (e.g. 'workflows/my_workflow.json'). Parent folders are created as needed. Must stay inside the skill folder."),content:g.Yj().max(1048576).describe("The full file content to write (UTF-8). Overwrites the file if it already exists.")}),c(31421);["PATH","HOME","TMPDIR","TMP","TEMP","LANG","LC_ALL","SHELL","USER","LOGNAME","TERM","SYSTEMROOT","WINDIR","PATHEXT","COMSPEC","HOMEDRIVE","HOMEPATH","USERPROFILE","APPDATA","LOCALAPPDATA","PUBLIC","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS","COMPUTERNAME","USERNAME","USERDOMAIN","PYTHONPATH","PYTHONHOME","VIRTUAL_ENV","LD_LIBRARY_PATH","PKG_CONFIG_PATH","NODE_PATH"].map(a=>a.toUpperCase());g.Ik({purpose:g.Yj().min(1).max(400).describe('REQUIRED. A short plain-language explanation, IN THE USER\'S LANGUAGE, of what this command does and why you are running it. Shown FIRST on the approval prompt so the user can decide WITHOUT reading the raw command. E.g. "Install the Python dependencies for the comfyui skill so I can generate the image."'),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE or destructive impact, if any: deletes/overwrites files, installs software, downloads from the network, spends money, long-running, or otherwise hard to undo. Shown as a ⚠️ warning on the approval prompt. OMIT entirely when the command is harmless / read-only."),command:g.Yj().min(1).max(8e3).describe('The shell command to run. May be a compound command joined with && or newlines (e.g. "npm install && node build.js") — it runs as ONE call. Executed via cmd.exe on Windows and /bin/sh on Unix.'),cwd:g.Yj().max(1e3).optional().describe('Optional working directory, relative to the agent workspace (e.g. "scripts/canvas"). Defaults to the workspace root. Must stay inside the workspace.'),timeout_seconds:g.ai().int().positive().max(1800).optional().describe("Optional timeout in seconds (default 300, max 1800). On timeout the command and its child processes are killed.")}),g.Ik({purpose:g.Yj().min(1).max(400).describe("REQUIRED. A short plain-language explanation, IN THE USER'S LANGUAGE, of what running this script does and why. Shown FIRST on the approval prompt so the user can decide without reading the raw script call."),impact:g.Yj().max(400).optional().describe("OPTIONAL. The potential NEGATIVE or destructive impact, if any (writes files, installs software, network/GPU use, spends money, long-running). Shown as a ⚠️ warning. OMIT when the script is harmless / read-only."),skill:g.Yj().min(1).describe("Slug of an installed skill you hold and are authorized to run scripts for (e.g. 'comfyui')."),script:g.Yj().min(1).max(1e3).describe("Path to the bundled script, relative to the skill folder (e.g. 'scripts/run_workflow.py'). Discover available scripts with skill_file_list. Only .py / .sh / .js are runnable."),args:g.YO(g.Yj().max(8e3)).max(100).optional().describe('Arguments passed to the script VERBATIM — not shell-interpreted, so they are injection-safe. E.g. ["--workflow", "workflows/sdxl_txt2img.json", "--prompt", "a cat", "--server", "http://127.0.0.1:8188"].'),timeout_seconds:g.ai().int().positive().max(1800).optional().describe("Optional timeout in seconds (default 300, max 1800). On timeout the script and its child processes are killed.")}),g.Ik({slug:g.Yj().min(1).describe('Slug of the skill to read, e.g. "comfyui" or "tool-create-mcp".')});g.Ik({provider:g.Yj().optional().describe('Optional provider key (e.g. "openrouter", "deepseek"). Omit to use the entity\'s active provider.')}),g.Ik({agentSlug:g.Yj().optional().describe("Optional: only schedules for this agent (slug or name). Omit for all schedules.")});let dB=[{name:"return_result",description:'Signal that the task is complete (status="success") or blocked (status="blocked"). For content delivery to the user, use the appropriate delivery tool (`telegram_send_message`, `dashboard_publish`, etc.) — return_result carries no content. Whenever your task involves delivering an answer, emit `return_result` and the delivery tool(s) **in the same assistant turn** (parallel tool calls). The runner handles delivery failures automatically (defers finalization if a sibling tool errors), so there is no need to wait for tool results before signaling completion — splitting into separate turns doubles input token cost (the full conversation replays) for no benefit. Use status="blocked" if you cannot proceed after 2 attempts. When you set status="blocked" you MUST also set `reason` to a clear, user-facing explanation: name the SPECIFIC thing that blocked YOU on THIS task — the exact tool, credential, or input that failed and its actual error — and the concrete next step the user can take. Write it from scratch for this situation; never copy a generic example. The user sees this reason verbatim.'},{name:"skill_view",description:"Load a skill's FULL instructions by slug, on demand. Call this the moment a skill listed in your Skills index is relevant — BEFORE acting — to get its complete guidance, the exact paths of its bundled files (scripts, ready-made workflows/templates), and how to run them. Also loads a tool's usage guide right before you call that tool (e.g. skill_view('tool-create-mcp')). Follow what it returns instead of reimplementing the skill yourself."},{name:"list_models",description:"List the valid model ids for assigning to an agent (curated catalog for the provider). Call this BEFORE create_agent / update_agent and pass the exact modelId it returns — never guess a model string."},{name:"list_schedules",description:'List the cron schedules (automations) in this workspace — name, agent, cron, timezone, active/paused, next & last run. Use it to answer "what are my schedules?" or to find a schedule\'s name before update_schedule / toggle_schedule / run_schedule.'},{name:"save_memory",description:"Save a durable fact to long-term memory. Use the `save_memory` tool whenever (a) the user explicitly asks you to remember, save, or store something, OR (b) you learn a stable preference, rule, or context that will improve future unrelated tasks. Invoke `save_memory` once per fact — multiple invocations if the user gives multiple facts. Skip ephemeral details (today's weather, transient calculation results)."},{name:"query_memory",description:"Read persistent memories shared across all agents in your entity. Use before starting a task to recall relevant context, user preferences, and learned rules — including memories saved by other agents in this same workspace. Pass `query` to search by keywords, or filter by skill_tags for narrower lookups."},{name:"search_history",description:'Search this workspace\'s PAST jobs and conversations by keyword (full-text). Use it to recall what was decided, found, or done before — including by OTHER agents in this workspace (e.g. "what ComfyUI port did we use?", "the brief we wrote last week"). Returns matching past tasks with a highlighted snippet. This is durable recall with no budget limit — reach for it when the answer is likely in past work but not in your injected memory.'},{name:"mark_memory_helpful",description:"Mark a fact from your Persistent memory block as having been helpful in this job. Bumps its importance (capped at 5★) so the memory stays in your auto-injection window over time. Use sparingly — only for facts that materially shaped your answer. Identify the memory by quoting a unique substring from the fact text."},{name:"mark_memory_outdated",description:"Mark a fact from your Persistent memory block as outdated when newer information in the current job contradicts or supersedes it. The memory is archived (not deleted) and dropped from your future auto-injection blocks. Identify the memory by quoting a unique substring from the fact text. Pair with save_memory(new fact) if a replacement is appropriate."},{name:"web_search",description:"Search the web. Uses your configured Tavily/Firecrawl provider if any, otherwise a free best-effort search."},{name:"dashboard_publish",description:"Set this job's RESULT — the agent's substantive output. It becomes agent_jobs.result, shown on /jobs, AND it is the exact text handed to any task that depends on this one and to the run's final delivery. So for a task whose output another step (a synthesis) or the user will consume, put the FULL content here — not a stub like \"see below\". (If you write your answer as your final message text, it is captured automatically; this tool makes it explicit and is required when the dashboard is an intended destination.) For other surfaces, use the corresponding tool (telegram_send_message, etc.).\n\n**Same-response with return_result (CRITICAL for cost & latency)**: Always emit dashboard_publish IN THE SAME response.content array as return_result. Splitting them across consecutive responses re-prompts the LLM unnecessarily and adds latency. Correct: response.content = [{tool-call: dashboard_publish, ...}, {tool-call: return_result, ...}]."},{name:"file_read",description:"Read the contents of a file in the agent workspace. Returns lines with start_line / end_line markers. Use `offset` and `limit` to paginate large files. Files above ~1 MiB MUST be paginated — request smaller chunks. Files above 50 MiB are refused outright, even with offset/limit — use `file_search` to locate content, or split the file."},{name:"file_write",description:"Write (or overwrite) a file in the agent workspace. Atomic: writes to a tempfile then renames over the target, so partial-write failures never corrupt the original. Use `file_edit` instead when you only need to change part of an existing file — it preserves lines you do not touch. Max 1 MiB per write."},{name:"file_edit",description:"Edit an existing file by replacing an exact substring. Quote the chunk to change verbatim (including whitespace). Fails loud when the substring is missing (you misquoted) or matches multiple places (ambiguous — narrow the quote, or pass replace_all:true). Use this instead of file_write when you only want to change part of a file — preserves untouched lines."},{name:"file_list",description:'List entries of a directory in the agent workspace(s). With no `path` argument, returns the list of available workspace labels. With a path, lists that directory. For multi-workspace agents, prefix paths with the workspace label (e.g. "notes/subdir"). Returns name, type, size, and modified time per entry. Use `glob` to filter (e.g. "*.md"). Pass `recursive:true` to walk subdirectories. Caps at 500 entries.'},{name:"file_search",description:'Search the agent workspace(s). `target:"files"` matches the regex against file paths. `target:"content"` (default) scans file contents and returns line-level matches. Use `file_glob` to restrict content scans (e.g. "*.md"). For multi-workspace agents, prefix `path` with a workspace label to search only that workspace (e.g. "notes/subdir"), or omit to search all workspaces. Skips .git/node_modules/dist by default.'}];g.Ik({chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID to send to. Omit to reply to the chat that triggered this job."),text:g.Yj().min(1).max(4096).describe("The message text to send.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL (e.g. a ComfyUI /view?filename=... URL). The runner fetches the bytes server-side — do NOT base64-encode the file."),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars, Telegram limit)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL. The runner fetches the bytes server-side — do NOT read the file or base64-encode it."),filename:g.Yj().min(1).max(255).optional().describe('Optional filename the recipient sees (with extension, e.g. "report.md"). Defaults to the name derived from the source path/URL.'),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars, Telegram limit)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")}),g.Ik({source:g.Yj().min(1).describe("Local file path OR an http(s) URL. The runner fetches the bytes server-side — do NOT read the file or base64-encode it."),filename:g.Yj().min(1).max(255).optional().describe("Optional filename the recipient sees (keep the extension). Defaults to the source name."),caption:g.Yj().max(1024).optional().describe("Optional caption (≤1024 chars)."),chatId:g.Yj().regex(/^-?\d+$/,"must be a numeric Telegram chat ID").max(20).optional().describe("Telegram chat ID. Omit to reply to the chat that triggered this job.")});let dC=/deepseek|minimax|qwen|glm|gemma|kimi|mistral|llama/i,dD=a=>du.filter(b=>dw(b)===a).map(a=>a.content.trim()),dE={tavily:{label:"Web search & page extraction",setup:"a Tavily API key"},firecrawl:{label:"Web scraping / crawling",setup:"a Firecrawl API key"},apify:{label:"Web automation & scraping actors",setup:"an Apify token"},gmail:{label:"Read and send email",setup:"a connected Google account"},"google-calendar":{label:"Google Calendar events",setup:"a connected Google account"},"google-drive":{label:"Google Drive files",setup:"a connected Google account"},"google-sheets":{label:"Google Sheets",setup:"a connected Google account"},"google-docs":{label:"Google Docs",setup:"a connected Google account"},"notion-oauth":{label:"Notion pages & databases",setup:"a connected Notion account"},notion:{label:"Notion pages & databases",setup:"a Notion internal-integration key"},"airtable-oauth":{label:"Airtable bases",setup:"a connected Airtable account"},airtable:{label:"Airtable bases",setup:"an Airtable personal access token"}},dF=(a,b)=>dE[a]?.label??b;async function dG(a,b,c){var d;let e,f,g,h,i=(a.name?`You are ${a.name}, an AI agent working for the user inside Nodal-Agents. Any other agents you create, manage, delegate to, or connect are SEPARATE from you — never speak or act as if you were them.
1423
1427
 
1424
- `:"")+a.personality,j=await c6(a.id,b),k=await b.select({skillId:m.eK.id,skillSlug:m.eK.slug,skillName:m.eK.name,skillDescription:m.eK.description}).from(m.$m).innerJoin(m.eK,(0,m.eq)(m.$m.skillId,m.eK.id)).where((0,m.eq)(m.$m.agentId,a.id)),l=await b.select({slug:m.tK.slug}).from(m.XT).innerJoin(m.tK,(0,m.eq)(m.tK.id,m.XT.connectorId)).where((0,m.eq)(m.XT.agentId,a.id)),n=await b.select({slug:m.h_.slug}).from(m.oS).innerJoin(m.h_,(0,m.eq)(m.h_.id,m.oS.mcpServerId)).where((0,m.eq)(m.oS.agentId,a.id)),o=null!==a.entityId?await b.select({slug:m.tK.slug,name:m.tK.name}).from(m.tK).where((0,m.eq)(m.tK.entityId,a.entityId)):[],p=null!==a.entityId?await b.select({slug:m.h_.slug,name:m.h_.name}).from(m.h_).where((0,m.eq)(m.h_.entityId,a.entityId)):[];k.length>0&&(0,m.t$)(b,k.map(a=>a.skillId)).catch(console.error);let q=await b.select({label:m.Kq.label,path:m.Kq.path}).from(m.Kq).where((0,m.eq)(m.Kq.agentId,a.id)).orderBy(m.Kq.position,m.Kq.label),r=k.filter(a=>{let b=dk(a.skillSlug);return null===b||"capability"===b}),s=r.map(a=>{let b=(a.skillDescription??"").trim()||"(load with skill_view for details)";return`- \`skill_view('${a.skillSlug}')\` — **${a.skillName}**: ${b}`}).join("\n"),t=r.length>0?`
1428
+ `:"")+a.personality,j=await dh(a.id,b),k=await b.select({skillId:p.eK.id,skillSlug:p.eK.slug,skillName:p.eK.name,skillDescription:p.eK.description}).from(p.$m).innerJoin(p.eK,(0,p.eq)(p.$m.skillId,p.eK.id)).where((0,p.eq)(p.$m.agentId,a.id)),l=await b.select({slug:p.tK.slug}).from(p.XT).innerJoin(p.tK,(0,p.eq)(p.tK.id,p.XT.connectorId)).where((0,p.eq)(p.XT.agentId,a.id)),m=await b.select({slug:p.h_.slug}).from(p.oS).innerJoin(p.h_,(0,p.eq)(p.h_.id,p.oS.mcpServerId)).where((0,p.eq)(p.oS.agentId,a.id)),n=null!==a.entityId?await b.select({slug:p.tK.slug,name:p.tK.name}).from(p.tK).where((0,p.eq)(p.tK.entityId,a.entityId)):[],o=null!==a.entityId?await b.select({slug:p.h_.slug,name:p.h_.name}).from(p.h_).where((0,p.eq)(p.h_.entityId,a.entityId)):[];k.length>0&&(0,p.t$)(b,k.map(a=>a.skillId)).catch(console.error);let q=await b.select({label:p.Kq.label,path:p.Kq.path}).from(p.Kq).where((0,p.eq)(p.Kq.agentId,a.id)).orderBy(p.Kq.position,p.Kq.label),r=k.filter(a=>{let b=dx(a.skillSlug);return null===b||"capability"===b}),s=r.map(a=>{let b=(a.skillDescription??"").trim()||"(load with skill_view for details)";return`- \`skill_view('${a.skillSlug}')\` — **${a.skillName}**: ${b}`}).join("\n"),t=r.length>0?`
1425
1429
 
1426
1430
  ## Skills (load before acting)
1427
1431
 
1428
1432
  Scan the skills below. For ANY skill even partially relevant to your task, you MUST call \`skill_view('<slug>')\` to load its full instructions and follow them BEFORE you act — even if you think you could do the task with basic tools. A skill defines HOW the task must be done here and ships tested scripts + ready-made files (e.g. prebuilt workflows). Run a skill's bundled scripts with \`run_skill_script\` (or by the exact paths skill_view gives you). NEVER reimplement a skill's logic inline, and NEVER rebuild or re-convert something the skill already provides.
1429
1433
 
1430
- ${s}`:"";j&&(i=i.includes("{{team}}")?i.replace("{{team}}",j):i+"\n\n"+j);let u=c?.deployment?"\n\n"+(e="lan"===(d=c.deployment).networkMode?`LAN — the dashboard is reachable by other devices on the local network${d.lanAddresses&&d.lanAddresses.length>0?` at ${d.lanAddresses.join(", ")}`:""}; multiple users may share this instance.`:"loopback — the dashboard is bound to localhost only; single-user instance on this machine.",f=["## Runtime","",`You run locally inside Nodal-Agents on the user's own machine (${d.os}). You are NOT a cloud or hosted agent — your process and the user's machine are the same host.`,"","- Local services on this machine are reachable directly at `127.0.0.1` / `localhost` (a local API, a database, or an app such as ComfyUI on `:8188`). Call them directly. NEVER ask the user to expose a local service through a public tunnel (ngrok, cloudflared) — it is unnecessary here and a needless security risk.",`- Network: ${e}`],d.timezone&&f.push(`- Date & time: it is currently ${d.localTime??"(unknown)"} in the user's timezone (${d.timezone}). Use this as "now". When scheduling, give wall-clock times in THIS timezone — the system applies the zone, so NEVER convert to UTC yourself.`),d.containerized&&f.push("- You run inside a container — to reach a service on the host machine, use `host.docker.internal` instead of `127.0.0.1`."),d.installNotes?.trim()&&f.push("","### Install notes (from the operator)","",d.installNotes.trim()),f.join("\n")):"",v=c?.surface==="chat"?"":(g=dg.map(a=>`- **${a.name}**: ${a.description}`).join("\n"),`## Built-in capabilities
1434
+ ${s}`:"";j&&(i=i.includes("{{team}}")?i.replace("{{team}}",j):i+"\n\n"+j);let u=c?.deployment?"\n\n"+(e="lan"===(d=c.deployment).networkMode?`LAN — the dashboard is reachable by other devices on the local network${d.lanAddresses&&d.lanAddresses.length>0?` at ${d.lanAddresses.join(", ")}`:""}; multiple users may share this instance.`:"loopback — the dashboard is bound to localhost only; single-user instance on this machine.",f=["## Runtime","",`You run locally inside Nodal-Agents on the user's own machine (${d.os}). You are NOT a cloud or hosted agent — your process and the user's machine are the same host.`,"","- Local services on this machine are reachable directly at `127.0.0.1` / `localhost` (a local API, a database, or an app such as ComfyUI on `:8188`). Call them directly. NEVER ask the user to expose a local service through a public tunnel (ngrok, cloudflared) — it is unnecessary here and a needless security risk.",`- Network: ${e}`],d.timezone&&f.push(`- Date & time: it is currently ${d.localTime??"(unknown)"} in the user's timezone (${d.timezone}). Use this as "now". When scheduling, give wall-clock times in THIS timezone — the system applies the zone, so NEVER convert to UTC yourself.`),d.containerized&&f.push("- You run inside a container — to reach a service on the host machine, use `host.docker.internal` instead of `127.0.0.1`."),d.installNotes?.trim()&&f.push("","### Install notes (from the operator)","",d.installNotes.trim()),f.join("\n")):"",v=c?.surface==="chat"?"":(g=dB.map(a=>`- **${a.name}**: ${a.description}`).join("\n"),`## Built-in capabilities
1431
1435
 
1432
1436
  These tools are always available to you. Use them proactively when they fit:
1433
1437
 
@@ -1449,24 +1453,40 @@ Example: \`${c.label}/notes.md\` to access \`notes.md\` in the **${c.label}** wo
1449
1453
 
1450
1454
  Durable facts loaded from your long-term memory. Treat as authoritative for the entity. DO NOT call \`query_memory\` to look up facts already listed here — only call it for facts that look missing.
1451
1455
 
1452
- ${b}`}(null!==a.entityId?await K(b,{entityId:a.entityId,maxChars:a.memoryTokenBudget,query:c?.task}):[]),y=c?(h=[`- origin: ${c.origin}`],c.telegramChatId&&h.push(`- telegram_chat_id: ${c.telegramChatId}`),"chat"===c.surface&&h.push('- surface: in-app dashboard chat — you are talking directly with the user; reply in plain text. For conversation or recalling facts, just reply (your durable facts are loaded below). For ANY action — using a connector or skill, delegating to your team, sending/fetching/creating/publishing, or (as the workspace ROOT) creating agents, skills, MCP servers, connectors or automations — you MUST call the `run_task` tool with a clear, self-contained instruction. CRITICAL: writing in text that you will do something (e.g. "Je lance X…") does NOT start anything — ONLY an actual `run_task` tool call performs the action. If you intend to act, the `run_task` tool call is mandatory; a text-only reply about an action accomplishes nothing. It runs as a tracked job with your FULL toolset. `run_task` is your gateway to everything you can do — NEVER tell the user you cannot do something that an action could accomplish; escalate it via `run_task` instead. You may add a one-line acknowledgment in your own voice alongside the call, but the `run_task` call is what actually does the work. Do not call any other named tool on this surface.'),c.notifyOnSuccess&&h.push("- notify_on_success: true — when this job finishes, send the user a short confirmation (what you did + the outcome) via your delivery tool before calling return_result."),`
1456
+ ${b}`}(null!==a.entityId?await N(b,{entityId:a.entityId,maxChars:a.memoryTokenBudget,query:c?.task}):[]),z=c?(h=[`- origin: ${c.origin}`],c.telegramChatId&&h.push(`- telegram_chat_id: ${c.telegramChatId}`),"chat"===c.surface&&h.push('- surface: in-app dashboard chat — you are talking directly with the user; reply in plain text. For conversation or recalling facts, just reply (your durable facts are loaded below). For ANY action — using a connector or skill, delegating to your team, sending/fetching/creating/publishing, or (as the workspace ROOT) creating agents, skills, MCP servers, connectors or automations — you MUST call the `run_task` tool with a clear, self-contained instruction. CRITICAL: writing in text that you will do something (e.g. "Je lance X…") does NOT start anything — ONLY an actual `run_task` tool call performs the action. If you intend to act, the `run_task` tool call is mandatory; a text-only reply about an action accomplishes nothing. It runs as a tracked job with your FULL toolset. `run_task` is your gateway to everything you can do — NEVER tell the user you cannot do something that an action could accomplish; escalate it via `run_task` instead. You may add a one-line acknowledgment in your own voice alongside the call, but the `run_task` call is what actually does the work. Do not call any other named tool on this surface.'),c.notifyOnSuccess&&h.push("- notify_on_success: true — when this job finishes, send the user a short confirmation (what you did + the outcome) via your delivery tool before calling return_result."),`
1453
1457
 
1454
1458
  ## Job context
1455
- ${h.join("\n")}`):"",z=function(a){let b=dn("baseline");if(0===b.length)return"";let c=dm.test(a)?"\n\n**Especially you — execution discipline:** Actually run or check your work before you say a task is done, and never write tool output you did not really get back. Be decisive: once a check passes (e.g. dependencies report ready), DO the action — do not keep re-verifying, re-listing, or running diagnostic commands. Use the tools, scripts, and exact file paths you were given (a skill loaded with skill_view ships run_skill_script and ready-made workflows/templates) instead of writing your own helper or conversion scripts, or rebuilding what already exists. Take the fewest steps that finish the task, then deliver the result with its output path.":"";return`## How you work (always)
1459
+ ${h.join("\n")}`):"",A=function(a){let b=dD("baseline");if(0===b.length)return"";let c=dC.test(a)?"\n\n**Especially you — execution discipline:** Actually run or check your work before you say a task is done, and never write tool output you did not really get back. Be decisive: once a check passes (e.g. dependencies report ready), DO the action — do not keep re-verifying, re-listing, or running diagnostic commands. Use the tools, scripts, and exact file paths you were given (a skill loaded with skill_view ships run_skill_script and ready-made workflows/templates) instead of writing your own helper or conversion scripts, or rebuilding what already exists. Take the fewest steps that finish the task, then deliver the result with its output path.":"";return`## How you work (always)
1456
1460
 
1457
- ${b.join("\n\n")}${c}`}(a.model),A=function(a){if("telegram"!==a.channel&&!0!==a.telegram)return"";let b=dn("channel");return 0===b.length?"":`## Channel etiquette
1461
+ ${b.join("\n\n")}${c}`}(a.model),B=function(a){if("telegram"!==a.channel&&!0!==a.telegram)return"";let b=dD("channel");return 0===b.length?"":`## Channel etiquette
1458
1462
 
1459
- ${b.join("\n\n")}`}({channel:c?.origin,telegram:!!c?.telegramChatId}),B=function(a){let b=new Set(a.assignedSkillSlugs),c=dh.filter(a=>"capability"===dj(a)&&!b.has(a.slug)),d=new Set(a.attachedConnectorSlugs),e=new Set(a.attachedMcpSlugs),f=a.workspaceConnectors.filter(a=>!d.has(a.slug)),g=a.workspaceMcps.filter(a=>!e.has(a.slug)),h=new Set(a.workspaceConnectors.map(a=>a.slug)),i=Object.entries(dp).filter(([a])=>a in c5&&!d.has(a)&&!h.has(a));if(0===c.length&&0===f.length&&0===g.length&&0===i.length)return"";let j=["## Capabilities you can request","","These are NOT active for YOU yet. Use the right one below — do NOT pretend you already can, do NOT refuse flatly, and do NOT ask the user to set up something that is already configured."];if(c.length>0)for(let a of(j.push("","Skills you can ask to be assigned:"),c))j.push(`- \`${a.slug}\` — ${a.description}`);if(f.length>0||g.length>0){for(let a of(j.push("","ALREADY configured in this workspace — just needs to be assigned to you (NO new API key needed; if you are the workspace ROOT, use `attach_connector` / `attach_mcp`, otherwise ask the user to assign it):"),f))j.push(`- ${dq(a.slug,a.name)} — connector \`${a.slug}\` (configured)`);for(let a of g)j.push(`- ${a.name} — MCP server \`${a.slug}\` (configured)`)}if(i.length>0)for(let[,a]of(j.push("","Not set up in this workspace yet — would need the user to add:"),i))j.push(`- ${a.label} — needs ${a.setup}`);return j.join("\n")}({assignedSkillSlugs:k.map(a=>a.skillSlug),attachedConnectorSlugs:l.map(a=>a.slug),attachedMcpSlugs:n.map(a=>a.slug),workspaceConnectors:o,workspaceMcps:p}),C=c?.isDelegated?"## Delegated sub-task\n\nYou are handling a sub-task delegated by an orchestrator — you are NOT addressing the end user directly. Deliver your result by calling `return_result` with your findings; the orchestrator collects it and sends the ONE final reply to the user on their original channel. Do NOT contact the user yourself — no email (e.g. `gmail_send_email`), no channel messages (`telegram_send_message` / `send_message`). A direct send from you is a duplicate and breaks the single-channel-return contract. (Producing a requested deliverable — a file, a document — is fine; it is messaging the user as a channel that is not.)":"",D=a=>a?"\n\n"+a:"";return i+D(z)+u+"\n\n"+v+w+x+t+D(B)+D(A)+D(C)+y}var ds=c(95488),dt=c(42112),du=c(75224),dv=c(73024);let dw=process.env.NODALAI_CONFIG_PATH??(0,i.join)((0,j.homedir)(),".nodalai","config.json");function dx(){if(!(0,dv.existsSync)(dw))return null;try{let a=(0,dv.readFileSync)(dw,"utf-8"),b=JSON.parse(a);if("object"!=typeof b||null===b)return null;return b}catch{return null}}function dy(a){let b=dx();if(!b)throw Error("cli_config_missing");let c={...b,...a};(0,dv.writeFileSync)(dw,JSON.stringify(c,null,2),"utf-8")}var dz=c(17030);let dA=Array.from({length:42},(a,b)=>{let c=String(b+1).padStart(2,"0");return{id:`avatar-${c}`,url:`/avatars/avatar-${c}.png`}});function dB(a){return null==a||"string"==typeof a&&dA.some(b=>b.url===a)}var dC=c(10796),dD=c(89398),dE=c(8027);async function dF(a){let b=new dC.K({name:"nodal-agents",version:"0.1.0"},{capabilities:{}});if("http"===a.transport){let c=function(a){let b=new URL(a.url),c={};if(a.apiKey){if(!a.authScheme)throw Error("buildMcpRequest: authScheme is required when apiKey is set");if("bearer"===a.authScheme)c.Authorization=`Bearer ${a.apiKey}`;else{if(!a.authParamName)throw Error(`buildMcpRequest: authParamName is required when authScheme is '${a.authScheme}'`);"query"===a.authScheme?b.searchParams.set(a.authParamName,a.apiKey):c[a.authParamName]=a.apiKey}}return{url:b,headers:c}}(a),d=new dD.j(c.url,{requestInit:{headers:c.headers}});await b.connect(d)}else{let c={};for(let[a,b]of Object.entries(process.env))"string"==typeof b&&(c[a]=b);let d=new dE.oQ({command:a.command,args:a.args,env:{...c,...a.env}});await b.connect(d)}let c=((await b.listTools()).tools??[]).map(a=>({name:a.name,description:"string"==typeof a.description?a.description:void 0,inputSchema:a.inputSchema,annotations:a.annotations}));return{client:b,tools:c,close:async()=>{await b.close()}}}g.Ik({}).catchall(g.L5()),process.env.MCP_CALL_TIMEOUT_MS;var dG=c(96591);function dH(a,b=new Date){try{return de.CronExpressionParser.parse(a.trim(),{currentDate:b}).next().toDate()}catch{return null}}var dI=c(75749);function dJ(a){return{ok:!0,data:a}}function dK(a,b){return{ok:!1,code:a,message:b}}async function dL(){let a,b=(0,ds.Iz)();try{let b=await (0,f.headers)();a=new Request("http://localhost/",{headers:b})}catch{a=new Request("http://localhost/")}let c=await (0,dt.oC)(a,b);return(0,ds.a1)(c,a)}async function dM(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({id:m.O5.id,name:m.O5.name,slug:m.O5.slug,icon:m.O5.icon,role:m.V.role}).from(m.V).innerJoin(m.O5,(0,m.eq)(m.O5.id,m.V.entityId)).where((0,m.eq)(m.V.userId,a.userId)).orderBy(m.O5.createdAt);return dJ(c.map(b=>({id:b.id,name:b.name,slug:b.slug,icon:b.icon,role:b.role??"member",active:b.id===a.entityId})))}catch(a){return console.error("[listWorkspacesAction]",a),dK("db_error","Failed to list workspaces")}}async function dN(a){try{let b,c=await dL(),d=g.Ik({name:g.Yj().min(1).max(60),icon:g.Yj().max(8).optional()}).safeParse(a);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,ds.Lf)(),h=crypto.randomUUID();return await f.insert(m.O5).values({id:h,userId:c.userId,name:d.data.name,slug:(b=d.data.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32),`${b||"workspace"}-${(0,l.randomBytes)(3).toString("hex")}`),icon:d.data.icon??"\uD83D\uDDC2️"}),await f.insert(m.V).values({entityId:h,userId:c.userId,role:"owner"}),(0,e.revalidatePath)("/","layout"),dJ({id:h})}catch(a){return console.error("[createWorkspaceAction]",a),dK("db_error","Failed to create workspace")}}async function dO(a){try{let b=await dL(),c=g.Ik({id:g.Yj().guid()}).safeParse(a);if(!c.success)return dK("validation_failed","Invalid workspace id");let d=(0,ds.Lf)(),[h]=await d.select({id:m.V.id}).from(m.V).where((0,m.Uo)((0,m.eq)(m.V.userId,b.userId),(0,m.eq)(m.V.entityId,c.data.id)));if(!h)return dK("not_found","Workspace not found");return(await (0,f.cookies)()).set(ds.St,c.data.id,{path:"/",httpOnly:!0,sameSite:"lax",maxAge:31536e3}),(0,e.revalidatePath)("/","layout"),dJ(void 0)}catch(a){return console.error("[switchWorkspaceAction]",a),dK("db_error","Failed to switch workspace")}}async function dP(a){try{let b=await dL(),c=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(60),icon:g.Yj().max(8).optional()}).safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),[f]=await d.select({role:m.V.role}).from(m.V).where((0,m.Uo)((0,m.eq)(m.V.userId,b.userId),(0,m.eq)(m.V.entityId,c.data.id)));if(!f)return dK("not_found","Workspace not found");return await d.update(m.O5).set({name:c.data.name,...c.data.icon?{icon:c.data.icon}:{},updatedAt:new Date}).where((0,m.eq)(m.O5.id,c.data.id)),(0,e.revalidatePath)("/","layout"),dJ(void 0)}catch(a){return console.error("[renameWorkspaceAction]",a),dK("db_error","Failed to rename workspace")}}async function dQ(){try{let a=await dL(),b=(0,ds.Lf)(),[c]=await b.select({timezone:m.O5.timezone}).from(m.O5).where((0,m.eq)(m.O5.id,a.entityId)),d=c?.timezone??null,e=d&&function(a){try{return new Intl.DateTimeFormat("en-US",{timeZone:a}),!0}catch{return!1}}(d)?d:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}();return dJ({timezone:e,isExplicit:!!d})}catch(a){return console.error("[getWorkspaceTimezoneAction]",a),dK("db_error","Failed to read timezone")}}async function dR(a){try{let b=await dL(),c=g.Ik({timezone:g.Yj().min(1).max(64)}).safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");try{new Intl.DateTimeFormat("en-US",{timeZone:c.data.timezone})}catch{return dK("validation_failed",`"${c.data.timezone}" is not a valid timezone.`)}let d=(0,ds.Lf)();return await d.update(m.O5).set({timezone:c.data.timezone,updatedAt:new Date}).where((0,m.eq)(m.O5.id,b.entityId)),(0,e.revalidatePath)("/","layout"),dJ(void 0)}catch(a){return console.error("[setWorkspaceTimezoneAction]",a),dK("db_error","Failed to set timezone")}}async function dS(a){try{let b=await dL(),c=g.Ik({id:g.Yj().guid()}).safeParse(a);if(!c.success)return dK("validation_failed","Invalid workspace id");if(c.data.id===b.entityId)return dK("validation_failed","Switch to another workspace before deleting this one.");let d=(0,ds.Lf)(),f=await d.select({entityId:m.V.entityId,role:m.V.role}).from(m.V).where((0,m.eq)(m.V.userId,b.userId));if(f.length<=1)return dK("validation_failed","Cannot delete your only workspace.");let h=f.find(a=>a.entityId===c.data.id);if(!h)return dK("not_found","Workspace not found");if("owner"!==h.role)return dK("forbidden","Only the owner can delete a workspace.");return await d.delete(m.O5).where((0,m.eq)(m.O5.id,c.data.id)),(0,e.revalidatePath)("/","layout"),dJ(void 0)}catch(a){return console.error("[deleteWorkspaceAction]",a),dK("db_error","Failed to delete workspace")}}let dT=g.Ik({slug:g.Yj().min(1).max(80).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with dashes"),name:g.Yj().min(1).max(120),personality:g.Yj().min(1),model:g.Yj().min(1),llmKeyId:g.Yj().guid().optional(),role:g.k5(["worker","router","planner"]).default("worker"),subAgentIds:g.YO(g.Yj().guid()).default([]),avatarUrl:g.Yj().max(200).optional().nullable().transform(a=>a&&""!==a.trim()?a.trim():null)}).refine(a=>"worker"!==a.role||0===a.subAgentIds.length,{message:"Sub-agents only apply when role is router or planner",path:["subAgentIds"]}),dU=g.Ik({prompt:g.Yj().min(1),agentId:g.Yj().guid("Must select a valid agent"),priority:g.k5(["low","medium","high"]).default("medium"),sendViaTelegram:g.KC([g.eu("true"),g.eu("false"),g.zM()]).optional().transform(a=>!0===a||"true"===a)});async function dV(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select().from(m.X6).where((0,m.eq)(m.X6.entityId,a.entityId)).orderBy(m.X6.position,m.X6.name,(0,m.i8)(m.X6.createdAt));return dJ(c)}catch(a){return console.error("[listAgentsAction]",a),dK("db_error","Failed to load agents")}}async function dW(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select().from(m.X6).where((0,m.eq)(m.X6.entityId,a.entityId)).orderBy(m.X6.position,m.X6.name),d=await b.select({orchestratorId:m.Qj.orchestratorId,subAgentId:m.Qj.subAgentId}).from(m.Qj).where((0,m.eq)(m.Qj.entityId,a.entityId)),e=new Map;for(let a of c)e.set(a.id,a);let f=new Map,g=new Set;for(let a of d){let b=f.get(a.orchestratorId)??new Set;b.add(a.subAgentId),f.set(a.orchestratorId,b),g.add(a.subAgentId)}let h=[];for(let a of c.filter(a=>"orchestrator"===a.role)){let b=f.get(a.id)??new Set,c=Array.from(b).map(a=>e.get(a)).filter(a=>!!a).sort((a,b)=>a.position-b.position||a.name.localeCompare(b.name));h.push({orchestrator:a,workers:c})}let i=c.filter(a=>"orchestrator"!==a.role&&!g.has(a.id)).sort((a,b)=>a.position-b.position||a.name.localeCompare(b.name));return i.length>0&&h.push({orchestrator:null,workers:i}),dJ(h)}catch(a){return console.error("[listAgentGroupsAction]",a),dK("db_error","Failed to load agent groups")}}async function dX(a){try{let b=await dL();if(!Array.isArray(a)||0===a.length)return dK("validation_failed","No agent ids provided");for(let b of a)if(!g.Yj().guid().safeParse(b).success)return dK("validation_failed",`Invalid agent id: ${b}`);let c=new Set,d=[];for(let b of a)c.has(b)||(c.add(b),d.push(b));let f=(0,ds.Lf)();if((await f.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.entityId,b.entityId),(0,m.RV)(m.X6.id,d)))).length!==d.length)return dK("not_found","One or more agents not in this workspace");let h=new Date;for(let a=0;a<d.length;a++){let b=d[a];b&&await f.update(m.X6).set({position:10*a,updatedAt:h}).where((0,m.eq)(m.X6.id,b))}return(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[reorderAgentsAction]",a),dK("db_error","Failed to reorder agents")}}async function dY(a){try{let b=await dL(),c=dT.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");if(!dB(c.data.avatarUrl))return dK("validation_failed","Unknown avatar — pick one from the gallery");let{dbRole:d,orchestratorMode:f}=d_(c.data.role),g=(0,ds.Lf)(),h=await (0,m.S$)(g,b.entityId,{slug:c.data.slug,name:c.data.name,personality:c.data.personality,model:c.data.model,llmKeyId:c.data.llmKeyId??null,role:d,orchestratorMode:f,avatarUrl:c.data.avatarUrl,subAgentIds:c.data.subAgentIds});if("error"in h)return dK("conflict","An agent with this slug already exists");return(0,e.revalidatePath)("/agents"),dJ({id:h.id})}catch(a){if(console.error("[createAgentAction]",a),"sub_agents_not_found"===(a instanceof Error?a.message:""))return dK("validation_failed","One or more sub-agents not found in this workspace");return dK("db_error","Failed to create agent")}}async function dZ(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");return await c.delete(m.X6).where((0,m.eq)(m.X6.id,a)),(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[deleteAgentAction]",a),dK("db_error","Failed to delete agent")}}let d$=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(120),personality:g.Yj().min(1),model:g.Yj().min(1),llmKeyId:g.Yj().guid().nullable().optional(),fallbackChain:g.YO(g.Ik({keyId:g.Yj().guid(),model:g.Yj().max(200)})).default([]),role:g.k5(["worker","router","planner"]),subAgentIds:g.YO(g.Yj().guid()).default([]),avatarUrl:g.Yj().max(200).optional().nullable().transform(a=>a&&""!==a.trim()?a.trim():null)});function d_(a){return"worker"===a?{dbRole:"agent",orchestratorMode:null}:{dbRole:"orchestrator",orchestratorMode:a}}async function d0(a){try{let b=await dL(),c=d$.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");if(!dB(c.data.avatarUrl))return dK("validation_failed","Unknown avatar — pick one from the gallery");let{id:d,name:f,personality:g,model:h,llmKeyId:i,fallbackChain:j,role:k,subAgentIds:l,avatarUrl:n}=c.data,o=(0,ds.Lf)(),[p]=await o.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b.entityId)));if(!p)return dK("not_found","Agent not found");let{dbRole:q,orchestratorMode:r}=d_(k),s={name:f,personality:g,model:h,role:q,orchestratorMode:r,updatedAt:new Date};return void 0!==i&&(s.llmKeyId=i),void 0!==n&&(s.avatarUrl=n),s.fallbackChain=j.filter(a=>a.keyId!==i),await o.update(m.X6).set(s).where((0,m.eq)(m.X6.id,d)),await o.delete(m.Qj).where((0,m.eq)(m.Qj.orchestratorId,d)),"worker"!==k&&l.length>0&&await o.insert(m.Qj).values(l.map(a=>({orchestratorId:d,subAgentId:a,entityId:b.entityId}))),await o.update(m.ME).set({systemPrompt:null,updatedAt:new Date}).where((0,m.Uo)((0,m.eq)(m.ME.agentId,d),(0,m.KL)(m.ME.status,["completed","failed","cancelled"]))),(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[updateAgentAction]",a),dK("db_error","Failed to update agent")}}async function d1(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select().from(m.Kq).where((0,m.eq)(m.Kq.agentId,a)).orderBy(m.Kq.position,m.Kq.label);return dJ(e)}catch(a){return console.error("[listAgentWorkspacesAction]",a),dK("db_error","Failed to load workspaces")}}async function d2(a,b,c){try{let d=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let f=g.Yj().min(1).max(80).safeParse(b);if(!f.success)return dK("validation_failed","Label must be 1-80 characters");let h=f.data.trim(),i=c.trim();if(!i)return dK("validation_failed","Path is required");if(!/^([A-Za-z]:[/\\]|\/|\\\\)/.test(i))return dK("validation_failed","Path must be absolute (e.g. /home/user/notes or C:\\Users\\you\\notes)");let j=(0,ds.Lf)(),[k]=await j.select({id:m.X6.id,entityId:m.X6.entityId}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,d.entityId)));if(!k)return dK("not_found","Agent not found");let[l]=await j.insert(m.Kq).values({agentId:a,entityId:k.entityId,label:h,path:i,position:0}).returning({id:m.Kq.id});if(!l)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)(`/agents/${a}/edit`),dJ({id:l.id})}catch(b){console.error("[addAgentWorkspaceAction]",b);let a=b instanceof Error?b.message:"";if(a.includes("unique")||a.includes("23505"))return dK("conflict","A workspace with this label already exists for this agent");return dK("db_error","Failed to add workspace")}}async function d3(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid workspace id");let c=(0,ds.Lf)(),[d]=await c.select({agentId:m.Kq.agentId}).from(m.Kq).where((0,m.eq)(m.Kq.id,a));if(!d)return dK("not_found","Workspace not found");let[f]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d.agentId),(0,m.eq)(m.X6.entityId,b.entityId)));if(!f)return dK("not_found","Workspace not found");return await c.delete(m.Kq).where((0,m.eq)(m.Kq.id,a)),(0,e.revalidatePath)(`/agents/${d.agentId}/edit`),dJ(void 0)}catch(a){return console.error("[removeAgentWorkspaceAction]",a),dK("db_error","Failed to remove workspace")}}let d4={"application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","text/csv":".csv","text/x-markdown":".md","application/octet-stream":""},d5=new Set([".docx",".xlsx",".pptx",".pdf",".txt",".md",".csv"]);async function d6(a,b){if(!(0,i.isAbsolute)(a))return{ok:!1,reason:"Workspace root is not an absolute path."};let c=(0,i.basename)(b);if(!c||c.startsWith("."))return{ok:!1,reason:`Invalid filename: "${b}"`};let d=await (0,h.realpath)(a).catch(()=>null);if(!d)return{ok:!1,reason:`Workspace directory does not exist: "${a}"`};let e=(0,i.resolve)(d,c),f=d.endsWith(i.sep)?d:d+i.sep;return e===d||e.startsWith(f)?{ok:!0,resolved:e}:{ok:!1,reason:`Path traversal blocked for filename "${b}".`}}async function d7(a,b,c){try{let d=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");if(!g.Yj().min(1).max(80).safeParse(b).success)return dK("validation_failed","Invalid workspace label");let f=(0,ds.Lf)(),[j]=await f.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,d.entityId)));if(!j)return dK("not_found","Agent not found");let[k]=await f.select({path:m.Kq.path}).from(m.Kq).where((0,m.Uo)((0,m.eq)(m.Kq.agentId,a),(0,m.eq)(m.Kq.label,b)));if(!k)return dK("not_found",`Workspace "${b}" not found for this agent`);let n=c.get("file");if(!(n instanceof File))return dK("validation_failed",'No file provided in FormData (field "file")');if(n.size>0x1900000)return dK("file_too_large",`File is ${n.size} bytes (max 26214400). Compress or split it first.`);let o=n.name.slice(n.name.lastIndexOf(".")).toLowerCase(),p=n.type in d4,q=d5.has(o);if(!p&&!q)return dK("unsupported_file_type",`File type "${n.type}" / extension "${o}" is not allowed. Allowed: ${[...d5].join(", ")}.`);if("application/octet-stream"===n.type&&!q)return dK("unsupported_file_type",`Extension "${o}" is not allowed. Allowed: ${[...d5].join(", ")}.`);await (0,h.mkdir)(k.path,{recursive:!0});let r=await d6(k.path,n.name);if(!r.ok)return dK("path_traversal_blocked",r.reason);let s=(0,i.dirname)(r.resolved),t=(0,i.join)(s,`.${(0,i.basename)(r.resolved)}.${(0,l.randomBytes)(6).toString("hex")}.tmp`),u=await n.arrayBuffer();try{await (0,h.writeFile)(t,Buffer.from(u)),await (0,h.rename)(t,r.resolved)}catch(a){throw await (0,h.unlink)(t).catch(()=>void 0),a}return(0,e.revalidatePath)(`/agents/${a}/edit`),dJ({filename:(0,i.basename)(r.resolved),bytes:n.size})}catch(a){return console.error("[uploadToWorkspaceAction]",a),dK("db_error","Upload failed")}}async function d8(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let d=(0,ds.Lf)(),[e]=await d.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,c.entityId)));if(!e)return dK("not_found","Agent not found");let[f]=await d.select({path:m.Kq.path}).from(m.Kq).where((0,m.Uo)((0,m.eq)(m.Kq.agentId,a),(0,m.eq)(m.Kq.label,b)));if(!f)return dK("not_found",`Workspace "${b}" not found for this agent`);if(!await (0,h.stat)(f.path).then(a=>a.isDirectory()).catch(()=>!1))return dJ([]);let j=await (0,h.readdir)(f.path,{withFileTypes:!0}),k=[];for(let a of j){if(!a.isFile())continue;let b=(0,i.join)(f.path,a.name),c=await (0,h.stat)(b).catch(()=>null);c&&k.push({name:a.name,size:c.size,modifiedAt:c.mtime.toISOString()})}return k.sort((a,b)=>a.name.localeCompare(b.name)),dJ(k)}catch(a){return console.error("[listWorkspaceFilesAction]",a),dK("db_error","Failed to list workspace files")}}async function d9(a,b,c){try{let d=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let f=(0,ds.Lf)(),[i]=await f.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,d.entityId)));if(!i)return dK("not_found","Agent not found");let[j]=await f.select({path:m.Kq.path}).from(m.Kq).where((0,m.Uo)((0,m.eq)(m.Kq.agentId,a),(0,m.eq)(m.Kq.label,b)));if(!j)return dK("not_found",`Workspace "${b}" not found for this agent`);let k=await d6(j.path,c);if(!k.ok)return dK("path_traversal_blocked",k.reason);return await (0,h.unlink)(k.resolved),(0,e.revalidatePath)(`/agents/${a}/edit`),dJ(void 0)}catch(a){if("ENOENT"===a.code)return dK("not_found",`File "${c}" not found in workspace`);return console.error("[deleteWorkspaceFileAction]",a),dK("db_error","Failed to delete file")}}async function ea(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select().from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select({subAgentId:m.Qj.subAgentId}).from(m.Qj).where((0,m.eq)(m.Qj.orchestratorId,a));return dJ({...d,orchestratorMode:d.orchestratorMode??null,subAgentIds:e.map(a=>a.subAgentId)})}catch(a){return console.error("[getAgentForEditAction]",a),dK("db_error","Failed to load agent")}}async function eb(a){try{let b=await dL(),c=dU.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),[f]=await d.select({id:m.X6.id,slug:m.X6.slug}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,c.data.agentId),(0,m.eq)(m.X6.entityId,b.entityId)));if(!f)return dK("not_found","Agent not found");let g=null;if(c.data.sendViaTelegram){let[a]=await d.select({chatId:m.X6.lastSeenChatIdTelegram}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,c.data.agentId),(0,m.eq)(m.X6.entityId,b.entityId))).limit(1);if(!a?.chatId)return dK("no_telegram_recipient_known","DM the bot first to register a recipient.");g=a.chatId}let[h]=await d.insert(m.ME).values({entityId:b.entityId,agentId:f.id,status:"pending",channel:"api",task:c.data.prompt,...g?{chatId:g}:{}}).returning({id:m.ME.id});if(!h)return dK("db_error","Failed to create job");let i=`${du._.RUNNER_URL}/api/worker`;return du._.WORKER_SECRET?fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify({jobId:h.id})}).catch(a=>{console.error("[sendTaskAction] runner ping failed:",a)}):console.error("[sendTaskAction] WORKER_SECRET missing — cannot ping runner"),(0,e.revalidatePath)("/jobs"),dJ({jobId:h.id})}catch(a){return console.error("[sendTaskAction]",a),dK("db_error","Failed to send task")}}async function ec(a={}){try{let b=await dL(),c=Math.min(a.limit??50,100),d=(0,ds.Lf)(),e=await d.select({id:m.ME.id,entityId:m.ME.entityId,agentId:m.ME.agentId,status:m.ME.status,channel:m.ME.channel,task:m.ME.task,result:m.ME.result,error:m.ME.error,chainCount:m.ME.chainCount,inputTokens:m.ME.inputTokens,outputTokens:m.ME.outputTokens,createdAt:m.ME.createdAt,completedAt:m.ME.completedAt}).from(m.ME).where((0,m.eq)(m.ME.entityId,b.entityId)).orderBy((0,m.i8)(m.ME.createdAt)).limit(c);return dJ(e)}catch(a){return console.error("[listJobsAction]",a),dK("db_error","Failed to load jobs")}}async function ed(a={}){try{let b=await dL(),c=Math.min(a.limit??50,100),d=(0,ds.Lf)(),e=await d.select({id:m.ME.id,agentName:m.X6.name,agentSlug:m.X6.slug,agentAvatarUrl:m.X6.avatarUrl,task:m.ME.task,channel:m.ME.channel,status:m.ME.status,inputTokens:m.ME.inputTokens,outputTokens:m.ME.outputTokens,costUsd:m.ME.totalCostUsd,createdAt:m.ME.createdAt,completedAt:m.ME.completedAt,parentJobId:m.ME.parentJobId}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.Uo)((0,m.eq)(m.ME.entityId,b.entityId),a.agentId?(0,m.eq)(m.ME.agentId,a.agentId):void 0)).orderBy((0,m.i8)(m.ME.createdAt)).limit(c),f=e.map(a=>a.id),g=f.length?await d.selectDistinct({p:m.ME.parentJobId}).from(m.ME).where((0,m.Uo)((0,m.eq)(m.ME.entityId,b.entityId),(0,m.RV)(m.ME.parentJobId,f))):[],h=new Set(g.map(a=>a.p).filter(a=>null!==a)),i=[...new Set(e.map(a=>a.parentJobId).filter(a=>null!==a))],j=new Map;if(i.length)for(let a of(await d.select({id:m.ME.id,name:m.X6.name}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.RV)(m.ME.id,i))))j.set(a.id,a.name??"Agent");let k=new Map(e.map(a=>[a.id,a])),l=new Map;for(let a of e)if(a.parentJobId&&k.has(a.parentJobId)){let b=l.get(a.parentJobId)??[];b.push(a),l.set(a.parentJobId,b)}let n=new Set,o=[],p=a=>{if(!n.has(a.id))for(let b of(n.add(a.id),o.push(a),l.get(a.id)??[]))p(b)};for(let a of e)a.parentJobId&&k.has(a.parentJobId)||p(a);for(let a of e)p(a);let q=o.map(a=>{let b=a.parentJobId?"delegated":h.has(a.id)?"orchestrator":"standalone",c=a.agentName??"Unknown";return{id:a.id,agentName:c,agentSlug:a.agentSlug,agentAvatarUrl:a.agentAvatarUrl??null,role:b,fromAgentName:a.parentJobId?j.get(a.parentJobId)??null:null,task:a.task,channel:a.channel,status:a.status,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,costUsd:a.costUsd??0,createdAt:a.createdAt,completedAt:a.completedAt}});return dJ(q)}catch(a){return console.error("[listDelegationRunsAction]",a),dK("db_error","Failed to load delegation runs")}}async function ee(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid job id");let c=(0,ds.Lf)(),[d]=await c.select({job:m.ME,agentName:m.X6.name,agentSlug:m.X6.slug}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.Uo)((0,m.eq)(m.ME.id,a),(0,m.eq)(m.ME.entityId,b.entityId)));if(!d)return dK("not_found","Job not found");let e=await c.select({id:m.ME.id,agentName:m.X6.name,agentSlug:m.X6.slug,status:m.ME.status,result:m.ME.result,error:m.ME.error,createdAt:m.ME.createdAt,completedAt:m.ME.completedAt}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.eq)(m.ME.parentJobId,a)).orderBy(m.ME.createdAt);return dJ({...d.job,agentName:d.agentName,agentSlug:d.agentSlug,children:e})}catch(a){return console.error("[getJobDetailAction]",a),dK("db_error","Failed to load job")}}async function ef(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid job id");let c=(0,ds.Lf)(),[d]=await c.select({status:m.ME.status,result:m.ME.result,error:m.ME.error}).from(m.ME).where((0,m.Uo)((0,m.eq)(m.ME.id,a),(0,m.eq)(m.ME.entityId,b.entityId)));if(!d)return dK("not_found","Job not found");return dJ({status:d.status??"pending",result:d.result,error:d.error})}catch(a){return console.error("[getJobStatusAction]",a),dK("db_error","Failed to load job status")}}let eg=new Set(["completed","failed","cancelled"]);async function eh(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid job id");let c=(0,ds.Lf)(),[d]=await c.select({status:m.ME.status}).from(m.ME).where((0,m.Uo)((0,m.eq)(m.ME.id,a),(0,m.eq)(m.ME.entityId,b.entityId)));if(!d)return dK("not_found","Job not found");let f=d.status??"pending";if(eg.has(f))return dK("already_terminal",`Job is already ${f}`);return await c.execute((0,m.ll)`
1463
+ ${b.join("\n\n")}`}({channel:c?.origin,telegram:!!c?.telegramChatId}),C=function(a){let b=new Set(a.assignedSkillSlugs),c=du.filter(a=>"capability"===dw(a)&&!b.has(a.slug)),d=new Set(a.attachedConnectorSlugs),e=new Set(a.attachedMcpSlugs),f=a.workspaceConnectors.filter(a=>!d.has(a.slug)),g=a.workspaceMcps.filter(a=>!e.has(a.slug)),h=new Set(a.workspaceConnectors.map(a=>a.slug)),i=Object.entries(dE).filter(([a])=>a in dg&&!d.has(a)&&!h.has(a));if(0===c.length&&0===f.length&&0===g.length&&0===i.length)return"";let j=["## Capabilities you can request","","These are NOT active for YOU yet. Use the right one below — do NOT pretend you already can, do NOT refuse flatly, and do NOT ask the user to set up something that is already configured."];if(c.length>0)for(let a of(j.push("","Skills you can ask to be assigned:"),c))j.push(`- \`${a.slug}\` — ${a.description}`);if(f.length>0||g.length>0){for(let a of(j.push("","ALREADY configured in this workspace — just needs to be assigned to you (NO new API key needed; if you are the workspace ROOT, use `attach_connector` / `attach_mcp`, otherwise ask the user to assign it):"),f))j.push(`- ${dF(a.slug,a.name)} — connector \`${a.slug}\` (configured)`);for(let a of g)j.push(`- ${a.name} — MCP server \`${a.slug}\` (configured)`)}if(i.length>0)for(let[,a]of(j.push("","Not set up in this workspace yet — would need the user to add:"),i))j.push(`- ${a.label} — needs ${a.setup}`);return j.join("\n")}({assignedSkillSlugs:k.map(a=>a.skillSlug),attachedConnectorSlugs:l.map(a=>a.slug),attachedMcpSlugs:m.map(a=>a.slug),workspaceConnectors:n,workspaceMcps:o}),D=c?.isDelegated?"## Delegated sub-task\n\nYou are handling a sub-task delegated by an orchestrator — you are NOT addressing the end user directly. Deliver your result by calling `return_result` with your findings; the orchestrator collects it and sends the ONE final reply to the user on their original channel. Do NOT contact the user yourself — no email (e.g. `gmail_send_email`), no channel messages (`telegram_send_message` / `send_message`). A direct send from you is a duplicate and breaks the single-channel-return contract. (Producing a requested deliverable — a file, a document — is fine; it is messaging the user as a channel that is not.)":"",E=a=>a?"\n\n"+a:"",F=i+E(A)+"\n\n"+v+w+t+E(C)+E(B)+E(D),G=u+x+z;return G.trim().length>0?F+y.jZ+G:F}var dH=c(95488),dI=c(57638),dJ=c(75224);let dK=process.env.NODALAI_CONFIG_PATH??(0,i.join)((0,j.homedir)(),".nodalai","config.json");function dL(){if(!(0,dn.existsSync)(dK))return null;try{let a=(0,dn.readFileSync)(dK,"utf-8"),b=JSON.parse(a);if("object"!=typeof b||null===b)return null;return b}catch{return null}}function dM(a){let b=dL();if(!b)throw Error("cli_config_missing");let c={...b,...a};(0,dn.writeFileSync)(dK,JSON.stringify(c,null,2),"utf-8")}var dN=c(17030);let dO=Array.from({length:42},(a,b)=>{let c=String(b+1).padStart(2,"0");return{id:`avatar-${c}`,url:`/avatars/avatar-${c}.png`}});function dP(a){return null==a||"string"==typeof a&&dO.some(b=>b.url===a)}var dQ=c(10796),dR=c(89398),dS=c(8027);async function dT(a,b,c,d){let e,f=new Promise((a,f)=>{e=setTimeout(()=>{d(),f(Error(`${c} timed out after ${b}ms`))},b)});try{return await Promise.race([a,f])}finally{clearTimeout(e)}}function dU(a){a.close?.()?.catch(()=>{})}async function dV(a){let b,c,d=new dQ.K({name:"nodal-agents",version:"0.1.0"},{capabilities:{}}),e=Number.isFinite(c=void 0!==(b=process.env.MCP_CONNECT_TIMEOUT_MS)?Number(b):NaN)&&c>0?c:12e4;if("http"===a.transport){let b=function(a){let b=new URL(a.url),c={};if(a.apiKey){if(!a.authScheme)throw Error("buildMcpRequest: authScheme is required when apiKey is set");if("bearer"===a.authScheme)c.Authorization=`Bearer ${a.apiKey}`;else{if(!a.authParamName)throw Error(`buildMcpRequest: authParamName is required when authScheme is '${a.authScheme}'`);"query"===a.authScheme?b.searchParams.set(a.authParamName,a.apiKey):c[a.authParamName]=a.apiKey}}return{url:b,headers:c}}(a),c=new dR.j(b.url,{requestInit:{headers:b.headers}});await dT(d.connect(c),e,`MCP connect (${b.url.hostname})`,()=>dU(c))}else{let b={};for(let[a,c]of Object.entries(process.env))"string"==typeof c&&(b[a]=c);let c=new dS.oQ({command:a.command,args:a.args,env:{...b,...a.env}});await dT(d.connect(c),e,`MCP connect (${a.command})`,()=>dU(c))}let f=((await d.listTools(void 0,{timeout:6e4})).tools??[]).map(a=>({name:a.name,description:"string"==typeof a.description?a.description:void 0,inputSchema:a.inputSchema,annotations:a.annotations}));return{client:d,tools:f,close:async()=>{await d.close()}}}g.Ik({}).catchall(g.L5()),process.env.MCP_CALL_TIMEOUT_MS;var dW=c(96591);function dX(a,b=new Date){try{return dz.CronExpressionParser.parse(a.trim(),{currentDate:b}).next().toDate()}catch{return null}}var dY=c(75749);function dZ(a){return{ok:!0,data:a}}function d$(a,b){return{ok:!1,code:a,message:b}}async function d_(){let a,b=(0,dH.Iz)();try{let b=await (0,f.headers)();a=new Request("http://localhost/",{headers:b})}catch{a=new Request("http://localhost/")}let c=await (0,dI.oC)(a,b);return(0,dH.a1)(c,a)}async function d0(){let a=(0,dH.Lf)();return(await a.select({id:p.VV.id}).from(p.VV).limit(2)).length>1?d$("multi_user_host","This action changes configuration for the entire host and is only allowed on a single-user install. With multiple accounts, edit ~/.nodalai/config.json directly on the server."):null}async function d1(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({id:p.O5.id,name:p.O5.name,slug:p.O5.slug,icon:p.O5.icon,role:p.V.role}).from(p.V).innerJoin(p.O5,(0,p.eq)(p.O5.id,p.V.entityId)).where((0,p.eq)(p.V.userId,a.userId)).orderBy(p.O5.createdAt);return dZ(c.map(b=>({id:b.id,name:b.name,slug:b.slug,icon:b.icon,role:b.role??"member",active:b.id===a.entityId})))}catch(a){return console.error("[listWorkspacesAction]",a),d$("db_error","Failed to list workspaces")}}async function d2(a){try{let b,c=await d_(),d=g.Ik({name:g.Yj().min(1).max(60),icon:g.Yj().max(8).optional()}).safeParse(a);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,dH.Lf)(),h=crypto.randomUUID();return await f.insert(p.O5).values({id:h,userId:c.userId,name:d.data.name,slug:(b=d.data.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32),`${b||"workspace"}-${(0,l.randomBytes)(3).toString("hex")}`),icon:d.data.icon??"\uD83D\uDDC2️"}),await f.insert(p.V).values({entityId:h,userId:c.userId,role:"owner"}),(0,e.revalidatePath)("/","layout"),dZ({id:h})}catch(a){return console.error("[createWorkspaceAction]",a),d$("db_error","Failed to create workspace")}}async function d3(a){try{let b=await d_(),c=g.Ik({id:g.Yj().guid()}).safeParse(a);if(!c.success)return d$("validation_failed","Invalid workspace id");let d=(0,dH.Lf)(),[h]=await d.select({id:p.V.id}).from(p.V).where((0,p.Uo)((0,p.eq)(p.V.userId,b.userId),(0,p.eq)(p.V.entityId,c.data.id)));if(!h)return d$("not_found","Workspace not found");return(await (0,f.cookies)()).set(dH.St,c.data.id,{path:"/",httpOnly:!0,sameSite:"lax",maxAge:31536e3}),(0,e.revalidatePath)("/","layout"),dZ(void 0)}catch(a){return console.error("[switchWorkspaceAction]",a),d$("db_error","Failed to switch workspace")}}async function d4(a){try{let b=await d_(),c=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(60),icon:g.Yj().max(8).optional()}).safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({role:p.V.role}).from(p.V).where((0,p.Uo)((0,p.eq)(p.V.userId,b.userId),(0,p.eq)(p.V.entityId,c.data.id)));if(!f)return d$("not_found","Workspace not found");return await d.update(p.O5).set({name:c.data.name,...c.data.icon?{icon:c.data.icon}:{},updatedAt:new Date}).where((0,p.eq)(p.O5.id,c.data.id)),(0,e.revalidatePath)("/","layout"),dZ(void 0)}catch(a){return console.error("[renameWorkspaceAction]",a),d$("db_error","Failed to rename workspace")}}async function d5(){try{let a=await d_(),b=(0,dH.Lf)(),[c]=await b.select({timezone:p.O5.timezone}).from(p.O5).where((0,p.eq)(p.O5.id,a.entityId)),d=c?.timezone??null,e=d&&function(a){try{return new Intl.DateTimeFormat("en-US",{timeZone:a}),!0}catch{return!1}}(d)?d:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}();return dZ({timezone:e,isExplicit:!!d})}catch(a){return console.error("[getWorkspaceTimezoneAction]",a),d$("db_error","Failed to read timezone")}}async function d6(a){try{let b=await d_(),c=g.Ik({timezone:g.Yj().min(1).max(64)}).safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");try{new Intl.DateTimeFormat("en-US",{timeZone:c.data.timezone})}catch{return d$("validation_failed",`"${c.data.timezone}" is not a valid timezone.`)}let d=(0,dH.Lf)();return await d.update(p.O5).set({timezone:c.data.timezone,updatedAt:new Date}).where((0,p.eq)(p.O5.id,b.entityId)),(0,e.revalidatePath)("/","layout"),dZ(void 0)}catch(a){return console.error("[setWorkspaceTimezoneAction]",a),d$("db_error","Failed to set timezone")}}async function d7(a){try{let b=await d_(),c=g.Ik({id:g.Yj().guid()}).safeParse(a);if(!c.success)return d$("validation_failed","Invalid workspace id");if(c.data.id===b.entityId)return d$("validation_failed","Switch to another workspace before deleting this one.");let d=(0,dH.Lf)(),f=await d.select({entityId:p.V.entityId,role:p.V.role}).from(p.V).where((0,p.eq)(p.V.userId,b.userId));if(f.length<=1)return d$("validation_failed","Cannot delete your only workspace.");let h=f.find(a=>a.entityId===c.data.id);if(!h)return d$("not_found","Workspace not found");if("owner"!==h.role)return d$("forbidden","Only the owner can delete a workspace.");return await d.delete(p.O5).where((0,p.eq)(p.O5.id,c.data.id)),(0,e.revalidatePath)("/","layout"),dZ(void 0)}catch(a){return console.error("[deleteWorkspaceAction]",a),d$("db_error","Failed to delete workspace")}}let d8=g.Ik({slug:g.Yj().min(1).max(80).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with dashes"),name:g.Yj().min(1).max(120),personality:g.Yj().min(1),model:g.Yj().min(1),llmKeyId:g.Yj().guid().optional(),role:g.k5(["worker","router","planner"]).default("worker"),subAgentIds:g.YO(g.Yj().guid()).default([]),avatarUrl:g.Yj().max(200).optional().nullable().transform(a=>a&&""!==a.trim()?a.trim():null)}).refine(a=>"worker"!==a.role||0===a.subAgentIds.length,{message:"Sub-agents only apply when role is router or planner",path:["subAgentIds"]}),d9=g.Ik({prompt:g.Yj().min(1),agentId:g.Yj().guid("Must select a valid agent"),priority:g.k5(["low","medium","high"]).default("medium"),sendViaTelegram:g.KC([g.eu("true"),g.eu("false"),g.zM()]).optional().transform(a=>!0===a||"true"===a)});async function ea(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select().from(p.X6).where((0,p.eq)(p.X6.entityId,a.entityId)).orderBy(p.X6.position,p.X6.name,(0,p.i8)(p.X6.createdAt));return dZ(c)}catch(a){return console.error("[listAgentsAction]",a),d$("db_error","Failed to load agents")}}async function eb(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select().from(p.X6).where((0,p.eq)(p.X6.entityId,a.entityId)).orderBy(p.X6.position,p.X6.name),d=await b.select({orchestratorId:p.Qj.orchestratorId,subAgentId:p.Qj.subAgentId}).from(p.Qj).where((0,p.eq)(p.Qj.entityId,a.entityId)),e=new Map;for(let a of c)e.set(a.id,a);let f=new Map,g=new Set;for(let a of d){let b=f.get(a.orchestratorId)??new Set;b.add(a.subAgentId),f.set(a.orchestratorId,b),g.add(a.subAgentId)}let h=[];for(let a of c.filter(a=>"orchestrator"===a.role)){let b=f.get(a.id)??new Set,c=Array.from(b).map(a=>e.get(a)).filter(a=>!!a).sort((a,b)=>a.position-b.position||a.name.localeCompare(b.name));h.push({orchestrator:a,workers:c})}let i=c.filter(a=>"orchestrator"!==a.role&&!g.has(a.id)).sort((a,b)=>a.position-b.position||a.name.localeCompare(b.name));return i.length>0&&h.push({orchestrator:null,workers:i}),dZ(h)}catch(a){return console.error("[listAgentGroupsAction]",a),d$("db_error","Failed to load agent groups")}}async function ec(a){try{let b=await d_();if(!Array.isArray(a)||0===a.length)return d$("validation_failed","No agent ids provided");for(let b of a)if(!g.Yj().guid().safeParse(b).success)return d$("validation_failed",`Invalid agent id: ${b}`);let c=new Set,d=[];for(let b of a)c.has(b)||(c.add(b),d.push(b));let f=(0,dH.Lf)();if((await f.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.entityId,b.entityId),(0,p.RV)(p.X6.id,d)))).length!==d.length)return d$("not_found","One or more agents not in this workspace");let h=new Date;for(let a=0;a<d.length;a++){let b=d[a];b&&await f.update(p.X6).set({position:10*a,updatedAt:h}).where((0,p.eq)(p.X6.id,b))}return(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[reorderAgentsAction]",a),d$("db_error","Failed to reorder agents")}}async function ed(a){try{let b=await d_(),c=d8.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");if(!dP(c.data.avatarUrl))return d$("validation_failed","Unknown avatar — pick one from the gallery");let{dbRole:d,orchestratorMode:f}=eg(c.data.role),g=(0,dH.Lf)(),h=await (0,p.S$)(g,b.entityId,{slug:c.data.slug,name:c.data.name,personality:c.data.personality,model:c.data.model,llmKeyId:c.data.llmKeyId??null,role:d,orchestratorMode:f,avatarUrl:c.data.avatarUrl,subAgentIds:c.data.subAgentIds});if("error"in h)return d$("conflict","An agent with this slug already exists");return(0,e.revalidatePath)("/agents"),dZ({id:h.id})}catch(a){if(console.error("[createAgentAction]",a),"sub_agents_not_found"===(a instanceof Error?a.message:""))return d$("validation_failed","One or more sub-agents not found in this workspace");return d$("db_error","Failed to create agent")}}async function ee(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");return await c.delete(p.X6).where((0,p.eq)(p.X6.id,a)),(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[deleteAgentAction]",a),d$("db_error","Failed to delete agent")}}let ef=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(120),personality:g.Yj().min(1),model:g.Yj().min(1),llmKeyId:g.Yj().guid().nullable().optional(),fallbackChain:g.YO(g.Ik({keyId:g.Yj().guid(),model:g.Yj().max(200)})).default([]),role:g.k5(["worker","router","planner"]),subAgentIds:g.YO(g.Yj().guid()).default([]),avatarUrl:g.Yj().max(200).optional().nullable().transform(a=>a&&""!==a.trim()?a.trim():null)});function eg(a){return"worker"===a?{dbRole:"agent",orchestratorMode:null}:{dbRole:"orchestrator",orchestratorMode:a}}async function eh(a){try{let b=await d_(),c=ef.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");if(!dP(c.data.avatarUrl))return d$("validation_failed","Unknown avatar — pick one from the gallery");let{id:d,name:f,personality:g,model:h,llmKeyId:i,fallbackChain:j,role:k,subAgentIds:l,avatarUrl:m}=c.data,n=(0,dH.Lf)(),[o]=await n.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b.entityId)));if(!o)return d$("not_found","Agent not found");if(l.length>0&&(await n.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.RV)(p.X6.id,l),(0,p.eq)(p.X6.entityId,b.entityId)))).length!==l.length)return d$("validation_failed","sub_agents_not_found");let{dbRole:q,orchestratorMode:r}=eg(k),s={name:f,personality:g,model:h,role:q,orchestratorMode:r,updatedAt:new Date};return void 0!==i&&(s.llmKeyId=i),void 0!==m&&(s.avatarUrl=m),s.fallbackChain=j.filter(a=>a.keyId!==i),await n.transaction(async a=>{await a.update(p.X6).set(s).where((0,p.eq)(p.X6.id,d)),await a.delete(p.Qj).where((0,p.eq)(p.Qj.orchestratorId,d)),"worker"!==k&&l.length>0&&await a.insert(p.Qj).values(l.map(a=>({orchestratorId:d,subAgentId:a,entityId:b.entityId}))).onConflictDoNothing({target:[p.Qj.orchestratorId,p.Qj.subAgentId]}),await a.update(p.ME).set({systemPrompt:null,updatedAt:new Date}).where((0,p.Uo)((0,p.eq)(p.ME.agentId,d),(0,p.KL)(p.ME.status,["completed","failed","cancelled"])))}),(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[updateAgentAction]",a),d$("db_error","Failed to update agent")}}async function ei(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select().from(p.Kq).where((0,p.eq)(p.Kq.agentId,a)).orderBy(p.Kq.position,p.Kq.label);return dZ(e)}catch(a){return console.error("[listAgentWorkspacesAction]",a),d$("db_error","Failed to load workspaces")}}async function ej(a,b,c){try{let d=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let f=g.Yj().min(1).max(80).safeParse(b);if(!f.success)return d$("validation_failed","Label must be 1-80 characters");let h=f.data.trim(),i=c.trim();if(!i)return d$("validation_failed","Path is required");if(!/^([A-Za-z]:[/\\]|\/|\\\\)/.test(i))return d$("validation_failed","Path must be absolute (e.g. /home/user/notes or C:\\Users\\you\\notes)");let j=(0,dH.Lf)(),[k]=await j.select({id:p.X6.id,entityId:p.X6.entityId}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,d.entityId)));if(!k)return d$("not_found","Agent not found");let[l]=await j.insert(p.Kq).values({agentId:a,entityId:k.entityId,label:h,path:i,position:0}).returning({id:p.Kq.id});if(!l)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)(`/agents/${a}/edit`),dZ({id:l.id})}catch(b){console.error("[addAgentWorkspaceAction]",b);let a=b instanceof Error?b.message:"";if(a.includes("unique")||a.includes("23505"))return d$("conflict","A workspace with this label already exists for this agent");return d$("db_error","Failed to add workspace")}}async function ek(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid workspace id");let c=(0,dH.Lf)(),[d]=await c.select({agentId:p.Kq.agentId}).from(p.Kq).where((0,p.eq)(p.Kq.id,a));if(!d)return d$("not_found","Workspace not found");let[f]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d.agentId),(0,p.eq)(p.X6.entityId,b.entityId)));if(!f)return d$("not_found","Workspace not found");return await c.delete(p.Kq).where((0,p.eq)(p.Kq.id,a)),(0,e.revalidatePath)(`/agents/${d.agentId}/edit`),dZ(void 0)}catch(a){return console.error("[removeAgentWorkspaceAction]",a),d$("db_error","Failed to remove workspace")}}let el={"application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","text/csv":".csv","text/x-markdown":".md","application/octet-stream":""},em=new Set([".docx",".xlsx",".pptx",".pdf",".txt",".md",".csv"]);async function en(a,b){if(!(0,i.isAbsolute)(a))return{ok:!1,reason:"Workspace root is not an absolute path."};let c=(0,i.basename)(b);if(!c||c.startsWith("."))return{ok:!1,reason:`Invalid filename: "${b}"`};let d=await (0,h.realpath)(a).catch(()=>null);if(!d)return{ok:!1,reason:`Workspace directory does not exist: "${a}"`};let e=(0,i.resolve)(d,c),f=d.endsWith(i.sep)?d:d+i.sep;return e===d||e.startsWith(f)?{ok:!0,resolved:e}:{ok:!1,reason:`Path traversal blocked for filename "${b}".`}}async function eo(a,b,c){try{let d=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");if(!g.Yj().min(1).max(80).safeParse(b).success)return d$("validation_failed","Invalid workspace label");let f=(0,dH.Lf)(),[j]=await f.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,d.entityId)));if(!j)return d$("not_found","Agent not found");let[k]=await f.select({path:p.Kq.path}).from(p.Kq).where((0,p.Uo)((0,p.eq)(p.Kq.agentId,a),(0,p.eq)(p.Kq.label,b)));if(!k)return d$("not_found",`Workspace "${b}" not found for this agent`);let m=c.get("file");if(!(m instanceof File))return d$("validation_failed",'No file provided in FormData (field "file")');if(m.size>0x1900000)return d$("file_too_large",`File is ${m.size} bytes (max 26214400). Compress or split it first.`);let n=m.name.slice(m.name.lastIndexOf(".")).toLowerCase(),o=m.type in el,q=em.has(n);if(!o&&!q)return d$("unsupported_file_type",`File type "${m.type}" / extension "${n}" is not allowed. Allowed: ${[...em].join(", ")}.`);if("application/octet-stream"===m.type&&!q)return d$("unsupported_file_type",`Extension "${n}" is not allowed. Allowed: ${[...em].join(", ")}.`);await (0,h.mkdir)(k.path,{recursive:!0});let r=await en(k.path,m.name);if(!r.ok)return d$("path_traversal_blocked",r.reason);let s=(0,i.dirname)(r.resolved),t=(0,i.join)(s,`.${(0,i.basename)(r.resolved)}.${(0,l.randomBytes)(6).toString("hex")}.tmp`),u=await m.arrayBuffer();try{await (0,h.writeFile)(t,Buffer.from(u)),await (0,h.rename)(t,r.resolved)}catch(a){throw await (0,h.unlink)(t).catch(()=>void 0),a}return(0,e.revalidatePath)(`/agents/${a}/edit`),dZ({filename:(0,i.basename)(r.resolved),bytes:m.size})}catch(a){return console.error("[uploadToWorkspaceAction]",a),d$("db_error","Upload failed")}}async function ep(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let d=(0,dH.Lf)(),[e]=await d.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,c.entityId)));if(!e)return d$("not_found","Agent not found");let[f]=await d.select({path:p.Kq.path}).from(p.Kq).where((0,p.Uo)((0,p.eq)(p.Kq.agentId,a),(0,p.eq)(p.Kq.label,b)));if(!f)return d$("not_found",`Workspace "${b}" not found for this agent`);if(!await (0,h.stat)(f.path).then(a=>a.isDirectory()).catch(()=>!1))return dZ([]);let j=await (0,h.readdir)(f.path,{withFileTypes:!0}),k=[];for(let a of j){if(!a.isFile())continue;let b=(0,i.join)(f.path,a.name),c=await (0,h.stat)(b).catch(()=>null);c&&k.push({name:a.name,size:c.size,modifiedAt:c.mtime.toISOString()})}return k.sort((a,b)=>a.name.localeCompare(b.name)),dZ(k)}catch(a){return console.error("[listWorkspaceFilesAction]",a),d$("db_error","Failed to list workspace files")}}async function eq(a,b,c){try{let d=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let f=(0,dH.Lf)(),[i]=await f.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,d.entityId)));if(!i)return d$("not_found","Agent not found");let[j]=await f.select({path:p.Kq.path}).from(p.Kq).where((0,p.Uo)((0,p.eq)(p.Kq.agentId,a),(0,p.eq)(p.Kq.label,b)));if(!j)return d$("not_found",`Workspace "${b}" not found for this agent`);let k=await en(j.path,c);if(!k.ok)return d$("path_traversal_blocked",k.reason);return await (0,h.unlink)(k.resolved),(0,e.revalidatePath)(`/agents/${a}/edit`),dZ(void 0)}catch(a){if("ENOENT"===a.code)return d$("not_found",`File "${c}" not found in workspace`);return console.error("[deleteWorkspaceFileAction]",a),d$("db_error","Failed to delete file")}}async function er(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select().from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({subAgentId:p.Qj.subAgentId}).from(p.Qj).where((0,p.eq)(p.Qj.orchestratorId,a));return dZ({...d,orchestratorMode:d.orchestratorMode??null,subAgentIds:e.map(a=>a.subAgentId)})}catch(a){return console.error("[getAgentForEditAction]",a),d$("db_error","Failed to load agent")}}async function es(a){try{let b=await d_(),c=d9.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({id:p.X6.id,slug:p.X6.slug}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,c.data.agentId),(0,p.eq)(p.X6.entityId,b.entityId)));if(!f)return d$("not_found","Agent not found");let g=null;if(c.data.sendViaTelegram){let[a]=await d.select({chatId:p.X6.lastSeenChatIdTelegram}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,c.data.agentId),(0,p.eq)(p.X6.entityId,b.entityId))).limit(1);if(!a?.chatId)return d$("no_telegram_recipient_known","DM the bot first to register a recipient.");g=a.chatId}let[h]=await d.insert(p.ME).values({entityId:b.entityId,agentId:f.id,status:"pending",channel:"api",task:c.data.prompt,...g?{chatId:g}:{}}).returning({id:p.ME.id});if(!h)return d$("db_error","Failed to create job");let i=`${dJ._.RUNNER_URL}/api/worker`;return dJ._.WORKER_SECRET?fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify({jobId:h.id})}).catch(a=>{console.error("[sendTaskAction] runner ping failed:",a)}):console.error("[sendTaskAction] WORKER_SECRET missing — cannot ping runner"),(0,e.revalidatePath)("/jobs"),dZ({jobId:h.id})}catch(a){return console.error("[sendTaskAction]",a),d$("db_error","Failed to send task")}}async function et(a={}){try{let b=await d_(),c=Math.min(a.limit??50,100),d=(0,dH.Lf)(),e=await d.select({id:p.ME.id,entityId:p.ME.entityId,agentId:p.ME.agentId,status:p.ME.status,channel:p.ME.channel,task:p.ME.task,result:p.ME.result,error:p.ME.error,chainCount:p.ME.chainCount,inputTokens:p.ME.inputTokens,outputTokens:p.ME.outputTokens,createdAt:p.ME.createdAt,completedAt:p.ME.completedAt}).from(p.ME).where((0,p.eq)(p.ME.entityId,b.entityId)).orderBy((0,p.i8)(p.ME.createdAt)).limit(c);return dZ(e)}catch(a){return console.error("[listJobsAction]",a),d$("db_error","Failed to load jobs")}}async function eu(a={}){try{let b=await d_(),c=Math.min(a.limit??50,100),d=(0,dH.Lf)(),e=await d.select({id:p.ME.id,agentName:p.X6.name,agentSlug:p.X6.slug,agentAvatarUrl:p.X6.avatarUrl,task:p.ME.task,channel:p.ME.channel,status:p.ME.status,inputTokens:p.ME.inputTokens,outputTokens:p.ME.outputTokens,costUsd:p.ME.totalCostUsd,createdAt:p.ME.createdAt,completedAt:p.ME.completedAt,parentJobId:p.ME.parentJobId}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.entityId,b.entityId),a.agentId?(0,p.eq)(p.ME.agentId,a.agentId):void 0)).orderBy((0,p.i8)(p.ME.createdAt)).limit(c),f=e.map(a=>a.id),g=f.length?await d.selectDistinct({p:p.ME.parentJobId}).from(p.ME).where((0,p.Uo)((0,p.eq)(p.ME.entityId,b.entityId),(0,p.RV)(p.ME.parentJobId,f))):[],h=new Set(g.map(a=>a.p).filter(a=>null!==a)),i=[...new Set(e.map(a=>a.parentJobId).filter(a=>null!==a))],j=new Map;if(i.length)for(let a of(await d.select({id:p.ME.id,name:p.X6.name}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.entityId,b.entityId),(0,p.RV)(p.ME.id,i)))))j.set(a.id,a.name??"Agent");let k=new Map(e.map(a=>[a.id,a])),l=new Map;for(let a of e)if(a.parentJobId&&k.has(a.parentJobId)){let b=l.get(a.parentJobId)??[];b.push(a),l.set(a.parentJobId,b)}let m=new Set,n=[],o=a=>{if(!m.has(a.id))for(let b of(m.add(a.id),n.push(a),l.get(a.id)??[]))o(b)};for(let a of e)a.parentJobId&&k.has(a.parentJobId)||o(a);for(let a of e)o(a);let q=n.map(a=>{let b=a.parentJobId?"delegated":h.has(a.id)?"orchestrator":"standalone",c=a.agentName??"Unknown";return{id:a.id,agentName:c,agentSlug:a.agentSlug,agentAvatarUrl:a.agentAvatarUrl??null,role:b,fromAgentName:a.parentJobId?j.get(a.parentJobId)??null:null,task:a.task,channel:a.channel,status:a.status,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,costUsd:a.costUsd??0,createdAt:a.createdAt,completedAt:a.completedAt}});return dZ(q)}catch(a){return console.error("[listDelegationRunsAction]",a),d$("db_error","Failed to load delegation runs")}}async function ev(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid job id");let c=(0,dH.Lf)(),[d]=await c.select({job:p.ME,agentName:p.X6.name,agentSlug:p.X6.slug}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.id,a),(0,p.eq)(p.ME.entityId,b.entityId)));if(!d)return d$("not_found","Job not found");let e=await c.select({id:p.ME.id,agentName:p.X6.name,agentSlug:p.X6.slug,status:p.ME.status,result:p.ME.result,error:p.ME.error,createdAt:p.ME.createdAt,completedAt:p.ME.completedAt}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.parentJobId,a),(0,p.eq)(p.ME.entityId,b.entityId))).orderBy(p.ME.createdAt);return dZ({...d.job,agentName:d.agentName,agentSlug:d.agentSlug,children:e})}catch(a){return console.error("[getJobDetailAction]",a),d$("db_error","Failed to load job")}}async function ew(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid job id");let c=(0,dH.Lf)(),[d]=await c.select({status:p.ME.status,result:p.ME.result,error:p.ME.error}).from(p.ME).where((0,p.Uo)((0,p.eq)(p.ME.id,a),(0,p.eq)(p.ME.entityId,b.entityId)));if(!d)return d$("not_found","Job not found");return dZ({status:d.status??"pending",result:d.result,error:d.error})}catch(a){return console.error("[getJobStatusAction]",a),d$("db_error","Failed to load job status")}}let ex=new Set(["completed","failed","cancelled"]);async function ey(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid job id");let c=(0,dH.Lf)(),[d]=await c.select({status:p.ME.status}).from(p.ME).where((0,p.Uo)((0,p.eq)(p.ME.id,a),(0,p.eq)(p.ME.entityId,b.entityId)));if(!d)return d$("not_found","Job not found");let f=d.status??"pending";if(ex.has(f))return d$("already_terminal",`Job is already ${f}`);return await c.execute((0,p.EI)`
1460
1464
  WITH RECURSIVE descendants AS (
1461
1465
  SELECT id FROM agent_jobs WHERE id = ${a}
1462
1466
  UNION ALL
1463
1467
  SELECT j.id
1464
1468
  FROM agent_jobs j
1465
1469
  INNER JOIN descendants d ON j.parent_job_id = d.id
1470
+ ),
1471
+ cancelled_jobs AS (
1472
+ UPDATE agent_jobs
1473
+ SET status = 'cancelled', updated_at = now()
1474
+ WHERE id IN (SELECT id FROM descendants)
1475
+ AND entity_id = ${b.entityId}
1476
+ AND status NOT IN ('completed', 'failed', 'cancelled')
1477
+ RETURNING id
1478
+ ),
1479
+ cancelled_tasks AS (
1480
+ UPDATE agent_tasks
1481
+ SET status = 'cancelled', updated_at = now()
1482
+ WHERE root_job_id IN (SELECT id FROM descendants)
1483
+ AND entity_id = ${b.entityId}
1484
+ AND status IN ('todo', 'in_progress')
1485
+ RETURNING id
1466
1486
  )
1467
- UPDATE agent_jobs
1468
- SET status = 'cancelled', updated_at = now()
1469
- WHERE id IN (SELECT id FROM descendants)
1487
+ UPDATE approval_requests
1488
+ SET status = 'expired', resolved_at = now(), resolved_by = 'system:job_cancelled'
1489
+ WHERE job_id IN (SELECT id FROM descendants)
1470
1490
  AND entity_id = ${b.entityId}
1471
- AND status NOT IN ('completed', 'failed', 'cancelled')
1472
- `),(0,e.revalidatePath)("/jobs"),(0,e.revalidatePath)(`/jobs/${a}`),dJ({status:"cancelled"})}catch(a){return console.error("[cancelJobAction]",a),dK("db_error","Failed to cancel job")}}let ei=g.Ik({agentId:g.Yj().guid(),botToken:g.Yj().min(20,"Token looks too short").max(200,"Token looks too long").regex(/^\d+:[A-Za-z0-9_-]+$/,"Token must look like 123456789:AAAAA...")});async function ej(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id,slug:m.X6.slug,name:m.X6.name,botToken:m.X6.telegramBotToken,botUsername:m.X6.telegramBotUsername,lastSeenChatIdTelegram:m.X6.lastSeenChatIdTelegram}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");return dJ({agentId:d.id,agentSlug:d.slug,agentName:d.name,status:d.botToken?"connected":"disconnected",botUsername:d.botUsername,lastSeenChatIdTelegram:d.lastSeenChatIdTelegram})}catch(a){return console.error("[getAgentTelegramConfigAction]",a),dK("db_error","Failed to load Telegram config")}}async function ek(a){try{let b,c=await dL(),d=ei.safeParse(a);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let{agentId:f,botToken:g}=d.data,h=(0,ds.Lf)(),[i]=await h.select({id:m.X6.id,slug:m.X6.slug,name:m.X6.name}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,f),(0,m.eq)(m.X6.entityId,c.entityId)));if(!i)return dK("not_found","Agent not found");try{b=await p(g)}catch(a){if(a instanceof n&&"telegram_invalid_token"===a.code)return dK("telegram_invalid_token","Telegram rejected this token. Double-check it from @BotFather.");throw a}let j=0;try{let a=await q({botToken:g,offset:-1,timeout:0,limit:1});a.length>0&&(j=Math.max(...a.map(a=>a.update_id))+1)}catch{}return await h.update(m.X6).set({telegramBotToken:g,telegramBotUsername:b.username,telegramOffset:j,updatedAt:new Date}).where((0,m.eq)(m.X6.id,f)),(0,e.revalidatePath)("/agents"),(0,e.revalidatePath)(`/agents/${f}/telegram`),dJ({agentId:i.id,agentSlug:i.slug,agentName:i.name,status:"connected",botUsername:b.username,lastSeenChatIdTelegram:null})}catch(a){return console.error("[configureAgentTelegramAction]",a),dK("db_error","Failed to configure Telegram")}}async function el(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");return await c.update(m.X6).set({telegramBotToken:null,telegramBotUsername:null,telegramOffset:null,updatedAt:new Date}).where((0,m.eq)(m.X6.id,a)),(0,e.revalidatePath)("/agents"),(0,e.revalidatePath)(`/agents/${a}/telegram`),dJ(void 0)}catch(a){return console.error("[disconnectAgentTelegramAction]",a),dK("db_error","Failed to disconnect Telegram")}}let em=g.Ik({agentId:g.Yj().guid().optional(),category:g.k5(["preference","context","outcome","learned_rule"]).optional(),tag:g.Yj().min(1).max(80).optional(),archived:g.zM().default(!1),page:g.ai().int().min(1).default(1),pageSize:g.ai().int().min(1).max(200).default(50)});async function en(a={}){try{let b=await dL(),c=em.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),e=await C(d,{entityId:b.entityId,agentId:c.data.agentId,category:c.data.category,tags:c.data.tag?[c.data.tag]:void 0,archived:c.data.archived,page:c.data.page,pageSize:c.data.pageSize,sort:"recent"}),f=Array.from(new Set(e.items.map(a=>a.agent_id).filter(a=>null!==a))),g=new Map;if(f.length>0)for(let a of(await d.select({id:m.X6.id,name:m.X6.name,slug:m.X6.slug}).from(m.X6).where((0,m.RV)(m.X6.id,f))))g.set(a.id,{name:a.name,slug:a.slug});let h=e.items.map(a=>{let b=a.agent_id?g.get(a.agent_id):null;return{...a,agentName:b?.name??null,agentSlug:b?.slug??null}});return dJ({items:h,page:e.page,pageSize:e.pageSize,totalCount:e.totalCount,hasMore:e.hasMore})}catch(a){return console.error("[listMemoriesAction]",a),dK("db_error","Failed to load memories")}}async function eo(a){try{let b=await dL(),c=a.trim();if(!c)return dJ([]);let d=(0,ds.Lf)(),e=await G(d,{query:c,entityId:b.entityId,limit:50,touch:!1}),f=Array.from(new Set(e.map(a=>a.agent_id).filter(a=>null!==a))),g=new Map;if(f.length>0)for(let a of(await d.select({id:m.X6.id,name:m.X6.name,slug:m.X6.slug}).from(m.X6).where((0,m.RV)(m.X6.id,f))))g.set(a.id,{name:a.name,slug:a.slug});let h=e.map(a=>{let b=a.agent_id?g.get(a.agent_id):null;return{...a,agentName:b?.name??null,agentSlug:b?.slug??null}});return dJ(h)}catch(a){return console.error("[searchMemoriesAction]",a),dK("db_error","Failed to search memories")}}let ep=g.Ik({fact:g.Yj().min(1).max(2e3),category:g.k5(["preference","context","outcome","learned_rule"]).default("context"),importance:g.ai().int().min(1).max(5).default(3)});async function eq(a){try{let b=await dL(),c=ep.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)();try{await y(d,{entity_id:b.entityId,agent_id:null,fact:c.data.fact,category:c.data.category,importance:c.data.importance,source:"manual",skill_tags:[]})}catch(a){if(a instanceof u)return dJ(void 0);throw a}return dJ(void 0)}catch(a){return console.error("[createMemoryAction]",a),dK("db_error","Failed to save memory")}}async function er(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid memory id");let c=(0,ds.Lf)();return await z(c,a,b.entityId,{archived:!0}),(0,e.revalidatePath)("/memories"),dJ(void 0)}catch(a){if(a instanceof s)return dK("not_found","Memory not found");return console.error("[archiveMemoryAction]",a),dK("db_error","Failed to archive memory")}}let es=g.Ik({id:g.Yj().guid(),importance:g.ai().int().min(1).max(5)});async function et(a,b){try{let c=await dL(),d=es.safeParse({id:a,importance:b});if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,ds.Lf)();return await z(f,d.data.id,c.entityId,{importance:d.data.importance,importance_locked:!0}),(0,e.revalidatePath)("/memories"),dJ(void 0)}catch(a){if(a instanceof s)return dK("not_found","Memory not found");return console.error("[updateMemoryImportanceAction]",a),dK("db_error","Failed to update importance")}}async function eu(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid memory id");let c=(0,ds.Lf)();return await z(c,a,b.entityId,{importance_locked:!1}),(0,e.revalidatePath)("/memories"),dJ(void 0)}catch(a){if(a instanceof s)return dK("not_found","Memory not found");return console.error("[unpinMemoryImportanceAction]",a),dK("db_error","Failed to unpin importance")}}async function ev(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid memory id");let c=(0,ds.Lf)();return await z(c,a,b.entityId,{archived:!1}),(0,e.revalidatePath)("/memories"),dJ(void 0)}catch(a){if(a instanceof s)return dK("not_found","Memory not found");return console.error("[unarchiveMemoryAction]",a),dK("db_error","Failed to unarchive memory")}}async function ew(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid memory id");let c=(0,ds.Lf)();return await A(c,a,b.entityId),(0,e.revalidatePath)("/memories"),dJ(void 0)}catch(a){if(a instanceof s)return dK("not_found","Memory not found");return console.error("[deleteMemoryAction]",a),dK("db_error","Failed to delete memory")}}async function ex(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select().from(m.tK).where((0,m.eq)(m.tK.entityId,a.entityId)),d=[...new Set(c.map(a=>a.credentialId).filter(a=>null!==a))],e=d.length>0?await b.select().from(m.z3).where((0,m.RV)(m.z3.id,d)):[],f=new Map;for(let a of e)f.set(a.id,a);let g=new Map;for(let a of e)try{let b=a.payload,c=b.startsWith("enc:v1:")?(0,L.Yc)(b):b,d=JSON.parse(c);g.set(a.id,{accountName:"string"==typeof d.accountName?d.accountName:null,expiresAt:"string"==typeof d.expiresAt&&d.expiresAt?new Date(d.expiresAt):null,scopes:"string"==typeof d.scopes?d.scopes:null})}catch{g.set(a.id,{accountName:null,expiresAt:null,scopes:null})}let h=c.map(a=>{let b=a.credentialId?f.get(a.credentialId):void 0,c=a.credentialId?g.get(a.credentialId)??null:null;return{id:a.id,slug:a.slug,name:a.name,authType:a.authType,active:a.active??!0,hasApiKey:!!a.apiKey,credentialId:a.credentialId??null,credentialName:b?.name??null,credentialType:b?b.type:null,credentialAccountName:c?.accountName??null,credentialExpiresAt:c?.expiresAt??null,credentialScopes:c?.scopes??null,createdAt:a.createdAt,updatedAt:a.updatedAt}}),i=dz.Y.map(a=>({slug:a.slug,label:a.label,authType:a.authType,docsHint:a.docsHint,credentialType:a.credentialType??null}));return dJ({instances:h,catalog:i})}catch(a){return console.error("[listConnectorsAction]",a),dK("db_error","Failed to load connectors")}}let ey=g.Ik({slug:g.Yj().min(1).max(80),name:g.Yj().min(1,"Name is required").max(120),apiKey:g.Yj().min(1,"API key is required")});async function ez(a){try{let b=await dL(),c=ey.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=dz.Y.find(a=>a.slug===c.data.slug);if(!d)return dK("validation_failed","Unknown connector slug");if("api_key"!==d.authType)return dK("validation_failed",`Connector ${c.data.slug} uses ${d.authType}, not api_key`);let f=(0,ds.Lf)(),g=(0,L.ph)(c.data.apiKey)?c.data.apiKey:(0,L.w)(c.data.apiKey),[h]=await f.insert(m.tK).values({entityId:b.entityId,slug:c.data.slug,name:c.data.name,apiKey:g,authType:"api_key",active:!0}).returning({id:m.tK.id});if(!h)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/connectors"),dJ({id:h.id})}catch(a){return console.error("[saveApiKeyConnectorAction]",a),dK("db_error","Failed to save connector")}}async function eA(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid connector id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.tK.id}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.id,a),(0,m.eq)(m.tK.entityId,b.entityId)));if(!d)return dK("not_found","Connector not found");return await c.delete(m.tK).where((0,m.eq)(m.tK.id,a)),(0,e.revalidatePath)("/connectors"),dJ(void 0)}catch(a){return console.error("[deleteConnectorAction]",a),dK("db_error","Failed to delete connector")}}async function eB(){try{let a=await dL(),b=(0,ds.Lf)(),c=(await b.select().from(m.h_).where((0,m.eq)(m.h_.entityId,a.entityId))).map(a=>({id:a.id,slug:a.slug,name:a.name,active:a.active??!0,hasApiKey:!!a.apiKey,apiKeyLast4:a.apiKeyLast4??null,toolCount:Array.isArray(a.availableTools)?a.availableTools.length:0,createdAt:a.createdAt})),d=v.$s.map(a=>({slug:a.slug,label:a.label,description:a.description,docsHint:a.docsHint,keyPrefix:a.keyPrefix,serverUrl:a.serverUrl,transport:a.transport,command:a.command,args:a.args,envVarNames:a.envVarNames,status:a.status??"verified"}));return dJ({instances:c,catalog:d})}catch(a){return console.error("[listMcpServersAction]",a),dK("db_error","Failed to load MCP connectors")}}let eC=g.Ik({slug:g.Yj().min(1).max(80),name:g.Yj().min(1,"Name is required").max(120),apiKey:g.Yj().max(2e3).optional(),url:g.Yj().url("Invalid URL").optional(),customSlug:g.Yj().min(2).max(30).regex(/^[a-z0-9-]+$/,"Slug must be lowercase letters, digits, dashes").optional(),customAuthScheme:g.k5(["header","query","bearer"]).optional(),customAuthParamName:g.Yj().min(1).max(100).optional(),customCommand:g.Yj().min(1).max(200).optional(),customArgs:g.YO(g.Yj().max(500)).max(20).optional(),customEnv:g.g1(g.Yj(),g.Yj().max(2e3)).optional()});async function eD(a){try{let b=await dL(),c=eC.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=v.$s.find(a=>a.slug===c.data.slug);if(!d)return dK("validation_failed","Unknown MCP connector");let f="custom-http-mcp"===d.slug,g="custom-stdio-mcp"===d.slug,h=d.slug,i=d.transport,j=d.authScheme,k=d.authParamName;if(f){if(!c.data.customSlug)return dK("validation_failed","Server slug is required for custom MCP");if(!c.data.customAuthScheme)return dK("validation_failed","Auth scheme is required for custom MCP");if(h=c.data.customSlug,j=c.data.customAuthScheme,k="bearer"===c.data.customAuthScheme?"Authorization":c.data.customAuthParamName??"","bearer"!==j&&!k)return dK("validation_failed",`Auth param name is required for the "${j}" scheme`)}else if(g){if(!c.data.customSlug)return dK("validation_failed","Server slug is required for custom MCP");if(!c.data.customCommand)return dK("validation_failed","Command is required for stdio MCP");h=c.data.customSlug,i="stdio"}if(f||g){let a=(0,ds.Lf)();if((await a.select({id:m.h_.id}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.entityId,b.entityId),(0,m.eq)(m.h_.slug,h)))).length>0)return dK("slug_taken",`Slug "${h}" is already used by another MCP server. Pick a different one.`)}if("http"===i){let a=(c.data.apiKey??"").trim();if(!a)return dK("validation_failed","API key is required");if(!f&&d.keyPrefix.length>0&&!d.keyPrefix.some(b=>a.startsWith(b))){let a=1===d.keyPrefix.length?`"${d.keyPrefix[0]}"`:`one of: ${d.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return dK("validation_failed",`API key must start with ${a}`)}let g=d.serverUrl??c.data.url??null;if(!g)return dK("validation_failed",`${d.label} requires a server URL`);let i=[],l=null;try{if(l=await dF({transport:"http",url:g,apiKey:a,authScheme:j,authParamName:k}),d.verifyToolName&&!f){let a=await l.client.callTool({name:d.verifyToolName,arguments:{}});if(!0===a.isError)return dK("mcp_connect_failed",`${d.label} rejected the API key.`)}i=l.tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return dK("mcp_connect_failed",`Could not connect to ${d.label}: ${a}`)}finally{l&&await l.close().catch(()=>{})}let n=(0,ds.Lf)(),o=(0,L.w)(a),[p]=await n.insert(m.h_).values({entityId:b.entityId,name:c.data.name,slug:h,transport:"http",url:g,apiKey:o,apiKeyLast4:(0,L.nK)(a),authScheme:j,authParamName:k,availableTools:i,active:!0}).returning({id:m.h_.id});if(!p)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/mcp"),dJ({id:p.id})}let l=g?c.data.customCommand:d.command??c.data.customCommand,n=c.data.customArgs??d.args??[],o=c.data.customEnv??{},p=[],q=null;try{p=(q=await dF({transport:"stdio",command:l,args:n,env:o})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return dK("mcp_connect_failed",`Could not start ${d.label} subprocess (${l}): ${a}`)}finally{q&&await q.close().catch(()=>{})}let r={};for(let[a,b]of Object.entries(o))r[a]=(0,L.w)(b);let s=(0,ds.Lf)(),[t]=await s.insert(m.h_).values({entityId:b.entityId,name:c.data.name,slug:h,transport:"stdio",url:null,apiKey:null,apiKeyLast4:null,authScheme:null,authParamName:null,command:l,args:n,envVars:r,availableTools:p,active:!0}).returning({id:m.h_.id});if(!t)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/mcp"),dJ({id:t.id})}catch(a){return console.error("[createMcpServerFromCatalogAction]",a),dK("db_error","Failed to save MCP connector")}}async function eE(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid MCP server id");let d=g.Yj().min(1,"Name is required").max(120).safeParse(b);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid name");let f=(0,ds.Lf)(),[h]=await f.select({id:m.h_.id}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,a),(0,m.eq)(m.h_.entityId,c.entityId)));if(!h)return dK("not_found","MCP connector not found");return await f.update(m.h_).set({name:d.data,updatedAt:new Date}).where((0,m.eq)(m.h_.id,a)),(0,e.revalidatePath)("/mcp"),dJ(void 0)}catch(a){return console.error("[renameMcpServerAction]",a),dK("db_error","Failed to rename MCP server")}}async function eF(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid MCP server id");let d=g.Yj().min(1,"API key is required").max(2e3).safeParse(b);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid API key");let f=d.data.trim(),h=(0,ds.Lf)(),[i]=await h.select({id:m.h_.id,slug:m.h_.slug,url:m.h_.url,authScheme:m.h_.authScheme,authParamName:m.h_.authParamName}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,a),(0,m.eq)(m.h_.entityId,c.entityId)));if(!i)return dK("not_found","MCP connector not found");let j=v.$s.find(a=>a.slug===i.slug);if(j&&j.keyPrefix.length>0&&!j.keyPrefix.some(a=>f.startsWith(a))){let a=1===j.keyPrefix.length?`"${j.keyPrefix[0]}"`:`one of: ${j.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return dK("validation_failed",`API key must start with ${a}`)}if(!i.url||!i.authScheme||!i.authParamName)return dK("validation_failed","MCP server has incomplete configuration");let k=[],l=null;try{l=await dF({transport:"http",url:i.url,apiKey:f,authScheme:i.authScheme,authParamName:i.authParamName}),k=((await l.client.listTools()).tools??[]).map(a=>({name:a.name,description:a.description??null})),j?.verifyToolName&&await l.client.callTool({name:j.verifyToolName,arguments:{}})}catch(b){let a=b instanceof Error?b.message:"unknown error";return dK("mcp_connect_failed",`Couldn't verify the new key: ${a}`)}finally{l&&await l.close().catch(()=>{})}let n=(0,L.ph)(f)?f:(0,L.w)(f);return await h.update(m.h_).set({apiKey:n,apiKeyLast4:(0,L.nK)(f),availableTools:k,updatedAt:new Date}).where((0,m.eq)(m.h_.id,a)),(0,e.revalidatePath)("/mcp"),dJ(void 0)}catch(a){return console.error("[updateMcpServerApiKeyAction]",a),dK("db_error","Failed to rotate MCP API key")}}async function eG(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid MCP server id");let c=(0,ds.Lf)(),[d]=await c.select().from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,a),(0,m.eq)(m.h_.entityId,b.entityId)));if(!d)return dK("not_found","MCP connector not found");let e=d.envVars??{};return dJ({id:d.id,name:d.name,slug:d.slug,transport:d.transport,url:d.url??null,authScheme:d.authScheme??null,authParamName:d.authParamName??null,command:d.command??null,args:Array.isArray(d.args)?d.args:[],envKeys:Object.keys(e),hasApiKey:!!d.apiKey,apiKeyLast4:d.apiKeyLast4??null})}catch(a){return console.error("[getMcpServerConfigAction]",a),dK("db_error","Failed to load MCP server config")}}let eH=g.Ik({name:g.Yj().min(1,"Name is required").max(120),url:g.Yj().url("Invalid URL").optional(),authScheme:g.k5(["header","query","bearer"]).optional(),authParamName:g.Yj().max(100).optional(),apiKey:g.Yj().max(2e3).optional(),command:g.Yj().min(1).max(200).optional(),args:g.YO(g.Yj().max(500)).max(20).optional(),env:g.g1(g.Yj(),g.Yj().max(2e3)).optional()});async function eI(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid MCP server id");let d=eH.safeParse(b);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,ds.Lf)(),[h]=await f.select().from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,a),(0,m.eq)(m.h_.entityId,c.entityId)));if(!h)return dK("not_found","MCP connector not found");let i=v.$s.find(a=>a.slug===h.slug);if("http"===h.transport){let b,c=(d.data.url??h.url??"").trim();if(!c)return dK("validation_failed","Server URL is required");let g=d.data.authScheme??h.authScheme??"header",j="bearer"===g?"Authorization":(d.data.authParamName??h.authParamName??"").trim();if("bearer"!==g&&!j)return dK("validation_failed",`Auth param name is required for the "${g}" scheme`);let k=(d.data.apiKey??"").trim(),l=k.length>0;if(l){if(i&&i.keyPrefix.length>0&&!i.keyPrefix.some(a=>k.startsWith(a))){let a=1===i.keyPrefix.length?`"${i.keyPrefix[0]}"`:`one of: ${i.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return dK("validation_failed",`API key must start with ${a}`)}b=k}else{if(!h.apiKey)return dK("validation_failed","No stored API key — provide one to connect");try{b=(0,L.Yc)(h.apiKey)}catch{return dK("validation_failed","Stored API key is unreadable — re-enter it")}}let n=[],o=null;try{n=(o=await dF({transport:"http",url:c,apiKey:b,authScheme:g,authParamName:j})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return dK("mcp_connect_failed",`Could not connect with the new config: ${a}`)}finally{o&&await o.close().catch(()=>{})}return await f.update(m.h_).set({name:d.data.name,url:c,authScheme:g,authParamName:j,availableTools:n,...l?{apiKey:(0,L.w)(b),apiKeyLast4:(0,L.nK)(b)}:{},updatedAt:new Date}).where((0,m.eq)(m.h_.id,a)),(0,e.revalidatePath)("/mcp"),dJ(void 0)}let j=(d.data.command??h.command??"").trim();if(!j)return dK("validation_failed","Command is required");let k=d.data.args??(Array.isArray(h.args)?h.args:[]),l=h.envVars??{},n=d.data.env,o={},p={};for(let[a,b]of n?Object.entries(n):Object.entries(l).map(([a])=>[a,""]))if(b&&b.length>0)o[a]=b,p[a]=(0,L.w)(b);else if(void 0!==l[a]){try{o[a]=(0,L.Yc)(l[a])}catch{return dK("validation_failed",`Stored value for "${a}" is unreadable — re-enter it`)}p[a]=l[a]}let q=[],r=null;try{q=(r=await dF({transport:"stdio",command:j,args:k,env:o})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return dK("mcp_connect_failed",`Could not start the subprocess (${j}): ${a}`)}finally{r&&await r.close().catch(()=>{})}return await f.update(m.h_).set({name:d.data.name,command:j,args:k,envVars:p,availableTools:q,updatedAt:new Date}).where((0,m.eq)(m.h_.id,a)),(0,e.revalidatePath)("/mcp"),dJ(void 0)}catch(a){return console.error("[updateMcpServerConfigAction]",a),dK("db_error","Failed to update MCP server")}}async function eJ(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid MCP server id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.h_.id}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,a),(0,m.eq)(m.h_.entityId,b.entityId)));if(!d)return dK("not_found","MCP connector not found");return await c.delete(m.h_).where((0,m.eq)(m.h_.id,a)),(0,e.revalidatePath)("/mcp"),dJ(void 0)}catch(a){return console.error("[deleteMcpServerAction]",a),dK("db_error","Failed to delete MCP connector")}}async function eK(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select({id:m.h_.id,slug:m.h_.slug,name:m.h_.name,availableTools:m.h_.availableTools}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.entityId,b.entityId),(0,m.eq)(m.h_.active,!0)));if(0===e.length)return dJ([]);let f=await c.select({mcpServerId:m.oS.mcpServerId,enabledTools:m.oS.enabledTools}).from(m.oS).where((0,m.eq)(m.oS.agentId,a)),h=new Map;for(let a of f)h.set(a.mcpServerId,{enabledTools:a.enabledTools??null});let i=e.map(a=>{let b=h.get(a.id);return{mcpServerId:a.id,slug:a.slug,label:a.name,assigned:void 0!==b,enabledTools:b?.enabledTools??null,availableTools:Array.isArray(a.availableTools)?a.availableTools:[]}});return dJ(i)}catch(a){return console.error("[listAgentMcpServersAction]",a),dK("db_error","Failed to load agent MCP connectors")}}async function eL(a,b,c,d){try{let f=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");if(!g.Yj().guid().safeParse(b).success)return dK("validation_failed","Invalid MCP server id");let h=(0,ds.Lf)(),[i]=await h.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,f.entityId)));if(!i)return dK("not_found","Agent not found");let[j]=await h.select({id:m.h_.id}).from(m.h_).where((0,m.Uo)((0,m.eq)(m.h_.id,b),(0,m.eq)(m.h_.entityId,f.entityId)));if(!j)return dK("not_found","MCP connector not found");return c?await h.insert(m.oS).values({agentId:a,mcpServerId:b,entityId:f.entityId,enabledTools:d??null}).onConflictDoUpdate({target:[m.oS.agentId,m.oS.mcpServerId],set:{enabledTools:d??null,updatedAt:new Date}}):await h.delete(m.oS).where((0,m.Uo)((0,m.eq)(m.oS.agentId,a),(0,m.eq)(m.oS.mcpServerId,b))),(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[setAgentMcpServerAssignmentAction]",a),dK("db_error","Failed to update MCP assignment")}}async function eM(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid connector id");if(null!==b&&!g.Yj().guid().safeParse(b).success)return dK("validation_failed","Invalid credential id");let d=(0,ds.Lf)(),[f]=await d.select({id:m.tK.id,slug:m.tK.slug,authType:m.tK.authType}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.id,a),(0,m.eq)(m.tK.entityId,c.entityId)));if(!f)return dK("not_found","Connector not found");if("oauth2"!==f.authType)return dK("invalid_auth_type","Only OAuth2 connectors support credential assignment");if(null!==b){let[a]=await d.select({id:m.z3.id,ownerUserId:m.z3.ownerUserId,type:m.z3.type}).from(m.z3).where((0,m.eq)(m.z3.id,b));if(!a)return dK("not_found","Credential not found");if(a.ownerUserId!==c.userId)return dK("forbidden","Access denied");let e=(0,dG.ZH)(f.slug);if(e&&e.credentialType!==a.type)return dK("type_mismatch",`Credential type '${a.type}' is not compatible with connector '${f.slug}' (expects '${e.credentialType}')`)}return await d.update(m.tK).set({credentialId:b,updatedAt:new Date}).where((0,m.eq)(m.tK.id,a)),(0,e.revalidatePath)("/connectors"),dJ(void 0)}catch(b){console.error("[assignCredentialAction]",b);let a=b instanceof Error?b.message:String(b);return dK("db_error",`Failed to assign credential: ${a}`)}}async function eN(a,b,c){try{let d=await dL();if(!g.Yj().min(1).max(80).safeParse(a).success)return dK("validation_failed","Invalid connector slug");if(!g.Yj().guid().safeParse(b).success)return dK("validation_failed","Invalid credential id");if(void 0!==c&&!g.Yj().min(1).max(120).safeParse(c).success)return dK("validation_failed","Invalid connector name");let f=dz.Y.find(b=>b.slug===a);if(!f)return dK("validation_failed","Unknown connector slug");if("oauth2"!==f.authType)return dK("invalid_auth_type","Only OAuth2 connectors support credential assignment");let h=(0,ds.Lf)(),[i]=await h.select({id:m.z3.id,ownerUserId:m.z3.ownerUserId,type:m.z3.type,name:m.z3.name}).from(m.z3).where((0,m.eq)(m.z3.id,b));if(!i)return dK("not_found","Credential not found");if(i.ownerUserId!==d.userId)return dK("forbidden","Access denied");if(f.credentialType&&f.credentialType!==i.type)return dK("type_mismatch",`Credential type '${i.type}' is not compatible with connector '${a}' (expects '${f.credentialType}')`);let j=c??i.name??f.label,[k]=await h.insert(m.tK).values({entityId:d.entityId,slug:a,name:j,authType:"oauth2",credentialId:b,active:!0}).returning({id:m.tK.id});if(!k)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/connectors"),dJ({connectorId:k.id})}catch(b){console.error("[createOrAssignOAuthConnectorAction]",b);let a=b instanceof Error?b.message:String(b);return dK("db_error",`Failed to assign credential: ${a}`)}}async function eO(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid connector id");let d=g.Yj().min(1,"Name is required").max(120).safeParse(b);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid name");let f=(0,ds.Lf)(),[h]=await f.select({id:m.tK.id}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.id,a),(0,m.eq)(m.tK.entityId,c.entityId)));if(!h)return dK("not_found","Connector not found");return await f.update(m.tK).set({name:d.data,updatedAt:new Date}).where((0,m.eq)(m.tK.id,a)),(0,e.revalidatePath)("/connectors"),dJ(void 0)}catch(a){return console.error("[renameConnectorAction]",a),dK("db_error","Failed to rename connector")}}async function eP(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid connector id");let d=g.Yj().min(1,"API key is required").max(2e3).safeParse(b);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid API key");let f=(0,ds.Lf)(),[h]=await f.select({id:m.tK.id,authType:m.tK.authType}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.id,a),(0,m.eq)(m.tK.entityId,c.entityId)));if(!h)return dK("not_found","Connector not found");if("api_key"!==h.authType)return dK("validation_failed",`Connector uses ${h.authType??"unknown"} auth — key rotation only applies to api_key connectors.`);let i=(0,L.ph)(d.data)?d.data:(0,L.w)(d.data);return await f.update(m.tK).set({apiKey:i,updatedAt:new Date}).where((0,m.eq)(m.tK.id,a)),(0,e.revalidatePath)("/connectors"),dJ(void 0)}catch(a){return console.error("[updateConnectorApiKeyAction]",a),dK("db_error","Failed to rotate API key")}}async function eQ(a={}){try{let b=await dL(),c=(0,ds.Lf)(),d=a.status??"pending",e=(0,m.eq)(m.MZ.entityId,b.entityId),f="all"===d?e:(0,m.Uo)(e,(0,m.eq)(m.MZ.status,d)),g=await c.select({id:m.MZ.id,jobId:m.MZ.jobId,agentId:m.MZ.agentId,agentName:m.X6.name,agentSlug:m.X6.slug,toolName:m.MZ.toolName,toolInput:m.MZ.toolInput,status:m.MZ.status,requestedAt:m.MZ.requestedAt,resolvedAt:m.MZ.resolvedAt,resolvedBy:m.MZ.resolvedBy,expiresAt:m.MZ.expiresAt,notes:m.MZ.notes,jobTask:m.ME.task}).from(m.MZ).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.MZ.agentId)).leftJoin(m.ME,(0,m.eq)(m.ME.id,m.MZ.jobId)).where(f).orderBy((0,m.i8)(m.MZ.requestedAt)).limit(100);return dJ(g.map(a=>({...a,status:a.status??"pending"})))}catch(a){return console.error("[listApprovalsAction]",a),dK("db_error","Failed to load approvals")}}let eR=g.Ik({approvalRequestId:g.Yj().guid(),decision:g.k5(["approve","reject"]),notes:g.Yj().max(5e3).optional()});async function eS(a){try{let b;await dL();let c=eR.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");if(!du._.WORKER_SECRET)return console.error("[resolveApprovalAction] WORKER_SECRET missing"),dK("config_error","WORKER_SECRET is not set");let d=`${du._.RUNNER_URL}/api/approve`;try{b=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify(c.data)})}catch(a){return console.error("[resolveApprovalAction] fetch failed",a),dK("runner_unreachable","Runner did not respond")}if(!b.ok){let a=(await b.json().catch(()=>({}))).error??`runner_${b.status}`;return dK(a,`Runner rejected: ${a}`)}let f=await b.json();return(0,e.revalidatePath)("/approvals"),(0,e.revalidatePath)("/jobs"),(0,e.revalidatePath)(`/jobs/${f.jobId}`),dJ({jobId:f.jobId,decision:f.decision})}catch(a){return console.error("[resolveApprovalAction]",a),dK("db_error","Failed to resolve approval")}}async function eT(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select({id:m.bN.id,toolName:m.bN.toolName,action:m.bN.action}).from(m.bN).where((0,m.Uo)((0,m.eq)(m.bN.entityId,b.entityId),(0,m.eq)(m.bN.agentId,a)));return dJ(e.map(a=>({id:a.id,toolName:a.toolName,action:a.action??"auto_approve"})))}catch(a){return console.error("[listAgentApprovalRulesAction]",a),dK("db_error","Failed to load approval rules")}}let eU=g.Ik({agentId:g.Yj().guid(),toolName:g.Yj().min(1).max(200),action:g.k5(["auto_approve","require_approval","block"]).nullable()});async function eV(a){try{let b=await dL(),c=eU.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,toolName:f,action:g}=c.data,h=(0,ds.Lf)(),[i]=await h.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b.entityId)));if(!i)return dK("not_found","Agent not found");if(null===g||"auto_approve"===g)await h.delete(m.bN).where((0,m.Uo)((0,m.eq)(m.bN.entityId,b.entityId),(0,m.eq)(m.bN.agentId,d),(0,m.eq)(m.bN.toolName,f)));else{let a=await h.select({id:m.bN.id}).from(m.bN).where((0,m.Uo)((0,m.eq)(m.bN.entityId,b.entityId),(0,m.eq)(m.bN.agentId,d),(0,m.eq)(m.bN.toolName,f))).limit(1);a.length>0&&a[0]?await h.update(m.bN).set({action:g,updatedAt:new Date}).where((0,m.eq)(m.bN.id,a[0].id)):await h.insert(m.bN).values({entityId:b.entityId,agentId:d,toolName:f,action:g})}return(0,e.revalidatePath)(`/agents/${d}/edit`),dJ(void 0)}catch(a){return console.error("[setAgentApprovalRuleAction]",a),dK("db_error","Failed to save approval rule")}}let eW=g.Ik({agentId:g.Yj().guid(),enabled:g.zM()});async function eX(a){try{let b=await dL(),c=eW.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,enabled:f}=c.data;if("local-trust"!==du._.AUTH_MODE){let a=(0,ds.Lf)(),[c]=await a.select({userId:m.O5.userId,lanCommandYolo:m.O5.lanCommandYolo}).from(m.O5).where((0,m.eq)(m.O5.id,b.entityId));if(!c)return dK("not_found","Workspace not found");if(c.userId!==b.userId)return dK("forbidden","Only the workspace owner can change command auto-run.");if(f&&!c.lanCommandYolo)return dK("forbidden","Yolo mode is not enabled for this workspace. Enable it in Settings → Command execution first.")}let g=(0,ds.Lf)(),[h]=await g.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b.entityId)));if(!h)return dK("not_found","Agent not found");return await g.delete(m.bN).where((0,m.Uo)((0,m.eq)(m.bN.entityId,b.entityId),(0,m.eq)(m.bN.agentId,d),(0,m.eq)(m.bN.toolName,"run_command"))),f&&await g.insert(m.bN).values({entityId:b.entityId,agentId:d,toolName:"run_command",action:"auto_approve"}),(0,e.revalidatePath)(`/agents/${d}/edit`),dJ(void 0)}catch(a){return console.error("[setRunCommandYoloAction]",a),dK("db_error","Failed to save command execution setting")}}async function eY(){try{let a=await dL(),b=(0,ds.Lf)(),[c]=await b.select({userId:m.O5.userId,lanCommandYolo:m.O5.lanCommandYolo}).from(m.O5).where((0,m.eq)(m.O5.id,a.entityId));if(!c)return dK("not_found","Workspace not found");return dJ({lanCommandYolo:c.lanCommandYolo,isOwner:c.userId===a.userId})}catch(a){return console.error("[getLanCommandYoloAction]",a),dK("db_error","Failed to load LAN command yolo setting")}}let eZ=g.Ik({enabled:g.zM()});async function e$(a){try{let b=await dL(),c=eZ.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{enabled:d}=c.data,f=(0,ds.Lf)(),[g]=await f.select({userId:m.O5.userId}).from(m.O5).where((0,m.eq)(m.O5.id,b.entityId));if(!g)return dK("not_found","Workspace not found");if(g.userId!==b.userId)return dK("forbidden","Only the workspace owner can change this setting.");return await f.update(m.O5).set({lanCommandYolo:d}).where((0,m.eq)(m.O5.id,b.entityId)),(0,e.revalidatePath)("/settings"),(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[setLanCommandYoloAction]",a),dK("db_error","Failed to save LAN command yolo setting")}}async function e_(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({id:m.eK.id,name:m.eK.name,slug:m.eK.slug,content:m.eK.content,defaultContent:m.eK.defaultContent,contentOverridden:m.eK.contentOverridden,description:m.eK.description,active:m.eK.active,requiredBuiltins:m.eK.requiredBuiltins,isCommunity:m.eK.isCommunity,source:m.eK.source,installedScripts:m.eK.installedScripts,createdAt:m.eK.createdAt,updatedAt:m.eK.updatedAt}).from(m.eK).where((0,m.or)((0,m.eq)(m.eK.entityId,a.entityId),(0,m.RV)(m.eK.slug,di))).orderBy((0,m.i8)(m.eK.updatedAt));if(0===c.length)return dJ([]);let d=await b.select({skillId:m.$m.skillId,c:(0,m.ll)`count(*)`}).from(m.$m).where((0,m.Uo)((0,m.eq)(m.$m.entityId,a.entityId),(0,m.RV)(m.$m.skillId,c.map(a=>a.id)))).groupBy(m.$m.skillId),e=new Map;for(let a of d)e.set(a.skillId,Number(a.c));let f=await b.select({skillId:m.$m.skillId,agentId:m.X6.id,agentName:m.X6.name,agentSlug:m.X6.slug,avatarUrl:m.X6.avatarUrl}).from(m.$m).innerJoin(m.X6,(0,m.eq)(m.X6.id,m.$m.agentId)).where((0,m.Uo)((0,m.eq)(m.$m.entityId,a.entityId),(0,m.RV)(m.$m.skillId,c.map(a=>a.id)))).orderBy(m.X6.name),g=new Map;for(let a of f){let b=g.get(a.skillId)??[];b.length<8&&(b.push({id:a.agentId,name:a.agentName,slug:a.agentSlug,avatarUrl:a.avatarUrl}),g.set(a.skillId,b))}return dJ(c.map(a=>({id:a.id,name:a.name,slug:a.slug,isSystem:di.includes(a.slug),systemKind:dk(a.slug),content:a.content,defaultContent:a.defaultContent,contentOverridden:a.contentOverridden??!1,description:a.description,active:a.active??!0,requiredBuiltins:a.requiredBuiltins??[],isCommunity:a.isCommunity??!1,source:a.source,installedScripts:a.installedScripts??null,scriptsAuthorized:null,filesWritable:null,assignmentCount:e.get(a.id)??0,assignedAgents:g.get(a.id)??[],createdAt:a.createdAt,updatedAt:a.updatedAt})))}catch(a){return console.error("[listSkillsAction]",a),dK("db_error","Failed to load skills")}}let e0=g.Ik({slug:g.Yj().min(1).max(80).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with dashes"),name:g.Yj().min(1).max(120),content:g.Yj().min(1),description:g.Yj().max(500).optional()});async function e1(a){try{let b=await dL(),c=e0.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),f=await (0,m.qz)(d,b.entityId,{slug:c.data.slug,name:c.data.name,content:c.data.content,description:c.data.description??null});if("error"in f)return dK("conflict","A skill with this slug already exists");return(0,e.revalidatePath)("/skills"),dJ({id:f.id})}catch(a){return console.error("[createSkillAction]",a),dK("db_error","Failed to create skill")}}async function e2(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid skill id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.eK.id}).from(m.eK).where((0,m.Uo)((0,m.eq)(m.eK.id,a),(0,m.eq)(m.eK.entityId,b.entityId)));if(!d)return dK("not_found","Skill not found");return await c.delete(m.eK).where((0,m.eq)(m.eK.id,a)),(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[deleteSkillAction]",a),dK("db_error","Failed to delete skill")}}let e3=g.Ik({source:g.Yj().min(1).max(2048)});async function e4(a){try{let b,c=await dL(),d=e3.safeParse({source:a});if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");if(!du._.WORKER_SECRET)return console.error("[installCommunitySkillAction] WORKER_SECRET missing"),dK("config_error","Runner secret not configured");try{b=await fetch(`${du._.RUNNER_URL}/api/skills/install`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify({source:d.data.source,entityId:c.entityId})})}catch(a){return console.error("[installCommunitySkillAction] fetch failed:",a),dK("network_error","Could not reach the runner — is it running?")}let f=await b.json();if(!f.ok)return dK(f.error,f.message);return(0,e.revalidatePath)("/skills"),dJ(f.skill)}catch(a){return console.error("[installCommunitySkillAction]",a),dK("unexpected_error","An unexpected error occurred")}}async function e5(a){try{let b,c=await dL();if(!g.Yj().min(1).safeParse(a).success)return dK("validation_failed","Invalid skill slug");if(!du._.WORKER_SECRET)return console.error("[uninstallCommunitySkillAction] WORKER_SECRET missing"),dK("config_error","Runner secret not configured");try{b=await fetch(`${du._.RUNNER_URL}/api/skills/uninstall`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify({slug:a,entityId:c.entityId})})}catch(a){return console.error("[uninstallCommunitySkillAction] fetch failed:",a),dK("network_error","Could not reach the runner — is it running?")}let d=await b.json();if(!d.ok)return dK(d.error??"uninstall_failed",d.message??"Uninstall failed");return(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[uninstallCommunitySkillAction]",a),dK("unexpected_error","An unexpected error occurred")}}let e6=g.Ik({skillId:g.Yj().guid(),agentId:g.Yj().guid()});async function e7(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid skill id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.eK.id}).from(m.eK).where((0,m.Uo)((0,m.eq)(m.eK.id,a),(0,m.eq)(m.eK.entityId,b.entityId)));if(!d)return dK("not_found","Skill not found");let e=await c.select({id:m.X6.id,name:m.X6.name,slug:m.X6.slug}).from(m.X6).where((0,m.eq)(m.X6.entityId,b.entityId)).orderBy(m.X6.name),f=await c.select({agentId:m.$m.agentId}).from(m.$m).where((0,m.eq)(m.$m.skillId,a)),h=new Set(f.map(a=>a.agentId));return dJ(e.map(a=>({agentId:a.id,agentName:a.name,agentSlug:a.slug,assigned:h.has(a.id)})))}catch(a){return console.error("[listSkillAssignmentsAction]",a),dK("db_error","Failed to load skill assignments")}}async function e8(a){try{let b=await dL(),c=e6.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),f=await (0,m.ps)(d,b.entityId,c.data,di);if("error"in f){if("skill_not_found"===f.error)return dK("not_found","Skill not found");if("agent_not_found"===f.error)return dK("not_found","Agent not found")}return(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[assignSkillAction]",a),dK("db_error","Failed to assign skill")}}let e9=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(120),description:g.Yj().max(500).optional(),content:g.Yj().min(1),active:g.zM().optional()});async function fa(a){try{let b=await dL(),c=e9.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{id:d,name:f,description:g,content:h,active:i}=c.data,j=(0,ds.Lf)(),[k]=await j.select({id:m.eK.id,content:m.eK.content}).from(m.eK).where((0,m.Uo)((0,m.eq)(m.eK.id,d),(0,m.eq)(m.eK.entityId,b.entityId)));if(!k)return dK("not_found","Skill not found");let l={name:f,description:g??null,content:h,...void 0!==i?{active:i}:{},updatedAt:new Date};return h!==k.content&&(l.contentOverridden=!0),await j.update(m.eK).set(l).where((0,m.eq)(m.eK.id,d)),(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[updateSkillAction]",a),dK("db_error","Failed to update skill")}}async function fb(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid skill id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.eK.id,defaultContent:m.eK.defaultContent}).from(m.eK).where((0,m.Uo)((0,m.eq)(m.eK.id,a),(0,m.eq)(m.eK.entityId,b.entityId)));if(!d)return dK("not_found","Skill not found");if(null===d.defaultContent)return dK("not_applicable","No default available — this is a user-created skill");return await c.update(m.eK).set({content:d.defaultContent,contentOverridden:!1,updatedAt:new Date}).where((0,m.eq)(m.eK.id,a)),(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[resetSkillToDefaultAction]",a),dK("db_error","Failed to reset skill")}}async function fc(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid skill id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.eK.id,name:m.eK.name,slug:m.eK.slug,content:m.eK.content,defaultContent:m.eK.defaultContent,contentOverridden:m.eK.contentOverridden,description:m.eK.description,active:m.eK.active,requiredBuiltins:m.eK.requiredBuiltins,isCommunity:m.eK.isCommunity,source:m.eK.source,installedScripts:m.eK.installedScripts,createdAt:m.eK.createdAt,updatedAt:m.eK.updatedAt}).from(m.eK).where((0,m.Uo)((0,m.eq)(m.eK.id,a),(0,m.or)((0,m.eq)(m.eK.entityId,b.entityId),(0,m.RV)(m.eK.slug,di))));if(!d)return dK("not_found","Skill not found");return dJ({id:d.id,name:d.name,slug:d.slug,isSystem:di.includes(d.slug),systemKind:dk(d.slug),content:d.content,defaultContent:d.defaultContent,contentOverridden:d.contentOverridden??!1,description:d.description,active:d.active??!0,requiredBuiltins:d.requiredBuiltins??[],isCommunity:d.isCommunity??!1,source:d.source,installedScripts:d.installedScripts??null,scriptsAuthorized:null,filesWritable:null,assignmentCount:0,assignedAgents:[],createdAt:d.createdAt,updatedAt:d.updatedAt})}catch(a){return console.error("[getSkillByIdAction]",a),dK("db_error","Failed to load skill")}}async function fd(a){try{let b=await dL(),c=e6.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)();return await d.delete(m.$m).where((0,m.Uo)((0,m.eq)(m.$m.skillId,c.data.skillId),(0,m.eq)(m.$m.agentId,c.data.agentId),(0,m.eq)(m.$m.entityId,b.entityId))),(0,e.revalidatePath)("/skills"),dJ(void 0)}catch(a){return console.error("[unassignSkillAction]",a),dK("db_error","Failed to unassign skill")}}async function fe(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select({id:m.eK.id,name:m.eK.name,slug:m.eK.slug,content:m.eK.content,defaultContent:m.eK.defaultContent,contentOverridden:m.eK.contentOverridden,description:m.eK.description,active:m.eK.active,requiredBuiltins:m.eK.requiredBuiltins,isCommunity:m.eK.isCommunity,source:m.eK.source,installedScripts:m.eK.installedScripts,createdAt:m.eK.createdAt,updatedAt:m.eK.updatedAt,scriptsAuthorized:m.$m.scriptsAuthorized,filesWritable:m.$m.filesWritable}).from(m.$m).innerJoin(m.eK,(0,m.eq)(m.eK.id,m.$m.skillId)).where((0,m.Uo)((0,m.eq)(m.$m.agentId,a),(0,m.eq)(m.$m.entityId,b.entityId))).orderBy(m.eK.name);return dJ(e.map(a=>({id:a.id,name:a.name,slug:a.slug,isSystem:di.includes(a.slug),systemKind:dk(a.slug),content:a.content,defaultContent:a.defaultContent,contentOverridden:a.contentOverridden??!1,description:a.description,active:a.active??!0,requiredBuiltins:a.requiredBuiltins??[],isCommunity:a.isCommunity??!1,source:a.source,installedScripts:a.installedScripts??null,scriptsAuthorized:a.scriptsAuthorized??!1,filesWritable:a.filesWritable??!1,assignmentCount:1,assignedAgents:[],createdAt:a.createdAt,updatedAt:a.updatedAt})))}catch(a){return console.error("[getAgentAttachedSkillsAction]",a),dK("db_error","Failed to load agent skills")}}let ff=g.Ik({agentId:g.Yj().guid(),skillId:g.Yj().guid(),authorized:g.zM()});async function fg(a){try{let b=await dL(),c=ff.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,skillId:f,authorized:g}=c.data,h=(0,ds.Lf)(),[i]=await h.select({userId:m.O5.userId}).from(m.O5).where((0,m.eq)(m.O5.id,b.entityId));if(!i)return dK("not_found","Workspace not found");if(i.userId!==b.userId)return dK("forbidden","Only the workspace owner can authorize skill scripts.");let[j]=await h.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b.entityId)));if(!j)return dK("not_found","Agent not found");let k=await (0,m.ZU)(h,d,f,g);if("error"in k)return dK("not_assigned","This skill is not assigned to the agent.");return(0,e.revalidatePath)(`/agents/${d}/edit`),dJ(void 0)}catch(a){return console.error("[setSkillScriptsAuthorizedAction]",a),dK("db_error","Failed to save script authorization")}}let fh=g.Ik({agentId:g.Yj().guid(),skillId:g.Yj().guid(),writable:g.zM()});async function fi(a){try{let b=await dL(),c=fh.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,skillId:f,writable:g}=c.data,h=(0,ds.Lf)(),[i]=await h.select({userId:m.O5.userId}).from(m.O5).where((0,m.eq)(m.O5.id,b.entityId));if(!i)return dK("not_found","Workspace not found");if(i.userId!==b.userId)return dK("forbidden","Only the workspace owner can authorize skill file writes.");let[j]=await h.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b.entityId)));if(!j)return dK("not_found","Agent not found");let k=await (0,m.rY)(h,d,f,g);if("error"in k)return dK("not_assigned","This skill is not assigned to the agent.");return(0,e.revalidatePath)(`/agents/${d}/edit`),dJ(void 0)}catch(a){return console.error("[setSkillFilesWritableAction]",a),dK("db_error","Failed to save file-write authorization")}}let fj=g.Ik({agentId:g.Yj().guid().optional(),toolName:g.Yj().min(1).max(120).optional(),jobId:g.Yj().guid().optional(),page:g.ai().int().min(1).default(1),pageSize:g.ai().int().min(1).max(200).default(50)});async function fk(a={}){try{let b=await dL(),c=fj.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),e=[(0,m.eq)(m.Ky.entityId,b.entityId)];c.data.toolName&&e.push((0,m.eq)(m.Ky.toolName,c.data.toolName)),c.data.jobId&&e.push((0,m.eq)(m.Ky.jobId,c.data.jobId));let f=(c.data.page-1)*c.data.pageSize,g=c.data.agentId?await d.select({id:m.Ky.id,jobId:m.Ky.jobId,agentId:m.ME.agentId,toolName:m.Ky.toolName,toolInput:m.Ky.toolInput,toolOutput:m.Ky.toolOutput,durationMs:m.Ky.durationMs,turn:m.Ky.turn,createdAt:m.Ky.createdAt}).from(m.Ky).leftJoin(m.ME,(0,m.eq)(m.ME.id,m.Ky.jobId)).where((0,m.Uo)(...e,(0,m.eq)(m.ME.agentId,c.data.agentId))).orderBy((0,m.i8)(m.Ky.createdAt)).limit(c.data.pageSize).offset(f):await d.select({id:m.Ky.id,jobId:m.Ky.jobId,agentId:m.ME.agentId,toolName:m.Ky.toolName,toolInput:m.Ky.toolInput,toolOutput:m.Ky.toolOutput,durationMs:m.Ky.durationMs,turn:m.Ky.turn,createdAt:m.Ky.createdAt}).from(m.Ky).leftJoin(m.ME,(0,m.eq)(m.ME.id,m.Ky.jobId)).where((0,m.Uo)(...e)).orderBy((0,m.i8)(m.Ky.createdAt)).limit(c.data.pageSize).offset(f),h=Array.from(new Set(g.map(a=>a.agentId).filter(a=>null!==a))),i=new Map;if(h.length>0)for(let a of(await d.select({id:m.X6.id,name:m.X6.name,slug:m.X6.slug}).from(m.X6).where((0,m.RV)(m.X6.id,h))))i.set(a.id,{name:a.name,slug:a.slug});let j=g.map(a=>{let b=a.agentId?i.get(a.agentId):null;return{id:a.id,jobId:a.jobId,agentId:a.agentId,agentName:b?.name??null,agentSlug:b?.slug??null,toolName:a.toolName,toolInput:a.toolInput,toolOutput:a.toolOutput,durationMs:a.durationMs,turn:a.turn,createdAt:a.createdAt}});return dJ({items:j,page:c.data.page,pageSize:c.data.pageSize})}catch(a){return console.error("[listToolCallsAction]",a),dK("db_error","Failed to load tool calls")}}async function fl(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.selectDistinct({toolName:m.Ky.toolName}).from(m.Ky).where((0,m.eq)(m.Ky.entityId,a.entityId)).orderBy(m.Ky.toolName);return dJ(c.map(a=>a.toolName))}catch(a){return console.error("[listToolNamesAction]",a),dK("db_error","Failed to load tool names")}}async function fm(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({status:m.ME.status,count:(0,m.ll)`count(*)`,inputTokens:(0,m.ll)`coalesce(sum(${m.ME.inputTokens}), 0)`,outputTokens:(0,m.ll)`coalesce(sum(${m.ME.outputTokens}), 0)`,durationMs:(0,m.ll)`coalesce(sum(${m.ME.totalDurationMs}), 0)`}).from(m.ME).where((0,m.eq)(m.ME.entityId,a.entityId)).groupBy(m.ME.status),d={},e=0,f=0,g=0,h=0;for(let a of c){let b=a.status??"unknown",c=Number(a.count);d[b]=(d[b]??0)+c,e+=c,f+=Number(a.inputTokens),g+=Number(a.outputTokens),h+=Number(a.durationMs)}let i=d.completed??0,j=i>0?h/i:null,[k]=await b.select({count:(0,m.ll)`count(*)`}).from(m.Ky).where((0,m.eq)(m.Ky.entityId,a.entityId)),l=Number(k?.count??0),n=(await b.select({agentId:m.ME.agentId,agentName:m.X6.name,agentSlug:m.X6.slug,jobCount:(0,m.ll)`count(*)`,inputTokens:(0,m.ll)`coalesce(sum(${m.ME.inputTokens}), 0)`,outputTokens:(0,m.ll)`coalesce(sum(${m.ME.outputTokens}), 0)`}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.eq)(m.ME.entityId,a.entityId)).groupBy(m.ME.agentId,m.X6.name,m.X6.slug).orderBy((0,m.i8)((0,m.ll)`count(*)`))).filter(a=>!!(a.agentId&&a.agentName&&a.agentSlug)).map(a=>({agentId:a.agentId,agentName:a.agentName,agentSlug:a.agentSlug,jobCount:Number(a.jobCount),inputTokens:Number(a.inputTokens),outputTokens:Number(a.outputTokens)})),[o]=await b.select({count:(0,m.ll)`count(*)`}).from(m.X6).where((0,m.eq)(m.X6.entityId,a.entityId)),p=Number(o?.count??0);return dJ({totalJobs:e,statusCounts:d,totalInputTokens:f,totalOutputTokens:g,totalDurationMs:h,avgDurationMs:j,totalToolCalls:l,agentCount:p,perAgent:n})}catch(a){return console.error("[getEntityStatsAction]",a),dK("db_error","Failed to load stats")}}async function fn(a,b){try{let c=await dL(),d=(0,ds.Lf)(),e="week"===a?(0,m.ll)`date_trunc('week', ${m.ME.createdAt})`:(0,m.ll)`date_trunc('day', ${m.ME.createdAt})`,f="week"===a?(0,m.ll)`${m.ME.createdAt} > now() - interval '12 weeks'`:(0,m.ll)`${m.ME.createdAt} > now() - interval '7 days'`,g=await d.select({bucket:(0,m.ll)`to_char(${e}, 'YYYY-MM-DD')`,status:m.ME.status,model:m.X6.model,provider:m.hG.provider,count:(0,m.ll)`count(*)`}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).leftJoin(m.hG,(0,m.eq)(m.hG.id,m.X6.llmKeyId)).where((0,m.Uo)((0,m.eq)(m.ME.entityId,c.entityId),f)).groupBy(e,m.ME.status,m.X6.model,m.hG.provider),h=new Map;for(let a of b)h.set(a,{week:a,completed:0,failed:0,cancelled:0,awaiting:0,pending:0,models:{}});let i=new Map;for(let a of g){let b=h.get(a.bucket);if(!b)continue;let c=Number(a.count),d=a.status??"";"completed"===d?b.completed+=c:"failed"===d?b.failed+=c:"cancelled"===d?b.cancelled+=c:"pending"===d?b.pending+=c:b.awaiting+=c;let e=function(a,b){if(!b)return"unknown";let c=(b.includes("/")?b.split("/").pop()??b:b).replace(/-20\d{6}$/,""),d=a&&a.trim()?a.trim():"";return d?`${d}/${c}`:c}(a.provider,a.model&&a.model.trim()?a.model:"");b.models[e]=(b.models[e]??0)+c,i.set(e,(i.get(e)??0)+c)}let j=Array.from(i.entries()).sort((a,b)=>b[1]-a[1]).map(([a])=>a);return dJ({rows:Array.from(h.values()),models:j})}catch(a){return console.error("[loadActivity]",a),dK("db_error","Failed to load activity")}}async function fo(){let a=new Date,b=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())),c=(b.getUTCDay()+6)%7;b.setUTCDate(b.getUTCDate()-c);let d=[];for(let a=11;a>=0;a--){let c=new Date(b);c.setUTCDate(c.getUTCDate()-7*a),d.push(c.toISOString().slice(0,10))}return fn("week",d)}async function fp(){let a=new Date,b=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())),c=[];for(let a=6;a>=0;a--){let d=new Date(b);d.setUTCDate(d.getUTCDate()-a),c.push(d.toISOString().slice(0,10))}return fn("day",c)}async function fq(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({agentId:m.ME.agentId,agentName:m.X6.name,agentSlug:m.X6.slug,avatarUrl:m.X6.avatarUrl,status:m.ME.status,count:(0,m.ll)`count(*)`}).from(m.ME).innerJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.Uo)((0,m.eq)(m.ME.entityId,a.entityId),(0,m.ll)`${m.ME.status} IN ('pending', 'processing', 'awaiting_approval', 'awaiting_delegation')`)).groupBy(m.ME.agentId,m.X6.name,m.X6.slug,m.X6.avatarUrl,m.ME.status),d=new Map;for(let a of c){if(!a.agentId||!a.agentName||!a.agentSlug)continue;let b=d.get(a.agentId)??{agentId:a.agentId,agentName:a.agentName,agentSlug:a.agentSlug,avatarUrl:a.avatarUrl??null,processing:0,awaiting:0,pending:0,total:0},c=Number(a.count),e=a.status??"";"processing"===e?b.processing+=c:"awaiting_approval"===e||"awaiting_delegation"===e?b.awaiting+=c:"pending"===e&&(b.pending+=c),b.total+=c,d.set(a.agentId,b)}let e=Array.from(d.values()).sort((a,b)=>b.total!==a.total?b.total-a.total:a.agentName.localeCompare(b.agentName));return dJ(e)}catch(a){return console.error("[getActiveJobsByAgentAction]",a),dK("db_error","Failed to load active jobs")}}async function fr(){try{let a=await dL(),b=(0,i.join)((0,j.homedir)(),".nodalai","workspaces",a.entityId,"shared");return dJ({llm:{provider:du._.LLM_PROVIDER??null,model:du._.LLM_MODEL??null,baseURL:du._.LLM_BASE_URL??null},authMode:du._.AUTH_MODE,runnerUrl:du._.RUNNER_URL,appUrl:du._.NEXT_PUBLIC_APP_URL,sharedWorkspaceUrl:(0,k.pathToFileURL)(b).href,sharedWorkspacePath:b,sharedWorkspacePathShort:`~/.nodalai/workspaces/${a.entityId.slice(0,8)}…/shared`,workerSecretConfigured:!!du._.WORKER_SECRET,user:{userId:a.userId,entityId:a.entityId}})}catch(a){return console.error("[getSettingsAction]",a),dK("db_error","Failed to load settings")}}let fs=null;async function ft(){let a=process.env.NODAL_VERSION??null,b=null;try{let a=Date.now();if(fs&&a-fs.at<18e5)b=fs.latest;else{let c=new AbortController,d=setTimeout(()=>c.abort(),4e3);try{let a=await fetch("https://registry.npmjs.org/nodal-agents/latest",{signal:c.signal,headers:{accept:"application/json"}});if(a.ok){let c=await a.json();b="string"==typeof c.version?c.version:null}}finally{clearTimeout(d)}fs={at:a,latest:b}}}catch{b=null}let c=!!(a&&b&&function(a,b){let c=a=>a.split("-")[0].split(".").map(a=>parseInt(a,10)||0),d=c(a),e=c(b);for(let a=0;a<3;a++)if((d[a]??0)!==(e[a]??0))return(d[a]??0)>(e[a]??0);return!1}(b,a));return dJ({current:a,latest:b,updateAvailable:c})}async function fu(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({id:m.uQ.id,agentId:m.uQ.agentId,agentName:m.X6.name,agentSlug:m.X6.slug,name:m.uQ.name,cronExpr:m.uQ.cronExpr,task:m.uQ.task,active:m.uQ.active,lastRun:m.uQ.lastRun,nextRun:m.uQ.nextRun,lastStatus:m.uQ.lastStatus,notifyOnSuccess:m.uQ.notifyOnSuccess,createdAt:m.uQ.createdAt,updatedAt:m.uQ.updatedAt}).from(m.uQ).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.uQ.agentId)).where((0,m.eq)(m.uQ.entityId,a.entityId)).orderBy((0,m.i8)(m.uQ.updatedAt));return dJ(c.map(a=>({...a,active:a.active??!0,notifyOnSuccess:a.notifyOnSuccess??!1})))}catch(a){return console.error("[listSchedulesAction]",a),dK("db_error","Failed to load schedules")}}let fv=g.Ik({agentId:g.Yj().guid("Pick an agent"),name:g.Yj().min(1).max(120),cronExpr:g.Yj().min(1).max(100),task:g.Yj().min(1),notifyOnSuccess:g.zM().optional().default(!1)});async function fw(a){try{let b=await dL(),c=fv.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),[f]=await d.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,c.data.agentId),(0,m.eq)(m.X6.entityId,b.entityId)));if(!f)return dK("not_found","Agent not found");let g=dH(c.data.cronExpr);if(!g)return dK("validation_failed","Invalid cron expression");let[h]=await d.insert(m.uQ).values({entityId:b.entityId,agentId:c.data.agentId,type:"cron",name:c.data.name,cronExpr:c.data.cronExpr,task:c.data.task,active:!0,nextRun:g,notifyOnSuccess:c.data.notifyOnSuccess}).returning({id:m.uQ.id});if(!h)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/automations"),dJ({id:h.id})}catch(a){return console.error("[createScheduleAction]",a),dK("db_error","Failed to create schedule")}}async function fx(a){try{if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid schedule id");let b=await dL(),c=(0,ds.Lf)(),[d]=await c.select({agentId:m.uQ.agentId,type:m.uQ.type,name:m.uQ.name,cronExpr:m.uQ.cronExpr,task:m.uQ.task,notifyOnSuccess:m.uQ.notifyOnSuccess}).from(m.uQ).where((0,m.Uo)((0,m.eq)(m.uQ.id,a),(0,m.eq)(m.uQ.entityId,b.entityId)));if(!d)return dK("not_found","Schedule not found");let[f]=await c.insert(m.uQ).values({entityId:b.entityId,agentId:d.agentId,type:d.type??"cron",name:`${d.name} (copy)`,cronExpr:d.cronExpr,task:d.task,active:!1,nextRun:null,notifyOnSuccess:d.notifyOnSuccess??!1}).returning({id:m.uQ.id});if(!f)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/automations"),dJ({id:f.id})}catch(a){return console.error("[duplicateScheduleAction]",a),dK("db_error","Failed to duplicate schedule")}}let fy=g.Ik({id:g.Yj().guid(),agentId:g.Yj().guid("Pick an agent"),name:g.Yj().min(1).max(120),cronExpr:g.Yj().min(1).max(100),task:g.Yj().min(1),notifyOnSuccess:g.zM().optional().default(!1)});async function fz(a){try{let b=await dL(),c=fy.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),[f]=await d.select({id:m.uQ.id}).from(m.uQ).where((0,m.Uo)((0,m.eq)(m.uQ.id,c.data.id),(0,m.eq)(m.uQ.entityId,b.entityId)));if(!f)return dK("not_found","Schedule not found");let[g]=await d.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,c.data.agentId),(0,m.eq)(m.X6.entityId,b.entityId)));if(!g)return dK("not_found","Agent not found");let h=dH(c.data.cronExpr);if(!h)return dK("validation_failed","Invalid cron expression");return await d.update(m.uQ).set({agentId:c.data.agentId,name:c.data.name,cronExpr:c.data.cronExpr,task:c.data.task,nextRun:h,notifyOnSuccess:c.data.notifyOnSuccess,updatedAt:new Date}).where((0,m.eq)(m.uQ.id,c.data.id)),(0,e.revalidatePath)("/automations"),dJ(void 0)}catch(a){return console.error("[updateScheduleAction]",a),dK("db_error","Failed to update schedule")}}async function fA(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid schedule id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.uQ.id,active:m.uQ.active}).from(m.uQ).where((0,m.Uo)((0,m.eq)(m.uQ.id,a),(0,m.eq)(m.uQ.entityId,b.entityId)));if(!d)return dK("not_found","Schedule not found");let f=!(d.active??!0);return await c.update(m.uQ).set({active:f,updatedAt:new Date}).where((0,m.eq)(m.uQ.id,a)),(0,e.revalidatePath)("/automations"),dJ({active:f})}catch(a){return console.error("[toggleScheduleAction]",a),dK("db_error","Failed to toggle schedule")}}async function fB(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid schedule id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.uQ.id}).from(m.uQ).where((0,m.Uo)((0,m.eq)(m.uQ.id,a),(0,m.eq)(m.uQ.entityId,b.entityId)));if(!d)return dK("not_found","Schedule not found");return await c.delete(m.uQ).where((0,m.eq)(m.uQ.id,a)),(0,e.revalidatePath)("/automations"),dJ(void 0)}catch(a){return console.error("[deleteScheduleAction]",a),dK("db_error","Failed to delete schedule")}}async function fC(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid schedule id");let c=(0,ds.Lf)(),[d]=await c.select({agentId:m.uQ.agentId,task:m.uQ.task,chatId:m.uQ.chatId,notifyOnSuccess:m.uQ.notifyOnSuccess,agentChatId:m.X6.lastSeenChatIdTelegram}).from(m.uQ).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.uQ.agentId)).where((0,m.Uo)((0,m.eq)(m.uQ.id,a),(0,m.eq)(m.uQ.entityId,b.entityId))).limit(1);if(!d)return dK("not_found","Schedule not found");if(!d.task)return dK("validation_failed","This automation has no task to run.");let f=d.notifyOnSuccess?d.chatId??d.agentChatId??null:null,[h]=await c.insert(m.ME).values({entityId:b.entityId,agentId:d.agentId,status:"pending",channel:"cron",task:d.task,messages:[{role:"user",content:d.task}],...f?{chatId:f}:{}}).returning({id:m.ME.id});if(!h)return dK("db_error","Failed to create job");return du._.WORKER_SECRET?fetch(`${du._.RUNNER_URL}/api/worker`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify({jobId:h.id})}).catch(a=>{console.error("[runScheduleNowAction] runner ping failed:",a)}):console.error("[runScheduleNowAction] WORKER_SECRET missing — cannot ping runner"),(0,e.revalidatePath)("/automations"),(0,e.revalidatePath)("/jobs"),dJ({jobId:h.id})}catch(a){return console.error("[runScheduleNowAction]",a),dK("db_error","Failed to run schedule now")}}async function fD(){try{await dL();let a=function(){let a=dx();if(!a)return{configuredMode:"local-trust",googleConfigured:!1,configPathExists:!1};let b=a.auth??null,c=a.bind;return{configuredMode:b?.mode??("lan"===c?"local-auth":"local-trust"),googleConfigured:!!(b?.googleClientId&&b?.googleClientSecret),configPathExists:!0}}();return dJ({runtimeMode:du._.AUTH_MODE,configuredMode:a.configuredMode,googleConfigured:a.googleConfigured,googleAvailableInRuntime:!!(du._.GOOGLE_CLIENT_ID&&du._.GOOGLE_CLIENT_SECRET),configPathExists:a.configPathExists})}catch(a){return console.error("[getSecuritySettingsAction]",a),dK("db_error","Failed to load security settings")}}let fE=g.Ik({mode:g.k5(["local-trust","local-auth"]),googleClientId:g.Yj().max(200).optional(),googleClientSecret:g.Yj().max(200).optional(),clearGoogle:g.zM().default(!1)});async function fF(a){try{await dL();let b=fE.safeParse(a);if(!b.success)return dK("validation_failed",b.error.issues[0]?.message??"Invalid input");let c=dx();if(!c)return dK("cli_config_missing","Cannot find ~/.nodalai/config.json — run `nodal-agents init` first.");let d={...c.auth??{},mode:b.data.mode};b.data.clearGoogle?(delete d.googleClientId,delete d.googleClientSecret):(b.data.googleClientId&&b.data.googleClientId.trim().length>0&&(d.googleClientId=b.data.googleClientId.trim()),b.data.googleClientSecret&&b.data.googleClientSecret.trim().length>0&&(d.googleClientSecret=b.data.googleClientSecret.trim()));try{dy({auth:d})}catch(b){let a=b instanceof Error?b.message:"";if("cli_config_missing"===a)return dK("cli_config_missing","Config file disappeared between read and write.");throw b}(0,e.revalidatePath)("/settings");let f=b.data.mode!==du._.AUTH_MODE;return dJ({requiresRestart:f})}catch(a){return console.error("[updateAuthSettingsAction]",a),dK("db_error","Failed to update auth settings")}}async function fG(){try{let a;await dL();let b=(a=dx())?{configuredBind:"lan"===a.bind?"lan":"loopback",configPathExists:!0}:{configuredBind:"loopback",configPathExists:!1},c="0.0.0.0"===du._.BIND?"lan":"loopback";return dJ({configuredBind:b.configuredBind,runtimeBind:c,lanAddresses:function(){let a=(0,j.networkInterfaces)(),b=[];for(let c of Object.values(a))if(c)for(let a of c)"IPv4"!==a.family||a.internal||b.push(a.address);return b}(),webPort:function(a){try{let b=new URL(a);if(b.port)return Number(b.port);return"https:"===b.protocol?443:80}catch{return 3e3}}(du._.NEXT_PUBLIC_APP_URL),configPathExists:b.configPathExists})}catch(a){return console.error("[getNetworkSettingsAction]",a),dK("db_error","Failed to load network settings")}}let fH=g.Ik({bind:g.k5(["loopback","lan"])});async function fI(a){try{await dL();let b=fH.safeParse(a);if(!b.success)return dK("validation_failed",b.error.issues[0]?.message??"Invalid input");try{dy({bind:b.data.bind})}catch(b){let a=b instanceof Error?b.message:"";if("cli_config_missing"===a)return dK("cli_config_missing","Cannot find ~/.nodalai/config.json — run `nodal-agents init` first.");throw b}(0,e.revalidatePath)("/settings");let c="0.0.0.0"===du._.BIND?"lan":"loopback";return dJ({requiresRestart:b.data.bind!==c})}catch(a){return console.error("[updateNetworkSettingsAction]",a),dK("db_error","Failed to update network settings")}}let fJ=["anthropic","openai","openai-compatible","ollama","openrouter","google","mistral","groq","deepseek","minimax"],fK=g.Yj().optional().transform(a=>a&&a.length>0?a:null).pipe(g.Yj().url().nullable().or(g.ch())),fL=g.Ik({provider:g.k5(fJ),baseUrl:fK,apiKey:g.Yj().optional(),nickname:g.Yj().max(120).nullish(),isActive:g.zM().default(!0)}),fM=g.Ik({id:g.Yj().guid(),provider:g.k5(fJ),baseUrl:fK,apiKey:g.Yj().optional(),nickname:g.Yj().max(120).nullish(),isActive:g.zM()}),fN=g.Ik({provider:g.k5(fJ),baseUrl:fK,apiKey:g.Yj().optional(),model:g.Yj().optional(),keyId:g.Yj().guid().optional()});function fO(a,b){return b&&0!==b.length?a.replaceAll(b,"[REDACTED]"):a}async function fP(){try{let a=await dL(),b=(0,ds.Lf)(),c=await b.select({id:m.hG.id,provider:m.hG.provider,baseUrl:m.hG.baseUrl,nickname:m.hG.nickname,isActive:m.hG.isActive,hasApiKey:(0,m.ll)`(${m.hG.apiKey} <> '')`,apiKeyLast4:m.hG.apiKeyLast4}).from(m.hG).where((0,m.eq)(m.hG.entityId,a.entityId)).orderBy((0,m.i8)(m.hG.createdAt)),d=await b.select({llmKeyId:m.X6.llmKeyId,n:(0,m.ll)`count(*)`}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.entityId,a.entityId),(0,m.eq)(m.X6.active,!0))).groupBy(m.X6.llmKeyId),e=new Map;for(let a of d)a.llmKeyId&&e.set(a.llmKeyId,Number(a.n));return dJ(c.map(a=>({id:a.id,provider:a.provider,baseUrl:a.baseUrl,nickname:a.nickname,isActive:a.isActive,hasApiKey:!!a.hasApiKey,apiKeyLast4:a.apiKeyLast4?a.apiKeyLast4:null,agentCount:e.get(a.id)??0})))}catch(a){return console.error("[listLlmKeysAction]",a),dK("db_error","Failed to load LLM providers")}}async function fQ(a){try{let b=await dL(),c=fL.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),[f]=await d.select({id:m.hG.id}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.entityId,b.entityId),(0,m.eq)(m.hG.provider,c.data.provider))).limit(1);if(f)return dK("provider_exists","This provider is already configured — edit the existing one.");let g=c.data.apiKey??"",[h]=await d.insert(m.hG).values({entityId:b.entityId,provider:c.data.provider,apiKey:(0,L.w)(g),apiKeyLast4:(0,L.nK)(g),baseUrl:c.data.baseUrl,nickname:c.data.nickname??null,isActive:c.data.isActive}).returning({id:m.hG.id});if(!h)return dK("db_error","Insert returned no row");return(0,e.revalidatePath)("/settings"),dJ({id:h.id})}catch(a){return console.error("[createLlmKeyAction]",a),dK("db_error","Failed to create LLM provider")}}async function fR(a){try{let b=await dL(),c=fM.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{id:d,provider:f,baseUrl:g,apiKey:h,nickname:i,isActive:j}=c.data,k=(0,ds.Lf)(),[l]=await k.select({id:m.hG.id}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.id,d),(0,m.eq)(m.hG.entityId,b.entityId)));if(!l)return dK("not_found","LLM provider not found");let n={provider:f,baseUrl:g,nickname:i??null,isActive:j,updatedAt:new Date};return h&&h.length>0&&(n.apiKey=(0,L.w)(h),n.apiKeyLast4=(0,L.nK)(h)),await k.update(m.hG).set(n).where((0,m.eq)(m.hG.id,d)),(0,e.revalidatePath)("/settings"),dJ(void 0)}catch(a){return console.error("[updateLlmKeyAction]",a),dK("db_error","Failed to update LLM provider")}}async function fS(a,b){try{let c=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid LLM provider id");let d=(0,ds.Lf)(),[f]=await d.select({id:m.hG.id}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.id,a),(0,m.eq)(m.hG.entityId,c.entityId)));if(!f)return dK("not_found","LLM provider not found");return await d.update(m.hG).set({isActive:b,updatedAt:new Date}).where((0,m.eq)(m.hG.id,a)),(0,e.revalidatePath)("/llm-providers"),dJ(void 0)}catch(a){return console.error("[setLlmKeyActiveAction]",a),dK("db_error","Failed to update LLM provider")}}async function fT(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid LLM provider id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.hG.id}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.id,a),(0,m.eq)(m.hG.entityId,b.entityId)));if(!d)return dK("not_found","LLM provider not found");return await c.delete(m.hG).where((0,m.eq)(m.hG.id,a)),(0,e.revalidatePath)("/settings"),dJ(void 0)}catch(a){return console.error("[deleteLlmKeyAction]",a),dK("db_error","Failed to delete LLM provider")}}let fU={anthropic:{canonicalBase:"https://api.anthropic.com/v1",path:"/models",auth:"x-api-key"},openai:{canonicalBase:"https://api.openai.com/v1",path:"/models",auth:"bearer"},openrouter:{canonicalBase:"https://openrouter.ai/api/v1",path:"/auth/key",auth:"bearer"},google:{canonicalBase:"https://generativelanguage.googleapis.com/v1beta",path:"/models",auth:"query"},mistral:{canonicalBase:"https://api.mistral.ai/v1",path:"/models",auth:"bearer"},groq:{canonicalBase:"https://api.groq.com/openai/v1",path:"/models",auth:"bearer"},"openai-compatible":{canonicalBase:null,path:"/models",auth:"bearer"},ollama:{canonicalBase:null,path:"/api/tags",auth:"none"},deepseek:{canonicalBase:"https://api.deepseek.com",path:"/models",auth:"bearer"},minimax:{canonicalBase:"https://api.minimax.io/anthropic",path:"/v1/models",auth:"bearer"}};async function fV(a,b,c){try{let d=fU[a];if("openrouter"===a)return[];let e={Accept:"application/json"},f=`${b}${d.path}`;"bearer"===d.auth&&c&&(e.Authorization=`Bearer ${c}`),"x-api-key"===d.auth&&c&&(e["x-api-key"]=c,e["anthropic-version"]="2023-06-01"),"query"===d.auth&&(f=`${f}?key=${encodeURIComponent(c??"")}`);let g=await fetch(f,{method:"GET",headers:e});if(!g.ok)return[];let h=await g.json(),i=h.data??h.models;if(!Array.isArray(i))return[];let j=i.map(a=>{let b=a.id??a.name;return"string"==typeof b?b:null}).filter(a=>null!==a&&a.length>0);return[...new Set(j)]}catch{return[]}}async function fW(a){let b;try{let c=await dL(),d=fN.safeParse(a);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let{provider:e,baseUrl:f}=d.data;if((!(b=d.data.apiKey)||0===b.length)&&d.data.keyId){let a=(0,ds.Lf)(),[e]=await a.select({apiKey:m.hG.apiKey}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.id,d.data.keyId),(0,m.eq)(m.hG.entityId,c.entityId)));if(!e)return dK("not_found","LLM provider not found");b=e.apiKey?(0,L.Yc)(e.apiKey):void 0}if(d.data.keyId&&(!b||0===b.length))return dK("no_api_key_provided","API key is required to test");let g=fU[e],h=(f??"").replace(/\/$/,"")||g.canonicalBase;if(!h)return dK("validation_failed",`baseUrl is required for ${e}`);let i={Accept:"application/json"},j=`${h}${g.path}`;"bearer"===g.auth&&b&&(i.Authorization=`Bearer ${b}`),"x-api-key"===g.auth&&b&&(i["x-api-key"]=b,i["anthropic-version"]="2023-06-01"),"query"===g.auth&&(j=`${j}?key=${encodeURIComponent(b??"")}`);let k=await fetch(j,{method:"GET",headers:i});if(!k.ok){let a=(await k.text().catch(()=>"")).slice(0,200);return dK("connection_failed",fO(`${e} responded ${k.status}: ${a}`,b))}let l=null;try{let a=await k.json(),b=a.data??a.models;Array.isArray(b)&&(l=b.length)}catch{}return dJ({message:null!==l?`Connected, ${l} models available`:"Connected"})}catch(a){return dK("connection_failed",fO(a instanceof Error?a.message:"Unknown error",b))}}async function fX(a){try{if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid key id");let b=await dL(),c=(0,ds.Lf)(),[d]=await c.select({provider:m.hG.provider,apiKey:m.hG.apiKey,baseUrl:m.hG.baseUrl}).from(m.hG).where((0,m.Uo)((0,m.eq)(m.hG.id,a),(0,m.eq)(m.hG.entityId,b.entityId)));if(!d)return dK("not_found","LLM key not found");let e=d.provider,f=d.apiKey&&d.apiKey.length>0?(0,L.Yc)(d.apiKey):void 0,h=fU[e],i=(d.baseUrl??"").replace(/\/$/,"")||h?.canonicalBase;if(!i)return dJ([]);let j=await fV(e,i,f);return dJ(j)}catch{return dJ([])}}async function fY(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,b.entityId)));if(!d)return dK("not_found","Agent not found");let e=await c.select({id:m.tK.id,slug:m.tK.slug,name:m.tK.name,credentialId:m.tK.credentialId,active:m.tK.active}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.entityId,b.entityId),(0,m.eq)(m.tK.active,!0)));if(0===e.length)return dJ([]);let f=[...new Set(e.map(a=>a.credentialId).filter(a=>null!==a))],h=new Map;if(f.length>0)for(let a of(await c.select({id:m.z3.id,name:m.z3.name}).from(m.z3).where((0,m.RV)(m.z3.id,f))))h.set(a.id,a.name);let i=await c.select({connectorId:m.XT.connectorId,enabledOperations:m.XT.enabledOperations}).from(m.XT).where((0,m.eq)(m.XT.agentId,a)),j=new Map;for(let a of i)j.set(a.connectorId,{enabledOperations:a.enabledOperations??null});let k=[];for(let a of e){let b=c5[a.slug];if(!b)continue;let c=j.get(a.id);k.push({connectorId:a.id,slug:a.slug,label:a.name,credentialName:a.credentialId?h.get(a.credentialId)??null:null,assigned:void 0!==c,enabledOperations:c?.enabledOperations??null,availableOperations:b.operations})}return dJ(k)}catch(a){return console.error("[listAgentConnectorsAction]",a),dK("db_error","Failed to load agent connectors")}}async function fZ(){try{await dL();let a=(0,ds.Lf)(),b=await (0,m.fI)(a);return dJ(b)}catch(a){return console.error("[getInstallNotesAction]",a),dK("db_error","Failed to load install notes")}}async function f$(a){try{await dL();let b=g.Yj().max(4e3).safeParse(a);if(!b.success)return dK("validation_failed",b.error.issues[0]?.message??"Invalid input");let c=(0,ds.Lf)();return await (0,m.lx)(c,b.data),(0,e.revalidatePath)("/settings"),dJ(void 0)}catch(a){return console.error("[setInstallNotesAction]",a),dK("db_error","Failed to save install notes")}}async function f_(){try{let a=await dL(),b=(0,ds.Lf)(),{rootAgentId:c,rootName:d}=await f7(b,a.entityId);if(!c)return dJ({rootAgentId:null,rootName:null,personality:"",skills:[]});let[e]=await b.select({personality:m.X6.personality}).from(m.X6).where((0,m.eq)(m.X6.id,c)),f=await b.select({id:m.eK.id,name:m.eK.name,description:m.eK.description,content:m.eK.content}).from(m.$m).innerJoin(m.eK,(0,m.eq)(m.$m.skillId,m.eK.id)).where((0,m.eq)(m.$m.agentId,c));return dJ({rootAgentId:c,rootName:d,personality:e?.personality??"",skills:f.map(a=>({id:a.id,name:a.name,description:a.description??null,content:a.content??""}))})}catch(a){return console.error("[getRootContextAction]",a),dK("db_error","Failed to load root context")}}let f0=g.Ik({personality:g.Yj().min(1).max(2e4)});async function f1(a){try{let b=await dL(),c=f0.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,ds.Lf)(),{rootAgentId:f}=await f7(d,b.entityId);if(!f)return dK("not_found","No ROOT agent designated");return await d.update(m.X6).set({personality:c.data.personality}).where((0,m.Uo)((0,m.eq)(m.X6.id,f),(0,m.eq)(m.X6.entityId,b.entityId))),(0,e.revalidatePath)("/settings/root-context"),dJ(void 0)}catch(a){return console.error("[updateRootPersonalityAction]",a),dK("db_error","Failed to update personality")}}async function f2(){try{let a=await dL(),b=(0,ds.Lf)(),{rootAgentId:c}=await f7(b,a.entityId);if(!c)return dK("not_found","No ROOT agent designated");let[d]=await b.select().from(m.X6).where((0,m.eq)(m.X6.id,c));if(!d)return dK("not_found","ROOT agent not found");let e={id:d.id,name:d.name,slug:d.slug,role:d.role??"agent",personality:d.personality,entityId:d.entityId??null,model:d.model??"",active:d.active??!0,orchestratorMode:d.orchestratorMode??null,memoryTokenBudget:d.memoryTokenBudget??4e3},f={os:"win32"===process.platform?"Windows":"darwin"===process.platform?"macOS":"Linux",networkMode:"0.0.0.0"===process.env.BIND?"lan":"loopback",authMode:process.env.AUTH_MODE??"local-trust",installNotes:await (0,m.fI)(b)},g=await dr(e,b,{origin:"dashboard",deployment:f});return dJ(g)}catch(a){return console.error("[getRootSystemPromptAction]",a),dK("db_error","Failed to assemble system prompt")}}async function f3(a,b,c,d){try{let f=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid agent id");if(!g.Yj().guid().safeParse(b).success)return dK("validation_failed","Invalid connector id");let h=(0,ds.Lf)(),[i]=await h.select({id:m.X6.id}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,a),(0,m.eq)(m.X6.entityId,f.entityId)));if(!i)return dK("not_found","Agent not found");let[j]=await h.select({id:m.tK.id}).from(m.tK).where((0,m.Uo)((0,m.eq)(m.tK.id,b),(0,m.eq)(m.tK.entityId,f.entityId)));if(!j)return dK("not_found","Connector not found");return c?await h.insert(m.XT).values({agentId:a,connectorId:b,entityId:f.entityId,enabledOperations:d??null}).onConflictDoUpdate({target:[m.XT.agentId,m.XT.connectorId],set:{enabledOperations:d??null,updatedAt:new Date}}):await h.delete(m.XT).where((0,m.Uo)((0,m.eq)(m.XT.agentId,a),(0,m.eq)(m.XT.connectorId,b))),(0,e.revalidatePath)("/agents"),dJ(void 0)}catch(a){return console.error("[setAgentConnectorAssignmentAction]",a),dK("db_error","Failed to update connector assignment")}}async function f4(){try{let a=await dL(),b=(0,ds.Lf)(),[c]=await b.select({rootAgentId:m.O5.rootAgentId,rootGrants:m.O5.rootGrants}).from(m.O5).where((0,m.eq)(m.O5.id,a.entityId));if(!c)return dK("not_found","Workspace not found");return dJ({rootAgentId:c.rootAgentId??null,grants:(0,v.DI)(c.rootGrants)})}catch(a){return console.error("[getRootConfigAction]",a),dK("db_error","Failed to load ROOT agent config")}}let f5=g.Ik({grants:g.Ik({createAgent:g.zM(),updateAgent:g.zM(),attachAgent:g.zM(),createSkill:g.zM(),updateSkill:g.zM(),assignSkill:g.zM(),createMcp:g.zM(),attachMcp:g.zM(),createConnector:g.zM(),attachConnector:g.zM(),manageSchedules:g.zM(),autonomy:g.k5(["propose_confirm","destructive_gate","fully_autonomous"])})});async function f6(a){try{let b=await dL(),c=f5.safeParse(a);if(!c.success)return dK("validation_failed",c.error.issues[0]?.message??"Invalid input");let{grants:d}=c.data,f=(0,ds.Lf)(),[g]=await f.select({role:m.V.role}).from(m.V).where((0,m.Uo)((0,m.eq)(m.V.userId,b.userId),(0,m.eq)(m.V.entityId,b.entityId)));if(!g)return dK("not_found","Workspace not found");let[h]=await f.select({rootAgentId:m.O5.rootAgentId}).from(m.O5).where((0,m.eq)(m.O5.id,b.entityId)),i=h?.rootAgentId??null;if(!i)return dK("not_found","No ROOT agent yet — create an orchestrator first");if(await f.update(m.O5).set({rootGrants:d,updatedAt:new Date}).where((0,m.eq)(m.O5.id,b.entityId)),await f.delete(m.bN).where((0,m.Uo)((0,m.eq)(m.bN.entityId,b.entityId),(0,m.RV)(m.bN.toolName,v.yO))),"propose_confirm"===d.autonomy){let a=(0,v.aT)(d);a.length>0&&await f.insert(m.bN).values(a.map(a=>({entityId:b.entityId,agentId:i,toolName:a,action:"require_approval"})))}return(0,e.revalidatePath)("/settings"),dJ(void 0)}catch(a){return console.error("[setRootAgentAction]",a),dK("db_error","Failed to save ROOT agent config")}}async function f7(a,b){let[c]=await a.select({rootAgentId:m.O5.rootAgentId}).from(m.O5).where((0,m.eq)(m.O5.id,b)).limit(1),d=c?.rootAgentId??null;if(!d)return{rootAgentId:null,rootName:null};let[e]=await a.select({name:m.X6.name}).from(m.X6).where((0,m.Uo)((0,m.eq)(m.X6.id,d),(0,m.eq)(m.X6.entityId,b))).limit(1);return{rootAgentId:d,rootName:e?.name??null}}async function f8(){try{let a=await dL(),b=(0,ds.Lf)(),{rootAgentId:c,rootName:d}=await f7(b,a.entityId);if(!c)return dJ({rootAgentId:null,rootName:null,conversations:[]});let e=await b.select({id:m.NP.id,title:m.NP.title,updatedAt:m.NP.updatedAt}).from(m.NP).where((0,m.Uo)((0,m.eq)(m.NP.entityId,a.entityId),(0,m.eq)(m.NP.agentId,c))).orderBy((0,m.i8)(m.NP.updatedAt)).limit(200),f=e.map(a=>a.id),g=new Map;if(f.length>0)for(let a of(await b.select({conversationId:m.p$.conversationId,content:m.p$.content}).from(m.p$).where((0,m.RV)(m.p$.conversationId,f)).orderBy((0,m.i8)(m.p$.createdAt)).limit(1e3)))a.conversationId&&!g.has(a.conversationId)&&g.set(a.conversationId,a.content);let h=e.map(a=>({id:a.id,title:a.title,preview:g.get(a.id)??"",updatedAt:a.updatedAt}));return dJ({rootAgentId:c,rootName:d,conversations:h})}catch(a){return console.error("[listConversationsAction]",a),dK("db_error","Failed to load conversations")}}async function f9(){try{let a=await dL(),b=(0,ds.Lf)(),{rootAgentId:c}=await f7(b,a.entityId);if(!c)return dK("no_root_agent","Designate a ROOT agent in Settings first.");let[d]=await b.insert(m.NP).values({entityId:a.entityId,agentId:c,title:""}).returning({id:m.NP.id});if(!d)return dK("db_error","Failed to create conversation");return(0,e.revalidatePath)("/chat"),dJ({id:d.id})}catch(a){return console.error("[createConversationAction]",a),dK("db_error","Failed to create conversation")}}async function ga(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid conversation id");let c=(0,ds.Lf)();return await c.delete(m.NP).where((0,m.Uo)((0,m.eq)(m.NP.id,a),(0,m.eq)(m.NP.entityId,b.entityId))),(0,e.revalidatePath)("/chat"),dJ(void 0)}catch(a){return console.error("[deleteConversationAction]",a),dK("db_error","Failed to delete conversation")}}async function gb(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid conversation id");let c=(0,ds.Lf)(),[d]=await c.select({id:m.NP.id}).from(m.NP).where((0,m.Uo)((0,m.eq)(m.NP.id,a),(0,m.eq)(m.NP.entityId,b.entityId))).limit(1);if(!d)return dK("not_found","Conversation not found");let e=(await c.select({id:m.p$.id,role:m.p$.role,content:m.p$.content,jobId:m.p$.jobId}).from(m.p$).where((0,m.eq)(m.p$.conversationId,a)).orderBy(m.p$.createdAt).limit(500)).map(a=>({id:a.id,role:a.role,content:a.content,jobId:a.jobId}));return dJ({messages:e})}catch(a){return console.error("[listChatAction]",a),dK("db_error","Failed to load chat")}}let gc=g.Ik({conversationId:g.Yj().guid(),message:g.Yj().min(1,"Message is empty").max(2e5)});async function gd(a){try{let b,c=await dL(),d=gc.safeParse(a);if(!d.success)return dK("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,ds.Lf)(),{rootAgentId:g}=await f7(f,c.entityId);if(!g)return dK("no_root_agent","Designate a ROOT agent in Settings first.");if(!du._.WORKER_SECRET)return console.error("[sendChatMessageAction] WORKER_SECRET missing — cannot reach runner"),dK("runner_unreachable","Chat backend not configured");try{b=await fetch(`${du._.RUNNER_URL}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${du._.WORKER_SECRET}`},body:JSON.stringify({entityId:c.entityId,agentId:g,conversationId:d.data.conversationId,message:d.data.message})})}catch(a){return console.error("[sendChatMessageAction] runner unreachable:",a),dK("runner_unreachable","Could not reach the chat backend")}let h=await b.json().catch(()=>null);if(!b.ok)return dK("chat_failed",h?.error??"The agent did not reply");return(0,e.revalidatePath)("/chat"),dJ({reply:h?.reply??""})}catch(a){return console.error("[sendChatMessageAction]",a),dK("db_error","Failed to send message")}}async function ge(a){try{let b=await dL();if(!g.Yj().guid().safeParse(a).success)return dK("validation_failed","Invalid job id");let c=(0,ds.Lf)(),[d]=await c.select({status:m.ME.status,result:m.ME.result}).from(m.ME).where((0,m.Uo)((0,m.eq)(m.ME.id,a),(0,m.eq)(m.ME.entityId,b.entityId))).limit(1);if(!d)return dK("not_found","Job not found");let e=(await c.select({agentName:m.X6.name,agentSlug:m.X6.slug,status:m.ME.status}).from(m.ME).leftJoin(m.X6,(0,m.eq)(m.X6.id,m.ME.agentId)).where((0,m.eq)(m.ME.parentJobId,a)).orderBy(m.ME.createdAt)).map(a=>({agentName:a.agentName??a.agentSlug??"agent",status:a.status??"pending"}));return dJ({status:d.status??"pending",result:d.result,children:e})}catch(a){return console.error("[getChatJobStatusAction]",a),dK("db_error","Failed to load job status")}}(0,dI.D)([dM,dN,dO,dP,dQ,dR,dS,dV,dW,dX,dY,dZ,d0,d1,d2,d3,d7,d8,d9,ea,eb,ec,ed,ee,ef,eh,ej,ek,el,en,eo,eq,er,et,eu,ev,ew,ex,ez,eA,eB,eD,eE,eF,eG,eI,eJ,eK,eL,eM,eN,eO,eP,eQ,eS,eT,eV,eX,eY,e$,e_,e1,e2,e4,e5,e7,e8,fa,fb,fc,fd,fe,fg,fi,fk,fl,fm,fo,fp,fq,fr,ft,fu,fw,fx,fz,fA,fB,fC,fD,fF,fG,fI,fP,fQ,fR,fS,fT,fW,fX,fY,fZ,f$,f_,f1,f2,f3,f4,f6,f8,f9,ga,gb,gd,ge]),(0,d.A)(dM,"003af1098fb2ea2815dd2e35d8d89187a071b69280",null),(0,d.A)(dN,"4058ff9b5b556469d2162bd3727e7ac8d2c70a501a",null),(0,d.A)(dO,"40a4aa24576354b17648a91aa1f592381a155e25d3",null),(0,d.A)(dP,"405922c2e5048693dc260e7050cbee254aae1dda5c",null),(0,d.A)(dQ,"001f94696fb12a175b6d548908577a150f9cb94fb0",null),(0,d.A)(dR,"4058063eaab019a562bcec2a4f0d4c5416f3786785",null),(0,d.A)(dS,"40dd870fbded89c5d8e8d1688111be85294ff2e2b1",null),(0,d.A)(dV,"003b4c8ad5bdfed072a49405f9b61754157a29fb62",null),(0,d.A)(dW,"00bbcc2947a582e91dd4c5eefa7e3447c376eff316",null),(0,d.A)(dX,"403e3410fa2cab692e022b6bd5a24be7c4c365189e",null),(0,d.A)(dY,"4065860b50f993dcc4bdae8979a2ad2ef4015b9a83",null),(0,d.A)(dZ,"40b172bd505b9d90237057bc69b2b6324f7d601922",null),(0,d.A)(d0,"406a006488d57bd13f75c58eb822151a7d19e2b4fd",null),(0,d.A)(d1,"40607e21897d73e9089c4dca854530e2bbc3726838",null),(0,d.A)(d2,"701a2e6d68a48f6952c83bbef74f5deb1fa25d592e",null),(0,d.A)(d3,"4042e770118eb4837bcc4ec95804b29b16a217b1d9",null),(0,d.A)(d7,"7057ff67f104831e6e11be16e5bc275875becc7f64",null),(0,d.A)(d8,"605da2e8613ff3ded0fdc38fed0843cc900f2e3566",null),(0,d.A)(d9,"701e433000bdf7198806cc0b2f00fb17fcc45cf6fb",null),(0,d.A)(ea,"40fd9747c08d69b33e553e8f6a1c7dec73f2688ba7",null),(0,d.A)(eb,"400678dc7ff23d2f5a6d18a4739bb498de66f7f60a",null),(0,d.A)(ec,"405fe2959258346492d1cd21f01067d76eb8ef1fb0",null),(0,d.A)(ed,"40574655f70d3f2fc987934937a9ee687bf82e3cd7",null),(0,d.A)(ee,"40628f77780f785b626e6692ab8e49af5566909f9c",null),(0,d.A)(ef,"40ce86809f6e965169904fc7c94f92162b520b7145",null),(0,d.A)(eh,"40e3d165a320ef9cc7216faef16ef1b9b19b580ab9",null),(0,d.A)(ej,"40251a1bbc26df13b10d59d6ae1f520ca88647c410",null),(0,d.A)(ek,"402e2234882f7c361a6badde530eaf4da7a0773d58",null),(0,d.A)(el,"404f606a6c7b87904a04d4bb1d6eea85288a056150",null),(0,d.A)(en,"405a30a677284ae4310ee22c19b6d1456926064dcb",null),(0,d.A)(eo,"40414ce5e8dc4a402036cd1ed53bc8abba24ba3432",null),(0,d.A)(eq,"40238625d64eddbb741ea48b543f11919002527755",null),(0,d.A)(er,"4056735c2c5cb3a91ad64fda5eae1037107e6738e5",null),(0,d.A)(et,"60cef35a4f0a16c313290993baf0e13a71bc48140c",null),(0,d.A)(eu,"40ab2487632b8b3fe7d9dd6f6c0d973e5c4ba0a898",null),(0,d.A)(ev,"40e14b4dd07e8b84c14150827d5851b4dd5441de03",null),(0,d.A)(ew,"40d01399a20d83ff16f6caafa35588cf2a0c558a2a",null),(0,d.A)(ex,"00961fa316e44ad990ec82a96ee66e32fc161e3513",null),(0,d.A)(ez,"402c3cd794af9806b21cb9b6af43c82c90a242b604",null),(0,d.A)(eA,"40c2a72001ea594726c16335ecfb1686b9c8a4955f",null),(0,d.A)(eB,"009f804e161614c2b969736a0d49319c0b0fdf55bd",null),(0,d.A)(eD,"400ba050d0c503e02c7f46ef81c574adf3d695e03a",null),(0,d.A)(eE,"60cef8bf2b9dc3fc39725abfd3e32ae3e75a49c553",null),(0,d.A)(eF,"60179332529b93530147cfe0ac66a8d2f76d0cec5a",null),(0,d.A)(eG,"403da9ba2931e17c6cb70c153768dd07a5b5ef3f7b",null),(0,d.A)(eI,"60ac2447f4dad2be34c7f4a488f7bc5a243397a32e",null),(0,d.A)(eJ,"40baaf433f2cec4018ff71235206e003c8a52d1ffd",null),(0,d.A)(eK,"40f0ade323dd48d2ee986105e14504845930d2cf83",null),(0,d.A)(eL,"787f6da3f33f453611487bb2c7dec7e4fb23ca15a9",null),(0,d.A)(eM,"60620f9c540ed326947f304c79e9fd6cd93ca23e37",null),(0,d.A)(eN,"70f836d2da2e8f09397025a5d562f8d1537dc01c98",null),(0,d.A)(eO,"60ddbddd6aca3ed418570971974ade218f004ba8ec",null),(0,d.A)(eP,"6039cf47cb60535c881da063562537d3f95f042a97",null),(0,d.A)(eQ,"4091a56ae49f9692f037a27b1733ac3e62709ec8ea",null),(0,d.A)(eS,"406589af82ec340355335d69e976a33b4a5205acdc",null),(0,d.A)(eT,"40a08d24380a846be39f04c9b266cfe6d47f247cea",null),(0,d.A)(eV,"401fa16f52dd9b615515d75bb2572b8d80a7b32f41",null),(0,d.A)(eX,"40b5af1a5dfc2ca4f88d182d54120cdf5f97e12981",null),(0,d.A)(eY,"0075fcb8edd591259129d652eda3bb0891aa5d5390",null),(0,d.A)(e$,"402ca1d6c854c9f3f96f34454a3aa76e6a3de9ae52",null),(0,d.A)(e_,"00a789918364d088fd84cd59360c2cec302bc58a48",null),(0,d.A)(e1,"4098fedc9bccfcb345d86e07ffcbc1fe5cb0db9aab",null),(0,d.A)(e2,"40e4f6e6802428941909c2d2ca74a62cc282cd10be",null),(0,d.A)(e4,"406a1f2c216816293a20bf6ac0af62408987c0f1e9",null),(0,d.A)(e5,"40261cbfbf57957c5512ffb45890d992584d11a42a",null),(0,d.A)(e7,"40d3537a5cc823bf9809252ae54b417daff96b799a",null),(0,d.A)(e8,"4056a53c1a88bd3360e09feb50931ded6515d71fc1",null),(0,d.A)(fa,"40b5a729e2b6d64e9e74b17ca364f38200ee022bc5",null),(0,d.A)(fb,"400fca191a94e63b7e7b8a3b20ca1d1efe13175b6c",null),(0,d.A)(fc,"40722c3a88f583dabb7ba422fc927042fa76f8f6db",null),(0,d.A)(fd,"400508ecdb21739070a8d0d26dcf75cecf1bafad36",null),(0,d.A)(fe,"40f05613800c978081aaa4ddb891f4c6b54fa9effe",null),(0,d.A)(fg,"40afd35d162d952b7a396692734f2a569bdccfbe13",null),(0,d.A)(fi,"4029ebea70d9f86ba4fb99053461b0b6ee035e91b6",null),(0,d.A)(fk,"4045e5b2e93c091fa6198e26e44558ec76c9e0ac15",null),(0,d.A)(fl,"00f5e31d3bb994c4d7b2dc7083743595f64139dcc4",null),(0,d.A)(fm,"0003b982c6b389b112c8f506583840b15795f42302",null),(0,d.A)(fo,"004cf17087b625f7076573d0ad96a0babd17002e43",null),(0,d.A)(fp,"0048a7fd4ebaf23e8e398b6b4a506805b7a8d3002f",null),(0,d.A)(fq,"00703cdccd8f65c061f14ce46020d81d614995b5ec",null),(0,d.A)(fr,"000063a064f70046183498a3a8f3259ca8069e6567",null),(0,d.A)(ft,"007e85d7da0aa058f0ae7672c8048e61b11ede1526",null),(0,d.A)(fu,"000e77ac1912006941e88a0d97d18d91faafbe2c7b",null),(0,d.A)(fw,"40b748165dfdd760d79480d35e5735653d0cf96d6b",null),(0,d.A)(fx,"40b90aad3a0011b81fbd5633452d5587b951786fb1",null),(0,d.A)(fz,"40473e3aa186743a343dc824227dd3e5561df4515f",null),(0,d.A)(fA,"40dd2b07199d4aa835fa7a9d4bd39b9cecaa0f756f",null),(0,d.A)(fB,"4091ae6e8b1b09e67d4c86586c24855d1da3ed99a3",null),(0,d.A)(fC,"4031977609c7e48929f4fc0f05dfe2d9f3a2015ab3",null),(0,d.A)(fD,"003d5665a00541cd0ba4ba0313ee8fd3b228e45530",null),(0,d.A)(fF,"406fda24563836fc9a76a74aaafd85587b6cef417b",null),(0,d.A)(fG,"00dcb7a47bc8b5e7c2039114f7d212e6161c7aeb67",null),(0,d.A)(fI,"40679bd9bb515ded07a7b7c88cb2bddbb958bc85d4",null),(0,d.A)(fP,"00021a363146d0ee232c4d87594e3aa058af3ddfbb",null),(0,d.A)(fQ,"40ec96380c1bf25ac67eafffb475457d9e6e2adf4a",null),(0,d.A)(fR,"40dfc67c369bd8b1a734f8674662de042ebb99d026",null),(0,d.A)(fS,"603ab59d54d0b0349b494de119381810e7f4e4c4a4",null),(0,d.A)(fT,"408d2202ae3a6412a8b21d7955456abd89c53448c6",null),(0,d.A)(fW,"401724e8ce4d089762351b208a49acb20b6fa11009",null),(0,d.A)(fX,"40c188a1ca78aba2e69d4228a2530dab209b6dd293",null),(0,d.A)(fY,"40c82f0d2707e46acd2bb4ea34e9cf0bdef8d81185",null),(0,d.A)(fZ,"005d09183db34c29d4b4c9dfee7067ad71a04bbdf3",null),(0,d.A)(f$,"40f173b37e96ef868939c5613d89387d926a057ea4",null),(0,d.A)(f_,"008c2c642eab653289663d7633474a0ef22a4d0112",null),(0,d.A)(f1,"40c5cc9fc2de133991c879d7f4cea5540dc62b7c14",null),(0,d.A)(f2,"0023bb0b586706aaa9dfc4bd72636444ea18752430",null),(0,d.A)(f3,"7822cfc3515bfbe909f16436db371e27c28a82c5e5",null),(0,d.A)(f4,"00a2042a91566689fa3df521615a9a86a0c3ac249d",null),(0,d.A)(f6,"401a8c70eb32059d795e983061e65b404b48c5bede",null),(0,d.A)(f8,"0086452d3c291f59206bb2848b1b3340d14c18ad9b",null),(0,d.A)(f9,"00cf9352f814f90790590e0bfe2bf66032bbb79bd5",null),(0,d.A)(ga,"40c08d3272b8ee96e764451f69137be7b3f51d894a",null),(0,d.A)(gb,"405e5254666e5334df0b6569dc277b8a02a423ef75",null),(0,d.A)(gd,"4009f8de55e607e50a0e1d547e1388881d71569049",null),(0,d.A)(ge,"40e085eda3a927ad2973b780ff1cb786c080f4fc6f",null)},54580:(a,b,c)=>{Promise.resolve().then(c.bind(c,84327))},54620:()=>{},54792:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,61186,23)),Promise.resolve().then(c.t.bind(c,6621,23)),Promise.resolve().then(c.t.bind(c,41837,23)),Promise.resolve().then(c.t.bind(c,85060,23)),Promise.resolve().then(c.t.bind(c,43484,23)),Promise.resolve().then(c.t.bind(c,8376,23)),Promise.resolve().then(c.t.bind(c,74625,23)),Promise.resolve().then(c.t.bind(c,51080,23))},55053:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>e});var d=c(10476);function e({error:a,reset:b}){return(0,d.jsx)("div",{className:"flex min-h-screen w-full items-center justify-center bg-canvas px-4",children:(0,d.jsxs)("div",{className:"max-w-sm space-y-4 text-center",children:[(0,d.jsx)("h1",{className:"text-2xl font-bold text-ink",children:"Something went wrong"}),(0,d.jsx)("p",{className:"text-sm text-ink-3",children:"An unexpected error occurred. Try again, or refresh the page — the details have been logged."}),(0,d.jsx)("button",{onClick:b,className:"rounded-lg bg-agent-vivid px-4 py-2 text-sm font-semibold text-canvas transition-[filter] hover:brightness-[0.92]",children:"Try again"}),a.digest&&(0,d.jsxs)("p",{className:"font-mono text-[12px] text-ink-4",children:["Reference: ",a.digest]})]})})}c(64565)},57712:(a,b,c)=>{"use strict";c.d(b,{default:()=>g});var d=c(10476),e=c(64565),f=c(48082);function g(){let[a,b]=(0,e.useState)("light");return(0,d.jsx)(f.l$,{theme:a,position:"bottom-right",richColors:!0,closeButton:!0})}},59166:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,88831,23))},59234:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,61186,23))},61166:(a,b,c)=>{"use strict";c.d(b,{ApprovalsProvider:()=>i,e:()=>k});var d=c(10476),e=c(64565),f=c(47092);let g=(0,f.createServerReference)("4091a56ae49f9692f037a27b1733ac3e62709ec8ea",f.callServer,void 0,f.findSourceMapURL,"listApprovalsAction"),h=(0,e.createContext)(null);function i({initial:a,children:b}){let[c,f]=(0,e.useState)(a),j=(0,e.useCallback)(async()=>{let a=await g({status:"pending"});a.ok&&f(a.data.map(a=>({id:a.id,jobId:a.jobId,toolName:a.toolName,agentName:a.agentName,toolInput:a.toolInput,requestedAt:a.requestedAt})))},[]),k=(0,e.useCallback)(()=>{j()},[j]);return(0,d.jsx)(h.Provider,{value:{pending:c,refresh:k},children:b})}let j={pending:[],refresh:()=>{}};function k(){let a=(0,e.useContext)(h);return a||(console.warn("[useApprovals] called outside <ApprovalsProvider> — returning empty state."),j)}},62952:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\Sidebar.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\Sidebar.tsx","default")},63894:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,16385,23))},64609:(a,b,c)=>{"use strict";c.d(b,{O:()=>e});var d=c(47092);let e=(0,d.createServerReference)("4058ff9b5b556469d2162bd3727e7ac8d2c70a501a",d.callServer,void 0,d.findSourceMapURL,"createWorkspaceAction")},69371:(a,b,c)=>{Promise.resolve().then(c.bind(c,81955)),Promise.resolve().then(c.bind(c,62952)),Promise.resolve().then(c.bind(c,97173)),Promise.resolve().then(c.bind(c,93690))},69679:(a,b,c)=>{"use strict";c.d(b,{A:()=>f,S:()=>e});var d=c(10476);let e=["\uD83D\uDDC2️","\uD83C\uDFE0","\uD83D\uDCBC","\uD83D\uDE80","\uD83E\uDDEA","\uD83C\uDFA8","\uD83D\uDCCA","\uD83D\uDEE0️","\uD83C\uDF10","⚡","\uD83E\uDD16","\uD83D\uDCE6"];function f({value:a,onChange:b,disabled:c}){return(0,d.jsx)("div",{className:"flex flex-wrap gap-1",children:e.map(e=>{let f=a===e;return(0,d.jsx)("button",{type:"button",disabled:c,"aria-pressed":f,onClick:()=>b(e),className:`flex h-8 w-8 items-center justify-center rounded-md border text-[16px] leading-none transition-colors disabled:opacity-50 ${f?"border-ink bg-hover-2":"border-rule-2 hover:bg-hover"}`,children:e},e)})})}},70577:a=>{function b(a){var b=Error("Cannot find module '"+a+"'");throw b.code="MODULE_NOT_FOUND",b}b.keys=()=>[],b.resolve=b,b.id=70577,a.exports=b},70615:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>j,metadata:()=>i});var d=c(99386),e=c(50277),f=c.n(e),g=c(80356),h=c.n(g);c(54620);let i={title:"Nodal-Agents",description:"Multi-agent platform"};function j({children:a}){return(0,d.jsxs)("html",{lang:"en",className:`${f().variable} ${h().variable}`,suppressHydrationWarning:!0,children:[(0,d.jsx)("head",{children:(0,d.jsx)("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('nodal.theme');if(t!=='dark'&&t!=='light')t='light';document.documentElement.setAttribute('data-theme',t);}catch(e){document.documentElement.setAttribute('data-theme','light');}})();"}})}),(0,d.jsx)("body",{children:a})]})}},70953:()=>{},72134:(a,b,c)=>{"use strict";c.d(b,{C:()=>e});var d=c(47092);let e=(0,d.createServerReference)("406589af82ec340355335d69e976a33b4a5205acdc",d.callServer,void 0,d.findSourceMapURL,"resolveApprovalAction")},74708:(a,b,c)=>{"use strict";c.d(b,{A:()=>g});var d=c(10476),e=c(64565),f=c(90424);function g({open:a,onClose:b,title:c,children:h,className:i=""}){let[j,k]=(0,e.useState)(!1);return a&&j?(0,f.createPortal)((0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"fixed inset-0 z-40 bg-black/60 animate-[fadeIn_150ms_ease]",onClick:b,"aria-hidden":"true"}),(0,d.jsx)("div",{role:"dialog","aria-modal":"true",className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:(0,d.jsxs)("div",{className:`pointer-events-auto w-full max-w-lg max-h-[90vh] overflow-y-auto bg-paper border border-rule-2 rounded-xl shadow-2xl animate-[scaleIn_150ms_ease] ${i}`,children:[void 0!==c&&(0,d.jsxs)("div",{className:"flex items-center justify-between gap-2 px-6 pt-5 pb-4 border-b border-rule-2",children:[(0,d.jsx)("h3",{className:"text-sm font-semibold text-ink",children:c}),(0,d.jsx)("button",{type:"button",onClick:b,"aria-label":"Close",className:"text-ink-3 hover:text-ink transition-colors",children:"✕"})]}),(0,d.jsx)("div",{className:"p-6 pt-5",children:h})]})})]}),document.body):null}},77386:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,67448,23))},79987:(a,b,c)=>{Promise.resolve().then(c.bind(c,61166)),Promise.resolve().then(c.bind(c,36069)),Promise.resolve().then(c.bind(c,28659)),Promise.resolve().then(c.bind(c,57712))},81955:(a,b,c)=>{"use strict";c.d(b,{ApprovalsProvider:()=>e});var d=c(49554);let e=(0,d.registerClientReference)(function(){throw Error("Attempted to call ApprovalsProvider() from the server but ApprovalsProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ApprovalsProvider.tsx","ApprovalsProvider");(0,d.registerClientReference)(function(){throw Error("Attempted to call useApprovals() from the server but useApprovals is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ApprovalsProvider.tsx","useApprovals")},84327:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\app\\\\error.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\app\\error.tsx","default")},93690:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\ui\\\\ThemedToaster.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ui\\ThemedToaster.tsx","default")},96591:(a,b,c)=>{"use strict";c.d(b,{ZH:()=>d.ZH,ip:()=>d.R3});var d=c(64190)},97173:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\SignOutButton.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\SignOutButton.tsx","default")},99740:(a,b,c)=>{"use strict";c.d(b,{ApifyApiError:()=>d,G:()=>e});class d extends Error{constructor(a,b,c){super(b),this.name="ApifyApiError",this.code=a,this.status=c}}function e(a){if(a instanceof d)return a;if(null!==a&&"object"==typeof a&&"statusCode"in a&&"number"==typeof a.statusCode){let c,e=a.message??`Apify API error ${a.statusCode}`;var b=a.statusCode;switch(!0){case 401===b:c="apify_unauthorized";break;case 403===b:c="apify_forbidden";break;case 404===b:c="apify_not_found";break;case 422===b:c="apify_validation_error";break;case 429===b:c="apify_rate_limited";break;case b>=500:c="apify_transient";break;default:c="apify_client_error"}return new d(c,e,b)}return a instanceof Error?new d("apify_unknown",a.message):new d("apify_unknown",String(a))}}};
1491
+ AND status = 'pending'
1492
+ `),(0,e.revalidatePath)("/jobs"),(0,e.revalidatePath)(`/jobs/${a}`),dZ({status:"cancelled"})}catch(a){return console.error("[cancelJobAction]",a),d$("db_error","Failed to cancel job")}}let ez=g.Ik({agentId:g.Yj().guid(),botToken:g.Yj().min(20,"Token looks too short").max(200,"Token looks too long").regex(/^\d+:[A-Za-z0-9_-]+$/,"Token must look like 123456789:AAAAA...")});async function eA(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id,slug:p.X6.slug,name:p.X6.name,botToken:p.X6.telegramBotToken,botUsername:p.X6.telegramBotUsername,lastSeenChatIdTelegram:p.X6.lastSeenChatIdTelegram}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");return dZ({agentId:d.id,agentSlug:d.slug,agentName:d.name,status:d.botToken?"connected":"disconnected",botUsername:d.botUsername,lastSeenChatIdTelegram:d.lastSeenChatIdTelegram})}catch(a){return console.error("[getAgentTelegramConfigAction]",a),d$("db_error","Failed to load Telegram config")}}async function eB(a){try{let b,c=await d_(),d=ez.safeParse(a);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let{agentId:f,botToken:g}=d.data,h=(0,dH.Lf)(),[i]=await h.select({id:p.X6.id,slug:p.X6.slug,name:p.X6.name}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,f),(0,p.eq)(p.X6.entityId,c.entityId)));if(!i)return d$("not_found","Agent not found");try{b=await s(g)}catch(a){if(a instanceof q&&"telegram_invalid_token"===a.code)return d$("telegram_invalid_token","Telegram rejected this token. Double-check it from @BotFather.");throw a}let j=0;try{let a=await t({botToken:g,offset:-1,timeout:0,limit:1});a.length>0&&(j=Math.max(...a.map(a=>a.update_id))+1)}catch{}return await h.update(p.X6).set({telegramBotToken:g,telegramBotUsername:b.username,telegramOffset:j,updatedAt:new Date}).where((0,p.eq)(p.X6.id,f)),(0,e.revalidatePath)("/agents"),(0,e.revalidatePath)(`/agents/${f}/telegram`),dZ({agentId:i.id,agentSlug:i.slug,agentName:i.name,status:"connected",botUsername:b.username,lastSeenChatIdTelegram:null})}catch(a){return console.error("[configureAgentTelegramAction]",a),d$("db_error","Failed to configure Telegram")}}async function eC(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");return await c.update(p.X6).set({telegramBotToken:null,telegramBotUsername:null,telegramOffset:null,updatedAt:new Date}).where((0,p.eq)(p.X6.id,a)),(0,e.revalidatePath)("/agents"),(0,e.revalidatePath)(`/agents/${a}/telegram`),dZ(void 0)}catch(a){return console.error("[disconnectAgentTelegramAction]",a),d$("db_error","Failed to disconnect Telegram")}}async function eD(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({id:p.dA.id,chatId:p.dA.chatId,role:p.dA.role,status:p.dA.status,requesterName:p.dA.requesterName,createdAt:p.dA.createdAt}).from(p.dA).where((0,p.Uo)((0,p.eq)(p.dA.agentId,a),(0,p.eq)(p.dA.entityId,b.entityId))).orderBy((0,p.i8)(p.dA.createdAt));return dZ(e.map(a=>({id:a.id,chatId:a.chatId,role:a.role,status:a.status,requesterName:a.requesterName,createdAt:a.createdAt?new Date(a.createdAt).toISOString():null})))}catch(a){return console.error("[getTelegramAllowedChatsAction]",a),d$("db_error","Failed to load authorized chats")}}async function eE(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.dA.id,role:p.dA.role,agentId:p.dA.agentId}).from(p.dA).where((0,p.Uo)((0,p.eq)(p.dA.id,a),(0,p.eq)(p.dA.entityId,b.entityId)));if(!d)return d$("not_found","Chat not found");if("owner"===d.role)return d$("validation_failed","Cannot revoke the owner — disconnect the bot instead.");return await c.delete(p.dA).where((0,p.Uo)((0,p.eq)(p.dA.id,a),(0,p.eq)(p.dA.entityId,b.entityId))),(0,e.revalidatePath)(`/agents/${d.agentId}/telegram`),dZ(void 0)}catch(a){return console.error("[revokeTelegramChatAction]",a),d$("db_error","Failed to revoke chat")}}async function eF(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid id");let d=(0,dH.Lf)(),[f]=await d.select({id:p.dA.id,status:p.dA.status,agentId:p.dA.agentId}).from(p.dA).where((0,p.Uo)((0,p.eq)(p.dA.id,a),(0,p.eq)(p.dA.entityId,c.entityId)));if(!f)return d$("not_found","Chat not found");if("pending"!==f.status)return d$("validation_failed","This chat is not pending");return"approve"===b?await d.update(p.dA).set({status:"active",updatedAt:new Date}).where((0,p.Uo)((0,p.eq)(p.dA.id,a),(0,p.eq)(p.dA.entityId,c.entityId))):await d.delete(p.dA).where((0,p.Uo)((0,p.eq)(p.dA.id,a),(0,p.eq)(p.dA.entityId,c.entityId))),(0,e.revalidatePath)(`/agents/${f.agentId}/telegram`),dZ(void 0)}catch(a){return console.error("[resolveTelegramChatAction]",a),d$("db_error","Failed to update chat")}}let eG=g.Ik({agentId:g.Yj().guid().optional(),category:g.k5(["preference","context","outcome","learned_rule"]).optional(),tag:g.Yj().min(1).max(80).optional(),archived:g.zM().default(!1),page:g.ai().int().min(1).default(1),pageSize:g.ai().int().min(1).max(200).default(50)});async function eH(a={}){try{let b=await d_(),c=eG.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),e=await F(d,{entityId:b.entityId,agentId:c.data.agentId,category:c.data.category,tags:c.data.tag?[c.data.tag]:void 0,archived:c.data.archived,page:c.data.page,pageSize:c.data.pageSize,sort:"recent"}),f=Array.from(new Set(e.items.map(a=>a.agent_id).filter(a=>null!==a))),g=new Map;if(f.length>0)for(let a of(await d.select({id:p.X6.id,name:p.X6.name,slug:p.X6.slug}).from(p.X6).where((0,p.RV)(p.X6.id,f))))g.set(a.id,{name:a.name,slug:a.slug});let h=e.items.map(a=>{let b=a.agent_id?g.get(a.agent_id):null;return{...a,agentName:b?.name??null,agentSlug:b?.slug??null}});return dZ({items:h,page:e.page,pageSize:e.pageSize,totalCount:e.totalCount,hasMore:e.hasMore})}catch(a){return console.error("[listMemoriesAction]",a),d$("db_error","Failed to load memories")}}async function eI(a){try{let b=await d_(),c=a.trim();if(!c)return dZ([]);let d=(0,dH.Lf)(),e=await J(d,{query:c,entityId:b.entityId,limit:50,touch:!1}),f=Array.from(new Set(e.map(a=>a.agent_id).filter(a=>null!==a))),g=new Map;if(f.length>0)for(let a of(await d.select({id:p.X6.id,name:p.X6.name,slug:p.X6.slug}).from(p.X6).where((0,p.RV)(p.X6.id,f))))g.set(a.id,{name:a.name,slug:a.slug});let h=e.map(a=>{let b=a.agent_id?g.get(a.agent_id):null;return{...a,agentName:b?.name??null,agentSlug:b?.slug??null}});return dZ(h)}catch(a){return console.error("[searchMemoriesAction]",a),d$("db_error","Failed to search memories")}}let eJ=g.Ik({fact:g.Yj().min(1).max(2e3),category:g.k5(["preference","context","outcome","learned_rule"]).default("context"),importance:g.ai().int().min(1).max(5).default(3)});async function eK(a){try{let b=await d_(),c=eJ.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)();try{await B(d,{entity_id:b.entityId,agent_id:null,fact:c.data.fact,category:c.data.category,importance:c.data.importance,source:"manual",skill_tags:[]})}catch(a){if(a instanceof x)return dZ(void 0);throw a}return dZ(void 0)}catch(a){return console.error("[createMemoryAction]",a),d$("db_error","Failed to save memory")}}async function eL(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid memory id");let c=(0,dH.Lf)();return await C(c,a,b.entityId,{archived:!0}),(0,e.revalidatePath)("/memories"),dZ(void 0)}catch(a){if(a instanceof v)return d$("not_found","Memory not found");return console.error("[archiveMemoryAction]",a),d$("db_error","Failed to archive memory")}}let eM=g.Ik({id:g.Yj().guid(),importance:g.ai().int().min(1).max(5)});async function eN(a,b){try{let c=await d_(),d=eM.safeParse({id:a,importance:b});if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,dH.Lf)();return await C(f,d.data.id,c.entityId,{importance:d.data.importance,importance_locked:!0}),(0,e.revalidatePath)("/memories"),dZ(void 0)}catch(a){if(a instanceof v)return d$("not_found","Memory not found");return console.error("[updateMemoryImportanceAction]",a),d$("db_error","Failed to update importance")}}async function eO(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid memory id");let c=(0,dH.Lf)();return await C(c,a,b.entityId,{importance_locked:!1}),(0,e.revalidatePath)("/memories"),dZ(void 0)}catch(a){if(a instanceof v)return d$("not_found","Memory not found");return console.error("[unpinMemoryImportanceAction]",a),d$("db_error","Failed to unpin importance")}}async function eP(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid memory id");let c=(0,dH.Lf)();return await C(c,a,b.entityId,{archived:!1}),(0,e.revalidatePath)("/memories"),dZ(void 0)}catch(a){if(a instanceof v)return d$("not_found","Memory not found");return console.error("[unarchiveMemoryAction]",a),d$("db_error","Failed to unarchive memory")}}async function eQ(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid memory id");let c=(0,dH.Lf)();return await D(c,a,b.entityId),(0,e.revalidatePath)("/memories"),dZ(void 0)}catch(a){if(a instanceof v)return d$("not_found","Memory not found");return console.error("[deleteMemoryAction]",a),d$("db_error","Failed to delete memory")}}async function eR(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select().from(p.tK).where((0,p.eq)(p.tK.entityId,a.entityId)),d=[...new Set(c.map(a=>a.credentialId).filter(a=>null!==a))],e=d.length>0?await b.select().from(p.z3).where((0,p.RV)(p.z3.id,d)):[],f=new Map;for(let a of e)f.set(a.id,a);let g=new Map;for(let a of e)try{let b=a.payload,c=b.startsWith("enc:v1:")?(0,O.Yc)(b):b,d=JSON.parse(c);g.set(a.id,{accountName:"string"==typeof d.accountName?d.accountName:null,expiresAt:"string"==typeof d.expiresAt&&d.expiresAt?new Date(d.expiresAt):null,scopes:"string"==typeof d.scopes?d.scopes:null})}catch{g.set(a.id,{accountName:null,expiresAt:null,scopes:null})}let h=c.map(a=>{let b=a.credentialId?f.get(a.credentialId):void 0,c=a.credentialId?g.get(a.credentialId)??null:null;return{id:a.id,slug:a.slug,name:a.name,authType:a.authType,active:a.active??!0,hasApiKey:!!a.apiKey,credentialId:a.credentialId??null,credentialName:b?.name??null,credentialType:b?b.type:null,credentialAccountName:c?.accountName??null,credentialExpiresAt:c?.expiresAt??null,credentialScopes:c?.scopes??null,createdAt:a.createdAt,updatedAt:a.updatedAt}}),i=dN.Y.map(a=>({slug:a.slug,label:a.label,authType:a.authType,docsHint:a.docsHint,credentialType:a.credentialType??null}));return dZ({instances:h,catalog:i})}catch(a){return console.error("[listConnectorsAction]",a),d$("db_error","Failed to load connectors")}}let eS=g.Ik({slug:g.Yj().min(1).max(80),name:g.Yj().min(1,"Name is required").max(120),apiKey:g.Yj().min(1,"API key is required")});async function eT(a){try{let b=await d_(),c=eS.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=dN.Y.find(a=>a.slug===c.data.slug);if(!d)return d$("validation_failed","Unknown connector slug");if("api_key"!==d.authType)return d$("validation_failed",`Connector ${c.data.slug} uses ${d.authType}, not api_key`);let f=(0,dH.Lf)(),g=(0,O.ph)(c.data.apiKey)?c.data.apiKey:(0,O.w)(c.data.apiKey),[h]=await f.insert(p.tK).values({entityId:b.entityId,slug:c.data.slug,name:c.data.name,apiKey:g,authType:"api_key",active:!0}).returning({id:p.tK.id});if(!h)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/connectors"),dZ({id:h.id})}catch(a){return console.error("[saveApiKeyConnectorAction]",a),d$("db_error","Failed to save connector")}}async function eU(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid connector id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.tK.id}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.id,a),(0,p.eq)(p.tK.entityId,b.entityId)));if(!d)return d$("not_found","Connector not found");return await c.delete(p.tK).where((0,p.eq)(p.tK.id,a)),(0,e.revalidatePath)("/connectors"),dZ(void 0)}catch(a){return console.error("[deleteConnectorAction]",a),d$("db_error","Failed to delete connector")}}async function eV(){try{let a=await d_(),b=(0,dH.Lf)(),c=(await b.select().from(p.h_).where((0,p.eq)(p.h_.entityId,a.entityId))).map(a=>({id:a.id,slug:a.slug,name:a.name,active:a.active??!0,hasApiKey:!!a.apiKey,apiKeyLast4:a.apiKeyLast4??null,toolCount:Array.isArray(a.availableTools)?a.availableTools.length:0,createdAt:a.createdAt})),d=y.$s.map(a=>({slug:a.slug,label:a.label,description:a.description,docsHint:a.docsHint,keyPrefix:a.keyPrefix,serverUrl:a.serverUrl,transport:a.transport,command:a.command,args:a.args,envVarNames:a.envVarNames,status:a.status??"verified"}));return dZ({instances:c,catalog:d})}catch(a){return console.error("[listMcpServersAction]",a),d$("db_error","Failed to load MCP connectors")}}let eW=g.Ik({slug:g.Yj().min(1).max(80),name:g.Yj().min(1,"Name is required").max(120),apiKey:g.Yj().max(2e3).optional(),url:g.Yj().url("Invalid URL").optional(),customSlug:g.Yj().min(2).max(30).regex(/^[a-z0-9-]+$/,"Slug must be lowercase letters, digits, dashes").optional(),customAuthScheme:g.k5(["header","query","bearer"]).optional(),customAuthParamName:g.Yj().min(1).max(100).optional(),customCommand:g.Yj().min(1).max(200).optional(),customArgs:g.YO(g.Yj().max(500)).max(20).optional(),customEnv:g.g1(g.Yj(),g.Yj().max(2e3)).optional()});async function eX(a){try{let b=await d_(),c=eW.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=y.$s.find(a=>a.slug===c.data.slug);if(!d)return d$("validation_failed","Unknown MCP connector");let f="custom-http-mcp"===d.slug,g="custom-stdio-mcp"===d.slug,h=d.slug,i=d.transport,j=d.authScheme,k=d.authParamName;if(f){if(!c.data.customSlug)return d$("validation_failed","Server slug is required for custom MCP");if(!c.data.customAuthScheme)return d$("validation_failed","Auth scheme is required for custom MCP");if(h=c.data.customSlug,j=c.data.customAuthScheme,k="bearer"===c.data.customAuthScheme?"Authorization":c.data.customAuthParamName??"","bearer"!==j&&!k)return d$("validation_failed",`Auth param name is required for the "${j}" scheme`)}else if(g){if(!c.data.customSlug)return d$("validation_failed","Server slug is required for custom MCP");if(!c.data.customCommand)return d$("validation_failed","Command is required for stdio MCP");h=c.data.customSlug,i="stdio"}if(f||g){let a=(0,dH.Lf)();if((await a.select({id:p.h_.id}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.entityId,b.entityId),(0,p.eq)(p.h_.slug,h)))).length>0)return d$("slug_taken",`Slug "${h}" is already used by another MCP server. Pick a different one.`)}if("http"===i){let a=(c.data.apiKey??"").trim();if(!a)return d$("validation_failed","API key is required");if(!f&&d.keyPrefix.length>0&&!d.keyPrefix.some(b=>a.startsWith(b))){let a=1===d.keyPrefix.length?`"${d.keyPrefix[0]}"`:`one of: ${d.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return d$("validation_failed",`API key must start with ${a}`)}let g=d.serverUrl??c.data.url??null;if(!g)return d$("validation_failed",`${d.label} requires a server URL`);let i=[],l=null;try{if(l=await dV({transport:"http",url:g,apiKey:a,authScheme:j,authParamName:k}),d.verifyToolName&&!f){let a=await l.client.callTool({name:d.verifyToolName,arguments:{}});if(!0===a.isError)return d$("mcp_connect_failed",`${d.label} rejected the API key.`)}i=l.tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return d$("mcp_connect_failed",`Could not connect to ${d.label}: ${a}`)}finally{l&&await l.close().catch(()=>{})}let m=(0,dH.Lf)(),n=(0,O.w)(a),[o]=await m.insert(p.h_).values({entityId:b.entityId,name:c.data.name,slug:h,transport:"http",url:g,apiKey:n,apiKeyLast4:(0,O.nK)(a),authScheme:j,authParamName:k,availableTools:i,active:!0}).returning({id:p.h_.id});if(!o)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/mcp"),dZ({id:o.id})}let l=g?c.data.customCommand:d.command??c.data.customCommand,m=c.data.customArgs??d.args??[],n=c.data.customEnv??{},o=[],q=null;try{o=(q=await dV({transport:"stdio",command:l,args:m,env:n})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return d$("mcp_connect_failed",`Could not start ${d.label} subprocess (${l}): ${a}`)}finally{q&&await q.close().catch(()=>{})}let r={};for(let[a,b]of Object.entries(n))r[a]=(0,O.w)(b);let s=(0,dH.Lf)(),[t]=await s.insert(p.h_).values({entityId:b.entityId,name:c.data.name,slug:h,transport:"stdio",url:null,apiKey:null,apiKeyLast4:null,authScheme:null,authParamName:null,command:l,args:m,envVars:r,availableTools:o,active:!0}).returning({id:p.h_.id});if(!t)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/mcp"),dZ({id:t.id})}catch(a){return console.error("[createMcpServerFromCatalogAction]",a),d$("db_error","Failed to save MCP connector")}}async function eY(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid MCP server id");let d=g.Yj().min(1,"Name is required").max(120).safeParse(b);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid name");let f=(0,dH.Lf)(),[h]=await f.select({id:p.h_.id}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,a),(0,p.eq)(p.h_.entityId,c.entityId)));if(!h)return d$("not_found","MCP connector not found");return await f.update(p.h_).set({name:d.data,updatedAt:new Date}).where((0,p.eq)(p.h_.id,a)),(0,e.revalidatePath)("/mcp"),dZ(void 0)}catch(a){return console.error("[renameMcpServerAction]",a),d$("db_error","Failed to rename MCP server")}}async function eZ(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid MCP server id");let d=g.Yj().min(1,"API key is required").max(2e3).safeParse(b);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid API key");let f=d.data.trim(),h=(0,dH.Lf)(),[i]=await h.select({id:p.h_.id,slug:p.h_.slug,url:p.h_.url,authScheme:p.h_.authScheme,authParamName:p.h_.authParamName}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,a),(0,p.eq)(p.h_.entityId,c.entityId)));if(!i)return d$("not_found","MCP connector not found");let j=y.$s.find(a=>a.slug===i.slug);if(j&&j.keyPrefix.length>0&&!j.keyPrefix.some(a=>f.startsWith(a))){let a=1===j.keyPrefix.length?`"${j.keyPrefix[0]}"`:`one of: ${j.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return d$("validation_failed",`API key must start with ${a}`)}if(!i.url||!i.authScheme||!i.authParamName)return d$("validation_failed","MCP server has incomplete configuration");let k=[],l=null;try{l=await dV({transport:"http",url:i.url,apiKey:f,authScheme:i.authScheme,authParamName:i.authParamName}),k=((await l.client.listTools()).tools??[]).map(a=>({name:a.name,description:a.description??null})),j?.verifyToolName&&await l.client.callTool({name:j.verifyToolName,arguments:{}})}catch(b){let a=b instanceof Error?b.message:"unknown error";return d$("mcp_connect_failed",`Couldn't verify the new key: ${a}`)}finally{l&&await l.close().catch(()=>{})}let m=(0,O.ph)(f)?f:(0,O.w)(f);return await h.update(p.h_).set({apiKey:m,apiKeyLast4:(0,O.nK)(f),availableTools:k,updatedAt:new Date}).where((0,p.eq)(p.h_.id,a)),(0,e.revalidatePath)("/mcp"),dZ(void 0)}catch(a){return console.error("[updateMcpServerApiKeyAction]",a),d$("db_error","Failed to rotate MCP API key")}}async function e$(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid MCP server id");let c=(0,dH.Lf)(),[d]=await c.select().from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,a),(0,p.eq)(p.h_.entityId,b.entityId)));if(!d)return d$("not_found","MCP connector not found");let e=d.envVars??{};return dZ({id:d.id,name:d.name,slug:d.slug,transport:d.transport,url:d.url??null,authScheme:d.authScheme??null,authParamName:d.authParamName??null,command:d.command??null,args:Array.isArray(d.args)?d.args:[],envKeys:Object.keys(e),hasApiKey:!!d.apiKey,apiKeyLast4:d.apiKeyLast4??null})}catch(a){return console.error("[getMcpServerConfigAction]",a),d$("db_error","Failed to load MCP server config")}}let e_=g.Ik({name:g.Yj().min(1,"Name is required").max(120),url:g.Yj().url("Invalid URL").optional(),authScheme:g.k5(["header","query","bearer"]).optional(),authParamName:g.Yj().max(100).optional(),apiKey:g.Yj().max(2e3).optional(),command:g.Yj().min(1).max(200).optional(),args:g.YO(g.Yj().max(500)).max(20).optional(),env:g.g1(g.Yj(),g.Yj().max(2e3)).optional()});async function e0(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid MCP server id");let d=e_.safeParse(b);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,dH.Lf)(),[h]=await f.select().from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,a),(0,p.eq)(p.h_.entityId,c.entityId)));if(!h)return d$("not_found","MCP connector not found");let i=y.$s.find(a=>a.slug===h.slug);if("http"===h.transport){let b,c=(d.data.url??h.url??"").trim();if(!c)return d$("validation_failed","Server URL is required");let g=d.data.authScheme??h.authScheme??"header",j="bearer"===g?"Authorization":(d.data.authParamName??h.authParamName??"").trim();if("bearer"!==g&&!j)return d$("validation_failed",`Auth param name is required for the "${g}" scheme`);let k=(d.data.apiKey??"").trim(),l=k.length>0;if(l){if(i&&i.keyPrefix.length>0&&!i.keyPrefix.some(a=>k.startsWith(a))){let a=1===i.keyPrefix.length?`"${i.keyPrefix[0]}"`:`one of: ${i.keyPrefix.map(a=>`"${a}"`).join(", ")}`;return d$("validation_failed",`API key must start with ${a}`)}b=k}else{if(!h.apiKey)return d$("validation_failed","No stored API key — provide one to connect");try{b=(0,O.Yc)(h.apiKey)}catch{return d$("validation_failed","Stored API key is unreadable — re-enter it")}}let m=[],n=null;try{m=(n=await dV({transport:"http",url:c,apiKey:b,authScheme:g,authParamName:j})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return d$("mcp_connect_failed",`Could not connect with the new config: ${a}`)}finally{n&&await n.close().catch(()=>{})}return await f.update(p.h_).set({name:d.data.name,url:c,authScheme:g,authParamName:j,availableTools:m,...l?{apiKey:(0,O.w)(b),apiKeyLast4:(0,O.nK)(b)}:{},updatedAt:new Date}).where((0,p.eq)(p.h_.id,a)),(0,e.revalidatePath)("/mcp"),dZ(void 0)}let j=(d.data.command??h.command??"").trim();if(!j)return d$("validation_failed","Command is required");let k=d.data.args??(Array.isArray(h.args)?h.args:[]),l=h.envVars??{},m=d.data.env,n={},o={};for(let[a,b]of m?Object.entries(m):Object.entries(l).map(([a])=>[a,""]))if(b&&b.length>0)n[a]=b,o[a]=(0,O.w)(b);else if(void 0!==l[a]){try{n[a]=(0,O.Yc)(l[a])}catch{return d$("validation_failed",`Stored value for "${a}" is unreadable — re-enter it`)}o[a]=l[a]}let q=[],r=null;try{q=(r=await dV({transport:"stdio",command:j,args:k,env:n})).tools.map(a=>({name:a.name,description:a.description??null}))}catch(b){let a=b instanceof Error?b.message:String(b);return d$("mcp_connect_failed",`Could not start the subprocess (${j}): ${a}`)}finally{r&&await r.close().catch(()=>{})}return await f.update(p.h_).set({name:d.data.name,command:j,args:k,envVars:o,availableTools:q,updatedAt:new Date}).where((0,p.eq)(p.h_.id,a)),(0,e.revalidatePath)("/mcp"),dZ(void 0)}catch(a){return console.error("[updateMcpServerConfigAction]",a),d$("db_error","Failed to update MCP server")}}async function e1(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid MCP server id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.h_.id}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,a),(0,p.eq)(p.h_.entityId,b.entityId)));if(!d)return d$("not_found","MCP connector not found");return await c.delete(p.h_).where((0,p.eq)(p.h_.id,a)),(0,e.revalidatePath)("/mcp"),dZ(void 0)}catch(a){return console.error("[deleteMcpServerAction]",a),d$("db_error","Failed to delete MCP connector")}}async function e2(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({id:p.h_.id,slug:p.h_.slug,name:p.h_.name,availableTools:p.h_.availableTools}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.entityId,b.entityId),(0,p.eq)(p.h_.active,!0)));if(0===e.length)return dZ([]);let f=await c.select({mcpServerId:p.oS.mcpServerId,enabledTools:p.oS.enabledTools}).from(p.oS).where((0,p.eq)(p.oS.agentId,a)),h=new Map;for(let a of f)h.set(a.mcpServerId,{enabledTools:a.enabledTools??null});let i=e.map(a=>{let b=h.get(a.id);return{mcpServerId:a.id,slug:a.slug,label:a.name,assigned:void 0!==b,enabledTools:b?.enabledTools??null,availableTools:Array.isArray(a.availableTools)?a.availableTools:[]}});return dZ(i)}catch(a){return console.error("[listAgentMcpServersAction]",a),d$("db_error","Failed to load agent MCP connectors")}}async function e3(a,b,c,d){try{let f=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");if(!g.Yj().guid().safeParse(b).success)return d$("validation_failed","Invalid MCP server id");let h=(0,dH.Lf)(),[i]=await h.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,f.entityId)));if(!i)return d$("not_found","Agent not found");let[j]=await h.select({id:p.h_.id}).from(p.h_).where((0,p.Uo)((0,p.eq)(p.h_.id,b),(0,p.eq)(p.h_.entityId,f.entityId)));if(!j)return d$("not_found","MCP connector not found");return c?await h.insert(p.oS).values({agentId:a,mcpServerId:b,entityId:f.entityId,enabledTools:d??null}).onConflictDoUpdate({target:[p.oS.agentId,p.oS.mcpServerId],set:{enabledTools:d??null,updatedAt:new Date}}):await h.delete(p.oS).where((0,p.Uo)((0,p.eq)(p.oS.agentId,a),(0,p.eq)(p.oS.mcpServerId,b))),(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[setAgentMcpServerAssignmentAction]",a),d$("db_error","Failed to update MCP assignment")}}async function e4(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid connector id");if(null!==b&&!g.Yj().guid().safeParse(b).success)return d$("validation_failed","Invalid credential id");let d=(0,dH.Lf)(),[f]=await d.select({id:p.tK.id,slug:p.tK.slug,authType:p.tK.authType}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.id,a),(0,p.eq)(p.tK.entityId,c.entityId)));if(!f)return d$("not_found","Connector not found");if("oauth2"!==f.authType)return d$("invalid_auth_type","Only OAuth2 connectors support credential assignment");if(null!==b){let[a]=await d.select({id:p.z3.id,ownerUserId:p.z3.ownerUserId,type:p.z3.type}).from(p.z3).where((0,p.eq)(p.z3.id,b));if(!a)return d$("not_found","Credential not found");if(a.ownerUserId!==c.userId)return d$("forbidden","Access denied");let e=(0,dW.ZH)(f.slug);if(e&&e.credentialType!==a.type)return d$("type_mismatch",`Credential type '${a.type}' is not compatible with connector '${f.slug}' (expects '${e.credentialType}')`)}return await d.update(p.tK).set({credentialId:b,updatedAt:new Date}).where((0,p.eq)(p.tK.id,a)),(0,e.revalidatePath)("/connectors"),dZ(void 0)}catch(a){return console.error("[assignCredentialAction]",a),d$("db_error","Failed to assign credential")}}async function e5(a,b,c){try{let d=await d_();if(!g.Yj().min(1).max(80).safeParse(a).success)return d$("validation_failed","Invalid connector slug");if(!g.Yj().guid().safeParse(b).success)return d$("validation_failed","Invalid credential id");if(void 0!==c&&!g.Yj().min(1).max(120).safeParse(c).success)return d$("validation_failed","Invalid connector name");let f=dN.Y.find(b=>b.slug===a);if(!f)return d$("validation_failed","Unknown connector slug");if("oauth2"!==f.authType)return d$("invalid_auth_type","Only OAuth2 connectors support credential assignment");let h=(0,dH.Lf)(),[i]=await h.select({id:p.z3.id,ownerUserId:p.z3.ownerUserId,type:p.z3.type,name:p.z3.name}).from(p.z3).where((0,p.eq)(p.z3.id,b));if(!i)return d$("not_found","Credential not found");if(i.ownerUserId!==d.userId)return d$("forbidden","Access denied");if(f.credentialType&&f.credentialType!==i.type)return d$("type_mismatch",`Credential type '${i.type}' is not compatible with connector '${a}' (expects '${f.credentialType}')`);let j=c??i.name??f.label,[k]=await h.insert(p.tK).values({entityId:d.entityId,slug:a,name:j,authType:"oauth2",credentialId:b,active:!0}).returning({id:p.tK.id});if(!k)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/connectors"),dZ({connectorId:k.id})}catch(a){return console.error("[createOrAssignOAuthConnectorAction]",a),d$("db_error","Failed to assign credential")}}async function e6(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid connector id");let d=g.Yj().min(1,"Name is required").max(120).safeParse(b);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid name");let f=(0,dH.Lf)(),[h]=await f.select({id:p.tK.id}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.id,a),(0,p.eq)(p.tK.entityId,c.entityId)));if(!h)return d$("not_found","Connector not found");return await f.update(p.tK).set({name:d.data,updatedAt:new Date}).where((0,p.eq)(p.tK.id,a)),(0,e.revalidatePath)("/connectors"),dZ(void 0)}catch(a){return console.error("[renameConnectorAction]",a),d$("db_error","Failed to rename connector")}}async function e7(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid connector id");let d=g.Yj().min(1,"API key is required").max(2e3).safeParse(b);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid API key");let f=(0,dH.Lf)(),[h]=await f.select({id:p.tK.id,authType:p.tK.authType}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.id,a),(0,p.eq)(p.tK.entityId,c.entityId)));if(!h)return d$("not_found","Connector not found");if("api_key"!==h.authType)return d$("validation_failed",`Connector uses ${h.authType??"unknown"} auth — key rotation only applies to api_key connectors.`);let i=(0,O.ph)(d.data)?d.data:(0,O.w)(d.data);return await f.update(p.tK).set({apiKey:i,updatedAt:new Date}).where((0,p.eq)(p.tK.id,a)),(0,e.revalidatePath)("/connectors"),dZ(void 0)}catch(a){return console.error("[updateConnectorApiKeyAction]",a),d$("db_error","Failed to rotate API key")}}async function e8(a={}){try{let b=await d_(),c=(0,dH.Lf)(),d=a.status??"pending",e=(0,p.eq)(p.MZ.entityId,b.entityId),f="all"===d?e:(0,p.Uo)(e,(0,p.eq)(p.MZ.status,d)),g=await c.select({id:p.MZ.id,jobId:p.MZ.jobId,agentId:p.MZ.agentId,agentName:p.X6.name,agentSlug:p.X6.slug,toolName:p.MZ.toolName,toolInput:p.MZ.toolInput,status:p.MZ.status,requestedAt:p.MZ.requestedAt,resolvedAt:p.MZ.resolvedAt,resolvedBy:p.MZ.resolvedBy,expiresAt:p.MZ.expiresAt,notes:p.MZ.notes,jobTask:p.ME.task}).from(p.MZ).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.MZ.agentId)).leftJoin(p.ME,(0,p.eq)(p.ME.id,p.MZ.jobId)).where(f).orderBy((0,p.i8)(p.MZ.requestedAt)).limit(100);return dZ(g.map(a=>({...a,status:a.status??"pending"})))}catch(a){return console.error("[listApprovalsAction]",a),d$("db_error","Failed to load approvals")}}let e9=g.Ik({approvalRequestId:g.Yj().guid(),decision:g.k5(["approve","reject"]),notes:g.Yj().max(5e3).optional()});async function fa(a){try{let b,c=await d_(),d=e9.safeParse(a);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,dH.Lf)(),[g]=await f.select({id:p.MZ.id}).from(p.MZ).where((0,p.Uo)((0,p.eq)(p.MZ.id,d.data.approvalRequestId),(0,p.eq)(p.MZ.entityId,c.entityId))).limit(1);if(!g)return d$("not_found","Approval not found");if(!dJ._.WORKER_SECRET)return console.error("[resolveApprovalAction] WORKER_SECRET missing"),d$("config_error","WORKER_SECRET is not set");let h=`${dJ._.RUNNER_URL}/api/approve`;try{b=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify(d.data)})}catch(a){return console.error("[resolveApprovalAction] fetch failed",a),d$("runner_unreachable","Runner did not respond")}if(!b.ok){let a=(await b.json().catch(()=>({}))).error??`runner_${b.status}`;return d$(a,`Runner rejected: ${a}`)}let i=await b.json();return(0,e.revalidatePath)("/approvals"),(0,e.revalidatePath)("/jobs"),(0,e.revalidatePath)(`/jobs/${i.jobId}`),dZ({jobId:i.jobId,decision:i.decision})}catch(a){return console.error("[resolveApprovalAction]",a),d$("db_error","Failed to resolve approval")}}async function fb(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({id:p.bN.id,toolName:p.bN.toolName,action:p.bN.action}).from(p.bN).where((0,p.Uo)((0,p.eq)(p.bN.entityId,b.entityId),(0,p.eq)(p.bN.agentId,a)));return dZ(e.map(a=>({id:a.id,toolName:a.toolName,action:a.action??"auto_approve"})))}catch(a){return console.error("[listAgentApprovalRulesAction]",a),d$("db_error","Failed to load approval rules")}}let fc=g.Ik({agentId:g.Yj().guid(),toolName:g.Yj().min(1).max(200),action:g.k5(["auto_approve","require_approval","block"]).nullable()});async function fd(a){try{let b=await d_(),c=fc.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,toolName:f,action:g}=c.data,h=(0,dH.Lf)(),[i]=await h.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b.entityId)));if(!i)return d$("not_found","Agent not found");return null===g||"auto_approve"===g?await h.delete(p.bN).where((0,p.Uo)((0,p.eq)(p.bN.entityId,b.entityId),(0,p.eq)(p.bN.agentId,d),(0,p.eq)(p.bN.toolName,f))):await h.insert(p.bN).values({entityId:b.entityId,agentId:d,toolName:f,action:g}).onConflictDoUpdate({target:[p.bN.entityId,p.bN.agentId,p.bN.toolName],set:{action:g,updatedAt:new Date}}),(0,e.revalidatePath)(`/agents/${d}/edit`),dZ(void 0)}catch(a){return console.error("[setAgentApprovalRuleAction]",a),d$("db_error","Failed to save approval rule")}}let fe=g.Ik({agentId:g.Yj().guid(),enabled:g.zM()});async function ff(a){try{let b=await d_(),c=fe.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,enabled:f}=c.data;if("local-trust"!==dJ._.AUTH_MODE){let a=(0,dH.Lf)(),[c]=await a.select({userId:p.O5.userId,lanCommandYolo:p.O5.lanCommandYolo}).from(p.O5).where((0,p.eq)(p.O5.id,b.entityId));if(!c)return d$("not_found","Workspace not found");if(c.userId!==b.userId)return d$("forbidden","Only the workspace owner can change command auto-run.");if(f&&!c.lanCommandYolo)return d$("forbidden","Yolo mode is not enabled for this workspace. Enable it in Settings → Command execution first.")}let g=(0,dH.Lf)(),[h]=await g.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b.entityId)));if(!h)return d$("not_found","Agent not found");return await g.transaction(async a=>{await a.delete(p.bN).where((0,p.Uo)((0,p.eq)(p.bN.entityId,b.entityId),(0,p.eq)(p.bN.agentId,d),(0,p.eq)(p.bN.toolName,"run_command"))),f&&await a.insert(p.bN).values({entityId:b.entityId,agentId:d,toolName:"run_command",action:"auto_approve"}).onConflictDoUpdate({target:[p.bN.entityId,p.bN.agentId,p.bN.toolName],set:{action:"auto_approve",updatedAt:new Date}})}),(0,e.revalidatePath)(`/agents/${d}/edit`),dZ(void 0)}catch(a){return console.error("[setRunCommandYoloAction]",a),d$("db_error","Failed to save command execution setting")}}async function fg(){try{let a=await d_(),b=(0,dH.Lf)(),[c]=await b.select({userId:p.O5.userId,lanCommandYolo:p.O5.lanCommandYolo}).from(p.O5).where((0,p.eq)(p.O5.id,a.entityId));if(!c)return d$("not_found","Workspace not found");return dZ({lanCommandYolo:c.lanCommandYolo,isOwner:c.userId===a.userId})}catch(a){return console.error("[getLanCommandYoloAction]",a),d$("db_error","Failed to load LAN command yolo setting")}}let fh=g.Ik({enabled:g.zM()});async function fi(a){try{let b=await d_(),c=fh.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{enabled:d}=c.data,f=(0,dH.Lf)(),[g]=await f.select({userId:p.O5.userId}).from(p.O5).where((0,p.eq)(p.O5.id,b.entityId));if(!g)return d$("not_found","Workspace not found");if(g.userId!==b.userId)return d$("forbidden","Only the workspace owner can change this setting.");return await f.update(p.O5).set({lanCommandYolo:d}).where((0,p.eq)(p.O5.id,b.entityId)),(0,e.revalidatePath)("/settings"),(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[setLanCommandYoloAction]",a),d$("db_error","Failed to save LAN command yolo setting")}}async function fj(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({id:p.eK.id,name:p.eK.name,slug:p.eK.slug,content:p.eK.content,defaultContent:p.eK.defaultContent,contentOverridden:p.eK.contentOverridden,description:p.eK.description,active:p.eK.active,requiredBuiltins:p.eK.requiredBuiltins,isCommunity:p.eK.isCommunity,source:p.eK.source,installedScripts:p.eK.installedScripts,createdBy:p.eK.createdBy,createdAt:p.eK.createdAt,updatedAt:p.eK.updatedAt}).from(p.eK).where((0,p.or)((0,p.eq)(p.eK.entityId,a.entityId),(0,p.Uo)((0,p.RV)(p.eK.slug,dv),(0,p.eq)(p.eK.createdBy,"system")))).orderBy((0,p.i8)(p.eK.updatedAt));if(0===c.length)return dZ([]);let d=await b.select({skillId:p.$m.skillId,c:(0,p.EI)`count(*)`}).from(p.$m).where((0,p.Uo)((0,p.eq)(p.$m.entityId,a.entityId),(0,p.RV)(p.$m.skillId,c.map(a=>a.id)))).groupBy(p.$m.skillId),e=new Map;for(let a of d)e.set(a.skillId,Number(a.c));let f=await b.select({skillId:p.$m.skillId,agentId:p.X6.id,agentName:p.X6.name,agentSlug:p.X6.slug,avatarUrl:p.X6.avatarUrl}).from(p.$m).innerJoin(p.X6,(0,p.eq)(p.X6.id,p.$m.agentId)).where((0,p.Uo)((0,p.eq)(p.$m.entityId,a.entityId),(0,p.RV)(p.$m.skillId,c.map(a=>a.id)))).orderBy(p.X6.name),g=new Map;for(let a of f){let b=g.get(a.skillId)??[];b.length<8&&(b.push({id:a.agentId,name:a.agentName,slug:a.agentSlug,avatarUrl:a.avatarUrl}),g.set(a.skillId,b))}return dZ(c.map(a=>({id:a.id,name:a.name,slug:a.slug,isSystem:"system"===a.createdBy,systemKind:dx(a.slug),content:a.content,defaultContent:a.defaultContent,contentOverridden:a.contentOverridden??!1,description:a.description,active:a.active??!0,requiredBuiltins:a.requiredBuiltins??[],isCommunity:a.isCommunity??!1,source:a.source,installedScripts:a.installedScripts??null,scriptsAuthorized:null,filesWritable:null,assignmentCount:e.get(a.id)??0,assignedAgents:g.get(a.id)??[],createdAt:a.createdAt,updatedAt:a.updatedAt})))}catch(a){return console.error("[listSkillsAction]",a),d$("db_error","Failed to load skills")}}let fk=g.Ik({slug:g.Yj().min(1).max(80).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with dashes"),name:g.Yj().min(1).max(120),content:g.Yj().min(1),description:g.Yj().max(500).optional()});async function fl(a){try{let b=await d_(),c=fk.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),f=await (0,p.qz)(d,b.entityId,{slug:c.data.slug,name:c.data.name,content:c.data.content,description:c.data.description??null},dv);if("error"in f){if("slug_reserved"===f.error)return d$("validation_failed",`"${c.data.slug}" is a reserved system skill slug — choose a different slug`);return d$("conflict","A skill with this slug already exists")}return(0,e.revalidatePath)("/skills"),dZ({id:f.id})}catch(a){return console.error("[createSkillAction]",a),d$("db_error","Failed to create skill")}}async function fm(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid skill id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.eK.id}).from(p.eK).where((0,p.Uo)((0,p.eq)(p.eK.id,a),(0,p.eq)(p.eK.entityId,b.entityId)));if(!d)return d$("not_found","Skill not found");return await c.delete(p.eK).where((0,p.eq)(p.eK.id,a)),(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[deleteSkillAction]",a),d$("db_error","Failed to delete skill")}}let fn=g.Ik({source:g.Yj().min(1).max(2048)});async function fo(a){try{let b,c=await d_(),d=fn.safeParse({source:a});if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");if(!dJ._.WORKER_SECRET)return console.error("[installCommunitySkillAction] WORKER_SECRET missing"),d$("config_error","Runner secret not configured");try{b=await fetch(`${dJ._.RUNNER_URL}/api/skills/install`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify({source:d.data.source,entityId:c.entityId})})}catch(a){return console.error("[installCommunitySkillAction] fetch failed:",a),d$("network_error","Could not reach the runner — is it running?")}let f=await b.json();if(!f.ok)return d$(f.error,f.message);return(0,e.revalidatePath)("/skills"),dZ(f.skill)}catch(a){return console.error("[installCommunitySkillAction]",a),d$("unexpected_error","An unexpected error occurred")}}async function fp(a){try{let b,c=await d_();if(!g.Yj().min(1).safeParse(a).success)return d$("validation_failed","Invalid skill slug");if(!dJ._.WORKER_SECRET)return console.error("[uninstallCommunitySkillAction] WORKER_SECRET missing"),d$("config_error","Runner secret not configured");try{b=await fetch(`${dJ._.RUNNER_URL}/api/skills/uninstall`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify({slug:a,entityId:c.entityId})})}catch(a){return console.error("[uninstallCommunitySkillAction] fetch failed:",a),d$("network_error","Could not reach the runner — is it running?")}let d=await b.json();if(!d.ok)return d$(d.error??"uninstall_failed",d.message??"Uninstall failed");return(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[uninstallCommunitySkillAction]",a),d$("unexpected_error","An unexpected error occurred")}}let fq=g.Ik({skillId:g.Yj().guid(),agentId:g.Yj().guid()});async function fr(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid skill id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.eK.id}).from(p.eK).where((0,p.Uo)((0,p.eq)(p.eK.id,a),(0,p.eq)(p.eK.entityId,b.entityId)));if(!d)return d$("not_found","Skill not found");let e=await c.select({id:p.X6.id,name:p.X6.name,slug:p.X6.slug}).from(p.X6).where((0,p.eq)(p.X6.entityId,b.entityId)).orderBy(p.X6.name),f=await c.select({agentId:p.$m.agentId}).from(p.$m).where((0,p.eq)(p.$m.skillId,a)),h=new Set(f.map(a=>a.agentId));return dZ(e.map(a=>({agentId:a.id,agentName:a.name,agentSlug:a.slug,assigned:h.has(a.id)})))}catch(a){return console.error("[listSkillAssignmentsAction]",a),d$("db_error","Failed to load skill assignments")}}async function fs(a){try{let b=await d_(),c=fq.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),f=await (0,p.ps)(d,b.entityId,c.data,dv);if("error"in f){if("skill_not_found"===f.error)return d$("not_found","Skill not found");if("agent_not_found"===f.error)return d$("not_found","Agent not found")}return(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[assignSkillAction]",a),d$("db_error","Failed to assign skill")}}let ft=g.Ik({id:g.Yj().guid(),name:g.Yj().min(1).max(120),description:g.Yj().max(500).optional(),content:g.Yj().min(1),active:g.zM().optional()});async function fu(a){try{let b=await d_(),c=ft.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{id:d,name:f,description:g,content:h,active:i}=c.data,j=(0,dH.Lf)(),[k]=await j.select({id:p.eK.id,content:p.eK.content}).from(p.eK).where((0,p.Uo)((0,p.eq)(p.eK.id,d),(0,p.eq)(p.eK.entityId,b.entityId)));if(!k)return d$("not_found","Skill not found");let l={name:f,description:g??null,content:h,...void 0!==i?{active:i}:{},updatedAt:new Date};return h!==k.content&&(l.contentOverridden=!0),await j.update(p.eK).set(l).where((0,p.eq)(p.eK.id,d)),(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[updateSkillAction]",a),d$("db_error","Failed to update skill")}}async function fv(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid skill id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.eK.id,defaultContent:p.eK.defaultContent}).from(p.eK).where((0,p.Uo)((0,p.eq)(p.eK.id,a),(0,p.eq)(p.eK.entityId,b.entityId)));if(!d)return d$("not_found","Skill not found");if(null===d.defaultContent)return d$("not_applicable","No default available — this is a user-created skill");return await c.update(p.eK).set({content:d.defaultContent,contentOverridden:!1,updatedAt:new Date}).where((0,p.eq)(p.eK.id,a)),(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[resetSkillToDefaultAction]",a),d$("db_error","Failed to reset skill")}}async function fw(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid skill id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.eK.id,name:p.eK.name,slug:p.eK.slug,content:p.eK.content,defaultContent:p.eK.defaultContent,contentOverridden:p.eK.contentOverridden,description:p.eK.description,active:p.eK.active,requiredBuiltins:p.eK.requiredBuiltins,isCommunity:p.eK.isCommunity,source:p.eK.source,installedScripts:p.eK.installedScripts,createdBy:p.eK.createdBy,createdAt:p.eK.createdAt,updatedAt:p.eK.updatedAt}).from(p.eK).where((0,p.Uo)((0,p.eq)(p.eK.id,a),(0,p.or)((0,p.eq)(p.eK.entityId,b.entityId),(0,p.Uo)((0,p.RV)(p.eK.slug,dv),(0,p.eq)(p.eK.createdBy,"system")))));if(!d)return d$("not_found","Skill not found");return dZ({id:d.id,name:d.name,slug:d.slug,isSystem:"system"===d.createdBy,systemKind:dx(d.slug),content:d.content,defaultContent:d.defaultContent,contentOverridden:d.contentOverridden??!1,description:d.description,active:d.active??!0,requiredBuiltins:d.requiredBuiltins??[],isCommunity:d.isCommunity??!1,source:d.source,installedScripts:d.installedScripts??null,scriptsAuthorized:null,filesWritable:null,assignmentCount:0,assignedAgents:[],createdAt:d.createdAt,updatedAt:d.updatedAt})}catch(a){return console.error("[getSkillByIdAction]",a),d$("db_error","Failed to load skill")}}async function fx(a){try{let b=await d_(),c=fq.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)();return await d.delete(p.$m).where((0,p.Uo)((0,p.eq)(p.$m.skillId,c.data.skillId),(0,p.eq)(p.$m.agentId,c.data.agentId),(0,p.eq)(p.$m.entityId,b.entityId))),(0,e.revalidatePath)("/skills"),dZ(void 0)}catch(a){return console.error("[unassignSkillAction]",a),d$("db_error","Failed to unassign skill")}}async function fy(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({id:p.eK.id,name:p.eK.name,slug:p.eK.slug,content:p.eK.content,defaultContent:p.eK.defaultContent,contentOverridden:p.eK.contentOverridden,description:p.eK.description,active:p.eK.active,requiredBuiltins:p.eK.requiredBuiltins,isCommunity:p.eK.isCommunity,source:p.eK.source,installedScripts:p.eK.installedScripts,createdBy:p.eK.createdBy,createdAt:p.eK.createdAt,updatedAt:p.eK.updatedAt,scriptsAuthorized:p.$m.scriptsAuthorized,filesWritable:p.$m.filesWritable}).from(p.$m).innerJoin(p.eK,(0,p.eq)(p.eK.id,p.$m.skillId)).where((0,p.Uo)((0,p.eq)(p.$m.agentId,a),(0,p.eq)(p.$m.entityId,b.entityId))).orderBy(p.eK.name);return dZ(e.map(a=>({id:a.id,name:a.name,slug:a.slug,isSystem:"system"===a.createdBy,systemKind:dx(a.slug),content:a.content,defaultContent:a.defaultContent,contentOverridden:a.contentOverridden??!1,description:a.description,active:a.active??!0,requiredBuiltins:a.requiredBuiltins??[],isCommunity:a.isCommunity??!1,source:a.source,installedScripts:a.installedScripts??null,scriptsAuthorized:a.scriptsAuthorized??!1,filesWritable:a.filesWritable??!1,assignmentCount:1,assignedAgents:[],createdAt:a.createdAt,updatedAt:a.updatedAt})))}catch(a){return console.error("[getAgentAttachedSkillsAction]",a),d$("db_error","Failed to load agent skills")}}let fz=g.Ik({agentId:g.Yj().guid(),skillId:g.Yj().guid(),authorized:g.zM()});async function fA(a){try{let b=await d_(),c=fz.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,skillId:f,authorized:g}=c.data,h=(0,dH.Lf)(),[i]=await h.select({userId:p.O5.userId}).from(p.O5).where((0,p.eq)(p.O5.id,b.entityId));if(!i)return d$("not_found","Workspace not found");if(i.userId!==b.userId)return d$("forbidden","Only the workspace owner can authorize skill scripts.");let[j]=await h.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b.entityId)));if(!j)return d$("not_found","Agent not found");let k=await (0,p.ZU)(h,d,f,g);if("error"in k)return d$("not_assigned","This skill is not assigned to the agent.");return(0,e.revalidatePath)(`/agents/${d}/edit`),dZ(void 0)}catch(a){return console.error("[setSkillScriptsAuthorizedAction]",a),d$("db_error","Failed to save script authorization")}}let fB=g.Ik({agentId:g.Yj().guid(),skillId:g.Yj().guid(),writable:g.zM()});async function fC(a){try{let b=await d_(),c=fB.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{agentId:d,skillId:f,writable:g}=c.data,h=(0,dH.Lf)(),[i]=await h.select({userId:p.O5.userId}).from(p.O5).where((0,p.eq)(p.O5.id,b.entityId));if(!i)return d$("not_found","Workspace not found");if(i.userId!==b.userId)return d$("forbidden","Only the workspace owner can authorize skill file writes.");let[j]=await h.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b.entityId)));if(!j)return d$("not_found","Agent not found");let k=await (0,p.rY)(h,d,f,g);if("error"in k)return d$("not_assigned","This skill is not assigned to the agent.");return(0,e.revalidatePath)(`/agents/${d}/edit`),dZ(void 0)}catch(a){return console.error("[setSkillFilesWritableAction]",a),d$("db_error","Failed to save file-write authorization")}}let fD=g.Ik({agentId:g.Yj().guid().optional(),toolName:g.Yj().min(1).max(120).optional(),jobId:g.Yj().guid().optional(),page:g.ai().int().min(1).default(1),pageSize:g.ai().int().min(1).max(200).default(50)});async function fE(a={}){try{let b=await d_(),c=fD.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),e=[(0,p.eq)(p.Ky.entityId,b.entityId)];c.data.toolName&&e.push((0,p.eq)(p.Ky.toolName,c.data.toolName)),c.data.jobId&&e.push((0,p.eq)(p.Ky.jobId,c.data.jobId));let f=(c.data.page-1)*c.data.pageSize,g=c.data.agentId?await d.select({id:p.Ky.id,jobId:p.Ky.jobId,agentId:p.ME.agentId,toolName:p.Ky.toolName,toolInput:p.Ky.toolInput,toolOutput:p.Ky.toolOutput,durationMs:p.Ky.durationMs,turn:p.Ky.turn,createdAt:p.Ky.createdAt}).from(p.Ky).leftJoin(p.ME,(0,p.eq)(p.ME.id,p.Ky.jobId)).where((0,p.Uo)(...e,(0,p.eq)(p.ME.agentId,c.data.agentId))).orderBy((0,p.i8)(p.Ky.createdAt)).limit(c.data.pageSize).offset(f):await d.select({id:p.Ky.id,jobId:p.Ky.jobId,agentId:p.ME.agentId,toolName:p.Ky.toolName,toolInput:p.Ky.toolInput,toolOutput:p.Ky.toolOutput,durationMs:p.Ky.durationMs,turn:p.Ky.turn,createdAt:p.Ky.createdAt}).from(p.Ky).leftJoin(p.ME,(0,p.eq)(p.ME.id,p.Ky.jobId)).where((0,p.Uo)(...e)).orderBy((0,p.i8)(p.Ky.createdAt)).limit(c.data.pageSize).offset(f),h=Array.from(new Set(g.map(a=>a.agentId).filter(a=>null!==a))),i=new Map;if(h.length>0)for(let a of(await d.select({id:p.X6.id,name:p.X6.name,slug:p.X6.slug}).from(p.X6).where((0,p.RV)(p.X6.id,h))))i.set(a.id,{name:a.name,slug:a.slug});let j=g.map(a=>{let b=a.agentId?i.get(a.agentId):null;return{id:a.id,jobId:a.jobId,agentId:a.agentId,agentName:b?.name??null,agentSlug:b?.slug??null,toolName:a.toolName,toolInput:a.toolInput,toolOutput:a.toolOutput,durationMs:a.durationMs,turn:a.turn,createdAt:a.createdAt}});return dZ({items:j,page:c.data.page,pageSize:c.data.pageSize})}catch(a){return console.error("[listToolCallsAction]",a),d$("db_error","Failed to load tool calls")}}async function fF(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.selectDistinct({toolName:p.Ky.toolName}).from(p.Ky).where((0,p.eq)(p.Ky.entityId,a.entityId)).orderBy(p.Ky.toolName);return dZ(c.map(a=>a.toolName))}catch(a){return console.error("[listToolNamesAction]",a),d$("db_error","Failed to load tool names")}}async function fG(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({status:p.ME.status,count:(0,p.EI)`count(*)`,inputTokens:(0,p.EI)`coalesce(sum(${p.ME.inputTokens}), 0)`,outputTokens:(0,p.EI)`coalesce(sum(${p.ME.outputTokens}), 0)`,durationMs:(0,p.EI)`coalesce(sum(${p.ME.totalDurationMs}), 0)`}).from(p.ME).where((0,p.eq)(p.ME.entityId,a.entityId)).groupBy(p.ME.status),d={},e=0,f=0,g=0,h=0;for(let a of c){let b=a.status??"unknown",c=Number(a.count);d[b]=(d[b]??0)+c,e+=c,f+=Number(a.inputTokens),g+=Number(a.outputTokens),h+=Number(a.durationMs)}let i=d.completed??0,j=i>0?h/i:null,[k]=await b.select({count:(0,p.EI)`count(*)`}).from(p.Ky).where((0,p.eq)(p.Ky.entityId,a.entityId)),l=Number(k?.count??0),m=(await b.select({agentId:p.ME.agentId,agentName:p.X6.name,agentSlug:p.X6.slug,jobCount:(0,p.EI)`count(*)`,inputTokens:(0,p.EI)`coalesce(sum(${p.ME.inputTokens}), 0)`,outputTokens:(0,p.EI)`coalesce(sum(${p.ME.outputTokens}), 0)`}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.eq)(p.ME.entityId,a.entityId)).groupBy(p.ME.agentId,p.X6.name,p.X6.slug).orderBy((0,p.i8)((0,p.EI)`count(*)`))).filter(a=>!!(a.agentId&&a.agentName&&a.agentSlug)).map(a=>({agentId:a.agentId,agentName:a.agentName,agentSlug:a.agentSlug,jobCount:Number(a.jobCount),inputTokens:Number(a.inputTokens),outputTokens:Number(a.outputTokens)})),[n]=await b.select({count:(0,p.EI)`count(*)`}).from(p.X6).where((0,p.eq)(p.X6.entityId,a.entityId)),o=Number(n?.count??0);return dZ({totalJobs:e,statusCounts:d,totalInputTokens:f,totalOutputTokens:g,totalDurationMs:h,avgDurationMs:j,totalToolCalls:l,agentCount:o,perAgent:m})}catch(a){return console.error("[getEntityStatsAction]",a),d$("db_error","Failed to load stats")}}async function fH(a,b){try{let c=await d_(),d=(0,dH.Lf)(),e="week"===a?(0,p.EI)`date_trunc('week', ${p.ME.createdAt})`:(0,p.EI)`date_trunc('day', ${p.ME.createdAt})`,f="week"===a?(0,p.EI)`${p.ME.createdAt} > now() - interval '12 weeks'`:(0,p.EI)`${p.ME.createdAt} > now() - interval '7 days'`,g=await d.select({bucket:(0,p.EI)`to_char(${e}, 'YYYY-MM-DD')`,status:p.ME.status,model:p.X6.model,provider:p.hG.provider,count:(0,p.EI)`count(*)`}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).leftJoin(p.hG,(0,p.eq)(p.hG.id,p.X6.llmKeyId)).where((0,p.Uo)((0,p.eq)(p.ME.entityId,c.entityId),f)).groupBy(e,p.ME.status,p.X6.model,p.hG.provider),h=new Map;for(let a of b)h.set(a,{week:a,completed:0,failed:0,cancelled:0,awaiting:0,pending:0,models:{}});let i=new Map;for(let a of g){let b=h.get(a.bucket);if(!b)continue;let c=Number(a.count),d=a.status??"";"completed"===d?b.completed+=c:"failed"===d?b.failed+=c:"cancelled"===d?b.cancelled+=c:"pending"===d?b.pending+=c:b.awaiting+=c;let e=function(a,b){if(!b)return"unknown";let c=(b.includes("/")?b.split("/").pop()??b:b).replace(/-20\d{6}$/,""),d=a&&a.trim()?a.trim():"";return d?`${d}/${c}`:c}(a.provider,a.model&&a.model.trim()?a.model:"");b.models[e]=(b.models[e]??0)+c,i.set(e,(i.get(e)??0)+c)}let j=Array.from(i.entries()).sort((a,b)=>b[1]-a[1]).map(([a])=>a);return dZ({rows:Array.from(h.values()),models:j})}catch(a){return console.error("[loadActivity]",a),d$("db_error","Failed to load activity")}}async function fI(){let a=new Date,b=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())),c=(b.getUTCDay()+6)%7;b.setUTCDate(b.getUTCDate()-c);let d=[];for(let a=11;a>=0;a--){let c=new Date(b);c.setUTCDate(c.getUTCDate()-7*a),d.push(c.toISOString().slice(0,10))}return fH("week",d)}async function fJ(){let a=new Date,b=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())),c=[];for(let a=6;a>=0;a--){let d=new Date(b);d.setUTCDate(d.getUTCDate()-a),c.push(d.toISOString().slice(0,10))}return fH("day",c)}async function fK(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({agentId:p.ME.agentId,agentName:p.X6.name,agentSlug:p.X6.slug,avatarUrl:p.X6.avatarUrl,status:p.ME.status,count:(0,p.EI)`count(*)`}).from(p.ME).innerJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.entityId,a.entityId),(0,p.EI)`${p.ME.status} IN ('pending', 'processing', 'awaiting_approval', 'awaiting_delegation')`)).groupBy(p.ME.agentId,p.X6.name,p.X6.slug,p.X6.avatarUrl,p.ME.status),d=new Map;for(let a of c){if(!a.agentId||!a.agentName||!a.agentSlug)continue;let b=d.get(a.agentId)??{agentId:a.agentId,agentName:a.agentName,agentSlug:a.agentSlug,avatarUrl:a.avatarUrl??null,processing:0,awaiting:0,pending:0,total:0},c=Number(a.count),e=a.status??"";"processing"===e?b.processing+=c:"awaiting_approval"===e||"awaiting_delegation"===e?b.awaiting+=c:"pending"===e&&(b.pending+=c),b.total+=c,d.set(a.agentId,b)}let e=Array.from(d.values()).sort((a,b)=>b.total!==a.total?b.total-a.total:a.agentName.localeCompare(b.agentName));return dZ(e)}catch(a){return console.error("[getActiveJobsByAgentAction]",a),d$("db_error","Failed to load active jobs")}}async function fL(){try{let a=await d_(),b=(0,i.join)((0,j.homedir)(),".nodalai","workspaces",a.entityId,"shared");return dZ({llm:{provider:dJ._.LLM_PROVIDER??null,model:dJ._.LLM_MODEL??null,baseURL:dJ._.LLM_BASE_URL??null},authMode:dJ._.AUTH_MODE,runnerUrl:dJ._.RUNNER_URL,appUrl:dJ._.NEXT_PUBLIC_APP_URL,sharedWorkspaceUrl:(0,k.pathToFileURL)(b).href,sharedWorkspacePath:b,sharedWorkspacePathShort:`~/.nodalai/workspaces/${a.entityId.slice(0,8)}…/shared`,workerSecretConfigured:!!dJ._.WORKER_SECRET,user:{userId:a.userId,entityId:a.entityId}})}catch(a){return console.error("[getSettingsAction]",a),d$("db_error","Failed to load settings")}}let fM=null;async function fN(){let a=process.env.NODAL_VERSION??null,b=null;try{let a=Date.now();if(fM&&a-fM.at<18e5)b=fM.latest;else{let c=new AbortController,d=setTimeout(()=>c.abort(),4e3);try{let a=await fetch("https://registry.npmjs.org/nodal-agents/latest",{signal:c.signal,headers:{accept:"application/json"}});if(a.ok){let c=await a.json();b="string"==typeof c.version?c.version:null}}finally{clearTimeout(d)}fM={at:a,latest:b}}}catch{b=null}let c=!!(a&&b&&function(a,b){let c=a=>a.split("-")[0].split(".").map(a=>parseInt(a,10)||0),d=c(a),e=c(b);for(let a=0;a<3;a++)if((d[a]??0)!==(e[a]??0))return(d[a]??0)>(e[a]??0);return!1}(b,a));return dZ({current:a,latest:b,updateAvailable:c})}async function fO(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({id:p.uQ.id,agentId:p.uQ.agentId,agentName:p.X6.name,agentSlug:p.X6.slug,name:p.uQ.name,cronExpr:p.uQ.cronExpr,task:p.uQ.task,active:p.uQ.active,lastRun:p.uQ.lastRun,nextRun:p.uQ.nextRun,lastStatus:p.uQ.lastStatus,notifyOnSuccess:p.uQ.notifyOnSuccess,createdAt:p.uQ.createdAt,updatedAt:p.uQ.updatedAt}).from(p.uQ).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.uQ.agentId)).where((0,p.eq)(p.uQ.entityId,a.entityId)).orderBy((0,p.i8)(p.uQ.updatedAt));return dZ(c.map(a=>({...a,active:a.active??!0,notifyOnSuccess:a.notifyOnSuccess??!1})))}catch(a){return console.error("[listSchedulesAction]",a),d$("db_error","Failed to load schedules")}}let fP=g.Ik({agentId:g.Yj().guid("Pick an agent"),name:g.Yj().min(1).max(120),cronExpr:g.Yj().min(1).max(100),task:g.Yj().min(1),notifyOnSuccess:g.zM().optional().default(!1)});async function fQ(a){try{let b=await d_(),c=fP.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,c.data.agentId),(0,p.eq)(p.X6.entityId,b.entityId)));if(!f)return d$("not_found","Agent not found");let g=dX(c.data.cronExpr);if(!g)return d$("validation_failed","Invalid cron expression");let[h]=await d.insert(p.uQ).values({entityId:b.entityId,agentId:c.data.agentId,type:"cron",name:c.data.name,cronExpr:c.data.cronExpr,task:c.data.task,active:!0,nextRun:g,notifyOnSuccess:c.data.notifyOnSuccess}).returning({id:p.uQ.id});if(!h)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/automations"),dZ({id:h.id})}catch(a){return console.error("[createScheduleAction]",a),d$("db_error","Failed to create schedule")}}async function fR(a){try{if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid schedule id");let b=await d_(),c=(0,dH.Lf)(),[d]=await c.select({agentId:p.uQ.agentId,type:p.uQ.type,name:p.uQ.name,cronExpr:p.uQ.cronExpr,task:p.uQ.task,notifyOnSuccess:p.uQ.notifyOnSuccess}).from(p.uQ).where((0,p.Uo)((0,p.eq)(p.uQ.id,a),(0,p.eq)(p.uQ.entityId,b.entityId)));if(!d)return d$("not_found","Schedule not found");let[f]=await c.insert(p.uQ).values({entityId:b.entityId,agentId:d.agentId,type:d.type??"cron",name:`${d.name} (copy)`,cronExpr:d.cronExpr,task:d.task,active:!1,nextRun:null,notifyOnSuccess:d.notifyOnSuccess??!1}).returning({id:p.uQ.id});if(!f)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/automations"),dZ({id:f.id})}catch(a){return console.error("[duplicateScheduleAction]",a),d$("db_error","Failed to duplicate schedule")}}let fS=g.Ik({id:g.Yj().guid(),agentId:g.Yj().guid("Pick an agent"),name:g.Yj().min(1).max(120),cronExpr:g.Yj().min(1).max(100),task:g.Yj().min(1),notifyOnSuccess:g.zM().optional().default(!1)});async function fT(a){try{let b=await d_(),c=fS.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({id:p.uQ.id}).from(p.uQ).where((0,p.Uo)((0,p.eq)(p.uQ.id,c.data.id),(0,p.eq)(p.uQ.entityId,b.entityId)));if(!f)return d$("not_found","Schedule not found");let[g]=await d.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,c.data.agentId),(0,p.eq)(p.X6.entityId,b.entityId)));if(!g)return d$("not_found","Agent not found");let h=dX(c.data.cronExpr);if(!h)return d$("validation_failed","Invalid cron expression");return await d.update(p.uQ).set({agentId:c.data.agentId,name:c.data.name,cronExpr:c.data.cronExpr,task:c.data.task,nextRun:h,notifyOnSuccess:c.data.notifyOnSuccess,updatedAt:new Date}).where((0,p.eq)(p.uQ.id,c.data.id)),(0,e.revalidatePath)("/automations"),dZ(void 0)}catch(a){return console.error("[updateScheduleAction]",a),d$("db_error","Failed to update schedule")}}async function fU(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid schedule id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.uQ.id,active:p.uQ.active}).from(p.uQ).where((0,p.Uo)((0,p.eq)(p.uQ.id,a),(0,p.eq)(p.uQ.entityId,b.entityId)));if(!d)return d$("not_found","Schedule not found");let f=!(d.active??!0);return await c.update(p.uQ).set({active:f,updatedAt:new Date}).where((0,p.eq)(p.uQ.id,a)),(0,e.revalidatePath)("/automations"),dZ({active:f})}catch(a){return console.error("[toggleScheduleAction]",a),d$("db_error","Failed to toggle schedule")}}async function fV(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid schedule id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.uQ.id}).from(p.uQ).where((0,p.Uo)((0,p.eq)(p.uQ.id,a),(0,p.eq)(p.uQ.entityId,b.entityId)));if(!d)return d$("not_found","Schedule not found");return await c.delete(p.uQ).where((0,p.eq)(p.uQ.id,a)),(0,e.revalidatePath)("/automations"),dZ(void 0)}catch(a){return console.error("[deleteScheduleAction]",a),d$("db_error","Failed to delete schedule")}}async function fW(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid schedule id");let c=(0,dH.Lf)(),[d]=await c.select({agentId:p.uQ.agentId,task:p.uQ.task,chatId:p.uQ.chatId,notifyOnSuccess:p.uQ.notifyOnSuccess,agentChatId:p.X6.lastSeenChatIdTelegram}).from(p.uQ).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.uQ.agentId)).where((0,p.Uo)((0,p.eq)(p.uQ.id,a),(0,p.eq)(p.uQ.entityId,b.entityId))).limit(1);if(!d)return d$("not_found","Schedule not found");if(!d.task)return d$("validation_failed","This automation has no task to run.");let f=d.notifyOnSuccess?d.chatId??d.agentChatId??null:null,[h]=await c.insert(p.ME).values({entityId:b.entityId,agentId:d.agentId,status:"pending",channel:"cron",task:d.task,messages:[{role:"user",content:d.task}],...f?{chatId:f}:{}}).returning({id:p.ME.id});if(!h)return d$("db_error","Failed to create job");return dJ._.WORKER_SECRET?fetch(`${dJ._.RUNNER_URL}/api/worker`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify({jobId:h.id})}).catch(a=>{console.error("[runScheduleNowAction] runner ping failed:",a)}):console.error("[runScheduleNowAction] WORKER_SECRET missing — cannot ping runner"),(0,e.revalidatePath)("/automations"),(0,e.revalidatePath)("/jobs"),dZ({jobId:h.id})}catch(a){return console.error("[runScheduleNowAction]",a),d$("db_error","Failed to run schedule now")}}async function fX(){try{await d_();let a=function(){let a=dL();if(!a)return{configuredMode:"local-trust",googleConfigured:!1,configPathExists:!1};let b=a.auth??null,c=a.bind;return{configuredMode:b?.mode??("lan"===c?"local-auth":"local-trust"),googleConfigured:!!(b?.googleClientId&&b?.googleClientSecret),configPathExists:!0}}();return dZ({runtimeMode:dJ._.AUTH_MODE,configuredMode:a.configuredMode,googleConfigured:a.googleConfigured,googleAvailableInRuntime:!!(dJ._.GOOGLE_CLIENT_ID&&dJ._.GOOGLE_CLIENT_SECRET),configPathExists:a.configPathExists})}catch(a){return console.error("[getSecuritySettingsAction]",a),d$("db_error","Failed to load security settings")}}let fY=g.Ik({mode:g.k5(["local-trust","local-auth"]),googleClientId:g.Yj().max(200).optional(),googleClientSecret:g.Yj().max(200).optional(),clearGoogle:g.zM().default(!1)});async function fZ(a){try{await d_();let b=await d0();if(b)return b;let c=fY.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=dL();if(!d)return d$("cli_config_missing","Cannot find ~/.nodalai/config.json — run `nodal-agents init` first.");let f={...d.auth??{},mode:c.data.mode};c.data.clearGoogle?(delete f.googleClientId,delete f.googleClientSecret):(c.data.googleClientId&&c.data.googleClientId.trim().length>0&&(f.googleClientId=c.data.googleClientId.trim()),c.data.googleClientSecret&&c.data.googleClientSecret.trim().length>0&&(f.googleClientSecret=c.data.googleClientSecret.trim()));try{dM({auth:f})}catch(b){let a=b instanceof Error?b.message:"";if("cli_config_missing"===a)return d$("cli_config_missing","Config file disappeared between read and write.");throw b}(0,e.revalidatePath)("/settings");let g=c.data.mode!==dJ._.AUTH_MODE;return dZ({requiresRestart:g})}catch(a){return console.error("[updateAuthSettingsAction]",a),d$("db_error","Failed to update auth settings")}}async function f$(){try{let a;await d_();let b=(a=dL())?{configuredBind:"lan"===a.bind?"lan":"loopback",configPathExists:!0}:{configuredBind:"loopback",configPathExists:!1},c="0.0.0.0"===dJ._.BIND?"lan":"loopback";return dZ({configuredBind:b.configuredBind,runtimeBind:c,lanAddresses:function(){let a=(0,j.networkInterfaces)(),b=[];for(let c of Object.values(a))if(c)for(let a of c)"IPv4"!==a.family||a.internal||b.push(a.address);return b}(),webPort:function(a){try{let b=new URL(a);if(b.port)return Number(b.port);return"https:"===b.protocol?443:80}catch{return 3e3}}(dJ._.NEXT_PUBLIC_APP_URL),configPathExists:b.configPathExists})}catch(a){return console.error("[getNetworkSettingsAction]",a),d$("db_error","Failed to load network settings")}}let f_=g.Ik({bind:g.k5(["loopback","lan"])});async function f0(a){try{await d_();let b=await d0();if(b)return b;let c=f_.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");try{dM({bind:c.data.bind})}catch(b){let a=b instanceof Error?b.message:"";if("cli_config_missing"===a)return d$("cli_config_missing","Cannot find ~/.nodalai/config.json — run `nodal-agents init` first.");throw b}(0,e.revalidatePath)("/settings");let d="0.0.0.0"===dJ._.BIND?"lan":"loopback";return dZ({requiresRestart:c.data.bind!==d})}catch(a){return console.error("[updateNetworkSettingsAction]",a),d$("db_error","Failed to update network settings")}}let f1=["anthropic","openai","openai-compatible","ollama","openrouter","google","mistral","groq","deepseek","minimax"],f2=g.Yj().optional().transform(a=>a&&a.length>0?a:null).pipe(g.Yj().url().nullable().or(g.ch())),f3=g.Ik({provider:g.k5(f1),baseUrl:f2,apiKey:g.Yj().optional(),nickname:g.Yj().max(120).nullish(),isActive:g.zM().default(!0)}),f4=g.Ik({id:g.Yj().guid(),provider:g.k5(f1),baseUrl:f2,apiKey:g.Yj().optional(),nickname:g.Yj().max(120).nullish(),isActive:g.zM()}),f5=g.Ik({provider:g.k5(f1),baseUrl:f2,apiKey:g.Yj().optional(),model:g.Yj().optional(),keyId:g.Yj().guid().optional()});async function f6(){try{let a=await d_(),b=(0,dH.Lf)(),c=await b.select({id:p.hG.id,provider:p.hG.provider,baseUrl:p.hG.baseUrl,nickname:p.hG.nickname,isActive:p.hG.isActive,hasApiKey:(0,p.EI)`(${p.hG.apiKey} <> '')`,apiKeyLast4:p.hG.apiKeyLast4}).from(p.hG).where((0,p.eq)(p.hG.entityId,a.entityId)).orderBy((0,p.i8)(p.hG.createdAt)),d=await b.select({llmKeyId:p.X6.llmKeyId,n:(0,p.EI)`count(*)`}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.entityId,a.entityId),(0,p.eq)(p.X6.active,!0))).groupBy(p.X6.llmKeyId),e=new Map;for(let a of d)a.llmKeyId&&e.set(a.llmKeyId,Number(a.n));return dZ(c.map(a=>({id:a.id,provider:a.provider,baseUrl:a.baseUrl,nickname:a.nickname,isActive:a.isActive,hasApiKey:!!a.hasApiKey,apiKeyLast4:a.apiKeyLast4?a.apiKeyLast4:null,agentCount:e.get(a.id)??0})))}catch(a){return console.error("[listLlmKeysAction]",a),d$("db_error","Failed to load LLM providers")}}async function f7(a){try{let b=await d_(),c=f3.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({id:p.hG.id}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.entityId,b.entityId),(0,p.eq)(p.hG.provider,c.data.provider))).limit(1);if(f)return d$("provider_exists","This provider is already configured — edit the existing one.");let g=c.data.apiKey??"",[h]=await d.insert(p.hG).values({entityId:b.entityId,provider:c.data.provider,apiKey:(0,O.w)(g),apiKeyLast4:(0,O.nK)(g),baseUrl:c.data.baseUrl,nickname:c.data.nickname??null,isActive:c.data.isActive}).returning({id:p.hG.id});if(!h)return d$("db_error","Insert returned no row");return(0,e.revalidatePath)("/settings"),dZ({id:h.id})}catch(a){return console.error("[createLlmKeyAction]",a),d$("db_error","Failed to create LLM provider")}}async function f8(a){try{let b=await d_(),c=f4.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{id:d,provider:f,baseUrl:g,apiKey:h,nickname:i,isActive:j}=c.data,k=(0,dH.Lf)(),[l]=await k.select({id:p.hG.id}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.id,d),(0,p.eq)(p.hG.entityId,b.entityId)));if(!l)return d$("not_found","LLM provider not found");let m={provider:f,baseUrl:g,nickname:i??null,isActive:j,updatedAt:new Date};return h&&h.length>0&&(m.apiKey=(0,O.w)(h),m.apiKeyLast4=(0,O.nK)(h)),await k.update(p.hG).set(m).where((0,p.eq)(p.hG.id,d)),(0,e.revalidatePath)("/settings"),dZ(void 0)}catch(a){return console.error("[updateLlmKeyAction]",a),d$("db_error","Failed to update LLM provider")}}async function f9(a,b){try{let c=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid LLM provider id");let d=(0,dH.Lf)(),[f]=await d.select({id:p.hG.id}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.id,a),(0,p.eq)(p.hG.entityId,c.entityId)));if(!f)return d$("not_found","LLM provider not found");return await d.update(p.hG).set({isActive:b,updatedAt:new Date}).where((0,p.eq)(p.hG.id,a)),(0,e.revalidatePath)("/llm-providers"),dZ(void 0)}catch(a){return console.error("[setLlmKeyActiveAction]",a),d$("db_error","Failed to update LLM provider")}}async function ga(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid LLM provider id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.hG.id}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.id,a),(0,p.eq)(p.hG.entityId,b.entityId)));if(!d)return d$("not_found","LLM provider not found");return await c.delete(p.hG).where((0,p.eq)(p.hG.id,a)),(0,e.revalidatePath)("/settings"),dZ(void 0)}catch(a){return console.error("[deleteLlmKeyAction]",a),d$("db_error","Failed to delete LLM provider")}}let gb=new Set(["metadata.google.internal","metadata.azure.com"]),gc=new Set(["100.100.100.200","192.0.0.192","fd00:ec2::254"].map(a=>o().parse(a).toString()));function gd(a){return!!gc.has(a.toString())||"linkLocal"===a.range()}function ge(a){let b,c;if(!o().isValid(a))return!1;let d=o().parse(a);return"ipv4"===d.kind()?gd(d):!!gd(d)||(b=d.toByteArray(),c=[o().fromByteArray(b.slice(12,16))],32===b[0]&&2===b[1]&&c.push(o().fromByteArray(b.slice(2,6))),c).some(a=>gd(a))}async function gf(a){let b;try{b=new URL(a)}catch{return"Invalid URL"}let c=b.hostname.replace(/^\[|\]$/g,"");if(gb.has(c.toLowerCase()))return"This endpoint is not reachable (blocked cloud metadata hostname).";if(o().isValid(c))return ge(c)?"This endpoint is not reachable (link-local / cloud metadata address).":null;try{for(let{address:a}of(await (0,m.lookup)(c,{all:!0})))if(ge(a))return"This endpoint is not reachable (resolves to a link-local / cloud metadata address)."}catch{}return null}async function gg(a,b){let c=await fetch(a,{...b,redirect:"manual"});if(c.status>=300&&c.status<400){let d=c.headers.get("location");if(!d)return c;let e=new URL(d,a).toString(),f=await gf(e);if(f)throw Error(`Redirect target blocked: ${f}`);return fetch(e,{...b,redirect:"manual"})}return c}let gh={anthropic:{canonicalBase:"https://api.anthropic.com/v1",path:"/models",auth:"x-api-key"},openai:{canonicalBase:"https://api.openai.com/v1",path:"/models",auth:"bearer"},openrouter:{canonicalBase:"https://openrouter.ai/api/v1",path:"/auth/key",auth:"bearer"},google:{canonicalBase:"https://generativelanguage.googleapis.com/v1beta",path:"/models",auth:"query"},mistral:{canonicalBase:"https://api.mistral.ai/v1",path:"/models",auth:"bearer"},groq:{canonicalBase:"https://api.groq.com/openai/v1",path:"/models",auth:"bearer"},"openai-compatible":{canonicalBase:null,path:"/models",auth:"bearer"},ollama:{canonicalBase:null,path:"/api/tags",auth:"none"},deepseek:{canonicalBase:"https://api.deepseek.com",path:"/models",auth:"bearer"},minimax:{canonicalBase:"https://api.minimax.io/anthropic",path:"/v1/models",auth:"bearer"}};async function gi(a,b,c){try{let d=gh[a];if("openrouter"===a||await gf(b))return[];let e={Accept:"application/json"},f=`${b}${d.path}`;"bearer"===d.auth&&c&&(e.Authorization=`Bearer ${c}`),"x-api-key"===d.auth&&c&&(e["x-api-key"]=c,e["anthropic-version"]="2023-06-01"),"query"===d.auth&&(f=`${f}?key=${encodeURIComponent(c??"")}`);let g=await gg(f,{method:"GET",headers:e});if(!g.ok)return[];let h=await g.json(),i=h.data??h.models;if(!Array.isArray(i))return[];let j=i.map(a=>{let b=a.id??a.name;return"string"==typeof b?b:null}).filter(a=>null!==a&&a.length>0);return[...new Set(j)]}catch{return[]}}async function gj(a){let b;try{let c=await d_(),d=f5.safeParse(a);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let{provider:e,baseUrl:f}=d.data;if((!(b=d.data.apiKey)||0===b.length)&&d.data.keyId){let a=(0,dH.Lf)(),[e]=await a.select({apiKey:p.hG.apiKey}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.id,d.data.keyId),(0,p.eq)(p.hG.entityId,c.entityId)));if(!e)return d$("not_found","LLM provider not found");b=e.apiKey?(0,O.Yc)(e.apiKey):void 0}if(d.data.keyId&&(!b||0===b.length))return d$("no_api_key_provided","API key is required to test");let g=gh[e],h=(f??"").replace(/\/$/,"")||g.canonicalBase;if(!h)return d$("validation_failed",`baseUrl is required for ${e}`);let i=await gf(h);if(i)return d$("validation_failed",i);let j={Accept:"application/json"},k=`${h}${g.path}`;"bearer"===g.auth&&b&&(j.Authorization=`Bearer ${b}`),"x-api-key"===g.auth&&b&&(j["x-api-key"]=b,j["anthropic-version"]="2023-06-01"),"query"===g.auth&&(k=`${k}?key=${encodeURIComponent(b??"")}`);let l=await gg(k,{method:"GET",headers:j});if(!l.ok)return d$("connection_failed",`${e} responded with status ${l.status}.`);let m=null;try{let a=await l.json(),b=a.data??a.models;Array.isArray(b)&&(m=b.length)}catch{}return dZ({message:null!==m?`Connected, ${m} models available`:"Connected"})}catch(a){var c,d;return d$("connection_failed",(c=a instanceof Error?a.message:"Unknown error",(d=b)&&0!==d.length?c.replaceAll(d,"[REDACTED]"):c))}}async function gk(a){try{if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid key id");let b=await d_(),c=(0,dH.Lf)(),[d]=await c.select({provider:p.hG.provider,apiKey:p.hG.apiKey,baseUrl:p.hG.baseUrl}).from(p.hG).where((0,p.Uo)((0,p.eq)(p.hG.id,a),(0,p.eq)(p.hG.entityId,b.entityId)));if(!d)return d$("not_found","LLM key not found");let e=d.provider,f=d.apiKey&&d.apiKey.length>0?(0,O.Yc)(d.apiKey):void 0,h=gh[e],i=(d.baseUrl??"").replace(/\/$/,"")||h?.canonicalBase;if(!i)return dZ([]);let j=await gi(e,i,f);return dZ(j)}catch{return dZ([])}}async function gl(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,b.entityId)));if(!d)return d$("not_found","Agent not found");let e=await c.select({id:p.tK.id,slug:p.tK.slug,name:p.tK.name,credentialId:p.tK.credentialId,active:p.tK.active}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.entityId,b.entityId),(0,p.eq)(p.tK.active,!0)));if(0===e.length)return dZ([]);let f=[...new Set(e.map(a=>a.credentialId).filter(a=>null!==a))],h=new Map;if(f.length>0)for(let a of(await c.select({id:p.z3.id,name:p.z3.name}).from(p.z3).where((0,p.RV)(p.z3.id,f))))h.set(a.id,a.name);let i=await c.select({connectorId:p.XT.connectorId,enabledOperations:p.XT.enabledOperations}).from(p.XT).where((0,p.eq)(p.XT.agentId,a)),j=new Map;for(let a of i)j.set(a.connectorId,{enabledOperations:a.enabledOperations??null});let k=[];for(let a of e){let b=dg[a.slug];if(!b)continue;let c=j.get(a.id);k.push({connectorId:a.id,slug:a.slug,label:a.name,credentialName:a.credentialId?h.get(a.credentialId)??null:null,assigned:void 0!==c,enabledOperations:c?.enabledOperations??null,availableOperations:b.operations})}return dZ(k)}catch(a){return console.error("[listAgentConnectorsAction]",a),d$("db_error","Failed to load agent connectors")}}async function gm(){try{let a=await d_(),b=(0,dH.Lf)(),c=await (0,p.fI)(b,a.entityId);return dZ(c)}catch(a){return console.error("[getInstallNotesAction]",a),d$("db_error","Failed to load install notes")}}async function gn(a){try{let b=await d_(),c=g.Yj().max(4e3).safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),[f]=await d.select({role:p.V.role}).from(p.V).where((0,p.Uo)((0,p.eq)(p.V.userId,b.userId),(0,p.eq)(p.V.entityId,b.entityId)));if(!f||"owner"!==f.role)return d$("forbidden","Only the workspace owner can set install notes.");return await (0,p.lx)(d,b.entityId,c.data),(0,e.revalidatePath)("/settings"),dZ(void 0)}catch(a){return console.error("[setInstallNotesAction]",a),d$("db_error","Failed to save install notes")}}async function go(){try{let a=await d_(),b=(0,dH.Lf)(),{rootAgentId:c,rootName:d}=await gw(b,a.entityId);if(!c)return dZ({rootAgentId:null,rootName:null,personality:"",skills:[]});let[e]=await b.select({personality:p.X6.personality}).from(p.X6).where((0,p.eq)(p.X6.id,c)),f=await b.select({id:p.eK.id,name:p.eK.name,description:p.eK.description,content:p.eK.content}).from(p.$m).innerJoin(p.eK,(0,p.eq)(p.$m.skillId,p.eK.id)).where((0,p.eq)(p.$m.agentId,c));return dZ({rootAgentId:c,rootName:d,personality:e?.personality??"",skills:f.map(a=>({id:a.id,name:a.name,description:a.description??null,content:a.content??""}))})}catch(a){return console.error("[getRootContextAction]",a),d$("db_error","Failed to load root context")}}let gp=g.Ik({personality:g.Yj().min(1).max(2e4)});async function gq(a){try{let b=await d_(),c=gp.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let d=(0,dH.Lf)(),{rootAgentId:f}=await gw(d,b.entityId);if(!f)return d$("not_found","No ROOT agent designated");return await d.update(p.X6).set({personality:c.data.personality}).where((0,p.Uo)((0,p.eq)(p.X6.id,f),(0,p.eq)(p.X6.entityId,b.entityId))),(0,e.revalidatePath)("/settings/root-context"),dZ(void 0)}catch(a){return console.error("[updateRootPersonalityAction]",a),d$("db_error","Failed to update personality")}}async function gr(){try{let a=await d_(),b=(0,dH.Lf)(),{rootAgentId:c}=await gw(b,a.entityId);if(!c)return d$("not_found","No ROOT agent designated");let[d]=await b.select().from(p.X6).where((0,p.eq)(p.X6.id,c));if(!d)return d$("not_found","ROOT agent not found");let e={id:d.id,name:d.name,slug:d.slug,role:d.role??"agent",personality:d.personality,entityId:d.entityId??null,model:d.model??"",active:d.active??!0,orchestratorMode:d.orchestratorMode??null,memoryTokenBudget:d.memoryTokenBudget??4e3},f={os:"win32"===process.platform?"Windows":"darwin"===process.platform?"macOS":"Linux",networkMode:"0.0.0.0"===process.env.BIND?"lan":"loopback",authMode:process.env.AUTH_MODE??"local-trust",installNotes:await (0,p.fI)(b,a.entityId)},g=await dG(e,b,{origin:"dashboard",deployment:f});return dZ(g)}catch(a){return console.error("[getRootSystemPromptAction]",a),d$("db_error","Failed to assemble system prompt")}}async function gs(a,b,c,d){try{let f=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid agent id");if(!g.Yj().guid().safeParse(b).success)return d$("validation_failed","Invalid connector id");let h=(0,dH.Lf)(),[i]=await h.select({id:p.X6.id}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,a),(0,p.eq)(p.X6.entityId,f.entityId)));if(!i)return d$("not_found","Agent not found");let[j]=await h.select({id:p.tK.id}).from(p.tK).where((0,p.Uo)((0,p.eq)(p.tK.id,b),(0,p.eq)(p.tK.entityId,f.entityId)));if(!j)return d$("not_found","Connector not found");return c?await h.insert(p.XT).values({agentId:a,connectorId:b,entityId:f.entityId,enabledOperations:d??null}).onConflictDoUpdate({target:[p.XT.agentId,p.XT.connectorId],set:{enabledOperations:d??null,updatedAt:new Date}}):await h.delete(p.XT).where((0,p.Uo)((0,p.eq)(p.XT.agentId,a),(0,p.eq)(p.XT.connectorId,b))),(0,e.revalidatePath)("/agents"),dZ(void 0)}catch(a){return console.error("[setAgentConnectorAssignmentAction]",a),d$("db_error","Failed to update connector assignment")}}async function gt(){try{let a=await d_(),b=(0,dH.Lf)(),[c]=await b.select({rootAgentId:p.O5.rootAgentId,rootGrants:p.O5.rootGrants}).from(p.O5).where((0,p.eq)(p.O5.id,a.entityId));if(!c)return d$("not_found","Workspace not found");return dZ({rootAgentId:c.rootAgentId??null,grants:(0,y.DI)(c.rootGrants)})}catch(a){return console.error("[getRootConfigAction]",a),d$("db_error","Failed to load ROOT agent config")}}let gu=g.Ik({grants:g.Ik({createAgent:g.zM(),updateAgent:g.zM(),attachAgent:g.zM(),createSkill:g.zM(),updateSkill:g.zM(),assignSkill:g.zM(),createMcp:g.zM(),attachMcp:g.zM(),createConnector:g.zM(),attachConnector:g.zM(),manageSchedules:g.zM(),autonomy:g.k5(["propose_confirm","destructive_gate","fully_autonomous"])})});async function gv(a){try{let b=await d_(),c=gu.safeParse(a);if(!c.success)return d$("validation_failed",c.error.issues[0]?.message??"Invalid input");let{grants:d}=c.data,f=(0,dH.Lf)(),[g]=await f.select({role:p.V.role}).from(p.V).where((0,p.Uo)((0,p.eq)(p.V.userId,b.userId),(0,p.eq)(p.V.entityId,b.entityId)));if(!g)return d$("not_found","Workspace not found");let[h]=await f.select({rootAgentId:p.O5.rootAgentId}).from(p.O5).where((0,p.eq)(p.O5.id,b.entityId)),i=h?.rootAgentId??null;if(!i)return d$("not_found","No ROOT agent yet — create an orchestrator first");return await f.update(p.O5).set({rootGrants:d,updatedAt:new Date}).where((0,p.eq)(p.O5.id,b.entityId)),await f.transaction(async a=>{if(await a.delete(p.bN).where((0,p.Uo)((0,p.eq)(p.bN.entityId,b.entityId),(0,p.RV)(p.bN.toolName,y.yO))),"propose_confirm"===d.autonomy){let c=(0,y.aT)(d);c.length>0&&await a.insert(p.bN).values(c.map(a=>({entityId:b.entityId,agentId:i,toolName:a,action:"require_approval"}))).onConflictDoUpdate({target:[p.bN.entityId,p.bN.agentId,p.bN.toolName],set:{action:"require_approval",updatedAt:new Date}})}}),(0,e.revalidatePath)("/settings"),dZ(void 0)}catch(a){return console.error("[setRootAgentAction]",a),d$("db_error","Failed to save ROOT agent config")}}async function gw(a,b){let[c]=await a.select({rootAgentId:p.O5.rootAgentId}).from(p.O5).where((0,p.eq)(p.O5.id,b)).limit(1),d=c?.rootAgentId??null;if(!d)return{rootAgentId:null,rootName:null};let[e]=await a.select({name:p.X6.name}).from(p.X6).where((0,p.Uo)((0,p.eq)(p.X6.id,d),(0,p.eq)(p.X6.entityId,b))).limit(1);return{rootAgentId:d,rootName:e?.name??null}}async function gx(){try{let a=await d_(),b=(0,dH.Lf)(),{rootAgentId:c,rootName:d}=await gw(b,a.entityId);if(!c)return dZ({rootAgentId:null,rootName:null,conversations:[]});let e=await b.select({id:p.NP.id,title:p.NP.title,updatedAt:p.NP.updatedAt}).from(p.NP).where((0,p.Uo)((0,p.eq)(p.NP.entityId,a.entityId),(0,p.eq)(p.NP.agentId,c))).orderBy((0,p.i8)(p.NP.updatedAt)).limit(200),f=e.map(a=>a.id),g=new Map;if(f.length>0)for(let a of(await b.select({conversationId:p.p$.conversationId,content:p.p$.content}).from(p.p$).where((0,p.RV)(p.p$.conversationId,f)).orderBy((0,p.i8)(p.p$.createdAt)).limit(1e3)))a.conversationId&&!g.has(a.conversationId)&&g.set(a.conversationId,a.content);let h=e.map(a=>({id:a.id,title:a.title,preview:g.get(a.id)??"",updatedAt:a.updatedAt}));return dZ({rootAgentId:c,rootName:d,conversations:h})}catch(a){return console.error("[listConversationsAction]",a),d$("db_error","Failed to load conversations")}}async function gy(){try{let a=await d_(),b=(0,dH.Lf)(),{rootAgentId:c}=await gw(b,a.entityId);if(!c)return d$("no_root_agent","Designate a ROOT agent in Settings first.");let[d]=await b.insert(p.NP).values({entityId:a.entityId,agentId:c,title:""}).returning({id:p.NP.id});if(!d)return d$("db_error","Failed to create conversation");return(0,e.revalidatePath)("/chat"),dZ({id:d.id})}catch(a){return console.error("[createConversationAction]",a),d$("db_error","Failed to create conversation")}}async function gz(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid conversation id");let c=(0,dH.Lf)();return await c.delete(p.NP).where((0,p.Uo)((0,p.eq)(p.NP.id,a),(0,p.eq)(p.NP.entityId,b.entityId))),(0,e.revalidatePath)("/chat"),dZ(void 0)}catch(a){return console.error("[deleteConversationAction]",a),d$("db_error","Failed to delete conversation")}}async function gA(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid conversation id");let c=(0,dH.Lf)(),[d]=await c.select({id:p.NP.id}).from(p.NP).where((0,p.Uo)((0,p.eq)(p.NP.id,a),(0,p.eq)(p.NP.entityId,b.entityId))).limit(1);if(!d)return d$("not_found","Conversation not found");let e=(await c.select({id:p.p$.id,role:p.p$.role,content:p.p$.content,jobId:p.p$.jobId}).from(p.p$).where((0,p.eq)(p.p$.conversationId,a)).orderBy(p.p$.createdAt).limit(500)).map(a=>({id:a.id,role:a.role,content:a.content,jobId:a.jobId}));return dZ({messages:e})}catch(a){return console.error("[listChatAction]",a),d$("db_error","Failed to load chat")}}let gB=g.Ik({conversationId:g.Yj().guid(),message:g.Yj().min(1,"Message is empty").max(2e5)});async function gC(a){try{let b,c=await d_(),d=gB.safeParse(a);if(!d.success)return d$("validation_failed",d.error.issues[0]?.message??"Invalid input");let f=(0,dH.Lf)(),{rootAgentId:g}=await gw(f,c.entityId);if(!g)return d$("no_root_agent","Designate a ROOT agent in Settings first.");if(!dJ._.WORKER_SECRET)return console.error("[sendChatMessageAction] WORKER_SECRET missing — cannot reach runner"),d$("runner_unreachable","Chat backend not configured");try{b=await fetch(`${dJ._.RUNNER_URL}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dJ._.WORKER_SECRET}`},body:JSON.stringify({entityId:c.entityId,agentId:g,conversationId:d.data.conversationId,message:d.data.message})})}catch(a){return console.error("[sendChatMessageAction] runner unreachable:",a),d$("runner_unreachable","Could not reach the chat backend")}let h=await b.json().catch(()=>null);if(!b.ok)return d$("chat_failed",h?.error??"The agent did not reply");return(0,e.revalidatePath)("/chat"),dZ({reply:h?.reply??""})}catch(a){return console.error("[sendChatMessageAction]",a),d$("db_error","Failed to send message")}}async function gD(a){try{let b=await d_();if(!g.Yj().guid().safeParse(a).success)return d$("validation_failed","Invalid job id");let c=(0,dH.Lf)(),[d]=await c.select({status:p.ME.status,result:p.ME.result}).from(p.ME).where((0,p.Uo)((0,p.eq)(p.ME.id,a),(0,p.eq)(p.ME.entityId,b.entityId))).limit(1);if(!d)return d$("not_found","Job not found");let e=(await c.select({agentName:p.X6.name,agentSlug:p.X6.slug,status:p.ME.status}).from(p.ME).leftJoin(p.X6,(0,p.eq)(p.X6.id,p.ME.agentId)).where((0,p.Uo)((0,p.eq)(p.ME.parentJobId,a),(0,p.eq)(p.ME.entityId,b.entityId))).orderBy(p.ME.createdAt)).map(a=>({agentName:a.agentName??a.agentSlug??"agent",status:a.status??"pending"}));return dZ({status:d.status??"pending",result:d.result,children:e})}catch(a){return console.error("[getChatJobStatusAction]",a),d$("db_error","Failed to load job status")}}(0,dY.D)([d1,d2,d3,d4,d5,d6,d7,ea,eb,ec,ed,ee,eh,ei,ej,ek,eo,ep,eq,er,es,et,eu,ev,ew,ey,eA,eB,eC,eD,eE,eF,eH,eI,eK,eL,eN,eO,eP,eQ,eR,eT,eU,eV,eX,eY,eZ,e$,e0,e1,e2,e3,e4,e5,e6,e7,e8,fa,fb,fd,ff,fg,fi,fj,fl,fm,fo,fp,fr,fs,fu,fv,fw,fx,fy,fA,fC,fE,fF,fG,fI,fJ,fK,fL,fN,fO,fQ,fR,fT,fU,fV,fW,fX,fZ,f$,f0,f6,f7,f8,f9,ga,gj,gk,gl,gm,gn,go,gq,gr,gs,gt,gv,gx,gy,gz,gA,gC,gD]),(0,d.A)(d1,"00f1ef002f17a474f7a5a639159f2f208a67ab2fa7",null),(0,d.A)(d2,"407c0c65975bbce8f37884b7f13cbd9fc7d01702a6",null),(0,d.A)(d3,"40397bed6f0cf2b3ba461e8e47ec7d4b6880ea452c",null),(0,d.A)(d4,"40de550eeec76905aec0e7d9e27c6051cf0a1470a9",null),(0,d.A)(d5,"00998b155b03c18d894b6a187414dc00e46d952d9b",null),(0,d.A)(d6,"4004d900812277dfba594d33d54f4bfdb0d3986eda",null),(0,d.A)(d7,"40e6a7206a7a446219e1f72fe24b89fd18ee5f934a",null),(0,d.A)(ea,"00bdc716a17646937e3e8a462f84d00cd07748d79d",null),(0,d.A)(eb,"00d3f492cc13d1b35154112e51b975d90d58cb4c49",null),(0,d.A)(ec,"40579337f2db185bdba19b691873fd80639183b430",null),(0,d.A)(ed,"40ee1dadf791a661179a364ced1053a3313c55a4eb",null),(0,d.A)(ee,"40d912a4ab8fa1fff5a87cd3963ced9894de782dca",null),(0,d.A)(eh,"408df2b11931bbea4429c0a7c374cb7ade9635b895",null),(0,d.A)(ei,"40cc515a6f0f6f3bdb9607287ae9531189c0ba1541",null),(0,d.A)(ej,"70e3d92f9d3f3db7bb5de1894c29d0576420aeee94",null),(0,d.A)(ek,"40224a127742dd27b8bd9a9f77616ee50a4611a1d3",null),(0,d.A)(eo,"70590053974fb747b319578c031c5c846d9e2fc371",null),(0,d.A)(ep,"605f7c75a0f45cae6282b52dcfe1bdf75a30089259",null),(0,d.A)(eq,"706d110d48e1718ed892cc0d5ae420c8d18a6cde6e",null),(0,d.A)(er,"40764e883ec0f0fc9e62e8154b0203023b0fc461b6",null),(0,d.A)(es,"40ebfa73d6ce5a7253441b08f876b0b93adee4c088",null),(0,d.A)(et,"403e6f7012baeb1cecd9d665de6d4a1cc7e52639b5",null),(0,d.A)(eu,"40e0c52dbe75d74f05eb90f5bcc786897231dbd120",null),(0,d.A)(ev,"40187c68935817bc3ca7069ea3ef7f599be2644413",null),(0,d.A)(ew,"401be6c3dc2139cceef264fd9521c8cfd73ae69b6d",null),(0,d.A)(ey,"40b949d58bd22598ed8f044c517eff538334a851c4",null),(0,d.A)(eA,"4075af73aa89f327c28ef069aac4ff7be1e2b63a32",null),(0,d.A)(eB,"404ac94514d8619417640c43b3416a82ac42f252e5",null),(0,d.A)(eC,"40df123f9b04c75f024f545f011643493659139a2b",null),(0,d.A)(eD,"4009043fe3667452d655983efe24a58679ba4a9c5c",null),(0,d.A)(eE,"40691a0da2455c343c08f1395b3001a5dc40b8c2c8",null),(0,d.A)(eF,"60cadb5ce28b559a8f145eec69f118015a83c5022d",null),(0,d.A)(eH,"409d9ec32f7e1c54762a2011af3c146357ca3045f5",null),(0,d.A)(eI,"407f838ed1b5c8e36d9f0c2eaed5a3c3ef94106658",null),(0,d.A)(eK,"40dcd921ca377eaff29d59be1d9bc43007b1e02f1c",null),(0,d.A)(eL,"408872bb8e87536ed63b8d60709ebea31f43f3c5b9",null),(0,d.A)(eN,"6045090ad49d14ab85eab9c1de89827d7afe35aefb",null),(0,d.A)(eO,"40910fd72ca0e8a4e413c0afb4b1cd57b5c2624578",null),(0,d.A)(eP,"40eeb9b47eb311c660cb25084dd9dc26dda27b2bba",null),(0,d.A)(eQ,"40c68523e4e2ba8b528d870b342dec12f542eb2fc5",null),(0,d.A)(eR,"0080ca0ff13028732fdad90d5fbb2c46e10bbef42f",null),(0,d.A)(eT,"4008c000999cf72aefcb5c8821c0acad202099e26d",null),(0,d.A)(eU,"40128f20f2ebad81a526ad80d118b79904c93a3ec1",null),(0,d.A)(eV,"002615fdcb7d91d4b4aeb800e9e203cc2661e1ed50",null),(0,d.A)(eX,"40c045237abd8e76436e9e8325969420a35178193e",null),(0,d.A)(eY,"606749fb478e59a9e4e327a2ff59b70482c1aef5f3",null),(0,d.A)(eZ,"60a6e6cd4b637a67c313c7570fc509b1d67ab4d576",null),(0,d.A)(e$,"40bc8c931f255353d02b3da6c94d343913bf6abb93",null),(0,d.A)(e0,"606f68ac7973f9937b88d803329807fa4ae7c03ef7",null),(0,d.A)(e1,"4014bd701c0f15e956509e9b94a3773aadc29993d8",null),(0,d.A)(e2,"40775b88cd24ee89c2e071391a9f7165c8a8d2b4d4",null),(0,d.A)(e3,"783b8b1ba4b89453f1cf1064c34a8453b8c45c7f7f",null),(0,d.A)(e4,"60a9a3db66df96af1bd3ce53ead612aa36c980fec0",null),(0,d.A)(e5,"70c7a8a1269734b871d26b7d12a6f4049a7202c2ed",null),(0,d.A)(e6,"602640429aa4ac0a169cdf4402a1e8acd3d3732ca7",null),(0,d.A)(e7,"605016142997a33fe2b55107bc8a0400d3411529db",null),(0,d.A)(e8,"4097f6d231fec2cd16168a9412d1b68b03b108fe6a",null),(0,d.A)(fa,"405714e3103acb8a86e8816a240e218d68c7bfe422",null),(0,d.A)(fb,"40de30a334259c82d756d3eb017a4a0d9402d86a91",null),(0,d.A)(fd,"4054e0a82931897c7444f29711df8d4fda90fca470",null),(0,d.A)(ff,"403f1c1da0489dadeb23050c8464c4d6cd873eb68c",null),(0,d.A)(fg,"008308c354a66e185a22d5acd4abaaf2ca409c7b6b",null),(0,d.A)(fi,"4067b8ff4a00c2c92f2464e1cc7503fd9e22837eed",null),(0,d.A)(fj,"0015ae9570da3865f6182796ac321d0c45ba4c11b1",null),(0,d.A)(fl,"4089229c3681af8ee5b66adb4c5d84e2fdb41eae0c",null),(0,d.A)(fm,"40b125044576bba9d9b7d3d50455d2bfeaf7d8d5c5",null),(0,d.A)(fo,"40b3d13f005d24eea4365d4a94bc32903b9b6c8eca",null),(0,d.A)(fp,"405f3f64d0928dbf53df29e0f06104453025aa12fc",null),(0,d.A)(fr,"40bdd006a671068473e215a769137c1ca068a3ddc3",null),(0,d.A)(fs,"4036c45eb854bbde9ee06cf9db8d3754b3a08030de",null),(0,d.A)(fu,"40b0dab57a7e20d815a98e4317d947938102ca135b",null),(0,d.A)(fv,"403f71242c58eb91cbd4e5daef29d6bee071ec7e65",null),(0,d.A)(fw,"40f90dbe85669e942896299b5163c991a0d5a83074",null),(0,d.A)(fx,"40da2054f7dd1ff77d7eecb4a99030f358b09de707",null),(0,d.A)(fy,"40fa2dd4614f470d5da133f1c77a10d6774e3ab5b6",null),(0,d.A)(fA,"40a4519096db6470bb8434ac9e0b4b0d613af322bf",null),(0,d.A)(fC,"4099860aad72be08a9a28709f8a1ff32eb1736bccd",null),(0,d.A)(fE,"401d9e22abc121ee3854dfdd6f8b3881807361c111",null),(0,d.A)(fF,"00ee92d4822efcc12364fd6f2b3fe4f03cb3e28c6e",null),(0,d.A)(fG,"008f846ebcf095d9e7e0368c21f0eaa8f9d602c0b1",null),(0,d.A)(fI,"00f59a0a74f98b5dec9ee1b4919a0a36e24ddccc97",null),(0,d.A)(fJ,"00b078241e200d030c387c79c4ab253df9c0fd19be",null),(0,d.A)(fK,"00f4b3acc107dcaff1c41e8f9d5b8145ac214f6379",null),(0,d.A)(fL,"004e8a15bf57c7045676e9ed99ef1d52c4a2e5c8d3",null),(0,d.A)(fN,"008359dc21a48b756aebca6da88725f8d096c7486d",null),(0,d.A)(fO,"000751b498462554b2253bd39a508b194ca2bcc9fb",null),(0,d.A)(fQ,"407703881b3cf4b39e3edb49fca9ee78486a4bfcb0",null),(0,d.A)(fR,"409319a7daeda40da84e77b6cc2ee79b1fa59a9efe",null),(0,d.A)(fT,"40dafedcea4cd0ff41c2249fe35a33e569de082bdf",null),(0,d.A)(fU,"4003c74e787eefda9053935e5d1f775934854ae3d5",null),(0,d.A)(fV,"40efec73e82f9575e8c7b168dfd02783dc30fe5542",null),(0,d.A)(fW,"4041595d19f3f1f860fb51f915107b308f211e7516",null),(0,d.A)(fX,"0006e0dbfdc234858c268c627610f0329c6c8fdd31",null),(0,d.A)(fZ,"40992882c713d264ddf42d592c84758ef5aebbaab4",null),(0,d.A)(f$,"00d33931c0c5dbdce2c7cee39806c32bf98e20f8e3",null),(0,d.A)(f0,"402bf7efe6704b07e40114c7156ffbdf3f36848af8",null),(0,d.A)(f6,"00fbc0f1e65e50d169bbf9ac697d5562cd1c92f5f1",null),(0,d.A)(f7,"40b1e80a920ce475113b5fbce89c2494f0599c0318",null),(0,d.A)(f8,"40ef217aa9916f074c45a6a7ebe489ade1058eb9ca",null),(0,d.A)(f9,"607a4e0fe270514e93af4dfa107b07c6e3fc451d55",null),(0,d.A)(ga,"40a92bc888d4c445e1f60ac74f0471b491e956600a",null),(0,d.A)(gj,"40029d917e83102fc3fe53281772f0f4a67f3c8121",null),(0,d.A)(gk,"40ae693984abe2a327713b38a1c552f6df8ea1678b",null),(0,d.A)(gl,"4040cdc83e064cf466b5651d61a94b596e4b1741d8",null),(0,d.A)(gm,"00759604b38bbd9c787808baa84fcb4704e68d1c9f",null),(0,d.A)(gn,"40d79a9807a2a1bf294e36679f7b21e569893ff1ed",null),(0,d.A)(go,"00b9e853a3b08e82eca38f7a88cdc3ace7462ac143",null),(0,d.A)(gq,"404ce25817920f99b2ecef8b96edb7521996e7cbb7",null),(0,d.A)(gr,"00ac1f9144714e1b471c7d1c2d94d5024eb7f33814",null),(0,d.A)(gs,"78f711f46e63ddd4787714f658f99b4aa34eb4c229",null),(0,d.A)(gt,"008792842917a0ae82f0ebca55cd41388af5c575ca",null),(0,d.A)(gv,"4002675d03f3a3ae308ea587d0af754f6ab2e91f03",null),(0,d.A)(gx,"00d7178e544dccd4c780f71d3f8c6afa8a6aac8b86",null),(0,d.A)(gy,"0027ed0d23cffc13987606629752e123c0419f928c",null),(0,d.A)(gz,"408767e7dac33bd3ed8d4ab7a476d8cf70f18647f1",null),(0,d.A)(gA,"40d1e415eaf83dc3c586859635bfd0b4270a5004dd",null),(0,d.A)(gC,"40162a1eb76527101e735f9d5484ad419dadd50c09",null),(0,d.A)(gD,"40615f213887f9542e1d99817aa9e634dee85d1517",null)},63894:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,16385,23))},69371:(a,b,c)=>{Promise.resolve().then(c.bind(c,81955)),Promise.resolve().then(c.bind(c,62952)),Promise.resolve().then(c.bind(c,97173)),Promise.resolve().then(c.bind(c,93690))},69679:(a,b,c)=>{"use strict";c.d(b,{A:()=>f,S:()=>e});var d=c(10476);let e=["\uD83D\uDDC2️","\uD83C\uDFE0","\uD83D\uDCBC","\uD83D\uDE80","\uD83E\uDDEA","\uD83C\uDFA8","\uD83D\uDCCA","\uD83D\uDEE0️","\uD83C\uDF10","⚡","\uD83E\uDD16","\uD83D\uDCE6"];function f({value:a,onChange:b,disabled:c}){return(0,d.jsx)("div",{className:"flex flex-wrap gap-1",children:e.map(e=>{let f=a===e;return(0,d.jsx)("button",{type:"button",disabled:c,"aria-pressed":f,onClick:()=>b(e),className:`flex h-8 w-8 items-center justify-center rounded-md border text-[16px] leading-none transition-colors disabled:opacity-50 ${f?"border-ink bg-hover-2":"border-rule-2 hover:bg-hover"}`,children:e},e)})})}},70577:a=>{function b(a){var b=Error("Cannot find module '"+a+"'");throw b.code="MODULE_NOT_FOUND",b}b.keys=()=>[],b.resolve=b,b.id=70577,a.exports=b},70615:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>j,metadata:()=>i});var d=c(99386),e=c(50277),f=c.n(e),g=c(80356),h=c.n(g);c(54620);let i={title:"Nodal-Agents",description:"Multi-agent platform"};function j({children:a}){return(0,d.jsxs)("html",{lang:"en",className:`${f().variable} ${h().variable}`,suppressHydrationWarning:!0,children:[(0,d.jsx)("head",{children:(0,d.jsx)("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('nodal.theme');if(t!=='dark'&&t!=='light')t='light';document.documentElement.setAttribute('data-theme',t);}catch(e){document.documentElement.setAttribute('data-theme','light');}})();"}})}),(0,d.jsx)("body",{children:a})]})}},70953:()=>{},74708:(a,b,c)=>{"use strict";c.d(b,{A:()=>g});var d=c(10476),e=c(64565),f=c(90424);function g({open:a,onClose:b,title:c,children:h,className:i=""}){let[j,k]=(0,e.useState)(!1);return a&&j?(0,f.createPortal)((0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"fixed inset-0 z-40 bg-black/60 animate-[fadeIn_150ms_ease]",onClick:b,"aria-hidden":"true"}),(0,d.jsx)("div",{role:"dialog","aria-modal":"true",className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:(0,d.jsxs)("div",{className:`pointer-events-auto w-full max-w-lg max-h-[90vh] overflow-y-auto bg-paper border border-rule-2 rounded-xl shadow-2xl animate-[scaleIn_150ms_ease] ${i}`,children:[void 0!==c&&(0,d.jsxs)("div",{className:"flex items-center justify-between gap-2 px-6 pt-5 pb-4 border-b border-rule-2",children:[(0,d.jsx)("h3",{className:"text-sm font-semibold text-ink",children:c}),(0,d.jsx)("button",{type:"button",onClick:b,"aria-label":"Close",className:"text-ink-3 hover:text-ink transition-colors",children:"✕"})]}),(0,d.jsx)("div",{className:"p-6 pt-5",children:h})]})})]}),document.body):null}},77386:(a,b,c)=>{Promise.resolve().then(c.t.bind(c,67448,23))},79987:(a,b,c)=>{Promise.resolve().then(c.bind(c,6833)),Promise.resolve().then(c.bind(c,89460)),Promise.resolve().then(c.bind(c,28659)),Promise.resolve().then(c.bind(c,57712))},81955:(a,b,c)=>{"use strict";c.d(b,{ApprovalsProvider:()=>e});var d=c(49554);let e=(0,d.registerClientReference)(function(){throw Error("Attempted to call ApprovalsProvider() from the server but ApprovalsProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ApprovalsProvider.tsx","ApprovalsProvider");(0,d.registerClientReference)(function(){throw Error("Attempted to call useApprovals() from the server but useApprovals is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ApprovalsProvider.tsx","useApprovals")},84327:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\app\\\\error.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\app\\error.tsx","default")},84807:(a,b,c)=>{"use strict";c.d(b,{C:()=>e});var d=c(47092);let e=(0,d.createServerReference)("405714e3103acb8a86e8816a240e218d68c7bfe422",d.callServer,void 0,d.findSourceMapURL,"resolveApprovalAction")},89460:(a,b,c)=>{"use strict";c.d(b,{default:()=>_});var d=c(10476),e=c(64565),f=c(12418),g=c(77568),h=c(3521),i=c(82271),j=c(13028),k=c(83588),l=c(92607),m=c(33478),n=c(1282),o=c(73836),p=c(11145),q=c(66442),r=c(63473),s=c(84132),t=c(64945),u=c(55234),v=c(93720),w=c(11745),x=c(4870);function y(){return(0,d.jsx)("div",{className:"px-4 pb-3.5",children:(0,d.jsxs)("div",{className:"flex items-center gap-2 text-[16px] font-medium leading-none tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-[22px] w-[22px] items-center justify-center rounded-md bg-ink text-[12px] font-semibold leading-none tracking-[0.04em] text-canvas font-mono",children:"N"}),(0,d.jsx)("span",{children:"Nodal-Agents"})]})})}function z({children:a}){return(0,d.jsx)("div",{className:"px-[22px] pt-4 pb-1.5 font-mono text-[11px] uppercase tracking-[0.14em] text-ink-4 lg:pt-3.5 lg:pb-1 lg:text-[11px]",children:a})}var A=c(88831),B=c.n(A);let C={agent:"bg-agent-vivid",skill:"bg-skill-vivid",conn:"bg-conn-vivid"};function D({href:a,label:b,icon:c,dot:e,count:g,pill:h,isActive:i}){let j=(0,f.usePathname)(),k=i??(j===a||j.startsWith(a+"/"));return(0,d.jsxs)(B(),{href:a,className:`group mx-3 flex h-12 items-center gap-3 rounded-xl px-3 text-[16px] transition-colors lg:h-[30px] lg:gap-2.5 lg:rounded-lg lg:px-3 lg:text-[13px] lg:leading-none ${k?"bg-paper text-ink font-medium shadow-[0_1px_2px_rgba(0,0,0,0.04)]":"text-ink-2 hover:bg-hover"}`,children:[e?(0,d.jsxs)("span",{className:"relative flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5",children:[(0,d.jsx)("span",{className:`lg:hidden ${k?"text-ink":"text-ink-3 group-hover:text-ink-2"}`,children:c}),(0,d.jsx)("span",{className:`absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-sidebar lg:static lg:h-2 lg:w-2 lg:ring-0 ${C[e]}`})]}):(0,d.jsx)("span",{className:`flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5 ${k?"text-ink":"text-ink-3 group-hover:text-ink-2"}`,children:c}),(0,d.jsx)("span",{className:"flex-1 truncate",children:b}),void 0!==h?(0,d.jsx)("span",{className:"rounded-full bg-err/12 px-2 py-0.5 text-[13px] font-medium text-err lg:px-1.5 lg:py-0 lg:text-[11px]",children:h>99?"99+":h}):void 0!==g&&(0,d.jsx)("span",{className:"font-mono text-[13px] tracking-[0.02em] text-ink-4 lg:text-[11px]",children:g})]})}var E=c(44100);function F({runningAgents:a,throughput:b,fill:c=.36}){if(void 0===a)return null;let e=100*Math.max(0,Math.min(1,c));return(0,d.jsxs)("div",{className:"mx-3 mt-2.5 rounded-[10px] border border-rule-2 bg-paper px-3 pt-2.5 pb-3",children:[(0,d.jsxs)("div",{className:"flex items-center gap-1.5 font-mono text-[11px] uppercase leading-none tracking-[0.14em] text-ink-3",children:[(0,d.jsx)(E.A,{variant:"lime"}),"Live"]}),(0,d.jsxs)("div",{className:"mt-1.5 text-[13px] leading-[1.35] text-ink-2",children:[(0,d.jsxs)("b",{className:"font-semibold text-ink",children:[a," agents"]}),b?` running \xb7 ${b}`:" running"]}),(0,d.jsx)("div",{className:"mt-2.5 h-[3px] overflow-hidden rounded-[2px] bg-black/[0.06] dark:bg-white/[0.06]",children:(0,d.jsx)("i",{className:"block h-full bg-agent-vivid",style:{width:`${e}%`}})})]})}var G=c(48082),H=c(45616),I=c(14199),J=c(9376),K=c(74708),L=c(47092);L.callServer,L.findSourceMapURL;let M="nodal-agents update";function N(){let[a,b]=(0,e.useState)(null),[c,f]=(0,e.useState)(!1);if(!a?.current)return null;let{current:g,latest:h,updateAvailable:i}=a;async function j(){try{await navigator.clipboard.writeText(M),G.oR.success("Command copied")}catch{G.oR.error("Could not copy")}}return(0,d.jsxs)("div",{className:"mx-2 mt-1",children:[i?(0,d.jsxs)("button",{type:"button",onClick:()=>f(!0),className:"flex w-full items-center gap-2 rounded-lg border border-agent-vivid/40 bg-agent-vivid/10 px-2.5 py-1.5 text-left transition-colors hover:bg-agent-vivid/20",children:[(0,d.jsx)(H.S,{size:14,weight:"bold",className:"shrink-0 text-ink-2"}),(0,d.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,d.jsx)("span",{className:"block text-[11.5px] font-medium leading-tight text-ink",children:"Update available"}),(0,d.jsxs)("span",{className:"block font-mono text-[10px] leading-tight text-ink-3",children:["v",g," → v",h]})]})]}):(0,d.jsxs)("div",{className:"flex items-center gap-1.5 px-2.5 py-1 text-ink-4",children:[(0,d.jsx)(I.r,{size:12,className:"shrink-0"}),(0,d.jsxs)("span",{className:"font-mono text-[10.5px]",children:["Nodal v",g]})]}),(0,d.jsx)(K.A,{open:c,onClose:()=>f(!1),title:"Update Nodal-Agents",children:(0,d.jsxs)("div",{className:"space-y-4",children:[(0,d.jsxs)("p",{className:"text-[13px] leading-relaxed text-ink-2",children:["A new version is available — ",(0,d.jsxs)("span",{className:"font-mono text-ink-3",children:["v",g]})," →"," ",(0,d.jsxs)("span",{className:"font-mono font-medium text-ink",children:["v",h]}),". Run this in your terminal, then restart Nodal-Agents:"]}),(0,d.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-rule-2 bg-hover px-3 py-2.5",children:[(0,d.jsx)("code",{className:"flex-1 font-mono text-[13px] text-ink",children:M}),(0,d.jsxs)("button",{type:"button",onClick:j,className:"inline-flex h-[28px] shrink-0 items-center gap-1.5 rounded-md border border-rule-2 bg-paper px-2.5 text-[12px] font-medium text-ink-3 transition-colors hover:text-ink",children:[(0,d.jsx)(J.Q,{size:13})," Copy"]})]}),(0,d.jsxs)("p",{className:"text-[12px] leading-relaxed text-ink-4",children:["On macOS/Linux, prefix with ",(0,d.jsx)("span",{className:"font-mono",children:"sudo"})," if the global install needs elevated permissions."]})]})})]})}var O=c(23586),P=c(42199);function Q({fleets:a,activeId:b,disabled:c,onChange:f,onNewWorkspace:g}){let[h,i]=(0,e.useState)(!1),j=(0,e.useRef)(null),k=a.find(a=>a.id===b)??a[0];return k?(0,d.jsxs)("div",{ref:j,className:"relative mx-3.5 mt-3.5 mb-1",children:[(0,d.jsxs)("button",{type:"button",onClick:()=>!c&&i(a=>!a),"aria-haspopup":"listbox","aria-expanded":h,"aria-disabled":c||void 0,className:`flex h-12 w-full items-center gap-3 rounded-xl border border-rule-2 bg-paper px-3 text-[15px] leading-none text-ink lg:h-[38px] lg:gap-2.5 lg:rounded-[9px] lg:px-2.5 lg:text-[13px] ${c?"cursor-default":"cursor-pointer hover:bg-hover-2/40"}`,children:[(0,d.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md font-mono text-[12px] font-semibold leading-none tracking-[0.04em] text-[#0a0a0a] lg:h-[22px] lg:w-[22px] lg:rounded-[5px] lg:text-[10.5px]",style:{background:k.color},children:k.icon??k.tag.slice(0,2)}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate text-left text-[15px] font-medium text-ink lg:text-[12.5px]",children:k.name}),!c&&(0,d.jsx)(O.a,{size:12,className:"h-4 w-4 shrink-0 text-ink-3 lg:h-3 lg:w-3"})]}),h&&!c&&(0,d.jsxs)("div",{role:"listbox",className:"absolute inset-x-0 top-[calc(100%+6px)] z-30 rounded-[9px] border border-rule-2 bg-paper p-1.5 shadow-[0_12px_32px_rgba(0,0,0,0.10)]",children:[a.map(a=>{let c=a.id===b;return(0,d.jsxs)("div",{role:"option","aria-selected":c,onClick:()=>{f?.(a.id),i(!1)},className:`flex cursor-pointer items-center gap-3 rounded-lg px-2.5 py-2.5 text-[15px] leading-[1.2] text-ink-2 hover:bg-hover lg:gap-2.5 lg:rounded-md lg:px-2 lg:py-1.5 lg:text-[12.5px] ${c?"bg-hover-2":""}`,children:[(0,d.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md font-mono text-[12px] font-semibold leading-none tracking-[0.04em] text-[#0a0a0a] lg:h-5 lg:w-5 lg:rounded-[5px] lg:text-[10px]",style:{background:a.color},children:a.icon??a.tag.slice(0,2)}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium text-ink",children:a.name}),(0,d.jsx)(P.J,{size:12,weight:"bold",className:`h-4 w-4 text-ink lg:h-3 lg:w-3 ${c?"opacity-100":"opacity-0"}`})]},a.id)}),g&&(0,d.jsxs)("button",{type:"button",onClick:()=>{i(!1),g()},className:"mt-1 flex w-full items-center gap-3 rounded-lg border-t border-rule px-2.5 py-2.5 text-[15px] font-medium text-ink-3 transition-colors hover:bg-hover hover:text-ink-2 lg:gap-2 lg:rounded-md lg:px-2 lg:py-1.5 lg:text-[12px]",children:[(0,d.jsx)("span",{className:"flex h-5 w-5 items-center justify-center rounded text-[16px] leading-none lg:h-4 lg:w-4 lg:text-[12px]",children:"+"}),"New workspace"]})]})]}):null}var R=c(69679),S=c(36143),T=c(4112);let U=["#d4ff2e","#74b9ff","#a29bfe","#fd79a8","#55efc4","#fdcb6e","#e17055","#6c5ce7"];function V(a){return{id:a.id,name:a.name,tag:a.name.replace(/[^a-zA-Z0-9]/g,"").slice(0,3).toUpperCase()||"WS",color:function(a){let b=0;for(let c=0;c<a.length;c+=1)b=31*b+a.charCodeAt(c)>>>0;return U[b%U.length]??U[0]}(a.slug),icon:a.icon??void 0}}function W({workspaces:a}){let b=(0,f.useRouter)(),[c,g]=(0,e.useTransition)(),[h,i]=(0,e.useTransition)(),[j,k]=(0,e.useState)(!1),[l,m]=(0,e.useState)(""),[n,o]=(0,e.useState)(R.S[0]),p=(0,e.useRef)(null),q=a.map(V),r=a.find(a=>a.active),s=r?.id??q[0]?.id??"";return(0,d.jsxs)("div",{children:[(0,d.jsx)(Q,{fleets:q,activeId:s,onChange:function(a){a===s||c||g(async()=>{let c=await (0,S.W)({id:a});c.ok?b.refresh():G.oR.error(c.message)})},disabled:c||0===q.length,onNewWorkspace:function(){k(!0),m(""),o(R.S[0]),requestAnimationFrame(()=>p.current?.focus())}}),j&&(0,d.jsxs)("form",{onSubmit:function(a){a.preventDefault();let c=l.trim();c&&i(async()=>{let a=await (0,T.O)({name:c,icon:n});if(!a.ok)return void G.oR.error(a.message);let d=await (0,S.W)({id:a.data.id});d.ok?(k(!1),m(""),G.oR.success(`Workspace "${c}" created`),b.refresh()):G.oR.error(d.message)})},className:"mx-3.5 mt-1 rounded-[9px] border border-rule-2 bg-paper p-2.5",children:[(0,d.jsx)("p",{className:"mb-1.5 font-mono text-[11px] uppercase tracking-[0.1em] text-ink-4",children:"New workspace"}),(0,d.jsx)("div",{className:"mb-2",children:(0,d.jsx)(R.A,{value:n,onChange:o,disabled:h})}),(0,d.jsxs)("div",{className:"flex gap-1.5",children:[(0,d.jsx)("input",{ref:p,type:"text",value:l,onChange:a=>m(a.target.value),placeholder:"Name…",maxLength:60,disabled:h,className:"min-w-0 flex-1 rounded-md border border-rule bg-canvas px-2.5 py-1.5 text-[13px] text-ink placeholder:text-ink-4 focus:border-ink-3 focus:outline-none disabled:opacity-50"}),(0,d.jsx)("button",{type:"submit",disabled:h||!l.trim(),className:"shrink-0 rounded-md bg-ink px-3 py-1.5 text-[13px] font-medium text-canvas hover:brightness-90 disabled:cursor-not-allowed disabled:opacity-50",children:h?"…":"Create"}),(0,d.jsx)("button",{type:"button",onClick:()=>k(!1),disabled:h,className:"shrink-0 rounded-md border border-rule px-2.5 py-1.5 text-[13px] text-ink-3 hover:border-rule-2 hover:text-ink-2 disabled:opacity-50",children:"✕"})]})]})]})}var X=c(43136),Y=c(35245),Z=c(6833);let $=[{section:"Overview",items:[{href:"/",label:"Home",icon:g.t},{href:"/chat",label:"Chat",icon:h.x},{href:"/jobs",label:"Runs",icon:i.T},{href:"/llm-providers",label:"LLM Providers",icon:j.R}]},{section:"Build",items:[{href:"/agents",label:"Agents",icon:k.n,dot:"agent"},{href:"/skills",label:"Skills",icon:l.f,dot:"skill"},{href:"/learned-skills",label:"Learned Skills",icon:m.g},{href:"/connectors",label:"API Connectors",icon:n.F,dot:"conn"},{href:"/mcp",label:"MCP Connectors",icon:o.X,dot:"conn"},{href:"/credentials",label:"Credentials",icon:p.U},{href:"/memories",label:"Memory",icon:q.j}]},{section:"Operate",items:[{href:"/automations",label:"Automation",icon:r.E},{href:"/approvals",label:"Approvals",icon:s.o},{href:"/logs",label:"Logs",icon:t.m}]},{section:"Workspace",items:[{href:"https://discord.gg/7UZsvZPgU",label:"Join Discord",external:!0},{href:"/settings",label:"Settings",icon:u._}]}];function _({workspaces:a,userMenu:b}){let c=(0,f.usePathname)(),[g,h]=(0,e.useState)(!1),{pending:i}=(0,Z.e)(),j=i.length;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("header",{className:"fixed top-0 right-0 left-0 z-40 flex h-16 items-center gap-1 border-b border-rule-2 bg-sidebar px-2 lg:hidden",children:[(0,d.jsx)("button",{type:"button",onClick:()=>h(!0),className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl text-ink-2 transition-colors hover:bg-hover hover:text-ink active:bg-hover","aria-label":"Open menu","aria-controls":"primary-nav","aria-expanded":g,children:(0,d.jsx)(v.B,{size:26})}),(0,d.jsxs)("div",{className:"flex min-w-0 items-center gap-2 pl-1 text-[15px] font-medium tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-md bg-ink font-mono text-[11px] font-semibold text-canvas",children:"N"}),(0,d.jsx)("span",{className:"truncate",children:"Nodal-Agents"})]}),(0,d.jsx)("div",{className:"flex-1"}),(0,d.jsxs)("div",{className:"flex items-center gap-1",children:[(0,d.jsx)(Y.default,{}),(0,d.jsx)(X.default,{})]})]}),(0,d.jsxs)("aside",{id:"primary-nav","aria-label":"Main navigation",className:`fixed top-0 left-0 z-50 flex h-full w-full flex-col border-r border-rule-2 bg-sidebar pt-4 pb-3 transition-transform duration-200 ease-out lg:z-40 lg:w-[244px] lg:translate-x-0 ${g?"translate-x-0":"-translate-x-full"}`,children:[(0,d.jsxs)("div",{className:"flex items-center justify-between px-4 pb-1 lg:hidden",children:[(0,d.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-[16px] font-medium tracking-[-0.005em] text-ink",children:[(0,d.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-ink font-mono text-[12px] font-semibold text-canvas",children:"N"}),(0,d.jsx)("span",{className:"truncate",children:"Nodal-Agents"})]}),(0,d.jsx)("button",{type:"button",onClick:()=>h(!1),className:"-mr-2 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl text-ink-2 transition-colors hover:bg-hover hover:text-ink active:bg-hover","aria-label":"Close menu",children:(0,d.jsx)(w.X,{size:24})})]}),(0,d.jsx)("div",{className:"hidden lg:block",children:(0,d.jsx)(y,{})}),(0,d.jsx)(W,{workspaces:a??[]}),(0,d.jsx)("nav",{className:"flex flex-1 flex-col overflow-y-auto py-1.5",children:$.map((a,b)=>(0,d.jsxs)("div",{children:[a.section&&(0,d.jsx)(z,{children:a.section}),a.items.map(a=>{var b;return a.external?(0,d.jsxs)("a",{href:a.href,target:"_blank",rel:"noopener noreferrer",className:"group mx-3 flex h-12 items-center gap-3 rounded-xl bg-[#5865F2] px-3 text-[15px] font-medium text-white transition-[filter] hover:brightness-110 lg:h-[30px] lg:gap-2.5 lg:rounded-lg lg:px-3 lg:text-[12.5px] lg:leading-none",children:[(0,d.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center lg:h-3.5 lg:w-3.5",children:(0,d.jsx)(x.B,{size:20,weight:"bold",className:"h-5 w-5 lg:h-3.5 lg:w-3.5"})}),(0,d.jsx)("span",{className:"flex-1 truncate",children:a.label})]},a.href):(0,d.jsx)(D,{href:a.href,label:a.label,icon:a.icon?(0,d.jsx)(a.icon,{size:20,className:"h-5 w-5 lg:h-3.5 lg:w-3.5"}):void 0,dot:a.dot,count:"/approvals"===a.href?void 0:a.count,pill:"/approvals"===a.href&&j>0?j:void 0,isActive:(b=a.href,"/"===b?"/"===c:c===b||c.startsWith(b+"/"))},a.href)})]},b))}),(0,d.jsx)(N,{}),(0,d.jsx)(F,{runningAgents:void 0}),b&&(0,d.jsx)("div",{className:"mt-2 border-t border-rule-2 px-3 pt-3","data-testid":"user-menu",children:b})]})]})}},93690:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\ui\\\\ThemedToaster.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\ui\\ThemedToaster.tsx","default")},96591:(a,b,c)=>{"use strict";c.d(b,{ZH:()=>d.ZH,ip:()=>d.R3});var d=c(98648)},97173:(a,b,c)=>{"use strict";c.d(b,{default:()=>d});let d=(0,c(49554).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\APPS\\\\NodalAI\\\\apps\\\\web\\\\src\\\\components\\\\SignOutButton.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\APPS\\NodalAI\\apps\\web\\src\\components\\SignOutButton.tsx","default")},99740:(a,b,c)=>{"use strict";c.d(b,{ApifyApiError:()=>d,G:()=>e});class d extends Error{constructor(a,b,c){super(b),this.name="ApifyApiError",this.code=a,this.status=c}}function e(a){if(a instanceof d)return a;if(null!==a&&"object"==typeof a&&"statusCode"in a&&"number"==typeof a.statusCode){let c,e=a.message??`Apify API error ${a.statusCode}`;var b=a.statusCode;switch(!0){case 401===b:c="apify_unauthorized";break;case 403===b:c="apify_forbidden";break;case 404===b:c="apify_not_found";break;case 422===b:c="apify_validation_error";break;case 429===b:c="apify_rate_limited";break;case b>=500:c="apify_transient";break;default:c="apify_client_error"}return new d(c,e,b)}return a instanceof Error?new d("apify_unknown",a.message):new d("apify_unknown",String(a))}}};