limixbot 0.3.132 → 0.3.133

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 (126) hide show
  1. package/dist/assets/{ActivityPanel-DiwStkWs.js → ActivityPanel-BTszBP4a.js} +1 -1
  2. package/dist/assets/App-B2fBpoRZ.js +250 -0
  3. package/dist/assets/{AppEventEditor-DVCVuXBO.js → AppEventEditor-CDO2rLAR.js} +1 -1
  4. package/dist/assets/{BotSettingsDialog-BpehLBV9.js → BotSettingsDialog-bwIEtMBP.js} +7 -7
  5. package/dist/assets/{BrowserPanel-BzKdGoFi.js → BrowserPanel-Cm4lK77e.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-DPsmibqG.js → BrowserProfilesManager-zGt-sq4k.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-BP9kk0Nk.js → CloudAddDialog-Bhz32gRM.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-C4UvAvXI.js → ComputerFilesPane-BC49N1Pm.js} +1 -1
  9. package/dist/assets/{ComputerPanel-CRIkNjX8.js → ComputerPanel-B5BJuUqm.js} +2 -2
  10. package/dist/assets/{DataPanel-C0K7tilO.js → DataPanel-D-zD8ngK.js} +1 -1
  11. package/dist/assets/{DesktopViewer-Cb9PL6v1.js → DesktopViewer-CgTlC2ON.js} +1 -1
  12. package/dist/assets/{GrokMoveDialog-B01fVBSp.js → GrokMoveDialog-Diktcl5X.js} +1 -1
  13. package/dist/assets/{InspectorPanel-B-vvtU5x.js → InspectorPanel-Dzl7wwRq.js} +1 -1
  14. package/dist/assets/{KeyboardShortcutsModal-xOYi4svn.js → KeyboardShortcutsModal-Bo7yVUTs.js} +1 -1
  15. package/dist/assets/{LimixResizeHandles-R0QGH2Cb.js → LimixResizeHandles-Bdcz_w8I.js} +1 -1
  16. package/dist/assets/{LiveDesktop-lBNaS0yO.js → LiveDesktop-qk7oOKR-.js} +1 -1
  17. package/dist/assets/{LocalVmWorkspace-ySsF6Z_A.js → LocalVmWorkspace-B7YaXgti.js} +1 -1
  18. package/dist/assets/{MacLocalControl-CHaSM0EU.js → MacLocalControl-YCjPm4U3.js} +1 -1
  19. package/dist/assets/{MarkdownFilePreview-Do6qCVxE.js → MarkdownFilePreview-uvNI77v4.js} +1 -1
  20. package/dist/assets/{MenuMotion-owWIcamS.js → MenuMotion-D8l5zOOH.js} +1 -1
  21. package/dist/assets/{NewBotDialog-CkWIeY-5.js → NewBotDialog-veYkUiA5.js} +1 -1
  22. package/dist/assets/{PhoneAppDialog-C354Hfye.js → PhoneAppDialog-CkE9M2PT.js} +1 -1
  23. package/dist/assets/{PlacesRail-BxdV2GDQ.js → PlacesRail-B0T5a390.js} +1 -1
  24. package/dist/assets/{PluginsPanel-B9O8_zcN.js → PluginsPanel-BSv-aWR7.js} +1 -1
  25. package/dist/assets/{ProIntroduction-D4oWKj80.js → ProIntroduction-BJMwoQGa.js} +1 -1
  26. package/dist/assets/{RemoteAgentSettingsPanel-CNI8se4s.js → RemoteAgentSettingsPanel-Dkaxe7IA.js} +1 -1
  27. package/dist/assets/{RoomPanel-DS45UqNT.js → RoomPanel-BIXVLWNZ.js} +1 -1
  28. package/dist/assets/{RoutinesPage-CFNBHcP6.js → RoutinesPage-B-QJRpZi.js} +2 -2
  29. package/dist/assets/SettingsModal-BtRFqxwn.js +20 -0
  30. package/dist/assets/{ShareTeamDialog-eDudYPOc.js → ShareTeamDialog-D3Ea5oSB.js} +1 -1
  31. package/dist/assets/{SignedInSites-kt2vOncY.js → SignedInSites-CPLPNDp5.js} +1 -1
  32. package/dist/assets/{TeamLibraryPanel-De7Bc42A.js → TeamLibraryPanel-D_pKnj54.js} +1 -1
  33. package/dist/assets/{TeamMapPage-Dq64Pir7.js → TeamMapPage-CBV2HmaF.js} +1 -1
  34. package/dist/assets/{TriggersPage-BmNRyndU.js → TriggersPage-C9FIxQGD.js} +1 -1
  35. package/dist/assets/{VisibilitySection-DdRD7jV_.js → VisibilitySection-B0z1XJD4.js} +1 -1
  36. package/dist/assets/{WebhookTrigger-BwkfTcft.js → WebhookTrigger-C7qvE8eC.js} +1 -1
  37. package/dist/assets/{WorksOnGrid-nHuBr3Uu.js → WorksOnGrid-BOLs3g9Y.js} +1 -1
  38. package/dist/assets/{abnfDiagram-YUKMZFIV-vvJbRPlq.js → abnfDiagram-YUKMZFIV-CBc7oFEe.js} +1 -1
  39. package/dist/assets/{activity-D26W1wR5.js → activity-BVpu0XkG.js} +1 -1
  40. package/dist/assets/{architectureDiagram-47P4ROYG-BxqUvVUX.js → architectureDiagram-47P4ROYG-B5jJZs7S.js} +1 -1
  41. package/dist/assets/{blockDiagram-E7TT5TSB-DDe2YxQP.js → blockDiagram-E7TT5TSB-DAjxXILv.js} +1 -1
  42. package/dist/assets/{c4Diagram-CRA5TL53-OdUvGZP-.js → c4Diagram-CRA5TL53-KWoy72TL.js} +1 -1
  43. package/dist/assets/{calendar-days-OEtSVrLe.js → calendar-days-DNA-E4Np.js} +1 -1
  44. package/dist/assets/channel-q-lG3psP.js +1 -0
  45. package/dist/assets/{chunk-2Q5K7J3B-DpnJlpzb.js → chunk-2Q5K7J3B-D3Ycc8P6.js} +1 -1
  46. package/dist/assets/{chunk-5VM5RSS4-C5UgOu8-.js → chunk-5VM5RSS4-C7mfSQVV.js} +1 -1
  47. package/dist/assets/{chunk-7TKQ45FW-Dv-gctKP.js → chunk-7TKQ45FW-BKvAYNH2.js} +1 -1
  48. package/dist/assets/{chunk-AW2ZBBNX-mehzuNgt.js → chunk-AW2ZBBNX-Ca8gRTzc.js} +1 -1
  49. package/dist/assets/{chunk-FVRAUYC3-6bArILty.js → chunk-FVRAUYC3-Bzkks_DT.js} +2 -2
  50. package/dist/assets/{chunk-HTAEGDNF-0w6XIlls.js → chunk-HTAEGDNF-Zo7ZYlx6.js} +1 -1
  51. package/dist/assets/{chunk-JWPE2WC7-DaZro178.js → chunk-JWPE2WC7-DuQPO5Rt.js} +1 -1
  52. package/dist/assets/{chunk-KQW6MTUR-CqA51RiN.js → chunk-KQW6MTUR-C3yGOwbc.js} +1 -1
  53. package/dist/assets/{chunk-XXDRQBXY-DPZH_wOz.js → chunk-XXDRQBXY-Dza0vL4n.js} +1 -1
  54. package/dist/assets/{classDiagram-v2-K4WV4PDN-Dgn2w_U2.js → classDiagram-v2-K4WV4PDN-DTtDRSzj.js} +1 -1
  55. package/dist/assets/{coins-D0EwvaZf.js → coins-Bn14rFjr.js} +1 -1
  56. package/dist/assets/{core-rawcXyep.js → core-CGuF_Hr1.js} +1 -1
  57. package/dist/assets/{cose-bilkent-JH36ORCC-B9lVmBnW.js → cose-bilkent-JH36ORCC-wZ_7CqXu.js} +1 -1
  58. package/dist/assets/{cynefin-EF2NZ3EQ-BoirpSv2.js → cynefin-EF2NZ3EQ-CE0jDEB2.js} +1 -1
  59. package/dist/assets/{cynefinDiagram-3GCD6N5R-Cdmdj7_K.js → cynefinDiagram-3GCD6N5R-CHr9A4jc.js} +1 -1
  60. package/dist/assets/{dagre-W4DXFKR2-BFjlE582.js → dagre-W4DXFKR2-C3IEvn1u.js} +1 -1
  61. package/dist/assets/{diagram-2UJZ2QOL-OsLSZez_.js → diagram-2UJZ2QOL-D6GEShaY.js} +1 -1
  62. package/dist/assets/{diagram-OVF4WLC6-CwDUdKBh.js → diagram-OVF4WLC6-vc-kIw0c.js} +1 -1
  63. package/dist/assets/{diagram-PFPMY2P6-BLtFTcT4.js → diagram-PFPMY2P6-Dz6L5P0U.js} +1 -1
  64. package/dist/assets/{diagram-UMYRVEAY-BSLF9HqA.js → diagram-UMYRVEAY-BKH-KrgS.js} +1 -1
  65. package/dist/assets/{diagram-YEKJPTXX-9rCjHXiY.js → diagram-YEKJPTXX-BugCeBVB.js} +1 -1
  66. package/dist/assets/{diagram-ZIFT7M5P-C4BY_KLT.js → diagram-ZIFT7M5P-BYARFkzf.js} +1 -1
  67. package/dist/assets/{ebnfDiagram-VR2GEFS7-AhQ5NsrM.js → ebnfDiagram-VR2GEFS7-CKzxPCV8.js} +1 -1
  68. package/dist/assets/{elk-IJKZMXRS-UnH28E2R.js → elk-IJKZMXRS--PWP5h9X.js} +1 -1
  69. package/dist/assets/{erDiagram-O2IAPWRE-CO0nepRl.js → erDiagram-O2IAPWRE-OYgx1l4s.js} +1 -1
  70. package/dist/assets/{file-up-D-jXnd_Y.js → file-up-DmgXwNtQ.js} +1 -1
  71. package/dist/assets/{flowDiagram-OXPTDLAJ-DdStYfx7.js → flowDiagram-OXPTDLAJ-Cx9uOAhj.js} +1 -1
  72. package/dist/assets/{ganttDiagram-R7TSEDQI-DH8CA0Mt.js → ganttDiagram-R7TSEDQI-DF4G2mlV.js} +1 -1
  73. package/dist/assets/{gitGraphDiagram-XJZIOB7I-Ds4256L4.js → gitGraphDiagram-XJZIOB7I-D9CUZ9nv.js} +1 -1
  74. package/dist/assets/{import-name-BTM25v_T.js → import-name-DUNKRTJV.js} +1 -1
  75. package/dist/assets/{index-DqsYd7H_.js → index-CV61vbZS.js} +1 -1
  76. package/dist/assets/{index-DpVzICi9.js → index-VDBTcIMw.js} +3 -3
  77. package/dist/assets/{infoDiagram-5W2HQ5XZ-mNLO1zPg.js → infoDiagram-5W2HQ5XZ-CZW1K3wV.js} +1 -1
  78. package/dist/assets/{ishikawaDiagram-K3B6WC7H-Daak_Ht_.js → ishikawaDiagram-K3B6WC7H-CnK_NQTK.js} +1 -1
  79. package/dist/assets/{journeyDiagram-COXZFDF6-U58GAPno.js → journeyDiagram-COXZFDF6-DSuoKe19.js} +1 -1
  80. package/dist/assets/{kanban-definition-P3RFRI5V-CcRE6J9f.js → kanban-definition-P3RFRI5V-DjmRhFSg.js} +1 -1
  81. package/dist/assets/{mermaid.core-QHRYQaNt.js → mermaid.core-DeRUYgIm.js} +4 -4
  82. package/dist/assets/{mindmap-definition-LZFPQGKD-CEyDomxS.js → mindmap-definition-LZFPQGKD-BJ3VBjfI.js} +1 -1
  83. package/dist/assets/{minimize-oQ71ZbVB.js → minimize-BXc-miDU.js} +1 -1
  84. package/dist/assets/{monitor-BmIglcrr.js → monitor-15mG3xlc.js} +1 -1
  85. package/dist/assets/{new-bot-BqPesTGN.js → new-bot-__CMk5sR.js} +1 -1
  86. package/dist/assets/{org-library-EETemhUh.js → org-library-DT_poCG3.js} +1 -1
  87. package/dist/assets/{package-format-aKMnPv8O.js → package-format-CgaIxeTU.js} +1 -1
  88. package/dist/assets/{pegDiagram-BGZESJAR-CTxI-cP8.js → pegDiagram-BGZESJAR-BZ-1foJI.js} +1 -1
  89. package/dist/assets/{pieDiagram-CAPJLFHJ-B8DCNi6O.js → pieDiagram-CAPJLFHJ-v_kbKYIo.js} +1 -1
  90. package/dist/assets/{quadrantDiagram-GDMTTRAM-CWdpAW4W.js → quadrantDiagram-GDMTTRAM-fpE5oT7k.js} +1 -1
  91. package/dist/assets/{rail-WaxapGbo.js → rail-fintvt10.js} +1 -1
  92. package/dist/assets/{railroadDiagram-SM67HX2B-BCY8OR1i.js → railroadDiagram-SM67HX2B-C8JH_pmt.js} +1 -1
  93. package/dist/assets/{remote-desktop-panel-DmZBAh6p.js → remote-desktop-panel-DAU_1yzY.js} +1 -1
  94. package/dist/assets/{requirementDiagram-X7JNWC4A-BcX43ufU.js → requirementDiagram-X7JNWC4A-DIZkii0D.js} +1 -1
  95. package/dist/assets/{sankeyDiagram-UM26HJRW-C3YBTWo7.js → sankeyDiagram-UM26HJRW-D28LUPgJ.js} +1 -1
  96. package/dist/assets/{sequenceDiagram-ZO4K6R2Y-CNLzalKN.js → sequenceDiagram-ZO4K6R2Y-By6Qr2OZ.js} +1 -1
  97. package/dist/assets/{sizeCapture-INFHLROL-D55E_ZEd.js → sizeCapture-INFHLROL-B8ky8h-O.js} +1 -1
  98. package/dist/assets/{stateDiagram-v2-TBUQTH76-CRDCsicX.js → stateDiagram-v2-TBUQTH76-CtuCVgt_.js} +1 -1
  99. package/dist/assets/styles-DKlhnsr7.css +1 -0
  100. package/dist/assets/{swimlanes-N4OXWK64-Ah7OauuN.js → swimlanes-N4OXWK64-DxwcpFlC.js} +1 -1
  101. package/dist/assets/swimlanesDiagram-K3J5GTZL-B7Xl2xDR.js +8 -0
  102. package/dist/assets/{team-share-D3Hwdncm.js → team-share-Dl1JG3TI.js} +1 -1
  103. package/dist/assets/{timeline-definition-YOQAKGHF-DV-V6CCB.js → timeline-definition-YOQAKGHF-C76P0vUA.js} +1 -1
  104. package/dist/assets/{usecaseDiagram-VIAY4XPW-T9J5Wpir.js → usecaseDiagram-VIAY4XPW-CYHUVqRH.js} +1 -1
  105. package/dist/assets/{vennDiagram-BLWOH2XV-RqJjHEmQ.js → vennDiagram-BLWOH2XV-Da7BHd4-.js} +1 -1
  106. package/dist/assets/{wardleyDiagram-YMQ3BMBF-xZxQC8Rt.js → wardleyDiagram-YMQ3BMBF-Ckv9W8Fc.js} +1 -1
  107. package/dist/assets/{xychartDiagram-TAQBALBS-BgPG2lil.js → xychartDiagram-TAQBALBS-Dw876alP.js} +1 -1
  108. package/dist/index.html +3 -3
  109. package/dist/rail.html +5 -5
  110. package/dist-server/hybrid-plugin-gateway.js +11 -9
  111. package/dist-server/index.js +98 -88
  112. package/dist-server/package.json +1 -1
  113. package/dist-server/server/hybrid-plugin-manifest.js +2 -1
  114. package/dist-server/server/limix-skill-hub.js +3 -3
  115. package/dist-server/server/limix-skill-requirements.js +29 -11
  116. package/dist-server/server/routes/plugin-studio.js +11 -2
  117. package/dist-server/shared/plugin-hub.js +52 -0
  118. package/package.json +1 -1
  119. package/skills/limix-bot-factory/SKILL.md +2 -0
  120. package/skills/limix-bot-factory/references/vi.md +2 -0
  121. package/dist/assets/App-Dijl28_T.js +0 -250
  122. package/dist/assets/SettingsModal-QB3AEILA.js +0 -19
  123. package/dist/assets/channel-D_nJ6dC4.js +0 -1
  124. package/dist/assets/styles-Cr4TcnLq.css +0 -1
  125. package/dist/assets/swimlanesDiagram-K3J5GTZL-G_1ilp2C.js +0 -8
  126. /package/dist/assets/{styles-D7SaLPZf.js → styles-Bixj4Mfc.js} +0 -0
