openpond 0.2.15 → 0.2.17

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 (110) hide show
  1. package/dist/app-server.d.ts +2 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-layer-SSLVAUNI.js → app-layer-CFIW5CWC.js} +1 -1
  4. package/dist/chunks/{app-server-runtime-QUC4HPQU.js → app-server-runtime-Q7NJ6PXF.js} +1 -1
  5. package/dist/chunks/{apps-JEKTEGSW.js → apps-67PSSK6Q.js} +1 -1
  6. package/dist/chunks/{chunk-YNXFXNQM.js → chunk-BE35DIOI.js} +1 -1
  7. package/dist/chunks/{chunk-4E5ETWKU.js → chunk-CULWDNK3.js} +334 -332
  8. package/dist/chunks/{chunk-ZYG2PXY2.js → chunk-G54T4IWQ.js} +1 -1
  9. package/dist/chunks/{chunk-7I73OREC.js → chunk-GHKJKXDF.js} +1 -1
  10. package/dist/chunks/{chunk-K4ZKAHLG.js → chunk-MACBJI6D.js} +1 -1
  11. package/dist/chunks/{chunk-UOQHYTCK.js → chunk-N3KS3AJK.js} +1 -1
  12. package/dist/chunks/{chunk-FHBQ6OWG.js → chunk-PRA6LX2G.js} +1 -1
  13. package/dist/chunks/{chunk-VRXXKDF2.js → chunk-Q7QAKAGF.js} +1 -1
  14. package/dist/chunks/chunk-RB7BWSFJ.js +5 -0
  15. package/dist/chunks/{chunk-JTQDNX2J.js → chunk-SKKAWYCQ.js} +1 -1
  16. package/dist/chunks/{chunk-QLZ67Y6C.js → chunk-VL3RGI55.js} +2 -2
  17. package/dist/chunks/{cli-7YSRAC4Y.js → cli-BCBRWI2M.js} +1 -1
  18. package/dist/chunks/{configuration-command-DH4ZZUKL.js → configuration-command-D66B4TXT.js} +1 -1
  19. package/dist/chunks/{core-commands-TUUSA6WB.js → core-commands-D6OHIVUG.js} +1 -1
  20. package/dist/chunks/{desktop-test-S3RME4QT.js → desktop-test-RBRWSLEM.js} +1 -1
  21. package/dist/chunks/{extension-D64BYPFY.js → extension-MP3XCX56.js} +1 -1
  22. package/dist/chunks/{help-AOVE3SSY.js → help-XVBIPQHN.js} +1 -1
  23. package/dist/chunks/{opchat-KC2FL5TT.js → opchat-NYSALH7B.js} +1 -1
  24. package/dist/chunks/{organizations-AAES2P7W.js → organizations-ZCQX3SY3.js} +1 -1
  25. package/dist/chunks/{profile-FRYWK2IE.js → profile-PFR6PWNE.js} +1 -1
  26. package/dist/chunks/{project-agent-WPW6DWK7.js → project-agent-KSMTTZYC.js} +1 -1
  27. package/dist/chunks/{sandbox-command-ZHKJZ3FJ.js → sandbox-command-MVBSIKB6.js} +1 -1
  28. package/dist/chunks/{sandbox-template-SPVQIMG5.js → sandbox-template-2OWCTKBP.js} +1 -1
  29. package/dist/chunks/{src-LYFCDA5G.js → src-7TTHR4DL.js} +1 -1
  30. package/dist/chunks/{src-AADCZ2JW.js → src-ITECV3AD.js} +105 -105
  31. package/dist/chunks/{teams-bot-LD3QORJI.js → teams-bot-IUE3CWSW.js} +1 -1
  32. package/dist/chunks/{workspaces-P2WNCMXC.js → workspaces-WI56RXUN.js} +1 -1
  33. package/dist/cli.js +1 -1
  34. package/dist/web/assets/{App-kwt-UxX_.js → App-DQfdLgyV.js} +3 -3
  35. package/dist/web/assets/{AppDialog-LXQo_7oW.js → AppDialog-BnldMLvF.js} +1 -1
  36. package/dist/web/assets/{AppTerminalPanel-CUqrUrkA.js → AppTerminalPanel-DR5SeX9y.js} +2 -2
  37. package/dist/web/assets/{AppsView-5J2RX301.js → AppsView-Bu_XEgkd.js} +1 -1
  38. package/dist/web/assets/{BrowserSidebar-mZ8RjUOr.js → BrowserSidebar-BdKPWbN8.js} +1 -1
  39. package/dist/web/assets/{CartesianChart-7x3SO8Hj.js → CartesianChart-CSkLcF_5.js} +1 -1
  40. package/dist/web/assets/{CollaborationTabs-ByC9WJqu.js → CollaborationTabs-C9cRq5ob.js} +1 -1
  41. package/dist/web/assets/{CommandMenu-CqDb2Kb2.js → CommandMenu-Deqzk3u9.js} +1 -1
  42. package/dist/web/assets/{CommunityView-BmxYkWqC.js → CommunityView-B5dKYacH.js} +1 -1
  43. package/dist/web/assets/{ComposerCreateImproveStrip-2Tyj9KOQ.js → ComposerCreateImproveStrip-5LPlQFN4.js} +1 -1
  44. package/dist/web/assets/{GetStartedView-1WYkmevY.js → GetStartedView-DmuGykfx.js} +1 -1
  45. package/dist/web/assets/HostedModelLearningReview-BRPSFNza.js +1 -0
  46. package/dist/web/assets/{HostedModelLearningSettings-Brza5hSD.js → HostedModelLearningSettings-BsdX-CkH.js} +1 -1
  47. package/dist/web/assets/{LabModelVersionDetailPage-C4WtQKER.js → LabModelVersionDetailPage-BUO5cpDh.js} +1 -1
  48. package/dist/web/assets/{LabSkillSidebar-D3g6E0Ap.js → LabSkillSidebar-mTpdM-G8.js} +1 -1
  49. package/dist/web/assets/{LabsRoute-BO0yEsCR.js → LabsRoute-BhfxBg5_.js} +4 -4
  50. package/dist/web/assets/{MainChatThread-CKPR_rY0.js → MainChatThread-BAxA18lN.js} +2 -2
  51. package/dist/web/assets/{MainPane-B8mDzSqi.js → MainPane-Dv5USGqR.js} +4 -4
  52. package/dist/web/assets/{MarkdownText-D6_UI4Ly.js → MarkdownText-DWGLUbdE.js} +1 -1
  53. package/dist/web/assets/{Messages-DptbENmQ.js → Messages-CuhCtaya.js} +1 -1
  54. package/dist/web/assets/{NativeSkillSidebar-CF1NTAR6.js → NativeSkillSidebar-B8OMVpPT.js} +1 -1
  55. package/dist/web/assets/{NewExperienceSwitcher-CwlpLsXW.js → NewExperienceSwitcher-kIKV8_Wd.js} +1 -1
  56. package/dist/web/assets/{NewProjectDialog-Ls4K9a5S.js → NewProjectDialog-B-7dHoT6.js} +1 -1
  57. package/dist/web/assets/{OutputsPage-ClNuidPW.js → OutputsPage-C4DRT8pF.js} +1 -1
  58. package/dist/web/assets/{ProjectsPage-Sj83NsdP.js → ProjectsPage-CLjW6Kc3.js} +1 -1
  59. package/dist/web/assets/{RightChatPanelStack-m5-cI0NL.js → RightChatPanelStack-C4-4VLb-.js} +1 -1
  60. package/dist/web/assets/{RightSidebarHomePanel-B--t--OJ.js → RightSidebarHomePanel-CVbfOg2p.js} +1 -1
  61. package/dist/web/assets/{ScheduledWorkPage-JVfMtGMs.js → ScheduledWorkPage-CWzwbOOZ.js} +1 -1
  62. package/dist/web/assets/SettingsView-BIwO8elm.js +9 -0
  63. package/dist/web/assets/{SettingsView-B9Tn0_zX.css → SettingsView-BaWWvIJW.css} +1 -1
  64. package/dist/web/assets/{TeamChatView-D8ilbncz.js → TeamChatView-miR9w_53.js} +1 -1
  65. package/dist/web/assets/{TerminalOverlay-A6nSxm5C.js → TerminalOverlay-BOmx_hJX.js} +1 -1
  66. package/dist/web/assets/{TrainingCreationPanel-CwpnBbuN.js → TrainingCreationPanel-DSRejaYV.js} +1 -1
  67. package/dist/web/assets/{TrainingDraftPanel-B_Gh_0yq.js → TrainingDraftPanel-XBH6Uh0_.js} +1 -1
  68. package/dist/web/assets/{UsageSettingsSection-qTX3k9-f.js → UsageSettingsSection-DROtDdak.js} +1 -1
  69. package/dist/web/assets/{WorkSidebarPanel-B-fDRRRs.js → WorkSidebarPanel-CHwObGs6.js} +1 -1
  70. package/dist/web/assets/{WorkspaceDiffPanel-CfvvifJg.js → WorkspaceDiffPanel-BoB_1R8w.js} +3 -3
  71. package/dist/web/assets/{WorkspaceEnvironmentMenu-BL6WHWLO.js → WorkspaceEnvironmentMenu-Dvqy2NJP.js} +1 -1
  72. package/dist/web/assets/{WorkspaceGitDialogs-pyZQJL_2.js → WorkspaceGitDialogs-BC45mifk.js} +1 -1
  73. package/dist/web/assets/{WorkspaceMonacoEditor-C2cNf0UO.js → WorkspaceMonacoEditor-cDO3Elh0.js} +3 -3
  74. package/dist/web/assets/{arrow-up-right-BQv8RCGD.js → arrow-up-right-Dv3nebbh.js} +1 -1
  75. package/dist/web/assets/{chat-file-links-C3erG0P2.js → chat-file-links-DQYtkwit.js} +1 -1
  76. package/dist/web/assets/chevron-up-BUOpWd2a.js +1 -0
  77. package/dist/web/assets/{clipboard-BSPYX7yq.js → clipboard-CnNPmg50.js} +1 -1
  78. package/dist/web/assets/{cloud-upload-CJVhhG6P.js → cloud-upload-DisZOwXE.js} +1 -1
  79. package/dist/web/assets/{cssMode-RCJXPUO-.js → cssMode-Bd8sFlb5.js} +1 -1
  80. package/dist/web/assets/{folder-open-2a5riVSG.js → folder-open-D0PIN0Cj.js} +1 -1
  81. package/dist/web/assets/{folder-plus-DuVvIFve.js → folder-plus-DTNZNwa9.js} +1 -1
  82. package/dist/web/assets/{git-commit-horizontal-BifoV1dR.js → git-commit-horizontal-C0QdA7uv.js} +1 -1
  83. package/dist/web/assets/{htmlMode-DnEOXzjT.js → htmlMode-Cu-nKV7Z.js} +1 -1
  84. package/dist/web/assets/{index-B5RqBp_p.js → index-De4k_YMo.js} +2 -2
  85. package/dist/web/assets/{info-BWvLCbJ2.js → info-B-n_omgE.js} +1 -1
  86. package/dist/web/assets/{jsonMode-DQfml7E4.js → jsonMode-B377iBCv.js} +1 -1
  87. package/dist/web/assets/{lspLanguageFeatures-WKs-7xHz.js → lspLanguageFeatures-BBHfVtV0.js} +1 -1
  88. package/dist/web/assets/{minimize-2-C-_iqAbt.js → minimize-2-C6JQGKgk.js} +1 -1
  89. package/dist/web/assets/{monaco.contribution-B5y78DUP.js → monaco.contribution-B0l6Oe3a.js} +2 -2
  90. package/dist/web/assets/{monaco.contribution-DCekL-SI.js → monaco.contribution-BDLeUQLG.js} +2 -2
  91. package/dist/web/assets/{monaco.contribution-Qc1u700n.js → monaco.contribution-CCSCAu65.js} +2 -2
  92. package/dist/web/assets/{monaco.contribution-B29c98Aa.js → monaco.contribution-CIq6sYw4.js} +2 -2
  93. package/dist/web/assets/{play-DsP3gpGK.js → play-B5O4Hz_W.js} +1 -1
  94. package/dist/web/assets/{python-CJ1QdM8L.js → python-BQkq0gZA.js} +1 -1
  95. package/dist/web/assets/{refresh-cw-DaASy_i0.js → refresh-cw-D2E-pp4H.js} +1 -1
  96. package/dist/web/assets/{save-BBQ7L8VS.js → save-CPNNuWwp.js} +1 -1
  97. package/dist/web/assets/{square-DTl9YrMp.js → square-DUgXVoF0.js} +1 -1
  98. package/dist/web/assets/{toggleHighContrast-D-DNRZ-D.js → toggleHighContrast-BbQBtO9I.js} +1 -1
  99. package/dist/web/assets/{tsMode-CmWbxnjM.js → tsMode-CsVhouTE.js} +1 -1
  100. package/dist/web/assets/{upload-juEp2zRQ.js → upload-t7xHt3GY.js} +1 -1
  101. package/dist/web/assets/{useLocalAgentSchedules-DF_bIseW.js → useLocalAgentSchedules-D4lJelHt.js} +1 -1
  102. package/dist/web/assets/{wifi-off-DrkIaS1O.js → wifi-off-B_QPKtA-.js} +1 -1
  103. package/dist/web/assets/{workers-LygfviY3.js → workers-p7TrE4Qa.js} +1 -1
  104. package/dist/web/assets/{yaml-BIpimtDQ.js → yaml-C8adeAyH.js} +1 -1
  105. package/dist/web/index.html +1 -1
  106. package/package.json +1 -1
  107. package/dist/chunks/chunk-6C2EXO4H.js +0 -5
  108. package/dist/web/assets/HostedModelLearningReview-DHahsQJH.js +0 -1
  109. package/dist/web/assets/SettingsView-B7FnZ-b0.js +0 -9
  110. package/dist/web/assets/chevron-up-D9MMQKU3.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{d as r,f as i,k as p}from"./chunk-QLZ67Y6C.js";import"./chunk-3M53YXEI.js";import{a as t}from"./chunk-FTQLQJQV.js";function d(){console.log(m())}t(d,"printHelp");function m(){let n=["OpenPond CLI","","Usage:"," openpond [--no-open] [--hostname HOST] [--port PORT]"," openpond <command> [options] [-- passthrough...]"," openpond --version","","Commands:"];for(let o of i()){let s=o.aliases?.length?` (aliases: ${o.aliases.join(", ")})`:"";n.push(` ${o.usage}${s}`);for(let e of o.usages??[])n.push(` ${e}`)}n.push("","Global options:");for(let[o,s]of Object.entries(r).sort(([e],[a])=>e.localeCompare(a))){let e=o.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);n.push(s==="boolean"?` --${e}`:` --${e} <${s}>`)}return n.push("","Run `openpond <command> --help` for the selected command schema.","Arguments after `--` are passed through without option parsing."),n.join(`
2
+ import{d as r,f as i,k as p}from"./chunk-VL3RGI55.js";import"./chunk-3M53YXEI.js";import{a as t}from"./chunk-FTQLQJQV.js";function d(){console.log(m())}t(d,"printHelp");function m(){let n=["OpenPond CLI","","Usage:"," openpond [--no-open] [--hostname HOST] [--port PORT]"," openpond <command> [options] [-- passthrough...]"," openpond --version","","Commands:"];for(let o of i()){let s=o.aliases?.length?` (aliases: ${o.aliases.join(", ")})`:"";n.push(` ${o.usage}${s}`);for(let e of o.usages??[])n.push(` ${e}`)}n.push("","Global options:");for(let[o,s]of Object.entries(r).sort(([e],[a])=>e.localeCompare(a))){let e=o.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);n.push(s==="boolean"?` --${e}`:` --${e} <${s}>`)}return n.push("","Run `openpond <command> --help` for the selected command schema.","Arguments after `--` are passed through without option parsing."),n.join(`
3
3
  `)}t(m,"formatCliHelp");function l(){return["# OpenPond CLI command reference","","<!-- Generated by `pnpm --dir apps/cli docs:commands`; do not edit by hand. -->","","Parsing, aliases, command help, and this reference use the same authoritative registry.","",...i().map(o=>`## ${o.name}
4
4
 
5
5
  \`\`\`text
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{c as w}from"./chunk-G2VYRU27.js";import{c as y,d as k,f as B}from"./chunk-ZVOO7FKM.js";import{a as m,c as U,d as C,i as A,j as O,k as v}from"./chunk-I5K74TOH.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import{Z as h}from"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{f as u}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as x}from"node:crypto";async function I(r,t){let e=t[0]||"smoke",n=await h(),l=await w(n,B(n)),c=R(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await S({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await U({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await C({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!u(r.stream)){let s=await A({apiBaseUrl:c,token:l,model:a,messages:[{role:"user",content:p}]});console.log(JSON.stringify(s,null,2));return}let d="",g=null,f=null;for await(let s of O({apiBaseUrl:c,token:l,model:a,messages:[{role:"user",content:p}]}))s.type==="text_delta"?(d+=s.text,process.stdout.write(s.text)):s.type==="finish"?g=s.finishReason:s.type==="usage"&&(f=s.usage);process.stdout.write(`
2
+ import{c as w}from"./chunk-G2VYRU27.js";import{c as y,d as k,f as B}from"./chunk-ZVOO7FKM.js";import{a as m,c as U,d as C,i as A,j as O,k as v}from"./chunk-I5K74TOH.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import{Z as h}from"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{f as u}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as x}from"node:crypto";async function I(r,t){let e=t[0]||"smoke",n=await h(),l=await w(n,B(n)),c=R(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await S({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await U({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await C({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!u(r.stream)){let s=await A({apiBaseUrl:c,token:l,model:a,messages:[{role:"user",content:p}]});console.log(JSON.stringify(s,null,2));return}let d="",g=null,f=null;for await(let s of O({apiBaseUrl:c,token:l,model:a,messages:[{role:"user",content:p}]}))s.type==="text_delta"?(d+=s.text,process.stdout.write(s.text)):s.type==="finish"?g=s.finishReason:s.type==="usage"&&(f=s.usage);process.stdout.write(`
3
3
  `),console.log(JSON.stringify({finishReason:g,usage:f,text:d},null,2));return}if(e==="smoke"){let a=await v({apiBaseUrl:c,token:l,defaultModel:o(r,"model")||void 0,compatibilityModel:o(r,"compatibilityModel")||o(r,"compatModel")||void 0,skipStream:u(r.skipStream),skipTool:u(r.skipTool),log:i(p=>console.log(p),"log")});u(r.json)&&console.log(JSON.stringify(a,null,2));return}throw new Error("usage: opchat <provider-catalog|models|model|chat|smoke> [--opchat-api-base-url <url>]")}i(I,"runOpChatCommand");async function S(r){let t=r.apiBaseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("OpChat API base URL is required.");let e=r.token.trim();if(!e)throw new Error("OpenPond API key is required.");let n=await fetch(`${t}/provider-catalog`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json","x-openpond-client":"openpond-cli","x-openpond-request-id":x()}});if(!n.ok)throw new Error(`Hosted provider catalog failed: ${n.status} ${await b(n)}`);return n.json()}i(S,"getOpChatProviderCatalog");async function b(r){let t=await r.text().catch(()=>"");if(!t)return r.statusText||`HTTP ${r.status}`;try{let e=JSON.parse(t);if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){let n=e.error;return[n.code,n.message].filter(Boolean).join(": ")||t}return t}catch{return t}}i(b,"readResponseError");function R(r,t){let e=o(t,"opchatApiBaseUrl")||o(t,"opchatApiBaseurl")||o(t,"opChatApiBaseUrl")||o(t,"opChatApiBaseurl")||o(t,"opchatApiUrl")||o(t,"opChatApiUrl");return e?m({opChatApiBaseUrl:e}):m({apiBaseUrl:y(t)||r.apiBaseUrl,chatApiBaseUrl:k(t)||r.chatApiBaseUrl})}i(R,"resolveOpChatCliBaseUrl");function o(r,t){let e=r[t];return typeof e=="string"?e.trim():""}i(o,"optionString");export{I as runOpChatCommand};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{p as B}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-FHBQ6OWG.js";import"./chunk-VRXXKDF2.js";import"./chunk-6MI4KKWF.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import{d as x,e as C}from"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-6FA3GG5B.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{a as _,f as b,h as k,i as E}from"./chunk-3M53YXEI.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as ie,randomBytes as ae}from"node:crypto";import{createServer as le}from"node:http";var Se=new URL(C).hostname,_e=new URL(x).hostname,Ee=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function L(e,t=process.platform){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}o(L,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??L(e),s=t.handoffTimeoutMs??1500;return new Promise(u=>{let r=!1,i=null,c=o(a=>{r||(r=!0,i&&clearTimeout(i),u(a))},"finish"),p=se(n.command,n.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});p.once("error",a=>{let l=a.code;c({opened:!1,error:l?`browser launcher ${n.command} failed (${l})`:`browser launcher ${n.command} failed`})}),p.once("close",(a,l)=>{if(a===0){c({opened:!0});return}let d=l?`signal ${l}`:`code ${a??"unknown"}`;c({opened:!1,error:`browser launcher ${n.command} exited with ${d}`})}),i=setTimeout(()=>{p.unref(),c({opened:!0})},s),i.unref()})}o(S,"openUrlWithSystemBrowser");function ce(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}o(ce,"formatOrganizationLine");function ue(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}o(ue,"formatOrganizationMemberLine");function de(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}o(de,"formatOrganizationMcpServerLine");var pe=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function O(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}o(O,"normalizeMcpResourceUrl");function z(e,t){let n=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(n)return O(n);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return O(e.resourceUrl)}o(z,"resolveMcpProbeResourceUrl");function H(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(H,"resolveMcpProbeOrigin");function M(e=32){return ae(e).toString("base64url")}o(M,"randomOauthToken");function me(e){return ie("sha256").update(e).digest("base64url")}o(me,"buildMcpOauthPkceChallenge");function fe(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...pe];let n=t.split(/[,\s]+/g).map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("scope must include at least one OAuth scope");return n}o(fe,"parseMcpOAuthScopes");function ge(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}o(ge,"resolveMcpOAuthClientId");function he(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}o(he,"resolveMcpOAuthTimeoutMs");function ye(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}o(ye,"resolveMcpOAuthCallbackPort");function N(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(N,"closeServer");async function Pe(e){let t=!1,n=null,s=null,u=null,r=new Promise((a,l)=>{s=a,u=l}),i=o((a,l,d,m,f)=>{if(t){a.writeHead(204).end();return}t=!0,a.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),a.end(d),n&&clearTimeout(n),m?s?.(m):u?.(f??new Error("oauth_callback_failed"))},"settle"),c=le((a,l)=>{let d=a.headers.host??"127.0.0.1",m=new URL(a.url??"/",`http://${d}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let f=m.searchParams.get("state")??"",g=m.searchParams.get("error")??"",P=m.searchParams.get("code")??"";if(f!==e.expectedState){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(g){i(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${g}`));return}if(!P){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}i(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:P,state:f})});await new Promise((a,l)=>{let d=o(f=>{c.off("listening",m),l(f)},"onError"),m=o(()=>{c.off("error",d),a()},"onListening");c.once("error",d),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let p=c.address();if(!p||typeof p.port!="number")throw await N(c),new Error("oauth_callback_listener_failed");return n=setTimeout(()=>{t||(t=!0,u?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:o(async()=>{n&&clearTimeout(n),await N(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${p.port}/callback`,waitForCallback:o(()=>r,"waitForCallback")}}o(Pe,"startMcpOAuthCallbackListener");function we(e){S(e)}o(we,"openUrlWithSystemBrowser");function Ae(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}o(Ae,"buildMcpOAuthAuthorizeUrl");async function Oe(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let n=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),s=await j(n);if(!n.ok)throw new Error(`oauth_token_exchange_failed:${n.status}:${JSON.stringify(s)}`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("oauth_token_exchange_invalid_response");let u=s;if(typeof u.access_token!="string"||!u.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:u.access_token,...typeof u.expires_in=="number"?{expires_in:u.expires_in}:{},...typeof u.refresh_token=="string"?{refresh_token:u.refresh_token}:{},...typeof u.scope=="string"?{scope:u.scope}:{},...typeof u.token_type=="string"?{token_type:u.token_type}:{}}}o(Oe,"exchangeMcpOAuthAuthorizationCode");async function j(e){let t=await e.text().catch(()=>"");if(!t)return null;let n=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{return t}return t}o(j,"readMcpProbeBody");async function U(e,t={}){let n=await fetch(e,t);return{url:e,status:n.status,ok:n.ok,headers:{contentType:n.headers.get("content-type"),location:n.headers.get("location"),wwwAuthenticate:n.headers.get("www-authenticate")},body:await j(n)}}o(U,"fetchMcpProbe");function be(e,t,n){return n?{jsonrpc:"2.0",id:e,method:t,params:n}:{jsonrpc:"2.0",id:e,method:t}}o(be,"buildMcpJsonRpcRequest");function D(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let n=_(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(D,"parseMcpToolArguments");async function R(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),U(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(be(e.id,e.method,e.params))})}o(R,"postMcpJsonRpcProbe");async function $(e){let t=O(e.resourceUrl),n=O(e.origin),s=`${t}/.well-known/oauth-protected-resource`,u=`${n}/.well-known/oauth-authorization-server`,[r,i,c,p,a,l,d]=await Promise.all([U(s),U(u),U(t),R({resourceUrl:t,id:1,method:"initialize"}),R({resourceUrl:t,id:2,method:"tools/list"}),R({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?R({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:n,protectedResource:r,authorizationServer:i,directGetChallenge:c,initialize:p,toolsList:a,unauthenticatedToolCall:l,...d?{authenticatedToolCall:d}:{}}}o($,"probeOrganizationMcp");function ke(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}o(ke,"parseOrganizationRole");function xe(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}o(xe,"buildOrganizationCreateInput");function Ce(e){let t={},n=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(n&&(t.displayName=n),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let s=e.status.trim();if(s!=="active"&&s!=="disabled"&&s!=="archived")throw new Error("status must be active, disabled, or archived");t.status=s}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}o(Ce,"buildOrganizationUpdateInput");function Re(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:ke(e.role)}}o(Re,"buildOrganizationMemberInput");function Ue(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:E(e.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function go(e,t){let n=t[0]||"list",s=await B(e),u=b(e.json);if(n==="list"){let r=await s.listOrganizations();if(u){console.log(JSON.stringify({organizations:r},null,2));return}if(r.length===0){console.log("no organizations found");return}for(let i of r)console.log(ce(i));return}if(n==="create"){let r=await s.createOrganization(xe(e));console.log(JSON.stringify({organization:r},null,2));return}if(n==="get"){let r=t[1];if(!r)throw new Error("usage: organizations get <slug>");let i=await s.getOrganization(r);console.log(JSON.stringify({organization:i},null,2));return}if(n==="update"){let r=t[1];if(!r)throw new Error("usage: organizations update <slug> [--name <name>]");let i=await s.updateOrganization(r,Ce(e));console.log(JSON.stringify({organization:i},null,2));return}if(n==="members"||n==="member-list"){let r=t[1];if(!r)throw new Error("usage: organizations members <slug>");let i=await s.listOrganizationMembers(r);if(u){console.log(JSON.stringify({members:i},null,2));return}if(i.length===0){console.log("no organization members found");return}for(let c of i)console.log(ue(c));return}if(n==="member-upsert"||n==="member-add"){let r=t[1];if(!r)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let i=await s.upsertOrganizationMember(r,Re(e));console.log(JSON.stringify({member:i},null,2));return}if(n==="mcp-get"||n==="mcp-server"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-get <slug>");let i=await s.getOrganizationMcpServer(r);if(u){console.log(JSON.stringify({mcpServer:i},null,2));return}console.log(de(i));return}if(n==="mcp-generate"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let i=await s.generateOrganizationMcpServer(r,Ue(e));console.log(JSON.stringify({mcpServer:i},null,2));return}if(n==="mcp-probe"||n==="mcp-inspect"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let i=await s.getOrganizationMcpServer(r),c=z(i,e),p=H(c,e),a=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=D(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await $({resourceUrl:c,origin:p,toolName:a,toolArguments:l,...d?{accessToken:d}:{}});console.log(JSON.stringify({mcpServer:i,probe:m},null,2));return}if(n==="mcp-authorize"||n==="mcp-oauth"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let i=await s.getOrganizationMcpServer(r),c=z(i,e),p=H(c,e),a=ge(e),l=fe(e),d=M(18),m=M(48),f=me(m),g=await Pe({expectedState:d,port:ye(e),timeoutMs:he(e)}),P=Ae({authorizationEndpoint:`${p}/oauth/authorize`,clientId:a,codeChallenge:f,redirectUri:g.redirectUri,resourceUrl:c,scopes:l,state:d});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(P),console.error(`Waiting for OAuth callback on ${g.redirectUri}`),b(e.open))try{we(P)}catch(w){console.error(`Unable to open a browser automatically: ${w instanceof Error?w.message:String(w)}`)}try{let w=await g.waitForCallback(),h=await Oe({clientId:a,code:w.code,codeVerifier:m,origin:p,redirectUri:g.redirectUri}),F=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",J=D(e),q=await $({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:J,toolName:F}),K=b(e.printToken);console.log(JSON.stringify({mcpServer:i,oauth:{accessTokenReceived:!0,clientId:a,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...K?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:q},null,2))}finally{await g.close()}return}if(n==="mcp-rotate"||n==="mcp-disable"||n==="mcp-enable"){let r=t[1];if(!r)throw new Error(`usage: organizations ${n} <slug>`);let i=n==="mcp-rotate"?await s.rotateOrganizationMcpServer(r):n==="mcp-disable"?await s.disableOrganizationMcpServer(r):await s.enableOrganizationMcpServer(r);console.log(JSON.stringify({mcpServer:i},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}o(go,"runOrganizationsCommand");export{pe as DEFAULT_MCP_AUTHORIZE_SCOPES,be as buildMcpJsonRpcRequest,Ae as buildMcpOAuthAuthorizeUrl,me as buildMcpOauthPkceChallenge,xe as buildOrganizationCreateInput,Ue as buildOrganizationMcpGenerateInput,Re as buildOrganizationMemberInput,Ce as buildOrganizationUpdateInput,N as closeServer,Oe as exchangeMcpOAuthAuthorizationCode,U as fetchMcpProbe,ce as formatOrganizationLine,de as formatOrganizationMcpServerLine,ue as formatOrganizationMemberLine,O as normalizeMcpResourceUrl,we as openUrlWithSystemBrowser,fe as parseMcpOAuthScopes,D as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,$ as probeOrganizationMcp,M as randomOauthToken,j as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,H as resolveMcpProbeOrigin,z as resolveMcpProbeResourceUrl,go as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};
2
+ import{p as B}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-PRA6LX2G.js";import"./chunk-Q7QAKAGF.js";import"./chunk-6MI4KKWF.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import{d as x,e as C}from"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-6FA3GG5B.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{a as _,f as b,h as k,i as E}from"./chunk-3M53YXEI.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as ie,randomBytes as ae}from"node:crypto";import{createServer as le}from"node:http";var Se=new URL(C).hostname,_e=new URL(x).hostname,Ee=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function L(e,t=process.platform){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}o(L,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??L(e),s=t.handoffTimeoutMs??1500;return new Promise(u=>{let r=!1,i=null,c=o(a=>{r||(r=!0,i&&clearTimeout(i),u(a))},"finish"),p=se(n.command,n.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});p.once("error",a=>{let l=a.code;c({opened:!1,error:l?`browser launcher ${n.command} failed (${l})`:`browser launcher ${n.command} failed`})}),p.once("close",(a,l)=>{if(a===0){c({opened:!0});return}let d=l?`signal ${l}`:`code ${a??"unknown"}`;c({opened:!1,error:`browser launcher ${n.command} exited with ${d}`})}),i=setTimeout(()=>{p.unref(),c({opened:!0})},s),i.unref()})}o(S,"openUrlWithSystemBrowser");function ce(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}o(ce,"formatOrganizationLine");function ue(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}o(ue,"formatOrganizationMemberLine");function de(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}o(de,"formatOrganizationMcpServerLine");var pe=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function O(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}o(O,"normalizeMcpResourceUrl");function z(e,t){let n=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(n)return O(n);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return O(e.resourceUrl)}o(z,"resolveMcpProbeResourceUrl");function H(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(H,"resolveMcpProbeOrigin");function M(e=32){return ae(e).toString("base64url")}o(M,"randomOauthToken");function me(e){return ie("sha256").update(e).digest("base64url")}o(me,"buildMcpOauthPkceChallenge");function fe(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...pe];let n=t.split(/[,\s]+/g).map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("scope must include at least one OAuth scope");return n}o(fe,"parseMcpOAuthScopes");function ge(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}o(ge,"resolveMcpOAuthClientId");function he(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}o(he,"resolveMcpOAuthTimeoutMs");function ye(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}o(ye,"resolveMcpOAuthCallbackPort");function N(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(N,"closeServer");async function Pe(e){let t=!1,n=null,s=null,u=null,r=new Promise((a,l)=>{s=a,u=l}),i=o((a,l,d,m,f)=>{if(t){a.writeHead(204).end();return}t=!0,a.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),a.end(d),n&&clearTimeout(n),m?s?.(m):u?.(f??new Error("oauth_callback_failed"))},"settle"),c=le((a,l)=>{let d=a.headers.host??"127.0.0.1",m=new URL(a.url??"/",`http://${d}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let f=m.searchParams.get("state")??"",g=m.searchParams.get("error")??"",P=m.searchParams.get("code")??"";if(f!==e.expectedState){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(g){i(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${g}`));return}if(!P){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}i(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:P,state:f})});await new Promise((a,l)=>{let d=o(f=>{c.off("listening",m),l(f)},"onError"),m=o(()=>{c.off("error",d),a()},"onListening");c.once("error",d),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let p=c.address();if(!p||typeof p.port!="number")throw await N(c),new Error("oauth_callback_listener_failed");return n=setTimeout(()=>{t||(t=!0,u?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:o(async()=>{n&&clearTimeout(n),await N(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${p.port}/callback`,waitForCallback:o(()=>r,"waitForCallback")}}o(Pe,"startMcpOAuthCallbackListener");function we(e){S(e)}o(we,"openUrlWithSystemBrowser");function Ae(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}o(Ae,"buildMcpOAuthAuthorizeUrl");async function Oe(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let n=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),s=await j(n);if(!n.ok)throw new Error(`oauth_token_exchange_failed:${n.status}:${JSON.stringify(s)}`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("oauth_token_exchange_invalid_response");let u=s;if(typeof u.access_token!="string"||!u.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:u.access_token,...typeof u.expires_in=="number"?{expires_in:u.expires_in}:{},...typeof u.refresh_token=="string"?{refresh_token:u.refresh_token}:{},...typeof u.scope=="string"?{scope:u.scope}:{},...typeof u.token_type=="string"?{token_type:u.token_type}:{}}}o(Oe,"exchangeMcpOAuthAuthorizationCode");async function j(e){let t=await e.text().catch(()=>"");if(!t)return null;let n=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{return t}return t}o(j,"readMcpProbeBody");async function U(e,t={}){let n=await fetch(e,t);return{url:e,status:n.status,ok:n.ok,headers:{contentType:n.headers.get("content-type"),location:n.headers.get("location"),wwwAuthenticate:n.headers.get("www-authenticate")},body:await j(n)}}o(U,"fetchMcpProbe");function be(e,t,n){return n?{jsonrpc:"2.0",id:e,method:t,params:n}:{jsonrpc:"2.0",id:e,method:t}}o(be,"buildMcpJsonRpcRequest");function D(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let n=_(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(D,"parseMcpToolArguments");async function R(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),U(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(be(e.id,e.method,e.params))})}o(R,"postMcpJsonRpcProbe");async function $(e){let t=O(e.resourceUrl),n=O(e.origin),s=`${t}/.well-known/oauth-protected-resource`,u=`${n}/.well-known/oauth-authorization-server`,[r,i,c,p,a,l,d]=await Promise.all([U(s),U(u),U(t),R({resourceUrl:t,id:1,method:"initialize"}),R({resourceUrl:t,id:2,method:"tools/list"}),R({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?R({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:n,protectedResource:r,authorizationServer:i,directGetChallenge:c,initialize:p,toolsList:a,unauthenticatedToolCall:l,...d?{authenticatedToolCall:d}:{}}}o($,"probeOrganizationMcp");function ke(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}o(ke,"parseOrganizationRole");function xe(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}o(xe,"buildOrganizationCreateInput");function Ce(e){let t={},n=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(n&&(t.displayName=n),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let s=e.status.trim();if(s!=="active"&&s!=="disabled"&&s!=="archived")throw new Error("status must be active, disabled, or archived");t.status=s}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}o(Ce,"buildOrganizationUpdateInput");function Re(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:ke(e.role)}}o(Re,"buildOrganizationMemberInput");function Ue(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:E(e.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function go(e,t){let n=t[0]||"list",s=await B(e),u=b(e.json);if(n==="list"){let r=await s.listOrganizations();if(u){console.log(JSON.stringify({organizations:r},null,2));return}if(r.length===0){console.log("no organizations found");return}for(let i of r)console.log(ce(i));return}if(n==="create"){let r=await s.createOrganization(xe(e));console.log(JSON.stringify({organization:r},null,2));return}if(n==="get"){let r=t[1];if(!r)throw new Error("usage: organizations get <slug>");let i=await s.getOrganization(r);console.log(JSON.stringify({organization:i},null,2));return}if(n==="update"){let r=t[1];if(!r)throw new Error("usage: organizations update <slug> [--name <name>]");let i=await s.updateOrganization(r,Ce(e));console.log(JSON.stringify({organization:i},null,2));return}if(n==="members"||n==="member-list"){let r=t[1];if(!r)throw new Error("usage: organizations members <slug>");let i=await s.listOrganizationMembers(r);if(u){console.log(JSON.stringify({members:i},null,2));return}if(i.length===0){console.log("no organization members found");return}for(let c of i)console.log(ue(c));return}if(n==="member-upsert"||n==="member-add"){let r=t[1];if(!r)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let i=await s.upsertOrganizationMember(r,Re(e));console.log(JSON.stringify({member:i},null,2));return}if(n==="mcp-get"||n==="mcp-server"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-get <slug>");let i=await s.getOrganizationMcpServer(r);if(u){console.log(JSON.stringify({mcpServer:i},null,2));return}console.log(de(i));return}if(n==="mcp-generate"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let i=await s.generateOrganizationMcpServer(r,Ue(e));console.log(JSON.stringify({mcpServer:i},null,2));return}if(n==="mcp-probe"||n==="mcp-inspect"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let i=await s.getOrganizationMcpServer(r),c=z(i,e),p=H(c,e),a=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=D(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await $({resourceUrl:c,origin:p,toolName:a,toolArguments:l,...d?{accessToken:d}:{}});console.log(JSON.stringify({mcpServer:i,probe:m},null,2));return}if(n==="mcp-authorize"||n==="mcp-oauth"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let i=await s.getOrganizationMcpServer(r),c=z(i,e),p=H(c,e),a=ge(e),l=fe(e),d=M(18),m=M(48),f=me(m),g=await Pe({expectedState:d,port:ye(e),timeoutMs:he(e)}),P=Ae({authorizationEndpoint:`${p}/oauth/authorize`,clientId:a,codeChallenge:f,redirectUri:g.redirectUri,resourceUrl:c,scopes:l,state:d});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(P),console.error(`Waiting for OAuth callback on ${g.redirectUri}`),b(e.open))try{we(P)}catch(w){console.error(`Unable to open a browser automatically: ${w instanceof Error?w.message:String(w)}`)}try{let w=await g.waitForCallback(),h=await Oe({clientId:a,code:w.code,codeVerifier:m,origin:p,redirectUri:g.redirectUri}),F=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",J=D(e),q=await $({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:J,toolName:F}),K=b(e.printToken);console.log(JSON.stringify({mcpServer:i,oauth:{accessTokenReceived:!0,clientId:a,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...K?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:q},null,2))}finally{await g.close()}return}if(n==="mcp-rotate"||n==="mcp-disable"||n==="mcp-enable"){let r=t[1];if(!r)throw new Error(`usage: organizations ${n} <slug>`);let i=n==="mcp-rotate"?await s.rotateOrganizationMcpServer(r):n==="mcp-disable"?await s.disableOrganizationMcpServer(r):await s.enableOrganizationMcpServer(r);console.log(JSON.stringify({mcpServer:i},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}o(go,"runOrganizationsCommand");export{pe as DEFAULT_MCP_AUTHORIZE_SCOPES,be as buildMcpJsonRpcRequest,Ae as buildMcpOAuthAuthorizeUrl,me as buildMcpOauthPkceChallenge,xe as buildOrganizationCreateInput,Ue as buildOrganizationMcpGenerateInput,Re as buildOrganizationMemberInput,Ce as buildOrganizationUpdateInput,N as closeServer,Oe as exchangeMcpOAuthAuthorizationCode,U as fetchMcpProbe,ce as formatOrganizationLine,de as formatOrganizationMcpServerLine,ue as formatOrganizationMemberLine,O as normalizeMcpResourceUrl,we as openUrlWithSystemBrowser,fe as parseMcpOAuthScopes,D as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,$ as probeOrganizationMcp,M as randomOauthToken,j as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,H as resolveMcpProbeOrigin,z as resolveMcpProbeResourceUrl,go as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{i as ue,j as D,k as F,r as fe,s as ge}from"./chunk-QWE3RHNY.js";import{a as he}from"./chunk-BX4J2VDU.js";import{p as B}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-X37KMV27.js";import{F as le,H as de,I as ce,J as y,e as Y,f as te,g as V,h as ne,i as re,j as se,q as Z,s as ae,t as ie,x as z}from"./chunk-DWROB2J6.js";import"./chunk-73KFNV3D.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{c as l,d as T,f as g}from"./chunk-3M53YXEI.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as Ae}from"node:fs/promises";import M from"node:path";import Q from"node:path";async function Se(e){if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let t=e.state.agents.find(m=>m.id===e.agentId);if(!t)throw new Error(`Profile agent not found for hosted materialization: ${e.agentId}`);if(!t.enabled)throw new Error(`Profile agent is disabled: ${e.agentId}`);let o=Ce(e.state.sourcePath,t.path),n=await ue(o),a=await D(o,n.entries),c=F(n,a.entries),p=await Re({client:e.client,teamId:e.teamId,projectId:e.projectId??null,profileProjectId:e.profileProjectId,profileName:e.profileName,agentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}),u=await e.client.projects.uploadSource(p.id,{teamId:e.teamId,entries:c.entries,branch:e.sourceRef,commitMessage:`Materialize OpenPond profile agent ${e.agentId}`}),d=await e.client.projects.sync(u.id,{teamId:e.teamId}),R=me(d)??me(u),C=pe(d)??pe(u)??e.sourceRef,$=`openpond-profile-agent:${e.profileProjectId}:${e.profileName}:${e.agentId}`,w=(await e.client.agents.list({teamId:e.teamId})).find(m=>m.externalId===$),O=await e.client.agents.upsert({teamId:e.teamId,projectId:d.id,name:t.name||e.agentId,slug:$e(e.profileName,e.agentId),selectedEntrypoint:be(e.state,e.agentId),triggerType:"manual",runtimeSource:{mode:"latest_source",...C?{sourceRef:C}:{},...R?{sourceCommitSha:R}:{}},metadata:{...w?.metadata??{},source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,profileSourcePath:t.path,localHead:e.localHead,hostedHead:e.hostedHead},externalId:$}),N=b(a.uploadMetadata),U=b(N?.commands),I=b(N?.dependencySetup),h=ke(I?.commands),K=[P(U?.validate),P(U?.eval)].filter(m=>!!m);return{status:"uploaded",agentId:e.agentId,runtimeAgentId:O.id,projectId:d.id,sourceRoot:o,sourceRef:C,sourceCommitSha:R??null,manifestHash:d.sandboxManifestHash??null,manifestPath:d.sandboxManifestPath??null,manifestSyncedAt:d.sandboxManifestSyncedAt??null,fileCount:c.fileCount,totalBytes:c.totalBytes,generatedManifestPath:a.generatedManifestPath,synthesizedOpenPondYaml:a.synthesizedOpenPondYaml,uploadMetadataPath:a.uploadMetadataPath,setupCommands:h,validationCommands:K,materializedAt:new Date().toISOString()}}s(Se,"materializeHostedProfileAgentSource");async function Re(e){if(e.projectId)try{return await e.client.projects.get(e.projectId,{teamId:e.teamId})}catch{}return e.client.projects.upsert({teamId:e.teamId,name:`OpenPond profile ${e.profileName} ${e.agentId}`,sourceType:"manual",externalId:`openpond-profile:${e.profileProjectId}:${e.profileName}:${e.agentId}`,description:`Materialized OpenPond profile agent ${e.agentId} for hosted Team execution.`,metadata:{source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}})}s(Re,"getOrCreateHostedSourceProject");function Ce(e,t){let o=t.replace(/\\/g,"/"),n=Q.resolve(e,o),a=Q.relative(e,n);if(a.startsWith("..")||Q.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}s(Ce,"resolveProfileAgentSourceRoot");function be(e,t){let o=e.actionCatalog.find(n=>n.agentId===t&&(n.sourceActionId==="chat"||n.name==="chat"))??e.actionCatalog.find(n=>n.agentId===t);return{scope:"action",name:typeof o?.sourceActionId=="string"&&o.sourceActionId||typeof o?.name=="string"&&o.name||"chat"}}s(be,"hostedEntrypointForProfileAgent");function $e(e,t){return`openpond-profile-${e}-${t}`.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"openpond-profile-agent"}s($e,"hostedRuntimeAgentSlug");function me(e){let t=b(e),o=b(t?.sourceConfig),n=b(t?.metadata);return P(o?.sourceCommitSha)??P(o?.commitSha)??P(o?.remoteSha)??P(n?.projectSourceUploadCommitSha)??P(n?.sourceCommitSha)??P(t?.templateRemoteSha)}s(me,"sandboxProjectSourceCommitSha");function pe(e){let t=b(e),o=b(t?.sourceConfig);return P(o?.sourceRef)??P(o?.branch)??P(t?.gitBranch)??P(t?.defaultBranch)}s(pe,"sandboxProjectSourceRef");function b(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(b,"record");function P(e){return typeof e=="string"&&e.trim()?e.trim():null}s(P,"text");function ke(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}s(ke,"stringArray");async function so(e){let t=await ae({repoPath:l(e,"path")||Z(),profile:l(e,"profile")||"default",template:l(e,"template")||"blank-agent",force:g(e.force)});if(g(e.json)){console.log(JSON.stringify(t,null,2));return}console.log(`Initialized OpenPond profile ${t.activeProfile} at ${t.repoPath}`),console.log(`Profile source: ${t.sourcePath}`)}s(so,"runOpenPondInitCommand");async function ao(e,t){let o=t[0]??"current";if(o==="load"){let n=l(e,"path")||t[1];if(!n)throw new Error("usage: openpond profile load --path <dir> [--profile <name>]");let a=await ie(n,l(e,"profile")||void 0);if(g(e.json)){console.log(JSON.stringify(a,null,2));return}console.log(`Loaded OpenPond profile ${a.activeProfile} from ${a.repoPath}`);return}if(o==="current"||o==="status"){let n=await z();if(g(e.json)){console.log(JSON.stringify(n,null,2));return}X(n);return}if(o==="diff"){let n=await z();if(g(e.json)){console.log(JSON.stringify({diff:n.diff,profile:n},null,2));return}Te(n);return}if(o==="catalog"){let n=await z();if(g(e.json)){console.log(JSON.stringify({catalog:n.catalog,actions:n.actionCatalog,profile:n},null,2));return}Be(n);return}if(o==="commit"){await je(e,t.slice(1));return}if(o==="push"){await Oe(e);return}if(o==="check"){await de(l(e,"kind")||t[1]||"all");return}if(o==="ensure-hosted"){await we(e);return}if(o==="hosted"){let n=t[1]??"status";if(n==="ensure"){await we(e);return}if(n==="status"||n==="current"){await Le(e);return}throw new Error("usage: openpond profile hosted [status|ensure] --team-id <id> [--json]")}if(o==="agents"){if((t[1]??"list")!=="list")throw new Error("usage: openpond profile agents list [--json]");await qe(e,["list"]);return}throw new Error("usage: openpond profile <status|diff|catalog|commit|push|load|check|agents|hosted|ensure-hosted> [args]")}s(ao,"runOpenPondProfileCommand");async function je(e,t){let o=l(e,"message")||l(e,"commitMessage")||t.join(" ").trim()||void 0,n=await ce(o);if(g(e.json)){console.log(JSON.stringify(n,null,2));return}if(!n.committed){console.log("No profile changes to commit."),X(n.state);return}console.log("Committed OpenPond profile changes."),n.stdout.trim()&&console.log(n.stdout.trim()),X(n.state)}s(je,"runProfileCommitCommand");async function Oe(e){let t=T(e,"usage: openpond profile push"),o=await z();if(o.error)throw new Error(o.error);if(!o.repoPath||!o.sourcePath||!o.manifestPath)throw new Error("No active OpenPond profile. Run `openpond init`.");if(!o.git?.isRepo)throw new Error("Active OpenPond profile source is not Git-backed. Run `openpond init` or reload a Git-backed profile.");if(!o.git.head)throw new Error("Profile source must have a committed Git head before push. Run `openpond profile commit` first.");if(o.git.dirty)throw new Error("Profile source has uncommitted changes. Run `openpond profile commit` before push.");let n=await B(e),a=g(e.ensureHosted)?await n.profile.ensureHosted({teamId:t}):await n.profile.get({teamId:t});if(!a)throw new Error("No hosted OpenPond profile repo found. Run `openpond profile ensure-hosted --team-id <id>` first, or pass `--ensure-hosted` to push.");let c=g(e.force),p=a.sourceUpload?.sourceCommitSha??null,u=o.hosted?.sourceCommitSha??null;if(u&&p!==u&&!c)throw new Error(["Hosted profile source changed since the last local push.",`Last pushed hosted head: ${u}`,`Current hosted head: ${p??"none"}`,"Inspect hosted changes before pushing, or rerun with --force to overwrite explicitly."].join(`
2
+ import{i as ue,j as D,k as F,r as fe,s as ge}from"./chunk-QWE3RHNY.js";import{a as he}from"./chunk-BX4J2VDU.js";import{p as B}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-X37KMV27.js";import{F as le,H as de,I as ce,J as y,e as Y,f as te,g as V,h as ne,i as re,j as se,q as Z,s as ae,t as ie,x as z}from"./chunk-DWROB2J6.js";import"./chunk-73KFNV3D.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{c as l,d as T,f as g}from"./chunk-3M53YXEI.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as Ae}from"node:fs/promises";import M from"node:path";import Q from"node:path";async function Se(e){if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let t=e.state.agents.find(m=>m.id===e.agentId);if(!t)throw new Error(`Profile agent not found for hosted materialization: ${e.agentId}`);if(!t.enabled)throw new Error(`Profile agent is disabled: ${e.agentId}`);let o=Ce(e.state.sourcePath,t.path),n=await ue(o),a=await D(o,n.entries),c=F(n,a.entries),p=await Re({client:e.client,teamId:e.teamId,projectId:e.projectId??null,profileProjectId:e.profileProjectId,profileName:e.profileName,agentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}),u=await e.client.projects.uploadSource(p.id,{teamId:e.teamId,entries:c.entries,branch:e.sourceRef,commitMessage:`Materialize OpenPond profile agent ${e.agentId}`}),d=await e.client.projects.sync(u.id,{teamId:e.teamId}),R=me(d)??me(u),C=pe(d)??pe(u)??e.sourceRef,$=`openpond-profile-agent:${e.profileProjectId}:${e.profileName}:${e.agentId}`,w=(await e.client.agents.list({teamId:e.teamId})).find(m=>m.externalId===$),O=await e.client.agents.upsert({teamId:e.teamId,projectId:d.id,name:t.name||e.agentId,slug:$e(e.profileName,e.agentId),selectedEntrypoint:be(e.state,e.agentId),triggerType:"manual",runtimeSource:{mode:"latest_source",...C?{sourceRef:C}:{},...R?{sourceCommitSha:R}:{}},metadata:{...w?.metadata??{},source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,profileSourcePath:t.path,localHead:e.localHead,hostedHead:e.hostedHead},externalId:$}),N=b(a.uploadMetadata),U=b(N?.commands),I=b(N?.dependencySetup),h=ke(I?.commands),K=[P(U?.validate),P(U?.eval)].filter(m=>!!m);return{status:"uploaded",agentId:e.agentId,runtimeAgentId:O.id,projectId:d.id,sourceRoot:o,sourceRef:C,sourceCommitSha:R??null,manifestHash:d.sandboxManifestHash??null,manifestPath:d.sandboxManifestPath??null,manifestSyncedAt:d.sandboxManifestSyncedAt??null,fileCount:c.fileCount,totalBytes:c.totalBytes,generatedManifestPath:a.generatedManifestPath,synthesizedOpenPondYaml:a.synthesizedOpenPondYaml,uploadMetadataPath:a.uploadMetadataPath,setupCommands:h,validationCommands:K,materializedAt:new Date().toISOString()}}s(Se,"materializeHostedProfileAgentSource");async function Re(e){if(e.projectId)try{return await e.client.projects.get(e.projectId,{teamId:e.teamId})}catch{}return e.client.projects.upsert({teamId:e.teamId,name:`OpenPond profile ${e.profileName} ${e.agentId}`,sourceType:"manual",externalId:`openpond-profile:${e.profileProjectId}:${e.profileName}:${e.agentId}`,description:`Materialized OpenPond profile agent ${e.agentId} for hosted Team execution.`,metadata:{source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}})}s(Re,"getOrCreateHostedSourceProject");function Ce(e,t){let o=t.replace(/\\/g,"/"),n=Q.resolve(e,o),a=Q.relative(e,n);if(a.startsWith("..")||Q.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}s(Ce,"resolveProfileAgentSourceRoot");function be(e,t){let o=e.actionCatalog.find(n=>n.agentId===t&&(n.sourceActionId==="chat"||n.name==="chat"))??e.actionCatalog.find(n=>n.agentId===t);return{scope:"action",name:typeof o?.sourceActionId=="string"&&o.sourceActionId||typeof o?.name=="string"&&o.name||"chat"}}s(be,"hostedEntrypointForProfileAgent");function $e(e,t){return`openpond-profile-${e}-${t}`.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"openpond-profile-agent"}s($e,"hostedRuntimeAgentSlug");function me(e){let t=b(e),o=b(t?.sourceConfig),n=b(t?.metadata);return P(o?.sourceCommitSha)??P(o?.commitSha)??P(o?.remoteSha)??P(n?.projectSourceUploadCommitSha)??P(n?.sourceCommitSha)??P(t?.templateRemoteSha)}s(me,"sandboxProjectSourceCommitSha");function pe(e){let t=b(e),o=b(t?.sourceConfig);return P(o?.sourceRef)??P(o?.branch)??P(t?.gitBranch)??P(t?.defaultBranch)}s(pe,"sandboxProjectSourceRef");function b(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(b,"record");function P(e){return typeof e=="string"&&e.trim()?e.trim():null}s(P,"text");function ke(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}s(ke,"stringArray");async function so(e){let t=await ae({repoPath:l(e,"path")||Z(),profile:l(e,"profile")||"default",template:l(e,"template")||"blank-agent",force:g(e.force)});if(g(e.json)){console.log(JSON.stringify(t,null,2));return}console.log(`Initialized OpenPond profile ${t.activeProfile} at ${t.repoPath}`),console.log(`Profile source: ${t.sourcePath}`)}s(so,"runOpenPondInitCommand");async function ao(e,t){let o=t[0]??"current";if(o==="load"){let n=l(e,"path")||t[1];if(!n)throw new Error("usage: openpond profile load --path <dir> [--profile <name>]");let a=await ie(n,l(e,"profile")||void 0);if(g(e.json)){console.log(JSON.stringify(a,null,2));return}console.log(`Loaded OpenPond profile ${a.activeProfile} from ${a.repoPath}`);return}if(o==="current"||o==="status"){let n=await z();if(g(e.json)){console.log(JSON.stringify(n,null,2));return}X(n);return}if(o==="diff"){let n=await z();if(g(e.json)){console.log(JSON.stringify({diff:n.diff,profile:n},null,2));return}Te(n);return}if(o==="catalog"){let n=await z();if(g(e.json)){console.log(JSON.stringify({catalog:n.catalog,actions:n.actionCatalog,profile:n},null,2));return}Be(n);return}if(o==="commit"){await je(e,t.slice(1));return}if(o==="push"){await Oe(e);return}if(o==="check"){await de(l(e,"kind")||t[1]||"all");return}if(o==="ensure-hosted"){await we(e);return}if(o==="hosted"){let n=t[1]??"status";if(n==="ensure"){await we(e);return}if(n==="status"||n==="current"){await Le(e);return}throw new Error("usage: openpond profile hosted [status|ensure] --team-id <id> [--json]")}if(o==="agents"){if((t[1]??"list")!=="list")throw new Error("usage: openpond profile agents list [--json]");await qe(e,["list"]);return}throw new Error("usage: openpond profile <status|diff|catalog|commit|push|load|check|agents|hosted|ensure-hosted> [args]")}s(ao,"runOpenPondProfileCommand");async function je(e,t){let o=l(e,"message")||l(e,"commitMessage")||t.join(" ").trim()||void 0,n=await ce(o);if(g(e.json)){console.log(JSON.stringify(n,null,2));return}if(!n.committed){console.log("No profile changes to commit."),X(n.state);return}console.log("Committed OpenPond profile changes."),n.stdout.trim()&&console.log(n.stdout.trim()),X(n.state)}s(je,"runProfileCommitCommand");async function Oe(e){let t=T(e,"usage: openpond profile push"),o=await z();if(o.error)throw new Error(o.error);if(!o.repoPath||!o.sourcePath||!o.manifestPath)throw new Error("No active OpenPond profile. Run `openpond init`.");if(!o.git?.isRepo)throw new Error("Active OpenPond profile source is not Git-backed. Run `openpond init` or reload a Git-backed profile.");if(!o.git.head)throw new Error("Profile source must have a committed Git head before push. Run `openpond profile commit` first.");if(o.git.dirty)throw new Error("Profile source has uncommitted changes. Run `openpond profile commit` before push.");let n=await B(e),a=g(e.ensureHosted)?await n.profile.ensureHosted({teamId:t}):await n.profile.get({teamId:t});if(!a)throw new Error("No hosted OpenPond profile repo found. Run `openpond profile ensure-hosted --team-id <id>` first, or pass `--ensure-hosted` to push.");let c=g(e.force),p=a.sourceUpload?.sourceCommitSha??null,u=o.hosted?.sourceCommitSha??null;if(u&&p!==u&&!c)throw new Error(["Hosted profile source changed since the last local push.",`Last pushed hosted head: ${u}`,`Current hosted head: ${p??"none"}`,"Inspect hosted changes before pushing, or rerun with --force to overwrite explicitly."].join(`
3
3
  `));let d=l(e,"hostedSourceAgentId"),R=g(e.hostedSourceChecks),C=g(e.publishHostedSource),$=l(e,"hostedRunAgentId"),w=d||(R||C?$:null),O=JSON.parse(await Ae(o.manifestPath,"utf8")),N=ve(O),U=O.profiles[o.activeProfile??O.defaultProfile]?.path??"profiles/default",I=await ze({state:o,hostedSourceAgentId:w}),h=await n.profile.push({teamId:t,entries:I.entries,branch:o.git.branch??"main",commitMessage:l(e,"commitMessage")||l(e,"message")||`Push OpenPond profile ${o.activeProfile??"default"} at ${o.git.shortHead??o.git.head}`,expectedSourceCommitSha:p,localHeadSha:o.git.head,manifest:N,sourcePath:U,agents:o.agents.map(i=>({id:i.id,path:i.path,enabled:i.enabled}))}),K=new Date().toISOString(),m=o.hosted?.lastPushedLocalHead===o.git.head&&o.hosted?.sourceCommitSha===h.sourceUpload.sourceCommitSha,r={status:"pushed",promotionStatus:m?o.hosted?.promotionStatus??"uploaded":"uploaded",hostedRunStatus:m?o.hosted?.hostedRunStatus??"not_started":"not_started",pushedAt:K,teamId:t,projectId:h.profile.project.id,localHead:o.git.head,hostedHead:h.sourceUpload.sourceCommitSha,sourceRef:h.sourceUpload.sourceRef,hostedRunAgentId:m?o.hosted?.hostedRunAgentId??null:null,hostedRunId:m?o.hosted?.hostedRunId??null:null,hostedRunAt:m?o.hosted?.hostedRunAt??null:null,hostedSourceMaterialization:m?o.hosted?.hostedSourceMaterialization??null:null,hostedSourceCheck:m?o.hosted?.hostedSourceCheck??null:null,hostedPublish:m?o.hosted?.hostedPublish??null:null,hostedRun:m?o.hosted?.hostedRun??null:null};await y(r);let S=w??Ee(o,$),ee=ge(e.hostedSourceDispatch,"hosted-source-dispatch")??"coding_core",_=null,k=null,W=null;if(w&&(R||C||d))try{let i=await Se({client:n,teamId:t,profileProjectId:h.profile.project.id,profileName:o.activeProfile??O.defaultProfile,state:o,agentId:w,sourceRef:h.sourceUpload.sourceRef??o.git.branch??"main",localHead:o.git.head,hostedHead:h.sourceUpload.sourceCommitSha,projectId:l(e,"hostedSourceProjectId")||(o.hosted?.hostedSourceMaterialization?.agentId===w?o.hosted.hostedSourceMaterialization.projectId:null)});r={...r,promotionStatus:"hosted_source_materialized",hostedSourceMaterialization:i},S=i.runtimeAgentId??w,await y(r)}catch(i){let f=i instanceof Error?i.message:String(i);throw r={...r,promotionStatus:"hosted_source_materialize_failed",hostedSourceMaterialization:{status:"failed",agentId:w,projectId:l(e,"hostedSourceProjectId")??null,error:f},error:f},await y(r),new Error(`Hosted source materialization failed after push: ${f}`)}if(R||C){if(!w)throw new Error("--hosted-source-agent-id or --hosted-run-agent-id is required for hosted source checks or publish.");if(!S)throw new Error("Unable to resolve the hosted runtime agent for source checks.");try{if(_=await n.agents.sourceDeployPlan(S,{teamId:t}),R){let i=r.hostedSourceMaterialization?.sourceRef??h.sourceUpload.sourceRef,f=r.hostedSourceMaterialization?.sourceCommitSha??h.sourceUpload.sourceCommitSha;if(k=await n.agents.requestSourceChecks(S,{teamId:t,...i?{sourceRef:i}:{},...f?{baseSha:f}:{},checkKind:fe(l(e,"hostedCheckKind")||l(e,"checkKind"))??"all",dispatch:ee,metadata:{source:"openpond_profile_push_checks",localHead:o.git.head,hostedHead:h.sourceUpload.sourceCommitSha,materializedProjectId:r.hostedSourceMaterialization?.projectId??null,materializedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??null,sourceRef:i,dispatch:ee}}),k.dispatchResult?.status==="failed")throw new Error(k.dispatchResult.error??"hosted_source_check_dispatch_failed");if(k.dispatchResult?.status==="completed"){let L=J(k.sourceCheckStatus);xe(L)&&(await _e({client:n,teamId:t,runtimeAgentId:S,sourceRef:i,sourceCommitSha:f,validatedAt:new Date().toISOString()}),_=await n.agents.sourceDeployPlan(S,{teamId:t}))}}r={...r,promotionStatus:R?"hosted_source_check_pending":r.promotionStatus,hostedSourceCheck:V({agentId:S,status:R?"requested":"deploy_plan_ready",deployPlan:_,checkResult:k})},await y(r)}catch(i){let f=i instanceof Error?i.message:String(i);throw r={...r,promotionStatus:"hosted_source_check_failed",hostedSourceCheck:V({agentId:S,status:"failed",deployPlan:_,checkedAt:new Date().toISOString(),error:f}),error:f},await y(r),new Error(`Hosted source check failed after push: ${f}`)}}if(C){if(!w)throw new Error("--hosted-source-agent-id or --hosted-run-agent-id is required for hosted source publish.");if(!S)throw new Error("Unable to resolve the hosted runtime agent for source publish.");try{let i=l(e,"expectedManifestHash")||r.hostedSourceCheck?.manifestHash||_?.source.manifestHash||void 0;W=await n.agents.publishSource(S,{teamId:t,...i?{expectedManifestHash:i}:{},...r.hostedSourceMaterialization?.sourceCommitSha??h.sourceUpload.sourceCommitSha?{expectedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??h.sourceUpload.sourceCommitSha}:{}}),r={...r,promotionStatus:"hosted_source_published",hostedPublish:ne({agentId:S,publishResult:W})},await y(r)}catch(i){let f=i instanceof Error?i.message:String(i);throw r={...r,promotionStatus:"hosted_source_publish_failed",hostedPublish:{status:"failed",agentId:S,error:f},error:f},await y(r),new Error(`Hosted source publish failed after push: ${f}`)}}let A=null;if($){let i=S||$,f=new Date().toISOString(),L=Fe(e,"hostedRunInput")??{prompt:"hello",channel:"openpond_chat"},q=l(e,"hostedRunConversationId")||l(e,"conversationId"),H=l(e,"hostedRunTargetProjectId"),oe=he({explicitKey:l(e,"hostedRunIdempotencyKey"),retry:g(e.hostedRunRetry),localHead:o.git.head,sourceHead:r.hostedSourceMaterialization?.sourceCommitSha??h.sourceUpload.sourceCommitSha,runtimeAgentId:i,targetProjectId:H,input:L});await y({...r,promotionStatus:"hosted_run_pending",hostedRunStatus:"running",hostedRunAgentId:i,hostedRunAt:f});try{A=await n.agents.run(i,{teamId:t,...q?{conversationId:q}:{},...H?{targetProjectId:H}:{},...H?{targetProject:{id:H}}:{},idempotencyKey:oe,input:L,metadata:{source:"openpond_profile_push_run",...q?{conversationId:q}:{},targetProjectId:H||null,localHead:o.git.head,hostedHead:h.sourceUpload.sourceCommitSha,hostedRunIdempotencyKey:oe,hostedRunRetry:g(e.hostedRunRetry),materializedProjectId:r.hostedSourceMaterialization?.projectId??null,materializedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??null,sourceRef:r.hostedSourceMaterialization?.sourceRef??h.sourceUpload.sourceRef,publishedSnapshotId:r.hostedPublish?.snapshotId??null,manifestHash:r.hostedPublish?.manifestHash??r.hostedSourceCheck?.manifestHash??null},runtimeSourcePolicy:C?{requirePublishedSnapshot:!0,source:"diagnostic"}:{allowLatestSource:!0,source:"diagnostic"}});let v=re({agentId:i,runResult:A}),j=se(v);await y({...r,promotionStatus:j==="passed"?"hosted_run_passed":j==="failed"?"hosted_run_failed":"hosted_run_pending",hostedRunStatus:j,hostedRunAgentId:i,hostedRunId:A.run.id,hostedRunAt:A.run.createdAt??f,hostedRun:v})}catch(v){let j=v instanceof Error?v.message:String(v);throw await y({...r,promotionStatus:"hosted_run_failed",hostedRunStatus:"failed",hostedRunAgentId:i,hostedRunAt:new Date().toISOString(),hostedRun:{status:"failed",agentId:i,error:j},error:j}),new Error(`Hosted invocation failed to start after push: ${j}`)}}if(g(e.json)){console.log(JSON.stringify({...h,uploaded:He(I),hostedSourceMaterialization:r.hostedSourceMaterialization??null,hostedSourceChecks:k,hostedSourcePublish:W,hostedRun:A},null,2));return}console.log(`Pushed OpenPond profile ${o.activeProfile??"default"} to hosted profile repo.`),console.log(`Project id: ${h.profile.project.id}`),console.log(`Local head: ${o.git.head}`),console.log(`Hosted source commit: ${h.sourceUpload.sourceCommitSha??"unknown"}`),console.log(`Uploaded ${I.fileCount} file(s), ${I.totalBytes} byte(s) via ${I.transport.mode} (limits: ${I.limits.maxFiles} files, ${I.limits.maxFileBytes} bytes/file, ${I.limits.maxTotalBytes} bytes total).`),console.log(A?`Hosted invocation: running ${A.run.id}`:"Hosted invocation: not started"),r.hostedSourceMaterialization&&console.log(`Hosted materialized: ${r.hostedSourceMaterialization.status}`+(r.hostedSourceMaterialization.projectId?` ${r.hostedSourceMaterialization.projectId}`:"")+(r.hostedSourceMaterialization.sourceCommitSha?` ${r.hostedSourceMaterialization.sourceCommitSha}`:"")),r.hostedSourceCheck&&console.log(`Hosted source checks: ${r.hostedSourceCheck.status}`),r.hostedPublish&&console.log(`Hosted publish: ${r.hostedPublish.status}`+(r.hostedPublish.snapshotId?` ${r.hostedPublish.snapshotId}`:"")),console.log(`Uploaded files: ${I.fileCount}`)}s(Oe,"runProfilePushCommand");function He(e){return{fileCount:e.fileCount,totalBytes:e.totalBytes,limits:e.limits,transport:e.transport}}s(He,"summarizeProfileSourceUpload");function ve(e){return{...e,profiles:Object.fromEntries(Object.entries(e.profiles).map(([t,o])=>[t,{path:o.path,defaultAgent:o.defaultAgent??"default",enabledAgents:o.enabledAgents??[]}]))}}s(ve,"normalizeHostedProfileManifest");async function ze(e){let t=e.state.repoPath;if(!t)throw new Error("Active OpenPond profile is missing a repository path.");let o=await te(t);if(!e.hostedSourceAgentId)return o;if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let n=e.state.agents.find(u=>u.id===e.hostedSourceAgentId);if(!n)throw new Error(`Profile agent not found for hosted source upload: ${e.hostedSourceAgentId}`);let a=Me(e.state.sourcePath,n.path),c=M.relative(t,a).replace(/\\/g,"/");if(c.startsWith("..")||M.isAbsolute(c))throw new Error(`Profile agent path escapes profile repo: ${n.path}`);let p=await D(a,[]);return p.entries.length===0?o:F(o,p.entries.map(u=>({...u,path:c?`${c}/${u.path}`:u.path})))}s(ze,"collectProfileSourceUploadForPush");function Me(e,t){let o=t.replace(/\\/g,"/"),n=M.resolve(e,o),a=M.relative(e,n);if(a.startsWith("..")||M.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}s(Me,"resolveProfileAgentSourceRoot");function J(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(J,"record");function E(e){return typeof e=="string"&&e.trim()?e.trim():null}s(E,"text");function Ee(e,t){if(!t)return null;let o=e.hosted?.hostedSourceMaterialization;return o?.agentId===t&&o.runtimeAgentId?o.runtimeAgentId:t}s(Ee,"resolveHostedRuntimeAgentIdForRun");async function _e(e){!e.sourceRef||!e.sourceCommitSha||await e.client.agents.update(e.runtimeAgentId,{teamId:e.teamId,runtimeSource:{mode:"latest_source",sourceRef:e.sourceRef,sourceCommitSha:e.sourceCommitSha,buildStatus:"succeeded",validationStatus:"passed",validatedAt:e.validatedAt}})}s(_e,"bindValidatedHostedRuntimeSource");function xe(e){if(!e)return!1;let t=E(e.finalResultState)?.toLowerCase();if(t&&t!=="completed"&&!Ie(t))return!1;let o=Array.isArray(e.checkRuns)?e.checkRuns.map(J).filter(d=>!!d):[];if(o.some(Ne))return!1;let n=o.some(d=>G(d).includes("build")&&x(d)),a=x(J(e.validation))||o.some(d=>G(d).includes("validate")&&x(d)),c=J(e.eval),u=!((E(e.requestedCheckKind)??"all")==="all"||(E(e.requestedCheckKind)??"")==="eval"||!!c||o.some(d=>G(d).includes("eval")))||x(c)||o.some(d=>G(d).includes("eval")&&x(d));return n&&a&&u}s(xe,"sourceCheckStatusPassed");function G(e){return(E(e.command)??"").toLowerCase()}s(G,"checkRunCommand");function Ne(e){let t=e.passed;if(typeof t=="boolean")return!t;let o=e.exitCode;if(typeof o=="number"&&o!==0)return!0;let n=E(e.status)?.toLowerCase();return!!(n&&Ue(n))}s(Ne,"checkRunFailed");function x(e){if(!e)return!1;if(typeof e.passed=="boolean")return e.passed;let t=Pe(e.failed)??Pe(e.failedCount);if(t!==null&&t>0)return!1;let o=e.exitCode;if(typeof o=="number")return o===0;let n=E(e.status)?.toLowerCase();return!!(n&&Ie(n))}s(x,"checkEvidencePassed");function Pe(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){let t=Number(e);return Number.isFinite(t)?t:null}return null}s(Pe,"numericEvidence");function Ie(e){return e==="passed"||e==="succeeded"||e==="success"}s(Ie,"passingStatus");function Ue(e){return e==="failed"||e==="failure"||e==="cancelled"}s(Ue,"failingStatus");async function Le(e){let t=T(e,"usage: openpond profile hosted status"),n=await(await B(e)).profile.get({teamId:t});if(g(e.json)){console.log(JSON.stringify({profile:n},null,2));return}if(!n){console.log("No hosted OpenPond profile repo found."),console.log("Run `openpond profile ensure-hosted --team-id <id>` to create one.");return}ye(n)}s(Le,"runHostedProfileStatusCommand");async function we(e){let t=T(e,"usage: openpond profile ensure-hosted"),n=await(await B(e)).profile.ensureHosted({teamId:t});if(g(e.json)){console.log(JSON.stringify({profile:n},null,2));return}ye(n)}s(we,"runHostedProfileEnsureCommand");async function qe(e,t){if((t[0]??"list")!=="list")throw new Error("usage: openpond agents list [--json]");let n=await z();if(n.error)throw new Error(n.error);if(g(e.json)){console.log(JSON.stringify({agents:n.agents,profile:n},null,2));return}if(n.mode==="none"){console.log("No active OpenPond profile. Run `openpond init`.");return}if(n.agents.length===0){console.log(`No agents found in ${n.activeProfile}.`);return}for(let a of n.agents)console.log(`${a.id} ${a.enabled?"enabled":"disabled"} ${a.path}`)}s(qe,"runOpenPondAgentsCommand");async function io(e,t,o){let n=l(t,"cwd"),a=[...o,...De(t,new Set(["cwd","account","profile","handle","baseUrl"]))];await le({command:e,cwd:n?M.resolve(n):void 0,args:a,inherit:!0})}s(io,"runOpenPondProfileSdkAlias");function X(e){if(e.mode==="none"){console.log("No active OpenPond profile."),console.log(`Default location: ${Z()}`);return}if(console.log(`Mode: ${e.mode}`),console.log(`Repo: ${e.repoPath}`),console.log(`Profile: ${e.activeProfile}`),console.log(`Source: ${e.sourcePath??"missing"}`),console.log(`State: ${e.summary.message}`),e.git&&(console.log(`Git: ${e.git.branch??"detached"} ${e.git.shortHead??"no-head"}${e.git.dirty?" dirty":" clean"}`),e.git.upstream&&console.log(`Upstream: ${e.git.upstream} ahead ${e.git.ahead??"?"} behind ${e.git.behind??"?"}`)),(e.hosted?.projectId||e.hosted?.sourceCommitSha)&&(console.log(`Hosted: ${e.hosted.projectId??"unbound"} ${e.hosted.sourceCommitSha??"no-source-head"}`),e.hosted.hostedSourceMaterialization&&console.log(`Hosted materialized: ${e.hosted.hostedSourceMaterialization.status}`+(e.hosted.hostedSourceMaterialization.agentId?` ${e.hosted.hostedSourceMaterialization.agentId}`:"")+(e.hosted.hostedSourceMaterialization.sourceCommitSha?` ${e.hosted.hostedSourceMaterialization.sourceCommitSha}`:"")),e.hosted.hostedSourceCheck&&console.log(`Hosted checks: ${e.hosted.hostedSourceCheck.status}`+(e.hosted.hostedSourceCheck.sandboxId?` sandbox ${e.hosted.hostedSourceCheck.sandboxId}`:"")),e.hosted.hostedPublish&&console.log(`Hosted publish: ${e.hosted.hostedPublish.status}`+(e.hosted.hostedPublish.snapshotId?` ${e.hosted.hostedPublish.snapshotId}`:"")),e.hosted.hostedRun&&console.log(`Hosted run: ${e.hosted.hostedRun.status}`+(e.hosted.hostedRun.runId?` ${e.hosted.hostedRun.runId}`:"")+(e.hosted.hostedRun.runtimeId?` runtime ${e.hosted.hostedRun.runtimeId}`:""))),console.log(`Catalog: ${e.catalog.actionCount} action(s)${e.catalog.stale?" stale":""}`),console.log(`Setup gate: ${e.setupGate.status} (${e.setupGate.blockingCount} blocking, ${e.setupGate.optionalMissingCount} optional missing)`),e.summary.defaultAction&&console.log(`Default action: ${e.summary.defaultAction}`),e.setupGate.blockingRequirements.length>0){console.log("Blocking setup:");for(let t of e.setupGate.blockingRequirements.slice(0,10))console.log(` ${Y(t)}`);e.setupGate.blockingRequirements.length>10&&console.log(` ... ${e.setupGate.blockingRequirements.length-10} more`)}if(!e.summary.checkFresh&&e.summary.checkStaleReason?console.log(`Checks: stale - ${e.summary.checkStaleReason}`):e.summary.checkFresh&&console.log("Checks: fresh"),e.lastCheck&&console.log(`Last check: ${e.lastCheck.command} ${e.lastCheck.status} at ${e.lastCheck.checkedAt}`),e.error&&console.log(`Error: ${e.error}`),e.agents.length>0){console.log("Agents:");for(let t of e.agents)console.log(` ${t.id} (${t.enabled?"enabled":"disabled"}) ${t.path}`)}if(e.skills.length>0){console.log("Skills:");for(let t of e.skills){let o=t.validationStatus==="valid"?"valid":t.validationStatus;console.log(` ${t.name} (${o}) ${t.path}`)}}}s(X,"printProfileState");function Te(e){if(e.mode==="none"){console.log("No active OpenPond profile.");return}console.log(`Profile: ${e.activeProfile}`),console.log(`State: ${e.summary.message}`);let t=[["Changed agents",e.diff.changedAgents],["New agents",e.diff.newAgents],["Deleted agents",e.diff.deletedAgents],["Changed skills",e.diff.changedSkills],["Changed actions",e.diff.changedActions],["Changed extensions",e.diff.changedExtensions],["Setup changes",e.diff.setupChanges],["Env requirement changes",e.diff.envRequirementChanges]];for(let[o,n]of t)n.length!==0&&console.log(`${o}: ${n.join(", ")}`);if(e.diff.files.length===0){console.log("No source changes.");return}console.log("Files:");for(let o of e.diff.files)console.log(` ${o.status.padEnd(2)} ${o.path}`)}s(Te,"printProfileDiff");function Be(e){if(e.mode==="none"){console.log("No active OpenPond profile.");return}if(console.log(`Profile: ${e.activeProfile}`),console.log(`Catalog: ${e.catalog.actionCount} action(s)${e.catalog.stale?" stale":""}`),console.log(`Setup gate: ${e.setupGate.status} (${e.setupGate.blockingCount} blocking, ${e.setupGate.optionalMissingCount} optional missing)`),e.catalog.generatedAt&&console.log(`Generated at: ${e.catalog.generatedAt}`),e.catalog.error&&console.log(`Catalog error: ${e.catalog.error}`),e.actionCatalog.length===0){console.log("No catalog actions found. Run `openpond inspect` or `openpond build`.");return}for(let o of e.actionCatalog){let n=o.label??o.name??o.id,a=o.visibility??"default",c=e.setupGate.blockingRequirements.filter(u=>u.actionId===o.id),p=c.length?`setup_required:${c.map(u=>u.label).join(",")}`:"setup_ready";console.log(`${o.id} ${a} ${p} ${n}`)}let t=e.setupGate.blockingRequirements.filter(o=>o.actionId===null);if(t.length>0){console.log("Source setup blockers:");for(let o of t)console.log(` ${Y(o)}`)}}s(Be,"printProfileCatalog");function ye(e){if(console.log(`Hosted profile repo: ${e.project.name}`),console.log(`Project id: ${e.project.id}`),console.log(`Role: ${e.project.role??"profile"}`),console.log(`Default profile: ${e.defaultProfile}`),console.log(`Source path: ${e.sourcePath}`),console.log(`Seed status: ${e.seedStatus}`),e.sourceUpload?.sourceRef&&console.log(`Source ref: ${e.sourceUpload.sourceRef}`),e.sourceUpload?.sourceCommitSha&&console.log(`Source commit: ${e.sourceUpload.sourceCommitSha}`),e.seededAt&&console.log(`Seeded at: ${e.seededAt}`),e.agents.length>0){console.log("Agents:");for(let t of e.agents)console.log(` ${t.id} (${t.enabled?"enabled":"disabled"}) ${t.path}`)}}s(ye,"printHostedProfileSummary");function De(e,t){let o=[],n=new Set(["force","json"]);for(let[a,c]of Object.entries(e)){if(t.has(a))continue;let p=`--${a.replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;if(c===!0||n.has(a)&&c==="true")o.push(p);else{if(n.has(a)&&c==="false")continue;typeof c=="string"&&o.push(p,c)}}return o}s(De,"optionArgs");function Fe(e,t){let o=l(e,t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`--${t} must be a JSON object`);return n}s(Fe,"parseJsonObjectOption");export{ze as collectProfileSourceUploadForPush,qe as runOpenPondAgentsCommand,so as runOpenPondInitCommand,ao as runOpenPondProfileCommand,io as runOpenPondProfileSdkAlias};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as b,b as Y,c as F,d as H,e as W,f as z,g as X,h as E,i as y,j as v,k as C,l as Z,m as ee,n as A,o as te,p as _,q as j,r as re,s as ne,t as x,u as M,v as R,w as J,x as N,y as U,z as T}from"./chunk-QWE3RHNY.js";import{p as h,q as I,y as P}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-73KFNV3D.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";function k(e){let o=e.gitRepo?`${e.gitOwner??"_"}/${e.gitRepo}`:e.internalRepoPath??e.templateRepoUrl??e.normalizedSourceIdentity;return[e.id,e.status,e.sourceType,e.name,o].join(" ")}g(k,"formatProjectLine");function L(e){let o=e.selectedEntrypoint.name?`${e.selectedEntrypoint.scope}:${e.selectedEntrypoint.name}`:e.selectedEntrypoint.scope,i=e.runtimeSource?[e.runtimeSource.mode,e.runtimeSource.publishedSnapshotName??e.runtimeSource.publishedSnapshotId??e.runtimeSource.sourceRef].filter(a=>!!a).join(":"):"latest_source";return[e.id,e.status,e.triggerType,e.defaultWorkflowMode,i,o,e.name].join(" ")}g(L,"formatAgentLine");async function B(e,o,i){let a=i[1]?.trim(),t=i[2]?.trim(),n="usage: agent source <deploy-plan|checks|manifest-snapshots|setup|publish> <agent-id> --team-id <id>",r=d(o,n);if(!a||!t)throw new Error(n);if(a==="deploy-plan"){let s=await e.agents.sourceDeployPlan(t,{teamId:r});console.log(JSON.stringify({deployPlan:s},null,2));return}if(a==="manifest-snapshots"){let s=await e.agents.manifestSnapshots(t,{teamId:r,limit:x(o.limit)});console.log(JSON.stringify({manifestSnapshots:s},null,2));return}if(a==="checks"){let s=await e.agents.requestSourceChecks(t,M(r,o));console.log(JSON.stringify(s,null,2));return}if(a==="setup"){let s=typeof o.provider=="string"?o.provider.trim():"",l=typeof o.allowedActions=="string"?o.allowedActions.split(",").map(c=>c.trim()).filter(Boolean):[];if(!s||l.length===0)throw new Error(`${n}; setup requires --provider and --allowed-actions`);let p=await e.agents.configureSourceSetup(t,{teamId:r,integrationBindings:[{provider:s,mode:"connected",connectionMode:"member_connection",grantPolicy:"read_only",allowedActions:l,enabled:!0}]});console.log(JSON.stringify(p,null,2));return}if(a==="publish"){let s=await e.agents.publishSource(t,R(r,o));console.log(JSON.stringify(s,null,2));return}throw new Error(n)}g(B,"runAgentSourceWorkflow");import G from"node:path";var Q=new Set(["inspect","build","validate","eval","traces"]);function $(e,o){return Q.has(e)?!0:e==="run"&&!u(o,"teamId")}g($,"shouldDelegateLocalAgentSdkCommand");async function q(e,o){let i=o[0]||"inspect",a=G.resolve(u(e,"cwd")||u(e,"path")||"."),t=[i,...o.slice(1),"--cwd",a];S(e.json)&&t.push("--json"),D(t,e,"input","input"),D(t,e,"inputFile","input-file");let n=b(a),r=await P(n.command,[...n.args,...t],{cwd:a,inherit:!0});r.code!==0&&(process.exitCode=r.code??1)}g(q,"runLocalAgentSdkCommand");function D(e,o,i,a){let t=u(o,i);t&&e.push(`--${a}`,t)}g(D,"appendForwardedOption");async function Oe(e,o){let i=o[0]||"list";if($(i,e)){await q(e,o);return}let a=await h(e);if(i==="list"){let t=d(e,"usage: agent list"),n=await a.agents.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({agents:n},null,2));return}if(n.length===0){console.log("no sandbox agents found");return}for(let r of n)console.log(L(r));return}if(i==="create"||i==="upsert"){let t=await a.agents.upsert(U(e));console.log(JSON.stringify({agent:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: agent get <agentId>");if(!t)throw new Error("usage: agent get <agentId> --team-id <id>");let r=await a.agents.get(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}if(i==="run"){let t=o[1]?.trim(),n=d(e,"usage: agent run <agentId>");if(!t)throw new Error("usage: agent run <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=A(e.triggerType),c=I(e.workflowMode),m=w(e,"input","input"),f=w(e,"metadata","metadata"),O=j(e),K=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...p?{triggerType:p}:{},...c?{workflowMode:c}:{},...m?{input:m}:{},...f?{metadata:f}:{},...O?{runtimeSourcePolicy:O}:{}});console.log(JSON.stringify(K,null,2));return}if(i==="bind-runtime-source"||i==="bind-source"){let t=o[1]?.trim(),n=d(e,"usage: agent bind-source <agentId>");if(!t)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let r=_(e);if(!r?.mode)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let s=await a.agents.update(t,{teamId:n,runtimeSource:r});console.log(JSON.stringify({agent:s,agentSource:s.runtimeSource},null,2));return}if(i==="run-test"){let t=o[1]?.trim(),n=d(e,"usage: agent run-test <agentId>");if(!t)throw new Error("usage: agent run-test <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=w(e,"input","input"),c=w(e,"metadata","metadata"),m=I(e.workflowMode),f=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...m?{workflowMode:m}:{},...p?{input:p}:{},metadata:{...c??{},source:"agent_run_test"},runtimeSourcePolicy:j(e,"diagnostic")});console.log(JSON.stringify({resolvedRuntimeSource:f.run.runtimeSource,agent:f.agent,run:f.run,sandbox:f.sandbox??null},null,2));return}if(i==="source"){await B(a,e,o);return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: agent update <agentId>");if(!t)throw new Error("usage: agent update <agentId> --team-id <id>");let r=await a.agents.update(t,T(n,e));console.log(JSON.stringify({agent:r},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: agent archive <agentId>");if(!t)throw new Error("usage: agent archive <agentId> --team-id <id>");let r=await a.agents.archive(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}throw new Error("usage: agent <inspect|build|validate|eval|traces|list|create|upsert|get|update|run|run-test|bind-source|source|edit|archive> [--team-id <id>] [--project-id <id>] [--name <name>]")}g(Oe,"runAgentCommand");import V from"node:path";async function xe(e,o){let i=o[0]||"list",a=await h(e);if(i==="list"){let t=d(e,"usage: project list"),n=await a.projects.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({projects:n},null,2));return}if(n.length===0){console.log("no sandbox projects found");return}for(let r of n)console.log(k(r));return}if(i==="create"||i==="upsert"){let t=await a.projects.upsert(J(e));console.log(JSON.stringify({project:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: project get <projectId>");if(!t)throw new Error("usage: project get <projectId> --team-id <id>");let r=await a.projects.get(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: project update <projectId>");if(!t)throw new Error("usage: project update <projectId> --team-id <id>");let r=await a.projects.update(t,N(n,e));console.log(JSON.stringify({project:r},null,2));return}if(i==="sync"){let t=o[1]?.trim(),n=d(e,"usage: project sync <projectId>");if(!t)throw new Error("usage: project sync <projectId> --team-id <id>");let r=await a.projects.sync(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="source-upload"||i==="upload-source"){let t=o[1]?.trim(),n=d(e,"usage: project source-upload <projectId>");if(!t)throw new Error("usage: project source-upload <projectId> --team-id <id> [--path <dir>]");let r=V.resolve(u(e,"path")||"."),s=await E(r,e),l=u(e,"commitMessage")||u(e,"commit-message")||"Upload OpenPond project source",p=await y(r),c=await v(r,p.entries),m=C(p,c.entries),f=await a.projects.uploadSource(t,{teamId:n,entries:m.entries,...s?{branch:s}:{},commitMessage:l});console.log(JSON.stringify({project:f,uploaded:{path:r,branch:s,fileCount:m.fileCount,totalBytes:m.totalBytes,limits:m.limits,transport:m.transport,...c.generatedManifestPath?{agentSdk:{generatedManifestPath:c.generatedManifestPath,generatedEntryCount:c.entries.length,synthesizedOpenPondYaml:c.synthesizedOpenPondYaml,uploadMetadataPath:c.uploadMetadataPath,uploadMetadataHash:c.uploadMetadataHash,commands:c.uploadMetadata?.commands,dependencySetup:c.uploadMetadata?.dependencySetup,packageManager:c.uploadMetadata?.packageManager,sourceTreeMode:c.uploadMetadata?.sourceTreeMode,artifactHashes:c.uploadMetadata?.artifactHashes}}:{}}},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: project archive <projectId>");if(!t)throw new Error("usage: project archive <projectId> --team-id <id>");let r=await a.projects.archive(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}throw new Error("usage: project <list|create|upsert|get|update|sync|source-upload|archive> [--team-id <id>] [--name <name>]")}g(xe,"runProjectCommand");export{W as PROJECT_SOURCE_UPLOAD_CONCURRENCY,z as PROJECT_SOURCE_UPLOAD_LIMITS,H as PROJECT_SOURCE_UPLOAD_MAX_BYTES,Y as PROJECT_SOURCE_UPLOAD_MAX_FILES,F as PROJECT_SOURCE_UPLOAD_MAX_FILE_BYTES,X as PROJECT_SOURCE_UPLOAD_TRANSPORT,M as buildAgentSourceChecksInput,_ as buildAgentSourceConfig,j as buildAgentSourcePolicy,R as buildAgentSourcePublishInput,T as buildAgentUpdateInput,U as buildAgentUpsertInput,N as buildProjectUpdateInput,J as buildProjectUpsertInput,y as collectProjectSourceUploadEntries,L as formatAgentLine,k as formatProjectLine,ee as parseAgentEntrypointScope,ne as parseAgentSourceCheckDispatch,re as parseAgentSourceCheckKind,te as parseAgentSourceMode,A as parseAgentTriggerType,x as parsePositiveLimit,Z as parseProjectSourceType,b as resolveLocalAgentSdkCommand,Oe as runAgentCommand,B as runAgentSourceWorkflow,xe as runProjectCommand};
2
+ import{a as b,b as Y,c as F,d as H,e as W,f as z,g as X,h as E,i as y,j as v,k as C,l as Z,m as ee,n as A,o as te,p as _,q as j,r as re,s as ne,t as x,u as M,v as R,w as J,x as N,y as U,z as T}from"./chunk-QWE3RHNY.js";import{p as h,q as I,y as P}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-73KFNV3D.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";function k(e){let o=e.gitRepo?`${e.gitOwner??"_"}/${e.gitRepo}`:e.internalRepoPath??e.templateRepoUrl??e.normalizedSourceIdentity;return[e.id,e.status,e.sourceType,e.name,o].join(" ")}g(k,"formatProjectLine");function L(e){let o=e.selectedEntrypoint.name?`${e.selectedEntrypoint.scope}:${e.selectedEntrypoint.name}`:e.selectedEntrypoint.scope,i=e.runtimeSource?[e.runtimeSource.mode,e.runtimeSource.publishedSnapshotName??e.runtimeSource.publishedSnapshotId??e.runtimeSource.sourceRef].filter(a=>!!a).join(":"):"latest_source";return[e.id,e.status,e.triggerType,e.defaultWorkflowMode,i,o,e.name].join(" ")}g(L,"formatAgentLine");async function B(e,o,i){let a=i[1]?.trim(),t=i[2]?.trim(),n="usage: agent source <deploy-plan|checks|manifest-snapshots|setup|publish> <agent-id> --team-id <id>",r=d(o,n);if(!a||!t)throw new Error(n);if(a==="deploy-plan"){let s=await e.agents.sourceDeployPlan(t,{teamId:r});console.log(JSON.stringify({deployPlan:s},null,2));return}if(a==="manifest-snapshots"){let s=await e.agents.manifestSnapshots(t,{teamId:r,limit:x(o.limit)});console.log(JSON.stringify({manifestSnapshots:s},null,2));return}if(a==="checks"){let s=await e.agents.requestSourceChecks(t,M(r,o));console.log(JSON.stringify(s,null,2));return}if(a==="setup"){let s=typeof o.provider=="string"?o.provider.trim():"",l=typeof o.allowedActions=="string"?o.allowedActions.split(",").map(c=>c.trim()).filter(Boolean):[];if(!s||l.length===0)throw new Error(`${n}; setup requires --provider and --allowed-actions`);let p=await e.agents.configureSourceSetup(t,{teamId:r,integrationBindings:[{provider:s,mode:"connected",connectionMode:"member_connection",grantPolicy:"read_only",allowedActions:l,enabled:!0}]});console.log(JSON.stringify(p,null,2));return}if(a==="publish"){let s=await e.agents.publishSource(t,R(r,o));console.log(JSON.stringify(s,null,2));return}throw new Error(n)}g(B,"runAgentSourceWorkflow");import G from"node:path";var Q=new Set(["inspect","build","validate","eval","traces"]);function $(e,o){return Q.has(e)?!0:e==="run"&&!u(o,"teamId")}g($,"shouldDelegateLocalAgentSdkCommand");async function q(e,o){let i=o[0]||"inspect",a=G.resolve(u(e,"cwd")||u(e,"path")||"."),t=[i,...o.slice(1),"--cwd",a];S(e.json)&&t.push("--json"),D(t,e,"input","input"),D(t,e,"inputFile","input-file");let n=b(a),r=await P(n.command,[...n.args,...t],{cwd:a,inherit:!0});r.code!==0&&(process.exitCode=r.code??1)}g(q,"runLocalAgentSdkCommand");function D(e,o,i,a){let t=u(o,i);t&&e.push(`--${a}`,t)}g(D,"appendForwardedOption");async function Oe(e,o){let i=o[0]||"list";if($(i,e)){await q(e,o);return}let a=await h(e);if(i==="list"){let t=d(e,"usage: agent list"),n=await a.agents.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({agents:n},null,2));return}if(n.length===0){console.log("no sandbox agents found");return}for(let r of n)console.log(L(r));return}if(i==="create"||i==="upsert"){let t=await a.agents.upsert(U(e));console.log(JSON.stringify({agent:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: agent get <agentId>");if(!t)throw new Error("usage: agent get <agentId> --team-id <id>");let r=await a.agents.get(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}if(i==="run"){let t=o[1]?.trim(),n=d(e,"usage: agent run <agentId>");if(!t)throw new Error("usage: agent run <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=A(e.triggerType),c=I(e.workflowMode),m=w(e,"input","input"),f=w(e,"metadata","metadata"),O=j(e),K=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...p?{triggerType:p}:{},...c?{workflowMode:c}:{},...m?{input:m}:{},...f?{metadata:f}:{},...O?{runtimeSourcePolicy:O}:{}});console.log(JSON.stringify(K,null,2));return}if(i==="bind-runtime-source"||i==="bind-source"){let t=o[1]?.trim(),n=d(e,"usage: agent bind-source <agentId>");if(!t)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let r=_(e);if(!r?.mode)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let s=await a.agents.update(t,{teamId:n,runtimeSource:r});console.log(JSON.stringify({agent:s,agentSource:s.runtimeSource},null,2));return}if(i==="run-test"){let t=o[1]?.trim(),n=d(e,"usage: agent run-test <agentId>");if(!t)throw new Error("usage: agent run-test <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=w(e,"input","input"),c=w(e,"metadata","metadata"),m=I(e.workflowMode),f=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...m?{workflowMode:m}:{},...p?{input:p}:{},metadata:{...c??{},source:"agent_run_test"},runtimeSourcePolicy:j(e,"diagnostic")});console.log(JSON.stringify({resolvedRuntimeSource:f.run.runtimeSource,agent:f.agent,run:f.run,sandbox:f.sandbox??null},null,2));return}if(i==="source"){await B(a,e,o);return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: agent update <agentId>");if(!t)throw new Error("usage: agent update <agentId> --team-id <id>");let r=await a.agents.update(t,T(n,e));console.log(JSON.stringify({agent:r},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: agent archive <agentId>");if(!t)throw new Error("usage: agent archive <agentId> --team-id <id>");let r=await a.agents.archive(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}throw new Error("usage: agent <inspect|build|validate|eval|traces|list|create|upsert|get|update|run|run-test|bind-source|source|edit|archive> [--team-id <id>] [--project-id <id>] [--name <name>]")}g(Oe,"runAgentCommand");import V from"node:path";async function xe(e,o){let i=o[0]||"list",a=await h(e);if(i==="list"){let t=d(e,"usage: project list"),n=await a.projects.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({projects:n},null,2));return}if(n.length===0){console.log("no sandbox projects found");return}for(let r of n)console.log(k(r));return}if(i==="create"||i==="upsert"){let t=await a.projects.upsert(J(e));console.log(JSON.stringify({project:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: project get <projectId>");if(!t)throw new Error("usage: project get <projectId> --team-id <id>");let r=await a.projects.get(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: project update <projectId>");if(!t)throw new Error("usage: project update <projectId> --team-id <id>");let r=await a.projects.update(t,N(n,e));console.log(JSON.stringify({project:r},null,2));return}if(i==="sync"){let t=o[1]?.trim(),n=d(e,"usage: project sync <projectId>");if(!t)throw new Error("usage: project sync <projectId> --team-id <id>");let r=await a.projects.sync(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="source-upload"||i==="upload-source"){let t=o[1]?.trim(),n=d(e,"usage: project source-upload <projectId>");if(!t)throw new Error("usage: project source-upload <projectId> --team-id <id> [--path <dir>]");let r=V.resolve(u(e,"path")||"."),s=await E(r,e),l=u(e,"commitMessage")||u(e,"commit-message")||"Upload OpenPond project source",p=await y(r),c=await v(r,p.entries),m=C(p,c.entries),f=await a.projects.uploadSource(t,{teamId:n,entries:m.entries,...s?{branch:s}:{},commitMessage:l});console.log(JSON.stringify({project:f,uploaded:{path:r,branch:s,fileCount:m.fileCount,totalBytes:m.totalBytes,limits:m.limits,transport:m.transport,...c.generatedManifestPath?{agentSdk:{generatedManifestPath:c.generatedManifestPath,generatedEntryCount:c.entries.length,synthesizedOpenPondYaml:c.synthesizedOpenPondYaml,uploadMetadataPath:c.uploadMetadataPath,uploadMetadataHash:c.uploadMetadataHash,commands:c.uploadMetadata?.commands,dependencySetup:c.uploadMetadata?.dependencySetup,packageManager:c.uploadMetadata?.packageManager,sourceTreeMode:c.uploadMetadata?.sourceTreeMode,artifactHashes:c.uploadMetadata?.artifactHashes}}:{}}},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: project archive <projectId>");if(!t)throw new Error("usage: project archive <projectId> --team-id <id>");let r=await a.projects.archive(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}throw new Error("usage: project <list|create|upsert|get|update|sync|source-upload|archive> [--team-id <id>] [--name <name>]")}g(xe,"runProjectCommand");export{W as PROJECT_SOURCE_UPLOAD_CONCURRENCY,z as PROJECT_SOURCE_UPLOAD_LIMITS,H as PROJECT_SOURCE_UPLOAD_MAX_BYTES,Y as PROJECT_SOURCE_UPLOAD_MAX_FILES,F as PROJECT_SOURCE_UPLOAD_MAX_FILE_BYTES,X as PROJECT_SOURCE_UPLOAD_TRANSPORT,M as buildAgentSourceChecksInput,_ as buildAgentSourceConfig,j as buildAgentSourcePolicy,R as buildAgentSourcePublishInput,T as buildAgentUpdateInput,U as buildAgentUpsertInput,N as buildProjectUpdateInput,J as buildProjectUpsertInput,y as collectProjectSourceUploadEntries,L as formatAgentLine,k as formatProjectLine,ee as parseAgentEntrypointScope,ne as parseAgentSourceCheckDispatch,re as parseAgentSourceCheckKind,te as parseAgentSourceMode,A as parseAgentTriggerType,x as parsePositiveLimit,Z as parseProjectSourceType,b as resolveLocalAgentSdkCommand,Oe as runAgentCommand,B as runAgentSourceWorkflow,xe as runProjectCommand};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as N,b as E,c as P,d as J,e as j,f as S,g as O,h as C,i as R,j as k,k as B,l as q,m as U,n as L,o as l}from"./chunk-V4ACXLID.js";import{p as v,v as w,w as y}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{b as I,f,g as h,h as p}from"./chunk-3M53YXEI.js";import{a as b}from"./chunk-FTQLQJQV.js";async function M(r,o,e,i){if(o==="list-files"){let t=i[1];if(!t)throw new Error("usage: sandbox list-files <sandboxId> [--path <path>]");let n=typeof e.path=="string"?e.path.trim():void 0,s=h(e.maxEntries,"max-entries"),a=e.recursive!==void 0?f(e.recursive):void 0,d=await r.listFiles(t,{...n?{path:n}:{},...a!==void 0?{recursive:a}:{},...s!==void 0?{maxEntries:s}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),files:d.files},null,2)),!0}if(o==="upload-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=typeof e.contents=="string"?e.contents:typeof e.content=="string"?e.content:"",a=typeof e.contentsBase64=="string"?e.contentsBase64.trim():typeof e.contentBase64=="string"?e.contentBase64.trim():"";if(!t||!n)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');if(!s&&!a)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');let d=a?await r.uploadFileBase64(t,n,a):await r.uploadFile(t,n,s);return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file},null,2)),!0}if(o==="download-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=Number(e["offset-bytes"]),a=Number(e["max-bytes"]);if(!t||!n)throw new Error("usage: sandbox download-file <sandboxId> --path <path>");let d=await r.downloadFileResponse(t,{path:n,...Number.isFinite(s)?{offsetBytes:s}:{},...Number.isFinite(a)?{maxBytes:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file,contents:Buffer.from(d.file.contentsBase64,"base64").toString("utf-8")},null,2)),!0}if(o==="search-files"){let t=i[1],n=typeof e.query=="string"?e.query.trim():"";if(!t||!n)throw new Error("usage: sandbox search-files <sandboxId> --query <text> [--path <path>]");let s=typeof e.path=="string"?e.path.trim():void 0,a=h(e.maxResults,"max-results"),d=await r.searchFiles(t,{query:n,...s?{path:s}:{},...a!==void 0?{maxResults:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),matches:d.matches},null,2)),!0}if(o==="delete-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox delete-file <sandboxId> --path <path> [--recursive]");let s=await r.deleteFile(t,n,{recursive:f(e.recursive)});return console.log(JSON.stringify({sandbox:l(s.sandbox),deleted:s.deleted},null,2)),!0}if(o==="stat-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox stat-file <sandboxId> --path <path>");let s=await r.statFile(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),file:s.file},null,2)),!0}if(o==="mkdir"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox mkdir <sandboxId> --path <path> [--recursive false]");let s=await r.mkdir(t,{path:n,recursive:e.recursive!==void 0?f(e.recursive):void 0});return console.log(JSON.stringify({sandbox:l(s.sandbox),directory:s.directory},null,2)),!0}if(o==="move-file"){let t=i[1],n=typeof e.fromPath=="string"?e.fromPath.trim():"",s=typeof e.toPath=="string"?e.toPath.trim():"";if(!t||!n||!s)throw new Error("usage: sandbox move-file <sandboxId> --from-path <path> --to-path <path> [--overwrite]");let a=await r.moveFile(t,{fromPath:n,toPath:s,overwrite:f(e.overwrite)});return console.log(JSON.stringify({sandbox:l(a.sandbox),moved:a.moved,file:a.file},null,2)),!0}return!1}b(M,"handleSandboxFilesCommand");async function T(r,o,e,i){if(o==="git-status"){let t=i[1];if(!t)throw new Error("usage: sandbox git-status <sandboxId>");let n=await r.gitStatus(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),status:n.status},null,2)),!0}if(o==="git-diff"){let t=i[1];if(!t)throw new Error("usage: sandbox git-diff <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitDiff(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),diff:s.diff},null,2)),!0}if(o==="git-export-patch"){let t=i[1];if(!t)throw new Error("usage: sandbox git-export-patch <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitExportPatch(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),patch:s.patch},null,2)),!0}if(o==="git-branch"){let t=i[1],n=typeof e.branch=="string"?e.branch.trim():"",s=typeof e.startPoint=="string"&&e.startPoint.trim()?e.startPoint.trim():void 0;if(!t||!n)throw new Error("usage: sandbox git-branch <sandboxId> --branch <name> [--create] [--start-point <ref>]");let a=await r.gitBranch(t,{branch:n,create:f(e.create),...s?{startPoint:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),branch:a.branch},null,2)),!0}if(o==="git-commit"){let t=i[1],n=typeof e.message=="string"?e.message.trim():"",s=f(e.all),d=(typeof e.paths=="string"?e.paths:typeof e.path=="string"?e.path:"").split(",").map(g=>g.trim()).filter(Boolean);if(!t||!n||!s&&d.length===0)throw new Error('usage: sandbox git-commit <sandboxId> --message "..." [--all|--paths <csv>]');let c=await r.gitCommit(t,{message:n,...s?{all:!0}:{paths:d}});return console.log(JSON.stringify({sandbox:l(c.sandbox),commit:c.commit},null,2)),!0}if(o==="git-pull"){let t=i[1];if(!t)throw new Error("usage: sandbox git-pull <sandboxId> [--remote origin] [--branch main] [--rebase|--ff-only false]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPull(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.rebase!==void 0?{rebase:f(e.rebase)}:{},...e.ffOnly!==void 0?{ffOnly:f(e.ffOnly)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pull:a.pull},null,2)),!0}if(o==="git-push"){let t=i[1];if(!t)throw new Error("usage: sandbox git-push <sandboxId> [--remote origin] [--branch main] [--set-upstream] [--force-with-lease]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPush(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.setUpstream!==void 0?{setUpstream:f(e.setUpstream)}:{},...e.forceWithLease!==void 0?{forceWithLease:f(e.forceWithLease)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),push:a.push},null,2)),!0}return!1}b(T,"handleSandboxGitCommand");async function F(r,o,e,i){if(o==="process-start"){let t=i[1],n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox process-start <sandboxId> --command <command>");let s=p(e.timeoutSeconds,"timeout-seconds"),a=await r.startProcess(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process},null,2)),!0}if(o==="process-list"){let t=i[1];if(!t)throw new Error("usage: sandbox process-list <sandboxId>");let n=await r.listProcesses(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),processes:n.processes},null,2)),!0}if(o==="process-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-get <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getProcess(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="process-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stop <sandboxId> <processId>");let s=await r.stopProcess(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),process:s.process},null,2)),!0}if(o==="process-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stream <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamProcessOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}if(o==="pty-start"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-start <sandboxId> [--command <command>]");let n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" "),s=p(e.timeoutSeconds,"timeout-seconds"),a=p(e.rows,"rows"),d=p(e.cols,"cols"),c=await r.startPty(t,{...n.trim()?{command:n.trim()}:{},...s!==void 0?{timeoutSeconds:s}:{},...a!==void 0?{rows:a}:{},...d!==void 0?{cols:d}:{}});return console.log(JSON.stringify({sandbox:l(c.sandbox),pty:c.pty},null,2)),!0}if(o==="pty-list"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-list <sandboxId>");let n=await r.listPtys(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),ptys:n.ptys},null,2)),!0}if(o==="pty-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-get <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getPty(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pty:a.pty,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="pty-write"){let t=i[1],n=i[2],s=typeof e.inputBase64=="string"?e.inputBase64.trim():"",a=(typeof e.input=="string"?e.input:null)||i.slice(3).join(" ");if(!t||!n||!s&&!a)throw new Error("usage: sandbox pty-write <sandboxId> <ptyId> --input <text>");let d=await r.writePtyInput(t,n,s?{dataBase64:s}:a);return console.log(JSON.stringify({sandbox:l(d.sandbox),pty:d.pty},null,2)),!0}if(o==="pty-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stop <sandboxId> <ptyId>");let s=await r.stopPty(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),pty:s.pty},null,2)),!0}if(o==="pty-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stream <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamPtyOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}return!1}b(F,"handleSandboxProcessCommand");async function A(r,o,e,i){if(o==="replays"||o==="replay-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=await r.listReplays({...t?{teamId:t}:{},...n?{projectId:n}:{}});if(f(e.json))return console.log(JSON.stringify(s,null,2)),!0;if(s.replays.length===0)return console.log("no sandbox replays found"),!0;for(let a of s.replays)console.log(O(a));return!0}if(o==="replay-start"||o==="start-replay"){let t=await r.startReplay(k(e));return console.log(JSON.stringify(t,null,2)),!0}if(o==="replay-get"||o==="get-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-get <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-logs"||o==="logs-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-logs <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayLogs(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let d of a.logs)console.log(d);return!0}if(o==="replay-artifacts"||o==="artifacts-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-artifacts <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayArtifacts(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify({replayId:a.replayId,artifacts:a.artifacts.map(C)},null,2)),!0}if(o==="replay-cancel"||o==="cancel-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-cancel <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.cancelReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-watch"||o==="watch-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-watch <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=p(e.intervalMs,"interval-ms")??5e3,d=p(e.timeoutMs,"timeout-ms")??900*1e3,c=Date.now(),g=new Set;for(;Date.now()-c<=d;){let u=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let m of u.replay.logs)g.has(m)||(g.add(m),console.log(m));if(u.replay.state==="succeeded"||u.replay.state==="failed"||u.replay.state==="canceled"){if(console.log(O(u.replay)),u.replay.state!=="succeeded")throw new Error(`sandbox replay ${u.replay.state}: ${u.replay.error??"no error"}`);return!0}await new Promise(m=>setTimeout(m,a))}throw new Error(`sandbox replay did not finish within ${d}ms`)}return!1}b(A,"handleSandboxReplayCommand");async function V(r,o,e,i){if(o==="runtime-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=typeof e.agentId=="string"?e.agentId.trim():"",a=await r.listSandboxRuntimes({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});return console.log(JSON.stringify({runtimes:a},null,2)),!0}if(o==="runtime-get"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-get <runtimeId>");let n=await r.getSandboxRuntime(t);return console.log(JSON.stringify({runtime:n},null,2)),!0}if(o==="runtime-events"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-events <runtimeId>");return console.log(JSON.stringify(await r.listSandboxRuntimeEvents(t),null,2)),!0}if(o==="runtime-status"){let t=i[1]?.trim(),n=typeof e.status=="string"&&e.status.trim()?e.status.trim():"",s=Number(e.expectedVersion),a=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0;if(!t||!n||!Number.isInteger(s))throw new Error("usage: sandbox runtime-status <runtimeId> --status <status> --expected-version <n>");let d=await r.updateSandboxRuntimeStatus(t,{status:n,expectedVersion:s,...a?{summary:a}:{}});return console.log(JSON.stringify({runtime:d},null,2)),!0}if(o==="runtime-event"){let t=i[1]?.trim(),n=typeof e.type=="string"&&e.type.trim()?e.type.trim():"",s=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,a=typeof e.payload=="string"&&e.payload.trim()?I(e.payload,"payload"):void 0,d=typeof e.lifecycleHint=="string"&&e.lifecycleHint.trim()?I(e.lifecycleHint,"lifecycle-hint"):void 0;if(!t||!n)throw new Error("usage: sandbox runtime-event <runtimeId> --type <eventType> [--summary <text>] [--payload <json>] [--lifecycle-hint <json>]");return console.log(JSON.stringify(await r.emitSandboxRuntimeEvent(t,{type:n,...s?{summary:s}:{},...a?{payload:a}:{},...d?{lifecycleHint:d}:{}}),null,2)),!0}if(o==="runtime-preserve-source"||o==="runtime-preserve"){let t=i[1]?.trim(),n=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():"",s=typeof e.sandboxId=="string"&&e.sandboxId.trim()?e.sandboxId.trim():"",a=typeof e.message=="string"&&e.message.trim()?e.message.trim():"";if(!t)throw new Error("usage: sandbox runtime-preserve-source <runtimeId> [--team-id <id>] [--sandbox-id <id>] [--message <text>]");return console.log(JSON.stringify(await r.runtimes.preserveSource(t,{...s?{sandboxId:s}:{},...a?{message:a}:{}},{...n?{teamId:n}:{}}),null,2)),!0}return!1}b(V,"handleSandboxRuntimeCommand");async function $(r,o,e,i){if(o==="secrets"||o==="secret-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=await r.listSecrets({...t?{teamId:t}:{}});if(f(e.json))return console.log(JSON.stringify({secrets:n.map(y)},null,2)),!0;if(n.length===0)return console.log("no sandbox secrets found"),!0;for(let s of n)console.log(`${s.name} ${s.status} v${s.currentVersion??"current"} ${s.secretRef}`);return!0}if(o==="secret-create"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.name=="string"?e.name.trim():"",s=typeof e.description=="string"&&e.description.trim()?e.description.trim():void 0,a=e.scope==="project"||e.scope==="template"||e.scope==="team"?e.scope:void 0;if(!n)throw new Error("usage: sandbox secret-create --name <ENV_NAME> [--team-id <id>] [--stdin]");let d=await w(e,`Value for ${n}`),c=await r.createSecret({...t?{teamId:t}:{},name:n,value:d,...s?{description:s}:{},...a?{scope:a}:{}});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-rotate"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox secret-rotate <secretId> [--team-id <id>] [--stdin]");let s=await w(e,"New secret value"),a=await r.rotateSecret(t,{...n?{teamId:n}:{},value:s});return console.log(JSON.stringify({secret:y(a)},null,2)),!0}if(o==="secret-attach"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.envName=="string"?e.envName.trim():"",a=e.targetType==="sandbox"||e.targetType==="template"||e.targetType==="project"||e.targetType==="agent"||e.targetType==="replay"?e.targetType:void 0,d=typeof e.targetId=="string"?e.targetId.trim():"";if(!t||!s||!a||!d)throw new Error("usage: sandbox secret-attach <secretId> --env-name <ENV_NAME> --target-type sandbox|project|agent|template|replay --target-id <id>");let c=await r.attachSecret(t,{...n?{teamId:n}:{},envName:s,targetType:a,targetId:d});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-revoke"||o==="secret-delete"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error(`usage: sandbox ${o} <secretId> [--team-id <id>]`);let s=o==="secret-revoke"?await r.revokeSecret(t,{...n?{teamId:n}:{}}):await r.deleteSecret(t,{...n?{teamId:n}:{}});return console.log(JSON.stringify({secret:y(s)},null,2)),!0}return!1}b($,"handleSandboxSecretsCommand");async function H(r,o,e,i){if(o==="published-snapshot-builds"||o==="published-snapshot-build-list"||o==="template-builds"||o==="template-build-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox published-snapshot-builds --team-id <id>");let n=await r.listPublishedSnapshotBuilds({teamId:t});if(f(e.json))return console.log(JSON.stringify({builds:n},null,2)),!0;if(n.length===0)return console.log("no published snapshot builds found"),!0;for(let s of n)console.log(S(s));return!0}if(o==="published-snapshot-build-create"||o==="create-published-snapshot-build"||o==="template-build-create"||o==="create-template-build"){let t=await r.createPublishedSnapshotBuild(U(e));return console.log(JSON.stringify({build:t},null,2)),!0}if(o==="published-snapshot-build-get"||o==="get-published-snapshot-build"||o==="template-build-get"||o==="get-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-get <buildId>");let n=await r.getPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-logs"||o==="published-snapshot-build-log"||o==="template-build-logs"||o==="template-build-log"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-logs <buildId>");let n=await r.getPublishedSnapshotBuildLogs(t);if(f(e.json))return console.log(JSON.stringify(n,null,2)),!0;for(let s of n.logs)console.log(s);return!0}if(o==="published-snapshot-build-cancel"||o==="cancel-published-snapshot-build"||o==="template-build-cancel"||o==="cancel-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-cancel <buildId>");let n=await r.cancelPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-watch"||o==="watch-published-snapshot-build"||o==="template-build-watch"||o==="watch-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-watch <buildId>");let n=p(e.intervalMs,"interval-ms")??5e3,s=p(e.timeoutMs,"timeout-ms")??900*1e3,a=Date.now(),d=new Set;for(;Date.now()-a<=s;){let[c,g]=await Promise.all([r.getPublishedSnapshotBuild(t),r.getPublishedSnapshotBuildLogs(t)]);for(let u of g.logs)d.has(u)||(d.add(u),console.log(u));if(c.status==="succeeded"||c.status==="failed"||c.status==="cancelled"){if(console.log(S(c)),c.status!=="succeeded")throw new Error(`published snapshot build ${c.status}: ${c.error??"no error"}`);return!0}await new Promise(u=>setTimeout(u,n))}throw new Error(`published snapshot build did not finish within ${s}ms`)}return!1}b(H,"handleSandboxTemplateBuildsCommand");function G(r){return f(r.async)||f(r.respondAsync)}b(G,"parseSandboxAsyncOption");async function Pe(r,o){let e=o[0]||"list",i=await v(r);if(e==="list"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.list({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(a.length===0){console.log("no sandboxes found");return}for(let d of a)console.log(P(d));return}if(e==="mcp-config"||e==="mcp-url"){let t=i.mcpServerConfig();console.log(JSON.stringify({...t,headers:{"openpond-api-key":"set OPENPOND_API_KEY or use your saved openpond profile"}},null,2));return}if(!await V(i,e,r,o)){if(e==="pricing"){let t=await i.pricing();console.log(JSON.stringify(t,null,2));return}if(e==="costs"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.costs({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(f(r.summary)){console.log(JSON.stringify({costs:{teamId:a.costs.teamId,ownerUserId:a.costs.ownerUserId,generatedAt:a.costs.generatedAt,summary:a.costs.summary,lineItems:a.costs.lineItems,tiers:a.costs.pricing.tiers.map(d=>({key:d.key,resources:d.resources,keepRunningEstimate:d.keepRunningEstimate}))}},null,2));return}console.log(JSON.stringify(a,null,2));return}if(!await $(i,e,r,o)){if(e==="snapshots"||e==="snapshot-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",d=typeof r.tag=="string"?r.tag.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"",g=typeof r.replayState=="string"?r.replayState.trim():"",u=await i.snapshotCatalog({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{q:a}:{},...d?{tag:d}:{},...c?{useCase:c}:{},...g==="draft"||g==="validated"||g==="published"?{replayState:g}:{}});if(u.snapshots.length===0){console.log("no sandbox snapshots found");return}for(let m of u.snapshots)console.log(J(m));return}if(e==="published-snapshots"||e==="published-snapshot-catalog"||e==="templates"||e==="template-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",a=typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.tag=="string"?r.tag.trim():"",g=typeof r.useCase=="string"?r.useCase.trim():"",u=await i.publishedSnapshots({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{q:s}:{},...a?{name:a}:{},...d?{version:d}:{},...c?{tag:c}:{},...g?{useCase:g}:{}});if(u.publishedSnapshots.length===0){console.log("no published snapshots found");return}for(let m of u.publishedSnapshots)console.log(j(m));return}if(!(await H(i,e,r,o)||await A(i,e,r,o))){if(e==="run-published-snapshot"||e==="published-snapshot-run"||e==="template-launch"||e==="launch-template"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.snapshotId=="string"&&r.snapshotId.trim()?r.snapshotId.trim():typeof r.snapshot=="string"&&r.snapshot.trim()?r.snapshot.trim():"",a=typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof o[1]=="string"&&o[1].trim()?o[1].trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"";if(!s&&!a&&!c)throw new Error("usage: sandbox run-published-snapshot [--snapshot-id <id>|--name <name>|--use-case <id>] [--version <v>]");let g=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",u=await i.runPublishedSnapshot({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{snapshotId:s}:{},...a?{templateName:a}:{},...d?{version:d}:{},...c?{useCase:c}:{},...g?{budget:{maxUsd:g}}:{},metadata:{source:"openpond-code-published-snapshot-run"}});console.log(JSON.stringify(u,null,2));return}if(e==="snapshot-fork"||e==="fork-snapshot"){let t=o[1];if(!t)throw new Error("snapshot-fork requires <snapshotId>");let n=typeof r.teamId=="string"?r.teamId.trim():"",s=typeof r.projectId=="string"?r.projectId.trim():"",a=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",d=await i.forkSnapshot(t,{...n?{teamId:n}:{},...s?{projectId:s}:{},...a?{budget:{maxUsd:a}}:{},metadata:{source:"openpond-code-snapshot-fork",templateSnapshotId:t}});console.log(JSON.stringify(d,null,2));return}if(e==="snapshot-create"||e==="create-snapshot"){let t=o[1];if(!t)throw new Error("usage: sandbox snapshot-create <sandboxId> --name <name>");let n=await i.createSnapshot(t,L(r));console.log(JSON.stringify(n,null,2));return}if(e==="snapshot-validate"||e==="validate-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-validate requires <sandboxId> <snapshotId>");let s=R(r.cleanup),a=await i.validateSnapshot(t,n,{...s?{cleanup:s}:{}});console.log(JSON.stringify(a,null,2));return}if(e==="snapshot-publish"||e==="publish-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-publish requires <sandboxId> <snapshotId>");let s=await i.publishSnapshot(t,n);console.log(JSON.stringify(s,null,2));return}if(e==="integration-connections"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=r.status==="active"||r.status==="revoked"||r.status==="error"||r.status==="all"?r.status:void 0,d=await i.integrationConnections({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{status:a}:{}});console.log(JSON.stringify(d,null,2));return}if(e==="create"){let t=await N(i,B(r));console.log(JSON.stringify({sandbox:l(t.sandbox),...t.runtime?{runtime:t.runtime}:{}},null,2));return}if(e==="exec"){let t=o[1],n=(typeof r.command=="string"?r.command:null)||o.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox exec <sandboxId> --command <command>");let s=p(r.timeoutSeconds,"timeout-seconds"),a=await i.exec(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});console.log(JSON.stringify({sandbox:l(a.sandbox),command:a.command},null,2));return}if(e==="port"||e==="preview"){let t=o[1],n=p(r.port,"port");if(!t||n===void 0)throw new Error("usage: sandbox port <sandboxId> --port <port>");let s=typeof r.label=="string"?r.label:void 0,a=typeof r.access=="string"?r.access.trim():"";if(a&&a!=="private"&&a!=="public")throw new Error("sandbox port --access must be private or public");let d=a==="public"?"public":"private",c=typeof r.domain=="string"?r.domain.trim():"",g=typeof r.authToken=="string"?r.authToken:"",u=typeof r.authHeader=="string"?r.authHeader.trim():"",m=typeof r.authHeaderValue=="string"?r.authHeaderValue:"";if(g&&(u||m))throw new Error("sandbox port auth options must use either --auth-token or --auth-header with --auth-header-value");if(u&&!m||!u&&m)throw new Error("sandbox port custom header auth requires both --auth-header and --auth-header-value");let x=await i.openPort(t,{port:n,...s?{label:s}:{},access:d,...r["auto-start"]||r.autoStart?{autoStart:!0}:{},...c?{customDomain:c}:{},...g?{authPolicy:{mode:"bearer",token:g}}:{},...u&&m?{authPolicy:{mode:"header",headerName:u,headerValue:m}}:{}});console.log(JSON.stringify(x.preview,null,2));return}if(e==="stop"){let t=o[1];if(!t)throw new Error("usage: sandbox stop <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.stop(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n.sandbox),receipt:n.receipt},null,2));return}if(e==="start"){let t=o[1];if(!t)throw new Error("usage: sandbox start <sandboxId>");let n=await i.start(t);console.log(JSON.stringify({sandbox:await E(i,n.sandbox),receipt:n.receipt},null,2));return}if(e==="delete"){let t=o[1];if(!t)throw new Error("usage: sandbox delete <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.delete(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n)},null,2));return}if(e==="receipts"){let t=o[1];if(!t)throw new Error("usage: sandbox receipts <sandboxId>");let n=await i.receipts(t);console.log(JSON.stringify({receipts:n},null,2));return}if(e==="logs"){let t=o[1];if(!t)throw new Error("usage: sandbox logs <sandboxId>");let n=await i.logs(t);for(let s of n)console.log(s);return}if(!(await F(i,e,r,o)||await M(i,e,r,o)||await T(i,e,r,o))){if(e==="billing"){let t=o[1];if(!t)throw new Error("usage: sandbox billing <sandboxId>");let n=await i.billing(t);console.log(JSON.stringify({sandbox:l(n.sandbox),billing:n.billing},null,2));return}if(e==="integration-leases"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-leases <sandboxId>");let n=await i.integrationLeases(t);console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-attach"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-attach <sandboxId> --integration-connection <id> --integration-capabilities <csv>");let n=await i.attachIntegrationConnection(t,q(r));console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-remove"){let t=o[1],n=typeof r.leaseId=="string"?r.leaseId.trim():"";if(!t||!n)throw new Error("usage: sandbox integration-remove <sandboxId> --lease-id <id>");let s=await i.removeIntegrationLease(t,n);console.log(JSON.stringify({sandbox:l(s.sandbox),integrationLeases:s.integrationLeases},null,2));return}if(e==="smoke"){let t=typeof r.repo=="string"?r.repo.trim():void 0,n=typeof r.budgetUsd=="string"?r.budgetUsd.trim():typeof r.budget=="string"?r.budget.trim():void 0,s=f(r.keep),a=r.preview!==void 0?f(r.preview):!f(r.noPreview),d=f(r.snapshot),c=f(r.fork),g={...t?{repo:t}:{},...n?{budgetUsd:n}:{},keep:s,preview:a,snapshot:d,fork:c};typeof r.expectedMppMode=="string"&&r.expectedMppMode.trim()&&(g.expectedMppMode=r.expectedMppMode.trim());let u=h(r.cpu,"cpu"),m=h(r.memoryGb,"memory-gb"),x=h(r.diskGb,"disk-gb");u!==void 0&&(g.cpu=u),m!==void 0&&(g.memoryGb=m),x!==void 0&&(g.diskGb=x);let z=await i.smoke(g);console.log(JSON.stringify(z,null,2));return}throw new Error("usage: sandbox <list|mcp-config|runtime-list|runtime-get|runtime-events|runtime-status|runtime-event|runtime-preserve-source|pricing|costs|secrets|secret-create|secret-rotate|secret-attach|secret-revoke|secret-delete|snapshots|published-snapshots|run-published-snapshot|snapshot-fork|snapshot-validate|snapshot-publish|create|exec|port|preview|stop|start|delete|receipts|logs|billing|process-start|process-list|process-get|process-stop|process-stream|pty-start|pty-list|pty-get|pty-write|pty-stop|pty-stream|upload-file|download-file|list-files|search-files|delete-file|stat-file|mkdir|move-file|git-status|git-diff|git-export-patch|git-branch|git-commit|git-pull|git-push|smoke> [args]")}}}}}b(Pe,"runSandboxCommand");export{Pe as runSandboxCommand};
2
+ import{a as N,b as E,c as P,d as J,e as j,f as S,g as O,h as C,i as R,j as k,k as B,l as q,m as U,n as L,o as l}from"./chunk-V4ACXLID.js";import{p as v,v as w,w as y}from"./chunk-G2VYRU27.js";import"./chunk-ZVOO7FKM.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{b as I,f,g as h,h as p}from"./chunk-3M53YXEI.js";import{a as b}from"./chunk-FTQLQJQV.js";async function M(r,o,e,i){if(o==="list-files"){let t=i[1];if(!t)throw new Error("usage: sandbox list-files <sandboxId> [--path <path>]");let n=typeof e.path=="string"?e.path.trim():void 0,s=h(e.maxEntries,"max-entries"),a=e.recursive!==void 0?f(e.recursive):void 0,d=await r.listFiles(t,{...n?{path:n}:{},...a!==void 0?{recursive:a}:{},...s!==void 0?{maxEntries:s}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),files:d.files},null,2)),!0}if(o==="upload-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=typeof e.contents=="string"?e.contents:typeof e.content=="string"?e.content:"",a=typeof e.contentsBase64=="string"?e.contentsBase64.trim():typeof e.contentBase64=="string"?e.contentBase64.trim():"";if(!t||!n)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');if(!s&&!a)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');let d=a?await r.uploadFileBase64(t,n,a):await r.uploadFile(t,n,s);return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file},null,2)),!0}if(o==="download-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=Number(e["offset-bytes"]),a=Number(e["max-bytes"]);if(!t||!n)throw new Error("usage: sandbox download-file <sandboxId> --path <path>");let d=await r.downloadFileResponse(t,{path:n,...Number.isFinite(s)?{offsetBytes:s}:{},...Number.isFinite(a)?{maxBytes:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file,contents:Buffer.from(d.file.contentsBase64,"base64").toString("utf-8")},null,2)),!0}if(o==="search-files"){let t=i[1],n=typeof e.query=="string"?e.query.trim():"";if(!t||!n)throw new Error("usage: sandbox search-files <sandboxId> --query <text> [--path <path>]");let s=typeof e.path=="string"?e.path.trim():void 0,a=h(e.maxResults,"max-results"),d=await r.searchFiles(t,{query:n,...s?{path:s}:{},...a!==void 0?{maxResults:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),matches:d.matches},null,2)),!0}if(o==="delete-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox delete-file <sandboxId> --path <path> [--recursive]");let s=await r.deleteFile(t,n,{recursive:f(e.recursive)});return console.log(JSON.stringify({sandbox:l(s.sandbox),deleted:s.deleted},null,2)),!0}if(o==="stat-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox stat-file <sandboxId> --path <path>");let s=await r.statFile(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),file:s.file},null,2)),!0}if(o==="mkdir"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox mkdir <sandboxId> --path <path> [--recursive false]");let s=await r.mkdir(t,{path:n,recursive:e.recursive!==void 0?f(e.recursive):void 0});return console.log(JSON.stringify({sandbox:l(s.sandbox),directory:s.directory},null,2)),!0}if(o==="move-file"){let t=i[1],n=typeof e.fromPath=="string"?e.fromPath.trim():"",s=typeof e.toPath=="string"?e.toPath.trim():"";if(!t||!n||!s)throw new Error("usage: sandbox move-file <sandboxId> --from-path <path> --to-path <path> [--overwrite]");let a=await r.moveFile(t,{fromPath:n,toPath:s,overwrite:f(e.overwrite)});return console.log(JSON.stringify({sandbox:l(a.sandbox),moved:a.moved,file:a.file},null,2)),!0}return!1}b(M,"handleSandboxFilesCommand");async function T(r,o,e,i){if(o==="git-status"){let t=i[1];if(!t)throw new Error("usage: sandbox git-status <sandboxId>");let n=await r.gitStatus(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),status:n.status},null,2)),!0}if(o==="git-diff"){let t=i[1];if(!t)throw new Error("usage: sandbox git-diff <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitDiff(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),diff:s.diff},null,2)),!0}if(o==="git-export-patch"){let t=i[1];if(!t)throw new Error("usage: sandbox git-export-patch <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitExportPatch(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),patch:s.patch},null,2)),!0}if(o==="git-branch"){let t=i[1],n=typeof e.branch=="string"?e.branch.trim():"",s=typeof e.startPoint=="string"&&e.startPoint.trim()?e.startPoint.trim():void 0;if(!t||!n)throw new Error("usage: sandbox git-branch <sandboxId> --branch <name> [--create] [--start-point <ref>]");let a=await r.gitBranch(t,{branch:n,create:f(e.create),...s?{startPoint:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),branch:a.branch},null,2)),!0}if(o==="git-commit"){let t=i[1],n=typeof e.message=="string"?e.message.trim():"",s=f(e.all),d=(typeof e.paths=="string"?e.paths:typeof e.path=="string"?e.path:"").split(",").map(g=>g.trim()).filter(Boolean);if(!t||!n||!s&&d.length===0)throw new Error('usage: sandbox git-commit <sandboxId> --message "..." [--all|--paths <csv>]');let c=await r.gitCommit(t,{message:n,...s?{all:!0}:{paths:d}});return console.log(JSON.stringify({sandbox:l(c.sandbox),commit:c.commit},null,2)),!0}if(o==="git-pull"){let t=i[1];if(!t)throw new Error("usage: sandbox git-pull <sandboxId> [--remote origin] [--branch main] [--rebase|--ff-only false]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPull(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.rebase!==void 0?{rebase:f(e.rebase)}:{},...e.ffOnly!==void 0?{ffOnly:f(e.ffOnly)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pull:a.pull},null,2)),!0}if(o==="git-push"){let t=i[1];if(!t)throw new Error("usage: sandbox git-push <sandboxId> [--remote origin] [--branch main] [--set-upstream] [--force-with-lease]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPush(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.setUpstream!==void 0?{setUpstream:f(e.setUpstream)}:{},...e.forceWithLease!==void 0?{forceWithLease:f(e.forceWithLease)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),push:a.push},null,2)),!0}return!1}b(T,"handleSandboxGitCommand");async function F(r,o,e,i){if(o==="process-start"){let t=i[1],n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox process-start <sandboxId> --command <command>");let s=p(e.timeoutSeconds,"timeout-seconds"),a=await r.startProcess(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process},null,2)),!0}if(o==="process-list"){let t=i[1];if(!t)throw new Error("usage: sandbox process-list <sandboxId>");let n=await r.listProcesses(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),processes:n.processes},null,2)),!0}if(o==="process-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-get <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getProcess(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="process-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stop <sandboxId> <processId>");let s=await r.stopProcess(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),process:s.process},null,2)),!0}if(o==="process-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stream <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamProcessOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}if(o==="pty-start"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-start <sandboxId> [--command <command>]");let n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" "),s=p(e.timeoutSeconds,"timeout-seconds"),a=p(e.rows,"rows"),d=p(e.cols,"cols"),c=await r.startPty(t,{...n.trim()?{command:n.trim()}:{},...s!==void 0?{timeoutSeconds:s}:{},...a!==void 0?{rows:a}:{},...d!==void 0?{cols:d}:{}});return console.log(JSON.stringify({sandbox:l(c.sandbox),pty:c.pty},null,2)),!0}if(o==="pty-list"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-list <sandboxId>");let n=await r.listPtys(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),ptys:n.ptys},null,2)),!0}if(o==="pty-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-get <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getPty(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pty:a.pty,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="pty-write"){let t=i[1],n=i[2],s=typeof e.inputBase64=="string"?e.inputBase64.trim():"",a=(typeof e.input=="string"?e.input:null)||i.slice(3).join(" ");if(!t||!n||!s&&!a)throw new Error("usage: sandbox pty-write <sandboxId> <ptyId> --input <text>");let d=await r.writePtyInput(t,n,s?{dataBase64:s}:a);return console.log(JSON.stringify({sandbox:l(d.sandbox),pty:d.pty},null,2)),!0}if(o==="pty-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stop <sandboxId> <ptyId>");let s=await r.stopPty(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),pty:s.pty},null,2)),!0}if(o==="pty-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stream <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamPtyOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}return!1}b(F,"handleSandboxProcessCommand");async function A(r,o,e,i){if(o==="replays"||o==="replay-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=await r.listReplays({...t?{teamId:t}:{},...n?{projectId:n}:{}});if(f(e.json))return console.log(JSON.stringify(s,null,2)),!0;if(s.replays.length===0)return console.log("no sandbox replays found"),!0;for(let a of s.replays)console.log(O(a));return!0}if(o==="replay-start"||o==="start-replay"){let t=await r.startReplay(k(e));return console.log(JSON.stringify(t,null,2)),!0}if(o==="replay-get"||o==="get-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-get <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-logs"||o==="logs-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-logs <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayLogs(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let d of a.logs)console.log(d);return!0}if(o==="replay-artifacts"||o==="artifacts-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-artifacts <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayArtifacts(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify({replayId:a.replayId,artifacts:a.artifacts.map(C)},null,2)),!0}if(o==="replay-cancel"||o==="cancel-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-cancel <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.cancelReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-watch"||o==="watch-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-watch <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=p(e.intervalMs,"interval-ms")??5e3,d=p(e.timeoutMs,"timeout-ms")??900*1e3,c=Date.now(),g=new Set;for(;Date.now()-c<=d;){let u=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let m of u.replay.logs)g.has(m)||(g.add(m),console.log(m));if(u.replay.state==="succeeded"||u.replay.state==="failed"||u.replay.state==="canceled"){if(console.log(O(u.replay)),u.replay.state!=="succeeded")throw new Error(`sandbox replay ${u.replay.state}: ${u.replay.error??"no error"}`);return!0}await new Promise(m=>setTimeout(m,a))}throw new Error(`sandbox replay did not finish within ${d}ms`)}return!1}b(A,"handleSandboxReplayCommand");async function V(r,o,e,i){if(o==="runtime-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=typeof e.agentId=="string"?e.agentId.trim():"",a=await r.listSandboxRuntimes({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});return console.log(JSON.stringify({runtimes:a},null,2)),!0}if(o==="runtime-get"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-get <runtimeId>");let n=await r.getSandboxRuntime(t);return console.log(JSON.stringify({runtime:n},null,2)),!0}if(o==="runtime-events"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-events <runtimeId>");return console.log(JSON.stringify(await r.listSandboxRuntimeEvents(t),null,2)),!0}if(o==="runtime-status"){let t=i[1]?.trim(),n=typeof e.status=="string"&&e.status.trim()?e.status.trim():"",s=Number(e.expectedVersion),a=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0;if(!t||!n||!Number.isInteger(s))throw new Error("usage: sandbox runtime-status <runtimeId> --status <status> --expected-version <n>");let d=await r.updateSandboxRuntimeStatus(t,{status:n,expectedVersion:s,...a?{summary:a}:{}});return console.log(JSON.stringify({runtime:d},null,2)),!0}if(o==="runtime-event"){let t=i[1]?.trim(),n=typeof e.type=="string"&&e.type.trim()?e.type.trim():"",s=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,a=typeof e.payload=="string"&&e.payload.trim()?I(e.payload,"payload"):void 0,d=typeof e.lifecycleHint=="string"&&e.lifecycleHint.trim()?I(e.lifecycleHint,"lifecycle-hint"):void 0;if(!t||!n)throw new Error("usage: sandbox runtime-event <runtimeId> --type <eventType> [--summary <text>] [--payload <json>] [--lifecycle-hint <json>]");return console.log(JSON.stringify(await r.emitSandboxRuntimeEvent(t,{type:n,...s?{summary:s}:{},...a?{payload:a}:{},...d?{lifecycleHint:d}:{}}),null,2)),!0}if(o==="runtime-preserve-source"||o==="runtime-preserve"){let t=i[1]?.trim(),n=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():"",s=typeof e.sandboxId=="string"&&e.sandboxId.trim()?e.sandboxId.trim():"",a=typeof e.message=="string"&&e.message.trim()?e.message.trim():"";if(!t)throw new Error("usage: sandbox runtime-preserve-source <runtimeId> [--team-id <id>] [--sandbox-id <id>] [--message <text>]");return console.log(JSON.stringify(await r.runtimes.preserveSource(t,{...s?{sandboxId:s}:{},...a?{message:a}:{}},{...n?{teamId:n}:{}}),null,2)),!0}return!1}b(V,"handleSandboxRuntimeCommand");async function $(r,o,e,i){if(o==="secrets"||o==="secret-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=await r.listSecrets({...t?{teamId:t}:{}});if(f(e.json))return console.log(JSON.stringify({secrets:n.map(y)},null,2)),!0;if(n.length===0)return console.log("no sandbox secrets found"),!0;for(let s of n)console.log(`${s.name} ${s.status} v${s.currentVersion??"current"} ${s.secretRef}`);return!0}if(o==="secret-create"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.name=="string"?e.name.trim():"",s=typeof e.description=="string"&&e.description.trim()?e.description.trim():void 0,a=e.scope==="project"||e.scope==="template"||e.scope==="team"?e.scope:void 0;if(!n)throw new Error("usage: sandbox secret-create --name <ENV_NAME> [--team-id <id>] [--stdin]");let d=await w(e,`Value for ${n}`),c=await r.createSecret({...t?{teamId:t}:{},name:n,value:d,...s?{description:s}:{},...a?{scope:a}:{}});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-rotate"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox secret-rotate <secretId> [--team-id <id>] [--stdin]");let s=await w(e,"New secret value"),a=await r.rotateSecret(t,{...n?{teamId:n}:{},value:s});return console.log(JSON.stringify({secret:y(a)},null,2)),!0}if(o==="secret-attach"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.envName=="string"?e.envName.trim():"",a=e.targetType==="sandbox"||e.targetType==="template"||e.targetType==="project"||e.targetType==="agent"||e.targetType==="replay"?e.targetType:void 0,d=typeof e.targetId=="string"?e.targetId.trim():"";if(!t||!s||!a||!d)throw new Error("usage: sandbox secret-attach <secretId> --env-name <ENV_NAME> --target-type sandbox|project|agent|template|replay --target-id <id>");let c=await r.attachSecret(t,{...n?{teamId:n}:{},envName:s,targetType:a,targetId:d});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-revoke"||o==="secret-delete"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error(`usage: sandbox ${o} <secretId> [--team-id <id>]`);let s=o==="secret-revoke"?await r.revokeSecret(t,{...n?{teamId:n}:{}}):await r.deleteSecret(t,{...n?{teamId:n}:{}});return console.log(JSON.stringify({secret:y(s)},null,2)),!0}return!1}b($,"handleSandboxSecretsCommand");async function H(r,o,e,i){if(o==="published-snapshot-builds"||o==="published-snapshot-build-list"||o==="template-builds"||o==="template-build-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox published-snapshot-builds --team-id <id>");let n=await r.listPublishedSnapshotBuilds({teamId:t});if(f(e.json))return console.log(JSON.stringify({builds:n},null,2)),!0;if(n.length===0)return console.log("no published snapshot builds found"),!0;for(let s of n)console.log(S(s));return!0}if(o==="published-snapshot-build-create"||o==="create-published-snapshot-build"||o==="template-build-create"||o==="create-template-build"){let t=await r.createPublishedSnapshotBuild(U(e));return console.log(JSON.stringify({build:t},null,2)),!0}if(o==="published-snapshot-build-get"||o==="get-published-snapshot-build"||o==="template-build-get"||o==="get-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-get <buildId>");let n=await r.getPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-logs"||o==="published-snapshot-build-log"||o==="template-build-logs"||o==="template-build-log"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-logs <buildId>");let n=await r.getPublishedSnapshotBuildLogs(t);if(f(e.json))return console.log(JSON.stringify(n,null,2)),!0;for(let s of n.logs)console.log(s);return!0}if(o==="published-snapshot-build-cancel"||o==="cancel-published-snapshot-build"||o==="template-build-cancel"||o==="cancel-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-cancel <buildId>");let n=await r.cancelPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-watch"||o==="watch-published-snapshot-build"||o==="template-build-watch"||o==="watch-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-watch <buildId>");let n=p(e.intervalMs,"interval-ms")??5e3,s=p(e.timeoutMs,"timeout-ms")??900*1e3,a=Date.now(),d=new Set;for(;Date.now()-a<=s;){let[c,g]=await Promise.all([r.getPublishedSnapshotBuild(t),r.getPublishedSnapshotBuildLogs(t)]);for(let u of g.logs)d.has(u)||(d.add(u),console.log(u));if(c.status==="succeeded"||c.status==="failed"||c.status==="cancelled"){if(console.log(S(c)),c.status!=="succeeded")throw new Error(`published snapshot build ${c.status}: ${c.error??"no error"}`);return!0}await new Promise(u=>setTimeout(u,n))}throw new Error(`published snapshot build did not finish within ${s}ms`)}return!1}b(H,"handleSandboxTemplateBuildsCommand");function G(r){return f(r.async)||f(r.respondAsync)}b(G,"parseSandboxAsyncOption");async function Pe(r,o){let e=o[0]||"list",i=await v(r);if(e==="list"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.list({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(a.length===0){console.log("no sandboxes found");return}for(let d of a)console.log(P(d));return}if(e==="mcp-config"||e==="mcp-url"){let t=i.mcpServerConfig();console.log(JSON.stringify({...t,headers:{"openpond-api-key":"set OPENPOND_API_KEY or use your saved openpond profile"}},null,2));return}if(!await V(i,e,r,o)){if(e==="pricing"){let t=await i.pricing();console.log(JSON.stringify(t,null,2));return}if(e==="costs"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.costs({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(f(r.summary)){console.log(JSON.stringify({costs:{teamId:a.costs.teamId,ownerUserId:a.costs.ownerUserId,generatedAt:a.costs.generatedAt,summary:a.costs.summary,lineItems:a.costs.lineItems,tiers:a.costs.pricing.tiers.map(d=>({key:d.key,resources:d.resources,keepRunningEstimate:d.keepRunningEstimate}))}},null,2));return}console.log(JSON.stringify(a,null,2));return}if(!await $(i,e,r,o)){if(e==="snapshots"||e==="snapshot-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",d=typeof r.tag=="string"?r.tag.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"",g=typeof r.replayState=="string"?r.replayState.trim():"",u=await i.snapshotCatalog({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{q:a}:{},...d?{tag:d}:{},...c?{useCase:c}:{},...g==="draft"||g==="validated"||g==="published"?{replayState:g}:{}});if(u.snapshots.length===0){console.log("no sandbox snapshots found");return}for(let m of u.snapshots)console.log(J(m));return}if(e==="published-snapshots"||e==="published-snapshot-catalog"||e==="templates"||e==="template-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",a=typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.tag=="string"?r.tag.trim():"",g=typeof r.useCase=="string"?r.useCase.trim():"",u=await i.publishedSnapshots({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{q:s}:{},...a?{name:a}:{},...d?{version:d}:{},...c?{tag:c}:{},...g?{useCase:g}:{}});if(u.publishedSnapshots.length===0){console.log("no published snapshots found");return}for(let m of u.publishedSnapshots)console.log(j(m));return}if(!(await H(i,e,r,o)||await A(i,e,r,o))){if(e==="run-published-snapshot"||e==="published-snapshot-run"||e==="template-launch"||e==="launch-template"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.snapshotId=="string"&&r.snapshotId.trim()?r.snapshotId.trim():typeof r.snapshot=="string"&&r.snapshot.trim()?r.snapshot.trim():"",a=typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof o[1]=="string"&&o[1].trim()?o[1].trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"";if(!s&&!a&&!c)throw new Error("usage: sandbox run-published-snapshot [--snapshot-id <id>|--name <name>|--use-case <id>] [--version <v>]");let g=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",u=await i.runPublishedSnapshot({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{snapshotId:s}:{},...a?{templateName:a}:{},...d?{version:d}:{},...c?{useCase:c}:{},...g?{budget:{maxUsd:g}}:{},metadata:{source:"openpond-code-published-snapshot-run"}});console.log(JSON.stringify(u,null,2));return}if(e==="snapshot-fork"||e==="fork-snapshot"){let t=o[1];if(!t)throw new Error("snapshot-fork requires <snapshotId>");let n=typeof r.teamId=="string"?r.teamId.trim():"",s=typeof r.projectId=="string"?r.projectId.trim():"",a=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",d=await i.forkSnapshot(t,{...n?{teamId:n}:{},...s?{projectId:s}:{},...a?{budget:{maxUsd:a}}:{},metadata:{source:"openpond-code-snapshot-fork",templateSnapshotId:t}});console.log(JSON.stringify(d,null,2));return}if(e==="snapshot-create"||e==="create-snapshot"){let t=o[1];if(!t)throw new Error("usage: sandbox snapshot-create <sandboxId> --name <name>");let n=await i.createSnapshot(t,L(r));console.log(JSON.stringify(n,null,2));return}if(e==="snapshot-validate"||e==="validate-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-validate requires <sandboxId> <snapshotId>");let s=R(r.cleanup),a=await i.validateSnapshot(t,n,{...s?{cleanup:s}:{}});console.log(JSON.stringify(a,null,2));return}if(e==="snapshot-publish"||e==="publish-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-publish requires <sandboxId> <snapshotId>");let s=await i.publishSnapshot(t,n);console.log(JSON.stringify(s,null,2));return}if(e==="integration-connections"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=r.status==="active"||r.status==="revoked"||r.status==="error"||r.status==="all"?r.status:void 0,d=await i.integrationConnections({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{status:a}:{}});console.log(JSON.stringify(d,null,2));return}if(e==="create"){let t=await N(i,B(r));console.log(JSON.stringify({sandbox:l(t.sandbox),...t.runtime?{runtime:t.runtime}:{}},null,2));return}if(e==="exec"){let t=o[1],n=(typeof r.command=="string"?r.command:null)||o.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox exec <sandboxId> --command <command>");let s=p(r.timeoutSeconds,"timeout-seconds"),a=await i.exec(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});console.log(JSON.stringify({sandbox:l(a.sandbox),command:a.command},null,2));return}if(e==="port"||e==="preview"){let t=o[1],n=p(r.port,"port");if(!t||n===void 0)throw new Error("usage: sandbox port <sandboxId> --port <port>");let s=typeof r.label=="string"?r.label:void 0,a=typeof r.access=="string"?r.access.trim():"";if(a&&a!=="private"&&a!=="public")throw new Error("sandbox port --access must be private or public");let d=a==="public"?"public":"private",c=typeof r.domain=="string"?r.domain.trim():"",g=typeof r.authToken=="string"?r.authToken:"",u=typeof r.authHeader=="string"?r.authHeader.trim():"",m=typeof r.authHeaderValue=="string"?r.authHeaderValue:"";if(g&&(u||m))throw new Error("sandbox port auth options must use either --auth-token or --auth-header with --auth-header-value");if(u&&!m||!u&&m)throw new Error("sandbox port custom header auth requires both --auth-header and --auth-header-value");let x=await i.openPort(t,{port:n,...s?{label:s}:{},access:d,...r["auto-start"]||r.autoStart?{autoStart:!0}:{},...c?{customDomain:c}:{},...g?{authPolicy:{mode:"bearer",token:g}}:{},...u&&m?{authPolicy:{mode:"header",headerName:u,headerValue:m}}:{}});console.log(JSON.stringify(x.preview,null,2));return}if(e==="stop"){let t=o[1];if(!t)throw new Error("usage: sandbox stop <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.stop(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n.sandbox),receipt:n.receipt},null,2));return}if(e==="start"){let t=o[1];if(!t)throw new Error("usage: sandbox start <sandboxId>");let n=await i.start(t);console.log(JSON.stringify({sandbox:await E(i,n.sandbox),receipt:n.receipt},null,2));return}if(e==="delete"){let t=o[1];if(!t)throw new Error("usage: sandbox delete <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.delete(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n)},null,2));return}if(e==="receipts"){let t=o[1];if(!t)throw new Error("usage: sandbox receipts <sandboxId>");let n=await i.receipts(t);console.log(JSON.stringify({receipts:n},null,2));return}if(e==="logs"){let t=o[1];if(!t)throw new Error("usage: sandbox logs <sandboxId>");let n=await i.logs(t);for(let s of n)console.log(s);return}if(!(await F(i,e,r,o)||await M(i,e,r,o)||await T(i,e,r,o))){if(e==="billing"){let t=o[1];if(!t)throw new Error("usage: sandbox billing <sandboxId>");let n=await i.billing(t);console.log(JSON.stringify({sandbox:l(n.sandbox),billing:n.billing},null,2));return}if(e==="integration-leases"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-leases <sandboxId>");let n=await i.integrationLeases(t);console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-attach"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-attach <sandboxId> --integration-connection <id> --integration-capabilities <csv>");let n=await i.attachIntegrationConnection(t,q(r));console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-remove"){let t=o[1],n=typeof r.leaseId=="string"?r.leaseId.trim():"";if(!t||!n)throw new Error("usage: sandbox integration-remove <sandboxId> --lease-id <id>");let s=await i.removeIntegrationLease(t,n);console.log(JSON.stringify({sandbox:l(s.sandbox),integrationLeases:s.integrationLeases},null,2));return}if(e==="smoke"){let t=typeof r.repo=="string"?r.repo.trim():void 0,n=typeof r.budgetUsd=="string"?r.budgetUsd.trim():typeof r.budget=="string"?r.budget.trim():void 0,s=f(r.keep),a=r.preview!==void 0?f(r.preview):!f(r.noPreview),d=f(r.snapshot),c=f(r.fork),g={...t?{repo:t}:{},...n?{budgetUsd:n}:{},keep:s,preview:a,snapshot:d,fork:c};typeof r.expectedMppMode=="string"&&r.expectedMppMode.trim()&&(g.expectedMppMode=r.expectedMppMode.trim());let u=h(r.cpu,"cpu"),m=h(r.memoryGb,"memory-gb"),x=h(r.diskGb,"disk-gb");u!==void 0&&(g.cpu=u),m!==void 0&&(g.memoryGb=m),x!==void 0&&(g.diskGb=x);let z=await i.smoke(g);console.log(JSON.stringify(z,null,2));return}throw new Error("usage: sandbox <list|mcp-config|runtime-list|runtime-get|runtime-events|runtime-status|runtime-event|runtime-preserve-source|pricing|costs|secrets|secret-create|secret-rotate|secret-attach|secret-revoke|secret-delete|snapshots|published-snapshots|run-published-snapshot|snapshot-fork|snapshot-validate|snapshot-publish|create|exec|port|preview|stop|start|delete|receipts|logs|billing|process-start|process-list|process-get|process-stop|process-stream|pty-start|pty-list|pty-get|pty-write|pty-stop|pty-stream|upload-file|download-file|list-files|search-files|delete-file|stat-file|mkdir|move-file|git-status|git-diff|git-export-patch|git-branch|git-commit|git-pull|git-push|smoke> [args]")}}}}}b(Pe,"runSandboxCommand");export{Pe as runSandboxCommand};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ee,o as Re}from"./chunk-V4ACXLID.js";import{m as he}from"./chunk-K4ZKAHLG.js";import{A as Se,c as se,d as ie,e as de,g as ce,h as le,n as me,p as N,q as fe,r as be,u as xe,y as g,z as ge}from"./chunk-G2VYRU27.js";import{f as ue,h as pe}from"./chunk-ZVOO7FKM.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import{Z as oe,l as ae}from"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-3A7HZJNE.js";import{c as f,d as we,e as Te,h as O,k as C,q as v,r as ye,s as U,t as Pe,u as ve}from"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-JTQDNX2J.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-QLZ67Y6C.js";import{a as M,f as h,h as R}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as P,existsSync as kt}from"node:fs";import b from"node:path";import{Buffer as ht}from"node:buffer";import{promises as y}from"node:fs";import w from"node:path";import{Buffer as Ve}from"node:buffer";import{promises as j}from"node:fs";import S from"node:path";async function q(e,t,n,r){let a=Ie(n,r);if(!a)return[];let o=Oe(n,r),s=typeof r.projectId=="string"&&r.projectId.trim()?r.projectId.trim():typeof r.runtimeProjectId=="string"?r.runtimeProjectId.trim():"",d=typeof r.teamId=="string"?r.teamId.trim():"",c=[];for(let l of a.schedules){let u=Ce({manifest:n,schedule:l,override:o.get(l.name),mode:a.mode,sourceSandboxId:t,teamId:d,projectId:s}),m=await e.createSchedule(u);c.push({id:m.schedule.id,name:m.schedule.name,enabled:m.schedule.enabled,scheduleType:m.schedule.scheduleType,scheduleExpression:m.schedule.scheduleExpression,syncStatus:m.schedule.syncStatus,awsScheduleArn:m.schedule.awsScheduleArn??null,target:m.schedule.target})}return c}i(q,"createSandboxTemplateStartSchedules");function Ie(e,t){let n=t.enableSchedules??t.enableSchedule,r=t.disableSchedules??t.disableSchedule;if(n!==void 0&&r!==void 0)throw new Error("pass only one of --enable-schedules or --disable-schedules");let a=null,o;if(n!==void 0)a="enabled",o=n;else if(r!==void 0)a="disabled",o=r;else if(t.schedules!==void 0){o=t.schedules;let c=typeof t.scheduleMode=="string"?t.scheduleMode.trim().toLowerCase():"disabled";if(c==="none")return null;if(c!=="enabled"&&c!=="disabled")throw new Error("--schedule-mode must be enabled, disabled, or none");a=c}if(!a)return null;if(e.schedules.length===0)return{mode:a,schedules:[]};let s=ke(o,e),d=s===null?e.schedules:e.schedules.filter(c=>s.has(c.name));return{mode:a,schedules:d}}i(Ie,"resolveSandboxTemplateStartScheduleSelection");function ke(e,t){if(e===void 0||e===!0)return null;let n=String(e).trim();if(!n||n==="true"||n.toLowerCase()==="all")return null;if(n.toLowerCase()==="none")return new Set;let r=new Set(t.schedules.map(o=>o.name)),a=new Set(n.split(",").map(o=>o.trim()).filter(Boolean));for(let o of a)if(!r.has(o))throw new Error(`manifest schedule not found: ${o}`);return a}i(ke,"parseSandboxTemplateScheduleNameSelection");function Oe(e,t){let n=typeof t.scheduleOverrides=="string"?t.scheduleOverrides:typeof t.scheduleOverride=="string"?t.scheduleOverride:"";if(!n.trim())return new Map;let r=M(n,"schedule-overrides");if(!r||typeof r!="object"||Array.isArray(r))throw new Error("schedule-overrides must be a JSON object keyed by schedule name");let a=new Set(e.schedules.map(s=>s.name)),o=new Map;for(let[s,d]of Object.entries(r)){if(!a.has(s))throw new Error(`schedule override target does not exist: ${s}`);if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`schedule override for ${s} must be an object`);o.set(s,d)}return o}i(Oe,"parseSandboxTemplateScheduleOverrides");function Ce(e){let t=Me(e.schedule,e.override),n=Ne(t);return{sourceSandboxId:e.sourceSandboxId,...e.teamId?{teamId:e.teamId}:{},...e.projectId?{projectId:e.projectId}:{},name:t.name,...t.description?{description:t.description}:{},...n,...t.timezone?{timezone:t.timezone}:{},enabled:typeof e.override?.enabled=="boolean"?e.override.enabled:e.mode==="enabled",...t.startAt?{startAt:t.startAt}:{},...t.endAt?{endAt:t.endAt}:{},...t.maxRuns!==void 0?{maxRuns:t.maxRuns}:{},runtimePolicy:t.runtimePolicy,target:Ae(e.manifest,t),...t.budget?{budget:t.budget}:{},...t.resources?{resources:t.resources}:{},...t.quotas?{quotas:t.quotas}:{},...t.lifecycle?{lifecycle:t.lifecycle}:{},...t.retentionPolicy?{retentionPolicy:t.retentionPolicy}:{},...t.env?{env:t.env}:{},...t.integrationLeases?{integrationLeases:t.integrationLeases}:{},metadata:{...t.metadata??{},manifestScheduleName:t.name,source:"openpond-code-sandbox-template-start"},managementSource:"openpond.yaml",manifestPath:f}}i(Ce,"buildSandboxTemplateStartScheduleInput");function Me(e,t){return t?{...e,...t,target:e.target||t.target?{...e.target??{},...t.target??{}}:void 0,metadata:e.metadata||t.metadata?{...e.metadata??{},...t.metadata??{}}:void 0}:e}i(Me,"mergeSandboxTemplateScheduleOverride");function Ne(e){return e.scheduleExpression?{scheduleType:e.scheduleType??"cron",scheduleExpression:e.scheduleExpression}:e.rate?{scheduleType:"rate",scheduleExpression:/^rate\(/i.test(e.rate)?e.rate:`rate(${e.rate})`}:e.once?{scheduleType:"once",scheduleExpression:/^at\(/i.test(e.once)?e.once:`at(${e.once})`}:{scheduleType:"cron",scheduleExpression:e.cron??""}}i(Ne,"sandboxTemplateScheduleExpression");function Ae(e,t){let n=t.command??t.target?.command??null;if(n)return{kind:"command",command:n,requiresStart:t.requiresStart??t.target?.requiresStart??!1};let r=t.target?.kind??"action";if(r==="start")return{kind:"command",command:e.start.command,requiresStart:t.requiresStart??t.target?.requiresStart??e.start.requiresStart??!1};if(r==="service"){let s=t.target?.name??"",d=e.services.find(c=>c.name===s);if(!d)throw new Error(`schedule service target does not exist: ${s}`);return{kind:"command",command:d.command,requiresStart:t.requiresStart??t.target?.requiresStart??d.requiresStart??!1}}let a=t.actionName??t.action??t.target?.actionName??(t.target?.kind==="action"?t.target?.name:void 0),o=e.actions.find(s=>s.name===a);if(!o)throw new Error(`schedule action target does not exist: ${a??""}`);return{kind:"command",command:o.command,requiresStart:t.requiresStart??t.target?.requiresStart??o.requiresStart??!1}}i(Ae,"sandboxTemplateScheduleCommandTarget");import{existsSync as Ge}from"node:fs";import We from"node:path";import{stdin as Ke}from"node:process";async function D(e,t,n){let r=typeof t.repo=="string"?t.repo.trim():"";if(r)return A(r);await $e(n);let a=await oe(),o=ue(a),s=pe(a),d=await se(a,o),c=await Se(n,"origin");if(!c){let l=typeof t.teamId=="string"?t.teamId.trim():"",u=await ae(s,d,{name:e.name,description:e.description,repoInit:"empty",...l?{teamId:l}:{}});c=ie(u);let m=await g("git",["remote","add","origin",c],{cwd:n});if(m.code!==0)throw new Error(`git remote add failed: ${m.stderr.trim()||m.stdout.trim()||"unknown error"}`)}if(le(c),await Fe(n,t),!h(t.noPush)){let l=await je(n,t);await Be(n,c,l,d,t)}return A(c)}i(D,"resolveSandboxTemplateStartRepo");async function $e(e){let t=We.join(e,".git");if(Ge(t))return;let n=await g("git",["init"],{cwd:e});if(n.code!==0)throw new Error(`git init failed: ${n.stderr.trim()||n.stdout.trim()||"unknown error"}`)}i($e,"ensureGitRepository");async function Fe(e,t){let n=await g("git",["status","--porcelain"],{cwd:e});if(n.code!==0)throw new Error(`git status failed: ${n.stderr.trim()||n.stdout.trim()||"unknown error"}`);let a=(await g("git",["rev-parse","--verify","HEAD"],{cwd:e})).code===0,o=n.stdout.trim().length>0;if(!o&&a)return;if(!(h(t.commit)||h(t.yes)||(Ke.isTTY?await me(a?"Commit local changes before starting the sandbox?":"Create the initial git commit before starting the sandbox?",!a):!1))){if(!a)throw new Error("local repository has no commits; pass --commit or commit before starting");o&&console.warn("warning: uncommitted local changes will not be included in the sandbox");return}let d=await g("git",["add","-A"],{cwd:e});if(d.code!==0)throw new Error(`git add failed: ${d.stderr.trim()||d.stdout.trim()||"unknown error"}`);let c=typeof t.commitMessage=="string"&&t.commitMessage.trim()?t.commitMessage.trim():`start ${f} sandbox`,l=await g("git",["commit","-m",c],{cwd:e});if(l.code!==0){let u=l.stderr.trim()||l.stdout.trim();if(u.includes("nothing to commit")&&a)return;throw new Error(`git commit failed: ${u||"unknown error"}`)}}i(Fe,"ensureGitCommitForSandboxTemplateStart");async function je(e,t){let r=(typeof t.branch=="string"?t.branch.trim():"")||await he(e);if(!r)throw new Error("unable to resolve git branch; pass --branch");return r}i(je,"resolveSandboxTemplateStartBranch");async function Be(e,t,n,r,a){let o;try{o=de(t,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let s=h(a.keepTokenRemote)||h(a.token)||h(a.setRemoteToken),d=t.includes("x-access-token:"),c=!s&&!d?t:null,l=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!d){let m=await g("git",["remote","set-url","origin",o],{cwd:e});if(m.code!==0)throw new Error(`git remote set-url failed: ${ce(m.stderr.trim()||m.stdout.trim()||"unknown error")}`)}if((await g("git",["push","-u","origin",n],{cwd:e,inherit:!0})).code!==0)throw new Error("git push failed")}finally{c&&await g("git",["remote","set-url","origin",c],{cwd:e}).catch(()=>null),l===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=l}}i(Be,"pushGitBranchForSandboxTemplateStart");function $(e){return A(e).replace(/\.git$/,"")}i($,"normalizeSandboxTemplateRepoIdentity");function A(e){let t=new URL(e);t.username="",t.password="";let n=t.toString();return n.endsWith(".git")?n:`${n.replace(/\/$/,"")}.git`}i(A,"normalizeSandboxTemplateRepoUrl");async function _e(e){let t=L(e),n=S.dirname(t),r=await j.readFile(t,"utf8"),a=O(r);if(!a.ok){console.error(C(a.diagnostics)),process.exitCode=1;return}let o=a.manifest,s=G(o,e),d=await B(o,e,n),c=await D(o,e,n),l=await N(e),u=Ye(o,e,c),m=await Qe(l,u,c);await tt(l,m.id);let p=await ut(l,m.id,o,e),x=await V(l,m.id,d.uploadRequests),T={...d.scalars,..._(x,d.uploadRequests)},I=await X(l,m.id,s,T,bt(m)),k=await St(l,m.id,s.ports),E=await q(l,m.id,o,e);console.log(JSON.stringify({ok:!0,file:t,repo:c,executable:{kind:s.kind,name:s.name,command:s.command},sandbox:Re(m),setupCommands:p,uploadedFiles:x,input:T,execution:I,previews:k,schedules:E,expectedArtifacts:s.artifactPaths},null,2))}i(_e,"runSandboxTemplateStart");function G(e,t){let n=v(e),r=typeof t.action=="string"?t.action.trim():"",a=typeof t.service=="string"?t.service.trim():"",o=typeof t.target=="string"?t.target.trim():"",s=typeof t.entrypoint=="string"?t.entrypoint.trim():"",d=r||a||o||s||"start",c=r?"action":a?"service":"",l=n.find(u=>u.name===d&&(!c||u.kind===c));if(!l)throw new Error(`manifest executable not found: ${d}. Available: ${n.map(u=>`${u.kind}:${u.name}`).join(", ")}`);return l}i(G,"resolveSandboxTemplateStartExecutable");function Ye(e,t,n){let r=typeof t.budgetUsd=="string"&&t.budgetUsd.trim()?t.budgetUsd.trim():typeof t.budget=="string"&&t.budget.trim()?t.budget.trim():"0.05",a=R(t.maxDurationSeconds,"max-duration-seconds"),o=R(t.idleTimeoutSeconds,"idle-timeout-seconds"),s=typeof t.teamId=="string"?t.teamId.trim():"",d=typeof t.projectId=="string"?t.projectId.trim():"",c=typeof t.runtimeProjectId=="string"?t.runtimeProjectId.trim():"";if(d&&c&&d!==c)throw new Error("project-id and runtime-project-id must match when both are set");let l=d||c,u=typeof t.agentId=="string"?t.agentId.trim():"",m=typeof t.runtimeAgentId=="string"?t.runtimeAgentId.trim():"";if(u&&m&&u!==m)throw new Error("agent-id and runtime-agent-id must match when both are set");let p=u||m,x=fe(t.workflowMode),T=be(t.runtimePromotionPolicy),I=typeof t.runtimeBaseBranch=="string"&&t.runtimeBaseBranch.trim()?t.runtimeBaseBranch.trim():"",k=typeof t.runtimeBaseSha=="string"&&t.runtimeBaseSha.trim()?t.runtimeBaseSha.trim():"",E=typeof t.runtimeId=="string"&&t.runtimeId.trim()?t.runtimeId.trim():"",te=!!(x||T||I||k||E||c||m),ne=xe(e,t),re=Xe(e);return{sandbox:{repo:n,...s?{teamId:s}:{},...l?{projectId:l}:{},...p?{agentId:p}:{},resources:e.resources??{},networkPolicy:{internetEgress:He(e.network.egress)},budget:{maxUsd:r},quotas:{maxSpendUsd:r,...a!==void 0?{maxDurationSeconds:a}:{},...o!==void 0?{idleTimeoutSeconds:o}:{}},...ne.length>0?{env:ne}:{},...re?{workloadSource:re}:{},volumes:e.volumes,metadata:{source:"openpond-code-sandbox-template-start",manifestFile:f,template:{name:e.name,version:e.version,useCase:e.useCase}}},...te&&E?{runtimeId:E}:{},...te&&!E?{sandboxRuntime:{...s?{teamId:s}:{},...x?{workflowMode:x}:{},...l?{projectId:l}:{},...p?{agentId:p}:{},baseBranch:I||"master",...k?{baseSha:k}:{},...T?{promotionPolicy:T}:{}}}:{}}}i(Ye,"buildSandboxTemplateStartCreateInput");function Xe(e){if(e.runtime.image)return{image:e.runtime.image};if(e.runtime.dockerfile)return{dockerfile:e.runtime.dockerfile}}i(Xe,"sandboxWorkloadSourceFromManifest");function He(e){return e==="allow"?"allow":"block"}i(He,"sandboxTemplateInternetEgressPolicy");async function Qe(e,t,n){let r=Date.now();try{return(await Ee(e,t)).sandbox}catch(a){if(!Ze(a))throw a;return console.warn("warning: sandbox create timed out; checking for the created sandbox record"),et(e,t.sandbox,n,r)}}i(Qe,"createSandboxTemplateStartSandbox");function Ze(e){return e instanceof Error&&/\b(504|timed out|timeout)\b/i.test(e.message)}i(Ze,"isLikelySandboxCreateTimeout");async function et(e,t,n,r){let s=Date.now()+72e4,d=$(n),c=t.metadata??{};for(;Date.now()<s;){let u=(await e.list({...t.teamId?{teamId:t.teamId}:{},...t.projectId?{projectId:t.projectId}:{},...t.agentId?{agentId:t.agentId}:{}})).filter(m=>{if(!m.repo||$(m.repo)!==d)return!1;let p=Date.parse(m.createdAt);return!(Number.isFinite(p)&&p<r-3e4||c.source&&m.metadata?.source!==c.source)}).sort((m,p)=>Date.parse(p.createdAt)-Date.parse(m.createdAt))[0];if(u?.state==="running"||u?.state==="stopped")return u;if(u?.state==="error")throw new Error(`sandbox create failed after timeout: ${u.id}
2
+ import{a as Ee,o as Re}from"./chunk-V4ACXLID.js";import{m as he}from"./chunk-MACBJI6D.js";import{A as Se,c as se,d as ie,e as de,g as ce,h as le,n as me,p as N,q as fe,r as be,u as xe,y as g,z as ge}from"./chunk-G2VYRU27.js";import{f as ue,h as pe}from"./chunk-ZVOO7FKM.js";import"./chunk-OGPHXXCD.js";import"./chunk-TWA56GFU.js";import{Z as oe,l as ae}from"./chunk-SS3EG6S2.js";import"./chunk-GLUWATL5.js";import"./chunk-UN3A7GEU.js";import"./chunk-J2S7BOZU.js";import"./chunk-A2PIGBPD.js";import"./chunk-3A7HZJNE.js";import{c as f,d as we,e as Te,h as O,k as C,q as v,r as ye,s as U,t as Pe,u as ve}from"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-SKKAWYCQ.js";import"./chunk-NNLI4OWY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-VL3RGI55.js";import{a as M,f as h,h as R}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as P,existsSync as kt}from"node:fs";import b from"node:path";import{Buffer as ht}from"node:buffer";import{promises as y}from"node:fs";import w from"node:path";import{Buffer as Ve}from"node:buffer";import{promises as j}from"node:fs";import S from"node:path";async function q(e,t,n,r){let a=Ie(n,r);if(!a)return[];let o=Oe(n,r),s=typeof r.projectId=="string"&&r.projectId.trim()?r.projectId.trim():typeof r.runtimeProjectId=="string"?r.runtimeProjectId.trim():"",d=typeof r.teamId=="string"?r.teamId.trim():"",c=[];for(let l of a.schedules){let u=Ce({manifest:n,schedule:l,override:o.get(l.name),mode:a.mode,sourceSandboxId:t,teamId:d,projectId:s}),m=await e.createSchedule(u);c.push({id:m.schedule.id,name:m.schedule.name,enabled:m.schedule.enabled,scheduleType:m.schedule.scheduleType,scheduleExpression:m.schedule.scheduleExpression,syncStatus:m.schedule.syncStatus,awsScheduleArn:m.schedule.awsScheduleArn??null,target:m.schedule.target})}return c}i(q,"createSandboxTemplateStartSchedules");function Ie(e,t){let n=t.enableSchedules??t.enableSchedule,r=t.disableSchedules??t.disableSchedule;if(n!==void 0&&r!==void 0)throw new Error("pass only one of --enable-schedules or --disable-schedules");let a=null,o;if(n!==void 0)a="enabled",o=n;else if(r!==void 0)a="disabled",o=r;else if(t.schedules!==void 0){o=t.schedules;let c=typeof t.scheduleMode=="string"?t.scheduleMode.trim().toLowerCase():"disabled";if(c==="none")return null;if(c!=="enabled"&&c!=="disabled")throw new Error("--schedule-mode must be enabled, disabled, or none");a=c}if(!a)return null;if(e.schedules.length===0)return{mode:a,schedules:[]};let s=ke(o,e),d=s===null?e.schedules:e.schedules.filter(c=>s.has(c.name));return{mode:a,schedules:d}}i(Ie,"resolveSandboxTemplateStartScheduleSelection");function ke(e,t){if(e===void 0||e===!0)return null;let n=String(e).trim();if(!n||n==="true"||n.toLowerCase()==="all")return null;if(n.toLowerCase()==="none")return new Set;let r=new Set(t.schedules.map(o=>o.name)),a=new Set(n.split(",").map(o=>o.trim()).filter(Boolean));for(let o of a)if(!r.has(o))throw new Error(`manifest schedule not found: ${o}`);return a}i(ke,"parseSandboxTemplateScheduleNameSelection");function Oe(e,t){let n=typeof t.scheduleOverrides=="string"?t.scheduleOverrides:typeof t.scheduleOverride=="string"?t.scheduleOverride:"";if(!n.trim())return new Map;let r=M(n,"schedule-overrides");if(!r||typeof r!="object"||Array.isArray(r))throw new Error("schedule-overrides must be a JSON object keyed by schedule name");let a=new Set(e.schedules.map(s=>s.name)),o=new Map;for(let[s,d]of Object.entries(r)){if(!a.has(s))throw new Error(`schedule override target does not exist: ${s}`);if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`schedule override for ${s} must be an object`);o.set(s,d)}return o}i(Oe,"parseSandboxTemplateScheduleOverrides");function Ce(e){let t=Me(e.schedule,e.override),n=Ne(t);return{sourceSandboxId:e.sourceSandboxId,...e.teamId?{teamId:e.teamId}:{},...e.projectId?{projectId:e.projectId}:{},name:t.name,...t.description?{description:t.description}:{},...n,...t.timezone?{timezone:t.timezone}:{},enabled:typeof e.override?.enabled=="boolean"?e.override.enabled:e.mode==="enabled",...t.startAt?{startAt:t.startAt}:{},...t.endAt?{endAt:t.endAt}:{},...t.maxRuns!==void 0?{maxRuns:t.maxRuns}:{},runtimePolicy:t.runtimePolicy,target:Ae(e.manifest,t),...t.budget?{budget:t.budget}:{},...t.resources?{resources:t.resources}:{},...t.quotas?{quotas:t.quotas}:{},...t.lifecycle?{lifecycle:t.lifecycle}:{},...t.retentionPolicy?{retentionPolicy:t.retentionPolicy}:{},...t.env?{env:t.env}:{},...t.integrationLeases?{integrationLeases:t.integrationLeases}:{},metadata:{...t.metadata??{},manifestScheduleName:t.name,source:"openpond-code-sandbox-template-start"},managementSource:"openpond.yaml",manifestPath:f}}i(Ce,"buildSandboxTemplateStartScheduleInput");function Me(e,t){return t?{...e,...t,target:e.target||t.target?{...e.target??{},...t.target??{}}:void 0,metadata:e.metadata||t.metadata?{...e.metadata??{},...t.metadata??{}}:void 0}:e}i(Me,"mergeSandboxTemplateScheduleOverride");function Ne(e){return e.scheduleExpression?{scheduleType:e.scheduleType??"cron",scheduleExpression:e.scheduleExpression}:e.rate?{scheduleType:"rate",scheduleExpression:/^rate\(/i.test(e.rate)?e.rate:`rate(${e.rate})`}:e.once?{scheduleType:"once",scheduleExpression:/^at\(/i.test(e.once)?e.once:`at(${e.once})`}:{scheduleType:"cron",scheduleExpression:e.cron??""}}i(Ne,"sandboxTemplateScheduleExpression");function Ae(e,t){let n=t.command??t.target?.command??null;if(n)return{kind:"command",command:n,requiresStart:t.requiresStart??t.target?.requiresStart??!1};let r=t.target?.kind??"action";if(r==="start")return{kind:"command",command:e.start.command,requiresStart:t.requiresStart??t.target?.requiresStart??e.start.requiresStart??!1};if(r==="service"){let s=t.target?.name??"",d=e.services.find(c=>c.name===s);if(!d)throw new Error(`schedule service target does not exist: ${s}`);return{kind:"command",command:d.command,requiresStart:t.requiresStart??t.target?.requiresStart??d.requiresStart??!1}}let a=t.actionName??t.action??t.target?.actionName??(t.target?.kind==="action"?t.target?.name:void 0),o=e.actions.find(s=>s.name===a);if(!o)throw new Error(`schedule action target does not exist: ${a??""}`);return{kind:"command",command:o.command,requiresStart:t.requiresStart??t.target?.requiresStart??o.requiresStart??!1}}i(Ae,"sandboxTemplateScheduleCommandTarget");import{existsSync as Ge}from"node:fs";import We from"node:path";import{stdin as Ke}from"node:process";async function D(e,t,n){let r=typeof t.repo=="string"?t.repo.trim():"";if(r)return A(r);await $e(n);let a=await oe(),o=ue(a),s=pe(a),d=await se(a,o),c=await Se(n,"origin");if(!c){let l=typeof t.teamId=="string"?t.teamId.trim():"",u=await ae(s,d,{name:e.name,description:e.description,repoInit:"empty",...l?{teamId:l}:{}});c=ie(u);let m=await g("git",["remote","add","origin",c],{cwd:n});if(m.code!==0)throw new Error(`git remote add failed: ${m.stderr.trim()||m.stdout.trim()||"unknown error"}`)}if(le(c),await Fe(n,t),!h(t.noPush)){let l=await je(n,t);await Be(n,c,l,d,t)}return A(c)}i(D,"resolveSandboxTemplateStartRepo");async function $e(e){let t=We.join(e,".git");if(Ge(t))return;let n=await g("git",["init"],{cwd:e});if(n.code!==0)throw new Error(`git init failed: ${n.stderr.trim()||n.stdout.trim()||"unknown error"}`)}i($e,"ensureGitRepository");async function Fe(e,t){let n=await g("git",["status","--porcelain"],{cwd:e});if(n.code!==0)throw new Error(`git status failed: ${n.stderr.trim()||n.stdout.trim()||"unknown error"}`);let a=(await g("git",["rev-parse","--verify","HEAD"],{cwd:e})).code===0,o=n.stdout.trim().length>0;if(!o&&a)return;if(!(h(t.commit)||h(t.yes)||(Ke.isTTY?await me(a?"Commit local changes before starting the sandbox?":"Create the initial git commit before starting the sandbox?",!a):!1))){if(!a)throw new Error("local repository has no commits; pass --commit or commit before starting");o&&console.warn("warning: uncommitted local changes will not be included in the sandbox");return}let d=await g("git",["add","-A"],{cwd:e});if(d.code!==0)throw new Error(`git add failed: ${d.stderr.trim()||d.stdout.trim()||"unknown error"}`);let c=typeof t.commitMessage=="string"&&t.commitMessage.trim()?t.commitMessage.trim():`start ${f} sandbox`,l=await g("git",["commit","-m",c],{cwd:e});if(l.code!==0){let u=l.stderr.trim()||l.stdout.trim();if(u.includes("nothing to commit")&&a)return;throw new Error(`git commit failed: ${u||"unknown error"}`)}}i(Fe,"ensureGitCommitForSandboxTemplateStart");async function je(e,t){let r=(typeof t.branch=="string"?t.branch.trim():"")||await he(e);if(!r)throw new Error("unable to resolve git branch; pass --branch");return r}i(je,"resolveSandboxTemplateStartBranch");async function Be(e,t,n,r,a){let o;try{o=de(t,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let s=h(a.keepTokenRemote)||h(a.token)||h(a.setRemoteToken),d=t.includes("x-access-token:"),c=!s&&!d?t:null,l=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!d){let m=await g("git",["remote","set-url","origin",o],{cwd:e});if(m.code!==0)throw new Error(`git remote set-url failed: ${ce(m.stderr.trim()||m.stdout.trim()||"unknown error")}`)}if((await g("git",["push","-u","origin",n],{cwd:e,inherit:!0})).code!==0)throw new Error("git push failed")}finally{c&&await g("git",["remote","set-url","origin",c],{cwd:e}).catch(()=>null),l===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=l}}i(Be,"pushGitBranchForSandboxTemplateStart");function $(e){return A(e).replace(/\.git$/,"")}i($,"normalizeSandboxTemplateRepoIdentity");function A(e){let t=new URL(e);t.username="",t.password="";let n=t.toString();return n.endsWith(".git")?n:`${n.replace(/\/$/,"")}.git`}i(A,"normalizeSandboxTemplateRepoUrl");async function _e(e){let t=L(e),n=S.dirname(t),r=await j.readFile(t,"utf8"),a=O(r);if(!a.ok){console.error(C(a.diagnostics)),process.exitCode=1;return}let o=a.manifest,s=G(o,e),d=await B(o,e,n),c=await D(o,e,n),l=await N(e),u=Ye(o,e,c),m=await Qe(l,u,c);await tt(l,m.id);let p=await ut(l,m.id,o,e),x=await V(l,m.id,d.uploadRequests),T={...d.scalars,..._(x,d.uploadRequests)},I=await X(l,m.id,s,T,bt(m)),k=await St(l,m.id,s.ports),E=await q(l,m.id,o,e);console.log(JSON.stringify({ok:!0,file:t,repo:c,executable:{kind:s.kind,name:s.name,command:s.command},sandbox:Re(m),setupCommands:p,uploadedFiles:x,input:T,execution:I,previews:k,schedules:E,expectedArtifacts:s.artifactPaths},null,2))}i(_e,"runSandboxTemplateStart");function G(e,t){let n=v(e),r=typeof t.action=="string"?t.action.trim():"",a=typeof t.service=="string"?t.service.trim():"",o=typeof t.target=="string"?t.target.trim():"",s=typeof t.entrypoint=="string"?t.entrypoint.trim():"",d=r||a||o||s||"start",c=r?"action":a?"service":"",l=n.find(u=>u.name===d&&(!c||u.kind===c));if(!l)throw new Error(`manifest executable not found: ${d}. Available: ${n.map(u=>`${u.kind}:${u.name}`).join(", ")}`);return l}i(G,"resolveSandboxTemplateStartExecutable");function Ye(e,t,n){let r=typeof t.budgetUsd=="string"&&t.budgetUsd.trim()?t.budgetUsd.trim():typeof t.budget=="string"&&t.budget.trim()?t.budget.trim():"0.05",a=R(t.maxDurationSeconds,"max-duration-seconds"),o=R(t.idleTimeoutSeconds,"idle-timeout-seconds"),s=typeof t.teamId=="string"?t.teamId.trim():"",d=typeof t.projectId=="string"?t.projectId.trim():"",c=typeof t.runtimeProjectId=="string"?t.runtimeProjectId.trim():"";if(d&&c&&d!==c)throw new Error("project-id and runtime-project-id must match when both are set");let l=d||c,u=typeof t.agentId=="string"?t.agentId.trim():"",m=typeof t.runtimeAgentId=="string"?t.runtimeAgentId.trim():"";if(u&&m&&u!==m)throw new Error("agent-id and runtime-agent-id must match when both are set");let p=u||m,x=fe(t.workflowMode),T=be(t.runtimePromotionPolicy),I=typeof t.runtimeBaseBranch=="string"&&t.runtimeBaseBranch.trim()?t.runtimeBaseBranch.trim():"",k=typeof t.runtimeBaseSha=="string"&&t.runtimeBaseSha.trim()?t.runtimeBaseSha.trim():"",E=typeof t.runtimeId=="string"&&t.runtimeId.trim()?t.runtimeId.trim():"",te=!!(x||T||I||k||E||c||m),ne=xe(e,t),re=Xe(e);return{sandbox:{repo:n,...s?{teamId:s}:{},...l?{projectId:l}:{},...p?{agentId:p}:{},resources:e.resources??{},networkPolicy:{internetEgress:He(e.network.egress)},budget:{maxUsd:r},quotas:{maxSpendUsd:r,...a!==void 0?{maxDurationSeconds:a}:{},...o!==void 0?{idleTimeoutSeconds:o}:{}},...ne.length>0?{env:ne}:{},...re?{workloadSource:re}:{},volumes:e.volumes,metadata:{source:"openpond-code-sandbox-template-start",manifestFile:f,template:{name:e.name,version:e.version,useCase:e.useCase}}},...te&&E?{runtimeId:E}:{},...te&&!E?{sandboxRuntime:{...s?{teamId:s}:{},...x?{workflowMode:x}:{},...l?{projectId:l}:{},...p?{agentId:p}:{},baseBranch:I||"master",...k?{baseSha:k}:{},...T?{promotionPolicy:T}:{}}}:{}}}i(Ye,"buildSandboxTemplateStartCreateInput");function Xe(e){if(e.runtime.image)return{image:e.runtime.image};if(e.runtime.dockerfile)return{dockerfile:e.runtime.dockerfile}}i(Xe,"sandboxWorkloadSourceFromManifest");function He(e){return e==="allow"?"allow":"block"}i(He,"sandboxTemplateInternetEgressPolicy");async function Qe(e,t,n){let r=Date.now();try{return(await Ee(e,t)).sandbox}catch(a){if(!Ze(a))throw a;return console.warn("warning: sandbox create timed out; checking for the created sandbox record"),et(e,t.sandbox,n,r)}}i(Qe,"createSandboxTemplateStartSandbox");function Ze(e){return e instanceof Error&&/\b(504|timed out|timeout)\b/i.test(e.message)}i(Ze,"isLikelySandboxCreateTimeout");async function et(e,t,n,r){let s=Date.now()+72e4,d=$(n),c=t.metadata??{};for(;Date.now()<s;){let u=(await e.list({...t.teamId?{teamId:t.teamId}:{},...t.projectId?{projectId:t.projectId}:{},...t.agentId?{agentId:t.agentId}:{}})).filter(m=>{if(!m.repo||$(m.repo)!==d)return!1;let p=Date.parse(m.createdAt);return!(Number.isFinite(p)&&p<r-3e4||c.source&&m.metadata?.source!==c.source)}).sort((m,p)=>Date.parse(p.createdAt)-Date.parse(m.createdAt))[0];if(u?.state==="running"||u?.state==="stopped")return u;if(u?.state==="error")throw new Error(`sandbox create failed after timeout: ${u.id}
3
3
  ${u.logs.join(`
4
4
  `)}`);await W(3e3)}throw new Error("sandbox create timed out and no matching created sandbox reached running state")}i(et,"recoverTimedOutSandboxCreate");async function tt(e,t){let a=Date.now()+12e4,o=null;for(;Date.now()<a;){try{let s=await e.exec(t,{command:"true",timeoutSeconds:30});if(s.command.status==="succeeded"&&s.command.exitCode===0)return;o=new Error(`readiness command ${s.command.status} with exit code ${String(s.command.exitCode)}`)}catch(s){if(o=s,!nt(s))throw s}await W(3e3)}throw new Error(`sandbox runner was not ready after create: ${rt(o)}`)}i(tt,"waitForSandboxTemplateRunnerReady");function nt(e){return e instanceof Error&&/\b(502|503|504|timed out|timeout|sandbox_not_found|sandbox_not_ready|sandbox_runner_failed)\b/i.test(e.message)}i(nt,"isRetryableSandboxRunnerReadyError");function rt(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown error"}i(rt,"formatUnknownError");function W(e){return new Promise(t=>setTimeout(t,e))}i(W,"sleep");async function B(e,t,n){let r=at(t),a=st(e),o=[],s=ot(t);for(let[c,l]of Object.entries(s)){let u=a.get(c);if(!u)throw new Error(`${c} is not declared as a file upload input in ${f}`);let m=await dt(l,n);if(!u.multiple&&m.length>1)throw new Error(`${c} accepts one file, got ${m.length}`);o.push({inputName:c,localPaths:m,spec:u})}let d=Array.isArray(e.inputs.schema.required)?e.inputs.schema.required.filter(c=>typeof c=="string"):[];for(let c of d)if(a.has(c)&&!o.some(l=>l.inputName===c))throw new Error(`${c} is required; pass --input-file ${c}=<path> or --input-files ${c}=<glob>`);return{scalars:r,uploadRequests:o}}i(B,"resolveSandboxTemplateStartInput");function at(e){let t=typeof e.inputs=="string"?e.inputs:typeof e.inputJson=="string"?e.inputJson:typeof e.params=="string"?e.params:"",n=t?M(t,"inputs"):{};if(!n||typeof n!="object"||Array.isArray(n))throw new Error("inputs must be a JSON object");let r=typeof e.input=="string"?e.input.trim():"";if(r){let[a,o]=J(r,"input");n[a]=o}return n}i(at,"parseSandboxTemplateScalarInputs");function ot(e){let t={},n=typeof e.inputFile=="string"?e.inputFile.trim():"";if(n){let[a,o]=J(n,"input-file");t[a]=o}let r=typeof e.inputFiles=="string"?e.inputFiles.trim():"";if(r){let[a,o]=J(r,"input-files");t[a]=o}return t}i(ot,"parseSandboxTemplateFileInputOptions");function J(e,t){let n=e.indexOf("=");if(n<=0)throw new Error(`${t} must be formatted as name=value`);let r=e.slice(0,n).trim(),a=e.slice(n+1).trim();if(!r||!a)throw new Error(`${t} must be formatted as name=value`);return[r,a]}i(J,"parseKeyValueOption");function st(e){let t=F(e.inputs.schema.properties)??{},n=new Map;for(let[r,a]of Object.entries(t)){let o=F(a);if(!o)continue;let s=F(o["x-openpond-upload"]??o.xOpenPondUpload);if(!s)continue;let d=typeof s.targetPath=="string"&&s.targetPath.trim()?it(s.targetPath):"";if(!d)throw new Error(`${r} upload metadata is missing targetPath`);let c=s.multiple===!0||o.type==="array"||F(o.items)?.format==="file";n.set(r,{inputName:r,multiple:c,targetPath:d})}return n}i(st,"collectSandboxTemplateUploadSpecs");function F(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}i(F,"asPlainRecord");function it(e){let t=e.trim().replace(/\\/g,"/").replace(/^\/workspace\//,"").replace(/^\.\//,"").replace(/^\/+/,"");if(!t||t.split("/").some(n=>n===".."||n===""))throw new Error(`invalid upload target path: ${e}`);if(t.split("/").some(K))throw new Error("sandbox template uploads cannot target .env* files; create sandbox secrets and pass refs with --env-ref");return t}i(it,"normalizeSandboxUploadTargetPath");async function dt(e,t){let n=e.split(",").map(a=>a.trim()).filter(Boolean),r=(await Promise.all(n.map(a=>ct(a,t)))).flat();if(r.length===0)throw new Error(`no files matched ${e}`);return r}i(dt,"expandSandboxTemplateUploadPaths");async function ct(e,t){let n=S.resolve(t,e);if(!e.includes("*")){if(lt(n),!(await j.stat(n)).isFile())throw new Error(`upload path is not a file: ${n}`);return[n]}let r=S.dirname(n),a=S.basename(n),o=mt(a),d=(await j.readdir(r,{withFileTypes:!0})).filter(l=>l.isFile()&&o.test(l.name)).sort((l,u)=>l.name.localeCompare(u.name));if(d.find(l=>K(l.name)))throw new Error("sandbox template uploads cannot include .env* files; create sandbox secrets and pass refs with --env-ref");return d.map(l=>S.join(r,l.name)).sort((l,u)=>l.localeCompare(u))}i(ct,"expandSandboxTemplateUploadPath");function lt(e){if(K(S.basename(e)))throw new Error("sandbox template uploads cannot include .env* files; create sandbox secrets and pass refs with --env-ref")}i(lt,"assertSandboxTemplateUploadPathAllowed");function K(e){return e===".env"||e.startsWith(".env.")}i(K,"isSandboxEnvFileName");function mt(e){let t=e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`)}i(mt,"globBasenameToRegExp");async function ut(e,t,n,r){let a=R(r.setupTimeoutSeconds,"setup-timeout-seconds")??900,o=[];for(let s of n.setup.commands){let d=await pt(e,t,s,a);if(o.push({command:s,status:d.status,exitCode:d.exitCode}),d.status!=="succeeded"||d.exitCode!==0)throw new Error(`setup command failed: ${s}
5
5
  ${d.output}`)}return o}i(ut,"runSandboxTemplateSetupCommands");async function V(e,t,n){let r=[];for(let a of n)for(let o of a.localPaths){let s=await j.readFile(o),d=Y(a.spec.targetPath,S.basename(o));await e.uploadFileBase64(t,d,s.toString("base64")),r.push({inputName:a.inputName,localPath:o,sandboxPath:d,sizeBytes:s.byteLength})}return r}i(V,"uploadSandboxTemplateStartFiles");function Y(e,t){return`${e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}i(Y,"joinSandboxUploadPath");function _(e,t){let n={};for(let r of t){let a=e.filter(o=>o.inputName===r.inputName).map(o=>o.sandboxPath);n[r.inputName]=r.spec.multiple?a:a[0]??""}return n}i(_,"formatUploadedFileParams");async function X(e,t,n,r,a={}){await ft(e,t,r);let o=xt(n,a),s=n.timeoutSeconds;if(n.kind==="service")return{kind:"service",process:(await e.startProcess(t,{command:o,...s!==void 0?{timeoutSeconds:s}:{}})).process};let d=await Le(e,t,o,s??900);if(d.status!=="succeeded"||d.exitCode!==0)throw new Error(`template command failed: ${n.name}