@@ -1318,7 +1318,7 @@ void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(c
1318
1318
  x ${i}`);else if(isEscaping){if(tokenChars[code]!==1)throw new SyntaxError(`Unexpected character at index ${i}`);start===-1?start=i:mustUnescape||(mustUnescape=!0),isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1)start===-1&&(start=i);else if(code===34&&start!==-1)inQuotes=!1,end=i;else if(code===92)isEscaping=!0;else throw new SyntaxError(`Unexpected character at index ${i}`);else if(code===34&&header3.charCodeAt(i-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1)start===-1&&(start=
1319
1319
  i);else if(start!==-1&&(code===32||code===9))end===-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let value3=header3.slice(start,end);mustUnescape&&(value3=value3.replace(/\\/g,""),mustUnescape=!1),push2(params2,paramName,value3),code===44&&(push2(offers,extensionName,params2),params2=Object.create(null),extensionName=void 0),paramName=void 0,start=end=-1}else throw new SyntaxError(`Unexpected character at ind\
1320
1320
  ex ${i}`);if(start===-1||inQuotes||code===32||code===9)throw new SyntaxError("Unexpected end of input");end===-1&&(end=i);let token3=header3.slice(start,end);return extensionName===void 0?push2(offers,token3,params2):(paramName===void 0?push2(params2,token3,!0):mustUnescape?push2(params2,paramName,token3.replace(/\\/g,"")):push2(params2,paramName,token3),push2(offers,extensionName,params2)),offers}function format6(extensions3){return Object.keys(extensions3).map(extension4=>{let configurations=extensions3[extension4];
1321
- return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params2=>[extension4].concat(Object.keys(params2).map(k3=>{let values4=params2[k3];return Array.isArray(values4)||(values4=[values4]),values4.map(v4=>v4===!0?k3:`${k3}=${v4}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format:format6,parse:parse18}}});var require_websocket=__commonJS({"node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter10=__require("events"),https3=__require("https"),http3=__require("http"),net10=__require("net"),tls5=__require("tls"),{randomBytes:randomBytes42,createHash:createHash138}=__require("crypto"),{Duplex:Duplex3,Readable:Readable4}=__require("stream"),{URL:URL3}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),
1321
+ return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params2=>[extension4].concat(Object.keys(params2).map(k3=>{let values4=params2[k3];return Array.isArray(values4)||(values4=[values4]),values4.map(v4=>v4===!0?k3:`${k3}=${v4}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format:format6,parse:parse18}}});var require_websocket=__commonJS({"node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter10=__require("events"),https3=__require("https"),http3=__require("http"),net10=__require("net"),tls5=__require("tls"),{randomBytes:randomBytes42,createHash:createHash139}=__require("crypto"),{Duplex:Duplex3,Readable:Readable4}=__require("stream"),{URL:URL3}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),
1322
1322
  {isBlob}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT:CLOSE_TIMEOUT2,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener:addEventListener2,removeEventListener}}=require_event_target(),{format:format6,parse:parse18}=require_extension(),{toBuffer:toBuffer2}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,
1323
1323
  WebSocket3=class _WebSocket extends EventEmitter10{constructor(address3,protocols,options2){super(),this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address3!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=
1324
1324
  0,protocols===void 0?!options2||options2.protocols===void 0?protocols=[]:Array.isArray(options2.protocols)?protocols=options2.protocols:protocols=[options2.protocols]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options2=protocols,options2.protocols===void 0?protocols=[]:Array.isArray(options2.protocols)?protocols=options2.protocols:protocols=[options2.protocols]):protocols=[protocols]),initAsClient(this,address3,protocols,options2)):(this._autoPong=options2.autoPong,
@@ -1344,7 +1344,7 @@ new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.ma
1344
1344
  parsedUrl2.host;let headers=options2&&options2.headers;if(options2={...options2,headers:{}},headers)for(let[key8,value3]of Object.entries(headers))options2.headers[key8.toLowerCase()]=value3}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl2.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,
1345
1345
  delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options2.headers.authorization&&(options2.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request11(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request11(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err2=>{req===null||req[kAborted]||
1346
1346
  (req=websocket._req=null,emitErrorAndClose(websocket,err2))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL3(location,address3)}catch{let err2=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err2);return}initAsClient(websocket,
1347
- addr,protocols,options2)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest6=createHash138("sha1").update(key7+
1347
+ addr,protocols,options2)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest6=createHash139("sha1").update(key7+
1348
1348
  GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest6){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);
1349
1349
  return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions3;try{extensions3=parse18(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions3);if(extensionNames.
1350
1350
  length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions3[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.
@@ -1361,7 +1361,7 @@ let terminateOnDestroy=!0,duplex=new Duplex3({...options2,autoDestroy:!1,emitClo
1361
1361
  ws3.CLOSED){callback(err2),process.nextTick(emitClose,duplex);return}let called=!1;ws3.once("error",function(err3){called=!0,callback(err3)}),ws3.once("close",function(){called||callback(err2),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws3.terminate()},duplex._final=function(callback){if(ws3.readyState===ws3.CONNECTING){ws3.once("open",function(){duplex._final(callback)});return}ws3._socket!==null&&(ws3._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.
1362
1362
  destroy()):(ws3._socket.once("finish",function(){callback()}),ws3.close()))},duplex._read=function(){ws3.isPaused&&ws3.resume()},duplex._write=function(chunk,encoding,callback){if(ws3.readyState===ws3.CONNECTING){ws3.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws3.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse18(header3){let protocols=new Set,start=-1,end=-1,i=0;for(i;i<header3.length;i++){let code=header3.charCodeAt(i);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at in\
1363
1363
  dex ${i}`);end===-1&&(end=i);let protocol2=header3.slice(start,end);if(protocols.has(protocol2))throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1||end!==-1)throw new SyntaxError("Unexpected end of input");let protocol=header3.slice(start,i);if(protocols.has(protocol))throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),
1364
- protocols}module.exports={parse:parse18}}});var require_websocket_server=__commonJS({"node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter10=__require("events"),http3=__require("http"),{Duplex:Duplex3}=__require("stream"),{createHash:createHash138}=__require("crypto"),extension4=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket3=require_websocket(),{CLOSE_TIMEOUT:CLOSE_TIMEOUT2,GUID,kWebSocket}=require_constants(),
1364
+ protocols}module.exports={parse:parse18}}});var require_websocket_server=__commonJS({"node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter10=__require("events"),http3=__require("http"),{Duplex:Duplex3}=__require("stream"),{createHash:createHash139}=__require("crypto"),extension4=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket3=require_websocket(),{CLOSE_TIMEOUT:CLOSE_TIMEOUT2,GUID,kWebSocket}=require_constants(),
1365
1365
  keyRegex=/^[+/0-9A-Za-z]{22}==$/,RUNNING2=0,CLOSING=1,CLOSED=2,WebSocketServer2=class extends EventEmitter10{constructor(options2,callback){if(super(),options2={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT2,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket3,...options2},
1366
1366
  options2.port==null&&!options2.server&&!options2.noServer||options2.port!=null&&(options2.server||options2.noServer)||options2.server&&options2.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options2.port!=null?(this._server=http3.createServer((req,res)=>{let body3=http3.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body3.length,"Content-Type":"text/plain"}),res.end(body3)}),this._server.listen(options2.port,options2.host,
1367
1367
  options2.backlog,callback)):options2.server&&(this._server=options2.server),this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}options2.perMessageDeflate===!0&&(options2.perMessageDeflate={}),options2.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=
@@ -1372,7 +1372,7 @@ if(version5!==13&&version5!==8){abortHandshakeOrEmitwsClientError(this,req,socke
1372
1372
  header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions3={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension4.parse(secWebSocketExtensions);offers[PerMessageDeflate2.extensionName]&&(perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]),extensions3[PerMessageDeflate2.extensionName]=
1373
1373
  perMessageDeflate)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info2={origin:req.headers[`${version5===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info2,(verified,code,message8,headers)=>{if(!verified)return abortHandshake(socket,code||401,message8,headers);this.
1374
1374
  completeUpgrade(extensions3,key7,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info2))return abortHandshake(socket,401)}this.completeUpgrade(extensions3,key7,protocols,req,socket,head,cb)}completeUpgrade(extensions3,key7,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>RUNNING2)
1375
- return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash138("sha1").update(key7+GUID).digest("base64")}`],ws3=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws3._protocol=protocol)}if(extensions3[PerMessageDeflate2.
1375
+ return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash139("sha1").update(key7+GUID).digest("base64")}`],ws3=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws3._protocol=protocol)}if(extensions3[PerMessageDeflate2.
1376
1376
  extensionName]){let params2=extensions3[PerMessageDeflate2.extensionName].params,value3=extension4.format({[PerMessageDeflate2.extensionName]:[params2]});headers.push(`Sec-WebSocket-Extensions: ${value3}`),ws3._extensions=extensions3}this.emit("headers",headers,req),socket.write(headers.concat(`\r
1377
1377
  `).join(`\r
1378
1378
  `)),socket.removeListener("error",socketOnError),ws3.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(ws3),ws3.on("close",()=>{this.clients.delete(ws3),this._shouldEmitClose&&!this.clients.size&&process.nextTick(emitClose,this)})),cb(ws3,req)}};module.exports=
@@ -19036,7 +19036,7 @@ url,OMB_CONTROL_TOKEN:control.token}:{}}}}function setupCommands(runtime2,platfo
19036
19036
  start || open -a Docker":runtime2==="docker"&&platform2==="linux"?"sudo systemctl start docker":null;if(!runtime2)return{install:install2,runtimeStart:null,pull:null,run:null,start:null,stop:null,remove:null,view:target4.viewerPort?`http://127.0.0.1:${target4.viewerPort}/vnc.html`:""};let command3=args=>[runtime2,...args].join(" ");return{install:install2,runtimeStart,pull:command3(baseImagePullArgs(runtime2)),run:target4.projectDir||runtime2==="container"&&target4.key!==SHARED_LOCAL_VM_TARGET.key?
19037
19037
  null:command3(containerRunArgs(runtime2,"CHANGE_ME",target4,{platform:platform2,resources:DEFAULT_DESKTOP_RESOURCES,hostUser:null})),start:command3(["start",target4.containerName]),stop:command3(["stop",target4.containerName]),remove:command3(["rm",runtime2==="container"?"--force":"-f",target4.containerName]),view:target4.viewerPort?`http://127.0.0.1:${target4.viewerPort}/vnc.html`:""}}function reserveGmailDrafts(calls2,reserved){let keys5=[];for(let call2 of calls2){if(call2.slug!=="GMAIL_CREATE_EMAIL_DRAFT")continue;let args=call2.arguments,thread2=args&&typeof args.thread_id=="string"?args.thread_id:"";if(!thread2)continue;let key7=JSON.stringify([args?.user_id??"me",thread2]);if(reserved.has(key7)||keys5.includes(key7))return"Draft creation for this Gmail thread was already attempted in this request. Read the existing drafts and update the intended draft by ID; do not crea\
19038
19038
  te another, including after a timeout.";keys5.push(key7)}for(let key7 of keys5)reserved.add(key7);return null}function createGmailDrafts(deps){let byGeneration=new Map,byNode=new Map;function forNode(id12){for(let cachedId of byNode.keys()){let node4=deps.node(cachedId);(!node4||deps.ended(node4.status))&&byNode.delete(cachedId)}let node3=deps.node(id12);if(!node3)return;let cached6=byNode.get(id12);if(cached6)return cached6;let owner2=deps.owner(node3.threadId),reserved=owner2?.generations.has(id12)&&owner2.gmailDrafts?owner2.gmailDrafts:(node3.parentId?forNode(node3.parentId):void 0)??new Set;return byNode.
19039
- set(id12,reserved),reserved}return{forNode,forTurn(threadId,generation2,handoffId){let cached6=byGeneration.get(generation2);if(cached6)return cached6;let owner2=deps.owner(threadId),reserved=owner2?.generation===generation2&&owner2.gmailDrafts?owner2.gmailDrafts:forNode(handoffId??generation2)??new Set;return byGeneration.set(generation2,reserved),reserved},forRoomTurn(generation2,handoffId){byGeneration.set(generation2,forNode(handoffId)??new Set)},endTurn(generation2){byGeneration.delete(generation2)}}}import{AsyncLocalStorage as AsyncLocalStorage5}from"node:async_hooks";import{createHash as createHash137,randomBytes as randomBytes41,randomUUID as randomUUID93,timingSafeEqual as timingSafeEqual18}from"node:crypto";import{existsSync as existsSync107,realpathSync as realpathSync32,rmSync as rmSync70}from"node:fs";import{homedir as homedir46}from"node:os";import{rm as removeDirectory}from"node:fs/promises";import{createServer as createServer16}from"node:http";import{basename as basename42,join as join296}from"node:path";import{createHash as createHash12,timingSafeEqual as timingSafeEqual7}from"node:crypto";import{closeSync as closeSync7,constants as constants4,fstatSync as fstatSync2,openSync as openSync6,readSync as readSync2}from"node:fs";var MAX_FILE_BYTES=1048576,ID6=/^[\w-]{1,128}$/,fingerprint=token3=>createHash12("sha256").update(token3).digest("hex"),sameFingerprint=(left2,right2)=>{let a=Buffer.from(left2),b11=Buffer.from(right2);return a.length===b11.length&&timingSafeEqual7(a,b11)};function registrations(file2){
19039
+ set(id12,reserved),reserved}return{forNode,forTurn(threadId,generation2,handoffId){let cached6=byGeneration.get(generation2);if(cached6)return cached6;let owner2=deps.owner(threadId),reserved=owner2?.generation===generation2&&owner2.gmailDrafts?owner2.gmailDrafts:forNode(handoffId??generation2)??new Set;return byGeneration.set(generation2,reserved),reserved},forRoomTurn(generation2,handoffId){byGeneration.set(generation2,forNode(handoffId)??new Set)},endTurn(generation2){byGeneration.delete(generation2)}}}import{AsyncLocalStorage as AsyncLocalStorage5}from"node:async_hooks";import{createHash as createHash138,randomBytes as randomBytes41,randomUUID as randomUUID93,timingSafeEqual as timingSafeEqual18}from"node:crypto";import{existsSync as existsSync107,realpathSync as realpathSync32,rmSync as rmSync70}from"node:fs";import{homedir as homedir46}from"node:os";import{rm as removeDirectory}from"node:fs/promises";import{createServer as createServer16}from"node:http";import{basename as basename43,join as join296}from"node:path";import{createHash as createHash12,timingSafeEqual as timingSafeEqual7}from"node:crypto";import{closeSync as closeSync7,constants as constants4,fstatSync as fstatSync2,openSync as openSync6,readSync as readSync2}from"node:fs";var MAX_FILE_BYTES=1048576,ID6=/^[\w-]{1,128}$/,fingerprint=token3=>createHash12("sha256").update(token3).digest("hex"),sameFingerprint=(left2,right2)=>{let a=Buffer.from(left2),b11=Buffer.from(right2);return a.length===b11.length&&timingSafeEqual7(a,b11)};function registrations(file2){
19040
19040
  let fd;try{fd=openSync6(file2,constants4.O_RDONLY|(process.platform==="win32"?0:constants4.O_NOFOLLOW|constants4.O_NONBLOCK));let stat16=fstatSync2(fd);if(!stat16.isFile()||stat16.size>MAX_FILE_BYTES)return[];if(process.platform!=="win32"&&(stat16.mode&63)!==0)return console.warn("[comms] ignoring external runtime credentials: use a private file (chmod 600)"),[];let bytes4=Buffer.alloc(stat16.size+1),count12=0;for(;;){let read4=readSync2(fd,bytes4,count12,bytes4.length-count12,null);if(!read4)break;
19041
19041
  if(count12+=read4,count12>stat16.size)return[]}let parsed3=JSON.parse(bytes4.subarray(0,count12).toString("utf8"));return!parsed3||typeof parsed3!="object"||Array.isArray(parsed3)?[]:Object.entries(parsed3).flatMap(([botId2,value3])=>{if(!ID6.test(botId2)||!value3||typeof value3!="object"||Array.isArray(value3))return[];let{token:token3,threadId}=value3;return typeof token3!="string"||token3.length<32||token3.length>4096||/\s/.test(token3)?[]:typeof threadId!="string"||!ID6.test(threadId)?[]:[{botId:botId2,
19042
19042
  tokenHash:fingerprint(token3),threadId}]})}catch{return[]}finally{fd!==void 0&&closeSync7(fd)}}function resolveRegistration(file2,tokenHash,botForId){let matches3=registrations(file2).filter(entry3=>sameFingerprint(entry3.tokenHash,tokenHash));if(matches3.length!==1)return null;let registration=matches3[0],bot=botForId(registration.botId);if(!bot||bot.hidden)return null;let task2=bot.tasks?.find(candidate=>candidate.threadId===registration.threadId);return!task2||task2.archivedAt!==void 0?null:{
@@ -28785,7 +28785,7 @@ root4)){let part2=join223(root4,name6);name6.endsWith(".part")&&Date.now()-statS
28785
28785
  s installed");if(await(options2.extract??extractZip2)(archive,staging2),!existsSync86(join223(staging2,EXECUTABLES[pin.platform])))throw new Error("the Chrome archive did not hold the browser; nothing was installed");return rmSync59(directory,{recursive:!0,force:!0}),renameWithRetry(staging2,directory),executable}finally{rmSync59(archive,{force:!0}),rmSync59(staging2,{recursive:!0,force:!0})}}import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync87,readdirSync as readdirSync48}from"node:fs";import{homedir as homedir39}from"node:os";import{posix as posix8,resolve as resolve50,win32 as win329}from"node:path";var MAC_CHROME_BINARY="Contents/MacOS/Google Chrome",MAC_POLICIES="/Library/Managed Preferences",WINDOWS_POLICIES="HKLM\\SOFTWARE\\Policies\\Google\\Chrome",WINDOWS_APP_PATHS="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe",LINUX_CHROME="/opt/google/chrome/chrome",LINUX_POLICIES="/etc/opt/chrome/policies/managed",AGENT_BROWSER_LAYOUTS={darwin:"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",linux:"chrome",win32:"chrome.exe"},paths=platform2=>platform2===
28786
28786
  "win32"?win329:posix8;function isHeadlessShell(path8){return/chrome-headless-shell/iu.test(path8)}function installedGoogleChrome(host3){let{join:join297}=paths(host3.platform),candidates=[];if(host3.platform==="darwin"){let registered2=host3.appForBundleId("com.google.Chrome");registered2&&candidates.push(join297(registered2,MAC_CHROME_BINARY)),candidates.push(join297("/Applications/Google Chrome.app",MAC_CHROME_BINARY),join297(host3.home,"Applications/Google Chrome.app",MAC_CHROME_BINARY))}else if(host3.
28787
28787
  platform==="win32"){for(let hive of["HKLM","HKCU"]){let registered2=host3.registryValue(`${hive}\\${WINDOWS_APP_PATHS}`);registered2&&candidates.push(registered2.replace(/^"|"$/gu,""))}for(let root4 of[host3.env.ProgramFiles,host3.env["ProgramFiles(x86)"],host3.env.LOCALAPPDATA])root4&&candidates.push(join297(root4,"Google","Chrome","Application","chrome.exe"))}else host3.platform==="linux"&&candidates.push(LINUX_CHROME);return candidates.find(candidate=>host3.exists(candidate))??null}function chromePolicyManaged(host3){
28788
- let{basename:basename43,join:join297}=paths(host3.platform);if(host3.platform==="darwin"){let user=host3.env.USER||basename43(host3.home);return host3.exists(join297(MAC_POLICIES,"com.google.Chrome.plist"))||host3.exists(join297(MAC_POLICIES,user,"com.google.Chrome.plist"))}return host3.platform==="win32"?host3.registryKeyExists(WINDOWS_POLICIES):host3.platform==="linux"?host3.list(LINUX_POLICIES).some(name6=>name6.endsWith(".json")):!1}function agentBrowserChrome(host3){let layout=AGENT_BROWSER_LAYOUTS[host3.
28788
+ let{basename:basename44,join:join297}=paths(host3.platform);if(host3.platform==="darwin"){let user=host3.env.USER||basename44(host3.home);return host3.exists(join297(MAC_POLICIES,"com.google.Chrome.plist"))||host3.exists(join297(MAC_POLICIES,user,"com.google.Chrome.plist"))}return host3.platform==="win32"?host3.registryKeyExists(WINDOWS_POLICIES):host3.platform==="linux"?host3.list(LINUX_POLICIES).some(name6=>name6.endsWith(".json")):!1}function agentBrowserChrome(host3){let layout=AGENT_BROWSER_LAYOUTS[host3.
28789
28789
  platform];if(!layout)return null;let{join:join297}=paths(host3.platform),browsers=join297(host3.home,".agent-browser","browsers");return host3.list(browsers).filter(name6=>name6.startsWith("chrome-")).sort((a,b11)=>b11.localeCompare(a,void 0,{numeric:!0})).map(version5=>join297(browsers,version5,layout)).find(candidate=>host3.exists(candidate))??null}var LINUX_ENGINE_BROWSERS=["google-chrome","google-chrome-stable","google-chrome-unstable","chromium","chromium-browser","brave-browser","brave-bro\
28790
28790
  wser-stable"],LINUX_CACHE_EXECUTABLES=["chrome-linux64/chrome","chrome-linux/chrome"];function engineFindsLinuxBrowser(host3){let{join:join297}=posix8;if((host3.enginePath?.()??host3.env.PATH??"").split(":").filter(Boolean).some(directory=>LINUX_ENGINE_BROWSERS.some(name6=>host3.exists(join297(directory,name6)))))return!0;let cached6=(directory,prefix)=>host3.list(directory).some(name6=>name6.startsWith(prefix)&&LINUX_CACHE_EXECUTABLES.some(executable=>host3.exists(join297(directory,name6,executable))));
28791
28791
  return cached6(join297(host3.env.PUPPETEER_CACHE_DIR||join297(host3.home,".cache","puppeteer"),"chrome"),"linux")||cached6(host3.env.PLAYWRIGHT_BROWSERS_PATH||join297(host3.home,".cache","ms-playwright"),"chromium-")}function resolveChromePlan(host3,engine,options2={}){let{env,platform:platform2}=host3;if(env.OMB_BROWSER_LEGACY_SHELL?.trim()==="1")return{kind:"legacy",reason:"OMB_BROWSER_LEGACY_SHELL=1"};let named4=env.OMB_CHROME_PATH?.trim()||env.AGENT_BROWSER_EXECUTABLE_PATH?.trim();if(named4)
@@ -31933,7 +31933,7 @@ routineRun.threadId),await routines2.cancelRun(routineRun.id));let groupTurn=act
31933
31933
  /^\/api\/bots\/([\w-]+)$/),m3&&method2==="DELETE"){let result2=await deleteBotWithLifecycle2(m3[1]);return json7(res,result2.status,result2.body)}return PASS}}init_zod();import{isAbsolute as isAbsolute44}from"node:path";init_new_bot_defaults();import{lstatSync as lstatSync47,readdirSync as readdirSync59,readFileSync as readFileSync189,statSync as statSync47}from"node:fs";import{basename as basename36,isAbsolute as isAbsolute42,join as join266}from"node:path";var MAX_ENTRIES2=400,MAX_DEPTH5=8;function listEntries(root4){let out=[],walk6=(dir,prefix,depth2)=>{if(!(depth2>MAX_DEPTH5||out.length>MAX_ENTRIES2))for(let name6 of readdirSync59(dir)){if(out.length>MAX_ENTRIES2)return;let absolute=join266(dir,name6),path8=prefix?`${prefix}/${name6}`:name6,info2=lstatSync47(absolute);info2.isSymbolicLink()?out.push({path:path8,kind:"link",size:0,absolute}):info2.isDirectory()?(out.push({path:path8,kind:"folder",size:0,absolute}),walk6(absolute,path8,depth2+1)):
31934
31934
  info2.isFile()&&out.push({path:path8,kind:"file",size:info2.size,executable:process.platform!=="win32"&&(info2.mode&73)!==0,absolute})}};return walk6(root4,"",1),out}function readOne(dir){let{take:take2,skipped:skipped2}=planSkillFolder(listEntries(dir));if(take2[0]?.path!=="SKILL.md")throw new Error(`no SKILL.md in ${basename36(dir)}`);let files2=take2.filter(entry3=>entry3.kind==="file").map(entry3=>({path:entry3.path,content:readFileSync189(entry3.absolute),executable:entry3.executable===!0}));
31935
31935
  return{source:`local:${basename36(dir)}`,files:files2,skipped:skipped2}}function readLocalSkills(folder3){try{if(!isAbsolute42(folder3)||!statSync47(folder3).isDirectory())return{error:"Choose a folder on this computer."};let dirs=[],has2=dir=>{try{return statSync47(join266(dir,"SKILL.md")).isFile()}catch{return!1}};if(has2(folder3))dirs.push(folder3);else for(let name6 of readdirSync59(folder3)){let sub=join266(folder3,name6);try{statSync47(sub).isDirectory()&&has2(sub)&&dirs.push(sub)}catch{}}
31936
- return dirs.length?{skills:dirs.slice(0,50).map(readOne)}:{error:"No SKILL.md found in that folder or in its subfolders."}}catch(error66){return{error:error66 instanceof Error?error66.message:"Could not read that folder."}}}import{readdirSync as readdirSync60,readFileSync as readFileSync190,statSync as statSync48,realpathSync as realpathSync31}from"node:fs";import{homedir as homedir45}from"node:os";import{dirname as dirname84,join as join267,resolve as resolve58,relative as relative28,isAbsolute as isAbsolute43,delimiter as delimiter13}from"node:path";import{execFile as execFile25}from"node:child_process";import{promisify as promisify8}from"node:util";init_config3();var run10=promisify8(execFile25),PACKAGE=/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i,BIN2=/^[a-z0-9][a-z0-9_.-]{0,79}$/i,object6=value3=>value3&&typeof value3=="object"&&!Array.isArray(value3)?value3:{};function extractSkillRequirements(text34){let out=[],optionalKeys2=new Set,add11=(kind2,value3,evidence)=>{if(typeof value3!="string"||!value3.trim())return;let raw=kind2==="review"?value3.trim():value3.trim().replace(/[.,;:]+$/,""),match5=raw.match(/^((?:@[\w.-]+\/)?[\w.-]+)(?:@|\s*(?=[<>=~^]))(.*)$/),
31936
+ return dirs.length?{skills:dirs.slice(0,50).map(readOne)}:{error:"No SKILL.md found in that folder or in its subfolders."}}catch(error66){return{error:error66 instanceof Error?error66.message:"Could not read that folder."}}}import{readdirSync as readdirSync60,readFileSync as readFileSync190,statSync as statSync48,realpathSync as realpathSync31}from"node:fs";import{createHash as createHash121}from"node:crypto";import{homedir as homedir45}from"node:os";import{basename as basename37,dirname as dirname84,join as join267,resolve as resolve58,relative as relative28,isAbsolute as isAbsolute43,delimiter as delimiter13}from"node:path";import{execFile as execFile25}from"node:child_process";import{promisify as promisify8}from"node:util";init_config3();var run10=promisify8(execFile25),PACKAGE=/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i,BIN2=/^[a-z0-9][a-z0-9_.-]{0,79}$/i,object6=value3=>value3&&typeof value3=="object"&&!Array.isArray(value3)?value3:{};function extractSkillRequirements(text34){let out=[],optionalKeys2=new Set,add11=(kind2,value3,evidence)=>{if(typeof value3!="string"||!value3.trim())return;let raw=kind2==="review"?value3.trim():value3.trim().replace(/[.,;:]+$/,""),match5=raw.match(/^((?:@[\w.-]+\/)?[\w.-]+)(?:@|\s*(?=[<>=~^]))(.*)$/),
31937
31937
  name6=match5?.[1]??raw;if(kind2!=="review"&&!(kind2==="env"?/^[A-Z_][A-Z0-9_]*$/.test(name6):kind2==="bin"?BIN2.test(name6):PACKAGE.test(name6))){out.push({kind:"review",name:raw,evidence});return}out.push({kind:kind2,name:name6,...kind2==="npm"&&!["remotion","@remotion/cli"].includes(name6)&&/\bnpm\s+(?:install|i)\b[^\n]*\s(?:-g|--global)(?:\s|$)/.test(evidence.split(/\s#|[;&|]/)[0])?{installScope:"tool"}:{},...match5?.[2]?{required:match5[2]}:{},evidence})},read4=(value3,kind2,evidence)=>{if(Array.
31938
31938
  isArray(value3))for(let item of value3)add11(typeof item=="string"?kind2:"review",typeof item=="string"?item:JSON.stringify(item),evidence);else if(typeof value3=="string")add11(kind2,value3,evidence);else for(let[name6,version5]of Object.entries(object6(value3)))add11(kind2,typeof version5=="string"&&version5!=="*"?`${name6}@${version5}`:name6,evidence)},front=text34.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/),body3=front?text34.replace(/^\uFEFF/,"").slice(front[0].length):text34;
31939
31939
  if(front)try{let doc=parseDocument(front[1]);if(doc.errors.length)throw new Error("invalid YAML");let fields3=object6(doc.toJS({maxAliasCount:20})),metadata3=object6(fields3.metadata);for(let block of[fields3.requires,fields3.requirements,fields3.dependencies,metadata3.requires,metadata3.requirements,metadata3.dependencies,object6(metadata3.openclaw).requires,object6(metadata3.clawdbot).requires]){let req=object6(block);(typeof block=="string"||Array.isArray(block))&&read4(block,"review","SKILL.\
@@ -31946,33 +31946,37 @@ kind2,`metadata.optionalRequirements.${key7}`);for(let req of out.slice(start))o
31946
31946
  includes(token3))continue;add11("review",match5[0],"Install command needs review");break}if(!/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:(?:@|>=|<=|==|~=|>|<|=)[\w.^~*+<>=|,-]+)?$/i.test(token3)){add11("review",match5[0],"Install command needs review");break}add11(kind2,token3,match5[0])}}for(let match5 of commands.matchAll(/\b(?:npx|bunx|pnpm\s+(?:exec|dlx))\s+(?:--?[\w-]+(?:=[^\s]+)?\s+)*((?:@[\w.-]+\/)?[\w.-]+(?:@[\w.^~+-]+)?)/g))add11("npm",match5[1]==="remotion"?"@remotion/cli":match5[1],match5[0]);
31947
31947
  if(/\bremotion\b/i.test(text34))for(let name6 of["remotion","@remotion/cli"])out.some(r=>r.kind==="npm"&&r.name===name6)||out.push({kind:"npm",name:name6,evidence:"Remotion code-rendering workflow",optional:!0});let section4=!1;for(let line6 of body3.split(/\r?\n/))/^#{1,6}\s/.test(line6)?section4=/prerequisit|requirement|dependenc|installation|setup|yêu cầu|cài đặt|phụ thuộc/i.test(line6):section4&&line6.trim()&&!line6.trim().startsWith("```")?add11("review",line6.trim(),"Requirement\
31948
31948
  s / setup instructions"):/\b(?:requires?|prerequisites?|dependencies|needs? to be installed)\b|yêu cầu|cần (?:cài|có)/i.test(line6)&&add11("review",line6.trim(),"Requirements mentioned in skill instructions");return[...new Map(out.map(req=>[`${req.kind}:${req.name}:${req.required??""}`,req])).values()].map(req=>optionalKeys2.has(`${req.kind}:${req.name}`)?{...req,optional:!0}:req)}function findSkillBinary(name6,dirs,platform2=process.platform){if(!BIN2.test(name6))return null;for(let dir of dirs)
31949
- for(let ext of platform2==="win32"?["",".exe",".cmd",".bat",".com"]:[""]){let file2=join267(dir,name6+ext);try{if(statSync48(file2).isFile())return file2}catch{}}return null}function findSkillNpmPackage(name6,roots){if(!PACKAGE.test(name6))return null;for(let root4 of roots){let dir=resolve58(root4);for(;;){let file2=join267(dir,"node_modules",name6,"package.json");try{let pkg2=JSON.parse(readFileSync190(file2,"utf8"));if(pkg2.name===name6)return{version:typeof pkg2.version=="string"?pkg2.version:
31949
+ for(let ext of platform2==="win32"?[".exe",".cmd",".bat",".com",""]:[""]){let file2=join267(dir,name6+ext);try{if(statSync48(file2).isFile())return file2}catch{}}return null}function findSkillNpmPackage(name6,roots){if(!PACKAGE.test(name6))return null;for(let root4 of roots){let dir=resolve58(root4);for(;;){let file2=join267(dir,"node_modules",name6,"package.json");try{let pkg2=JSON.parse(readFileSync190(file2,"utf8"));if(pkg2.name===name6)return{version:typeof pkg2.version=="string"?pkg2.version:
31950
31950
  void 0,where:file2}}catch{}let parent2=dirname84(dir);if(parent2===dir)break;dir=parent2}}return null}function findSkillPythonPackage(name6,roots){let normalized2=value3=>value3.toLowerCase().replace(/[-_.]+/g,"-");for(let root4 of roots)for(let env of[root4,join267(root4,".venv"),join267(root4,"venv")]){let sites=[join267(env,"Lib","site-packages")];try{for(let dir of readdirSync60(join267(env,"lib")))/^python\d/.test(dir)&&sites.push(join267(env,"lib",dir,"site-packages"))}catch{}for(let site of sites)
31951
31951
  try{for(let dir of readdirSync60(site).filter(s4=>s4.endsWith(".dist-info"))){let file2=join267(site,dir,"METADATA"),text34=readFileSync190(file2,"utf8");if(normalized2(text34.match(/^Name: (.+)$/m)?.[1]?.trim()??"")!==normalized2(name6))continue;let version5=text34.match(/^Version: (.+)$/m)?.[1]?.trim();if(version5)return{version:version5,where:file2}}}catch{}}return null}async function scanSkillRequirements(bots,mcpServers={},projects=[]){let sources2=new Map,warnings=[],add11=(name6,directory,projects2=[])=>{
31952
31952
  try{let real2=realpathSync31(directory),prior=sources2.get(real2);prior?prior.projects=[...new Set([...prior.projects,...projects2])]:sources2.set(real2,{name:name6,directory:real2,projects:projects2})}catch{warnings.push(`Could not read ${name6}`)}};for(let skill of[...loadBundledSkills(),...loadUserSkills(join267(DATA_DIR,"skills"))])add11(skill.manifest.name,skill.directory);for(let skill of listLibrarySkills())add11(skill.name,librarySkillDirectory(skillsLibraryRoot(),skill.name));for(let name6 of Object.
31953
31953
  keys(readImportedSkills()))add11(name6,join267(IMPORTED_SKILLS_DIR,name6));for(let bot of bots)for(let skill of listMigratableSkills(bot.id))skill.directory&&add11(`${skill.name} (${bot.name})`,skill.directory,[bot.cwd??workspaceDir(bot.id)]);let home2=homedir45(),dirs=`${process.env.OMB_EXTRA_PATH??""}${delimiter13}${process.env.PATH??""}`.split(delimiter13).filter(Boolean);if(process.platform==="win32")try{let{stdout}=await run10("powershell.exe",["-NoProfile","-NonInteractive","-Command","[En\
31954
- vironment]::GetEnvironmentVariable('Path','Machine')+';'+[Environment]::GetEnvironmentVariable('Path','User')"],{windowsHide:!0,timeout:8e3});dirs.push(...stdout.trim().split(";").map(p3=>p3.replace(/%([^%]+)%/g,(_m,key7)=>process.env[key7]??"")))}catch{warnings.push("Could not refresh Windows PATH")}let requirements=[];for(let source5 of sources2.values()){let documents=[],readDocuments=(dir,depth2=0)=>{if(depth2>4){warnings.push(`Document depth limit: ${source5.name}`);return}try{for(let entry3 of readdirSync60(
31955
- dir,{withFileTypes:!0})){if(["node_modules",".git",".venv","venv"].includes(entry3.name)||entry3.isSymbolicLink())continue;let file2=join267(dir,entry3.name);if(entry3.isDirectory()){readDocuments(file2,depth2+1);continue}if(!entry3.isFile()||!(/\.md$/i.test(entry3.name)||["manifest.json","requirements.json","requirements.yaml","requirements.yml","package.json","requirements.txt","pyproject.toml"].includes(entry3.name)))continue;let rel=relative28(source5.directory,realpathSync31(file2));if(!(isAbsolute43(
31956
- rel)||rel.startsWith(".."))){if(statSync48(file2).size>262144){warnings.push(`Document too large: ${source5.name}/${entry3.name}`);continue}documents.push({file:entry3.name,text:readFileSync190(file2,"utf8")})}}}catch{warnings.push(`Could not read documents: ${source5.name}`)}};readDocuments(source5.directory);let found2=[];for(let doc of documents){if(found2.push(...extractSkillRequirements(doc.text)),["manifest.json","requirements.json","requirements.yaml","requirements.yml"].includes(doc.file)&&
31957
- found2.push(...extractSkillRequirements(`---
31954
+ vironment]::GetEnvironmentVariable('Path','Machine')+';'+[Environment]::GetEnvironmentVariable('Path','User')"],{windowsHide:!0,timeout:8e3});process.env.APPDATA&&dirs.push(join267(process.env.APPDATA,"npm")),dirs.push(...stdout.trim().split(";").map(p3=>p3.replace(/%([^%]+)%/g,(_m,key7)=>process.env[key7]??"")))}catch{warnings.push("Could not refresh Windows PATH")}let python=process.env.LIMIX_PYTHON??findSkillBinary("python",dirs)??findSkillBinary("python3",dirs),requirements=[];for(let source5 of sources2.
31955
+ values()){let bundleKey=createHash121("sha256").update(source5.directory).digest("hex"),matchingProjects=projects.filter(project3=>basename37(dirname84(project3))!=="skill-bundles"||basename37(project3)===bundleKey),documents=[],readDocuments=(dir,depth2=0)=>{if(depth2>4){warnings.push(`Document depth limit: ${source5.name}`);return}try{for(let entry3 of readdirSync60(dir,{withFileTypes:!0})){if(["node_modules",".git",".venv","venv"].includes(entry3.name)||entry3.isSymbolicLink())continue;let file2=join267(
31956
+ dir,entry3.name);if(entry3.isDirectory()){readDocuments(file2,depth2+1);continue}if(!entry3.isFile()||!(/\.md$/i.test(entry3.name)||["manifest.json","requirements.json","requirements.yaml","requirements.yml","package.json","requirements.txt","pyproject.toml"].includes(entry3.name)))continue;let rel=relative28(source5.directory,realpathSync31(file2));if(!(isAbsolute43(rel)||rel.startsWith(".."))){if(statSync48(file2).size>256*1024){warnings.push(`Document too large: ${source5.name}/${entry3.name}`);
31957
+ continue}documents.push({file:entry3.name,path:file2,text:readFileSync190(file2,"utf8")})}}}catch{warnings.push(`Could not read documents: ${source5.name}`)}};readDocuments(source5.directory);let found2=[];for(let doc of documents){if(found2.push(...extractSkillRequirements(doc.text)),["manifest.json","requirements.json","requirements.yaml","requirements.yml"].includes(doc.file)&&found2.push(...extractSkillRequirements(`---
31958
31958
  ${doc.text}
31959
- ---`)),doc.file==="package.json")try{let pkg2=JSON.parse(doc.text);for(let[name6,version5]of Object.entries({...pkg2.dependencies,...pkg2.devDependencies,...pkg2.peerDependencies}))found2.push({kind:"npm",name:name6,required:String(version5),evidence:"package.json"})}catch{warnings.push(`Invalid package.json: ${source5.name}`)}if(doc.file==="requirements.txt")for(let line6 of doc.text.split(/\r?\n/).filter(s4=>s4.trim()&&!s4.startsWith("#"))){let match5=line6.trim().match(/^([\w.-]+)(.*)$/);found2.
31960
- push(match5?{kind:"python",name:match5[1],required:match5[2]||void 0,evidence:"requirements.txt"}:{kind:"review",name:line6,evidence:"requirements.txt"})}if(doc.file==="pyproject.toml"){let declarations=doc.text.match(/(?:dependencies|requires)\s*=\s*\[[\s\S]*?\]/g)??["Python project dependencies need review"];for(let declaration of declarations)found2.push({kind:"review",name:"pyproject.toml",evidence:declaration})}}found2.length||found2.push({kind:"review",name:"SKILL.md",evidence:"No machine-\
31961
- checkable requirements declared; review skill instructions"}),documents.some(doc=>doc.file==="SKILL.md")||warnings.push(`SKILL.md unreadable: ${source5.name}`);let unique3=new Map(found2.map(req=>[`${req.kind}:${req.name}:${req.required??""}`,req]));for(let req of unique3.values()){let result2={...req,skill:source5.name,directory:source5.directory,status:"review"};if(req.kind==="bin"){let where2=findSkillBinary(req.name,dirs);result2.status=where2?req.required?"review":"found":"missing",where2&&
31962
- (result2.where=where2)}else if(req.kind==="npm"){let pkg2=findSkillNpmPackage(req.name,[source5.directory,...source5.projects,...projects,...bots.filter(b11=>!b11.computer||b11.computer==="local").map(b11=>b11.cwd??workspaceDir(b11.id)),join267(process.env.APPDATA??home2,"npm")]);result2.status=pkg2?req.required&&req.required!=="*"?"review":"found":"missing",pkg2&&Object.assign(result2,pkg2),req.installScope==="tool"&&BIN2.test(req.name)&&!findSkillBinary(req.name,dirs)&&(result2.status="missing")}else if(req.
31963
- kind==="env")result2.status=process.env[req.name]?"found":"missing";else if(req.kind==="python"){let pkg2=findSkillPythonPackage(req.name,[source5.directory,...source5.projects,...projects,...bots.filter(b11=>!b11.computer||b11.computer==="local").map(b11=>b11.cwd??workspaceDir(b11.id))]);pkg2&&(Object.assign(result2,pkg2),result2.status=req.required?"review":"found")}else req.kind==="mcp"&&(result2.where=Object.hasOwn(mcpServers,req.name)?"Configured; connection needs checking":"No matching MCP\
31964
- configuration");requirements.push(result2)}}let python=process.env.LIMIX_PYTHON??findSkillBinary("python",dirs)??findSkillBinary("python3",dirs),pythonRows=requirements.filter(r=>r.kind==="python"&&!r.version&&PACKAGE.test(r.name));if(python&&pythonRows.length)try{let names5=[...new Set(pythonRows.map(r=>r.name))],code=`import importlib.metadata as m,json,sys
31959
+ ---`)),doc.file==="package.json")try{let pkg2=JSON.parse(doc.text);for(let[name6,version5]of Object.entries({...pkg2.dependencies,...pkg2.devDependencies,...pkg2.peerDependencies,...pkg2.optionalDependencies}))found2.push({kind:"npm",name:name6,required:String(version5),evidence:"package.json"})}catch{warnings.push(`Invalid package.json: ${source5.name}`)}if(doc.file==="requirements.txt")for(let line6 of doc.text.split(/\r?\n/).filter(s4=>s4.trim()&&!s4.startsWith("#"))){let match5=line6.trim().
31960
+ match(/^([\w.-]+)(.*)$/);found2.push(match5?{kind:"python",name:match5[1],required:match5[2]||void 0,evidence:"requirements.txt"}:{kind:"review",name:line6,evidence:"requirements.txt"})}if(doc.file==="pyproject.toml")try{if(!python)throw new Error("Python unavailable");let code=`import json,sys,tomllib
31961
+ with open(sys.argv[1],'rb') as f: data=tomllib.load(f)
31962
+ p=data.get('project',{})
31963
+ print(json.dumps([*p.get('dependencies',[]),*(s for group in p.get('optional-dependencies',{}).values() for s in group),*data.get('build-system',{}).get('requires',[])]))`,{stdout}=await run10(python,["-I","-c",code,doc.path],{timeout:5e3,windowsHide:!0}),specs=JSON.parse(stdout);for(let spec of specs){let match5=/^([\w.-]+)\s*((?:[<>=~!].*)?)$/.exec(spec);found2.push(match5?{kind:"python",name:match5[1],required:match5[2]||void 0,evidence:"pyproject.toml"}:{kind:"review",name:spec,evidence:"pyp\
31964
+ roject.toml"})}specs.length||found2.push({kind:"review",name:"pyproject.toml",evidence:"Check project-specific dependency configuration"})}catch{found2.push({kind:"review",name:"pyproject.toml",evidence:"Python project dependencies need review"})}}found2.length||found2.push({kind:"review",name:"SKILL.md",evidence:"No machine-checkable requirements declared; review skill instructions"}),documents.some(doc=>doc.file==="SKILL.md")||warnings.push(`SKILL.md unreadable: ${source5.name}`);let unique3=new Map(
31965
+ found2.map(req=>[`${req.kind}:${req.name}:${req.required??""}`,req]));for(let req of unique3.values()){let result2={...req,skill:source5.name,directory:source5.directory,status:"review"};if(req.kind==="bin"){let where2=findSkillBinary(req.name,[...dirs,...source5.projects.map(project3=>join267(project3,"node_modules",".bin"))]);result2.status=where2?req.required?"review":"found":"missing",where2&&(result2.where=where2)}else if(req.kind==="npm"){let pkg2=findSkillNpmPackage(req.name,[source5.directory,
31966
+ ...source5.projects,...matchingProjects,...bots.filter(b11=>!b11.computer||b11.computer==="local").map(b11=>b11.cwd??workspaceDir(b11.id)),join267(process.env.APPDATA??home2,"npm")]);result2.status=pkg2?req.required&&req.required!=="*"?"review":"found":"missing",pkg2&&Object.assign(result2,pkg2),req.installScope==="tool"&&BIN2.test(req.name)&&!findSkillBinary(req.name,dirs)&&(result2.status="missing")}else if(req.kind==="env")result2.status=process.env[req.name]?"found":"missing";else if(req.kind===
31967
+ "python"){let pkg2=findSkillPythonPackage(req.name,[source5.directory,...source5.projects,...matchingProjects,...bots.filter(b11=>!b11.computer||b11.computer==="local").map(b11=>b11.cwd??workspaceDir(b11.id))]);pkg2&&(Object.assign(result2,pkg2),result2.status=req.required?"review":"found")}else req.kind==="mcp"&&(result2.where=Object.hasOwn(mcpServers,req.name)?"Configured; connection needs checking":"No matching MCP configuration");requirements.push(result2)}}let pythonRows=requirements.filter(
31968
+ r=>r.kind==="python"&&!r.version&&PACKAGE.test(r.name));if(python&&pythonRows.length)try{let names5=[...new Set(pythonRows.map(r=>r.name))],code=`import importlib.metadata as m,json,sys
31965
31969
  out={}
31966
31970
  for n in sys.argv[1:]:
31967
31971
  try: out[n]=m.version(n)
31968
31972
  except m.PackageNotFoundError: pass
31969
- print(json.dumps(out))`,{stdout}=await run10(python,["-c",code,...names5],{timeout:1e4,windowsHide:!0,maxBuffer:1024*1024}),versions=JSON.parse(stdout);for(let row of pythonRows)row.version=versions[row.name],row.where=python,row.status=row.version?row.required?"review":"found":"missing"}catch{warnings.push("Could not inspect Python package metadata")}return{scope:"host",scannedAt:new Date().toISOString(),skillCount:sources2.size,requirements,warnings}}async function fetchHubFile(root4,area5,id12,path8,fetcher){let first2=area5==="quarantine"?"quarantine":"skills",response=await fetcher(`${root4}/${first2}/${id12}/${path8}`);return response.status!==404?response:fetcher(`${root4}/${first2==="skills"?"quarantine":"skills"}/${id12}/${path8}`)}import{createHash as createHash121}from"node:crypto";import{existsSync as existsSync104,mkdirSync as mkdirSync125,readFileSync as readFileSync191}from"node:fs";import{join as join268}from"node:path";init_atomic();init_config3();var HUB_REPO="leomieo/limix-skill-hub",FILE_MAX_BYTES3=SKILL_FOLDER_LIMITS.fileBytes,HUB_BRANCH="main",SYNC_MIN_GAP_MS=1200*60*1e3,DEFAULT_SETTINGS={autoSync:!0,autoInstall:!1,lastSync:null,lastError:null,etag:null},hubDir=()=>join268(DATA_DIR,"skill-hub"),settingsFile=()=>join268(hubDir(),"settings.json"),catalogFile=()=>join268(hubDir(),"catalog.json");function readJson7(file2,fallback2){try{return JSON.parse(readFileSync191(file2,"utf8"))}catch{return fallback2}}function hubSettings(){return{
31973
+ print(json.dumps(out))`,{stdout}=await run10(python,["-c",code,...names5],{timeout:1e4,windowsHide:!0,maxBuffer:1024*1024}),versions=JSON.parse(stdout);for(let row of pythonRows)row.version=versions[row.name],row.where=python,row.status=row.version?row.required?"review":"found":"missing"}catch{warnings.push("Could not inspect Python package metadata")}return{scope:"host",scannedAt:new Date().toISOString(),skillCount:sources2.size,requirements,warnings}}async function fetchHubFile(root4,area5,id12,path8,fetcher){let first2=area5==="quarantine"?"quarantine":"skills",response=await fetcher(`${root4}/${first2}/${id12}/${path8}`);return response.status!==404?response:fetcher(`${root4}/${first2==="skills"?"quarantine":"skills"}/${id12}/${path8}`)}import{createHash as createHash122}from"node:crypto";import{existsSync as existsSync104,mkdirSync as mkdirSync125,readFileSync as readFileSync191}from"node:fs";import{join as join268}from"node:path";init_atomic();init_config3();var HUB_REPO="leomieo/limix-skill-hub",FILE_MAX_BYTES3=SKILL_FOLDER_LIMITS.fileBytes,HUB_BRANCH="main",SYNC_MIN_GAP_MS=1200*60*1e3,DEFAULT_SETTINGS={autoSync:!0,autoInstall:!1,lastSync:null,lastError:null,etag:null},hubDir=()=>join268(DATA_DIR,"skill-hub"),settingsFile=()=>join268(hubDir(),"settings.json"),catalogFile=()=>join268(hubDir(),"catalog.json");function readJson7(file2,fallback2){try{return JSON.parse(readFileSync191(file2,"utf8"))}catch{return fallback2}}function hubSettings(){return{
31970
31974
  ...DEFAULT_SETTINGS,...readJson7(settingsFile(),{})}}function saveSettings(next){mkdirSync125(hubDir(),{recursive:!0,mode:448}),writeFileAtomic(settingsFile(),JSON.stringify(next,null,2),{mode:384})}function hubCatalog(){let body3=readJson7(catalogFile(),{});return Array.isArray(body3.skills)?body3.skills:[]}var rawUrl=path8=>`https://raw.githubusercontent.com/${HUB_REPO}/${HUB_BRANCH}/${path8}`;async function fetchText2(url3,headers={}){return fetch(url3,{signal:AbortSignal.timeout(3e4),headers:{
31971
31975
  "User-Agent":"limix-bot",...headers}})}async function withCatalogDates(entries4){let cached6=new Map(hubCatalog().map(skill=>[skill.id,skill.added_at])),dated=entries4.map(skill=>({...skill,added_at:skill.added_at||cached6.get(skill.id)||null}));if(dated.every(skill=>skill.added_at))return dated;try{let response=await fetchText2(rawUrl("registry/versions.json"));if(!response.ok)return dated;let history=await response.json();for(let skill of dated){if(skill.added_at||!Array.isArray(history[skill.
31972
31976
  id]))continue;let dates=history[skill.id].flatMap(({at:at8})=>at8&&Number.isFinite(Date.parse(at8))?[Date.parse(at8)]:[]);dates.length&&(skill.added_at=new Date(Math.min(...dates)).toISOString())}}catch{}return dated}var syncing=null;function syncHub(){return syncing||(syncing=(async()=>{let settings=hubSettings();try{let response=await fetchText2(rawUrl("registry/catalog.json"),settings.etag&&existsSync104(catalogFile())&&hubCatalog().every(skill=>skill.added_at)?{"If-None-Match":settings.etag}:
31973
31977
  {});if(response.status===304)return saveSettings({...settings,lastSync:new Date().toISOString(),lastError:null}),{changed:!1,count:hubCatalog().length};if(!response.ok)throw new Error(lxs(`Hub tr\u1EA3 v\u1EC1 ${response.status}`,`The hub returned ${response.status}`));let text34=await response.text(),parsed3=JSON.parse(text34);if(!Array.isArray(parsed3.skills))throw new Error(lxs("Danh m\u1EE5c Hub kh\xF4ng \u0111\xFAng \u0111\u1ECBnh d\u1EA1ng","The hub catalog has the wrong format"));return mkdirSync125(
31974
31978
  hubDir(),{recursive:!0,mode:448}),writeFileAtomic(catalogFile(),JSON.stringify({...parsed3,skills:await withCatalogDates(parsed3.skills)}),{mode:384}),saveSettings({...settings,etag:response.headers.get("etag"),lastSync:new Date().toISOString(),lastError:null}),settings.autoInstall&&await autoInstallEligible(),{changed:!0,count:parsed3.skills.length}}catch(cause){let message8=cause instanceof Error?cause.message:String(cause);return saveSettings({...settings,lastError:message8}),{error:message8}}finally{
31975
- syncing=null}})(),syncing)}var SCRIPT4=/\.(py|js|mjs|cjs|ts|sh|bash|zsh|ps1|bat|cmd|rb|pl|php|go|rs|exe|dll|so|dylib|bin|jar|class|scr|msi|com|apk|dex|node|wasm)$/i,MCP_FILE=/(^|\/)(\.mcp\.json|mcp\.json|mcp-servers?\.json|claude_desktop_config\.json)$/i,isToolFile=path8=>SCRIPT4.test(path8)||MCP_FILE.test(path8),sha=data4=>createHash121("sha256").update(data4).digest("hex");function hubSkillBlocked(entry3){return entry3.area==="quarantine"||entry3.security_status==="quarantined"?lxs("B\u1ED9 qu\xE9t \u0111\xE1\
31979
+ syncing=null}})(),syncing)}var SCRIPT4=/\.(py|js|mjs|cjs|ts|sh|bash|zsh|ps1|bat|cmd|rb|pl|php|go|rs|exe|dll|so|dylib|bin|jar|class|scr|msi|com|apk|dex|node|wasm)$/i,MCP_FILE=/(^|\/)(\.mcp\.json|mcp\.json|mcp-servers?\.json|claude_desktop_config\.json)$/i,isToolFile=path8=>SCRIPT4.test(path8)||MCP_FILE.test(path8),sha=data4=>createHash122("sha256").update(data4).digest("hex");function hubSkillBlocked(entry3){return entry3.area==="quarantine"||entry3.security_status==="quarantined"?lxs("B\u1ED9 qu\xE9t \u0111\xE1\
31976
31980
  nh d\u1EA5u r\u1EE7i ro v\xE0 c\xE1ch ly skill; c\u1EA7n xem c\xE1c ph\xE1t hi\u1EC7n tr\u01B0\u1EDBc khi d\xF9ng.","The scanner flagged risks and quarantined this skill; review the findings before use."):entry3.approval_status==="quarantined"||entry3.approval_status==="rejected"?lxs("Skill b\u1ECB t\u1EEB ch\u1ED1i.","This skill was rejected."):null}function installedFromHub(){let out=new Map;for(let entry3 of Object.values(readSkillLibraryIndex())){let match5=/^limix-hub:([a-z0-9-]+)@([0-9a-f]{64})/.
31977
31981
  exec(entry3.source);match5&&out.set(match5[1],{checksum:match5[2],sha256:entry3.sha256,reviewState:entry3.reviewState})}return out}function hubSkills(){let installed3=installedFromHub(),library=readSkillLibraryIndex();return hubCatalog().map(entry3=>{let have=installed3.get(entry3.id);return{...entry3,installed:!!have,enabled:have?.reviewState==="approved",updateAvailable:!!(have&&have.checksum!==entry3.checksum),blocked:!have&&library[entry3.id]?lxs("Th\u01B0 vi\u1EC7n \u0111\xE3 c\xF3 k\u1EF9 n\u0103ng c\xF9ng t\xEAn kh\xF4ng \u0111\u1EBFn t\u1EEB\
31978
31982
  Hub.","The library already has a skill with this name that did not come from the hub."):null,risky:hubSkillBlocked(entry3)}})}async function installHubSkill(id12,options2={}){if(!isSkillName(id12))return{error:lxs("T\xEAn k\u1EF9 n\u0103ng kh\xF4ng h\u1EE3p l\u1EC7","Invalid skill name")};let entry3=hubCatalog().find(e=>e.id===id12);if(!entry3)return{error:lxs("Kh\xF4ng th\u1EA5y k\u1EF9 n\u0103ng n\xE0y trong danh m\u1EE5c Hub. H\xE3y \u0111\u1ED3ng b\u1ED9 l\u1EA1i.","This skill is not in the\
@@ -31981,14 +31985,15 @@ allowTools||!isToolFile(path8))),skipped2=Object.keys(entry3.file_hashes).filter
31981
31985
  `Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c ${path8}: `,`Couldn't download ${path8}: `)+(cause instanceof Error?cause.message:String(cause))}}if(!response.ok)return{error:lxs(`Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c ${path8} (${response.status})`,`Couldn't download ${path8} (${response.status})`),...response.status===404?{missingFile:path8}:{}};let bytes4=new Uint8Array(await response.arrayBuffer());if(bytes4.byteLength>FILE_MAX_BYTES3)return{error:lxs(`${path8} qu\xE1 l\u1EDBn`,`${path8} is too large`)};
31982
31986
  if(sha(bytes4)!==expected)return{error:lxs(`${path8} kh\xF4ng kh\u1EDBp m\xE3 SHA-256 trong danh m\u1EE5c \u2014 \u0111\xE3 d\u1EEBng c\xE0i`,`${path8} does not match the SHA-256 in the catalog \u2014 install stopped`)};path8==="SKILL.md"?skillMd=new TextDecoder().decode(bytes4):files2.push({path:path8,content:bytes4})}if(installed3){let retired=retireLibrarySkill(id12,installed3.sha256);if("error"in retired)return{error:retired.error};if("stale"in retired)return{error:lxs("K\u1EF9 n\u0103ng \u0111\xE3 b\u1ECB s\u1EEDa tay\
31983
31987
  sau khi c\xE0i, kh\xF4ng c\u1EADp nh\u1EADt \u0111\xE8.","This skill was edited by hand after installing, so it is not overwritten.")}}let result2=installLibrarySkill({name:id12,instructions:skillMd,source:`limix-hub:${id12}@${entry3.checksum} (${entry3.source.repository??"?"}@${(entry3.source.commit??"").slice(0,7)})`,...entry3.license?{license:entry3.license}:{},...entry3.compatibility.text?{compatibility:entry3.compatibility.text}:{},...entry3.tags.length?{tags:entry3.tags}:{},warnings:entry3.
31984
- notes,skippedFiles:skipped2,reviewState:blocked?"disabled":"approved",...files2.length?{files:files2}:{}});return"error"in result2?{error:result2.error}:{ok:!0,skipped:skipped2}}function setHubSkillEnabled(id12,enabled){if(!installedFromHub().has(id12))return{error:lxs("K\u1EF9 n\u0103ng n\xE0y ch\u01B0a c\xE0i t\u1EEB Hub","This skill was not installed from the hub")};let result2=setLibrarySkillReviewState(id12,enabled?"approved":"disabled");return"error"in result2?{error:result2.error}:{ok:!0}}
31985
- function removeHubSkill(id12){let installed3=installedFromHub().get(id12);if(!installed3)return{error:lxs("K\u1EF9 n\u0103ng n\xE0y ch\u01B0a c\xE0i t\u1EEB Hub","This skill was not installed from the hub")};let result2=retireLibrarySkill(id12,installed3.sha256);return"error"in result2?{error:result2.error}:"stale"in result2?{error:lxs("K\u1EF9 n\u0103ng \u0111\xE3 b\u1ECB s\u1EEDa tay sau khi c\xE0i, kh\xF4ng g\u1EE1 t\u1EF1 \u0111\u1ED9ng.","This skill was edited by hand after installing, so i\
31986
- t is not removed automatically.")}:{ok:!0}}async function autoInstallEligible(){let budget=5;for(let skill of hubSkills()){if(budget<=0)return;if(!(!skill.blocked&&!skill.risky&&skill.kind==="instructions-only"&&skill.approval_status==="approved"&&(skill.grade==="excellent"||skill.grade==="recommended"))||skill.installed&&!skill.updateAvailable)continue;budget-=1,"ok"in await installHubSkill(skill.id)&&skill.updateAvailable&&skill.enabled&&setHubSkillEnabled(skill.id,!0)}}async function handleLimixHub(method2,path8,body3){
31987
- let record31=body3&&typeof body3=="object"?body3:{};if(method2==="GET"&&path8==="/api/limix/hub")return{status:200,body:{repo:HUB_REPO,settings:hubSettings(),skills:hubSkills()}};if(method2==="POST"&&path8==="/api/limix/hub/sync"){let result2=await syncHub();return"error"in result2?{status:502,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/settings"){let current3=hubSettings();return saveSettings({...current3,autoSync:typeof record31.autoSync=="boolean"?record31.
31988
- autoSync:current3.autoSync,autoInstall:typeof record31.autoInstall=="boolean"?record31.autoInstall:current3.autoInstall}),{status:200,body:{settings:hubSettings()}}}let id12=typeof record31.id=="string"?record31.id:"";if(method2==="POST"&&(path8==="/api/limix/hub/install"||path8==="/api/limix/hub/update")){let expected=hubCatalog().find(entry3=>entry3.id===id12)?.checksum,result2=await installHubSkill(id12,{allowTools:record31.allowTools===!0,allowRisky:record31.allowRisky===!0});return"error"in
31989
- result2&&result2.missingFile?!("error"in await syncHub())&&hubCatalog().find(entry3=>entry3.id===id12)?.checksum!==expected?{status:409,body:{error:lxs("Kho k\u1EF9 n\u0103ng v\u1EEBa c\u1EADp nh\u1EADt. H\xE3y xem l\u1EA1i m\u1EE5c n\xE0y tr\u01B0\u1EDBc khi c\xE0i.","The skill catalog has changed. Review this skill before installing.")}}:{status:422,body:{error:lxs(`G\xF3i k\u1EF9 n\u0103ng \u0111ang thi\u1EBFu t\u1EC7p ${result2.missingFile}. Ch\u01B0a c\xE0i \u0111\u1EB7t k\u1EF9 n\u0103ng.`,
31990
- `The skill package is missing ${result2.missingFile}. The skill was not installed.`)}}:"error"in result2?{status:422,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/enable"){let result2=setHubSkillEnabled(id12,record31.enabled===!0);return"error"in result2?{status:422,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/remove"){let result2=removeHubSkill(id12);return"error"in result2?{status:422,body:result2}:{status:200,body:result2}}
31991
- return null}var started2=!1;function startHubAutoSync(){if(started2)return;started2=!0;let tick2=()=>{let settings=hubSettings();settings.autoSync&&(settings.lastSync&&Date.now()-Date.parse(settings.lastSync)<SYNC_MIN_GAP_MS||syncHub())};setTimeout(tick2,6e4).unref(),setInterval(tick2,1800*1e3).unref()}function createBotSkillsRoutes(deps){let{store:store5,cfg:cfg2,listBotSkills:listBotSkills2,readBotSkillFile:readBotSkillFile2,stagedSkillListing:stagedSkillListing2}=deps;return async({req,res,url:url3,path:path8,method:method2,json:json7,readBody:readBody2})=>{let m3=null;if(method2==="GET"&&path8==="/api/limix/skill-requirements")return json7(res,200,await scanSkillRequirements(store5.bots,cfg2.mcpServers));if(method2==="POST"&&path8==="/api/limix/skill-requirements/scan"){let input3=external_exports.
31988
+ notes,skippedFiles:skipped2,reviewState:blocked||installed3?.reviewState==="disabled"?"disabled":"approved",...files2.length?{files:files2}:{}});return"error"in result2?{error:result2.error}:{ok:!0,skipped:skipped2,...options2.allowTools?{bundle:{directory:librarySkillDirectory(skillsLibraryRoot(),id12),mcp:files2.filter(file2=>MCP_FILE.test(file2.path)).map(file2=>new TextDecoder().decode(file2.content))}}:{}}}function setHubSkillEnabled(id12,enabled){if(!installedFromHub().has(id12))return{error:lxs(
31989
+ "K\u1EF9 n\u0103ng n\xE0y ch\u01B0a c\xE0i t\u1EEB Hub","This skill was not installed from the hub")};let result2=setLibrarySkillReviewState(id12,enabled?"approved":"disabled");return"error"in result2?{error:result2.error}:{ok:!0}}function removeHubSkill(id12){let installed3=installedFromHub().get(id12);if(!installed3)return{error:lxs("K\u1EF9 n\u0103ng n\xE0y ch\u01B0a c\xE0i t\u1EEB Hub","This skill was not installed from the hub")};let result2=retireLibrarySkill(id12,installed3.sha256);return"\
31990
+ error"in result2?{error:result2.error}:"stale"in result2?{error:lxs("K\u1EF9 n\u0103ng \u0111\xE3 b\u1ECB s\u1EEDa tay sau khi c\xE0i, kh\xF4ng g\u1EE1 t\u1EF1 \u0111\u1ED9ng.","This skill was edited by hand after installing, so it is not removed automatically.")}:{ok:!0}}async function autoInstallEligible(){let budget=5;for(let skill of hubSkills()){if(budget<=0)return;if(!(!skill.blocked&&!skill.risky&&skill.kind==="instructions-only"&&skill.approval_status==="approved"&&(skill.grade==="excell\
31991
+ ent"||skill.grade==="recommended"))||skill.installed&&!skill.updateAvailable)continue;budget-=1,"ok"in await installHubSkill(skill.id)&&skill.updateAvailable&&skill.enabled&&setHubSkillEnabled(skill.id,!0)}}async function handleLimixHub(method2,path8,body3){let record31=body3&&typeof body3=="object"?body3:{};if(method2==="GET"&&path8==="/api/limix/hub")return{status:200,body:{repo:HUB_REPO,settings:hubSettings(),skills:hubSkills()}};if(method2==="POST"&&path8==="/api/limix/hub/sync"){let result2=await syncHub();
31992
+ return"error"in result2?{status:502,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/settings"){let current3=hubSettings();return saveSettings({...current3,autoSync:typeof record31.autoSync=="boolean"?record31.autoSync:current3.autoSync,autoInstall:typeof record31.autoInstall=="boolean"?record31.autoInstall:current3.autoInstall}),{status:200,body:{settings:hubSettings()}}}let id12=typeof record31.id=="string"?record31.id:"";if(method2==="POST"&&(path8==="/api/\
31993
+ limix/hub/install"||path8==="/api/limix/hub/update")){let expected=hubCatalog().find(entry3=>entry3.id===id12)?.checksum,result2=await installHubSkill(id12,{allowTools:record31.allowTools===!0,allowRisky:record31.allowRisky===!0});return"error"in result2&&result2.missingFile?!("error"in await syncHub())&&hubCatalog().find(entry3=>entry3.id===id12)?.checksum!==expected?{status:409,body:{error:lxs("Kho k\u1EF9 n\u0103ng v\u1EEBa c\u1EADp nh\u1EADt. H\xE3y xem l\u1EA1i m\u1EE5c n\xE0y tr\u01B0\u1EDBc khi c\xE0i.",
31994
+ "The skill catalog has changed. Review this skill before installing.")}}:{status:422,body:{error:lxs(`G\xF3i k\u1EF9 n\u0103ng \u0111ang thi\u1EBFu t\u1EC7p ${result2.missingFile}. Ch\u01B0a c\xE0i \u0111\u1EB7t k\u1EF9 n\u0103ng.`,`The skill package is missing ${result2.missingFile}. The skill was not installed.`)}}:"error"in result2?{status:422,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/enable"){let result2=setHubSkillEnabled(id12,record31.enabled===!0);
31995
+ return"error"in result2?{status:422,body:result2}:{status:200,body:result2}}if(method2==="POST"&&path8==="/api/limix/hub/remove"){let result2=removeHubSkill(id12);return"error"in result2?{status:422,body:result2}:{status:200,body:result2}}return null}var started2=!1;function startHubAutoSync(){if(started2)return;started2=!0;let tick2=()=>{let settings=hubSettings();settings.autoSync&&(settings.lastSync&&Date.now()-Date.parse(settings.lastSync)<SYNC_MIN_GAP_MS||syncHub())};setTimeout(tick2,6e4).unref(),
31996
+ setInterval(tick2,1800*1e3).unref()}function createBotSkillsRoutes(deps){let{store:store5,cfg:cfg2,listBotSkills:listBotSkills2,readBotSkillFile:readBotSkillFile2,stagedSkillListing:stagedSkillListing2}=deps;return async({req,res,url:url3,path:path8,method:method2,json:json7,readBody:readBody2})=>{let m3=null;if(method2==="GET"&&path8==="/api/limix/skill-requirements")return json7(res,200,await scanSkillRequirements(store5.bots,cfg2.mcpServers));if(method2==="POST"&&path8==="/api/limix/skill-requirements/scan"){let input3=external_exports.
31992
31997
  object({projects:external_exports.array(external_exports.string().max(4096).refine(isAbsolute44)).max(200)}).safeParse(await readBody2(req));return input3.success?json7(res,200,await scanSkillRequirements(store5.bots,cfg2.mcpServers,input3.data.projects)):json7(res,400,{error:"Choose valid project folders"})}if(path8.startsWith("/api/limix/bots")){let library=await handleLimixBotLibrary(method2,path8);if(library)return json7(res,library.status,library.body)}if(path8.startsWith("/api/limix/hub")){
31993
31998
  let hub=await handleLimixHub(method2,path8,method2==="POST"?await readBody2(req):void 0);if(hub)return json7(res,hub.status,hub.body)}if(path8.startsWith("/api/limix/skill-store/")){let skillStore=handleLimixSkillStore(store5,method2,path8,method2==="POST"?await readBody2(req):void 0);if(skillStore)return json7(res,skillStore.status,skillStore.body)}if(method2==="GET"&&path8==="/api/limix/bundled-skills"){let skills=loadBundledSkills().map(({manifest})=>({id:manifest.id,name:manifest.name,description:limixSkillText(
31994
31999
  manifest.id,manifest.description),defaultEnabled:manifest.defaultEnabled,triggerTerms:manifest.triggerTerms,core:LIMIX_CORE_SKILLS.has(manifest.id)}));return json7(res,200,{skills})}if(m3=path8.match(/^\/api\/bots\/([\w-]+)\/skill-template$/),m3&&method2==="POST"){if(!store5.bot(m3[1]))return json7(res,404,{error:"no such bot"});let checked=botSkillTemplateSchema.safeParse(await readBody2(req));if(!checked.success)return json7(res,400,{error:checked.error.message});let input3=checked.data,parsed3=parseSkillMd(
@@ -32008,31 +32013,36 @@ rt"});let skill=parseSkillMd(parsed3.data.text);if("error"in skill)return json7(
32008
32013
  m3&&method2==="GET"){if(!skillsLibraryEnabled(cfg2))return json7(res,404,{error:"skills library is not enabled"});let text34=readLibrarySkillFile(m3[1]);return text34===null?json7(res,404,{error:"no such skill"}):json7(res,200,{text:text34})}if(m3&&method2==="PATCH"){if(!skillsLibraryEnabled(cfg2))return json7(res,404,{error:"skills library is not enabled"});let parsed3=external_exports.object({enabled:external_exports.boolean().optional(),everyBot:external_exports.boolean().optional()}).refine(
32009
32014
  body3=>body3.enabled!==void 0!=(body3.everyBot!==void 0)).safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"enabled or everyBot must be true or false"});let result2=parsed3.data.enabled!==void 0?setLibrarySkillReviewState(m3[1],parsed3.data.enabled?"approved":"disabled"):setLibrarySkillEveryBot(m3[1],parsed3.data.everyBot);return"error"in result2?json7(res,404,{error:result2.error}):json7(res,200,{skill:result2})}if(m3=path8.match(/^\/api\/bots\/([\w-]+)\/skills-library$/),
32010
32015
  m3&&method2==="PUT"){if(!skillsLibraryEnabled(cfg2))return json7(res,404,{error:"skills library is not enabled"});if(!store5.bot(m3[1]))return json7(res,404,{error:"no such bot"});let parsed3=external_exports.object({skills:external_exports.array(external_exports.string().min(1).max(64)).max(200)}).safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"skills must be a list of skill names"});let index4=readSkillLibraryIndex(),names5=[...new Set(parsed3.data.skills)],unknown2=names5.
32011
- filter(name6=>!index4[name6]);if(unknown2.length)return json7(res,422,{error:"not in the library: "+unknown2.join(", ")});for(let name6 of names5)setLibrarySkillOptOut(m3[1],name6,!1);return store5.patchBot(m3[1],{assignedSkills:names5}),json7(res,200,{assignedSkills:names5})}return PASS}}init_zod();init_zod();import{createHash as createHash122}from"node:crypto";var pluginContentKinds=["skills","resources","frameworks","guardrails"],pluginEvents=["import","approve","reject","install","remove","assign","assign-pins","invalidate","attach-evaluation","set-host-execution"];function pluginEnabled(plugin,bot,siblings=[]){return Object.hasOwn(plugin.bots,bot.id)?plugin.bots[bot.id]:plugin.teams.includes(bot.section??"")&&!siblings.some(p3=>p3.id===plugin.id&&p3.bots[bot.id]===!0)}init_redact();var pluginId=external_exports.string().max(80).regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/),pluginVersion=external_exports.string().max(40).regex(/^\d+\.\d+\.\d+$/),labels2=max4=>external_exports.object({en:external_exports.string().min(1).max(max4),vi:external_exports.string().min(1).max(max4)}).strict(),serverName=external_exports.string().regex(/^[\w-]{1,80}$/),unique2=entries4=>new Set(entries4).size===entries4.length,text30=external_exports.object({name:external_exports.string().refine(
32012
- isSkillName),description:external_exports.string().min(1).max(1024),content:external_exports.string().min(1).max(262144)}).strict(),texts2=external_exports.array(text30).max(32).refine(items=>unique2(items.map(item=>item.name))).default([]),source4=external_exports.object({server:serverName,uri:external_exports.string().min(1).max(2048),revision:external_exports.string().min(1).max(512)}).strict(),manifestSchema3=external_exports.object({schemaVersion:external_exports.literal("1.0.0"),id:pluginId,
32013
- version:pluginVersion,name:labels2(96),description:labels2(1024),license:external_exports.string().trim().min(1).max(512),type:external_exports.enum(["local","remote-mcp","hybrid"]),components:external_exports.object({skills:texts2,resources:texts2,frameworks:texts2,guardrails:texts2,mcpServers:external_exports.array(serverName).max(12).refine(unique2).default([]),tools:external_exports.array(external_exports.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/)).max(64).refine(unique2).default([])}).strict(),
32014
- localization:external_exports.union([external_exports.object({core:external_exports.literal("en"),interface:external_exports.literal("vi")}).strict(),external_exports.object({core:external_exports.literal("original"),interface:external_exports.literal("original")}).strict()]),source:source4.optional(),permissions:external_exports.object({shell:external_exports.literal(!1),filesystem:external_exports.array(external_exports.string()).max(0),network:external_exports.array(external_exports.string()).
32015
- max(0),secrets:external_exports.array(external_exports.string()).max(0)}).strict().optional(),security:external_exports.object({approvalRequired:external_exports.literal(!0),sandboxRequired:external_exports.literal(!0),verifyIntegrity:external_exports.literal(!0)}).strict().optional()}).strict().superRefine((m3,ctx)=>{let issue3=message8=>ctx.addIssue({code:"custom",message:message8}),remote2=m3.components.mcpServers.length>0,content4=pluginContentKinds.some(kind2=>m3.components[kind2].length>0);
32016
- remote2!==(m3.type!=="local")&&issue3("The manifest type must match its MCP connections"),m3.type==="hybrid"&&!content4&&issue3("A hybrid plugin needs a local component"),!remote2&&!content4&&!m3.components.tools.length&&issue3("The package is empty"),m3.source&&(m3.type!=="remote-mcp"||!m3.components.mcpServers.includes(m3.source.server))&&issue3("Invalid skill origin"),!m3.source&&m3.localization.core!=="en"&&issue3("Local packages require an English core");let encoded=JSON.stringify(m3);Buffer.
32017
- byteLength(encoded)>512*1024&&issue3("Package exceeds the 512 KiB limit"),holdsCredential(encoded)&&issue3("A plugin manifest cannot contain credentials");for(let skill of m3.components.skills){let parsed3=parseSkillMd(skill.content);("error"in parsed3||parsed3.name!==skill.name||!parsed3.body.trim())&&issue3("SKILL.md must contain a matching name, description and body")}}),hurdleEvaluation=external_exports.object({schemaVersion:external_exports.union([external_exports.literal(2),external_exports.
32018
- literal(3)]),id:external_exports.string().regex(/^run_[0-9a-f-]{36}$/),state:external_exports.literal("complete"),verdict:external_exports.enum(["pass","fail","incomplete","unknown"]),snapshotFingerprint:external_exports.string().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),scanPluginContent=manifest=>{let warnings=new Set,inspect=(label4,value3)=>{for(let warning of scanSkillText(value3))warnings.add(label4+": "+warning);/\b(ignore|override|bypass|disregard)\b.{0,48}\b(instructions?|policy|policies|permissions?|approval)\b/i.
32016
+ filter(name6=>!index4[name6]);if(unknown2.length)return json7(res,422,{error:"not in the library: "+unknown2.join(", ")});for(let name6 of names5)setLibrarySkillOptOut(m3[1],name6,!1);return store5.patchBot(m3[1],{assignedSkills:names5}),json7(res,200,{assignedSkills:names5})}return PASS}}init_zod();var pluginContentKinds=["skills","resources","frameworks","guardrails"],pluginServiceIcons={youtube:{label:"YouTube",domain:"youtube.com"},github:{label:"GitHub",domain:"github.com"},notion:{label:"Notion",domain:"notion.so"},slack:{label:"Slack",domain:"slack.com"},supabase:{label:"Supabase",domain:"supabase.com"},googlecalendar:{label:"Google Calendar",domain:"calendar.google.com"},googlesheets:{label:"Google Sheets",domain:"sheets.google.com"},googledocs:{label:"Google Docs",domain:"docs.goog\
32017
+ le.com"},googledrive:{label:"Google Drive",domain:"drive.google.com"},linear:{label:"Linear",domain:"linear.app"},outlook:{label:"Outlook",domain:"outlook.com"},hubspot:{label:"HubSpot",domain:"hubspot.com"},airtable:{label:"Airtable",domain:"airtable.com"},perplexity:{label:"Perplexity AI",domain:"perplexity.ai"},composio:{label:"Composio",domain:"composio.dev"}},serviceIcons=Object.keys(pluginServiceIcons),pluginIconKinds=[...serviceIcons,"video","research","support","commerce","data","automat\
32018
+ ion","plugin"];function inferPluginServiceIcon(...labels3){let services2=new Set;for(let label4 of labels3){let words8=" "+label4.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()+" ";for(let service of serviceIcons){let name6=pluginServiceIcons[service].label.toLowerCase();(words8.includes(" "+service+" ")||words8.includes(" "+name6+" "))&&services2.add(service)}}if(services2.size===1)return services2.values().next().value}var pluginIconRules=[["video",/\b(?:youtube|video|film|cinema|livestream|phim)\b|dựng phim|dựng clip/u],
32019
+ ["support",/\b(?:support|helpdesk)\b|hỗ trợ|chăm sóc/u],["commerce",/\b(?:commerce|shop|store|sales|orders?)\b|bán hàng|đơn hàng|thương mại/u],["data",/\b(?:analytics|database|dashboard|reporting|data)\b|dữ liệu|thống kê|báo cáo/u],["research",/\b(?:research|search|lookup)\b|nghiên cứu|tìm kiếm|tra cứu/u],["automation",/\b(?:automation|workflow|pipeline|scheduler)\b|tự động|quy trình|lập lịch/u]];function inferPluginIcon(...labels3){for(let label4 of labels3){
32020
+ let words8=label4.normalize("NFC").toLowerCase(),match5=pluginIconRules.find(([,pattern])=>pattern.test(words8));if(match5)return match5[0]}return"plugin"}var pluginEvents=["import","approve","reject","install","remove","assign","assign-pins","invalidate","attach-evaluation","set-host-execution"];function pluginEnabled(plugin,bot,siblings=[]){return Object.hasOwn(plugin.bots,bot.id)?plugin.bots[bot.id]:plugin.teams.includes(bot.section??"")&&!siblings.some(p3=>p3.id===plugin.id&&p3.bots[bot.id]===
32021
+ !0)}init_zod();import{createHash as createHash123}from"node:crypto";init_redact();var pluginId=external_exports.string().max(80).regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/),pluginVersion=external_exports.string().max(40).regex(/^\d+\.\d+\.\d+$/),labels2=max4=>external_exports.object({en:external_exports.string().min(1).max(max4),vi:external_exports.string().min(1).max(max4)}).strict(),serverName=external_exports.string().regex(/^[\w-]{1,80}$/),unique2=entries4=>new Set(entries4).size===entries4.length,text30=external_exports.object({name:external_exports.string().refine(
32022
+ isSkillName),description:external_exports.string().min(1).max(1024),content:external_exports.string().min(1).max(262144)}).strict(),texts2=external_exports.array(text30).max(32).refine(items=>unique2(items.map(item=>item.name))).default([]),source4=external_exports.object({server:serverName,uri:external_exports.string().min(1).max(2048),revision:external_exports.string().min(1).max(512)}).strict(),manifestSchema3=external_exports.object({icon:external_exports.enum(pluginIconKinds).optional(),schemaVersion:external_exports.
32023
+ literal("1.0.0"),id:pluginId,version:pluginVersion,name:labels2(96),description:labels2(1024),license:external_exports.string().trim().min(1).max(512),type:external_exports.enum(["local","remote-mcp","hybrid"]),components:external_exports.object({skills:texts2,resources:texts2,frameworks:texts2,guardrails:texts2,mcpServers:external_exports.array(serverName).max(12).refine(unique2).default([]),tools:external_exports.array(external_exports.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/)).max(64).refine(
32024
+ unique2).default([])}).strict(),localization:external_exports.union([external_exports.object({core:external_exports.literal("en"),interface:external_exports.literal("vi")}).strict(),external_exports.object({core:external_exports.literal("original"),interface:external_exports.literal("original")}).strict()]),source:source4.optional(),permissions:external_exports.object({shell:external_exports.literal(!1),filesystem:external_exports.array(external_exports.string()).max(0),network:external_exports.
32025
+ array(external_exports.string()).max(0),secrets:external_exports.array(external_exports.string()).max(0)}).strict().optional(),security:external_exports.object({approvalRequired:external_exports.literal(!0),sandboxRequired:external_exports.literal(!0),verifyIntegrity:external_exports.literal(!0)}).strict().optional()}).strict().superRefine((m3,ctx)=>{let issue3=message8=>ctx.addIssue({code:"custom",message:message8}),remote2=m3.components.mcpServers.length>0,content4=pluginContentKinds.some(kind2=>m3.
32026
+ components[kind2].length>0);remote2!==(m3.type!=="local")&&issue3("The manifest type must match its MCP connections"),m3.type==="hybrid"&&!content4&&issue3("A hybrid plugin needs a local component"),!remote2&&!content4&&!m3.components.tools.length&&issue3("The package is empty"),m3.source&&(m3.type!=="remote-mcp"||!m3.components.mcpServers.includes(m3.source.server))&&issue3("Invalid skill origin"),!m3.source&&m3.localization.core!=="en"&&issue3("Local packages require an English core");let encoded=JSON.
32027
+ stringify(m3);Buffer.byteLength(encoded)>512*1024&&issue3("Package exceeds the 512 KiB limit"),holdsCredential(encoded)&&issue3("A plugin manifest cannot contain credentials");for(let skill of m3.components.skills){let parsed3=parseSkillMd(skill.content);("error"in parsed3||parsed3.name!==skill.name||!parsed3.body.trim())&&issue3("SKILL.md must contain a matching name, description and body")}}),hurdleEvaluation=external_exports.object({schemaVersion:external_exports.union([external_exports.literal(
32028
+ 2),external_exports.literal(3)]),id:external_exports.string().regex(/^run_[0-9a-f-]{36}$/),state:external_exports.literal("complete"),verdict:external_exports.enum(["pass","fail","incomplete","unknown"]),snapshotFingerprint:external_exports.string().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),scanPluginContent=manifest=>{let warnings=new Set,inspect=(label4,value3)=>{for(let warning of scanSkillText(value3))warnings.add(label4+": "+warning);/\b(ignore|override|bypass|disregard)\b.{0,48}\b(instructions?|policy|policies|permissions?|approval)\b/i.
32019
32029
  test(value3)&&warnings.add(label4+": instructions may attempt to override host policy")};for(let kind2 of pluginContentKinds)for(let part2 of manifest.components[kind2])inspect(kind2+"/"+part2.name,part2.description+`
32020
32030
  `+part2.content);for(let lang of["en","vi"])inspect(lang,manifest.name[lang]+`
32021
- `+manifest.description[lang]);return manifest.source&&manifest.license==="Unspecified"&&warnings.add("Remote source does not declare a license"),[...warnings]};function reviewManifest(manifest,evaluate3=scanPluginContent){let{id:id12,version:version5,name:name6,description:description2}=manifest,sha2567=createHash122("sha256").update(JSON.stringify(manifest)).digest("hex");return{id:id12,version:version5,name:name6,description:description2,requiresMcp:manifest.components.mcpServers,manifest,sha256:sha2567,
32031
+ `+manifest.description[lang]);return manifest.source&&manifest.license==="Unspecified"&&warnings.add("Remote source does not declare a license"),[...warnings]};function reviewManifest(manifest,evaluate3=scanPluginContent){let{id:id12,version:version5,name:name6,description:description2}=manifest,sha2567=createHash123("sha256").update(JSON.stringify(manifest)).digest("hex");return{id:id12,version:version5,name:name6,description:description2,requiresMcp:manifest.components.mcpServers,manifest,sha256:sha2567,
32022
32032
  warnings:evaluate3(manifest)}}var input2=external_exports.object({botId:external_exports.string().min(1).max(128),description:external_exports.string().trim().min(1).max(4e3),servers:external_exports.array(external_exports.string().regex(/^[\w-]{1,80}$/)).max(12).default([])}).strict();function createPluginStudio(generate3){let busy=new Set;return async({req,res,method:method2,path:path8,auth,json:json7,readBody:readBody2})=>{if(path8!=="/api/limix/plugins/draft")return PASS;if(!ownerOrAdmin(auth)||auth.kind==="loopback"&&auth.
32023
32033
  companionDevice)return json7(res,403,{error:"Admin access required"});if(method2!=="POST")return json7(res,405,{error:"POST required"});let body3=input2.safeParse(await readBody2(req));if(!body3.success)return json7(res,400,{error:"Invalid draft request"});let{botId:botId2,description:description2,servers}=body3.data;if(busy.has(botId2)||busy.size>=3)return json7(res,429,{error:"Draft generation is busy"});busy.add(botId2);let abort=new AbortController;res.once("close",()=>abort.abort());try{let prompt=[
32024
32034
  "Draft a Limix Bot plugin manifest. Return one JSON object. Produce text components only. Never include shell code, credentials or new permissions.",'Schema: {schemaVersion:"1.0.0",id:"kebab-case",version:"1.0.0",type:"local"|"hybrid",license:"UNLICENSED",name:{en,vi},description:{en,vi},localization:{core:"en",interface:"vi"},components:{skills:[{name,description,content}],resources:[],frameworks:[],guardrails:[],mcpServers:[],tools:[]}}.',"Each skill content is an English SKILL.md beginning wi\
32025
- th YAML frontmatter with its exact name and English description, then workflow instructions. Include its Vietnamese display name and description in the package labels. Only reference servers selected below. Do not invent tool identifiers.",JSON.stringify({description:description2,allowedServers:servers})].join(`
32026
- `),raw=await generate3(botId2,prompt,abort.signal);if(!raw)return json7(res,503,{error:"No text-generation engine is available for this bot"});let candidate=raw.trim().replace(/^\x60\x60\x60(?:json)?\s*\n/i,"").replace(/\n\x60\x60\x60$/,"");if(Buffer.byteLength(candidate)>512*1024)throw Error();let manifest=manifestSchema3.parse(JSON.parse(candidate));if(manifest.source||manifest.components.mcpServers.some(s4=>!servers.includes(s4)))throw Error();return json7(res,200,{manifest})}catch{return json7(
32027
- res,422,{error:"The engine could not produce a valid draft"})}finally{busy.delete(botId2)}}}init_zod();import{readFileSync as readFileSync192}from"node:fs";var MIN_FRAME=64*1024,MAX_FRAME3=16*1024*1024;var retrievalDecoder,compiled;function createDecoder(){try{return compiled??=new WebAssembly.Module(readFileSync192(limixNativeResource("limix_tool_gateway.wasm"))),new WebAssembly.Instance(compiled).exports}catch{return null}}var passageKey;function nativePassages(key7,normalized2,query2){retrievalDecoder===void 0&&(retrievalDecoder=createDecoder());let native=retrievalDecoder;if(!native?.index_passages||!native.find_passages)return;let write4=text34=>{let bytes4=Buffer.from(text34),ptr=native.
32035
+ th YAML frontmatter with its exact name and English description, then workflow instructions. Include its Vietnamese display name and description in the package labels. Only reference servers selected below. Do not invent tool identifiers.","Leave the icon field unset. Limix Bot assigns it locally.",JSON.stringify({description:description2,allowedServers:servers})].join(`
32036
+ `),raw=await generate3(botId2,prompt,abort.signal);if(!raw)return json7(res,503,{error:"No text-generation engine is available for this bot"});let candidate=raw.trim().replace(/^\x60\x60\x60(?:json)?\s*\n/i,"").replace(/\n\x60\x60\x60$/,"");if(Buffer.byteLength(candidate)>512*1024)throw Error();let draft=JSON.parse(candidate);if(!draft||typeof draft!="object"||Array.isArray(draft))throw Error();let{icon:_generatedIcon,...fields3}=draft,manifest=manifestSchema3.parse(fields3);if(manifest.source||
32037
+ manifest.components.mcpServers.some(s4=>!servers.includes(s4)))throw Error();let icon2=inferPluginServiceIcon(manifest.name.vi,manifest.name.en,manifest.id)??inferPluginServiceIcon(description2,...manifest.components.mcpServers)??inferPluginIcon(description2,manifest.name.vi,manifest.name.en,manifest.id);return json7(res,200,{manifest:{...manifest,icon:icon2}})}catch{return json7(res,422,{error:"The engine could not produce a valid draft"})}finally{busy.delete(botId2)}}}init_zod();import{readFileSync as readFileSync192}from"node:fs";var MIN_FRAME=64*1024,MAX_FRAME3=16*1024*1024;var retrievalDecoder,compiled;function createDecoder(){try{return compiled??=new WebAssembly.Module(readFileSync192(limixNativeResource("limix_tool_gateway.wasm"))),new WebAssembly.Instance(compiled).exports}catch{return null}}var passageKey;function nativePassages(key7,normalized2,query2){retrievalDecoder===void 0&&(retrievalDecoder=createDecoder());let native=retrievalDecoder;if(!native?.index_passages||!native.find_passages)return;let write4=text34=>{let bytes4=Buffer.from(text34),ptr=native.
32028
32038
  reserve_frame(bytes4.length);new Uint8Array(native.memory.buffer,ptr,bytes4.length).set(bytes4)};try{if(key7!==passageKey){if(passageKey=void 0,write4(normalized2()),!native.index_passages())return;passageKey=key7}write4(query2);let layout=native.find_passages(),[count12,ptr]=new Uint32Array(native.memory.buffer,layout,2);return Array.from(new Uint32Array(native.memory.buffer,ptr,count12))}catch{passageKey=void 0;return}}var words7=line6=>line6.match(/[\p{L}\p{N}]+/gu)??[];function searchPluginResource(key7,text34,query2,native=process.env.LIMIX_PLUGIN_SEARCH!=="typescript"){let lines=text34.split(/\r?\n/),normalize9=line6=>line6.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," "),normalizedQuery=normalize9(query2),hits=native&&text34.length>=8192?nativePassages(key7,()=>lines.map(normalize9).join(`
32029
- `),normalizedQuery):void 0;if(!hits){let terms2=new Set(words7(normalizedQuery));hits=lines.map((line6,index4)=>{let matched=new Set(words7(normalize9(line6)).filter(word=>terms2.has(word)));return{index:index4,score:matched.size}}).filter(hit2=>hit2.score).sort((a,b11)=>b11.score-a.score||a.index-b11.index).slice(0,3).map(hit2=>hit2.index)}return hits.map(index4=>({line:index4+1,text:Array.from(lines[index4]).slice(0,1600).join("")}))}import{createHash as createHash123,createHmac as createHmac9,randomBytes as randomBytes38}from"node:crypto";import{linkSync as linkSync7,readFileSync as readFileSync193,unlinkSync as unlinkSync28,writeFileSync as writeFileSync48}from"node:fs";import{join as join269}from"node:path";import{isDeepStrictEqual as isDeepStrictEqual5}from"node:util";var EXTENSION="io.modelcontextprotocol/skills",MAX_ENTRIES3=1e3,MAX_PAGES3=32,MAX_FILES3=1024,MAX_RESOURCE_BYTES=2*1024*1024,MAX_CACHE_BYTES=8*1024*1024,ephemeralKey=randomBytes38(32),cache4=new Map,cacheBytes=0;function object7(value3){return!!value3&&typeof value3=="object"&&!Array.isArray(value3)}function revisionKey(dataDir){if(!dataDir)return ephemeralKey;let path8=join269(dataDir,"mcp-skills-origin.key"),read4=()=>{let key7=readFileSync193(path8);if(key7.length!==32)throw new Error("Invali\
32039
+ `),normalizedQuery):void 0;if(!hits){let terms2=new Set(words7(normalizedQuery));hits=lines.map((line6,index4)=>{let matched=new Set(words7(normalize9(line6)).filter(word=>terms2.has(word)));return{index:index4,score:matched.size}}).filter(hit2=>hit2.score).sort((a,b11)=>b11.score-a.score||a.index-b11.index).slice(0,3).map(hit2=>hit2.index)}return hits.map(index4=>({line:index4+1,text:Array.from(lines[index4]).slice(0,1600).join("")}))}import{createHash as createHash124,createHmac as createHmac9,randomBytes as randomBytes38}from"node:crypto";import{linkSync as linkSync7,readFileSync as readFileSync193,unlinkSync as unlinkSync28,writeFileSync as writeFileSync48}from"node:fs";import{join as join269}from"node:path";import{isDeepStrictEqual as isDeepStrictEqual5}from"node:util";var EXTENSION="io.modelcontextprotocol/skills",MAX_ENTRIES3=1e3,MAX_PAGES3=32,MAX_FILES3=1024,MAX_RESOURCE_BYTES=2*1024*1024,MAX_CACHE_BYTES=8*1024*1024,ephemeralKey=randomBytes38(32),cache4=new Map,cacheBytes=0;function object7(value3){return!!value3&&typeof value3=="object"&&!Array.isArray(value3)}function revisionKey(dataDir){if(!dataDir)return ephemeralKey;let path8=join269(dataDir,"mcp-skills-origin.key"),read4=()=>{let key7=readFileSync193(path8);if(key7.length!==32)throw new Error("Invali\
32030
32040
  d MCP skill origin key");return key7};try{return read4()}catch(err2){if(err2.code!=="ENOENT")throw err2}let temp2=path8+"."+randomBytes38(16).toString("hex");writeFileSync48(temp2,randomBytes38(32),{mode:384,flag:"wx"});try{linkSync7(temp2,path8)}catch(err2){if(err2.code!=="EEXIST")throw err2}finally{unlinkSync28(temp2)}return read4()}function capabilities(raw){let extensions3=object7(raw.extensions)?raw.extensions:{},config3=extensions3[EXTENSION],resources=object7(raw.resources),skills=resources&&
32031
32041
  object7(config3);return{resources,skills,directoryRead:skills&&config3.directoryRead===!0,tools:object7(raw.tools),prompts:object7(raw.prompts),tasks:object7(extensions3["io.modelcontextprotocol/tasks"])||object7(raw.tasks)}}function hasControl(text34){for(let char of text34){let code=char.charCodeAt(0);if(code<32||code===127)return!0}return!1}function validUri(value3){if(typeof value3!="string"||value3.length>4096||!/^[a-z][a-z\d+.-]*:\/\//i.test(value3))return!1;try{return!hasControl(value3)&&
32032
32042
  !/[?#\\\s]/.test(value3)&&value3.slice(value3.indexOf("://")+3).split("/").every(part2=>{let decoded=decodeURIComponent(part2);return decoded!=="."&&decoded!==".."&&!hasControl(decoded)&&!/[/\\]/.test(decoded)})}catch{return!1}}function entryOf(value3){if(!object7(value3)||!validUri(value3.uri)||!object7(value3.frontmatter))throw new Error("Invalid MCP skill entry");let{uri,frontmatter}=value3,{name:name6,description:description2}=frontmatter;if(typeof name6!="string"||!isSkillName(name6)||!uri.
32033
32043
  endsWith("/"+name6+"/SKILL.md")||typeof description2!="string"||!description2.trim()||description2.length>1024)throw new Error("Invalid MCP skill metadata");let root4=uri.slice(0,-8),files2=null;if(value3.resources!=="dynamic"){if(!Array.isArray(value3.resources)||value3.resources.length>MAX_FILES3)throw new Error("Invalid MCP skill manifest");let seen=new Set;if(files2=value3.resources.map(file2=>{if(!object7(file2)||!validUri(file2.uri)||!file2.uri.startsWith(root4)||file2.uri===root4||seen.has(
32034
32044
  file2.uri)||typeof file2.digest!="string"||!/^sha256:[a-f0-9]{64}$/.test(file2.digest)||typeof file2.size!="number"||!Number.isSafeInteger(file2.size)||file2.size<0)throw new Error("Invalid MCP skill file");return seen.add(file2.uri),{uri:file2.uri,digest:file2.digest,size:file2.size}}),!seen.has(uri))throw new Error("MCP skill manifest is missing SKILL.md");files2.sort((a,b11)=>a.uri<b11.uri?-1:a.uri>b11.uri?1:0)}return{uri,name:name6,description:description2,frontmatter,files:files2,root:root4}}
32035
- function summarize2(entry3,identity9){let{uri,name:name6,description:description2,files:files2}=entry3,revision=files2&&createHash123("sha256").update(canonicalJson([identity9,uri,files2])).digest("hex");return{uri,name:name6,description:description2,revision,fileCount:files2?.length??0}}async function connected(origin2,server3,as3,run12){let identity9=createHmac9("sha256",revisionKey(as3.dataDir)).update(canonicalJson([origin2,server3])).digest("hex"),connection=await openSkillConnection(server3,
32045
+ function summarize2(entry3,identity9){let{uri,name:name6,description:description2,files:files2}=entry3,revision=files2&&createHash124("sha256").update(canonicalJson([identity9,uri,files2])).digest("hex");return{uri,name:name6,description:description2,revision,fileCount:files2?.length??0}}async function connected(origin2,server3,as3,run12){let identity9=createHmac9("sha256",revisionKey(as3.dataDir)).update(canonicalJson([origin2,server3])).digest("hex"),connection=await openSkillConnection(server3,
32036
32046
  AbortSignal.timeout(3e4),as3);try{return await run12(connection,identity9)}finally{await connection.close()}}async function pages2(c,method2,field5,params2){let all3=[],seen=new Set,cursor3,bytes4=0;for(let page=0;page<MAX_PAGES3;page++){let response=await c.request(method2,cursor3===void 0?params2:{...params2,cursor:cursor3});if(!object7(response)||!Array.isArray(response[field5]))throw new Error("Invalid MCP listing");if(all3.length+response[field5].length>MAX_ENTRIES3)throw new Error("MCP lis\
32037
32047
  ting exceeds the item limit");if(bytes4+=Buffer.byteLength(JSON.stringify(response[field5])),bytes4>8*1024*1024)throw new Error("MCP listing exceeds the byte limit");all3.push(...response[field5]);let next=response.nextCursor;if(next===void 0)return all3;if(typeof next!="string"||!next||next.length>4096||seen.has(next))throw new Error("Invalid MCP pagination cursor");cursor3=next,seen.add(next)}throw new Error("MCP listing exceeds the page limit")}async function discoverMcpSkills(origin2,server3,as3={}){
32038
32048
  return connected(origin2,server3,as3,async(client,identity9)=>{let caps=capabilities(client.capabilities),skills=caps.skills?(await pages2(client,"skills/list","skills",{})).map(value3=>summarize2(entryOf(value3),identity9)):[];if(new Set(skills.map(skill=>skill.uri)).size!==skills.length)throw new Error("Duplicate MCP skill URI");return{origin:origin2,capabilities:caps,skills}})}async function listMcpInventory(origin2,server3,kind2,as3={}){return connected(origin2,server3,as3,async client=>{if(!capabilities(
@@ -32040,7 +32050,7 @@ client.capabilities)[kind2])throw new Error("Capability unavailable on this MCP
32040
32050
  description.slice(0,4096)}:{},...kind2==="resources"&&typeof value3.uri=="string"?{uri:value3.uri}:{}}});return{origin:origin2,kind:kind2,items}})}var McpSkillChanged=class extends Error{};async function heldEntry(c,identity9,uri,revision){if(!capabilities(c.capabilities).skills)throw new Error("MCP server does not advertise Skills");if(!validUri(uri)||!uri.endsWith("/SKILL.md")||!/^[a-f0-9]{64}$/.test(revision))throw new Error("Invalid MCP skill selection");let response=await c.request("skills/\
32041
32051
  get",{uri}),entry3=entryOf(object7(response)&&response.skill);if(entry3.uri!==uri||!entry3.files||summarize2(entry3,identity9).revision!==revision)throw new McpSkillChanged("MCP skill changed. Review its current manifest.");return{...entry3,files:entry3.files}}function discard(key7){let file2=cache4.get(key7);file2&&(cacheBytes-=file2.bytes.length,cache4.delete(key7))}async function readFile16(c,file2,key7,limit2){if(file2.size>limit2)throw new Error("MCP skill resource exceeds the size limit");
32042
32052
  let cached6=cache4.get(key7);if(cached6&&cached6.until>Date.now())return cached6.bytes;discard(key7);let response=await c.request("resources/read",{uri:file2.uri});if(!object7(response)||!Array.isArray(response.contents)||response.contents.length!==1)throw new Error("Invalid MCP resource result");let part2=response.contents[0];if(!object7(part2)||part2.uri!==file2.uri||typeof part2.text=="string"==(typeof part2.blob=="string"))throw new Error("Invalid MCP resource content");let bytes4=typeof part2.
32043
- text=="string"?Buffer.from(part2.text):Buffer.from(part2.blob,"base64");if(typeof part2.blob=="string"&&bytes4.toString("base64")!==part2.blob||bytes4.length!==file2.size||"sha256:"+createHash123("sha256").update(bytes4).digest("hex")!==file2.digest)throw new McpSkillChanged("MCP skill resource failed its integrity check");if(typeof response.ttlMs=="number"&&response.ttlMs>0&&Number.isFinite(response.ttlMs)){for(discard(key7);cacheBytes+bytes4.length>MAX_CACHE_BYTES||cache4.size>=256;)discard(cache4.
32053
+ text=="string"?Buffer.from(part2.text):Buffer.from(part2.blob,"base64");if(typeof part2.blob=="string"&&bytes4.toString("base64")!==part2.blob||bytes4.length!==file2.size||"sha256:"+createHash124("sha256").update(bytes4).digest("hex")!==file2.digest)throw new McpSkillChanged("MCP skill resource failed its integrity check");if(typeof response.ttlMs=="number"&&response.ttlMs>0&&Number.isFinite(response.ttlMs)){for(discard(key7);cacheBytes+bytes4.length>MAX_CACHE_BYTES||cache4.size>=256;)discard(cache4.
32044
32054
  keys().next().value);cache4.set(key7,{bytes:bytes4,until:Date.now()+Math.min(response.ttlMs,3e5)}),cacheBytes+=bytes4.length}return bytes4}async function previewMcpSkill(origin2,server3,uri,revision,as3={}){return connected(origin2,server3,as3,async(c,identity9)=>{let entry3=await heldEntry(c,identity9,uri,revision),file2=entry3.files.find(resource=>resource.uri===uri),key7=JSON.stringify([as3.id,identity9,revision,uri]),bytes4=await readFile16(c,file2,key7,262144),text34=new TextDecoder("utf-8",
32045
32055
  {fatal:!0}).decode(bytes4),yaml=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text34),doc=yaml&&parseDocument(yaml[1],{schema:"core",uniqueKeys:!0});if(!doc||doc.errors.length||doc.warnings.length||!isDeepStrictEqual5(doc.toJS({maxAliasCount:0}),entry3.frontmatter))throw discard(key7),new McpSkillChanged("MCP skill frontmatter differs from its manifest");return{origin:origin2,uri,revision,text:text34,name:entry3.name,description:entry3.description,...typeof entry3.frontmatter.license=="string"?{
32046
32056
  license:entry3.frontmatter.license}:{}}})}async function readMcpSkillResource(origin2,server3,uri,revision,resource,as3={}){return connected(origin2,server3,as3,async(c,identity9)=>{let file2=(await heldEntry(c,identity9,uri,revision)).files.find(f3=>f3.uri===resource);if(!file2||resource.endsWith("/SKILL.md"))throw new Error("Select the skill itself or a listed supporting file");let key7=JSON.stringify([as3.id,identity9,revision,resource]),bytes4=await readFile16(c,file2,key7,MAX_RESOURCE_BYTES);
@@ -32054,7 +32064,7 @@ input3.server,input3.uri,input3.revision,preview3.text,preview3.name,preview3.de
32054
32064
  let input3=component.safeParse(body3),denied2={status:403,body:{error:"Component unavailable for this bot and revision"}};if(!input3.success||input3.data.query&&input3.data.kind!=="resources")return denied2;let{plugin_id:id12,sha256:sha2567,kind:kind2,name:name6}=input3.data,read4=()=>hub.readComponent(bot,allowed3(),id12,sha2567,kind2,name6),text34=read4();if(text34===null)return denied2;let source5=hub.remoteSource(id12,sha2567),{file_uri,directory_uri}=input3.data;if((file_uri||directory_uri)&&
32055
32065
  (!source5||kind2!=="skills"))return denied2;if(source5){if(!hub.remoteExecutionApproved(id12,sha2567)||!selectOrigin(source5.server))return denied2;try{let spec=await resolve59(source5.server,bot.id),context3={dataDir,id:bot.id,...startAs};if(!spec)return denied2;let verified=await previewMcpSkill(source5.server,spec,source5.uri,source5.revision,context3);if(text34=read4(),text34===null||verified.text!==text34)return denied2;if(directory_uri||file_uri){if(directory_uri){let list10=await listMcpSkillDirectory(
32056
32066
  source5.server,spec,source5.uri,source5.revision,directory_uri,context3);text34=JSON.stringify(list10.resources)}else{let file2=await readMcpSkillResource(source5.server,spec,source5.uri,source5.revision,file_uri,context3),bytes4=Buffer.from(file2.blob,"base64");if(bytes4.length>256*1024||bytes4.includes(0))return denied2;text34=new TextDecoder("utf-8",{fatal:!0}).decode(bytes4)}if(read4()===null)return denied2}text34=JSON.stringify({type:"external_skill_reference",origin:source5.server,skill:source5.
32057
- uri,resource:file_uri??directory_uri??source5.uri,revision:source5.revision,content:text34})}catch(error66){return error66 instanceof McpSkillChanged&&hub.remoteSource(id12,sha2567)?.revision===source5.revision&&hub.invalidateRemoteSkill(source5.server,source5.uri,source5.revision),denied2}}return input3.data.query&&(text34=JSON.stringify(searchPluginResource(JSON.stringify([sha2567,kind2,name6]),text34,input3.data.query))),{status:200,body:{text:text34}}}init_config3();init_zod();init_atomic();import{createHash as createHash124}from"node:crypto";import{existsSync as existsSync105,readFileSync as readFileSync194}from"node:fs";import{join as join270}from"node:path";var root3="https://raw.githubusercontent.com/leomieo/limix-plugin-hub/main/",slug2=external_exports.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),metadata2=external_exports.object({id:slug2,version:pluginVersion,name:labels2(96),description:labels2(600),requiresMcp:external_exports.array(serverName).max(12)}).strict(),digest5=external_exports.string().regex(/^[a-f0-9]{64}$/),entry2=metadata2.extend({sha256:digest5}),manifestEntry=entry2.extend({id:pluginId,description:labels2(1024),schemaVersion:external_exports.
32067
+ uri,resource:file_uri??directory_uri??source5.uri,revision:source5.revision,content:text34})}catch(error66){return error66 instanceof McpSkillChanged&&hub.remoteSource(id12,sha2567)?.revision===source5.revision&&hub.invalidateRemoteSkill(source5.server,source5.uri,source5.revision),denied2}}return input3.data.query&&(text34=JSON.stringify(searchPluginResource(JSON.stringify([sha2567,kind2,name6]),text34,input3.data.query))),{status:200,body:{text:text34}}}init_config3();init_zod();init_atomic();import{createHash as createHash125}from"node:crypto";import{existsSync as existsSync105,readFileSync as readFileSync194}from"node:fs";import{join as join270}from"node:path";var root3="https://raw.githubusercontent.com/leomieo/limix-plugin-hub/main/",slug2=external_exports.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),metadata2=external_exports.object({id:slug2,version:pluginVersion,name:labels2(96),description:labels2(600),requiresMcp:external_exports.array(serverName).max(12)}).strict(),digest5=external_exports.string().regex(/^[a-f0-9]{64}$/),entry2=metadata2.extend({sha256:digest5}),manifestEntry=entry2.extend({id:pluginId,description:labels2(1024),schemaVersion:external_exports.
32058
32068
  literal("1.0.0"),type:external_exports.enum(["local","hybrid","remote-mcp"])}).refine(row=>!row.id.startsWith("remote."),"Remote skill identifiers are assigned by discovery"),catalog=external_exports.array(external_exports.union([entry2,manifestEntry])).max(500).refine(rows2=>new Set(rows2.map(r=>r.id)).size===rows2.length),bundle2=metadata2.extend({instructions:external_exports.string().trim().min(1).max(8e3)}),assignments={teams:external_exports.array(external_exports.string()),bots:external_exports.
32059
32069
  record(external_exports.string(),external_exports.boolean())},installed2=bundle2.extend({sha256:digest5,...assignments}),legacyDatabase=external_exports.object({catalog,installed:external_exports.array(installed2)}).strict(),savedManifest=external_exports.object({manifest:manifestSchema3,sha256:digest5,catalogSha256:digest5.optional(),evaluation:hurdleEvaluation.optional()}).transform((value3,ctx)=>{let row=reviewManifest(value3.manifest);return row.sha256!==value3.sha256&&ctx.addIssue({code:"cu\
32060
32070
  stom",message:"Manifest digest mismatch"}),{...row,catalogSha256:value3.catalogSha256,evaluation:value3.evaluation}}),savedHybrid=external_exports.object({manifest:manifestSchema3,sha256:digest5,catalogSha256:digest5.optional(),evaluation:hurdleEvaluation.optional(),allowHostExecution:external_exports.boolean().optional(),...assignments}).transform((value3,ctx)=>{let{warnings:_warnings,...row}=reviewManifest(value3.manifest);return row.sha256!==value3.sha256&&ctx.addIssue({code:"custom",message:"\
@@ -32071,7 +32081,7 @@ known.catalogSha256!==catalogSha256){let pending3=state.pending.map(p3=>p3===kno
32071
32081
  filter(p3=>p3.bots[bot.id]===!0).map(p3=>[p3.id,p3.sha256]));return state.installed.filter(p3=>pluginEnabled(p3,bot)&&(!pinned2.has(p3.id)||pinned2.get(p3.id)===p3.sha256)&&(!p3.manifest?.source||p3.allowHostExecution===!0)&&p3.requiresMcp.every(name6=>availableMcp.includes(name6)))}function invalidate(stale){let keep=p3=>!p3.manifest?.source||!stale(p3.manifest.source),installed3=state.installed.filter(keep),pending3=state.pending.filter(keep);if(installed3.length!==state.installed.length||pending3.
32072
32082
  length!==state.pending.length){let events3=[...state.pending,...state.installed].filter(p3=>!keep(p3)).map(p3=>audit("invalidate",p3,"mcp"));save7({...state,installed:installed3,pending:pending3},events3)}}let view3=()=>({...state,...targets()}),route=async({req,res,path:path8,method:method2,auth,json:json7,readBody:readBody2})=>{if(path8!=="/api/limix/plugins")return PASS;if(!ownerOrAdmin(auth)||auth.kind==="loopback"&&auth.companionDevice)return json7(res,403,{error:"forbidden: this session la\
32073
32083
  cks the admin scope"});if(!readable2)return json7(res,503,{error:"The saved plugin library could not be read"});if(method2==="GET")return json7(res,200,view3());if(method2!=="POST")return json7(res,405,{error:"Method not allowed"});let parsed3=change2.safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"Invalid plugin action"});let input3=parsed3.data,actor=auth.kind==="session"?"session:"+auth.session.id:"owner";if(input3.action==="sync")try{let rows2=catalog.parse(JSON.
32074
- parse((await load9("catalog.json",1048576)).toString()));save7({...state,catalog:rows2})}catch{return json7(res,502,{error:"Could not sync the plugin catalog"})}else if(input3.action==="install"){let row=state.catalog.find(r=>r.id===input3.id&&r.sha256===input3.sha256);if(!row)return json7(res,409,{error:"Refresh the catalog and review this version"});try{let bytes4=await load9("plugins/"+row.id+".json",row.schemaVersion?1048576:65536);if(createHash124("sha256").update(bytes4).digest("hex")!==row.
32084
+ parse((await load9("catalog.json",1048576)).toString()));save7({...state,catalog:rows2})}catch{return json7(res,502,{error:"Could not sync the plugin catalog"})}else if(input3.action==="install"){let row=state.catalog.find(r=>r.id===input3.id&&r.sha256===input3.sha256);if(!row)return json7(res,409,{error:"Refresh the catalog and review this version"});try{let bytes4=await load9("plugins/"+row.id+".json",row.schemaVersion?1048576:65536);if(createHash125("sha256").update(bytes4).digest("hex")!==row.
32075
32085
  sha256)throw Error("digest");if(!state.catalog.some(current3=>JSON.stringify(current3)===JSON.stringify(row)))throw Error("stale");let raw=JSON.parse(bytes4.toString("utf8"));if(row.schemaVersion){let manifest=manifestSchema3.parse(raw),index4=packMetadata({...manifest,requiresMcp:manifest.components.mcpServers});if(manifest.source||manifest.type!==row.type||JSON.stringify(index4)!==JSON.stringify(packMetadata(row)))throw Error("metadata");stage(manifest,actor,row.sha256)}else{let pack=bundle2.parse(
32076
32086
  raw);if(JSON.stringify(packMetadata(pack))!==JSON.stringify(packMetadata(row)))throw Error("metadata");if(state.installed.some(p3=>p3.id===row.id&&p3.manifest)||state.pending.some(p3=>p3.id===row.id))return json7(res,409,{error:"Plugin ID already in use"});state.installed.some(p3=>p3.id===row.id&&p3.sha256===row.sha256)||save7({...state,installed:[...state.installed.filter(p3=>p3.id!==row.id),{...pack,sha256:row.sha256,teams:[],bots:{}}]},[audit("install",row,actor)])}}catch{return json7(res,422,
32077
32087
  {error:"Plugin download or integrity check failed"})}}else if(input3.action==="import"){if(input3.manifest.source||input3.manifest.id.startsWith("remote."))return json7(res,422,{error:"Remote provenance requires MCP discovery"});try{stage(input3.manifest,actor)}catch(e){return json7(res,422,{error:e instanceof Error?e.message:"Import failed"})}}else if(input3.action==="attach-evaluation"){let row=state.pending.find(p3=>p3.id===input3.id&&p3.sha256===input3.sha256);if(!row)return json7(res,409,{error:"\
@@ -32083,7 +32093,7 @@ pins"){if(!targets().bots.some(bot=>bot.id===input3.botId))return json7(res,404,
32083
32093
  sign-pins",p3,actor,input3.botId,!0)))}else{let current3=state.installed.find(p3=>p3.id===input3.id&&p3.sha256===input3.sha256);if(!current3)return json7(res,409,{error:"Review the installed version first"});let{bots,teams}=targets(),next=structuredClone(current3);if(input3.target==="bot"){if(!bots.some(b11=>b11.id===input3.key))return json7(res,404,{error:"Unknown bot"});input3.enabled===null?delete next.bots[input3.key]:next.bots[input3.key]=input3.enabled}else{if(!teams.includes(input3.key))return json7(
32084
32094
  res,404,{error:"Unknown team"});next.teams=next.teams.filter(s4=>s4!==input3.key),input3.enabled&&next.teams.push(input3.key)}save7({...state,installed:state.installed.map(p3=>p3.sha256===next.sha256?next:p3.id!==next.id||input3.enabled!==!0?p3:input3.target==="team"?{...p3,teams:p3.teams.filter(team=>team!==input3.key)}:{...p3,bots:{...p3.bots,[input3.key]:!1}})},[audit("assign",next,actor,input3.target+":"+input3.key,input3.enabled)])}return json7(res,200,view3())},approved=(id12,sha2567)=>state.
32085
32095
  installed.find(p3=>p3.id===id12&&p3.sha256===sha2567)?.manifest;return{route,getApproved(id12,sha2567){let m3=approved(id12,sha2567);return m3&&!m3.source?m3:null},remoteSource(id12,sha2567){return approved(id12,sha2567)?.source??null},remoteExecutionApproved(id12,sha2567){return state.installed.some(p3=>p3.id===id12&&p3.sha256===sha2567&&p3.manifest?.source&&p3.allowHostExecution===!0)},hasComponents(bot,availableMcp){return active3(bot,availableMcp).some(p3=>p3.manifest&&pluginContentKinds.some(
32086
- k3=>p3.manifest.components[k3].length>0))},readComponent(bot,availableMcp,id12,sha2567,kind2,name6){return pluginContentKinds.includes(kind2)?active3(bot,availableMcp).find(p3=>p3.id===id12&&p3.sha256===sha2567)?.manifest?.components[kind2].find(p3=>p3.name===name6)?.content??null:null},stageRemote(server3,uri,revision,content4,name6,description2,license){let parsed3=parseSkillMd(content4);if("error"in parsed3||parsed3.name!==name6)throw Error("Invalid remote SKILL.md");let key7=createHash124("s\
32096
+ k3=>p3.manifest.components[k3].length>0))},readComponent(bot,availableMcp,id12,sha2567,kind2,name6){return pluginContentKinds.includes(kind2)?active3(bot,availableMcp).find(p3=>p3.id===id12&&p3.sha256===sha2567)?.manifest?.components[kind2].find(p3=>p3.name===name6)?.content??null:null},stageRemote(server3,uri,revision,content4,name6,description2,license){let parsed3=parseSkillMd(content4);if("error"in parsed3||parsed3.name!==name6)throw Error("Invalid remote SKILL.md");let key7=createHash125("s\
32087
32097
  ha256").update(JSON.stringify([server3,uri])).digest("hex").slice(0,32),manifest=manifestSchema3.parse({schemaVersion:"1.0.0",id:"remote."+key7,version:"1.0.0",name:{en:name6,vi:name6},description:{en:description2,vi:description2},license:license??parsed3.license??"Unspecified",type:"remote-mcp",components:{skills:[{name:name6,description:description2,content:content4}],mcpServers:[server3]},source:{server:server3,uri,revision},localization:{core:"original",interface:"original"}});return invalidate(
32088
32098
  origin2=>origin2.server===server3&&origin2.uri===uri&&origin2.revision!==revision),stage(manifest,"mcp:"+server3),view3()},invalidateRemoteSkill(server3,uri,expectedRevision){invalidate(source5=>source5.server===server3&&source5.uri===uri&&(expectedRevision===void 0||source5.revision===expectedRevision))},invalidateRemoteServer(server3){invalidate(source5=>source5.server===server3)},invalidateRemote(server3,skills){let revisions=new Map(skills.map(skill=>[skill.uri,skill.revision]));invalidate(source5=>source5.
32089
32099
  server===server3&&revisions.has(source5.uri)&&revisions.get(source5.uri)!==source5.revision)},pruneTeams(teams){state.installed.some(p3=>p3.teams.some(team=>!teams.includes(team)))&&save7({...state,installed:state.installed.map(p3=>({...p3,teams:p3.teams.filter(team=>teams.includes(team))}))})},renameTeam(from,to2){state.installed.some(p3=>p3.teams.includes(from))&&save7({...state,installed:state.installed.map(p3=>({...p3,teams:p3.teams.flatMap(team=>team!==from?[team]:to2?[to2]:[])}))})},instructions(bot,availableMcp){
@@ -32105,7 +32115,7 @@ accept===!0){if(!teamMemory2.resolve(section4,m3[1],"accept",body3.expectedRevis
32105
32115
  success)return json7(res,400,{error:"Invalid memory edit"});if(!teamMemory2.update(section4,m3[1],parsed3.data,body3.expectedRevision))return json7(res,404,{error:"no such entry"})}return json7(res,200,{entries:teamMemory2.list(section4),loadedIds:teamMemory2.promptSelection(section4).loadedIds})}catch(error66){return json7(res,error66 instanceof TeamMemoryConflict?409:400,{error:error66 instanceof Error?error66.message:String(error66),...userErrorFields(error66)})}}if(path8==="/api/section-cont\
32106
32116
  ext"&&(method2==="GET"||method2==="PUT")){if(!url3.searchParams.has("section"))return json7(res,400,{error:"section is required"});let requested=url3.searchParams.get("section")??"",section4=sectionContextKey(requested);if(section4.length>60)return json7(res,400,{error:"section must be at most 60 characters"});if(!(section4===""||store5.sections.includes(section4)||store5.bots.some(bot=>!bot.hidden&&sectionKey2(bot.section)===section4)||store5.groups.some(group2=>sectionKey2(group2.section)===section4)))
32107
32117
  return json7(res,404,userError("serverError.department.missing"));if(method2==="GET"){let context4=readSectionContext(section4);return json7(res,200,{section:section4,label:sectionContextLabel(section4),text:context4?.text??"",updatedAt:context4?.updatedAt??null,maxBytes:SECTION_CONTEXT_MAX_BYTES})}let parsed3=external_exports.object({text:external_exports.string()}).safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"text must be a string"});if(Buffer.byteLength(parsed3.
32108
- data.text,"utf8")>SECTION_CONTEXT_MAX_BYTES)return json7(res,400,{error:`section context is capped at ${SECTION_CONTEXT_MAX_BYTES/1e3}KB`});let context3=writeSectionContext(section4,parsed3.data.text);return json7(res,200,{ok:!0,section:section4,label:sectionContextLabel(section4),text:context3?.text??"",updatedAt:context3?.updatedAt??null,maxBytes:SECTION_CONTEXT_MAX_BYTES})}return PASS}}init_zod();import{createHash as createHash125}from"node:crypto";import{readFileSync as readFileSync195}from"node:fs";import{join as join271}from"node:path";var GOES_WELL_WITH={gmail:["googlecalendar","googledrive","slack"],googlecalendar:["gmail","googlemeet","slack"],googledrive:["googledocs","googlesheets","gmail"],googledocs:["googledrive","googlesheets","notion"],googlesheets:["googledrive","airtable","gmail"],outlook:["one_drive","microsoft_teams","slack"],slack:["gmail","notion","linear"],discord:["github","notion","googlecalendar"],github:["linear","slack","notion"],gitlab:["linear","slack","jira"],linear:["github","slack","notion"],jira:["c\
32118
+ data.text,"utf8")>SECTION_CONTEXT_MAX_BYTES)return json7(res,400,{error:`section context is capped at ${SECTION_CONTEXT_MAX_BYTES/1e3}KB`});let context3=writeSectionContext(section4,parsed3.data.text);return json7(res,200,{ok:!0,section:section4,label:sectionContextLabel(section4),text:context3?.text??"",updatedAt:context3?.updatedAt??null,maxBytes:SECTION_CONTEXT_MAX_BYTES})}return PASS}}init_zod();import{createHash as createHash126}from"node:crypto";import{readFileSync as readFileSync195}from"node:fs";import{join as join271}from"node:path";var GOES_WELL_WITH={gmail:["googlecalendar","googledrive","slack"],googlecalendar:["gmail","googlemeet","slack"],googledrive:["googledocs","googlesheets","gmail"],googledocs:["googledrive","googlesheets","notion"],googlesheets:["googledrive","airtable","gmail"],outlook:["one_drive","microsoft_teams","slack"],slack:["gmail","notion","linear"],discord:["github","notion","googlecalendar"],github:["linear","slack","notion"],gitlab:["linear","slack","jira"],linear:["github","slack","notion"],jira:["c\
32109
32119
  onfluence","github","slack"],sentry:["github","linear","slack"],posthog:["github","linear","slack"],notion:["slack","googledrive","linear"],airtable:["slack","googlesheets","notion"],asana:["slack","googlecalendar","gmail"],trello:["slack","googlecalendar","gmail"],hubspot:["gmail","slack","googlecalendar"],salesforce:["gmail","slack","googlesheets"],stripe:["hubspot","slack","googlesheets"],shopify:["stripe","mailchimp","googlesheets"],dropbox:["gmail","slack","notion"],figma:["linear","slack",
32110
32120
  "notion"],zoom:["googlecalendar","slack","gmail"]},STARTER_APPS=["gmail","googlecalendar","slack","notion","googledrive","github","googlesheets","linear","hubspot","airtable","jira","asana","trello","dropbox","zoom","stripe"],SUGGESTED_SECTION_SIZE=6;var WANTED_FIRST_MAX=3,NOISE_WORDS=new Set(["a","an","app","apps","and","connect","for","i","in","my","need","of","on","or","something","that","the","to","tool","tools","want","with"]),partnersOf=slug4=>Object.hasOwn(GOES_WELL_WITH,slug4)?GOES_WELL_WITH[slug4]:[];function pairings(connected2){let votes=new Map;for(let app of connected2)partnersOf(app).forEach((partner,position3)=>votes.set(partner,(votes.get(partner)??0)+3-position3));return[...votes].sort((a,b11)=>b11[1]-a[1]).map(([slug4])=>slug4)}
32111
32121
  function rankAppSuggestions(input3){let bySlug=new Map(input3.catalog.map(card=>[card.slug,card])),held4=new Set([...input3.held,...input3.connected,...input3.about?[input3.about]:[]]),offerable=slug4=>{let card=bySlug.get(slug4);return!!card&&!card.noAuth&&!held4.has(slug4)&&(input3.allowed?.(slug4)??!0)},ordered=[...(input3.wanted??[]).filter(offerable).slice(0,WANTED_FIRST_MAX),...input3.picks??[],...input3.about?partnersOf(input3.about):[],...pairings(input3.connected),...STARTER_APPS];return[
@@ -32122,19 +32132,19 @@ return;let candidates=rankAppSuggestions({catalog:here.cards,connected:here.conn
32122
32132
  finally(()=>{picking=null}),await picking,suggest({limit:limit2})},async find(input3){let here=await reading();if(!here)return"The list of apps can't be read right now. Try again in a minute.";let matches3=searchCatalog(here.cards,input3.query,FIND_LIMIT*3),scope=input3.bot.connectorScopes,usable=matches3.filter(card=>(!scope||scope.apps[card.slug])&&!input3.refusal(card.slug)).slice(0,FIND_LIMIT);if(!usable.length)return(matches3[0]?input3.refusal(matches3[0].slug):null)??`No app that can be co\
32123
32133
  nnected here matches "${clean(input3.query,120)}". Try other words.`;let connected2=new Set(here.connected),missing2=usable.filter(card=>!connected2.has(card.slug)&&!card.noAuth);for(let card of missing2.slice(0,FIND_NOTED).reverse())noteWanted(card.slug);let standing=card=>connected2.has(card.slug)?"connected":card.noAuth?"no sign-in needed":"not connected";return[`Apps matching "${clean(input3.query,120)}":`,...usable.map(card=>`- ${card.slug}: ${clean(card.label,80)} (${standing(card)}). ${clean(
32124
32134
  card.blurb,120)}`),'To show the person a card that connects one, call this tool again with toolkits: ["<slug>"], using a slug listed here.'].join(`
32125
- `)}}}function pickKey(connected2,bots){let people=bots.map(bot=>[bot.name,bot.role??""]).sort((a,b11)=>a.join().localeCompare(b11.join()));return createHash125("sha256").update(JSON.stringify([connected2,people])).digest("hex")}var MAX_LIMIT2=20,MAX_QUERY2=200;function createAppSuggestionRoutes(host3){return async({res,url:url3,path:path8,method:method2,json:json7})=>{if(method2==="GET"&&path8==="/api/connectors/suggestions"){let limit2=Number(url3.searchParams.get("limit")),botId2=url3.searchParams.get("botId")??void 0,about=url3.searchParams.get("for")?.trim().toLowerCase()||void 0;return json7(res,200,await host3.suggest({limit:Number.isInteger(limit2)&&limit2>0?Math.min(limit2,MAX_LIMIT2):SUGGESTED_SECTION_SIZE,...botId2?
32135
+ `)}}}function pickKey(connected2,bots){let people=bots.map(bot=>[bot.name,bot.role??""]).sort((a,b11)=>a.join().localeCompare(b11.join()));return createHash126("sha256").update(JSON.stringify([connected2,people])).digest("hex")}var MAX_LIMIT2=20,MAX_QUERY2=200;function createAppSuggestionRoutes(host3){return async({res,url:url3,path:path8,method:method2,json:json7})=>{if(method2==="GET"&&path8==="/api/connectors/suggestions"){let limit2=Number(url3.searchParams.get("limit")),botId2=url3.searchParams.get("botId")??void 0,about=url3.searchParams.get("for")?.trim().toLowerCase()||void 0;return json7(res,200,await host3.suggest({limit:Number.isInteger(limit2)&&limit2>0?Math.min(limit2,MAX_LIMIT2):SUGGESTED_SECTION_SIZE,...botId2?
32126
32136
  {botId:botId2}:{},...about?{about}:{}}))}return method2==="POST"&&path8==="/api/connectors/suggestions/pick"?json7(res,200,await host3.pick(SUGGESTED_SECTION_SIZE)):PASS}}function createAppFindRoute(deps){return async({res,path:path8,method:method2,json:json7})=>{if(method2!=="POST"||path8!=="/api/internal/connectors/find")return PASS;let body3=await deps.readBody(),query2=typeof body3?.query=="string"?body3.query.trim().slice(0,MAX_QUERY2):"";if(!query2)return json7(res,400,{error:"find must sa\
32127
32137
  y what the app is for."});let bot=deps.bot(deps.botId);return bot?json7(res,200,{text:await deps.host.find({query:query2,bot,refusal:deps.refusal})}):json7(res,409,{error:"connected apps are not enabled for this bot"})}}init_user_errors();init_config();var MAX_KEY_LENGTH=512;function createDeciderRoutes(deps){let models=deps.models??createOpenRouterModelCatalog();return async({req,res,path:path8,method:method2,json:json7,readBody:readBody2})=>{if(path8==="/api/decider/models"&&method2==="GET")return res.setHeader("cache-control","no-store"),json7(res,200,await models.load(deps.config().decider?.openrouterBaseUrl));if(path8!=="/api/decider/test"||method2!=="POST")return PASS;let body3=await readBody2(req,8192);if(body3?.key!==void 0&&typeof body3.
32128
32138
  key!="string")return json7(res,400,{error:"key must be a string"});let draft=typeof body3?.key=="string"?body3.key.trim():"";if(draft.length>MAX_KEY_LENGTH)return json7(res,400,{error:"That does not look like an API key."});res.setHeader("cache-control","no-store");let provider=body3?.provider==="jev"||body3?.provider==="openrouter"||body3?.provider==="workersai"?body3.provider:void 0;if(body3?.accountId!==void 0&&(typeof body3.accountId!="string"||!WORKERS_AI_ACCOUNT_ID.test(body3.accountId.trim())))
32129
32139
  return json7(res,400,userError("serverError.decider.accountId"));let accountId=typeof body3?.accountId=="string"?body3.accountId.trim():void 0;if(body3?.model!==void 0&&(typeof body3.model!="string"||body3.model.length>OPENROUTER_MODEL_ID_MAX))return json7(res,400,{error:"model must be an OpenRouter model id"});let model4=typeof body3?.model=="string"&&body3.model.trim()?body3.model.trim():void 0,api=body3?.api==="decisions"||body3?.api==="chat"?body3.api:void 0,result2=await deps.decider.testKey(
32130
32140
  {...draft?{key:draft}:{},...provider?{provider}:{},...model4?{model:model4}:{},...api?{api}:{},...accountId?{accountId}:{}}),read4=!draft&&(!provider||provider==="workersai")&&deps.extractor?await deps.extractor.testKey():null,extraction=read4&&!(read4.ok===!1&&read4.reason==="no_key")?{extraction:read4.ok?{ok:!0}:{ok:!1,reason:read4.reason,...read4.status?{status:read4.status}:{}}}:{};return result2.ok?json7(res,200,{ok:!0,latencyMs:result2.latencyMs,...extraction}):json7(res,200,{ok:!1,reason:result2.
32131
- reason,...result2.status?{status:result2.status}:{},...extraction})}}init_zod();init_bot_avatar();init_zod();import{createHash as createHash126,randomUUID as randomUUID81}from"node:crypto";import{createReadStream as createReadStream10}from"node:fs";import{link as link4,lstat as lstat12,mkdir as mkdir15,open as open13,readdir as readdir13,rename as rename7,stat as stat14,unlink as unlink7}from"node:fs/promises";import{statfsSync as statfsSync4}from"node:fs";import{dirname as dirname85,join as join272}from"node:path";var FILE_PART_BYTES=8*1024*1024,MAX_FILES4=2e5,PARTIAL_MAX_AGE_MS=1440*60*1e3,SHA3=/^[a-f0-9]{64}$/u,PLACE2=/^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/./u,CARRIED_OTHERWISE=/^workspaces\/[\w-]{1,128}\/(?:MEMORY\.md$|memory(?:\/|$)|skills(?:\/|$))|^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/\.(?:claude|agents|grok)(?:\/|$)/u;function movedFilePath(path8){return PLACE2.test(path8)&&validRelative(path8)&&!CARRIED_OTHERWISE.test(path8)&&
32132
- !omittedFromWorkspaceBackup(path8)&&!path8.split("/").includes("node_modules")}var hashes=new Map;async function fileSha256(full,size3,mtimeMs){let key7=`${full}\0${size3}\0${mtimeMs}`,known=hashes.get(key7);if(known)return known;let hash4=createHash126("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);let digest6=hash4.digest("hex");return hashes.size>=MAX_FILES4&&hashes.delete(hashes.keys().next().value),hashes.set(key7,digest6),digest6}async function listBotFiles(dataDir,botIds){
32141
+ reason,...result2.status?{status:result2.status}:{},...extraction})}}init_zod();init_bot_avatar();init_zod();import{createHash as createHash127,randomUUID as randomUUID81}from"node:crypto";import{createReadStream as createReadStream10}from"node:fs";import{link as link4,lstat as lstat12,mkdir as mkdir15,open as open13,readdir as readdir13,rename as rename7,stat as stat14,unlink as unlink7}from"node:fs/promises";import{statfsSync as statfsSync4}from"node:fs";import{dirname as dirname85,join as join272}from"node:path";var FILE_PART_BYTES=8*1024*1024,MAX_FILES4=2e5,PARTIAL_MAX_AGE_MS=1440*60*1e3,SHA3=/^[a-f0-9]{64}$/u,PLACE2=/^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/./u,CARRIED_OTHERWISE=/^workspaces\/[\w-]{1,128}\/(?:MEMORY\.md$|memory(?:\/|$)|skills(?:\/|$))|^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/\.(?:claude|agents|grok)(?:\/|$)/u;function movedFilePath(path8){return PLACE2.test(path8)&&validRelative(path8)&&!CARRIED_OTHERWISE.test(path8)&&
32142
+ !omittedFromWorkspaceBackup(path8)&&!path8.split("/").includes("node_modules")}var hashes=new Map;async function fileSha256(full,size3,mtimeMs){let key7=`${full}\0${size3}\0${mtimeMs}`,known=hashes.get(key7);if(known)return known;let hash4=createHash127("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);let digest6=hash4.digest("hex");return hashes.size>=MAX_FILES4&&hashes.delete(hashes.keys().next().value),hashes.set(key7,digest6),digest6}async function listBotFiles(dataDir,botIds){
32133
32143
  let out=[],walk6=async relative30=>{let names5;try{names5=(await readdir13(join272(dataDir,relative30))).sort()}catch{return}for(let name6 of names5){if(out.length>=MAX_FILES4)return;let path8=`${relative30}/${name6}`,info2=await lstat12(join272(dataDir,path8)).catch(()=>null);if(!(!info2||name6==="node_modules")){if(info2.isDirectory()){!CARRIED_OTHERWISE.test(`${path8}/`)&&!omittedFromWorkspaceBackup(path8)&&await walk6(path8);continue}info2.isFile()&&movedFilePath(path8)&&out.push({path:path8,
32134
32144
  size:info2.size,sha256:await fileSha256(join272(dataDir,path8),info2.size,info2.mtimeMs)})}}};for(let id12 of botIds)/^[\w-]{1,128}$/u.test(id12)&&(await walk6(`workspaces/${id12}`),await walk6(`task-workspaces/${id12}`));return out}function space(dataDir){try{let disk=statfsSync4(dataDir,{bigint:!0}),clamp4=value3=>value3>BigInt(Number.MAX_SAFE_INTEGER)?Number.MAX_SAFE_INTEGER:Number(value3);return{freeBytes:clamp4(disk.bavail*disk.bsize),volumeBytes:clamp4(disk.blocks*disk.bsize)}}catch{return null}}
32135
32145
  var staging=dataDir=>join272(dataDir,"tmp","move-files"),partialPath=(dataDir,sha2567,size3)=>join272(staging(dataDir),`${sha2567}-${size3}.partial`);async function tidyPartials(dataDir,now2=Date.now()){let folder3=staging(dataDir);for(let name6 of await readdir13(folder3).catch(()=>[])){if(!name6.endsWith(".partial"))continue;let info2=await stat14(join272(folder3,name6)).catch(()=>null);info2&&now2-info2.mtimeMs>PARTIAL_MAX_AGE_MS&&await unlink7(join272(folder3,name6)).catch(()=>{})}}function rawBody(req,limit2){
32136
32146
  return new Promise((resolve59,reject)=>{let chunks=[],bytes4=0;req.on("data",chunk=>{bytes4+=chunk.length,bytes4<=limit2&&chunks.push(chunk)}),req.on("end",()=>resolve59(bytes4>limit2?null:Buffer.concat(chunks))),req.on("error",reject)})}async function realFolders(dataDir,path8){let at8=dataDir;for(let part2 of dirname85(path8).split("/")){at8=join272(at8,part2);let info2=await lstat12(at8).catch(()=>null);if(!info2)await mkdir15(at8,{mode:448}).catch(()=>{});else if(!info2.isDirectory()||info2.
32137
- isSymbolicLink())return!1}return(await lstat12(at8).catch(()=>null))?.isDirectory()===!0}async function sha256Of(full){try{let hash4=createHash126("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);return hash4.digest("hex")}catch{return null}}var putSchema=external_exports.object({path:external_exports.string().max(4096),size:external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),sha256:external_exports.string().regex(SHA3),offset:external_exports.
32147
+ isSymbolicLink())return!1}return(await lstat12(at8).catch(()=>null))?.isDirectory()===!0}async function sha256Of(full){try{let hash4=createHash127("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);return hash4.digest("hex")}catch{return null}}var putSchema=external_exports.object({path:external_exports.string().max(4096),size:external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),sha256:external_exports.string().regex(SHA3),offset:external_exports.
32138
32148
  coerce.number().int().min(0),mode:external_exports.enum(["new","replace"]),expect:external_exports.string().regex(SHA3).optional()}),partSchema=external_exports.object({path:external_exports.string().max(4096),offset:external_exports.coerce.number().int().min(0),length:external_exports.coerce.number().int().min(1).max(FILE_PART_BYTES)});async function readPart(dataDir,{path:path8,offset:offset4,length:length3}){let at8=dataDir;for(let part2 of path8.split("/")){at8=join272(at8,part2);let info2=await lstat12(
32139
32149
  at8).catch(()=>null);if(!info2||info2.isSymbolicLink())return null}let handle2=await open13(at8,"r").catch(()=>null);if(!handle2)return null;try{let buffer=Buffer.alloc(length3),{bytesRead}=await handle2.read(buffer,0,length3,offset4);return buffer.subarray(0,bytesRead)}finally{await handle2.close()}}async function takePart(deps,req,query2){let{path:path8,size:size3,sha256:sha2567,offset:offset4,mode,expect:expect2}=query2,botId2=/^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path8)?.[1];
32140
32150
  if(!movedFilePath(path8)||!botId2)return{status:400,body:{error:"not a bot file a move carries"}};if(!deps.bots().some(bot=>bot.id===botId2))return{status:409,body:{error:"This file's bot is not on My Cloud yet."}};let partial2=partialPath(deps.dataDir,sha2567,size3);await mkdir15(staging(deps.dataDir),{recursive:!0,mode:448});let held4=(await stat14(partial2).catch(()=>null))?.size??0;if(offset4!==held4)return await rawBody(req,0),{status:409,body:{received:held4}};let bytes4=await rawBody(req,
@@ -32145,9 +32155,9 @@ if(res.setHeader("cache-control","no-store"),method2==="GET"&&url3.searchParams.
32145
32155
  json7(res,200,{v:1,files:await listBotFiles(deps.dataDir,deps.bots().map(bot=>bot.id)),space:space(deps.dataDir)}),!0;if(method2!=="POST")return json7(res,405,{error:"method not allowed"}),!0;if(!deps.owner(auth))return await rawBody(req,0),json7(res,403,{error:"Only My Cloud's owner can move files into it."}),!0;let query2=putSchema.safeParse(Object.fromEntries(url3.searchParams));if(!query2.success)return await rawBody(req,0),json7(res,400,{error:"send ?path, size, sha256, offset and mode"}),!0;
32146
32156
  let answer2=await takePart(deps,req,query2.data);return json7(res,answer2.status,answer2.body),!0}init_zod();var LEASE_MS=10*6e4,askSchema2=external_exports.object({v:external_exports.literal(1),holder:external_exports.string().regex(/^[\w-]{8,128}$/u),label:external_exports.string().max(120).optional(),release:external_exports.literal(!0).optional()});function createMoveLeases(now2=Date.now){let held4=null;return{ask(holder,label4){return held4&&held4.holder!==holder&&held4.until>now2()?held4:(held4={holder,label:label4||(held4?.holder===holder?held4.label:""),until:now2()+LEASE_MS},null)},
32147
32157
  release(holder){held4?.holder===holder&&(held4=null)},held:()=>held4&&held4.until>now2()?held4:null}}async function moveLeaseRoute(deps,{req,res,path:path8,method:method2,auth,json:json7,readBody:readBody2}){if(path8!=="/api/cloud-send/lease")return!1;if(res.setHeader("cache-control","no-store"),method2!=="POST")return json7(res,405,{error:"method not allowed"}),!0;if(!deps.owner(auth))return req.resume(),json7(res,403,{error:"Only My Cloud's owner can move into it."}),!0;let asked=askSchema2.safeParse(
32148
- await readBody2(req,4096));if(!asked.success)return json7(res,400,{error:"send { v: 1, holder, label }"}),!0;let{holder,label:label4="",release:release3}=asked.data;if(release3)return deps.leases.release(holder),json7(res,200,{v:1,held:!1}),!0;let other=deps.leases.ask(holder,label4.trim());return other?(json7(res,409,{v:1,held:!1,label:other.label,until:other.until}),!0):(json7(res,200,{v:1,held:!0,until:deps.leases.held()?.until??null}),!0)}init_zod();import{createHash as createHash127}from"node:crypto";import{lstatSync as lstatSync48,readdirSync as readdirSync61,readFileSync as readFileSync196}from"node:fs";import{hostname as hostname8}from"node:os";import{join as join273}from"node:path";var SHARED_ROOT="/omb-data",FINISHED=new Set(["completed","failed","cancelled","missed"]),KIND_BODY_MAX2=8*1024*1024,ROUTINE_FIELDS=["name","prompt","target","botId","groupId","runOn","schedule","durationMinutes","timeoutMinutes","attachments","continuity","modelSelection","overlap","runOnStartup","sourceThreadId","resultsThreadId","createdAt","checks","access","deliver"],CALL_FIELDS=["name","description","botIds","schedule","durationMinutes","attachments","roomId","createdAt"],WEBHOOK_FIELDS2=[
32158
+ await readBody2(req,4096));if(!asked.success)return json7(res,400,{error:"send { v: 1, holder, label }"}),!0;let{holder,label:label4="",release:release3}=asked.data;if(release3)return deps.leases.release(holder),json7(res,200,{v:1,held:!1}),!0;let other=deps.leases.ask(holder,label4.trim());return other?(json7(res,409,{v:1,held:!1,label:other.label,until:other.until}),!0):(json7(res,200,{v:1,held:!0,until:deps.leases.held()?.until??null}),!0)}init_zod();import{createHash as createHash128}from"node:crypto";import{lstatSync as lstatSync48,readdirSync as readdirSync61,readFileSync as readFileSync196}from"node:fs";import{hostname as hostname8}from"node:os";import{join as join273}from"node:path";var SHARED_ROOT="/omb-data",FINISHED=new Set(["completed","failed","cancelled","missed"]),KIND_BODY_MAX2=8*1024*1024,ROUTINE_FIELDS=["name","prompt","target","botId","groupId","runOn","schedule","durationMinutes","timeoutMinutes","attachments","continuity","modelSelection","overlap","runOnStartup","sourceThreadId","resultsThreadId","createdAt","checks","access","deliver"],CALL_FIELDS=["name","description","botIds","schedule","durationMinutes","attachments","roomId","createdAt"],WEBHOOK_FIELDS2=[
32149
32159
  "name","prompt","botId","runOn","delivery","groupId","eventTypes","maxPendingRuns","resultsThreadId","createdAt"],APP_EVENT_FIELDS=["name","prompt","botId","runOn","app","event","accountId","config","filter","sourceThreadId"],TEXTS=["prompt","description","output","error"],MOVE_BOT_FIELDS=Object.values(MOVE_BOT_PARTS).flat(),record29=value3=>value3!==null&&typeof value3=="object"&&!Array.isArray(value3),pick7=(source5,names5)=>Object.fromEntries(names5.filter(name6=>source5[name6]!==void 0).map(
32150
- name6=>[name6,structuredClone(source5[name6])])),sha2566=value3=>createHash127("sha256").update(value3).digest("hex"),hashOf=value3=>sha2566(canonicalJson(value3).replaceAll("\\\\","/")).slice(0,24);function rebased(value3,from,to2){let copy6=structuredClone(value3),paths2=restorePaths(from,to2);paths2.fields(copy6);for(let key7 of TEXTS)typeof copy6[key7]=="string"&&(copy6[key7]=paths2.text(copy6[key7]));return copy6}var definitionHash=(value3,names5,dataDir)=>hashOf(rebased(pick7(value3,names5),
32160
+ name6=>[name6,structuredClone(source5[name6])])),sha2566=value3=>createHash128("sha256").update(value3).digest("hex"),hashOf=value3=>sha2566(canonicalJson(value3).replaceAll("\\\\","/")).slice(0,24);function rebased(value3,from,to2){let copy6=structuredClone(value3),paths2=restorePaths(from,to2);paths2.fields(copy6);for(let key7 of TEXTS)typeof copy6[key7]=="string"&&(copy6[key7]=paths2.text(copy6[key7]));return copy6}var definitionHash=(value3,names5,dataDir)=>hashOf(rebased(pick7(value3,names5),
32151
32161
  dataDir,SHARED_ROOT));function finishedRuns(routines2,routineId2){return routines2.listRuns().filter(run12=>run12.routineId===routineId2&&FINISHED.has(run12.status)&&run12.triggerSource!=="webhook")}function importedSkillFiles(name6){let root4=join273(IMPORTED_SKILLS_DIR,name6),files2=[],skillMd=null,walk6=(folder3,prefix,depth2)=>{if(depth2>8)return!1;for(let entry3 of readdirSync61(folder3).sort()){let full=join273(folder3,entry3),path8=prefix?`${prefix}/${entry3}`:entry3,info2=lstatSync48(full);
32152
32162
  if(info2.isDirectory()){if(!walk6(full,path8,depth2+1))return!1;continue}if(!info2.isFile())return!1;let content4=readFileSync196(full,"utf8");path8==="SKILL.md"?skillMd=content4:files2.push({path:path8,content:content4,executable:(info2.mode&64)!==0})}return!0};try{if(!walk6(root4,"",0))return null}catch{return null}return skillMd===null?null:{skillMd,files:files2}}function importedSkillHash(skill){let lines=[`SKILL.md ${sha2566(skill.skillMd)}`,...[...skill.files].sort((a,b11)=>a.path.localeCompare(
32153
32163
  b11.path)).map(file2=>`${file2.executable?"x":"-"} ${file2.path} ${sha2566(file2.content)}`)];return sha2566(lines.join(`
@@ -32185,9 +32195,9 @@ s being replaced."),held4&&held4.sha256!==sha2566(text34)&&held4.reviewState!==e
32185
32195
  string().max(120).optional(),sourceDefault:external_exports.boolean().optional()});function thisComputerName(){return(process.env.OMB_ENVIRONMENT_LABEL?.trim()||hostname8()).replace(/\.local$/iu,"").slice(0,120)}async function moveKindsRoute(deps,{req,res,path:path8,method:method2,url:url3,auth,json:json7,readBody:readBody2}){if(path8!=="/api/cloud-send/kind")return!1;res.setHeader("cache-control","no-store");try{if(method2==="GET"){let key7=parseKey(url3.searchParams.get("key")),found2=key7&&kindRecord(
32186
32196
  deps,key7.kind,key7.id);return found2?json7(res,200,{v:1,dataDir:deps.dataDir,...key7.kind==="bot"?{computer:thisComputerName()}:{},...found2}):json7(res,404,{error:"not here"}),!0}if(method2==="PUT"){let owner2=deps.owner(auth);if(!owner2)return json7(res,403,{error:"Only My Cloud's owner can move things into it."}),!0;let body3=putSchema2.safeParse(await readBody2(req,KIND_BODY_MAX2)),key7=body3.success?parseKey(body3.data.key):null;return!body3.success||!key7?(json7(res,400,{error:"send { v: \
32187
32197
  1, key, dataDir, record }"}),!0):(await adopt2(deps,key7.kind,key7.id,body3.data.record,body3.data.runs,body3.data.dataDir,owner2,{computer:body3.data.computer,defaultBot:body3.data.sourceDefault}),json7(res,200,{v:1,ok:!0}),!0)}if(method2==="DELETE"){let key7=parseKey(url3.searchParams.get("key"));return key7?.kind!=="app-event"?(json7(res,400,{error:"only an app event My Cloud now collects is let go of here"}),!0):(json7(res,200,{v:1,removed:await(deps.appEvents()?.remove(key7.id)??!1)}),!0)}json7(
32188
- res,405,{error:"method not allowed"})}catch(error66){let status5=error66 instanceof Refused||Number.isInteger(error66.status)?error66.status:500;json7(res,status5,{error:error66.message?.slice(0,300)||"It could not be moved.",...error66 instanceof Refused&&error66.final?{final:!0}:{}})}return!0}init_zod();import{createHash as createHash128}from"node:crypto";var MEMORY_BODY_MAX=16*1024*1024,JOURNAL_ROWS=500,FRONTMATTER=/^---\n[\s\S]*?\n---\n/u;function blocks(text34){let lines=text34.split(`
32198
+ res,405,{error:"method not allowed"})}catch(error66){let status5=error66 instanceof Refused||Number.isInteger(error66.status)?error66.status:500;json7(res,status5,{error:error66.message?.slice(0,300)||"It could not be moved.",...error66 instanceof Refused&&error66.final?{final:!0}:{}})}return!0}init_zod();import{createHash as createHash129}from"node:crypto";var MEMORY_BODY_MAX=16*1024*1024,JOURNAL_ROWS=500,FRONTMATTER=/^---\n[\s\S]*?\n---\n/u;function blocks(text34){let lines=text34.split(`
32189
32199
  `),entries4=new Map(parseMemoryEntries(text34).map(entry3=>[entry3.line,entry3])),out=[];for(let line6=0;line6<lines.length;){let entry3=entries4.get(line6);if(entry3){out.push({text:lines.slice(entry3.line,entry3.end).join(`
32190
- `),identity:`e:${factIdentity(entry3.body)}`}),line6=entry3.end;continue}lines[line6].trim()&&out.push({text:lines[line6],identity:`l:${factIdentity(lines[line6].replace(/~~/gu,""))}`}),line6+=1}return out}function memoryLines(text34){let body3=text34.replace(FRONTMATTER,"");return[...new Set(blocks(body3).map(block=>createHash128("sha256").update(block.identity).digest("hex").slice(0,12)))]}function mergeMemoryText(theirs,mine){if(!theirs.trim())return mine;let front=FRONTMATTER.exec(mine)?.[0]??
32200
+ `),identity:`e:${factIdentity(entry3.body)}`}),line6=entry3.end;continue}lines[line6].trim()&&out.push({text:lines[line6],identity:`l:${factIdentity(lines[line6].replace(/~~/gu,""))}`}),line6+=1}return out}function memoryLines(text34){let body3=text34.replace(FRONTMATTER,"");return[...new Set(blocks(body3).map(block=>createHash129("sha256").update(block.identity).digest("hex").slice(0,12)))]}function mergeMemoryText(theirs,mine){if(!theirs.trim())return mine;let front=FRONTMATTER.exec(mine)?.[0]??
32191
32201
  "",known=new Set(blocks(theirs.replace(FRONTMATTER,"")).map(block=>block.identity)),adding=[];for(let block of blocks(mine.slice(front.length)))known.has(block.identity)||(known.add(block.identity),adding.push(block.text));let base2=!FRONTMATTER.test(theirs)&&front?`${front}${theirs}`:theirs;return adding.length?`${base2.replace(/\s*$/u,"")}
32192
32202
  ${adding.join(`
32193
32203
  `)}
@@ -32203,8 +32213,8 @@ send { v: 1, bot, files, journal } or { v: 1, about, teams }"}),!0)}function mem
32203
32213
  [],counts=sources2.heads(),leaves=activeLeaves(),conversations2=chatHeads(only2!==void 0?store5.bots.filter(bot=>bot.id===only2):chosen?store5.bots.filter(bot=>chosen.has(bot.id)):store5.bots,rooms).map(head=>({threadId:head.threadId,...head.bot?{bot:head.bot}:{room:head.room},rows:counts.get(head.threadId)?.rows??0,newest:head.lastId,leaf:leaves.get(head.threadId)??head.lastId,settings:conversationSettings(store5,head)})),attachments=sources2.attachments===!1?{}:{attachments:[...attachmentNamesOf(
32204
32214
  new Set(conversations2.map(head=>head.threadId)),sources2.dataDir)].sort()},files2=sources2.files===!1?{}:{files:await listBotFiles(sources2.dataDir,sent)};return only2!==void 0?{v:1,appVersion:summary3.appVersion,items:summary3.items,memory:[],journal:[],learned:[],forgotten:[],teams:[],rooms:[],connections:[],conversations:conversations2,...attachments,...files2,automations:sources2.kinds?automationSwitches(sources2.kinds,only2):[],runs:sources2.kinds?routineRunIds(sources2.kinds,only2):[]}:{v:1,
32205
32215
  appVersion:summary3.appVersion,items:summary3.items,memory:sent.flatMap(memoryOf),journal:sent.map(bot=>({bot,ids:journalIds(bot)})).filter(entry3=>entry3.ids.length),learned:[...new Set(learnedState().learned.map(fact=>factIdentity(fact.text)).filter(Boolean))].sort(),forgotten:[...new Set(learnedState().removed)].sort(),teams:sources2.teamMemory?teamsHere(sources2.teamMemory).map(team=>({section:team.section,context:team.context===null?null:memoryLines(team.context),memory:team.memory.map(entry3=>entry3.
32206
- key??`${entry3.kind}:${entry3.name.toLowerCase()}`).sort()})):[],rooms:rooms.map(room=>({id:room.id,name:room.name,members:[...room.memberIds].sort(),threads:room.tasks?.length?room.tasks.map(task2=>task2.threadId):[room.threadId]})),connections:(await sources2.connections()).map(item=>item.id).sort(),conversations:conversations2,...attachments,...files2,automations:sources2.kinds?automationSwitches(sources2.kinds):[],runs:sources2.kinds?routineRunIds(sources2.kinds):[]}}import{createHash as createHash129}from"node:crypto";var TEAM_HELD_PARTS=["chief","helper"];function empty2(value3){return value3==null||value3===""?!0:Array.isArray(value3)?value3.length===0:typeof value3=="object"&&Object.keys(value3).length===0}function partHash2(value3){if(empty2(value3))return EMPTY3;let kept2=typeof value3=="object"&&!Array.isArray(value3)?Object.fromEntries(Object.entries(value3).filter(([,field5])=>!empty2(field5))):value3;return empty2(kept2)?EMPTY3:createHash129("sha256").update(canonicalJson(kept2)).digest("hex").slice(
32207
- 0,24)}var pictureHashes=new Map;function pictureHash(avatarUrl,picture2){let known=pictureHashes.get(avatarUrl);if(known)return known;let bytes4=picture2(avatarUrl);if(!bytes4)return EMPTY3;let hash4=createHash129("sha256").update(bytes4).digest("hex").slice(0,24);return pictureHashes.size>1e3&&pictureHashes.clear(),pictureHashes.set(avatarUrl,hash4),hash4}function botParts(bot,picture2){let fields3=bot,parts3={};for(let[part2,names5]of Object.entries(BOT_PARTS))parts3[part2]=partHash2(names5.length===
32216
+ key??`${entry3.kind}:${entry3.name.toLowerCase()}`).sort()})):[],rooms:rooms.map(room=>({id:room.id,name:room.name,members:[...room.memberIds].sort(),threads:room.tasks?.length?room.tasks.map(task2=>task2.threadId):[room.threadId]})),connections:(await sources2.connections()).map(item=>item.id).sort(),conversations:conversations2,...attachments,...files2,automations:sources2.kinds?automationSwitches(sources2.kinds):[],runs:sources2.kinds?routineRunIds(sources2.kinds):[]}}import{createHash as createHash130}from"node:crypto";var TEAM_HELD_PARTS=["chief","helper"];function empty2(value3){return value3==null||value3===""?!0:Array.isArray(value3)?value3.length===0:typeof value3=="object"&&Object.keys(value3).length===0}function partHash2(value3){if(empty2(value3))return EMPTY3;let kept2=typeof value3=="object"&&!Array.isArray(value3)?Object.fromEntries(Object.entries(value3).filter(([,field5])=>!empty2(field5))):value3;return empty2(kept2)?EMPTY3:createHash130("sha256").update(canonicalJson(kept2)).digest("hex").slice(
32217
+ 0,24)}var pictureHashes=new Map;function pictureHash(avatarUrl,picture2){let known=pictureHashes.get(avatarUrl);if(known)return known;let bytes4=picture2(avatarUrl);if(!bytes4)return EMPTY3;let hash4=createHash130("sha256").update(bytes4).digest("hex").slice(0,24);return pictureHashes.size>1e3&&pictureHashes.clear(),pictureHashes.set(avatarUrl,hash4),hash4}function botParts(bot,picture2){let fields3=bot,parts3={};for(let[part2,names5]of Object.entries(BOT_PARTS))parts3[part2]=partHash2(names5.length===
32208
32218
  1?fields3[names5[0]]:Object.fromEntries(names5.map(name6=>[name6,fields3[name6]])));return parts3[PICTURE_PART]=bot.avatarUrl?pictureHash(bot.avatarUrl,picture2):EMPTY3,parts3}function unused(bot,skills,greetingOnly,inRoom=()=>!1,automated=()=>!1){return!bot.soul?.trim()&&!bot.title&&!bot.description&&!bot.avatarUrl&&!bot.sidebarHidden&&!bot.welcomed&&skills===0&&(bot.tasks?.length??1)<=1&&greetingOnly(bot.threadId,bot.name)&&!inRoom(bot.id)&&!automated(bot.id)}function cloudSendSummary(sources2,{
32209
32219
  move:move3=!1,bot:only2,bots:chosen,leaving=!1}={}){let items=[],carried2=new Set;for(let bot of sources2.bots()){if(only2!==void 0&&bot.id!==only2||chosen&&!chosen.has(bot.id)||leaving&&bot.movedTo?.state==="moved")continue;let skills=sources2.skills(bot);if(only2===void 0&&unused(bot,skills.length,sources2.greetingOnly,sources2.inRoom,move3?sources2.automated:void 0))continue;carried2.add(bot.id);let parts3={...botParts(bot,sources2.picture),...move3&&sources2.move?sources2.move.botParts(bot):
32210
32220
  {}};if(only2!==void 0)for(let part2 of TEAM_HELD_PARTS)delete parts3[part2];items.push({key:itemKey.bot(bot.id),kind:"bot",label:bot.name,id:bot.id,parts:parts3});for(let skill of skills)items.push({key:itemKey.skill(bot.id,skill.name),kind:"skill",label:skill.name,id:skill.name,bot:bot.id,parts:{text:skill.sha256.slice(0,24)||EMPTY3,on:skill.enabled?"on":"off"}})}if(only2!==void 0){let bot=sources2.bots().find(candidate=>candidate.id===only2);return move3&&sources2.move&&bot&&items.push(...sources2.
@@ -32234,7 +32244,7 @@ failedAt=Date.now()}).finally(()=>{reading=null})),slugs.flatMap(slug4=>{let ent
32234
32244
  let granted=bot.composio===!1?[]:Object.keys(bot.connectorTools??{}),apps3=connected2(granted.filter(slug4=>SLUG5.test(slug4))).filter(([,on4])=>!on4).map(([slug4])=>toolkitName(slug4.toUpperCase())),from=sources2.movedFrom?.()??null;return[from?` You moved to My Cloud from the person's computer ${from}, with everything in Limix Bot. What lives outside Limix Bot stayed on ${from}: its other folders and files, passkeys, the person's own browser sessions and apps, Local VM disks and model servers \
32235
32245
  on its home network. When a task needs one, use ${from} if it is lent to My Cloud and online; otherwise say in plain words that it stayed there.`:"",toConnect.length?` Not connected on My Cloud yet: ${toConnect.join("; ")}. When a task needs one, say in plain words that it needs the person once on My Cloud and give its link; do not try another way.`:"",apps3.length?` Assigned to this bot but not connected on My Cloud yet: ${apps3.join(", ")}. When a task needs one, call COMPOSIO_MANAGE_CONNECTIO\
32236
32246
  NS for it, which shows the person a card to connect it, and end the turn.`:"",...lent?lent.size?[` Runs on the person's own computer and can't be reached now: ${[...lent.values()].join(" ")} If a task needs one, tell the person that in plain words, and do not write your own replacement.`]:[]:[...elsewhere].map(([computer,names5])=>` Runs only on the person's computer ${computer}, not on My Cloud: ${names5.join("; ")}. It worked there before the bots moved here. If a task needs one, tell the pers\
32237
- on in plain words that it stayed on ${computer} and why, not that it was never set up, and do not write your own replacement.`)].join("")}}init_zod();import{createHash as createHash130}from"node:crypto";init_config3();var meSchema=external_exports.object({installationId:external_exports.string().min(1),user:external_exports.string().regex(/^[0-9a-f]{24}$/u).optional(),shared:external_exports.boolean().optional()}),IDENTITY_TTL_MS=10*6e4,APPS_TTL_MS=10*6e4,ownDigest=userId=>createHash130("sha256").update(`omb-composio-own:${userId}`).digest("hex").slice(0,24),identity8=null,apps2=null,appsReading=null;function forgetComposioIdentity(){identity8=null,apps2=null}async function brokerFetch(path8,init2={}){
32247
+ on in plain words that it stayed on ${computer} and why, not that it was never set up, and do not write your own replacement.`)].join("")}}init_zod();import{createHash as createHash131}from"node:crypto";init_config3();var meSchema=external_exports.object({installationId:external_exports.string().min(1),user:external_exports.string().regex(/^[0-9a-f]{24}$/u).optional(),shared:external_exports.boolean().optional()}),IDENTITY_TTL_MS=10*6e4,APPS_TTL_MS=10*6e4,ownDigest=userId=>createHash131("sha256").update(`omb-composio-own:${userId}`).digest("hex").slice(0,24),identity8=null,apps2=null,appsReading=null;function forgetComposioIdentity(){identity8=null,apps2=null}async function brokerFetch(path8,init2={}){
32238
32248
  let access2=brokerAccess();if(!access2)throw new Error("The connected-apps service is unavailable.");return fetch(`${access2.url}${path8}`,{...init2,redirect:"error",signal:AbortSignal.timeout(2e4),headers:{authorization:`Bearer ${access2.token}`,...init2.body?{"content-type":"application/json"}:{}}})}async function managedMe(){let access2=brokerAccess();if(!access2)return null;if(identity8&&identity8.token===access2.token&&Date.now()-identity8.at<IDENTITY_TTL_MS)return identity8.value;let response=await brokerFetch(
32239
32249
  "/v1/me");if(!response.ok)return await response.body?.cancel(),null;let parsed3=meSchema.safeParse(await response.json().catch(()=>null));if(!parsed3.success)return null;let value3={installationId:parsed3.data.installationId,...parsed3.data.user?{user:parsed3.data.user}:{},shared:parsed3.data.shared===!0};return identity8={token:access2.token,at:Date.now(),value:value3},value3}function connectedApps(cfg2,key7){return!(apps2&&apps2.key===key7&&Date.now()-apps2.at<APPS_TTL_MS)&&!appsReading&&(appsReading=
32240
32250
  connectedServices(cfg2).then(services2=>{apps2={key:key7,at:Date.now(),slugs:Object.entries(services2).filter(([,state])=>state.connected).map(([slug4])=>slug4).sort()}}).catch(()=>{}).finally(()=>{appsReading=null})),apps2?.key===key7?apps2.slugs:void 0}async function composioIdentity(cfg2){let mode=connectionMode(cfg2);if(mode==="self-hosted"){let userId=cfg2.composio?.userId;return userId?{mode:"own",account:`own:${ownDigest(userId)}`,shared:!1,apps:connectedApps(cfg2,`own:${userId}`)}:null}if(mode!==
@@ -32291,10 +32301,10 @@ string.",`url() may name a theme file (${THEME_ASSET_PREFIX}<theme id>/<file>),
32291
32301
  what}`),"","Calls: theme (optional id: also return that saved theme). set_theme with id and theme (the theme as JSON) saves and wears it; with only id it wears a saved theme, a built-in skin, or none. add_theme_asset with id and path.",`theme_history lists the person's last ${LOOK_HISTORY_LIMIT} look changes, newest first, each with its index and the look right after it. undo_theme goes back: steps (default 1) undoes that many changes; index returns to the look right after that entry, theme file\
32292
32302
  and all. An undo is itself a change, so undoing it again is a redo.`,"","You cannot see the result. Make one small change at a time, then ask the person how it looks.",'Going back: "undo that", "go back", "go back two changes", "how it was before" \u2192 undo_theme with steps. "The purple one from earlier", "the one from this morning" \u2192 theme_history, then undo_theme with that index.','"Revert" or "reset" to the original, default or normal look \u2192 set_theme with id "none". Wear a built-in s\
32293
32303
  kin only when the person names one.',`If a theme hides what the person needs, tell them: ${SHORTCUT} resets to the default look, and opening the app with ?${SAFE_LOOK_PARAM} in its address starts it without the theme. The card in the conversation has Undo too.`].join(`
32294
- `)}import{createHash as createHash131}from"node:crypto";import{cpSync as cpSync5,existsSync as existsSync106,mkdirSync as mkdirSync126,readdirSync as readdirSync62,readFileSync as readFileSync200,rmSync as rmSync66,statSync as statSync49}from"node:fs";import{join as join277}from"node:path";init_atomic();init_zod();import{readFileSync as readFileSync199}from"node:fs";import{join as join276}from"node:path";init_atomic();var skinSchema=external_exports.enum([...SKIN_IDS,"system"]),lookSchema=external_exports.object({id:external_exports.string().regex(THEME_ID).nullable(),skin:skinSchema.optional()}).strict(),snapshotSchema=external_exports.object({file:themeFileSchema.nullable(),assets:external_exports.array(external_exports.string().regex(THEME_ASSET_NAME))}).strict(),entrySchema5=external_exports.object({seq:external_exports.number().int().positive(),at:external_exports.string(),change:external_exports.
32304
+ `)}import{createHash as createHash132}from"node:crypto";import{cpSync as cpSync5,existsSync as existsSync106,mkdirSync as mkdirSync126,readdirSync as readdirSync62,readFileSync as readFileSync200,rmSync as rmSync66,statSync as statSync49}from"node:fs";import{join as join277}from"node:path";init_atomic();init_zod();import{readFileSync as readFileSync199}from"node:fs";import{join as join276}from"node:path";init_atomic();var skinSchema=external_exports.enum([...SKIN_IDS,"system"]),lookSchema=external_exports.object({id:external_exports.string().regex(THEME_ID).nullable(),skin:skinSchema.optional()}).strict(),snapshotSchema=external_exports.object({file:themeFileSchema.nullable(),assets:external_exports.array(external_exports.string().regex(THEME_ASSET_NAME))}).strict(),entrySchema5=external_exports.object({seq:external_exports.number().int().positive(),at:external_exports.string(),change:external_exports.
32295
32305
  object({kind:external_exports.enum(LOOK_CHANGE_KINDS),name:external_exports.string().max(60).optional(),count:external_exports.number().int().positive().optional()}).strict(),before:lookSchema,after:lookSchema,themes:external_exports.record(external_exports.string().regex(THEME_ID),snapshotSchema).optional()}).strict(),historySchema=external_exports.object({entries:external_exports.array(entrySchema5)}).strict(),FILE7="history.json";function readHistory2(folder3){try{let parsed3=historySchema.safeParse(
32296
32306
  JSON.parse(readFileSync199(join276(folder3,FILE7),"utf8")));return parsed3.success?parsed3.data.entries:[]}catch{return[]}}function appendHistory(folder3,entry3,now2=new Date){let entries4=readHistory2(folder3),seq2=(entries4.at(-1)?.seq??0)+1,kept2=[...entries4,{...entry3,seq:seq2,at:now2.toISOString()}].slice(-LOOK_HISTORY_LIMIT);writeFileAtomic(join276(folder3,FILE7),`${JSON.stringify({entries:kept2})}
32297
- `)}function lookAfter(entries4,seq2){let first2=entries4[0];if(!first2||seq2<first2.seq-1||seq2>entries4.at(-1).seq)return null;let undone=entries4.filter(entry3=>entry3.seq>seq2),themes={};for(let entry3 of undone)for(let[id12,snapshot4]of Object.entries(entry3.themes??{}))themes[id12]??=snapshot4;return{look:undone[0]?.before??entries4.at(-1).after,themes,undone}}var refused2=refusal7=>({refusal:refusal7}),isRefusal=value3=>typeof value3=="object"&&value3!==null&&"refusal"in value3,personFolder=person2=>/^[\w-]{1,64}$/.test(person2)?person2:`h_${createHash131("sha256").update(person2).digest("hex").slice(0,32)}`,RESERVED_IDS=new Set(["active","history","import","none"]),slugFor=name6=>name6.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"theme";function looksLike(name6,bytes4){let ext=name6.slice(name6.lastIndexOf(
32307
+ `)}function lookAfter(entries4,seq2){let first2=entries4[0];if(!first2||seq2<first2.seq-1||seq2>entries4.at(-1).seq)return null;let undone=entries4.filter(entry3=>entry3.seq>seq2),themes={};for(let entry3 of undone)for(let[id12,snapshot4]of Object.entries(entry3.themes??{}))themes[id12]??=snapshot4;return{look:undone[0]?.before??entries4.at(-1).after,themes,undone}}var refused2=refusal7=>({refusal:refusal7}),isRefusal=value3=>typeof value3=="object"&&value3!==null&&"refusal"in value3,personFolder=person2=>/^[\w-]{1,64}$/.test(person2)?person2:`h_${createHash132("sha256").update(person2).digest("hex").slice(0,32)}`,RESERVED_IDS=new Set(["active","history","import","none"]),slugFor=name6=>name6.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"theme";function looksLike(name6,bytes4){let ext=name6.slice(name6.lastIndexOf(
32298
32308
  ".")+1),starts=(...values4)=>values4.every((value3,index4)=>bytes4[index4]===value3),ascii=(at8,text34)=>bytes4.subarray(at8,at8+text34.length).toString("latin1")===text34;switch(ext){case"png":return starts(137,80,78,71);case"jpg":case"jpeg":return starts(255,216,255);case"gif":return ascii(0,"GIF8");case"webp":return ascii(0,"RIFF")&&ascii(8,"WEBP");case"avif":return ascii(4,"ftyp");case"woff":return ascii(0,"wOFF");case"woff2":return ascii(0,"wOF2");case"ttf":return starts(0,1,0,0)||ascii(0,"\
32299
32309
  true");case"otf":return ascii(0,"OTTO");case"svg":{let head=bytes4.subarray(0,4096).toString("utf8").replace(/^/,"").trimStart();return/^(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*(<!DOCTYPE svg[^>]*>\s*)?<svg[\s>]/i.test(head)}default:return!1}}function createThemeStore(deps){let root4=join277(deps.dataDir,"themes"),home2=person2=>join277(root4,personFolder(person2)),folder3=(person2,id12)=>join277(home2(person2),id12),assetsDir=(person2,id12)=>join277(folder3(person2,id12),"assets"),validId2=id12=>THEME_ID.
32300
32310
  test(id12)&&!RESERVED_IDS.has(id12);function read4(person2,id12){if(!validId2(id12))return null;try{let parsed3=themeFileSchema.safeParse(JSON.parse(readFileSync200(join277(folder3(person2,id12),"theme.json"),"utf8")));return parsed3.success?parsed3.data:null}catch{return null}}function ids(person2){try{return readdirSync62(home2(person2),{withFileTypes:!0}).filter(entry3=>entry3.isDirectory()&&validId2(entry3.name)).map(entry3=>entry3.name).sort()}catch{return[]}}function assets(person2,id12){try{
@@ -32323,7 +32333,7 @@ restore(person2,target4.seq);return isRefusal(done)?json7(res,409,{error:done.re
32323
32333
  let match5=THEME_PATH.exec(path8);if(!match5)return json7(res,404,{error:"No such theme route."});let id12=match5[1];if(match5[2]==="/export"&&method2==="GET"){let data4=store5.exportTheme(person2,id12);return data4?json7(res,200,data4):json7(res,404,{error:"No such theme."})}if(match5[2]==="/duplicate"&&method2==="POST"){let parsed3=nameBody.safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"name is required"});let copy6=store5.duplicate(person2,id12,parsed3.data.name);
32324
32334
  return isRefusal(copy6)?json7(res,400,{error:copy6.refusal}):json7(res,200,copy6)}if(match5[2])return json7(res,405,{error:"Method not allowed."});if(method2==="GET"){let theme=store5.read(person2,id12);return theme?json7(res,200,{id:id12,theme}):json7(res,404,{error:"No such theme."})}if(method2==="PUT"){let parsed3=saveBody.safeParse(await readBody2(req,THEME_LIMITS.cssChars*4+5e4));if(!parsed3.success)return json7(res,400,{error:parsed3.error.issues.map(issue3=>`${issue3.path.join(".")}: ${issue3.
32325
32335
  message}`).join("; ")});let done=store5.change(person2,{saves:[{id:id12,file:parsed3.data.theme}]});return isRefusal(done)?json7(res,400,{error:done.refusal}):(store5.active(person2)===id12&&deps.changed(person2),json7(res,200,{ok:!0}))}if(method2==="PATCH"){let parsed3=nameBody.safeParse(await readBody2(req)),theme=store5.read(person2,id12);if(!parsed3.success||!theme)return json7(res,parsed3.success?404:400,{error:parsed3.success?"No such theme.":"name is required"});let refusal7=store5.save(person2,
32326
- id12,{...theme,name:parsed3.data.name});return refusal7?json7(res,400,{error:refusal7.refusal}):json7(res,200,{ok:!0})}if(method2==="DELETE"){let wasActive=store5.active(person2)===id12;return store5.remove(person2,id12),wasActive&&deps.changed(person2),json7(res,200,{ok:!0})}return json7(res,405,{error:"Method not allowed."})}}init_zod();import{basename as basename37,dirname as dirname86,extname as extname11}from"node:path";var BUILT_IN2=[...SKIN_IDS,"system"],reply4=(status5,body3)=>({status:status5,body:body3}),refuse4=(status5,error66)=>reply4(status5,{error:error66});function said2(change3){switch(change3.kind){case"made":return`made ${change3.name}`;case"edited":return`edited ${change3.name}`;case"deleted":return`deleted ${change3.name} while wearing it`;case"wore":return`wore ${change3.name}`;case"skin":return`wore the built-in ${change3.name} skin`;case"default":return"back to default";case"undid":return`wen\
32336
+ id12,{...theme,name:parsed3.data.name});return refusal7?json7(res,400,{error:refusal7.refusal}):json7(res,200,{ok:!0})}if(method2==="DELETE"){let wasActive=store5.active(person2)===id12;return store5.remove(person2,id12),wasActive&&deps.changed(person2),json7(res,200,{ok:!0})}return json7(res,405,{error:"Method not allowed."})}}init_zod();import{basename as basename38,dirname as dirname86,extname as extname11}from"node:path";var BUILT_IN2=[...SKIN_IDS,"system"],reply4=(status5,body3)=>({status:status5,body:body3}),refuse4=(status5,error66)=>reply4(status5,{error:error66});function said2(change3){switch(change3.kind){case"made":return`made ${change3.name}`;case"edited":return`edited ${change3.name}`;case"deleted":return`deleted ${change3.name} while wearing it`;case"wore":return`wore ${change3.name}`;case"skin":return`wore the built-in ${change3.name} skin`;case"default":return"back to default";case"undid":return`wen\
32327
32337
  t back ${change3.count===1?"1 change":`${change3.count} changes`}`}}function createThemeTool(deps){let{store:store5}=deps;function entry3(person2){let read4=()=>{let id12=store5.active(person2);return id12?store5.read(person2,id12)?.name??id12:""};return{id:"appearance.theme",label:"Theme",help:"A custom look for the app.",where:"Settings \u2192 Appearance",synonyms:[],tier:"safe",value:external_exports.unknown(),allowed:"a theme",read:read4,current:()=>({undoTo:store5.history(person2)[0]?.seq??
32328
32338
  0}),write:async value3=>{let wear=value3,done="undoTo"in wear?store5.restore(person2,wear.undoTo):store5.change(person2,{saves:wear.save?[wear.save]:[],wear:wear.id,...wear.skin?{skin:wear.skin}:{}});return isRefusal(done)?done.refusal:(deps.changed(person2,done.skin),null)}}}function overview(person2,id12){let list10=store5.list(person2),asked=typeof id12=="string"&&THEME_ID.test(id12)?store5.read(person2,id12):null,current3=list10.active?store5.read(person2,list10.active):null;return reply4(200,
32329
32339
  {text:JSON.stringify({current:list10.active?{id:list10.active,theme:current3}:"none: the person's built-in skin",builtIn:BUILT_IN2,saved:list10.themes,...asked?{theme:{id:id12,...asked}}:{},guide:themeGuide()})})}function wanted(person2,body3){let id12=typeof body3.id=="string"?body3.id.trim():"";if(body3.theme!==void 0){let raw=body3.theme;if(typeof raw=="string")try{raw=JSON.parse(raw)}catch{return{error:'theme must be the theme as JSON: {"name", "canvas", "accent", "colors", "css", ...}.'}}let parsed3=themeFileSchema.
@@ -32334,7 +32344,7 @@ look.skin&&item.look.skin!=="system"?`built-in ${item.look.skin}`:"default"}));r
32334
32344
  steps===""?1:whole3(body3.steps);if(!items.length)return{error:"There are no look changes to go back on."};if(!Number.isInteger(count12)||count12<(byIndex?0:1)||count12>items.length-(byIndex?1:0))return{error:`${byIndex?"index":"steps"} must be a whole number from 1 to ${items.length}. Call theme_history to see the changes.`};if(count12===0)return{error:"That is how it looks now."};let target4=byIndex?items[count12]:items[count12-1],undoTo=byIndex?target4.seq:target4.seq-1,missing2=store5.missingAssets(
32335
32345
  person2,undoTo),back=byIndex?`Go back to the look after: ${said2(target4)}`:count12===1?`Undo the last look change (${said2(items[0])})`:`Undo the last ${count12} look changes`;return{wear:{undoTo},change:`${back}${missing2.length?`; files no longer there: ${missing2.join(", ")}`:""}`}}async function addAsset(turn2,person2,body3){let id12=typeof body3.id=="string"?body3.id:"";if(!THEME_ID.test(id12)||!store5.read(person2,id12))return refuse4(404,"Name a saved theme in id: save it with set_theme \
32336
32346
  first.");let path8=typeof body3.path=="string"?body3.path.trim():"";if(!path8)return refuse4(400,"path is the file in your workspace or this conversation's attachments.");let sources2=deps.sources(turn2),attached=sources2.attachments.includes(path8),file2;try{file2=await openMessageFile(path8,attached?[dirname86(path8)]:sources2.roots,THEME_LIMITS.assetBytes)}catch(error66){let status5=error66.status??400;return refuse4(status5,status5===413?`A theme file may be up to ${THEME_LIMITS.assetBytes/1024/
32337
- 1024} MB.`:"That file is not in your workspace or this conversation's attachments, or it cannot be read.")}try{let ext=(extname11(file2.name).slice(1)||"").toLowerCase(),stem2=slugFor(basename37(file2.name,extname11(file2.name))).slice(0,60),added=store5.addAsset(person2,id12,`${stem2}.${ext}`,await file2.handle.readFile());return isRefusal(added)?refuse4(400,added.refusal):reply4(200,{text:`Added. In the theme's css write url("${added.url}"). Then call set_theme with the theme to use it.`})}finally{
32347
+ 1024} MB.`:"That file is not in your workspace or this conversation's attachments, or it cannot be read.")}try{let ext=(extname11(file2.name).slice(1)||"").toLowerCase(),stem2=slugFor(basename38(file2.name,extname11(file2.name))).slice(0,60),added=store5.addAsset(person2,id12,`${stem2}.${ext}`,await file2.handle.readFile());return isRefusal(added)?refuse4(400,added.refusal):reply4(200,{text:`Added. In the theme's css write url("${added.url}"). Then call set_theme with the theme to use it.`})}finally{
32338
32348
  await file2.handle.close().catch(()=>{})}}return{entry:entry3,overview,wanted,undo,history,addAsset,person:deps.person}}import{randomUUID as randomUUID86}from"node:crypto";init_zod();init_bot_thread_limits();init_zod();import{randomUUID as randomUUID82}from"node:crypto";import{join as join278}from"node:path";init_config3();var displayName2=external_exports.string().trim().min(1).max(80).refine(value3=>!new RegExp("\\p{Cc}","u").test(value3),"Name cannot contain control characters"),awsProfile=external_exports.string().trim().regex(/^[A-Za-z0-9._+=,@-]{1,128}$/,"Enter the AWS profile name from this computer's ~/.aws config."),awsRegion=external_exports.string().trim().regex(/^[a-z]{2}(-[a-z]+)+-\d$/,"Enter an AWS region, such as us-east-1."),model2=external_exports.string().trim().max(160).regex(CLAUDE_MODEL_ID,"Us\
32339
32349
  e the model id Bedrock serves.").refine(value3=>value3!=="default","Claude Code reserves `default`; use the model id Bedrock serves."),optionalModel=external_exports.union([model2,external_exports.literal("")]),claudeBedrockSchema=external_exports.object({displayName:displayName2,awsProfile,awsRegion,model:model2,opusModel:optionalModel.optional(),sonnetModel:optionalModel.optional(),haikuModel:optionalModel.optional(),smallFastModel:optionalModel.optional()}).strict(),claudeBedrockUpdateSchema=external_exports.
32340
32350
  object({displayName:displayName2.optional(),awsProfile:awsProfile.optional(),awsRegion:awsRegion.optional(),model:model2.optional(),opusModel:optionalModel.optional(),sonnetModel:optionalModel.optional(),haikuModel:optionalModel.optional(),smallFastModel:optionalModel.optional()}).strict().refine(value3=>Object.keys(value3).length>0,"No settings supplied"),TIERS2=[["opusModel","ANTHROPIC_DEFAULT_OPUS_MODEL"],["sonnetModel","ANTHROPIC_DEFAULT_SONNET_MODEL"],["haikuModel","ANTHROPIC_DEFAULT_HAIKU_\
@@ -32434,16 +32444,16 @@ library skill on or off, or give it to every bot. Library skills are listed in S
32434
32444
  {"name","enabled":true|false} or {"name","everyBot":true|false}',read:()=>"",current:async({name:name6,enabled})=>{let skill=(await libraryList()).find(one5=>one5.name===name6);return skill?enabled!==void 0?{name:name6,enabled:skill.enabled}:{name:name6,everyBot:skill.everyBot}:void 0},describe:({name:name6,enabled,everyBot})=>({change:enabled!==void 0?`${enabled?"Turn on":"Turn off"} the library skill ${name6}`:`${everyBot?"Give":"Stop giving"} the library skill ${name6} to every bot`}),write:({
32435
32445
  name:name6,...change3})=>deps.call("skills","PATCH",`/api/skills-library/${name6}`,change3)}),writable2({id:"bots.skills",label:"A bot's library skills",help:"Which library skills one bot uses. Send the full list.",where:"a bot's Settings",synonyms:["skills","assign skills","bot skills"],value:external_exports.object({botId:external_exports.string().regex(/^[\w-]{1,120}$/),skills:external_exports.array(external_exports.string().min(1).max(64)).max(200)}).strict(),allowed:'{"botId","skills":[name\
32436
32446
  s]}',read:()=>"",current:({botId:botId2})=>{let bot=deps.bots().find(one5=>one5.id===botId2);return bot?{botId:botId2,skills:bot.assignedSkills??[]}:void 0},describe:({botId:botId2,skills})=>{let name6=botName(botId2);return name6?{change:skills.length?`Give ${name6} the library skills ${skills.join(", ")}`:`Take every library skill from ${name6}`}:{refusal:`No bot has the id ${botId2}. Use list_bots for the ids.`}},write:({botId:botId2,skills})=>deps.call("skills","PUT",`/api/bots/${encodeURIComponent(
32437
- botId2)}/skills-library`,{skills})})]}init_zod();init_bot_avatar();import{basename as basename39}from"node:path";init_bot_avatar();import{realpath as realpath6}from"node:fs/promises";import{basename as basename38,isAbsolute as isAbsolute45,join as join281,relative as relative29,sep as sep18}from"node:path";var PICTURE_FILE_MAX_BYTES=5*1024*1024,PICTURE_FILE_KINDS="a PNG, JPEG, GIF or WebP picture",inside8=(root4,path8)=>{let rest=relative29(root4,path8);return rest!==""&&rest!==".."&&!rest.startsWith(`..${sep18}`)&&!isAbsolute45(rest)},outside=path8=>`${path8} is outside your workspace, your working folder and this conversation's files, so it can't be a picture.`;function refusalFor3(error66,path8){let{status:status5,code}=error66??{};return status5===404?`No file was found at ${path8}. Save the p\
32447
+ botId2)}/skills-library`,{skills})})]}init_zod();init_bot_avatar();import{basename as basename40}from"node:path";init_bot_avatar();import{realpath as realpath6}from"node:fs/promises";import{basename as basename39,isAbsolute as isAbsolute45,join as join281,relative as relative29,sep as sep18}from"node:path";var PICTURE_FILE_MAX_BYTES=5*1024*1024,PICTURE_FILE_KINDS="a PNG, JPEG, GIF or WebP picture",inside8=(root4,path8)=>{let rest=relative29(root4,path8);return rest!==""&&rest!==".."&&!rest.startsWith(`..${sep18}`)&&!isAbsolute45(rest)},outside=path8=>`${path8} is outside your workspace, your working folder and this conversation's files, so it can't be a picture.`;function refusalFor3(error66,path8){let{status:status5,code}=error66??{};return status5===404?`No file was found at ${path8}. Save the p\
32438
32448
  icture in your workspace or working folder and pass its exact path.`:code==="outside_workspace"?outside(path8):status5===413?`That file is over ${PICTURE_FILE_MAX_BYTES/1024/1024} MB. Use a smaller picture.`:error66 instanceof Error?error66.message:"That file could not be read."}function createPictureFiles(deps){return{async take(turn2,path8){let opened;try{opened=await openMessageFile(path8,[...deps.ownFolders(turn2),deps.attachmentsDir],PICTURE_FILE_MAX_BYTES)}catch(error66){return{refusal:refusalFor3(
32439
- error66,path8)}}try{let store5=await realpath6(deps.attachmentsDir).catch(()=>null);if(store5&&inside8(store5,opened.path)&&!deps.inConversation(turn2,basename38(opened.path)))return{refusal:outside(path8)};let bytes4=await opened.handle.readFile(),mime=sniffRaster(bytes4);if(!mime)return{refusal:`${basename38(opened.path)} is not ${PICTURE_FILE_KINDS}.`};let saved=deps.save(bytes4,mime),avatarUrl=botAvatarUrlFromStoredPath(saved);return avatarUrl?{avatarUrl}:(deps.remove(saved),{refusal:"That p\
32440
- icture could not be stored."})}finally{await opened.handle.close().catch(()=>{})}},discard(avatarUrl){deps.remove(join281(deps.attachmentsDir,basename38(avatarUrl)))}}}var path7=external_exports.string().trim().max(4096),SOURCE2=`${PICTURE_FILE_KINDS} of up to ${PICTURE_FILE_MAX_BYTES/1024/1024} MB in your workspace, your working folder or this conversation's files`,pictureShown=one5=>!!botAvatarProfile(one5).avatarUrl&&botAvatarProfile(one5).avatarCrop!=="mascot",MASCOT_LOOK={avatarUrl:null,avatarCrop:"mascot",avatarZoom:AVATAR_ZOOM_MIN,avatarFocusX:AVATAR_FOCUS_CENTER,avatarFocusY:AVATAR_FOCUS_CENTER};function pictureEntries(deps,writable2){let bot=id12=>deps.
32449
+ error66,path8)}}try{let store5=await realpath6(deps.attachmentsDir).catch(()=>null);if(store5&&inside8(store5,opened.path)&&!deps.inConversation(turn2,basename39(opened.path)))return{refusal:outside(path8)};let bytes4=await opened.handle.readFile(),mime=sniffRaster(bytes4);if(!mime)return{refusal:`${basename39(opened.path)} is not ${PICTURE_FILE_KINDS}.`};let saved=deps.save(bytes4,mime),avatarUrl=botAvatarUrlFromStoredPath(saved);return avatarUrl?{avatarUrl}:(deps.remove(saved),{refusal:"That p\
32450
+ icture could not be stored."})}finally{await opened.handle.close().catch(()=>{})}},discard(avatarUrl){deps.remove(join281(deps.attachmentsDir,basename39(avatarUrl)))}}}var path7=external_exports.string().trim().max(4096),SOURCE2=`${PICTURE_FILE_KINDS} of up to ${PICTURE_FILE_MAX_BYTES/1024/1024} MB in your workspace, your working folder or this conversation's files`,pictureShown=one5=>!!botAvatarProfile(one5).avatarUrl&&botAvatarProfile(one5).avatarCrop!=="mascot",MASCOT_LOOK={avatarUrl:null,avatarCrop:"mascot",avatarZoom:AVATAR_ZOOM_MIN,avatarFocusX:AVATAR_FOCUS_CENTER,avatarFocusY:AVATAR_FOCUS_CENTER};function pictureEntries(deps,writable2){let bot=id12=>deps.
32441
32451
  bots().find(candidate=>candidate.id===id12),missing2=id12=>`No bot has the id ${id12}. Use list_bots for the ids.`,ownPicture=()=>deps.cfg().profile?.avatarUrl??"";return[writable2({id:"bots.picture",label:"Bot picture",where:"a bot's Settings",fromFile:!0,help:"A bot's own picture, shown instead of its mascot face wherever the bot appears. Use a picture file you have: one you made or downloaded, or one the person sent in this conversation.",synonyms:["picture","avatar","photo","image","profile \
32442
32452
  picture","icon","face","pfp","bot picture"],value:withoutKeys(external_exports.object({botId:external_exports.string().regex(/^[\w-]{1,120}$/),path:path7}).strict()),allowed:`{"botId","path"}: path is ${SOURCE2}; an empty path takes the picture off and brings back the mascot face`,read:()=>deps.bots().map(one5=>`${one5.name}: ${pictureShown(one5)?one5.avatarUrl:"mascot face"}`).join("; "),describe:({botId:botId2,path:file2})=>{let one5=bot(botId2);return one5?file2?{change:`Give ${one5.name} the\
32443
- picture ${basename39(file2)}`}:pictureShown(one5)?{change:`Take ${one5.name}'s picture off; it shows its mascot face again`}:{refusal:`${one5.name} has no picture; it already shows its mascot face.`}:{refusal:missing2(botId2)}},current:({botId:botId2})=>{let one5=bot(botId2);return one5&&{botId:botId2,avatarUrl:one5.avatarUrl??"",avatarCrop:one5.avatarCrop??"mascot",avatarZoom:one5.avatarZoom??AVATAR_ZOOM_MIN,avatarFocusX:one5.avatarFocusX??AVATAR_FOCUS_CENTER,avatarFocusY:one5.avatarFocusY??AVATAR_FOCUS_CENTER}},
32453
+ picture ${basename40(file2)}`}:pictureShown(one5)?{change:`Take ${one5.name}'s picture off; it shows its mascot face again`}:{refusal:`${one5.name} has no picture; it already shows its mascot face.`}:{refusal:missing2(botId2)}},current:({botId:botId2})=>{let one5=bot(botId2);return one5&&{botId:botId2,avatarUrl:one5.avatarUrl??"",avatarCrop:one5.avatarCrop??"mascot",avatarZoom:one5.avatarZoom??AVATAR_ZOOM_MIN,avatarFocusX:one5.avatarFocusX??AVATAR_FOCUS_CENTER,avatarFocusY:one5.avatarFocusY??AVATAR_FOCUS_CENTER}},
32444
32454
  write:async value3=>{let one5=bot(value3.botId);if(!one5)return missing2(value3.botId);if(value3.path!==void 0)return deps.patchBot(one5.id,{...MASCOT_LOOK});let crop=one5.avatarCrop&&one5.avatarCrop!=="mascot"?one5.avatarCrop:"circle";return deps.patchBot(one5.id,{avatarUrl:value3.avatarUrl||null,avatarCrop:value3.avatarCrop??crop,avatarZoom:value3.avatarZoom??AVATAR_ZOOM_MIN,avatarFocusX:value3.avatarFocusX??AVATAR_FOCUS_CENTER,avatarFocusY:value3.avatarFocusY??AVATAR_FOCUS_CENTER})}}),writable2(
32445
32455
  {id:"profile.photo",label:"Your photo",where:"Settings \u2192 You and your bots",fromFile:!0,help:"The person's own picture, shown wherever the app shows them. Use a picture file you have: one you made or downloaded, or one the person sent in this conversation.",synonyms:["photo","avatar","profile picture","my picture","my photo","pfp","picture of me"],value:external_exports.object({path:path7}).strict(),allowed:`{"path"}: path is ${SOURCE2}; an empty path takes the photo off`,read:ownPicture,current:()=>({
32446
- avatarUrl:ownPicture()}),describe:({path:file2})=>file2?{change:`Make ${basename39(file2)} your photo`}:ownPicture()?{change:"Take your photo off"}:{refusal:"The person has no photo to take off."},write:value3=>deps.saveConfig({profile:{avatarUrl:value3.path!==void 0?"":value3.avatarUrl??""}})})]}var turn=(on4,yes,no2)=>on4?yes:no2;function windowEntries(windowPref){let flag5=(id12,label4,help,where2,synonyms,yes,no2)=>windowPref(id12,label4,help,where2,synonyms,"true or false",{says:on4=>turn(on4,yes,no2)}),wayIn=(id12,label4,help,synonyms,yes)=>windowPref(id12,label4,help,"Settings \u2192 Phone & devices",synonyms,"true (turning it off is done by the person, in Settings)",{says:()=>yes,refusal:on4=>on4?null:personOnly2(`Turning off ${label4}`,"Settings \u2192 Phone & devices")});return[
32456
+ avatarUrl:ownPicture()}),describe:({path:file2})=>file2?{change:`Make ${basename40(file2)} your photo`}:ownPicture()?{change:"Take your photo off"}:{refusal:"The person has no photo to take off."},write:value3=>deps.saveConfig({profile:{avatarUrl:value3.path!==void 0?"":value3.avatarUrl??""}})})]}var turn=(on4,yes,no2)=>on4?yes:no2;function windowEntries(windowPref){let flag5=(id12,label4,help,where2,synonyms,yes,no2)=>windowPref(id12,label4,help,where2,synonyms,"true or false",{says:on4=>turn(on4,yes,no2)}),wayIn=(id12,label4,help,synonyms,yes)=>windowPref(id12,label4,help,"Settings \u2192 Phone & devices",synonyms,"true (turning it off is done by the person, in Settings)",{says:()=>yes,refusal:on4=>on4?null:personOnly2(`Turning off ${label4}`,"Settings \u2192 Phone & devices")});return[
32447
32457
  flag5("appearance.userBubbles","Coloured messages","Your own messages take the bot's colour.","Settings \u2192 Appearance",["bubbles","message color","my messages"],"Colour your messages with each bot's colour","Show your messages in plain grey"),flag5("appearance.runCard","This run card","Show the card that follows a bot's run while it works.","Settings \u2192 Appearance",["this run","run card","progress"],"Show the card that follows each run","Hide the card that follows each run"),flag5("appea\
32448
32458
  rance.showThreads","Threads in the sidebar","List each bot's conversations under it in the sidebar.","Settings \u2192 Appearance",["threads","conversations","sidebar"],"List each bot's threads in the sidebar","Hide threads from the sidebar"),windowPref("appearance.toolsLayout","Sidebar tools layout","How the sidebar shows its tools: rows, or a toolbar of icons.","Settings \u2192 Appearance",["tools layout","toolbar","rows"],"rows or toolbar",{says:layout=>layout==="rows"?"Show the sidebar's tool\
32449
32459
  s as rows":"Show the sidebar's tools as a toolbar of icons"}),flag5("appearance.pinnedCircles","Pinned bots as circles","Pinned bots show as a row of circles at the top of the sidebar.","Settings \u2192 Appearance",["pinned","circles","pins"],"Show pinned bots as circles","Show pinned bots as rows"),flag5("appearance.universalPins","Universal pins","Pinned bots stay pinned in every place on the rail.","Settings \u2192 Appearance",["universal pins","pins everywhere"],"Keep pinned bots pinned in e\
@@ -32746,7 +32756,7 @@ push({slug:slug4,name:name6,category:text32(raw.category,80)??"",integrations:Ar
32746
32756
  return raw}let reader=response.body.getReader(),chunks=[],total=0;for(;;){let{done,value:value3}=await reader.read();if(done)break;if(total+=value3.byteLength,total>maxBytes)throw await reader.cancel().catch(()=>{}),oversized();chunks.push(value3)}return Buffer.concat(chunks).toString("utf8")}async function fetchBotDirectory(fetcher=fetch){let response=await fetcher(BOT_DIRECTORY_API_URL,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)});if(!response.ok)throw new Error(
32747
32757
  `The bot directory returned HTTP ${response.status}`);return parseBotDirectory(parseJson(await readBounded2(response,MAX_DIRECTORY_BYTES)))}var STOPWORDS=new Set(["your","with","that","this","from","have","what","when","where","will","them","then","than","only","also","into","over","about","after","before","every","some","most","much","many","very","just","like","each","other","their","there","these","those","using","based","open","free","fast","simple","easy","apps","tool","tools","project","te\
32748
32758
  am","chat","bots"]);function matchDirectoryBots(profile,bots,limit2=5){let terms2=new Set;for(let stack2 of profile.stacks){let term=stack2.toLowerCase();term.length>=4&&terms2.add(term)}for(let signal of profile.signals)terms2.add(signal.role);for(let raw of`${profile.name} ${profile.summary}`.toLowerCase().split(/[^a-z0-9+.#-]+/)){let word=raw.replace(/^[.#+-]+|[.#+-]+$/g,"");word.length>=4&&!STOPWORDS.has(word)&&terms2.add(word)}return bots.flatMap(bot=>{let haystackParts=[bot.name,bot.category,
32749
- ...bot.integrations].map(part2=>part2.toLowerCase()),matched=[...terms2].filter(term=>haystackParts.some(part2=>part2.includes(term)));return matched.length>0?[{...bot,matched}]:[]}).sort((a,b11)=>b11.matched.length-a.matched.length).slice(0,limit2)}init_bot_visibility();import{readFileSync as readFileSync201,readdirSync as readdirSync63,statSync as statSync50}from"node:fs";import{basename as basename40,join as join283}from"node:path";var MAX_FILE_BYTES3=256e3,MAX_DIR_ENTRIES=400;function readText7(path8){try{return statSync50(path8).size>MAX_FILE_BYTES3?null:readFileSync201(path8,"utf8")}catch{return null}}function listNames2(dir){try{return readdirSync63(dir).slice(0,MAX_DIR_ENTRIES)}catch{return[]}}function isDir(path8){try{return statSync50(path8).isDirectory()}catch{return!1}}function packageJson(cwd){let raw=readText7(join283(cwd,"package.json"));if(!raw)return{deps:new Set};try{let parsed3=JSON.parse(raw);if(!parsed3||
32759
+ ...bot.integrations].map(part2=>part2.toLowerCase()),matched=[...terms2].filter(term=>haystackParts.some(part2=>part2.includes(term)));return matched.length>0?[{...bot,matched}]:[]}).sort((a,b11)=>b11.matched.length-a.matched.length).slice(0,limit2)}init_bot_visibility();import{readFileSync as readFileSync201,readdirSync as readdirSync63,statSync as statSync50}from"node:fs";import{basename as basename41,join as join283}from"node:path";var MAX_FILE_BYTES3=256e3,MAX_DIR_ENTRIES=400;function readText7(path8){try{return statSync50(path8).size>MAX_FILE_BYTES3?null:readFileSync201(path8,"utf8")}catch{return null}}function listNames2(dir){try{return readdirSync63(dir).slice(0,MAX_DIR_ENTRIES)}catch{return[]}}function isDir(path8){try{return statSync50(path8).isDirectory()}catch{return!1}}function packageJson(cwd){let raw=readText7(join283(cwd,"package.json"));if(!raw)return{deps:new Set};try{let parsed3=JSON.parse(raw);if(!parsed3||
32750
32760
  typeof parsed3!="object"||Array.isArray(parsed3))return{deps:new Set};let pkg2=parsed3,deps=new Set;for(let field5 of["dependencies","devDependencies"]){let block=pkg2[field5];if(block&&typeof block=="object"&&!Array.isArray(block))for(let dep of Object.keys(block))deps.add(dep)}return{name:typeof pkg2.name=="string"?pkg2.name:void 0,description:typeof pkg2.description=="string"?pkg2.description:void 0,deps}}catch{return{deps:new Set}}}function readme(cwd){let raw=readText7(join283(cwd,"README.m\
32751
32761
  d"))??readText7(join283(cwd,"readme.md"))??readText7(join283(cwd,"README"));if(!raw)return{};let title3,summary3;for(let line6 of raw.slice(0,64e3).split(`
32752
32762
  `)){let trimmed=line6.trim();if(trimmed){if(trimmed.startsWith("#")){title3||(title3=trimmed.replace(/^#+\s*/,"").trim()||void 0);continue}if(!(trimmed.startsWith("[![")||trimmed.startsWith("![")||trimmed.startsWith("<")||trimmed.startsWith(">"))){summary3=trimmed.replace(/[*_`]/g,"").slice(0,1e3);break}}}return{title:title3,summary:summary3}}var DETECTORS=[{role:"frontend",deps:["react","vue","svelte","next","nuxt","astro","vite","@angular/core","solid-js"],paths:["index.html","vite.config.ts",
@@ -32756,7 +32766,7 @@ ckage.json"]},{stack:"Python",paths:["pyproject.toml","requirements.txt","setup.
32756
32766
  cwd,"requirements.txt"))??""}
32757
32767
  ${readText7(join283(cwd,"pyproject.toml"))??""}`.toLowerCase(),hasDep=dep=>pkg2.deps.has(dep)||pythonDeps.length>1&&pythonDeps.includes(dep),pathEvidence=path8=>path8.includes("/")?isDir(join283(cwd,path8))&&listNames2(join283(cwd,path8)).length>0?`${path8}/`:null:entries4.has(path8)?isDir(join283(cwd,path8))?`${path8}/`:path8:null,signals=[];for(let detector of DETECTORS){let evidence=[];for(let dep of detector.deps)hasDep(dep)&&evidence.push(dep);for(let path8 of detector.paths){let found2=pathEvidence(
32758
32768
  path8);found2&&evidence.push(found2)}if(detector.role==="docs"&&evidence.length>0){let hasMkdocs=evidence.includes("mkdocs.yml"),hasMarkdown=listNames2(join283(cwd,"docs")).some(name6=>name6.endsWith(".md"));if(!hasMkdocs&&!hasMarkdown)continue}evidence.length>0&&signals.push({role:detector.role,evidence:evidence.slice(0,6)})}let stacks=[];for(let marker of STACK_MARKERS){let byDep=marker.deps?.some(dep=>hasDep(dep))??!1,byPath=marker.paths?.some(path8=>entries4.has(path8))??!1;(byDep||byPath)&&
32759
- stacks.push(marker.stack)}return{name:(md2.title??pkg2.name??basename40(cwd)).slice(0,100),summary:(md2.summary??pkg2.description??"").slice(0,1e3),stacks,signals}}var stackLine=profile=>profile.stacks.length>0?` The stack: ${profile.stacks.join(", ")}.`:"",ROLE_TEMPLATES={frontend:{name:"Pixel",title:"Frontend Builder",color:"pink",describe:(profile,evidence)=>`You build and refine the user interface of ${profile.name}.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. Keep cha\
32769
+ stacks.push(marker.stack)}return{name:(md2.title??pkg2.name??basename41(cwd)).slice(0,100),summary:(md2.summary??pkg2.description??"").slice(0,1e3),stacks,signals}}var stackLine=profile=>profile.stacks.length>0?` The stack: ${profile.stacks.join(", ")}.`:"",ROLE_TEMPLATES={frontend:{name:"Pixel",title:"Frontend Builder",color:"pink",describe:(profile,evidence)=>`You build and refine the user interface of ${profile.name}.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. Keep cha\
32760
32770
  nges small, match the existing component patterns, and check what you built actually renders before calling it done.`},backend:{name:"Forge",title:"Backend Builder",color:"blue",describe:(profile,evidence)=>`You own the server side of ${profile.name}: endpoints, business logic, and the contracts the frontend relies on.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. Change behavior only alongside the tests that prove it.`},mobile:{name:"Pocket",title:"Mobile Builder",color:"co\
32761
32771
  ral",describe:(profile,evidence)=>`You keep ${profile.name} working on phones: screens, navigation, and platform quirks.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. Test on both platforms before declaring victory.`},data:{name:"Schema",title:"Data Engineer",color:"teal",describe:(profile,evidence)=>`You own the data layer of ${profile.name}: models, migrations, and query performance.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. Every migration ships w\
32762
32772
  ith its rollback story.`},testing:{name:"Probe",title:"Test Engineer",color:"green",describe:(profile,evidence)=>`You guard ${profile.name} with tests: you reproduce bugs before they are fixed and extend coverage where changes land.${stackLine(profile)} Your turf shows up as ${evidence.join(", ")}. A red test you wrote is worth more than a green suite nobody trusts.`},infra:{name:"Anchor",title:"Infra & CI",color:"orange",describe:(profile,evidence)=>`You keep ${profile.name} buildable, shippabl\
@@ -32823,7 +32833,7 @@ bot=>publicBot2(store5.bot(bot.id)??bot)),group:imported.group,groups:imported.g
32823
32833
  "object"||Array.isArray(body3)||Object.keys(body3).some(key7=>key7!=="threadIds"))return json7(res,400,{error:"send {} or { threadIds }"});let raw=body3.threadIds;if(raw!==void 0&&(!Array.isArray(raw)||raw.length>MAX_THREAD_IDS||raw.some(id12=>typeof id12!="string")))return json7(res,400,{error:"threadIds must be a list of this bot's thread ids"});let tasks2=bot.tasks??[],ids=new Set(tasks2.map(task2=>task2.threadId)),foreign=raw?.find(id12=>!ids.has(id12));if(foreign!==void 0)return json7(res,400,
32824
32834
  {error:`"${foreign}" is not one of this bot's threads`});if(bot.approvalGrant)return json7(res,409,{error:"wait for the approval-level change to finish before changing models"});let listed3=raw===void 0?null:new Set(raw),own4=tasks2.filter(task2=>(!listed3||listed3.has(task2.threadId))&&task2.modelSelection!==void 0&&!sameModelSelection(task2.modelSelection,bot.modelSelection)),busy=own4.filter(task2=>deps.busy(bot.id,task2.threadId)),switched=deps.follow(bot.id,own4.filter(task2=>!busy.includes(
32825
32835
  task2)).map(task2=>task2.threadId));return json7(res,200,{switched:switched.length,busy:busy.length,bot:deps.reply(bot.id)})}}function createUndoRoutes(deps){return async({req,res,path:path8,method:method2,auth,json:json7,readBody:readBody2})=>{let m3=path8.match(/^\/api\/threads\/([\w-]+)\/undo$/);if(!m3||method2!=="POST")return PASS;let threadId=m3[1],body3=await readBody2(req),requestId=typeof body3?.requestId=="string"?body3.requestId:"";if(!requestId)return json7(res,400,{error:"requestId is required"});let refusal7=deps.refusal(auth,threadId,requestId);if(refusal7)return json7(res,403,{error:refusal7});await deps.
32826
- undo(auth,res,threadId,requestId)}}import{createHash as createHash132}from"node:crypto";import{request as request10}from"node:http";import{ServerResponse}from"node:http";import{Socket}from"node:net";var HANDSHAKE_MS=1e4,EARLY_BYTES=64*1024;function createUpgrades(){let owners=[],pending3=new Map,stopped=!1;return{route(owns){owners.push(owns)},attach(server3,handle2){server3.on("upgrade",(req,socket,head)=>{if(stopped||!(socket instanceof Socket)){socket.destroy();return}let res=new ServerResponse(req);res.assignSocket(socket),res.setHeader("connection","close"),socket.on("error",()=>socket.destroy()),res.once("finish",()=>socket.
32836
+ undo(auth,res,threadId,requestId)}}import{createHash as createHash133}from"node:crypto";import{request as request10}from"node:http";import{ServerResponse}from"node:http";import{Socket}from"node:net";var HANDSHAKE_MS=1e4,EARLY_BYTES=64*1024;function createUpgrades(){let owners=[],pending3=new Map,stopped=!1;return{route(owns){owners.push(owns)},attach(server3,handle2){server3.on("upgrade",(req,socket,head)=>{if(stopped||!(socket instanceof Socket)){socket.destroy();return}let res=new ServerResponse(req);res.assignSocket(socket),res.setHeader("connection","close"),socket.on("error",()=>socket.destroy()),res.once("finish",()=>socket.
32827
32837
  end(()=>socket.destroy()));let path8;try{path8=new URL(req.url??"","http://localhost").pathname}catch{res.writeHead(400).end();return}if(!owners.some(owns=>owns(path8))){res.writeHead(404).end();return}let upgrade={socket,head,release:()=>socket.off("data",buffer)},buffer=data4=>{upgrade.head.length+data4.length>EARLY_BYTES?socket.destroy():upgrade.head=Buffer.concat([upgrade.head,data4])};socket.on("data",buffer),socket.once("end",()=>socket.destroy()),socket.once("close",()=>{upgrade.release(),
32828
32838
  pending3.delete(req)}),pending3.set(req,upgrade);let timeout3=setTimeout(()=>socket.destroy(),HANDSHAKE_MS);timeout3.unref(),socket.once("close",()=>clearTimeout(timeout3)),handle2(req,res).catch(()=>{res.headersSent?socket.destroy():res.writeHead(500).end()}).finally(()=>clearTimeout(timeout3))})},pending(req){return pending3.get(req)},close(){stopped=!0;for(let upgrade of pending3.values())upgrade.socket.destroy()}}}var ROUTE2=/^\/api\/desktop-viewer\/(local\/(?:shared|bot-[a-f0-9]{64}|pool-\d+)|vps\/[\w-]+)(\/websockify)?$/,HANDSHAKE_MS2=1e4,RECHECK_MS5=5e3,WS_GUID="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",BOT_ID9=/^[\w-]+$/,CONTROL_LEASE=/^[A-Za-z0-9_-]{16,120}$/;function desktopViewerUrl(target4,threadId){return`/desktop-viewer#${new URLSearchParams({target:target4,...threadId?{threadId}:{}})}`}function createDesktopViewer(deps){let upgrades2=deps.upgrades??createUpgrades(),ownGate=deps.upgrades===void 0;upgrades2.
32829
32839
  route(path8=>!!ROUTE2.exec(path8)?.[2]);let viewers=new Map,stopped=!1;return{route:async({req,res,url:url3,path:path8,method:method2,auth,json:json7})=>{let match5=ROUTE2.exec(path8);if(!match5)return PASS;if(res.setHeader("cache-control","private, no-store"),method2!=="GET")return json7(res,405,{error:"method not allowed"});if(!auth.scopes.includes("admin")||!isSameOrigin(req))return json7(res,403,{error:"forbidden"});let botId2=url3.searchParams.get("botId"),controlLeaseId=url3.searchParams.get(
@@ -32833,7 +32843,7 @@ if(botId2!==null&&(match5[1]==="local/shared"||match5[1].startsWith("local/pool-
32833
32843
  tatus"in error66?error66.status:502;return json7(res,typeof status5=="number"&&status5>=400&&status5<600?status5:502,{error:"The desktop is not available. Open it again from Limix Bot."})}if(res.destroyed||upgrade?.socket.destroyed)return;let live2=()=>deps.live(auth)&&deps.target(match5[1])?.key===target4.key&&(connection.live?.()??!0);if(!live2())return json7(res,401,{error:"Viewer access expired"});if(!holds())return json7(res,409,{error:"Take control of this computer first"});if(!Number.isInteger(
32834
32844
  connection.port)||connection.port<1||connection.port>65535)return json7(res,409,{error:"The desktop viewer is not available."});if(!match5[2])return json7(res,200,{password:connection.password});if(!upgrade||!pending3)return json7(res,426,{error:"WebSocket upgrade required"});let key7=req.headers["sec-websocket-key"];if(req.headers.upgrade?.toLowerCase()!=="websocket"||req.headers["sec-websocket-version"]!=="13"||typeof key7!="string"||!/^[A-Za-z0-9+/]{22}==$/.test(key7))return json7(res,400,{error:"\
32835
32845
  Invalid WebSocket handshake"});let upstream=request10({hostname:"127.0.0.1",port:connection.port,path:"/websockify",headers:{Upgrade:"websocket",Connection:"Upgrade","Sec-WebSocket-Key":key7,"Sec-WebSocket-Version":"13"}}),{socket}=upgrade,peer,recheck,release3=connection.retain?.(),closed=!1,timeout3=setTimeout(()=>fail14(),HANDSHAKE_MS2);timeout3.unref(),upgrade.close=()=>{closed||(closed=!0,release3?.(),clearTimeout(timeout3),clearInterval(recheck),upstream.destroy(),peer?.destroy(),socket.destroy())};
32836
- let fail14=()=>{if(!closed){if(peer||socket.destroyed){upgrade.close();return}!res.headersSent&&!socket.destroyed&&json7(res,502,{error:"Could not connect to the desktop viewer"}),upstream.destroy()}};socket.once("close",upgrade.close),upstream.once("error",fail14),upstream.once("response",answer2=>{answer2.resume(),fail14()}),upstream.once("upgrade",(answer2,remote2,remoteHead)=>{let accept=createHash132("sha1").update(key7+WS_GUID).digest("base64");if(!live2()||!holds()||socket.destroyed||answer2.
32846
+ let fail14=()=>{if(!closed){if(peer||socket.destroyed){upgrade.close();return}!res.headersSent&&!socket.destroyed&&json7(res,502,{error:"Could not connect to the desktop viewer"}),upstream.destroy()}};socket.once("close",upgrade.close),upstream.once("error",fail14),upstream.once("response",answer2=>{answer2.resume(),fail14()}),upstream.once("upgrade",(answer2,remote2,remoteHead)=>{let accept=createHash133("sha1").update(key7+WS_GUID).digest("base64");if(!live2()||!holds()||socket.destroyed||answer2.
32837
32847
  headers["sec-websocket-accept"]!==accept||answer2.headers.upgrade?.toLowerCase()!=="websocket"){remote2.destroy(),fail14();return}clearTimeout(timeout3),peer=remote2,remote2.once("error",upgrade.close),remote2.once("close",upgrade.close),pending3.release(),res.detachSocket(socket),socket.write(`HTTP/1.1 101 Switching Protocols\r
32838
32848
  Upgrade: websocket\r
32839
32849
  Connection: Upgrade\r
@@ -33282,13 +33292,13 @@ sted"},close2=(threadId,watch,how)=>{pause(watch);let posted=watch.phase==="post
33282
33292
  return{onEvent(event2){let watch=watches.get(event2.threadId);if(event2.type==="turn.started"){if(!event2.turnId||watch?.turnId===event2.turnId)return;watch&&close2(event2.threadId,watch,"over");let next={turnId:event2.turnId,timer:null,phase:"waiting",row:null};watches.set(event2.threadId,next),arm(event2.threadId,next);return}if(!(!watch||event2.turnId!==void 0&&event2.turnId!==watch.turnId)){if(AI_OUTPUT.has(event2.type)){close2(event2.threadId,watch,"settled");return}switch(event2.type){case"\
33283
33293
  runtime.error":close2(event2.threadId,watch,"over");return;case"turn.wait_started":pause(watch);return;case"turn.wait_ended":watch.phase==="waiting"&&arm(event2.threadId,watch);return;case"turn.completed":close2(event2.threadId,watch,"over"),watches.delete(event2.threadId);return;default:return}}}}}function closeLeftOpen(deps){let open14;try{open14=(deps.leftOpen??openRescueMessages)()}catch(error66){console.error("first-reply rescue: could not read the notices left open:",error66 instanceof Error?
33284
33294
  error66.message:error66);return}for(let{threadId,message:message8}of open14){let tool5=message8.tool;if(!tool5?.rescue)continue;let botName=deps.store.bot(tool5.rescue.botId)?.name,name6=botName?firstReplyOverName(botName,tool5.rescue.ai):tool5.name;try{deps.store.patchMessage(threadId,message8.id,{tool:{...tool5,name:name6,rescue:{...tool5.rescue,over:!0}}})}catch(error66){console.error(`first-reply rescue: could not close a notice in ${threadId}:`,error66 instanceof Error?error66.message:error66)}}}function createReactionRoutes(deps){return async({req,res,path:path8,method:method2,auth,json:json7,readBody:readBody2})=>{let m3=path8.match(/^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/reactions$/);if(!m3||method2!=="POST")return PASS;let body3=await readBody2(req),emoji3=normalizeReaction(body3?.emoji);if(!emoji3)return json7(res,400,{error:`emoji must be one of ${REACTIONS.join(" ")}`});if(body3.on!==void 0&&typeof body3.on!="boolean")return json7(res,400,{error:"on must be true or false"});
33285
- let notYours=deps.cloudGuestSendRefusal(auth,m3[1]);if(notYours)return json7(res,403,{error:notYours});try{return json7(res,200,await deps.react({auth,threadId:m3[1],messageId:m3[2],emoji:emoji3,reactor:deps.reactorFor(auth),on:body3.on}))}catch(error66){let{status:status5,code}=error66;if(typeof status5!="number")throw error66;return json7(res,status5,{error:error66 instanceof Error?error66.message:String(error66),...typeof code=="string"?{code}:{}})}}}import{createHash as createHash133}from"node:crypto";var conflict=message8=>Object.assign(new Error(message8),{status:409}),decidedByBot=card=>card.answeredBy?.kind==="bot";function createPersonReplies(deps){let{store:store5,sendSequencer:sendSequencer2}=deps;function room(threadId){let group2=store5.groupByThread(threadId),owned=group2?group2.dm?group2.threadId===threadId:!!store5.groupTaskByThread(group2.id,threadId):!1;return{group:group2,owned}}async function deliver(reply5){let{auth,threadId,owner:owner2,target:target4,answer:answer2,sendId,about,
33295
+ let notYours=deps.cloudGuestSendRefusal(auth,m3[1]);if(notYours)return json7(res,403,{error:notYours});try{return json7(res,200,await deps.react({auth,threadId:m3[1],messageId:m3[2],emoji:emoji3,reactor:deps.reactorFor(auth),on:body3.on}))}catch(error66){let{status:status5,code}=error66;if(typeof status5!="number")throw error66;return json7(res,status5,{error:error66 instanceof Error?error66.message:String(error66),...typeof code=="string"?{code}:{}})}}}import{createHash as createHash134}from"node:crypto";var conflict=message8=>Object.assign(new Error(message8),{status:409}),decidedByBot=card=>card.answeredBy?.kind==="bot";function createPersonReplies(deps){let{store:store5,sendSequencer:sendSequencer2}=deps;function room(threadId){let group2=store5.groupByThread(threadId),owned=group2?group2.dm?group2.threadId===threadId:!!store5.groupTaskByThread(group2.id,threadId):!1;return{group:group2,owned}}async function deliver(reply5){let{auth,threadId,owner:owner2,target:target4,answer:answer2,sendId,about,
33286
33296
  via,callId}=reply5,{group:group2,owned}=room(threadId);if(group2&&(!owned||!group2.memberIds.includes(owner2.id)))throw conflict(`the bot that ${about==="question"?"asked this question":"wrote this message"} is no longer in this conversation`);if(!group2&&!store5.taskByThread(owner2.id,threadId))throw conflict(`the ${about}'s conversation no longer exists`);let text34=group2?`@${owner2.name}: ${answer2}`:answer2,key7=group2?`group:${group2.id}:${threadId}:${sendId}`:`bot:${owner2.id}:${threadId}\
33287
33297
  :${sendId}`;return sendSequencer2.run(key7,sendFingerprint(text34,target4.id,group2?"chat":void 0),async()=>{let accepted=acceptedSendMatch(store5.messagesFor(threadId),sendId,text34,target4.id,group2?"chat":void 0);if(accepted.kind==="conflict")throw conflict(`this ${about} already has a different recorded answer`);if(accepted.kind==="match")return{queued:!1,repeated:!0};let queuedDirect=group2?null:queuedSteeredMessage(owner2.id,threadId,sendId);if(queuedDirect){if(queuedDirect.text!==text34||
33288
33298
  queuedDirect.replyToId!==target4.id)throw conflict(`this ${about} already has a different queued answer`);return{queued:!0}}let queuedRoom=group2?queuedChannelMessage(group2.id,threadId,sendId):null;if(queuedRoom){if(queuedRoom.text!==text34||queuedRoom.replyToId!==target4.id||queuedRoom.mode!=="chat")throw conflict(`this ${about} already has a different queued answer`);return{queued:!0}}let refused3=reply5.refusal?.();if(refused3)throw conflict(refused3);deps.assertWithinBudget();let sender2=deps.
33289
33299
  messageSender(auth),trigger=deps.usageTriggerFor(auth);if(group2){let current3=store5.group(group2.id);if(!current3||!owned)throw conflict("the room switched tasks before it could receive the answer");return deps.groupThreadIsWorking(current3.id,threadId)?(queueChannelMessage(current3.id,threadId,text34,{replyToId:target4.id,sendId,mode:"chat",sender:sender2,trigger,reaction:target4.reactedWith,mentions:[owner2.id]}),{queued:!0}):(deps.startGroupTurn(current3.id,text34,target4,sendId,"chat",void 0,
33290
33300
  {threadId,sender:sender2,trigger,mentions:[owner2.id]}),{queued:!1})}return{queued:!!(await deps.startOrQueueDirectMessage(owner2.id,threadId,text34,target4,sendId,sender2,trigger,via,callId)).queued}})}function withdraw(threadId,owner2,sendId){let group2=store5.groupByThread(threadId);if(group2){let queued2=queuedChannelMessage(group2.id,threadId,sendId);queued2&&cancelChannelMessage(group2.id,queued2.id);return}let queued=queuedSteeredMessage(owner2.id,threadId,sendId);queued&&cancelSteeredMessage(
33291
- owner2.id,queued.id,threadId)}async function deliverLateQuestionAnswer2(auth,threadId,requestId,answer2,cardMessage,owner2,via,callId){let latestCard=()=>store5.messagesFor(threadId).find(message8=>message8.id===cardMessage.id)?.card,receipt=await deliver({auth,threadId,owner:owner2,target:cardMessage,answer:answer2,via,callId,about:"question",sendId:`late-question-${createHash133("sha256").update(`${threadId}:${requestId}`).digest("hex").slice(0,32)}`,refusal:()=>{let card=latestCard();return!card||
33301
+ owner2.id,queued.id,threadId)}async function deliverLateQuestionAnswer2(auth,threadId,requestId,answer2,cardMessage,owner2,via,callId){let latestCard=()=>store5.messagesFor(threadId).find(message8=>message8.id===cardMessage.id)?.card,receipt=await deliver({auth,threadId,owner:owner2,target:cardMessage,answer:answer2,via,callId,about:"question",sendId:`late-question-${createHash134("sha256").update(`${threadId}:${requestId}`).digest("hex").slice(0,32)}`,refusal:()=>{let card=latestCard();return!card||
33292
33302
  card.answered&&!decidedByBot(card)||card.dismissed?"this question has already been answered":null}}),latest=latestCard();if(latest&&(!latest.answered||decidedByBot(latest))&&!latest.dismissed){let{answeredBy:_decider,...card}=latest;store5.patchMessage(threadId,cardMessage.id,{card:{...card,answered:"answer",answeredText:answer2,dismissed:!1}})}return receipt}return{deliver,withdraw,deliverLateQuestionAnswer:deliverLateQuestionAnswer2}}var EXACT=new Set(["POST /api/internal/hook","POST /api/internal/tool-timing","GET /api/internal/tool-result","POST /api/internal/tool-result","POST /api/internal/options-card","POST /api/internal/escalate","POST /api/internal/people/message","POST /api/internal/attach-file","POST /api/internal/voice-note","GET /api/internal/agents","GET /api/internal/rooms","GET /api/internal/room-targets","GET /api/internal/threads","POST /api/internal/threads","GET /api/internal/assignment-status","GET /api/i\
33293
33303
  nternal/session-search","GET /api/internal/session-read","GET /api/internal/skills","GET /api/internal/team-setup-catalog","GET /api/internal/team-library","GET /api/internal/engine-limits","GET /api/internal/triggers","GET /api/internal/trigger-events","GET /api/internal/waits","POST /api/internal/waits","POST /api/internal/waits/cancel","POST /api/internal/helpers/decide","POST /api/internal/helpers/extract","POST /api/internal/coordinate-bots","POST /api/internal/post-to-room","POST /api/inte\
33294
33304
  rnal/retry-thread","POST /api/internal/trigger-requests","POST /api/internal/manage-room","POST /api/internal/meetings/join","POST /api/internal/meetings/status","POST /api/internal/meetings/chat","POST /api/internal/meetings/leave","POST /api/internal/meetings/notes","POST /api/internal/memory","POST /api/internal/memory/log","POST /api/internal/team-memory","POST /api/internal/profile-requests","POST /api/internal/model-requests","POST /api/internal/team-setup-requests","POST /api/internal/bot\
@@ -33395,12 +33405,12 @@ long)}. ${SAY_LONG_WAIT} Each has its own line in this inbox, and that is where
33395
33405
  ed"),{status:passed.status})):Promise.resolve(repeated?{queued:!1,repeated:!0}:{queued:!1}):null},view(auth){if(!team&&deps.place)return deps.place.view(auth);let me2=sessionPerson(auth);return team&&me2?inbox.view(me2.key):null},count(auth){if(!team&&deps.place)return deps.place.count(auth);let me2=sessionPerson(auth),view3=team&&me2?inbox.view(me2.key):null;return view3?view3.rows.filter(row=>row.tab==="needs-you"||row.tab==="info"&&row.unread).length:null},markDone(auth,id12){if(!team&&deps.place)
33396
33406
  return deps.place.markDone(auth,id12);let me2=sessionPerson(auth);return team&&me2?inbox.markDone(me2.key,id12):"unknown"},markRead(auth,id12){if(!team&&deps.place)return deps.place.markRead(auth,id12);let me2=sessionPerson(auth);return!!(team&&me2&&inbox.markRead(me2.key,id12))},needsYou(auth){let me2=sessionPerson(auth);return!team||!me2?[]:inbox.unseen(me2.key).filter(item=>item.kind==="message"&&now2()-item.at<WAITING_MS).map(item=>({kind:"message",id:item.id,at:item.at,botId:item.botId,threadId:item.
33397
33407
  threadId,messageId:item.id,from:item.from,...item.fromEmail?{fromEmail:item.fromEmail}:{},text:item.text}))},seen(auth,threadId){team||deps.place?.seen(auth,threadId);let me2=sessionPerson(auth);me2&&inbox.seen(me2.key,threadId)},arrived(auth){let me2=sessionPerson(auth);if(!team||!me2)return{returned:!1};let day2=new Date(now2()).toDateString();if(arrivedOn.get(me2.key)===day2)return{returned:!1};arrivedOn.set(me2.key,day2);let waiting2=inbox.unseen(me2.key)[0];return waiting2?{returned:!1,open:{
33398
- botId:waiting2.botId,threadId:waiting2.threadId}}:{returned:!1}},route(notification,how={}){return!team&&deps.place?deps.place.route(notification,how):inbox.route(notification,how)},handedResult(work,requester){team||deps.place?.handedResult(work,requester)},stop(){unsubscribe2(),inbox.stop(),deps.place?.stop()}}}init_zod();init_atomic();import{createHash as createHash134,createHmac as createHmac10,randomBytes as randomBytes39}from"node:crypto";import{mkdirSync as mkdirSync128,readdirSync as readdirSync64,readFileSync as readFileSync205,rmSync as rmSync69}from"node:fs";import{join as join290}from"node:path";var TEAM_AWAY_ADMIN_PATH="/api/cloud/machines/team-away",AWAY_EMAILS_PATH="/api/me/away-emails",AWAY_WINDOW_MS=10*6e4,AWAY_ASK_MIN_MS=5*6e4,AWAY_GAP_MS=30*6e4,AWAY_DAILY_MAX=6,AWAY_STRETCH_MS=720*6e4,AWAY_ITEMS_MAX=10,AWAY_EMAILS_FILE="away-emails.json",DAY_MS17=1440*6e4,KEYS_KEEP_MS=7*DAY_MS17,KEYS_MAX=5e3,RETRY_MS5=[6e4,5*6e4],UNAVAILABLE_MS=60*6e4,REFRESH_GAP_MS=6e4,FETCH_TIMEOUT_MS6=15e3,ANSWER_MAX_BYTES3=64*1024,PERSON6=/^p_[\w-]{22}$/u,answerSchema4=external_exports.object({v:external_exports.
33399
- literal(1),results:external_exports.array(external_exports.object({id:external_exports.string(),state:external_exports.string()})).max(50),off:external_exports.array(external_exports.string().max(320)).max(1e3).optional()});function teamAwaySignature(secret,machineId,timestamp5,nonce,body3){let bodyHash=createHash134("sha256").update(body3).digest("base64url");return createHmac10("sha256",secret).update(`omb-team-away-v1
33408
+ botId:waiting2.botId,threadId:waiting2.threadId}}:{returned:!1}},route(notification,how={}){return!team&&deps.place?deps.place.route(notification,how):inbox.route(notification,how)},handedResult(work,requester){team||deps.place?.handedResult(work,requester)},stop(){unsubscribe2(),inbox.stop(),deps.place?.stop()}}}init_zod();init_atomic();import{createHash as createHash135,createHmac as createHmac10,randomBytes as randomBytes39}from"node:crypto";import{mkdirSync as mkdirSync128,readdirSync as readdirSync64,readFileSync as readFileSync205,rmSync as rmSync69}from"node:fs";import{join as join290}from"node:path";var TEAM_AWAY_ADMIN_PATH="/api/cloud/machines/team-away",AWAY_EMAILS_PATH="/api/me/away-emails",AWAY_WINDOW_MS=10*6e4,AWAY_ASK_MIN_MS=5*6e4,AWAY_GAP_MS=30*6e4,AWAY_DAILY_MAX=6,AWAY_STRETCH_MS=720*6e4,AWAY_ITEMS_MAX=10,AWAY_EMAILS_FILE="away-emails.json",DAY_MS17=1440*6e4,KEYS_KEEP_MS=7*DAY_MS17,KEYS_MAX=5e3,RETRY_MS5=[6e4,5*6e4],UNAVAILABLE_MS=60*6e4,REFRESH_GAP_MS=6e4,FETCH_TIMEOUT_MS6=15e3,ANSWER_MAX_BYTES3=64*1024,PERSON6=/^p_[\w-]{22}$/u,answerSchema4=external_exports.object({v:external_exports.
33409
+ literal(1),results:external_exports.array(external_exports.object({id:external_exports.string(),state:external_exports.string()})).max(50),off:external_exports.array(external_exports.string().max(320)).max(1e3).optional()});function teamAwaySignature(secret,machineId,timestamp5,nonce,body3){let bodyHash=createHash135("sha256").update(body3).digest("base64url");return createHmac10("sha256",secret).update(`omb-team-away-v1
33400
33410
  ${machineId}
33401
33411
  ${timestamp5}
33402
33412
  ${nonce}
33403
- ${bodyHash}`).digest("base64url")}var awayKey=about=>createHash134("sha256").update(`omb-team-away
33413
+ ${bodyHash}`).digest("base64url")}var awayKey=about=>createHash135("sha256").update(`omb-team-away
33404
33414
  ${about}`).digest("hex"),prefSchema=external_exports.object({version:external_exports.literal(1),on:external_exports.boolean(),synced:external_exports.boolean()});function createTeamAway(deps){let now2=deps.now??Date.now,log7=deps.log??(()=>{}),fetcher=deps.fetchImpl??globalThis.fetch,setTimer=deps.setTimer??((run12,ms2)=>setTimeout(run12,ms2)),clearTimer2=deps.clearTimer??(timer4=>clearTimeout(timer4)),windowMs=deps.windowMs??AWAY_WINDOW_MS,askMinMs=Math.min(AWAY_ASK_MIN_MS,windowMs/2),pending3=new Map,
33405
33415
  timers=new Map,sentKeys=new Map,sentAt2=new Map,stretches=new Map,retries=new Map,unavailableUntil=0,stopped=!1,lastRefresh=0,syncTimer=null,prefPath=person2=>join290(deps.dataDir,"people",person2,AWAY_EMAILS_FILE),readPref=person2=>{if(!PERSON6.test(person2))return null;try{let parsed3=prefSchema.safeParse(JSON.parse(readFileSync205(prefPath(person2),"utf8")));return parsed3.success?parsed3.data:null}catch{return null}},writePref=(person2,pref)=>{if(PERSON6.test(person2))try{if(!pref||pref.on&&
33406
33416
  pref.synced){rmSync69(prefPath(person2),{force:!0});return}mkdirSync128(join290(deps.dataDir,"people",person2),{recursive:!0,mode:448}),writeFileAtomic(prefPath(person2),`${JSON.stringify(pref)}
@@ -33520,7 +33530,7 @@ groupByThread(threadId)){let run12=generation2===void 0?void 0:deps.roomRun(gene
33520
33530
  person2,since)?person2:null}let handed2=run12.handedFor;return handed2&&onlyTheirs(thread2,handed2.person,handed2.since)?handed2.person:null}let request11=deps.direct(threadId),turn2=generation2??request11?.generation;if(!request11||!turn2||request11.stopped||!request11.generations.has(turn2)||request11.automation!==void 0)return null;if(request11.messageId){let line6=thread2.find(message8=>message8.id===request11.messageId),person2=linePerson2(line6);if(line6&&person2)return onlyTheirs(thread2,
33521
33531
  person2,line6.at)?person2:null}let handed=request11.origin?.kind==="user"?request11.origin.person:void 0;return handed&&onlyTheirs(thread2,handed,0)?handed:null};return{requester,handOn(turn2,work,lends=!1){let person2=requester(turn2.threadId,turn2.generation);deps.handed.record(work.id,person2,lends),work.rootId===turn2.generation&&deps.handed.record(work.rootId,person2,lends)},handedOrigin(origin2,workId){let handed=deps.handed.get(workId);return withPerson(origin2,handed?.person,handed?.lends===
33522
33532
  !0)},handedRun(workId){let entry3=deps.handed.get(workId);return entry3?{person:entry3.person,since:entry3.at}:void 0}}}var keptPrivate=place2=>!!place2.child&&place2.parent!==place2.child,lastLineAsks=text34=>/^needs input:/i.test(text34.trimEnd().split(/\r?\n/).at(-1)?.trim()??"");function privateHandBack(outcome,place2){if(!keptPrivate(place2))return outcome;let where2=`${place2.bot}'s chat with ${place2.person}`,question=`${place2.bot} has a question for ${place2.person}, in ${where2}.`,{evidence:_evidence,
33523
- ...rest}=outcome,asks2=lastLineAsks(outcome.text);return{...rest,text:asks2?`NEEDS INPUT: ${question}`:`${outcome.ok?"Done":"It stopped before it finished"}. The result is in ${where2}.`,...outcome.cards?{cards:{...outcome.cards,question}}:{},...outcome.approvalAsk?{approvalAsk:question}:{},...asks2||outcome.cards||outcome.approvalAsk?{privateQuestion:!0}:{}}}function createTurnCallSignals(isActive){let calls2=new Map;return{signal(grant,res){let call2=new AbortController;calls2.set(call2,grant);let onClose=()=>{calls2.delete(call2),res.writableEnded||call2.abort()};return res.closed?onClose():res.once("close",onClose),call2.signal},sweep(){for(let[call2,grant]of calls2)isActive(grant)||(calls2.delete(call2),call2.abort())}}}init_user_errors();import{basename as basename41,join as join294}from"node:path";import{createWriteStream as createWriteStream5}from"node:fs";import{mkdtemp as mkdtemp9,readFile as readFile17,rm as rm15}from"node:fs/promises";import{tmpdir as tmpdir25}from"node:os";import{join as join293}from"node:path";import{pipeline as pipeline9}from"node:stream/promises";var XMIND_MIME="application/vnd.xmind.workbook",MAX_ARCHIVE_ENTRIES=1e4,MAX_CONTENT_BYTES=32*1024*1024,MAX_TOPICS=1e5,MAX_XML_ELEMENTS=5e5;function statusError6(status5,message8){return Object.assign(new Error(message8),{status:status5})}var text33=value3=>typeof value3=="string"?value3:"",list9=value3=>Array.isArray(value3)?value3:[],record30=value3=>value3&&typeof value3=="object"?value3:{};function topicFromJson(raw,budget,floating=!1){if(--budget.topics<0)throw new Error("too many topics");let topic=record30(
33533
+ ...rest}=outcome,asks2=lastLineAsks(outcome.text);return{...rest,text:asks2?`NEEDS INPUT: ${question}`:`${outcome.ok?"Done":"It stopped before it finished"}. The result is in ${where2}.`,...outcome.cards?{cards:{...outcome.cards,question}}:{},...outcome.approvalAsk?{approvalAsk:question}:{},...asks2||outcome.cards||outcome.approvalAsk?{privateQuestion:!0}:{}}}function createTurnCallSignals(isActive){let calls2=new Map;return{signal(grant,res){let call2=new AbortController;calls2.set(call2,grant);let onClose=()=>{calls2.delete(call2),res.writableEnded||call2.abort()};return res.closed?onClose():res.once("close",onClose),call2.signal},sweep(){for(let[call2,grant]of calls2)isActive(grant)||(calls2.delete(call2),call2.abort())}}}init_user_errors();import{basename as basename42,join as join294}from"node:path";import{createWriteStream as createWriteStream5}from"node:fs";import{mkdtemp as mkdtemp9,readFile as readFile17,rm as rm15}from"node:fs/promises";import{tmpdir as tmpdir25}from"node:os";import{join as join293}from"node:path";import{pipeline as pipeline9}from"node:stream/promises";var XMIND_MIME="application/vnd.xmind.workbook",MAX_ARCHIVE_ENTRIES=1e4,MAX_CONTENT_BYTES=32*1024*1024,MAX_TOPICS=1e5,MAX_XML_ELEMENTS=5e5;function statusError6(status5,message8){return Object.assign(new Error(message8),{status:status5})}var text33=value3=>typeof value3=="string"?value3:"",list9=value3=>Array.isArray(value3)?value3:[],record30=value3=>value3&&typeof value3=="object"?value3:{};function topicFromJson(raw,budget,floating=!1){if(--budget.topics<0)throw new Error("too many topics");let topic=record30(
33524
33534
  raw);return{title:text33(topic.title),note:text33(record30(record30(topic.notes).plain).content),labels:list9(topic.labels).map(text33).filter(Boolean),markers:list9(topic.markers).map(marker=>text33(record30(marker).markerId)).filter(Boolean),href:text33(topic.href),floating,children:Object.entries(record30(topic.children)).flatMap(([group2,topics])=>list9(topics).map(child2=>topicFromJson(child2,budget,group2==="detached")))}}function outlineFromJson(source5){let budget={topics:MAX_TOPICS},sheets=list9(
33525
33535
  JSON.parse(source5)).map(raw=>{let sheet=record30(raw);return{title:text33(sheet.title),root:sheet.rootTopic?topicFromJson(sheet.rootTopic,budget):null}});return renderSheets(sheets)}var XML_ENTITIES={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function decodeXml(value3){return value3.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(\w+));/gi,(entity,hex5,decimal2,named4)=>{if(named4)return XML_ENTITIES[named4]??entity;let code=hex5?Number.parseInt(hex5,16):Number(decimal2);return code>0&&code<=1114111?String.fromCodePoint(
33526
33536
  code):entity})}var localName=name6=>name6.slice(name6.indexOf(":")+1);function parseXml(source5){let root4={name:"",attrs:{},children:[],text:""},stack2=[root4],cursor3=0,elements=0;for(;cursor3<source5.length;){let top=stack2[stack2.length-1],open14=source5.indexOf("<",cursor3);if(open14<0)break;if(top.text+=decodeXml(source5.slice(cursor3,open14)),source5.startsWith("<![CDATA[",open14)){let end=source5.indexOf("]]>",open14+9);if(end<0)break;top.text+=source5.slice(open14+9,end),cursor3=end+3;continue}
@@ -33535,13 +33545,13 @@ labels.map(oneLine14).join(", ")}`:"",topic.markers.length?`markers: ${topic.mar
33535
33545
  `)+`
33536
33546
  `}async function outlineFromArchive(archive,scratch){let members2=await readZipDirectory(archive,MAX_ARCHIVE_ENTRIES),member=members2.find(entry3=>entry3.name==="content.json")??members2.find(entry3=>entry3.name==="content.xml");if(!member||member.uncompressedBytes>MAX_CONTENT_BYTES)throw new Error("no readable content");let extracted=join293(scratch,"content");await extractZipMember(archive,member,extracted,384);let source5=await readFile17(extracted,"utf8");return member.name==="content.json"?
33537
33547
  outlineFromJson(source5):outlineFromXml(source5)}async function saveXmindUpload(chunks,originalName,options2={}){let name6=`${originalName}.md`;sanitizeSharedFileName(name6,"text/markdown");let scratch=await mkdtemp9(join293(tmpdir25(),"omb-xmind-"));try{let archive=join293(scratch,"map.xmind"),bytes4=0;if(await pipeline9(chunks,async function*(source5){for await(let chunk of source5){if(bytes4+=chunk.byteLength,bytes4>104857600)throw statusError6(413,`file exceeds ${104857600} bytes`);yield chunk}},
33538
- createWriteStream5(archive,{mode:384})),bytes4===0)throw statusError6(400,"empty file");let outline;try{outline=await outlineFromArchive(archive,scratch)}catch{throw statusError6(400,"not a readable XMind file")}return await saveFile((async function*(){yield Buffer.from(outline,"utf8")})(),name6,"text/markdown",{uploadId:options2.uploadId})}finally{await rm15(scratch,{recursive:!0,force:!0})}}init_bot_visibility();import{createHash as createHash135}from"node:crypto";var RESULT_CLIP=280,NODES_SHOWN=500,ended=a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled",plural4=(n,one5,many2)=>`${n} ${n===1?one5:many2}`,names4=(rows2,label4)=>{let unique3=[...new Set(rows2.map(label4))];return unique3.length>3?`${unique3.slice(0,3).join(", ")} and ${unique3.length-3} more`:unique3.join(", ")};function jobView(input3){let nameOf2=botId2=>input3.nameOf(botId2)??botId2,shows=row=>input3.visible(row.assignee.destination.threadId),label4=row=>shows(row)?nameOf2(
33548
+ createWriteStream5(archive,{mode:384})),bytes4===0)throw statusError6(400,"empty file");let outline;try{outline=await outlineFromArchive(archive,scratch)}catch{throw statusError6(400,"not a readable XMind file")}return await saveFile((async function*(){yield Buffer.from(outline,"utf8")})(),name6,"text/markdown",{uploadId:options2.uploadId})}finally{await rm15(scratch,{recursive:!0,force:!0})}}init_bot_visibility();import{createHash as createHash136}from"node:crypto";var RESULT_CLIP=280,NODES_SHOWN=500,ended=a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled",plural4=(n,one5,many2)=>`${n} ${n===1?one5:many2}`,names4=(rows2,label4)=>{let unique3=[...new Set(rows2.map(label4))];return unique3.length>3?`${unique3.slice(0,3).join(", ")} and ${unique3.length-3} more`:unique3.join(", ")};function jobView(input3){let nameOf2=botId2=>input3.nameOf(botId2)??botId2,shows=row=>input3.visible(row.assignee.destination.threadId),label4=row=>shows(row)?nameOf2(
33539
33549
  row.assignee.botId):"a teammate",byId=new Map(input3.rows.map(row=>[row.id,row])),starts=new Set(input3.scopes),awaited2=new Map,counts=row=>{let known=awaited2.get(row.id);if(known!==void 0)return known;awaited2.set(row.id,!1);let parent2=row.parentId?byId.get(row.parentId):void 0,result2=starts.has(row.id)||row.reply!=="none"&&parent2!==void 0&&!ended(parent2)&&counts(parent2);return awaited2.set(row.id,result2),result2},scoped=input3.rows.filter(row=>starts.has(row.id)),live2=input3.scope==="\
33540
33550
  turn"?scoped.filter(row=>!ended(row)&&row.status!=="waiting"):input3.rows.filter(row=>!ended(row)&&counts(row)),parked2=live2.filter(row=>row.status==="needs_input"),asking2=live2.filter(row=>row.status==="running"&&input3.activityOf(row)==="waiting-on-you"),{conversation:conversation2}=input3,lead=scoped.at(-1),leadName=lead?nameOf2(lead.assignee.botId):conversation2.kind==="room"?"The room":"The bot",state,reason3;if(conversation2.activity==="waiting-on-you"||parked2.length||asking2.length){state=
33541
33551
  "needs-input";let first2=parked2[0]??asking2[0];reason3=first2?shows(first2)?`${nameOf2(first2.assignee.botId)} needs you: ${first2.question??"an approval is waiting in its conversation"}`:"A teammate needs an answer in a conversation you cannot open":`${leadName} is waiting for your answer in this conversation`}else if(conversation2.activity==="dead")state="failed",reason3=`${leadName}'s engine stopped unexpectedly`;else if(conversation2.activity==="no-signal")state="stalled",reason3=`No sign o\
33542
33552
  f progress from ${leadName}'s engine`;else if(conversation2.busy||conversation2.queued>0||live2.length){state="running";let teammates=live2.filter(row=>!starts.has(row.id));reason3=conversation2.busy?`${leadName} is working`:teammates.length?`Waiting on ${plural4(teammates.length,"teammate task","teammate tasks")}: ${names4(teammates,label4)}`:conversation2.queued>0?"A message is waiting its turn":`${leadName} is about to continue`}else if(!lead)state="idle",reason3="Nothing is running in this c\
33543
33553
  onversation";else if(lead.status==="completed"||lead.status==="waiting"){state="completed";let failed2=input3.rows.filter(row=>row.id!==lead.id&&(row.status==="failed"||row.status==="cancelled"));reason3=`${leadName} finished${failed2.length?`; ${plural4(failed2.length,"teammate task","teammate tasks")} did not complete (${names4(failed2,label4)})`:""}`}else state=lead.outcome==="stalled"?"stalled":"failed",reason3=`${leadName}'s work ended ${lead.status==="cancelled"||lead.outcome==="stopped"?"\
33544
- because it was stopped":`as ${lead.outcome??lead.status}`}${lead.outcomeDetail?`: ${lead.outcomeDetail}`:""}`;let shown3=input3.rows.filter(shows),listed3=shown3.slice(-NODES_SHOWN),ordered=[...listed3.filter(row=>starts.has(row.id)),...listed3.filter(row=>!starts.has(row.id))],tally={queued:0,running:0,waiting:0,needsInput:0,completed:0,failed:0,cancelled:0};for(let row of input3.rows)row.status==="needs_input"?tally.needsInput+=1:row.status==="resume"?tally.queued+=1:tally[row.status]+=1;let version5=createHash135(
33554
+ because it was stopped":`as ${lead.outcome??lead.status}`}${lead.outcomeDetail?`: ${lead.outcomeDetail}`:""}`;let shown3=input3.rows.filter(shows),listed3=shown3.slice(-NODES_SHOWN),ordered=[...listed3.filter(row=>starts.has(row.id)),...listed3.filter(row=>!starts.has(row.id))],tally={queued:0,running:0,waiting:0,needsInput:0,completed:0,failed:0,cancelled:0};for(let row of input3.rows)row.status==="needs_input"?tally.needsInput+=1:row.status==="resume"?tally.queued+=1:tally[row.status]+=1;let version5=createHash136(
33545
33555
  "sha256").update(JSON.stringify([state,conversation2.busy,conversation2.activity??"",conversation2.queued,asking2.map(row=>row.id),input3.rows.map(row=>[row.id,row.status,row.outcome??"",row.executions,row.question??""])])).digest("base64url").slice(0,16),node3=row=>{let{destination}=row.assignee,title3=input3.titleOf(row),result2=ended(row)||row.status==="waiting"||row.status==="needs_input"?row.result:"";return{id:row.id,rootId:row.rootId,...row.parentId?{parentId:row.parentId}:{},depth:row.depth,
33546
33556
  botId:row.assignee.botId,botName:nameOf2(row.assignee.botId),threadId:destination.threadId,...title3?{threadTitle:title3}:{},...destination.groupId?{groupId:destination.groupId}:{},status:row.status,...row.outcome?{outcome:row.outcome}:{},...row.outcomeDetail?{outcomeDetail:row.outcomeDetail}:{},...row.question?{question:row.question}:{},mode:row.mode,reply:row.reply,awaited:input3.scope==="job"?counts(row):starts.has(row.id),createdAt:row.createdAt,...row.startedAt!==void 0?{startedAt:row.startedAt}:
33547
33557
  {},...row.finishedAt!==void 0?{finishedAt:row.finishedAt}:{},executions:row.executions,...result2?{result:input3.full||result2.length<=RESULT_CLIP?result2:`${result2.slice(0,RESULT_CLIP)}\u2026`}:{}}};return{threadId:input3.threadId,scope:input3.scope,since:input3.since,now:input3.now,state,reason:reason3,version:version5,conversation:conversation2,roots:[...input3.scopes],nodes:ordered.map(node3),hidden:input3.rows.length-shown3.length,counts:tally,needsInput:[...parked2,...asking2].filter(row=>input3.
@@ -33572,10 +33582,10 @@ res,415,{error:"only images can be previewed here"});if(res.writeHead(200,{"cont
33572
33582
  ross-origin-resource-policy":"same-origin","referrer-policy":"no-referrer"}:{}}),file2.bytes===0)return await file2.handle.close(),res.end();let stream2=file2.handle.createReadStream({start:0,end:file2.bytes-1,autoClose:!0});stream2.on("error",()=>res.destroy()),res.on("close",()=>stream2.destroy()),stream2.pipe(res);return}if(method2==="POST"&&path8==="/api/attachments"){let uploadId;try{uploadId=validateAttachmentUploadId(url3.searchParams.get("uploadId")??void 0)}catch(error66){throw req.resume(),
33573
33583
  error66}let mime=(Array.isArray(req.headers["content-type"])?req.headers["content-type"][0]:req.headers["content-type"])?.split(";")[0]?.trim().toLowerCase();if(!mime||!extensionForMime(mime))return json7(res,400,{error:"content-type must be an image type"});let rawLength=Array.isArray(req.headers["content-length"])?req.headers["content-length"][0]:req.headers["content-length"],declaredLength=rawLength===void 0?void 0:Number(rawLength);if(declaredLength!==void 0&&(!Number.isSafeInteger(declaredLength)||
33574
33584
  declaredLength<0))return req.resume(),json7(res,400,{error:"content-length must be a non-negative integer"});if(declaredLength!==void 0&&declaredLength>IMAGE_MAX_BYTES)return req.resume(),json7(res,413,{error:`image exceeds ${IMAGE_MAX_BYTES} bytes`});let saved=await new Promise((resolve59,reject)=>{let chunks=[],received=0,settled2=!1,fail14=(status5,msg)=>{settled2||(settled2=!0,reject(Object.assign(new Error(msg),{status:status5})))};req.on("data",chunk=>{if(!settled2){if(received+=chunk.byteLength,
33575
- received>IMAGE_MAX_BYTES)return fail14(413,`image exceeds ${IMAGE_MAX_BYTES} bytes`);chunks.push(chunk)}}),req.on("end",async()=>{if(!settled2){settled2=!0;try{resolve59(await saveImageUpload(Buffer.concat(chunks),mime,uploadId))}catch(e){reject(e instanceof Error?e:new Error(String(e)))}}}),req.on("error",e=>fail14(400,e instanceof Error?e.message:String(e)))});return deps.uploads.note(auth,basename41(saved.path)),json7(res,201,saved)}if(method2==="POST"&&path8==="/api/files"){let uploadId;try{
33585
+ received>IMAGE_MAX_BYTES)return fail14(413,`image exceeds ${IMAGE_MAX_BYTES} bytes`);chunks.push(chunk)}}),req.on("end",async()=>{if(!settled2){settled2=!0;try{resolve59(await saveImageUpload(Buffer.concat(chunks),mime,uploadId))}catch(e){reject(e instanceof Error?e:new Error(String(e)))}}}),req.on("error",e=>fail14(400,e instanceof Error?e.message:String(e)))});return deps.uploads.note(auth,basename42(saved.path)),json7(res,201,saved)}if(method2==="POST"&&path8==="/api/files"){let uploadId;try{
33576
33586
  uploadId=validateAttachmentUploadId(url3.searchParams.get("uploadId")??void 0)}catch(error66){throw req.resume(),error66}let name6=url3.searchParams.get("name");if(!name6)return req.resume(),json7(res,400,{error:"name is required"});let rawType=Array.isArray(req.headers["content-type"])?req.headers["content-type"][0]:req.headers["content-type"],rawLength=Array.isArray(req.headers["content-length"])?req.headers["content-length"][0]:req.headers["content-length"],declaredLength=rawLength===void 0?void 0:
33577
33587
  Number(rawLength);if(declaredLength!==void 0&&(!Number.isSafeInteger(declaredLength)||declaredLength<0))return req.resume(),json7(res,400,{error:"content-length must be a non-negative integer"});if(declaredLength!==void 0&&declaredLength>104857600)return req.resume(),json7(res,413,{error:`file exceeds ${104857600} bytes`});try{let chunks=req.iterator({destroyOnReturn:!1}),saved=rawType?.split(";")[0].trim().toLowerCase()===XMIND_MIME?await saveXmindUpload(chunks,name6,{uploadId}):await saveFile(
33578
- chunks,name6,rawType??"",{uploadId,expectedBytes:declaredLength});return deps.uploads.note(auth,basename41(saved.path)),json7(res,201,saved)}catch(error66){throw req.resume(),error66}}if(path8==="/api/attachment-storage"&&deps.keptAttachments){if(method2==="GET")return json7(res,200,attachmentStorageUsage());if(method2==="POST"){let kept2=deps.keptAttachments();return kept2?json7(res,200,{...clearAttachments(kept2),...attachmentStorageUsage()}):json7(res,503,{error:"Routines are still loading. T\
33588
+ chunks,name6,rawType??"",{uploadId,expectedBytes:declaredLength});return deps.uploads.note(auth,basename42(saved.path)),json7(res,201,saved)}catch(error66){throw req.resume(),error66}}if(path8==="/api/attachment-storage"&&deps.keptAttachments){if(method2==="GET")return json7(res,200,attachmentStorageUsage());if(method2==="POST"){let kept2=deps.keptAttachments();return kept2?json7(res,200,{...clearAttachments(kept2),...attachmentStorageUsage()}):json7(res,503,{error:"Routines are still loading. T\
33579
33589
  ry again in a moment."})}}if(m3=path8.match(/^\/api\/attachments\/([\w.-]+)$/),m3&&method2==="DELETE"){let name6=m3[1];return!UPLOADED_NAME.test(name6)||!deps.uploads.owns(auth,name6)?json7(res,404,{error:"no such attachment"}):deps.attachmentInUse(name6)?json7(res,409,{...userError("serverError.attachment.alreadyInMessage")}):(deleteAttachment(join294(ATTACHMENTS_DIR,name6)),json7(res,200,{ok:!0}))}if(m3&&method2==="GET"){let attachment=readAttachment(m3[1]);if(!attachment)return json7(res,404,
33580
33590
  {error:"no such attachment"});let size3=attachment.bytes.byteLength,headers={"content-type":attachment.mime,"cache-control":"private, no-store","x-content-type-options":"nosniff"};if(attachment.mime.startsWith("audio/")){let rawRange=Array.isArray(req.headers.range)?req.headers.range[0]:req.headers.range,range6=parseAudioRange(rawRange,size3);if(range6.kind==="unsatisfiable")return res.writeHead(416,{...headers,"content-range":`bytes */${size3}`}),res.end();if(range6.kind==="range")return res.writeHead(
33581
33591
  206,{...headers,"content-length":String(range6.end-range6.start+1),"content-range":`bytes ${range6.start}-${range6.end}/${size3}`}),res.end(attachment.bytes.subarray(range6.start,range6.end+1))}return res.writeHead(200,{...headers,"content-length":String(size3)}),res.end(attachment.bytes)}if(method2==="GET"&&path8==="/api/search"){let q2=url3.searchParams.get("q")??"",rawLimit=url3.searchParams.get("limit"),limit2=rawLimit?Math.min(Math.max(Number(rawLimit)||0,1),100):40,threadId=url3.searchParams.
@@ -33597,7 +33607,7 @@ test(resumeKey))return{status:400,body:{error:"invalid resume key"}};if(!items.l
33597
33607
  bot.id,botName:owner2.bot.name,tool:"COMPOSIO_MANAGE_CONNECTIONS",summary:outside2,decision:"auto-denied",source:"connector-scope",rule:`scope:${outside2}:app`}),{status:403,body:{error:`${owner2.bot.name} has not been given access to ${outside2}; allow it under the bot's Access settings first`}}}let scopedLine=deps.refusal(capability2,slugs);if(scopedLine)return{status:409,body:{error:scopedLine}};let authConfigNote=await deps.composio.prepareConnectionAuthConfigs(cfg2,items),connectionState=await deps.
33598
33608
  composio.connectionStatus(cfg2,slugs).catch(()=>({}));requireActive();let messageIds=[];for(let item of items){let existing=deps.store.messagesFor(threadId).find(message9=>message9.connector?.resumeKey===resumeKey&&message9.connector.slug===item.slug&&(message9.connector.alias??"").toLowerCase()===(item.alias??"").toLowerCase());if(existing){messageIds.push(existing.id);continue}let toolkit=await deps.composio.toolkitCard(cfg2,item.slug);requireActive();let connected2=connectionState[item.slug]?.
33599
33609
  connected===!0,status5=item.alias?"required":connected2?"connected":"required",language=deps.language(threadId),description2=item.alias?connectorCardDescription(toolkit.label,item.alias,language):toolkit.blurb||connectorCardDescription(toolkit.label,void 0,language),message8=deps.store.appendMessage(threadId,{role:"bot",kind:"connector",text:connectorCardText(toolkit.label,item.alias,language),...owner2.group?{from:{botId:owner2.bot.id,name:owner2.bot.name,color:owner2.bot.color}}:{},connector:{
33600
- slug:item.slug,label:toolkit.label,description:description2,status:status5,resumeKey,...item.alias?{alias:item.alias}:{}}});messageIds.push(message8.id)}return deps.maybeResume(threadId,resumeKey),{status:200,body:{messageIds,...authConfigNote?{authConfigNote}:{}}}}return{request:request11}}import{createHash as createHash136,randomUUID as randomUUID92}from"node:crypto";import{readFileSync as readFileSync209}from"node:fs";import{join as join295}from"node:path";init_atomic();var CLOCK_SKEW_MS2=3e4,CODE_WAIT_MS=6e4,CODE_POLL_MS=5e3,BODIES_PER_MAILBOX=10,FAILED_ROUNDS=2,MAX_SCANNED=2e4,MAX_CANDIDATES2=20,NEAR_BEFORE=80,NEAR_AFTER=40,HTML_ENTITIES={nbsp:" ",amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},DROPPED_BLOCKS=/<(style|script|head|title)\b[^>]*>[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/giu,LINKS=/\bhttps?:\/\/\S+|\bwww\.\S+/giu,ADDRESSES2=/\S+@\S+/gu,DATES=/\b\d{4}-\d{1,2}-\d{1,2}\b|\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b/gu,COPYRIGHT=/(?:©|\(c\)|copyright)\s*\d{4}/giu,PHONES=/\+\d[\d ().-]{6,}\d|\(\d{3}\)\s*\d{3}[-. ]?\d{4}/gu,
33610
+ slug:item.slug,label:toolkit.label,description:description2,status:status5,resumeKey,...item.alias?{alias:item.alias}:{}}});messageIds.push(message8.id)}return deps.maybeResume(threadId,resumeKey),{status:200,body:{messageIds,...authConfigNote?{authConfigNote}:{}}}}return{request:request11}}import{createHash as createHash137,randomUUID as randomUUID92}from"node:crypto";import{readFileSync as readFileSync209}from"node:fs";import{join as join295}from"node:path";init_atomic();var CLOCK_SKEW_MS2=3e4,CODE_WAIT_MS=6e4,CODE_POLL_MS=5e3,BODIES_PER_MAILBOX=10,FAILED_ROUNDS=2,MAX_SCANNED=2e4,MAX_CANDIDATES2=20,NEAR_BEFORE=80,NEAR_AFTER=40,HTML_ENTITIES={nbsp:" ",amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},DROPPED_BLOCKS=/<(style|script|head|title)\b[^>]*>[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/giu,LINKS=/\bhttps?:\/\/\S+|\bwww\.\S+/giu,ADDRESSES2=/\S+@\S+/gu,DATES=/\b\d{4}-\d{1,2}-\d{1,2}\b|\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b/gu,COPYRIGHT=/(?:©|\(c\)|copyright)\s*\d{4}/giu,PHONES=/\+\d[\d ().-]{6,}\d|\(\d{3}\)\s*\d{3}[-. ]?\d{4}/gu,
33601
33611
  CANDIDATE=/(?<![\p{L}\p{N}-])(\d{3}[- ]\d{3}|\d{4}[- ]\d{4}|[A-Z0-9]{4}-[A-Z0-9]{4}|\d{4,10}|[A-Z0-9]{4,10})(?![\p{L}\p{N}-])/gu,NOT_A_CODE_WORD=/(?:zip|postal|post|promo|coupon|discount|voucher|country|area|referral|invite|gift|error|reference|tracking|bar|qr|source)[- ]?code\b/giu,CODE_WORD=/(?<![\p{L}\p{N}])(?:code|otp|passcode|pin|verification|verify|c[oó]digo|verifica[cç][aã]o|verificaci[oó]n|verifizierungscode|bestätigungscode|sicherheitscode|anmeldecode|код)(?![\p{L}\p{N}])/iu,CODE_MAIL_SUBJECT=/(?<![\p{L}\p{N}])(?:code|otp|passcode|verify|verification|sign[- ]?in|log[- ]?in|login|c[oó]digo|verifica[cç][aã]o)(?![\p{L}\p{N}])/iu;
33602
33612
  function bodyText(raw){return/<[a-z!/][^>]*>/iu.test(raw)?raw.replace(DROPPED_BLOCKS," ").replace(/<br\s*\/?>|<\/(?:p|div|tr|td|table|h[1-6]|li)>/giu,`
33603
33613
  `).replace(/<[^>]*>/gu," ").replace(/&(#\d+|#x[\da-f]+|[a-z]+);/giu,(whole3,name6)=>{if(name6[0]!=="#")return HTML_ENTITIES[name6.toLowerCase()]??whole3;let point11=name6[1]==="x"||name6[1]==="X"?Number.parseInt(name6.slice(2),16):Number(name6.slice(1));return Number.isFinite(point11)&&point11>0&&point11<=1114111?String.fromCodePoint(point11):whole3}):raw}function extractCode(subject,body3,boxes){let fixedLength=boxes!==void 0&&boxes>1?boxes:void 0,text34=`${subject}
@@ -33608,7 +33618,7 @@ listed3;try{listed3=await box2.list(options2.askedAt-CLOCK_SKEW_MS2)}catch{retur
33608
33618
  mail.id)}catch{text34=null}if(text34===null){round2.unreadable=!0;continue}result2=extractCode(mail.subject,text34,options2.boxes),read4.set(mail.id,result2)}result2.kind==="ambiguous"&&(round2.ambiguous=!0),result2.kind==="code"&&(options2.isUsed(result2.code)?round2.used=!0:round2.codes.add(result2.code))}return round2}async function waitForEmailCode(mailboxes,options2){let waitMs=options2.waitMs??CODE_WAIT_MS,pollMs=options2.pollMs??CODE_POLL_MS,deadline=options2.now()+waitMs,read4=mailboxes.
33609
33619
  map(()=>new Map),wrongSender=!1,used=!1,unreadable=!1,failedRounds=0;for(;;){let rounds=await Promise.all(mailboxes.map((box2,index4)=>look2(box2,options2,read4[index4]))),codes=new Set(rounds.flatMap(round2=>[...round2.codes]));if(rounds.some(round2=>round2.ambiguous)||codes.size>1)return{kind:"miss",why:"ambiguous"};if(codes.size===1)return{kind:"code",code:[...codes][0]};if(wrongSender||=rounds.some(round2=>round2.wrongSender),used||=rounds.some(round2=>round2.used),unreadable||=rounds.some(round2=>round2.
33610
33620
  unreadable),failedRounds=rounds.every(round2=>round2.failed)?failedRounds+1:0,failedRounds>=FAILED_ROUNDS||options2.now()>=deadline||options2.active?.()===!1)break;await options2.sleep(pollMs)}return failedRounds>=FAILED_ROUNDS||unreadable?{kind:"miss",why:"unreadable"}:used?{kind:"miss",why:"used"}:{kind:"miss",why:wrongSender?"wrong-sender":"not-found"}}var MAIL_CARD_FILE="email-code-card.json",LIST_LIMIT3=20,ACCOUNTS_PER_APP=3,ASKED_BEFORE_CALL_MS=12e4,REMEMBER_ASK_MS=15*6e4,REMEMBER_USED_MS=30*6e4,READS2={gmail:[GMAIL_FETCH_TOOL,GMAIL_MESSAGE_TOOL],outlook:[OUTLOOK_LIST_TOOL,OUTLOOK_MESSAGE_TOOL]};function readAsked(file2){try{let parsed3=JSON.parse(readFileSync209(file2,"utf8"));return new Map(Object.entries(parsed3.asked??{}).filter(([,at8])=>typeof at8=="number"))}catch{return new Map}}function createLoginMailCodes(deps){let run12={recentInbox,
33611
- readMessage:readMessage2,...deps.run},askedFile=join295(deps.dataDir,MAIL_CARD_FILE),asked=readAsked(askedFile),asks2=new Map,used=new Map,usedKey=(site,code)=>createHash136("sha256").update(`${site}\0${code}`).digest("hex"),forgetOld=(map7,before)=>{for(let[key7,at8]of map7)at8<before&&map7.delete(key7)},mayRead3=(bot,app)=>deps.appAllowed(app)&&READS2[app].every(slug4=>connectorAccessDecision(bot.connectorScopes,[{slug:slug4}],[app]).ok&&evaluateConnectorTools([slug4],bot.connectorTools,[app]).
33621
+ readMessage:readMessage2,...deps.run},askedFile=join295(deps.dataDir,MAIL_CARD_FILE),asked=readAsked(askedFile),asks2=new Map,used=new Map,usedKey=(site,code)=>createHash137("sha256").update(`${site}\0${code}`).digest("hex"),forgetOld=(map7,before)=>{for(let[key7,at8]of map7)at8<before&&map7.delete(key7)},mayRead3=(bot,app)=>deps.appAllowed(app)&&READS2[app].every(slug4=>connectorAccessDecision(bot.connectorScopes,[{slug:slug4}],[app]).ok&&evaluateConnectorTools([slug4],bot.connectorTools,[app]).
33612
33622
  allowed);function imapBox(account2){return{list:async sinceMs=>(await run12.recentInbox(account2,deps.imapGuard,{sinceMs,limit:LIST_LIMIT3})).map(mail=>({id:String(mail.uid),at:mail.at,from:mail.from,subject:mail.subject})),body:async id12=>(await run12.readMessage(account2,deps.imapGuard,{mailbox:"INBOX",uid:Number(id12)})).text}}function appBox(app,reads){return app==="gmail"?{list:async sinceMs=>(await reads.emails(sinceMs,LIST_LIMIT3)).emails,body:id12=>reads.messageBody(id12)}:{list:sinceMs=>reads.
33613
33623
  outlookEmails(sinceMs,LIST_LIMIT3),body:id12=>reads.outlookBody(id12)}}async function appBoxes(turn2,app){let cfg2=deps.cfg(),access2;if(deps.personApps().includes(app)){let person2=deps.turnPerson(turn2.threadId,turn2.generation);if(!person2)return[];let own4=deps.appsAccess(person2);if(!own4)return[];[cfg2,access2]=asPerson(cfg2,own4)}let state=(await deps.composio.connectedServices(cfg2,access2))[app];if(!state?.connected)return[];let active3=(state.accounts??[]).filter(one5=>/^active$/i.test(
33614
33624
  one5.status));return(active3.length>1?active3.slice(0,ACCOUNTS_PER_APP).map(one5=>one5.id):[void 0]).map(account2=>appBox(app,createConnectedReads({connected:async()=>null,...account2?{accounts:async()=>({[app]:account2})}:{},relay:(payload,session,signal)=>deps.composio.relayMcp(cfg2,payload,session,void 0,signal,access2)}).session()))}async function mailboxes(bot,turn2){let boxes=deps.imapAccounts(bot).slice(0,ACCOUNTS_PER_APP).map(imapBox),unknown2=!1;if(deps.composio.configured(deps.cfg())&&
@@ -33660,7 +33670,7 @@ origin||owner2.stopped||!owner2.generations.has(capability2.generation)?OUTSIDE:
33660
33670
  threadId)||cloudThreadStarters(threadId).some(person2=>person2!==void 0&&!cloudProvenOwnerPerson(person2)))return!1;let thread2=store4.messagesFor(threadId),last=thread2.at(-1),cached6=ownerOnlyCache.get(threadId),lastKey=last?`${last.id}:${last.card?.answeredBy?JSON.stringify(last.card.answeredBy):""}`:void 0;if(cached6&&cached6.length===thread2.length&&cached6.last===lastKey)return cached6.owner;let owner2=ownerOnlyConversation(thread2,cloudProvenOwnerPerson,cloudCardAnswerer)&&!thread2.some(cloudReportFromOthers);
33661
33671
  return ownerOnlyCache.size>5e3&&ownerOnlyCache.clear(),ownerOnlyCache.set(threadId,{length:thread2.length,last:lastKey,owner:owner2}),owner2}function noteForeignTurn(botId2,threadId,generation2){if(lendingMemory){foreignTurns.set(generation2,{botId:botId2,threadId});try{lendingMemory.noteForeignTurn(botId2)}catch(error66){console.warn(`lending: could not record a turn someone else started: ${error66.message}`)}}}function foreignTurnRunning(botId2){return[...foreignTurns.values()].some(turn2=>turn2.
33662
33672
  botId===botId2)}function sessionLendingPrincipal(auth){return CLOUD_HOME?CLOUD_PERSONAL&&cloudOwnerSession(auth)?CLOUD_HOME_LENDER:null:auth.kind==="session"?personKey(auth.session):null}var CLOUD_OWNER_PROFILE_FIELDS=["name","title","description","soul","notifications"];function cloudThreadRefusal(auth,threadId){return!CLOUD_HOME||cloudOwnerSession(auth)||auth.kind==="session"&&threadStarters.get(threadId)===actorKey(auth)?null:"On this Cloud you can only change conversations you started."}function cloudGuestSendRefusal(auth,threadId){
33663
- return!CLOUD_PERSONAL||auth.kind!=="session"||cloudOwnerSession(auth)||threadStarters.get(threadId)===actorKey(auth)?null:"On this Cloud you can only write in conversations you started. Start a new conversation with this bot."}var CLOUD_OWNER_KEY=CLOUD_PERSONAL?`p_${createHash137("sha256").update(`cloud-owner:${CLOUD_HOME.machineId}`).digest("base64url").slice(0,22)}`:null,cloudEarlierOwners={adopted:new Set,proven:new Set},cloudHome2=null,teamHost=createCloudTeamHost({team:CLOUD_TEAM,dataDir:DATA_DIR,
33673
+ return!CLOUD_PERSONAL||auth.kind!=="session"||cloudOwnerSession(auth)||threadStarters.get(threadId)===actorKey(auth)?null:"On this Cloud you can only write in conversations you started. Start a new conversation with this bot."}var CLOUD_OWNER_KEY=CLOUD_PERSONAL?`p_${createHash138("sha256").update(`cloud-owner:${CLOUD_HOME.machineId}`).digest("base64url").slice(0,22)}`:null,cloudEarlierOwners={adopted:new Set,proven:new Set},cloudHome2=null,teamHost=createCloudTeamHost({team:CLOUD_TEAM,dataDir:DATA_DIR,
33664
33674
  store:{groupByThread:threadId=>store4.groupByThread(threadId),get bots(){return store4.bots}},engineHomes,starters:threadStarters,markers:new Set([CLOUD_NOBODY_KEY,CLOUD_OUTSIDE_KEY]),language:appLanguage,serverProfile:{read:()=>cfg.profile,clear:()=>{adminActorScope.exit(()=>saveConfig({profile:{name:"",email:"",aboutMe:"",avatarUrl:""}})),Object.assign(cfg,loadConfig())}}}),teamOwners=createTeamOwners({team:CLOUD_TEAM,dataDir:DATA_DIR,sessions,store:()=>store4,audienceOf:threadId=>teamHost.audienceOf(
33665
33675
  threadId),starters:threadStarters}),mausbotOwnChat=createMausBotOwnChat({bots:()=>store4.bots,starters:threadStarters,personKey:email3=>personKey({id:"",email:email3}),moveNotes:(from,to2,person2)=>moveMemoryLayer(from,to2,personLanguages.forLine(person2))}),personRooms=createPersonRooms({reads:CLOUD_TEAM?createRoomReads(DATA_DIR,person2=>{botOrders?.forgetPerson(person2),forgetNotificationReader(person2)}):null,store:()=>store4,newestMessageId:threadId=>readCursor(threadId).lastReadMessageId,publicGroupState,
33666
33676
  broadcast,shared:threadId=>teamHost.privateTo(threadId)===null,wireBot:botId2=>{let bot=store4.bot(botId2);return bot?wireBot(bot):null}}),botOrders=CLOUD_TEAM?createPersonBotOrder(DATA_DIR):null,teamRoutines=createTeamRoutines({team:!!CLOUD_TEAM,privateTo:teamHost.privateTo,task:(botId2,threadId)=>store4.taskByThread(botId2,threadId),routines:()=>routines,authors:cloudRoutineAuthors,withWriter:withRoutineWriter,ownBot:botId2=>{let person2=store4.bot(botId2)?.defaultBot?.person;return person2?personKey(
@@ -34320,7 +34330,7 @@ settle(threadId),directTurnBots.delete(threadId),drainQueuedSends();return}let s
34320
34330
  phase==="result"&&coordinationChildren?.has(m3.roomRequest.id))&&skipTranscript.add(m3.id);let context3=directContext(bot,threadId,activeMessages),contextOrder=context3.map(m3=>m3.id),replayable=context3.filter(m3=>!skipTranscript.has(m3.id)),record31=latestCompaction(activeMessages),selection3=selectReplay(context3,{budgetBytes:cfg.context?.rebuildBytes??DEFAULT_REBUILD_BYTES,excludedIds:skipTranscript,compaction:record31,tools:replayToolCalls(activeMessages,cfg.context)}),transcript=selection3.
34321
34331
  transcript.map(({role,text:text35})=>({role,text:text35})),contextReset=selection3.compacted>0&&record31?.id!==task2.appliedCompactionId;contextReset&&store4.patchTask(bot.id,threadId,{resumeCursors:{}});let followed=folderToFollow(bot,threadId,task2.cwd,{worksInFolders:supportsWorkspaceFiles(instance.driverKind),keepsPrivateFolder:guestConfined||cloudGuestOpened(threadId)});followed&&store4.patchTask(bot.id,threadId,{cwd:followed,resumeCursors:{}});let rewound=!!task2.rewound,externalContextMarker=isExternalContextMarker(
34322
34332
  task2.lastInstanceId)?task2.lastInstanceId:void 0,fresh=!rewound&&!externalContextMarker&&engineIsFresh({instanceId,lastInstanceId:task2.lastInstanceId,resumeCursors:task2.resumeCursors,transcript:replayable}),strictResume=instance.adapter.capabilities.strictResume===!0,cursor3=task2.resumeCursors[instanceId],handed=strictResume&&!rewound&&!contextReset&&!fresh&&!externalContextMarker&&cursor3!==void 0?task2.handedMessages?.[instanceId]:void 0,unseen=handed&&handedStateUsable(handed,cursor3,contextOrder)?
34323
- unseenMessages(replayable,contextOrder,handed):void 0,externalUpdate=!!(opts?.coordination?.resumed||unseen?.some(m3=>m3.keep)),persistentConfig=[bot.name,bot.title,bot.description,sectionContextSystemPrompt(bot.section),...cfg.everyBotRules?.trim()?[cfg.everyBotRules.trim()]:[],...instance.driverKind==="codex"?[model4,effort??null]:[]],sessionConfig=soul=>createHash137("sha256").update(JSON.stringify([...persistentConfig,soul])).digest("hex").slice(0,16),plannedConfig=sessionConfig(bot.soul),skillAuthoring=skillAuthoringEnabled(
34333
+ unseenMessages(replayable,contextOrder,handed):void 0,externalUpdate=!!(opts?.coordination?.resumed||unseen?.some(m3=>m3.keep)),persistentConfig=[bot.name,bot.title,bot.description,sectionContextSystemPrompt(bot.section),...cfg.everyBotRules?.trim()?[cfg.everyBotRules.trim()]:[],...instance.driverKind==="codex"?[model4,effort??null]:[]],sessionConfig=soul=>createHash138("sha256").update(JSON.stringify([...persistentConfig,soul])).digest("hex").slice(0,16),plannedConfig=sessionConfig(bot.soul),skillAuthoring=skillAuthoringEnabled(
34324
34334
  cfg)&&agentsMounted,skillCommandText=!careGuest&&supportsWorkspaceFiles(instance.driverKind)?skillsHost.expandSkillCommand(bot,threadId,providerText,instance,personLine?activeMessages.filter(line6=>skipTranscript.has(line6.id)):[],personLine&&!userMessage.relayed&&!startedOutside(threadId)||["schedule","manual","startup"].includes(opts?.automationSource??"")):providerText,setupText=agentsMounted?expandBurstTurnText(expandSetupTurnText(skillCommandText)):skillCommandText,userTurnText=(opts?.app?.
34325
34335
  context??"")+(opts?.cardContinuation?"":routineRunNote(threadId,opts?.automationSource))+labelledLine(personLine&&!opts?.excludeMessageIds?userMessage:{},withReactionNotes(promptWithReply(skillAuthoring?expandLearnTurnText(setupText):setupText,opts?.replyTo,userNameFor(threadId)),personLine?activeMessages:[],skipTranscript,userNameFor(threadId)),lineLabels(threadId)),replay=usesNativeImageInput?extractReplayImages(selection3.inline,turnImages):{transcript:selection3.inline,images:[]},decideContext=config3=>{
34326
34336
  let effortHeld=!effort&&typeof handed?.effort=="string",handedStale=!!(handed&&(!unseen||effortHeld||externalUpdate&&handed.config!==config3)),{block:unseenBlock,placed}=unseen&&!handedStale?renderUnseen(unseen):{block:"",placed:[]},{turnText:contextTurnText,resume}=buildTurnContext({text:userTurnText,transcript:replay.transcript,rewound,fresh:fresh||contextReset,externallyUpdated:!!externalContextMarker||handedStale,replaysNatively:replaysNatively(instance.driverKind)}),resumeCursor=resume?task2.
@@ -34465,7 +34475,7 @@ maxParallel:()=>cfg.burst?.maxParallel,hasRoom:()=>engineMemory.laneHasRoom(),st
34465
34475
  approvalFor(bot,selection3),defaultModel:(bot,threadId)=>burstDefaultModel({own:store4.taskByThread(bot.id,threadId)?.modelSelection??bot.modelSelection,catalog:id12=>registry2.get(id12)?.models,refused:id12=>quickFallback.refused(id12),usable:selection3=>ownThreads.refusal(selection3,bot)===null}),modelName,route:notification=>teamMessages.route(notification,{routine:!0}),announce:notification=>{broadcast({kind:"notify",notification:logNotification(notification)})}}),teamMemory=new TeamMemory(join296(
34466
34476
  DATA_DIR,"team-memory.json")),teamMemoryRequests=createTeamMemoryRequests({teamMemory,store:store4,sectionKey:sectionContextKey,decide:row=>appendDecision(DATA_DIR,row)}),outsideWrites=createOutsideWrites({store:store4,notify,language:threadId=>threadLanguage(threadId),decide:row=>appendDecision(DATA_DIR,row),writeMemory:(botId2,threadId,change3)=>{let written=botMemoryUpdate(teamHost.layer(botId2,threadId),change3,{source:memorySourceLabel({room:store4.groupByThread(threadId),task:store4.taskByThread(
34467
34477
  teamHost.baseBotId(botId2),threadId),threadId}),aboutMe:null,prefer:null});return written.ok?null:written.error}}),outboundRequests=new OutboundRequestService,outboundHold=createOutboundHold({store:store4,dataDir:DATA_DIR,outboundRequests,holdMs:OUTBOUND_HOLD_MS,connectorThread,activeGroupTurnForBot,notify}),pendingSends=new PendingOutboundSends(join296(DATA_DIR,"pending-outbound"));async function outboundGmailConnection(){let settings=cfg.composio;if(CLOUD_HOME||HOSTED_WORKSPACE||!settings?.apiKey?.
34468
- trim()||!settings.userId)return;let accounts=(await connectedServices(cfg)).gmail?.accounts.filter(account2=>/^active$/i.test(account2.status));if(!(cfg.composio!==settings||accounts?.length!==1))return createHash137("sha256").update(JSON.stringify([settings,accounts[0].id,process.env.OMB_COMPOSIO_API])).digest("hex")}async function sendRecoveredOutbound(requestId,saved){let payload={jsonrpc:"2.0",id:requestId,method:"tools/call",params:{name:"GMAIL_SEND_EMAIL",arguments:saved.args}},calls2=connectorCallsIn(
34478
+ trim()||!settings.userId)return;let accounts=(await connectedServices(cfg)).gmail?.accounts.filter(account2=>/^active$/i.test(account2.status));if(!(cfg.composio!==settings||accounts?.length!==1))return createHash138("sha256").update(JSON.stringify([settings,accounts[0].id,process.env.OMB_COMPOSIO_API])).digest("hex")}async function sendRecoveredOutbound(requestId,saved){let payload={jsonrpc:"2.0",id:requestId,method:"tools/call",params:{name:"GMAIL_SEND_EMAIL",arguments:saved.args}},calls2=connectorCallsIn(
34469
34479
  payload.params.name,saved.args),services2=await connectedServiceSlugs(cfg),settings=cfg.composio;if(await outboundGmailConnection()!==saved.connection)throw new Error("Gmail connection changed");let result2=await relayMcp(cfg,payload,void 0,()=>{let bot=store4.bot(saved.botId);if(!bot||bot.composio===!1||cfg.composio!==settings||!directChatOf(saved.botId,saved.threadId)||outsideDrivenThread(saved.threadId)||proactive.fence.refusesConnectorCall(bot,saved.threadId,payload)||managedPolicy.appsCallRefusal(
34470
34480
  calls2,services2)||!connectorAccessDecision(bot.connectorScopes,calls2,services2).ok||!evaluateConnectorTools([payload.params.name],bot.connectorTools,services2).allowed||!pendingSends.get(requestId,saved.threadId))throw new Error("The original send is no longer authorized");pendingSends.claim(requestId)});if(!confirmedOutboundSend(result2))throw new Error("Gmail did not confirm delivery")}function confirmedOutboundSend(result2){if(result2.status<200||result2.status>=300)return!1;try{let reply5=JSON.
34471
34481
  parse(new TextDecoder().decode(result2.bytes));return!!(reply5.result&&!reply5.error&&!reply5.result.isError)}catch{return!1}}var{resolveAndSendTrust}=createTrustAnswers({store:store4,dataDir:DATA_DIR,teamMemoryRequests,outsideWrites,outboundRequests,pendingSends,sendRecovered:sendRecoveredOutbound}),profileRequests=new ProfileRequestService({store:store4,autoApply:appliesDirectly,canPersist:proposalPersistence,validateTarget:chiefPeerTargetRule("profile")}),modelRequests=new ModelRequestService(
@@ -34658,7 +34668,7 @@ dataDir:DATA_DIR,persistence:skillProposalPersistence,listBotSkills,readBotSkill
34658
34668
  this skill request belongs to a different bot"};if(isSkillSwitchAction(request11.action))return skillSwitch.resolve(args,message8.id,card,{...request11,action:request11.action});if(card.answered||card.dismissed){let cleanup=rejectStagedSkillWrite(args.botId,request11.stagedId);return"applied"in cleanup&&cleanup.applied&&card.answered!=="allow"?(store4.patchMessage(args.threadId,message8.id,{card:{...card,answered:"allow",dismissed:!1,held:void 0}}),{claimed:!0,outcome:"allowed-once",alreadySettled:!0}):
34659
34669
  {claimed:!0,outcome:card.answered==="allow"?"allowed-once":"rejected",alreadySettled:!0}}if(args.behavior!=="allow"){let rejected2=rejectStagedSkillWrite(args.botId,request11.stagedId);return"error"in rejected2&&rejected2.error!=="no such staged skill"?{claimed:!0,status:409,error:rejected2.error}:"applied"in rejected2?(store4.patchMessage(args.threadId,message8.id,{card:{...card,answered:"allow",dismissed:!1,held:void 0}}),appendDecision(DATA_DIR,{threadId:args.threadId,requestId:args.requestId,
34660
34670
  botId:args.botId,botName:args.botName,tool:card.tool,summary:card.subtitle,decision:"user-approved",source:"user"}),{claimed:!0,outcome:"allowed-once"}):(store4.patchMessage(args.threadId,message8.id,{card:{...card,answered:"deny",dismissed:!0,held:void 0}}),appendDecision(DATA_DIR,{threadId:args.threadId,requestId:args.requestId,botId:args.botId,botName:args.botName,tool:card.tool,summary:card.subtitle,decision:"user-denied",source:"user"}),{claimed:!0,outcome:"rejected"})}if(typeof request11.preview!=
34661
- "string"||typeof request11.sha256!="string")return{claimed:!0,status:409,error:"this proposal was created by an older build \u2014 deny it and ask the bot to create it again"};if(args.reviewedSha256!==request11.sha256)return{claimed:!0,status:409,error:"reviewedSha256 must match the skill shown on the approval card"};if(createHash137("sha256").update(request11.preview).digest("hex")!==request11.sha256||skillReferencesSha256(request11.references??[])!==request11.referencesSha256)return{claimed:!0,
34671
+ "string"||typeof request11.sha256!="string")return{claimed:!0,status:409,error:"this proposal was created by an older build \u2014 deny it and ask the bot to create it again"};if(args.reviewedSha256!==request11.sha256)return{claimed:!0,status:409,error:"reviewedSha256 must match the skill shown on the approval card"};if(createHash138("sha256").update(request11.preview).digest("hex")!==request11.sha256||skillReferencesSha256(request11.references??[])!==request11.referencesSha256)return{claimed:!0,
34662
34672
  status:422,error:"the skill preview changed after review \u2014 deny and recreate it"};let staged=getStagedSkillWrite(args.botId,request11.stagedId);if(!staged){let replayed=applyStagedSkillWrite(args.botId,request11.stagedId,{expectedSha256:request11.sha256,expectedReferencesSha256:request11.referencesSha256??null});return"error"in replayed||replayed.name!==request11.name||replayed.source!==request11.source?{claimed:!0,status:422,error:"the staged skill no longer matches this approval card"}:store4.
34663
34673
  patchMessage(args.threadId,message8.id,{card:{...card,answered:"allow",held:void 0}})?(appendDecision(DATA_DIR,{threadId:args.threadId,requestId:args.requestId,botId:args.botId,botName:args.botName,tool:card.tool,summary:card.subtitle,decision:"user-approved",source:"user"}),{claimed:!0,outcome:"allowed-once"}):{claimed:!0,status:409,error:"the learned-skill approval card is no longer available"}}if(request11.requestId!==args.requestId||request11.threadId!==args.threadId||staged.action!==request11.
34664
34674
  action||staged.name!==request11.name||staged.source!==request11.source||staged.sha256!==request11.sha256||staged.referencesSha256!==request11.referencesSha256)return{claimed:!0,status:422,error:"the staged skill no longer matches this approval card"};let applied=applyStagedSkillWrite(args.botId,request11.stagedId,{expectedSha256:request11.sha256,expectedReferencesSha256:request11.referencesSha256??null,onApplied:()=>{if(!store4.patchMessage(args.threadId,message8.id,{card:{...card,answered:"allo\
@@ -35012,7 +35022,7 @@ internalCapability.threadId,internalCapability.generation),readBody:readInternal
35012
35022
  auth,json:json3,readBody})||await dispatchRoutes([createInternalSignInRoutes({readBody:readInternalBody,request:(site,reason3)=>requestSignIn(internalSender,internalCapability.threadId,site,reason3)})],{req,res,url:url3,path:path8,method:method2,auth,json:json3,readBody}))return;if(method2==="POST"&&path8==="/api/internal/fill-login"){let body3=await readInternalBody(),outcome=await fillLoginForTurn(internalSender,internalCapability,body3.username,body3.submit,body3.email);return requireActiveInternalCapability(),
35013
35023
  json3(res,200,outcome)}if(method2==="POST"&&path8==="/api/internal/voice-note"){let body3=await readInternalBody(),text34=typeof body3.text=="string"?body3.text.trim():"";if(!text34)return json3(res,400,{error:"text required"});if(text34.length>1e3)return json3(res,413,{error:"voice notes are limited to 1000 characters"});let voiceBot=botForThread(internalSender.id,internalCapability.threadId)??internalSender;if(voiceBot.voiceNotes===!1)return json3(res,403,{error:"voice notes are turned off for\
35014
35024
  this bot"});try{let audio2=await speak(cfg,text34,voiceBot.voice,void 0,callSignal2);requireActiveInternalCapability();let turnId=liveTurnByThread.get(internalCapability.threadId);if(!turnId)return json3(res,409,{error:"this turn has not started yet or already ended"});let saved=saveAudio(Buffer.from(audio2.bytes),audio2.mime);if(!existsSync107(saved.path))throw new Error("the voice note's audio file was not saved");let key7=turnAttachmentKey(internalCapability.threadId,turnId),current3=turnAttachmentsByTurn.
35015
- get(key7)??[];return current3.push({kind:"audio",path:saved.path,mime:saved.mime,text:text34}),turnAttachmentsByTurn.set(key7,current3),console.info(`[voice-note] parked thread=${internalCapability.threadId} turn=${turnId} file=${basename42(saved.path)}`),json3(res,201,{attached:!0,file:basename42(saved.path)})}catch(error66){let failure12=voiceNoteFailure(error66);if(failure12)return json3(res,failure12.status,failure12.body);throw error66}}if(method2==="POST"&&path8==="/api/internal/connectors\
35025
+ get(key7)??[];return current3.push({kind:"audio",path:saved.path,mime:saved.mime,text:text34}),turnAttachmentsByTurn.set(key7,current3),console.info(`[voice-note] parked thread=${internalCapability.threadId} turn=${turnId} file=${basename43(saved.path)}`),json3(res,201,{attached:!0,file:basename43(saved.path)})}catch(error66){let failure12=voiceNoteFailure(error66);if(failure12)return json3(res,failure12.status,failure12.body);throw error66}}if(method2==="POST"&&path8==="/api/internal/connectors\
35016
35026
  /mcp"){let body3=await readInternalBody(),currentSender=store4.bot(internalCapability.botId);if(!currentSender||currentSender.composio===!1||!configured(cfg))return json3(res,403,{error:"connected apps are not enabled for this bot"});let actor=teamConnections.relayActor(internalCapability);if(actor.refusal)return json3(res,200,{jsonrpc:"2.0",id:body3.id??null,result:{content:[{type:"text",text:actor.refusal}],isError:!0}});let call2=connectorCallFromFrame(body3),serviceSlugs=[];if(call2.kind==="\
35017
35027
  unrecognized"&&currentSender.connectorTools!==void 0){appendDecision(DATA_DIR,{threadId:internalCapability.threadId,botId:currentSender.id,botName:currentSender.name,tool:call2.invoked,summary:call2.reason,decision:"auto-denied",source:"connector-scope",rule:"connectorTools"});let refusal7=connectorUnrecognizedText(call2.invoked,call2.reason);return res.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),res.end(JSON.stringify({jsonrpc:"2.0",id:body3.id??null,result:{content:[
35018
35028
  {type:"text",text:refusal7}],isError:!0}}))}if(call2.kind==="tools"){if(serviceSlugs=await connectedServiceSlugs(...teamConnections.via(actor.access)),requireActiveInternalCapability(),currentSender=store4.bot(internalCapability.botId),!currentSender||currentSender.composio===!1||!configured(cfg))return json3(res,403,{error:"connected apps are no longer enabled for this bot"});let verdict=evaluateConnectorTools(call2.names,currentSender.connectorTools,serviceSlugs);if(!verdict.allowed){for(let denial of verdict.