openpond 0.2.35 → 0.2.37

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 (150) hide show
  1. package/dist/app-server.d.ts +197 -4
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/actions-command-GNQREIDD.js +2 -0
  4. package/dist/chunks/{app-layer-HK2GTSRX.js → app-layer-BDAKS3DG.js} +1 -1
  5. package/dist/chunks/app-server-runtime-D74FFS27.js +2 -0
  6. package/dist/chunks/apps-2SUP5JZE.js +2 -0
  7. package/dist/chunks/chunk-2O5UZOYL.js +13 -0
  8. package/dist/chunks/{chunk-BRJKTOMI.js → chunk-3I5BMVJI.js} +1 -1
  9. package/dist/chunks/{chunk-E4U7LXSW.js → chunk-3LG4G5JR.js} +2 -2
  10. package/dist/chunks/{chunk-4QX2I2DX.js → chunk-3N4GQL6I.js} +1 -1
  11. package/dist/chunks/{chunk-DR3XPQRZ.js → chunk-3YA2CD22.js} +1 -1
  12. package/dist/chunks/{chunk-EFTLCT7C.js → chunk-4R4KM6LL.js} +1 -1
  13. package/dist/chunks/{chunk-MXLB6MEW.js → chunk-5YUITAUN.js} +1 -1
  14. package/dist/chunks/{chunk-QPZNN5Q3.js → chunk-6EAQL7YX.js} +1 -1
  15. package/dist/chunks/{chunk-77BXXOHW.js → chunk-BLXEK5F7.js} +1 -1
  16. package/dist/chunks/{chunk-QWENRTVW.js → chunk-DAOLQUAK.js} +1 -1
  17. package/dist/chunks/{chunk-JFSDNQHW.js → chunk-DG4DIFF4.js} +3 -3
  18. package/dist/chunks/{chunk-SRQVXHSM.js → chunk-DXOOJFFU.js} +1 -1
  19. package/dist/chunks/chunk-EIB7GHIQ.js +4 -0
  20. package/dist/chunks/{chunk-XCTFXXVY.js → chunk-FFEI7IRU.js} +1 -1
  21. package/dist/chunks/chunk-FOW3LI6G.js +2 -0
  22. package/dist/chunks/{chunk-JLWAK5PS.js → chunk-FQOVC2GR.js} +78 -78
  23. package/dist/chunks/chunk-HZP5U2AA.js +3 -0
  24. package/dist/chunks/chunk-I6DQSOSF.js +12 -0
  25. package/dist/chunks/chunk-IYROEHYB.js +2 -0
  26. package/dist/chunks/{chunk-BOQBDCVU.js → chunk-KCFVJDIV.js} +1 -1
  27. package/dist/chunks/chunk-L6NNQUAT.js +53 -0
  28. package/dist/chunks/chunk-OO7JG7KM.js +42 -0
  29. package/dist/chunks/chunk-PKBU37CH.js +5 -0
  30. package/dist/chunks/chunk-QUNRWDVO.js +155 -0
  31. package/dist/chunks/{chunk-34URWDE7.js → chunk-S4RSY6CR.js} +1 -1
  32. package/dist/chunks/{chunk-VL553I5E.js → chunk-SL7XLTIT.js} +199 -199
  33. package/dist/chunks/{chunk-BAKCGJ5D.js → chunk-TZ6N7WFI.js} +1 -1
  34. package/dist/chunks/{chunk-Z6F6PYF4.js → chunk-UJLZRM2M.js} +1 -1
  35. package/dist/chunks/chunk-XISNUB62.js +2 -0
  36. package/dist/chunks/{chunk-PZ2ZILPN.js → chunk-XLVFY2BA.js} +1 -1
  37. package/dist/chunks/{chunk-K6EGNB2A.js → chunk-YQPECTJ2.js} +1 -1
  38. package/dist/chunks/{chunk-PMXE4CAA.js → chunk-Z3RBK6LN.js} +1 -1
  39. package/dist/chunks/cli-A2P56J7R.js +2 -0
  40. package/dist/chunks/configuration-command-URDRLDNY.js +2 -0
  41. package/dist/chunks/core-commands-CMAAUKPQ.js +2 -0
  42. package/dist/chunks/desktop-test-5PKGG6H6.js +3 -0
  43. package/dist/chunks/dist-CEKBK32A.js +2 -0
  44. package/dist/chunks/dist-GKCGK44T.js +2 -0
  45. package/dist/chunks/{extension-RMJAXEKN.js → extension-DG2XISC6.js} +1 -1
  46. package/dist/chunks/{help-QDMTLEIL.js → help-ZLJV3ZVW.js} +1 -1
  47. package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +2 -0
  48. package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +3 -0
  49. package/dist/chunks/{opchat-MHH4C5YQ.js → opchat-IMGIFM4W.js} +1 -1
  50. package/dist/chunks/organizations-G3UOHURO.js +2 -0
  51. package/dist/chunks/{profile-KVDJTM4D.js → profile-LMRN5QMQ.js} +1 -1
  52. package/dist/chunks/project-agent-DTAVYEB6.js +2 -0
  53. package/dist/chunks/sandbox-command-YO6RR5SD.js +2 -0
  54. package/dist/chunks/{sandbox-template-Q6K5JXA3.js → sandbox-template-LN5OQ55F.js} +1 -1
  55. package/dist/chunks/{src-42VXY5DZ.js → src-A5KEQW52.js} +1 -1
  56. package/dist/chunks/{src-ZGGKHNNF.js → src-LRJO4THC.js} +3 -3
  57. package/dist/chunks/{teams-bot-7TPB34DR.js → teams-bot-RY5M6AOW.js} +1 -1
  58. package/dist/chunks/{workspaces-XFUQZH5T.js → workspaces-KZ6ZJXXY.js} +1 -1
  59. package/dist/cli.js +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/web/assets/{App-BKY1b22z.js → App-BRZg56AC.js} +32 -32
  62. package/dist/web/assets/{AppDialog-C64bP66E.js → AppDialog-BR9UjEFe.js} +1 -1
  63. package/dist/web/assets/{AppTerminalPanel-fVkWSvWK.js → AppTerminalPanel-DNXVV6S_.js} +2 -2
  64. package/dist/web/assets/{AppsView-DHnab11q.js → AppsView-DhaB7uT7.js} +1 -1
  65. package/dist/web/assets/{BrowserSidebar-C7YeQ9KS.js → BrowserSidebar-zecj1P2T.js} +1 -1
  66. package/dist/web/assets/{CartesianChart-CYX3IXBM.js → CartesianChart-DRhWC0XA.js} +1 -1
  67. package/dist/web/assets/{CollaborationTabs-j2oBkesr.js → CollaborationTabs-BzNNwOcD.js} +1 -1
  68. package/dist/web/assets/{CommandMenu-BN1a4dTn.js → CommandMenu-C7HuXmgN.js} +1 -1
  69. package/dist/web/assets/{CommunityView-CNoxP71Z.js → CommunityView-C4HfU5ky.js} +1 -1
  70. package/dist/web/assets/{ComposerCreateImproveStrip-IoK3lqK8.js → ComposerCreateImproveStrip-CG8YZxWB.js} +1 -1
  71. package/dist/web/assets/{GetStartedView-QPabIxZC.js → GetStartedView-ZxtcgU5X.js} +1 -1
  72. package/dist/web/assets/HostedModelLearningReview-BhGIhvoc.js +1 -0
  73. package/dist/web/assets/{HostedModelLearningSettings-TkSSxw8x.js → HostedModelLearningSettings-BKM_1-LZ.js} +1 -1
  74. package/dist/web/assets/{LabModelVersionDetailPage-CRFw6V7e.js → LabModelVersionDetailPage-CklKwV_e.js} +1 -1
  75. package/dist/web/assets/{LabSkillSidebar-Dl8KWUe0.js → LabSkillSidebar-Cq_axOXr.js} +1 -1
  76. package/dist/web/assets/{LabsRoute-BzdL7mUM.js → LabsRoute-BPGkQnKq.js} +6 -6
  77. package/dist/web/assets/{MainChatThread-C3IdxbN3.js → MainChatThread-DvllW6Ej.js} +2 -2
  78. package/dist/web/assets/{MainPane-BdR1K59_.js → MainPane-BaUIvio6.js} +4 -4
  79. package/dist/web/assets/{MarkdownText-CkLxqh2M.js → MarkdownText-DP7Hjp4L.js} +1 -1
  80. package/dist/web/assets/{NativeSkillSidebar-VkWpZX6S.js → NativeSkillSidebar-BSSKKH-y.js} +1 -1
  81. package/dist/web/assets/{NewExperienceSwitcher-D_K16Ho-.js → NewExperienceSwitcher-cWw4m_pU.js} +1 -1
  82. package/dist/web/assets/{NewProjectDialog-B6E1wWOM.js → NewProjectDialog-BMzXEHsC.js} +1 -1
  83. package/dist/web/assets/{OutputsPage-27MuutGA.js → OutputsPage-CGWtgJ_j.js} +1 -1
  84. package/dist/web/assets/{ProjectsPage-CokpZHgx.js → ProjectsPage-C00Wt3oR.js} +1 -1
  85. package/dist/web/assets/{RightChatPanelStack-B6JhJdlc.js → RightChatPanelStack-0D_jpeAm.js} +1 -1
  86. package/dist/web/assets/{RightSidebarHomePanel-nn0dqUF0.js → RightSidebarHomePanel-BgHpI97K.js} +1 -1
  87. package/dist/web/assets/{ScheduledWorkPage-idJ8AO15.js → ScheduledWorkPage-C-P_Jv04.js} +1 -1
  88. package/dist/web/assets/{SettingsView-ZH2gDC6E.js → SettingsView-BJDvzvtZ.js} +3 -3
  89. package/dist/web/assets/{TeamChatView-B5cG9M6w.js → TeamChatView-BdUQNXvx.js} +2 -2
  90. package/dist/web/assets/{TerminalOverlay-9SPRce9W.js → TerminalOverlay-85H1eqcg.js} +1 -1
  91. package/dist/web/assets/{TrainingCreationPanel-2dkxe7py.js → TrainingCreationPanel-Bdx2BJzb.js} +1 -1
  92. package/dist/web/assets/{TrainingDraftPanel-oYbOFapi.js → TrainingDraftPanel-TcvqZfYS.js} +1 -1
  93. package/dist/web/assets/{UsageSettingsSection-zWs4Z_9b.js → UsageSettingsSection-Dm8bsNIT.js} +1 -1
  94. package/dist/web/assets/{WorkSidebarPanel-CiBQztz6.js → WorkSidebarPanel-C9bKi4NH.js} +1 -1
  95. package/dist/web/assets/{WorkspaceDiffPanel-BPt29A2a.js → WorkspaceDiffPanel-CFzHklbv.js} +3 -3
  96. package/dist/web/assets/{WorkspaceEnvironmentMenu-pb6fs4-2.js → WorkspaceEnvironmentMenu-_e6IkhGw.js} +1 -1
  97. package/dist/web/assets/{WorkspaceGitDialogs-DHD-L4Vs.js → WorkspaceGitDialogs-BglcR8S9.js} +1 -1
  98. package/dist/web/assets/{WorkspaceMonacoEditor-BxtCNaRo.js → WorkspaceMonacoEditor-BuipCT-i.js} +3 -3
  99. package/dist/web/assets/{arrow-up-right-DcP3EZaY.js → arrow-up-right-jN0p0koy.js} +1 -1
  100. package/dist/web/assets/{clipboard-BXulVWTJ.js → clipboard-Bat4as9H.js} +1 -1
  101. package/dist/web/assets/{cloud-upload-B3hP6o0H.js → cloud-upload-CFs0F_2n.js} +1 -1
  102. package/dist/web/assets/{cssMode-c85YG3Pd.js → cssMode-Cg4Jey3B.js} +1 -1
  103. package/dist/web/assets/{folder-open-CtOXE4jL.js → folder-open-BqInWH_9.js} +1 -1
  104. package/dist/web/assets/{folder-plus-KO96VZiR.js → folder-plus-BSA6I7ld.js} +1 -1
  105. package/dist/web/assets/{git-commit-horizontal-Bhtev2bN.js → git-commit-horizontal-CLDqrpDQ.js} +1 -1
  106. package/dist/web/assets/{htmlMode-BbCawv2y.js → htmlMode-DHHN3vwk.js} +1 -1
  107. package/dist/web/assets/{index-Hynq87d2.js → index-VtbQYCWA.js} +2 -2
  108. package/dist/web/assets/{info-Dqf1UVHA.js → info-BSebzpyp.js} +1 -1
  109. package/dist/web/assets/{jsonMode-CFycP8DE.js → jsonMode-mvqMGlEK.js} +1 -1
  110. package/dist/web/assets/{lspLanguageFeatures-CYX4VXe2.js → lspLanguageFeatures-Bw_QMGcP.js} +1 -1
  111. package/dist/web/assets/{minimize-2-BCmNskf_.js → minimize-2-CaHjbHpF.js} +1 -1
  112. package/dist/web/assets/{monaco.contribution-CJYgsAyM.js → monaco.contribution-CBkwYqsg.js} +2 -2
  113. package/dist/web/assets/{monaco.contribution-CPkt_0fd.js → monaco.contribution-CiXEi4Ka.js} +2 -2
  114. package/dist/web/assets/{monaco.contribution-3ZJbmsu3.js → monaco.contribution-DubQum0F.js} +2 -2
  115. package/dist/web/assets/{monaco.contribution-DR_TcZx7.js → monaco.contribution-KrPDFXc4.js} +2 -2
  116. package/dist/web/assets/{monitor-DWlfguJj.js → monitor-DwOfVMY6.js} +1 -1
  117. package/dist/web/assets/{python-rAXzgbqp.js → python-BPnA89YS.js} +1 -1
  118. package/dist/web/assets/{refresh-cw-BUPgzu5R.js → refresh-cw-DO-hUyTn.js} +1 -1
  119. package/dist/web/assets/{save-Mb-ECgFZ.js → save-C7WFI7Mn.js} +1 -1
  120. package/dist/web/assets/{square-CxNbsHso.js → square-DiLQ59tw.js} +1 -1
  121. package/dist/web/assets/{toggleHighContrast-DUvtEJ40.js → toggleHighContrast-BWFPIQBM.js} +1 -1
  122. package/dist/web/assets/{tsMode-IPAavolh.js → tsMode-CWxqU0x6.js} +1 -1
  123. package/dist/web/assets/{upload-Bn6_UQEa.js → upload-vUnuWYGk.js} +1 -1
  124. package/dist/web/assets/{useLocalAgentSchedules-DAHspLJg.js → useLocalAgentSchedules-BFbGmflA.js} +1 -1
  125. package/dist/web/assets/{useSessionTurnCache-CUiJuUjd.js → useSessionTurnCache-C0zgYrCB.js} +1 -1
  126. package/dist/web/assets/{wifi-off-Bsy0Wjm8.js → wifi-off-DbNO6u3Z.js} +1 -1
  127. package/dist/web/assets/{workers-35o3qFXU.js → workers-4I09fePv.js} +1 -1
  128. package/dist/web/assets/{yaml-Ba5fmKgb.js → yaml-DpHYonDY.js} +1 -1
  129. package/dist/web/index.html +1 -1
  130. package/package.json +1 -1
  131. package/dist/chunks/actions-command-6LFZFTLA.js +0 -2
  132. package/dist/chunks/app-server-runtime-CAWXM33C.js +0 -2
  133. package/dist/chunks/apps-YJRRLX2N.js +0 -2
  134. package/dist/chunks/chunk-5BFWDFPX.js +0 -166
  135. package/dist/chunks/chunk-B5LKUQGM.js +0 -2
  136. package/dist/chunks/chunk-CWW2EK77.js +0 -4
  137. package/dist/chunks/chunk-IFP6W4OW.js +0 -54
  138. package/dist/chunks/chunk-OYJ73BSC.js +0 -42
  139. package/dist/chunks/chunk-TBX3Z7TX.js +0 -2
  140. package/dist/chunks/chunk-XR6ZLKVW.js +0 -15
  141. package/dist/chunks/cli-YI6G22CQ.js +0 -2
  142. package/dist/chunks/configuration-command-CYUWO6CD.js +0 -2
  143. package/dist/chunks/core-commands-Z5C7S6OH.js +0 -2
  144. package/dist/chunks/desktop-test-JBZCCTSN.js +0 -3
  145. package/dist/chunks/dist-XCT2G25K.js +0 -2
  146. package/dist/chunks/hosted-profile-compiler-7SGXUZB4.js +0 -3
  147. package/dist/chunks/organizations-5KM2JD32.js +0 -2
  148. package/dist/chunks/project-agent-SXUMNJLZ.js +0 -2
  149. package/dist/chunks/sandbox-command-FQGX5MSS.js +0 -2
  150. package/dist/web/assets/HostedModelLearningReview-CNd3-FrC.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{B as te,D as ne,E as oe,F as P,G as re,H as se,l as H,z as ee}from"./chunk-B5LKUQGM.js";import{a as T,b as y,c as w,h as Y,i as B,j as K}from"./chunk-MJC26GOX.js";import{Ja as $,Mb as M,Va as Q,tb as F}from"./chunk-5BFWDFPX.js";import{k as l}from"./chunk-IFP6W4OW.js";import{b as a}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";function ie(r,e){return{supportsResume:!e,get:d((...t)=>r.get(...t),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...t)=>r.start(...t),exec:d((t,n)=>r.exec(t,e?{...n,timeoutSeconds:Math.min(n.timeoutSeconds??30,60)}:n),"exec"),mkdir:d((...t)=>r.mkdir(...t),"mkdir"),uploadFile:d((...t)=>r.uploadFile(...t),"uploadFile"),uploadFileBase64:d((...t)=>r.uploadFileBase64(...t),"uploadFileBase64"),listFiles:d((...t)=>r.listFiles(...t),"listFiles"),downloadFileResponse:d((...t)=>r.downloadFileResponse(...t),"downloadFileResponse"),stop:d((...t)=>r.stop(...t),"stop"),delete:d((...t)=>r.delete(...t),"delete"),createWork:d(({requestId:t,repo:n,budgetUsd:o,metadata:s})=>{if(e){if(n?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(o!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let p={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...t?{requestId:t}:{}};return r.create(p)}let i=o?.trim()||"1.00";return r.create({...n?.trim()?{repo:n.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:i},quotas:{maxSpendUsd:i,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...s,...t?{workRequestId:t}:{}}},{async:!0})},"createWork")}}d(ie,"workSandbox");function N(r,e){let t=new URL(r);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return t.toString().replace(/\/$/,"")}d(N,"configuredEndpoint");function _(r,e){if(!r?.trim())throw new Error(`${e} is required`);return r.trim()}d(_,"configuredKey");var ke=a.object({choices:a.array(a.object({message:a.object({content:a.string().nullable().optional(),tool_calls:a.array(a.object({id:a.string().min(1),type:a.literal("function"),function:a.object({name:a.string().min(1),arguments:a.string()})})).optional()})})).min(1)});async function ae(r,e){if(!e)return K(r);let t=await fetch(`${r.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},body:JSON.stringify({model:r.model,messages:r.messages,tools:r.tools,tool_choice:"auto",stream:!1}),signal:r.signal,redirect:"error"});if(!t.ok)throw new Error(`Configured model request failed (${t.status})`);return ke.parse(await t.json())}d(ae,"workModelTurn");var xe="openpond-chat",Re=24,Se=4e4,D=2e4,z="outputs",J="inputs/previous-outputs",ue="inputs/.openpond-context.json",Ce=100,de=100,pe=100*1024*1024,x=class{static{d(this,"OpenPondWorkClient")}#e;#n;#t;#o;#r;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#o=ie(e.sandboxes,e.sandboxConfig),this.#r=e.defaultModel??xe,this.#s=e.customModel??!1}async run(e){let t=e.prompt.trim();if(!t)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let n=d(async m=>e.onEvent?.(m),"emit"),o=e.cleanup??"keep",s=We(o),i=null,p=null,f=!1,g=le(e.maxSteps,1,100,Re),c="";try{await n({type:"status",message:"Preparing sandbox"}),i=await this.#g(e),await n({type:"sandbox",sandboxId:i.id,state:i.state}),await this.#u(i.id,e.inputs??[]),p=await this.#m(i.id);let m=[{role:"system",content:ve(i.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(h=>({...h})),{role:"user",content:t}];for(let h=1;h<=g;h+=1){e.signal?.throwIfAborted(),await n({type:"status",message:`Thinking \xB7 step ${h}`});let G=(await ae({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#r,messages:m,tools:Ie,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:i.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],W=G?.message?.content?.trim()??"",L=G?.message?.tool_calls??[];if(m.push({role:"assistant",content:W||null,...L.length>0?{tool_calls:L}:{}}),W&&(c=W,await n({type:"assistant",text:W})),L.length===0){let b=await this.#p(i.id,p);for(let U of b)await n({type:"output",output:U});f=!0,await this.#i(i.id,b,e,s,n);let A={sandboxId:i.id,text:c,steps:h,outputs:b,lifecycle:s};return await n({type:"done",...A}),A}for(let[b,A]of L.entries()){e.signal?.throwIfAborted();let U=await this.#h(i.id,A,b,e.timeoutSeconds,n);m.push(U)}}throw new Error(`Work did not finish within ${g} steps`)}catch(m){if(i&&p&&!f)try{let h=await this.#p(i.id,p);for(let Z of h)await n({type:"output",output:Z});await this.#i(i.id,h,e,s,n)}catch(h){ce(m,s,h)}throw ce(m,s),m}}async deleteSandbox(e){try{if((await this.#o.get(e)).state==="deleted")return;await this.#o.delete(e)}catch(t){if(t instanceof T&&t.status===404)return;throw t}}async#u(e,t){if(t.length===0)return;if(t.length>de)throw new Error(`Work inputs exceed the ${de} file limit`);if(t.reduce((i,p)=>i+Buffer.byteLength(p.contentsBase64,"base64"),0)>pe)throw new Error(`Work inputs exceed the ${pe} byte limit`);await this.#o.mkdir(e,{path:J,recursive:!0});let o=new Set,s=[];for(let[i,p]of t.entries()){let f=Ae(p,i,o),g=`${J}/${f}`;await this.#o.uploadFileBase64(e,g,p.contentsBase64),s.push({id:p.id,path:g,name:p.name,mimeType:p.mimeType??null,checksumSha256:p.checksumSha256??null,revision:p.revision??null,metadata:p.metadata??{}})}await this.#o.uploadFile(e,ue,JSON.stringify({version:1,files:s},null,2))}async#i(e,t,n,o,s){if(o.persistence.outputCount=t.length,t.length===0)o.persistence.status="not_needed";else if(n.persistOutput){o.persistence.status="running";for(let i of t){await s({type:"persistence",output:i,status:"started"});try{let p=Le(this.#o,e,i);await n.persistOutput({output:i,download:p}),o.persistence.persistedCount+=1,await s({type:"persistence",output:i,status:"succeeded"})}catch(p){let f=k(p);throw o.persistence.status="failed",o.persistence.error=f,await s({type:"persistence",output:i,status:"failed",error:f}),(n.cleanup??"keep")!=="keep"&&await this.#a(e,o,s),p}}o.persistence.status="complete"}else{if((n.cleanup??"keep")==="delete"&&!n.discardOutputs)throw o.persistence.status="failed",o.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,o,s),new Error(o.persistence.error);o.persistence.status="not_requested"}await this.#d(e,n.cleanup??"keep",o,s)}async#a(e,t,n){if(this.#o.supportsResume){await this.#d(e,"stop",t,n);return}t.cleanup.status="pending",t.cleanup.finalSandboxState="running",t.cleanup.error="Output persistence must be retried before guest deletion",await n({type:"cleanup",policy:t.cleanupPolicy,status:"pending",sandboxState:"running",error:t.cleanup.error})}async#d(e,t,n,o){if(t!=="keep"){n.cleanup.status="running",await o({type:"cleanup",policy:t,status:"started"});try{let s=t==="delete"?await this.#o.delete(e):(await this.#o.stop(e)).sandbox;n.cleanup.finalSandboxState=s.state,n.cleanup.status=t==="delete"&&s.state==="deleted"||t==="stop"&&s.state==="stopped"?"complete":"pending",await o({type:"cleanup",policy:t,status:n.cleanup.status,sandboxState:s.state})}catch(s){let i=k(s);throw n.cleanup.status="failed",n.cleanup.error=i,await o({type:"cleanup",policy:t,status:"failed",error:i}),s}}}downloadOutput(e,t){return this.#o.downloadFileResponse(e,typeof t=="string"?t:t.path)}async#m(e){return await this.#o.mkdir(e,{path:z,recursive:!0}),Te(await this.#c(e))}async#p(e,t){return(await this.#c(e)).filter(o=>t.get(o.path)!==me(o)).sort((o,s)=>o.path.localeCompare(s.path)).slice(0,Ce).map(_e)}async#c(e){return(await this.#o.listFiles(e,{path:z,recursive:!0,maxEntries:500})).files.filter(n=>n.type==="file"&&!ge(n.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let n=await this.#o.get(e.sandboxId);if(n.state==="stopped")await this.#o.start(n.id,{async:!0});else if(n.state==="deleted"||n.state==="error")throw new Error(`Cannot resume sandbox ${n.id} in state ${n.state}`);return await this.#l(n.id,e.signal)}let t=await this.#o.createWork(e);return this.#l(t.id,e.signal)}async#l(e,t){let n=Date.now()+72e4,o=await this.#o.get(e);for(;Date.now()<n;){if(t?.throwIfAborted(),o.state==="running")return o;if(o.state==="error"||o.state==="deleted")throw new Error(`Sandbox ${o.id} entered ${o.state}${o.logs.length?`: ${o.logs.join(`
2
+ import{B as te,D as ne,E as oe,F as P,G as re,H as se,l as H,z as ee}from"./chunk-IYROEHYB.js";import{a as T,b as y,c as w,h as Y,i as B,j as K}from"./chunk-MJC26GOX.js";import{O as F,b as $,fa as M,n as Q}from"./chunk-2O5UZOYL.js";import{a as l}from"./chunk-HZP5U2AA.js";import{b as a}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";function ie(r,e){return{supportsResume:!e,get:d((...t)=>r.get(...t),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...t)=>r.start(...t),exec:d((t,n)=>r.exec(t,e?{...n,timeoutSeconds:Math.min(n.timeoutSeconds??30,60)}:n),"exec"),mkdir:d((...t)=>r.mkdir(...t),"mkdir"),uploadFile:d((...t)=>r.uploadFile(...t),"uploadFile"),uploadFileBase64:d((...t)=>r.uploadFileBase64(...t),"uploadFileBase64"),listFiles:d((...t)=>r.listFiles(...t),"listFiles"),downloadFileResponse:d((...t)=>r.downloadFileResponse(...t),"downloadFileResponse"),stop:d((...t)=>r.stop(...t),"stop"),delete:d((...t)=>r.delete(...t),"delete"),createWork:d(({requestId:t,repo:n,budgetUsd:o,metadata:s})=>{if(e){if(n?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(o!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let p={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...t?{requestId:t}:{}};return r.create(p)}let i=o?.trim()||"1.00";return r.create({...n?.trim()?{repo:n.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:i},quotas:{maxSpendUsd:i,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...s,...t?{workRequestId:t}:{}}},{async:!0})},"createWork")}}d(ie,"workSandbox");function N(r,e){let t=new URL(r);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return t.toString().replace(/\/$/,"")}d(N,"configuredEndpoint");function _(r,e){if(!r?.trim())throw new Error(`${e} is required`);return r.trim()}d(_,"configuredKey");var ke=a.object({choices:a.array(a.object({message:a.object({content:a.string().nullable().optional(),tool_calls:a.array(a.object({id:a.string().min(1),type:a.literal("function"),function:a.object({name:a.string().min(1),arguments:a.string()})})).optional()})})).min(1)});async function ae(r,e){if(!e)return K(r);let t=await fetch(`${r.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},body:JSON.stringify({model:r.model,messages:r.messages,tools:r.tools,tool_choice:"auto",stream:!1}),signal:r.signal,redirect:"error"});if(!t.ok)throw new Error(`Configured model request failed (${t.status})`);return ke.parse(await t.json())}d(ae,"workModelTurn");var xe="openpond-chat",Re=24,Se=4e4,D=2e4,z="outputs",J="inputs/previous-outputs",ue="inputs/.openpond-context.json",Ce=100,de=100,pe=100*1024*1024,x=class{static{d(this,"OpenPondWorkClient")}#e;#n;#t;#o;#r;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#o=ie(e.sandboxes,e.sandboxConfig),this.#r=e.defaultModel??xe,this.#s=e.customModel??!1}async run(e){let t=e.prompt.trim();if(!t)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let n=d(async m=>e.onEvent?.(m),"emit"),o=e.cleanup??"keep",s=We(o),i=null,p=null,f=!1,g=le(e.maxSteps,1,100,Re),c="";try{await n({type:"status",message:"Preparing sandbox"}),i=await this.#g(e),await n({type:"sandbox",sandboxId:i.id,state:i.state}),await this.#u(i.id,e.inputs??[]),p=await this.#m(i.id);let m=[{role:"system",content:ve(i.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(h=>({...h})),{role:"user",content:t}];for(let h=1;h<=g;h+=1){e.signal?.throwIfAborted(),await n({type:"status",message:`Thinking \xB7 step ${h}`});let G=(await ae({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#r,messages:m,tools:Ie,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:i.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],W=G?.message?.content?.trim()??"",L=G?.message?.tool_calls??[];if(m.push({role:"assistant",content:W||null,...L.length>0?{tool_calls:L}:{}}),W&&(c=W,await n({type:"assistant",text:W})),L.length===0){let b=await this.#p(i.id,p);for(let U of b)await n({type:"output",output:U});f=!0,await this.#i(i.id,b,e,s,n);let A={sandboxId:i.id,text:c,steps:h,outputs:b,lifecycle:s};return await n({type:"done",...A}),A}for(let[b,A]of L.entries()){e.signal?.throwIfAborted();let U=await this.#h(i.id,A,b,e.timeoutSeconds,n);m.push(U)}}throw new Error(`Work did not finish within ${g} steps`)}catch(m){if(i&&p&&!f)try{let h=await this.#p(i.id,p);for(let Z of h)await n({type:"output",output:Z});await this.#i(i.id,h,e,s,n)}catch(h){ce(m,s,h)}throw ce(m,s),m}}async deleteSandbox(e){try{if((await this.#o.get(e)).state==="deleted")return;await this.#o.delete(e)}catch(t){if(t instanceof T&&t.status===404)return;throw t}}async#u(e,t){if(t.length===0)return;if(t.length>de)throw new Error(`Work inputs exceed the ${de} file limit`);if(t.reduce((i,p)=>i+Buffer.byteLength(p.contentsBase64,"base64"),0)>pe)throw new Error(`Work inputs exceed the ${pe} byte limit`);await this.#o.mkdir(e,{path:J,recursive:!0});let o=new Set,s=[];for(let[i,p]of t.entries()){let f=Ae(p,i,o),g=`${J}/${f}`;await this.#o.uploadFileBase64(e,g,p.contentsBase64),s.push({id:p.id,path:g,name:p.name,mimeType:p.mimeType??null,checksumSha256:p.checksumSha256??null,revision:p.revision??null,metadata:p.metadata??{}})}await this.#o.uploadFile(e,ue,JSON.stringify({version:1,files:s},null,2))}async#i(e,t,n,o,s){if(o.persistence.outputCount=t.length,t.length===0)o.persistence.status="not_needed";else if(n.persistOutput){o.persistence.status="running";for(let i of t){await s({type:"persistence",output:i,status:"started"});try{let p=Le(this.#o,e,i);await n.persistOutput({output:i,download:p}),o.persistence.persistedCount+=1,await s({type:"persistence",output:i,status:"succeeded"})}catch(p){let f=k(p);throw o.persistence.status="failed",o.persistence.error=f,await s({type:"persistence",output:i,status:"failed",error:f}),(n.cleanup??"keep")!=="keep"&&await this.#a(e,o,s),p}}o.persistence.status="complete"}else{if((n.cleanup??"keep")==="delete"&&!n.discardOutputs)throw o.persistence.status="failed",o.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,o,s),new Error(o.persistence.error);o.persistence.status="not_requested"}await this.#d(e,n.cleanup??"keep",o,s)}async#a(e,t,n){if(this.#o.supportsResume){await this.#d(e,"stop",t,n);return}t.cleanup.status="pending",t.cleanup.finalSandboxState="running",t.cleanup.error="Output persistence must be retried before guest deletion",await n({type:"cleanup",policy:t.cleanupPolicy,status:"pending",sandboxState:"running",error:t.cleanup.error})}async#d(e,t,n,o){if(t!=="keep"){n.cleanup.status="running",await o({type:"cleanup",policy:t,status:"started"});try{let s=t==="delete"?await this.#o.delete(e):(await this.#o.stop(e)).sandbox;n.cleanup.finalSandboxState=s.state,n.cleanup.status=t==="delete"&&s.state==="deleted"||t==="stop"&&s.state==="stopped"?"complete":"pending",await o({type:"cleanup",policy:t,status:n.cleanup.status,sandboxState:s.state})}catch(s){let i=k(s);throw n.cleanup.status="failed",n.cleanup.error=i,await o({type:"cleanup",policy:t,status:"failed",error:i}),s}}}downloadOutput(e,t){return this.#o.downloadFileResponse(e,typeof t=="string"?t:t.path)}async#m(e){return await this.#o.mkdir(e,{path:z,recursive:!0}),Te(await this.#c(e))}async#p(e,t){return(await this.#c(e)).filter(o=>t.get(o.path)!==me(o)).sort((o,s)=>o.path.localeCompare(s.path)).slice(0,Ce).map(_e)}async#c(e){return(await this.#o.listFiles(e,{path:z,recursive:!0,maxEntries:500})).files.filter(n=>n.type==="file"&&!ge(n.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let n=await this.#o.get(e.sandboxId);if(n.state==="stopped")await this.#o.start(n.id,{async:!0});else if(n.state==="deleted"||n.state==="error")throw new Error(`Cannot resume sandbox ${n.id} in state ${n.state}`);return await this.#l(n.id,e.signal)}let t=await this.#o.createWork(e);return this.#l(t.id,e.signal)}async#l(e,t){let n=Date.now()+72e4,o=await this.#o.get(e);for(;Date.now()<n;){if(t?.throwIfAborted(),o.state==="running")return o;if(o.state==="error"||o.state==="deleted")throw new Error(`Sandbox ${o.id} entered ${o.state}${o.logs.length?`: ${o.logs.join(`
3
3
  `)}`:""}`);await Ue(2e3,t),o=await this.#o.get(e)}throw new Error(`Sandbox ${e} did not become ready before timeout`)}async#h(e,t,n,o,s){let i=t.id||`work_tool_${n}`,p=t.function?.name;if(p!=="run_command")return O(i,{error:`Unknown tool: ${p??"missing"}`});let f;try{f=JSON.parse(t.function?.arguments||"{}")}catch(c){return O(i,{error:`Invalid tool arguments: ${k(c)}`})}let g=typeof f.command=="string"?f.command.trim():"";if(!g)return O(i,{error:"command is required"});if(g.length>D){let c=`command exceeds the ${D} character limit`;return await s({type:"tool",toolCallId:i,command:g,status:"failed",output:c}),O(i,{status:"failed",error:c})}await s({type:"tool",toolCallId:i,command:g,status:"started"});try{let c=await this.#o.exec(e,{command:g,timeoutSeconds:le(o,1,900,180)}),m=Ee(c.command.output,Se),h=c.command.status==="succeeded"?"succeeded":"failed";return await s({type:"tool",toolCallId:i,command:g,status:h,output:m,exitCode:c.command.exitCode}),O(i,{status:c.command.status,exitCode:c.command.exitCode,output:m})}catch(c){if(c instanceof T)throw c;let m=k(c);return await s({type:"tool",toolCallId:i,command:g,status:"failed",output:m}),O(i,{status:"failed",error:m})}}},Ie=[{type:"function",function:{name:"run_command",description:"Run a shell command inside the persistent OpenPond sandbox. Use standard shell tools to inspect, edit, build, and test files. Commands start in the repository workspace.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:D,description:"Shell command to execute."}},required:["command"]}}}];function ve(r,e){return["You are OpenPond Work, a careful coding agent operating in an isolated Linux sandbox.",`The active sandbox is ${r}.`,...e?[`The authoritative saved files for this turn are staged under /workspace/${J}; their manifest is /workspace/${ue}.`,"Before revising a previous output, read its staged file and manifest. Copy the staged input into the output directory before editing it; previous output paths may not exist in this sandbox.","Preserve the actual file bytes. Never reconstruct a saved file from the conversation or claim to have preserved it without reading the staged input."]:[],"Use run_command to inspect the workspace, edit files, and validate your work.",`Place completed user-facing files in ${z}. The runtime collects new and revised files there automatically when the turn completes.`,"Do the requested work completely. Preserve existing user changes and avoid destructive commands.","Keep the user informed with concise prose, but call tools whenever verification or file changes are needed.","Before finishing, run relevant tests and summarize the concrete result."].join(`
4
4
  `)}d(ve,"systemPrompt");function We(r){return{cleanupPolicy:r,persistence:{status:"not_requested",outputCount:0,persistedCount:0},cleanup:{status:"not_requested"}}}d(We,"initialLifecycle");function Le(r,e,t){let n=null;return()=>(n??=r.downloadFileResponse(e,{path:t.path,maxBytes:Math.max(1,t.sizeBytes)}).then(o=>{let s=Buffer.byteLength(o.file.contentsBase64,"base64");if(o.file.truncated||o.file.returnedBytes!==o.file.totalSizeBytes||s!==t.sizeBytes)throw new Error(`Output download was incomplete for ${t.name}`);return o}),n)}d(Le,"lazyOutputDownload");function Ae(r,e,t){let n=r.id.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,80)||`input-${e+1}`,o=r.name.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(-120)||"file",s=`${n}-${o}`,i=s,p=1;for(;t.has(i);)p+=1,i=`${s}-${p}`;return t.add(i),i}d(Ae,"uniqueInputName");function ce(r,e,t){!r||typeof r!="object"||Object.assign(r,{workLifecycle:e,...t?{workFinalizationError:k(t)}:{}})}d(ce,"attachWorkFailure");function Te(r){return new Map(r.map(e=>[e.path,me(e)]))}d(Te,"outputSignatures");function me(r){return`${r.sizeBytes}:${r.updatedAt}`}d(me,"outputSignature");function _e(r){let e=ge(r.path).split("/").at(-1)||r.path,t=qe(e);return{path:r.path,name:e,mimeType:t,sizeBytes:r.sizeBytes,updatedAt:r.updatedAt,isBinary:r.isBinary??null,previewable:r.previewable??(t.startsWith("image/")||t==="application/pdf"||t.startsWith("text/"))}}d(_e,"workOutputFromFile");function ge(r){return r.replaceAll("\\","/")}d(ge,"normalizedOutputPath");function qe(r){let e=r.toLowerCase().match(/\.[^.]+$/)?.[0]??"";return je[e]??"application/octet-stream"}d(qe,"workOutputMimeType");var je=Object.freeze({".avif":"image/avif",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".m4a":"audio/mp4",".md":"text/markdown",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});function O(r,e){return{role:"tool",tool_call_id:r,content:JSON.stringify(e)}}d(O,"toolMessage");function le(r,e,t,n){return Number.isFinite(r)?Math.min(t,Math.max(e,Math.floor(r))):n}d(le,"boundedInteger");function Ee(r,e){return r.length<=e?r:`${r.slice(0,e)}
5
5
  \u2026 output truncated by openpond-sdk`}d(Ee,"truncate");function k(r){return r instanceof Error?r.message:String(r)}d(k,"errorMessage");function Ue(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}let o=setTimeout(t,r);o.unref?.(),e?.addEventListener("abort",()=>{clearTimeout(o),n(e.reason)},{once:!0})})}d(Ue,"sleep");import{promises as he}from"node:fs";var R=class{static{d(this,"OpenPondProjectActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e){let t=await y(this.#n,this.#e,q(e.projectId,"releases",e.teamId));return(await w(t,"List Project Action releases")).releases}async catalog(e){let t=await y(this.#n,this.#e,q(e.projectId,"catalog",e.teamId));return(await w(t,"Get Project Action catalog")).catalog}async publish(e){let[t,n]=await Promise.all([he.readFile(e.build.bundlePath),he.readFile(e.build.runnerPath)]),o=await y(this.#n,this.#e,q(e.projectId,"releases",e.teamId),{method:"POST",body:JSON.stringify({sourceRef:e.sourceRef,sourceCommitSha:e.sourceCommitSha,bundleBase64:t.toString("base64"),runnerBase64:n.toString("base64"),registry:e.build.registry,manifest:e.build.manifest,metadata:e.metadata})});return(await w(o,"Publish Project Actions")).release}async run(e){let t=await y(this.#n,this.#e,q(e.projectId,`actions/${encodeURIComponent(e.actionId)}`,e.teamId),{method:"POST",body:JSON.stringify({input:e.value??{},releaseId:e.releaseId,idempotencyKey:e.idempotencyKey,callerType:e.callerType??"sdk",callerId:e.callerId}),signal:e.signal,timeoutMs:9e5});return(await w(t,"Run Project Action")).invocation}};function q(r,e,t){return`/v1/project-actions/${encodeURIComponent(r)}/${e}?teamId=${encodeURIComponent(t)}`}d(q,"projectActionPath");var C=class{static{d(this,"OpenPondProfileActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async catalog(e){let t=S(e.teamId,"teamId"),n=new URLSearchParams({teamId:t});e.profileId?.trim()&&n.set("profileId",e.profileId.trim()),e.profileName?.trim()&&n.set("profileName",e.profileName.trim());let o=await y(this.#n,this.#e,`/v1/profile/actions?${n.toString()}`);return(await w(o,"Get Profile Action catalog")).catalog}async run(e){let t=S(e.teamId,"teamId"),n=S(e.actionKey,"actionKey"),o=S(e.idempotencyKey,"idempotencyKey"),s=S(e.catalogVersion,"catalogVersion"),i=await y(this.#n,this.#e,`/v1/profile/actions/run?${new URLSearchParams({teamId:t}).toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e.profileId?.trim()?{profileId:e.profileId.trim()}:{},...e.profileName?.trim()?{profileName:e.profileName.trim()}:{},actionKey:n,value:e.value??{},conversationId:e.conversationId??null,createConversation:e.createConversation,conversationTitle:e.conversationTitle??null,idempotencyKey:o,catalogVersion:s,externalCapabilityLeases:e.externalCapabilityLeases})});return w(i,"Run Profile Action")}};function S(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}d(S,"requiredValue");import{randomUUID as fe}from"node:crypto";var I=class{static{d(this,"OpenPondWorkflowsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e={}){return this.#t("","List Workflows",{signal:e.signal})}async create(e,t={}){return this.#t("","Create Workflow",{method:"POST",body:JSON.stringify({...e,clientRequestId:e.clientRequestId?.trim()||fe()}),signal:t.signal})}async update(e,t,n={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}`,"Update Workflow",{method:"PATCH",body:JSON.stringify(t),signal:n.signal})}async delete(e,t={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}`,"Delete Workflow",{method:"DELETE",signal:t.signal})}async runNow(e,t={},n={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}/run`,"Run Workflow",{method:"POST",body:JSON.stringify({clientRequestId:t.clientRequestId?.trim()||fe()}),signal:n.signal})}async#t(e,t,n={}){let o=await y(this.#n,this.#e,`/v1/saved-work${e}`,n);return w(o,t)}};function V(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}d(V,"requiredId");var j=a.object({id:l,scope:l,sourceId:l,name:a.string().trim().min(1).max(100),keyPrefix:a.string().min(1).max(100),createdAt:a.iso.datetime(),expiresAt:a.iso.datetime(),revokedAt:a.iso.datetime().nullable()}).strict(),ye=a.string().regex(/^opk_key_[A-Za-z0-9]{16}_[A-Za-z0-9]{48}$/),E=a.discriminatedUnion("action",[a.object({action:a.literal("create"),scope:l,sourceId:l,name:a.string().trim().min(1).max(100),expiresAt:a.iso.datetime(),operationId:l,apiKey:ye}).strict(),a.object({action:a.literal("list"),scope:l,sourceId:l,afterId:l.optional(),limit:a.number().int().min(1).max(100).default(30)}).strict(),a.object({action:a.literal("revoke"),scope:l,sourceId:l,id:l}).strict()]),we=a.object({credential:j,apiKey:ye}).strict(),Pe=a.object({items:a.array(j).max(100),nextCursor:l.nullable()}).strict(),Oe=a.object({scope:l,sourceId:l}).strict(),be=a.object({scope:l,source:F,taskDefinition:F,enabled:a.boolean(),allowedSplits:a.array(Q).min(1).max(4)}).strict();var Be=a.object({batchId:a.string().trim().min(1).max(500),modelProjectId:a.string().trim().min(1).max(500)}).strict(),Ke=a.object({batchId:a.string().min(1),projectId:a.string().min(1),tasksetId:a.string().min(1),releaseId:a.string().min(1),revision:a.number().int().positive(),contentHash:a.string().regex(/^[a-f0-9]{64}$/)}).strict(),u=class extends Error{constructor(t,n,o,s){super(o);this.status=t;this.code=n;this.details=s;this.name="OpenPondLearningError"}status;code;details;static{d(this,"OpenPondLearningError")}},v=class{static{d(this,"OpenPondLearningClient")}#e;constructor(e){if(!e.apiKey.trim()||!e.scope.trim())throw new Error("Learning API key and scope are required.");let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("Learning base URL must be an HTTP(S) endpoint without credentials, query, or fragment.");this.#e={...e,baseUrl:t.toString().replace(/\/+$/,"")}}async command(e,t={}){ne(e);let n=oe.parse({scope:this.#e.scope,command:e}),o=se.parse(await this.#t("commands",n,t));if(o.operationId!==e.operationId)throw new u(502,"operation_identity_mismatch","Learning response did not match the submitted operation.",null);return o}submitExample(e,t={}){return this.command({action:"submit_example",operationId:e.idempotencyKey,example:e},t)}submitFeedback(e,t={}){return this.command({action:"submit_feedback",operationId:e.idempotencyKey,feedback:e},t)}async get(e,t,n,o={}){let s=P.parse({action:"get",scope:this.#e.scope,kind:e,id:t,...n===void 0?{}:{revision:n}});return H[e].parse(await this.#t("read",s,o))}async inspectEvidence(e,t={}){let n=P.parse({action:"inspect_evidence",scope:this.#e.scope,evidence:e}),o=re.parse(await this.#t("read",n,t));if(!M(o.evidence,e))throw new u(502,"evidence_identity_mismatch","Inspection did not match the requested evidence release.",null);return o}async inspectTaskQueue(e=null,t={}){let n=P.parse({action:"inspect_task_queue",scope:this.#e.scope,modelProjectId:e}),o=te.parse(await this.#t("read",n,t));if(o.modelProjectId!==e)throw new u(502,"model_identity_mismatch","Task queue did not match the requested Model.",null);return o}async inspectPolicy(e,t={}){let n=P.parse({action:"inspect_policy",scope:this.#e.scope,policy:e}),o=ee.parse(await this.#t("read",n,t));if(!M(o.policy,e))throw new u(502,"policy_identity_mismatch","Inspection did not match the requested policy release.",null);return o}async createSourceCredential(e,t={}){let n=E.parse({...e,action:"create",scope:this.#e.scope}),o=we.parse(await this.#t("credentials",n,t));if(this.#n(o.credential,e.sourceId),o.apiKey!==e.apiKey||!e.apiKey.startsWith(`${o.credential.keyPrefix}_`))throw new u(502,"credential_identity_mismatch","Credential response did not match the prepared credential.",null);return o}async listSourceCredentials(e,t={},n={}){let o=E.parse({...t,action:"list",scope:this.#e.scope,sourceId:e}),s=Pe.parse(await this.#t("credentials",o,n));if(s.items.length>(t.limit??30))throw new u(502,"credential_page_invalid","Credential response exceeded the requested page size.",null);for(let i of s.items)this.#n(i,e);return s}async revokeSourceCredential(e,t,n={}){let o=E.parse({action:"revoke",scope:this.#e.scope,sourceId:e,id:t}),s=j.parse(await this.#t("credentials",o,n));if(this.#n(s,e),s.id!==t||s.revokedAt===null)throw new u(502,"credential_revocation_mismatch","Credential revocation did not match the requested credential.",null);return s}async sourceConfiguration(e,t={}){let n=Oe.parse({scope:this.#e.scope,sourceId:e}),o=be.parse(await this.#t("source-config",n,t));if(o.scope!==this.#e.scope||o.source.id!==e)throw new u(502,"source_identity_mismatch","Source configuration did not match the requested source.",null);return o}#n(e,t){if(e.scope!==this.#e.scope||e.sourceId!==t)throw new u(502,"credential_scope_mismatch","Credential response did not match the requested source.",null)}async list(e,t={},n={}){let o=P.parse({action:"list",scope:this.#e.scope,kind:e,...t});return a.object({items:a.array(H[e]).max(100),nextCursor:a.string().nullable()}).strict().parse(await this.#t("read",o,n))}async publishBatch(e,t={}){let n=Be.parse(e),o=Ke.parse(await this.#t("publish-batch",{...n,scope:this.#e.scope},t));if(o.batchId!==n.batchId)throw new u(502,"batch_identity_mismatch","Published batch response did not match the requested batch.",null);return o}async#t(e,t,n){$(t,16777216);let o=await(this.#e.fetch??globalThis.fetch)(`${this.#e.baseUrl}/v1/learning/${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.#e.apiKey}`,"Content-Type":"application/json",Accept:"application/json","X-OpenPond-Team-Id":this.#e.scope},body:JSON.stringify(t),signal:n.signal,redirect:"error"}),s=await $e(o);if(!o.ok){let i=a.object({code:a.string().optional(),error:a.string().optional()}).passthrough().safeParse(s);throw new u(o.status,i.success?i.data.code??"learning_request_failed":"learning_request_failed",i.success?i.data.error??`Learning request failed (${o.status}).`:`Learning request failed (${o.status}).`,s)}return s}};async function $e(r){let t=r.body?.getReader();if(!t)throw new u(r.status,"empty_response","Learning response was empty.",null);let n=new TextDecoder,o=0,s="";try{for(;;){let p=await t.read();if(p.done)break;if(o+=p.value.byteLength,o>16777216)throw new u(r.status,"response_too_large","Learning response exceeded 16 MiB; request a smaller page.",null);s+=n.decode(p.value,{stream:!0})}s+=n.decode();let i=JSON.parse(s);return $(i,16777216),i}finally{await t.cancel(),t.releaseLock()}}d($e,"readBoundedLearningResponse");var X=class{static{d(this,"OpenPondClient")}sandboxes;work;workflows;actions;profileActions;learning;constructor(e){let t=e.apiKey?.trim()??"";if(!t&&(!e.sandbox||!e.model))throw new Error("OpenPond API key is required when using a default sandbox or model");let n=e.sandbox?{...e.sandbox,endpoint:N(e.sandbox.endpoint,"Sandbox endpoint"),apiKey:_(e.sandbox.apiKey,"Sandbox API key")}:void 0,o=e.model?{endpoint:N(e.model.endpoint,"Model endpoint"),apiKey:_(e.model.apiKey,"Model API key"),model:_(e.model.model,"Model ID")}:void 0,s=e.baseUrl?.trim()||"https://api.openpond.ai";this.learning=i=>new v({apiKey:t,baseUrl:s,scope:i}),this.sandboxes=Y({apiKey:n?.apiKey??t,baseUrl:s,sandboxApiUrl:n?.endpoint??e.sandboxApiUrl,customEndpoint:!!n}),this.work=new x({apiKey:o?.apiKey??t,apiBaseUrl:s,chatApiBaseUrl:o?.endpoint||e.chatApiUrl?.trim()||B({apiBaseUrl:s,env:{}}),sandboxes:this.sandboxes,sandboxConfig:n,defaultModel:o?.model,customModel:!!o}),this.workflows=new I({apiKey:t,apiBaseUrl:s}),this.actions=new R({apiKey:t,apiBaseUrl:s}),this.profileActions=new C({apiKey:t,apiBaseUrl:s})}};function Jt(r){return new X(r)}d(Jt,"createOpenPondClient");export{Jt as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as v,b as I}from"./chunk-GLUWATL5.js";import{Pa as L,Qa as E}from"./chunk-IFP6W4OW.js";import{f as w}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";var T=class extends Error{constructor(t,e){super(`API request timed out after ${t}ms: ${e}`);this.timeoutMs=t;this.requestUrl=e;this.name="ApiTimeoutError"}timeoutMs;requestUrl;static{a(this,"ApiTimeoutError")}code="OPENPOND_API_TIMEOUT"},S=class extends Error{constructor(t,e){super(`API response exceeded ${t} bytes: ${e}`);this.maximumBytes=t;this.requestUrl=e;this.name="ApiResponseTooLargeError"}maximumBytes;requestUrl;static{a(this,"ApiResponseTooLargeError")}code="OPENPOND_API_RESPONSE_TOO_LARGE"},O=class extends Error{constructor(t,e,s,r=null){let c=r||e;super(`${s} failed: ${t}${c?` ${c}`:""}`);this.status=t;this.apiMessage=r;this.name="OpenPondApiError",this.code=e||"OPENPOND_API_ERROR"}status;apiMessage;static{a(this,"OpenPondApiError")}code};async function i(o,n,t,e={}){let{timeoutMs:s=3e4,maxResponseBytes:r=8388608,explicitBearerAuth:c=!1,...p}=e,d=`${o}${t}`,m=new Headers(p.headers);m.set("Content-Type","application/json");let g=c?void 0:process.env.OPENPOND_API_KEY,h=n?.trim()||"",u=!c&&h.startsWith("opk_"),x=g||(u?h:null);x&&!m.has("openpond-api-key")&&m.set("openpond-api-key",x),n?m.set("Authorization",u?`ApiKey ${h}`:`Bearer ${n}`):g&&!m.has("Authorization")&&m.set("Authorization",`ApiKey ${g}`);let y=new AbortController,f=new T(s,d),R=s>0?setTimeout(()=>y.abort(f),s):null;R?.unref?.();let P=U(p.signal,y.signal,s),k=a(()=>{R&&clearTimeout(R)},"cleanup");try{let A=await fetch(d,{...p,headers:m,signal:P});return C(A,{cleanup:k,maximumBytes:r,requestUrl:d,timeoutController:y,timeoutError:f})}catch(A){throw k(),y.signal.aborted?f:A}}a(i,"apiFetch");async function l(o,n){let t;try{let e=await o.text();t=e?JSON.parse(e):{}}catch(e){if(e instanceof T||e instanceof S)throw e;t={}}if(!o.ok){let e=typeof t.error=="string"?t.error:null,s=typeof t.message=="string"?t.message:null;throw new O(o.status,e,n,s)}return t}a(l,"readApiJson");function C(o,n){if(!o.body)return n.cleanup(),o;let t=Number(o.headers.get("content-length"));if(n.maximumBytes>0&&Number.isFinite(t)&&t>n.maximumBytes)throw n.cleanup(),o.body.cancel(),new S(n.maximumBytes,n.requestUrl);let e=o.body.getReader(),s=0,r=new ReadableStream({async pull(c){try{let p=await e.read();if(p.done){n.cleanup(),c.close();return}if(s+=p.value.byteLength,n.maximumBytes>0&&s>n.maximumBytes){n.cleanup(),await e.cancel(),c.error(new S(n.maximumBytes,n.requestUrl));return}c.enqueue(p.value)}catch(p){n.cleanup(),c.error(n.timeoutController.signal.aborted?n.timeoutError:p)}},async cancel(c){n.cleanup(),await e.cancel(c)}});return new Response(r,{headers:o.headers,status:o.status,statusText:o.statusText})}a(C,"boundedResponse");function U(o,n,t){return t<=0?o??void 0:o?AbortSignal.any([o,n]):n}a(U,"composedSignal");async function _(o,n,t,e,s){let r=await i(o,n,`/v4/apps/${t}/commits`,{method:"POST",body:JSON.stringify({files:e,message:s})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Commit failed: ${r.status} ${c}`)}return await r.json()}a(_,"commitFiles");async function j(o,n,t,e){let s=e?.environment??"production",r=await i(o,n,`/v4/apps/${t}/deployments`,{method:"POST",body:JSON.stringify({environment:s,...e?.commitSha?{commitSha:e.commitSha}:{},...e?.branch?{branch:e.branch}:{}})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Deploy failed: ${r.status} ${c}`)}return await r.json()}a(j,"deployApp");async function B(o,n,t,e){let s=await i(o,n,`/v4/apps/${encodeURIComponent(t)}/deployments/promote-preview`,{method:"POST",body:JSON.stringify(e)});return l(s,"Preview promotion")}a(B,"promotePreviewToProduction");async function G(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/lifecycle/start`,{method:"POST",body:JSON.stringify(e)});return l(s,"App lifecycle start")}a(G,"startAppLifecycle");async function J(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/logs`,{method:"GET"});if(!e.ok){let c=await e.text().catch(()=>"");throw new Error(`Deployment logs failed: ${e.status} ${c}`)}let s=await e.json().catch(()=>({}));return(Array.isArray(s.logs)?s.logs:[]).map(c=>{let p=typeof c.createdAt=="string"?c.createdAt:c.createdAt instanceof Date?c.createdAt.toISOString():new Date().toISOString();return{id:typeof c.id=="string"?c.id:`${Math.random()}`,type:typeof c.type=="string"?c.type:void 0,message:typeof c.message=="string"?c.message:"",createdAt:p}})}a(J,"getDeploymentLogs");async function M(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/status`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment status failed: ${e.status} ${r}`)}return{status:(await e.json().catch(()=>({}))).deployment?.status}}a(M,"getDeploymentStatus");async function F(o,n,t,e){let s=new URLSearchParams;e?.status&&e.status.length>0&&s.set("status",e.status.join(",")),e?.createdAfter&&s.set("createdAfter",e.createdAfter),e?.branch&&s.set("branch",e.branch);let r=s.toString(),c=await i(o,n,`/apps/${t}/deployments/latest${r?`?${r}`:""}`,{method:"GET"});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`Latest deployment lookup failed: ${c.status} ${d}`)}let p=await c.json().catch(()=>({}));return p.deployment?{id:p.deployment.id,status:p.deployment.status}:null}a(F,"getLatestDeploymentForApp");async function H(o,n,t){let e=await i(o,n,`/apps/deployments/${t}`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment fetch failed: ${e.status} ${r}`)}return(await e.json().catch(()=>({}))).deployment??null}a(H,"getDeploymentDetail");var V=new URL(I).hostname,D=new URL(v).hostname;async function ae(o,n,t){let e=new URLSearchParams;t?.handle&&e.set("handle",t.handle),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&e.set("limit",String(Math.max(1,Math.floor(t.limit)))),typeof t?.offset=="number"&&Number.isFinite(t.offset)&&e.set("offset",String(Math.max(0,Math.floor(t.offset)))),typeof t?.includeScheduled=="boolean"&&e.set("includeScheduled",t.includeScheduled?"true":"false");let s=e.toString(),r=await i(o,n,`/apps/list${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let p=await r.text().catch(()=>"");throw new Error(`Apps list failed: ${r.status} ${p}`)}let c=await r.json().catch(()=>({}));return Array.isArray(c.apps)?c.apps:[]}a(ae,"listApps");async function ie(o,n,t){let e=await i(o,n,"/api/projects/local",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Create project failed: ${e.status} ${s}`)}return await e.json()}a(ie,"createLocalProject");async function ce(o,n,t){let e=await i(o,n,"/apps/repo/create",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Repo create failed: ${e.status} ${s}`)}return await e.json()}a(ce,"createRepo");async function pe(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/code-visibility`,{method:"PATCH",body:JSON.stringify({codeVisibility:e})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Code visibility update failed: ${s.status} ${r}`)}return await s.json()}a(pe,"updateAppCodeVisibility");async function ue(o,n,t,e){let s=await i(o,n,"/v4/apps/headless",{method:"POST",body:JSON.stringify({items:t,...e?{teamId:e}:{}})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Headless create failed: ${s.status} ${r}`)}return await s.json()}a(ue,"createHeadlessApps");async function le(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/status`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template status failed: ${e.status} ${s}`)}return await e.json()}a(le,"getTemplateStatus");async function de(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/branches`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template branches failed: ${e.status} ${s}`)}return await e.json()}a(de,"listTemplateBranches");async function me(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/template/deploy-latest`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Template deploy failed: ${s.status} ${r}`)}return await s.json()}a(me,"deployLatestTemplate");async function ge(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/environment`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Environment update failed: ${s.status} ${r}`)}return await s.json()}a(ge,"updateAppEnvironment");async function he(o,n,t){let e=await i(o,n,`/v4/apps/${t}/environment`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Environment get failed: ${e.status} ${s}`)}return await e.json()}a(he,"getAppEnvironment");async function ye(o,n){let t=await i(o,n,"/api/tools/manifest",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Manifest fetch failed: ${t.status} ${e}`)}return await t.json()}a(ye,"fetchToolManifest");async function fe(o,n){let t=await i(o,n,"/apps/tools",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Tools lookup failed: ${t.status} ${e}`)}return await t.json()}a(fe,"listUserTools");async function Re(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Schedules lookup failed: ${e.status} ${r}`)}let s=await e.json().catch(()=>({}));return{schedules:Array.isArray(s.schedules)?s.schedules:[]}}a(Re,"listAppSchedules");async function we(o,n,t={}){let e=new URLSearchParams;t.domain&&e.set("domain",t.domain),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion),typeof t.limit=="number"&&e.set("limit",String(t.limit));for(let c of t.tags??[])e.append("tag",c);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe list")}a(we,"listOpenToolRecipes");async function Se(o,n,t){let e=await i(o,n,"/v1/opentool/recipes/search",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool recipe search")}a(Se,"searchOpenToolRecipes");async function xe(o,n,t){let e=new URLSearchParams;typeof t.includeExamples=="boolean"&&e.set("includeExamples",String(t.includeExamples)),typeof t.includeTests=="boolean"&&e.set("includeTests",String(t.includeTests)),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes/${encodeURIComponent(t.id)}${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe get")}a(xe,"getOpenToolRecipe");async function Te(o,n,t){let e=await i(o,n,"/v1/opentool/rules",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool rules get")}a(Te,"getOpenToolRules");function b(o){let n=new URLSearchParams;typeof o=="number"&&Number.isFinite(o)&&n.set("limit",String(Math.max(1,Math.floor(o))));let t=n.toString();return t?`?${t}`:""}a(b,"buildLimitQuery");function N(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];let n=o;return Array.isArray(n.logs)?n.logs:Array.isArray(n.runs)?n.runs:Array.isArray(n.scheduleRuns)?n.scheduleRuns:Array.isArray(n.items)?n.items:[]}a(N,"normalizeScheduleExecutionLogs");async function Pe(o,n,t,e){let s={...e?.preferredScheduleId?{preferredScheduleId:e.preferredScheduleId}:{},...e?.scheduleId?{scheduleId:e.scheduleId}:{},...e?.startAt?{startAt:e.startAt}:{},...e&&"endAt"in e?{endAt:e.endAt??null}:{}},r=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/start`,{method:"POST",body:JSON.stringify(s)});return l(r,"Schedule start")}a(Pe,"startAppSchedules");async function Ae(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/stop`,{method:"POST",body:JSON.stringify({})});return l(e,"Schedule stop")}a(Ae,"stopAppSchedules");async function Ee(o,n){let t=await i(o,n,"/apps/schedules/current/stop",{method:"POST",body:JSON.stringify({})});return l(t,"Current schedule stop")}a(Ee,"stopCurrentAppSchedules");async function Oe(o,n,t){let e=await i(o,n,"/v1/schedules/run",{method:"POST",body:JSON.stringify({scheduleId:t.scheduleId})});return l(e,"Schedule run")}a(Oe,"runScheduleNow");async function be(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/${encodeURIComponent(e)}`,{method:"DELETE"});return l(s,"Schedule delete")}a(be,"deleteOrArchiveSchedule");async function $e(o,n,t,e){let s=await i(o,n,`/v1/schedules/${encodeURIComponent(t)}/execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Schedule execution logs");return{logs:N(r)}}a($e,"listScheduleExecutionLogs");async function ke(o,n,t,e){let s=await i(o,n,`/v1/deployments/${encodeURIComponent(t)}/schedule-execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Deployment schedule execution logs");return{logs:N(r)}}a(ke,"listDeploymentScheduleExecutionLogs");async function Le(o,n,t){let e=await i(o,n,`/v1/schedule-execution-logs/${encodeURIComponent(t)}`,{method:"GET"});return l(e,"Schedule execution log")}a(Le,"getScheduleExecutionLog");async function ve(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/execution-timeline${b(e?.limit)}`,{method:"GET"});return l(s,"App execution timeline")}a(ve,"getAppExecutionTimeline");async function Ie(o,n,t){return i(o,n,"/apps/agent/create",{method:"POST",body:JSON.stringify(t)})}a(Ie,"createAgentFromPrompt");async function De(o,n,t){let e=new URLSearchParams;t?.appId&&e.set("appId",t.appId);let s=e.toString(),r=await i(o,n,`/apps/performance${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Performance lookup failed: ${r.status} ${c}`)}return await r.json()}a(De,"getUserPerformance");async function Ne(o,n,t){let e=new URLSearchParams({appId:t}),s=await i(o,n,`/apps/summary?${e.toString()}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Summary lookup failed: ${s.status} ${r}`)}return await s.json()}a(Ne,"getAppRuntimeSummary");async function z(o,n){let t=await i(o,n,"/v1/account",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Account lookup failed: ${t.status} ${e}`)}return await t.json()}a(z,"getOpenPondAccount");async function qe(o,n){let t=new Date().toISOString(),e=Date.now(),s=o.replace(/\/$/,"");try{let r=await i(s,null,"/health",{method:"GET",headers:{Accept:"application/json"}}),c=Date.now()-e,p=await r.json().catch(()=>({})),d=null,m=null;if(n?.trim())try{let g=await z(s,n);d=!0,m=g.account}catch{d=!1}return{reachable:r.ok,authenticated:d,apiBase:s,latencyMs:c,status:r.status,service:typeof p.service=="string"?p.service:null,checkedAt:t,account:m,...r.ok?{}:{error:r.statusText||`HTTP ${r.status}`}}}catch(r){return{reachable:!1,authenticated:n?.trim()?!1:null,apiBase:s,latencyMs:Date.now()-e,status:null,service:null,checkedAt:t,error:r instanceof Error?r.message:String(r)}}}a(qe,"checkOpenPondApiHealth");async function Ce(o,n,t){let e=await i(o,n,"/apps/assistant/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Assistant run failed: ${e.status} ${s}`)}return await e.json()}a(Ce,"runAssistantMode");async function Ue(o,n,t){let e=await i(o,n,"/apps/agent/digest",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Agent digest failed: ${e.status} ${s}`)}return await e.json()}a(Ue,"postAgentDigest");async function _e(o,n,t){let e=await i(o,n,"/apps/tools/execute",{method:"POST",body:JSON.stringify(t)}),s=await e.text().catch(()=>""),r=null;try{r=s?JSON.parse(s):null}catch{r=s}return e.ok?{ok:!0,status:e.status,data:r}:{ok:!1,status:e.status,error:r&&typeof r=="object"&&"error"in r?String(r.error):s||e.statusText}}a(_e,"executeUserTool");async function je(o,n,t){let e=await i(o,n,"/apps/backtests/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Backtest run failed: ${e.status} ${s}`)}return await e.json()}a(je,"submitBacktestRun");async function Be(o,n,t){let e=t.query&&Object.keys(t.query).length>0?`?${new URLSearchParams(t.query).toString()}`:"",s=await i(o,n,`/apps/backtests/tx${e}`,{method:t.method,body:t.method==="POST"&&t.body!==void 0?JSON.stringify(t.body):void 0});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtests request failed: ${s.status} ${r}`)}return await s.json()}a(Be,"submitBacktestTx");async function Ge(o,n,t){let e=new URLSearchParams(t).toString(),s=await i(o,n,`/apps/backtests/detail?${e}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtest detail failed: ${s.status} ${r}`)}return await s.json()}a(Ge,"submitBacktestDetail");function K(o){let n=o.trim().replace(/^\/+/,"");return encodeURIComponent(n||"tool")}a(K,"normalizeToolPathSegment");function W(o){let n=o.replace(/\/$/,""),t=process.env.OPENPOND_TOOL_URL;if(t)return t.replace(/\/$/,"");try{let e=new URL(n),s=e.hostname.toLowerCase(),r=s==="apps.openpond.live"?null:s===V||s===D||s===`www.${D}`||s==="openpond.live"||s==="www.openpond.live"?"https://apps.openpond.live":null;if(r)return r;let c=s==="localhost"||s==="127.0.0.1",p=e.port||(e.protocol==="https:"?"443":"80");if(c&&p==="3000")return n}catch{}return n}a(W,"resolveWorkerBaseUrl");async function Je(o,n,t){let e=W(o),s=K(t.toolName),c=`${t.deploymentId?`/${t.appId}/deployments/${t.deploymentId}`:`/${t.appId}`}/${s}`,p=new Headers(t.headers||{}),d=t.method??"POST",m=t.body===void 0||d==="GET"?void 0:JSON.stringify(t.body),g=await i(e,n,c,{method:d,body:m,headers:p}),h=await g.text().catch(()=>""),u=null;try{u=h?JSON.parse(h):null}catch{u=h}let x=u&&typeof u=="object"&&"ok"in u?!!u.ok:!0,y=g.ok&&x,f=u&&typeof u=="object"&&"status"in u&&Number(u.status)||g.status,R=u&&typeof u=="object"&&"error"in u?String(u.error):g.ok?void 0:h||g.statusText,P=u&&typeof u=="object"&&"data"in u?u.data:u;return{ok:y,status:f,data:P,error:R}}a(Je,"executeHostedTool");import{createHash as Y}from"node:crypto";var X=3600*1e3;function $(o){return Y("sha256").update(JSON.stringify([o.apiBase.replace(/\/$/,""),o.apiKey.trim()])).digest("hex")}a($,"buildCacheKey");async function q(o,n){let t=await L(w(),o,$(n),{allowStale:!0});return!t||Date.now()-Date.parse(t.updatedAt)>=(n.ttlMs??X)?null:t.payload}a(q,"cached");async function ot(o){return q("cloud.apps",o)}a(ot,"getCachedApps");async function st(o){await E(w(),"cloud.apps",$(o),o.apps)}a(st,"setCachedApps");async function rt(o){return q("cloud.tools",o)}a(rt,"getCachedTools");async function at(o){await E(w(),"cloud.tools",$(o),o.tools)}a(at,"setCachedTools");var pt=["openpond-generic-v1","openpond-work-v1","openpond-coding-core-v1","openpond-agent-harness-v1"];export{i as a,_ as b,j as c,B as d,G as e,J as f,M as g,F as h,H as i,ae as j,ie as k,ce as l,pe as m,ue as n,le as o,de as p,me as q,ge as r,he as s,ye as t,fe as u,Re as v,we as w,Se as x,xe as y,Te as z,Pe as A,Ae as B,Ee as C,Oe as D,be as E,$e as F,ke as G,Le as H,ve as I,Ie as J,De as K,Ne as L,z as M,qe as N,Ce as O,Ue as P,_e as Q,je as R,Be as S,Ge as T,W as U,Je as V,X as W,ot as X,st as Y,rt as Z,at as _,pt as $};
2
+ import{a as v,b as I}from"./chunk-GLUWATL5.js";import{ya as L,za as E}from"./chunk-L6NNQUAT.js";import{f as w}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";var T=class extends Error{constructor(t,e){super(`API request timed out after ${t}ms: ${e}`);this.timeoutMs=t;this.requestUrl=e;this.name="ApiTimeoutError"}timeoutMs;requestUrl;static{a(this,"ApiTimeoutError")}code="OPENPOND_API_TIMEOUT"},S=class extends Error{constructor(t,e){super(`API response exceeded ${t} bytes: ${e}`);this.maximumBytes=t;this.requestUrl=e;this.name="ApiResponseTooLargeError"}maximumBytes;requestUrl;static{a(this,"ApiResponseTooLargeError")}code="OPENPOND_API_RESPONSE_TOO_LARGE"},O=class extends Error{constructor(t,e,s,r=null){let c=r||e;super(`${s} failed: ${t}${c?` ${c}`:""}`);this.status=t;this.apiMessage=r;this.name="OpenPondApiError",this.code=e||"OPENPOND_API_ERROR"}status;apiMessage;static{a(this,"OpenPondApiError")}code};async function i(o,n,t,e={}){let{timeoutMs:s=3e4,maxResponseBytes:r=8388608,explicitBearerAuth:c=!1,...p}=e,d=`${o}${t}`,m=new Headers(p.headers);m.set("Content-Type","application/json");let g=c?void 0:process.env.OPENPOND_API_KEY,h=n?.trim()||"",u=!c&&h.startsWith("opk_"),x=g||(u?h:null);x&&!m.has("openpond-api-key")&&m.set("openpond-api-key",x),n?m.set("Authorization",u?`ApiKey ${h}`:`Bearer ${n}`):g&&!m.has("Authorization")&&m.set("Authorization",`ApiKey ${g}`);let y=new AbortController,f=new T(s,d),R=s>0?setTimeout(()=>y.abort(f),s):null;R?.unref?.();let P=U(p.signal,y.signal,s),k=a(()=>{R&&clearTimeout(R)},"cleanup");try{let A=await fetch(d,{...p,headers:m,signal:P});return C(A,{cleanup:k,maximumBytes:r,requestUrl:d,timeoutController:y,timeoutError:f})}catch(A){throw k(),y.signal.aborted?f:A}}a(i,"apiFetch");async function l(o,n){let t;try{let e=await o.text();t=e?JSON.parse(e):{}}catch(e){if(e instanceof T||e instanceof S)throw e;t={}}if(!o.ok){let e=typeof t.error=="string"?t.error:null,s=typeof t.message=="string"?t.message:null;throw new O(o.status,e,n,s)}return t}a(l,"readApiJson");function C(o,n){if(!o.body)return n.cleanup(),o;let t=Number(o.headers.get("content-length"));if(n.maximumBytes>0&&Number.isFinite(t)&&t>n.maximumBytes)throw n.cleanup(),o.body.cancel(),new S(n.maximumBytes,n.requestUrl);let e=o.body.getReader(),s=0,r=new ReadableStream({async pull(c){try{let p=await e.read();if(p.done){n.cleanup(),c.close();return}if(s+=p.value.byteLength,n.maximumBytes>0&&s>n.maximumBytes){n.cleanup(),await e.cancel(),c.error(new S(n.maximumBytes,n.requestUrl));return}c.enqueue(p.value)}catch(p){n.cleanup(),c.error(n.timeoutController.signal.aborted?n.timeoutError:p)}},async cancel(c){n.cleanup(),await e.cancel(c)}});return new Response(r,{headers:o.headers,status:o.status,statusText:o.statusText})}a(C,"boundedResponse");function U(o,n,t){return t<=0?o??void 0:o?AbortSignal.any([o,n]):n}a(U,"composedSignal");async function _(o,n,t,e,s){let r=await i(o,n,`/v4/apps/${t}/commits`,{method:"POST",body:JSON.stringify({files:e,message:s})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Commit failed: ${r.status} ${c}`)}return await r.json()}a(_,"commitFiles");async function j(o,n,t,e){let s=e?.environment??"production",r=await i(o,n,`/v4/apps/${t}/deployments`,{method:"POST",body:JSON.stringify({environment:s,...e?.commitSha?{commitSha:e.commitSha}:{},...e?.branch?{branch:e.branch}:{}})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Deploy failed: ${r.status} ${c}`)}return await r.json()}a(j,"deployApp");async function B(o,n,t,e){let s=await i(o,n,`/v4/apps/${encodeURIComponent(t)}/deployments/promote-preview`,{method:"POST",body:JSON.stringify(e)});return l(s,"Preview promotion")}a(B,"promotePreviewToProduction");async function G(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/lifecycle/start`,{method:"POST",body:JSON.stringify(e)});return l(s,"App lifecycle start")}a(G,"startAppLifecycle");async function J(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/logs`,{method:"GET"});if(!e.ok){let c=await e.text().catch(()=>"");throw new Error(`Deployment logs failed: ${e.status} ${c}`)}let s=await e.json().catch(()=>({}));return(Array.isArray(s.logs)?s.logs:[]).map(c=>{let p=typeof c.createdAt=="string"?c.createdAt:c.createdAt instanceof Date?c.createdAt.toISOString():new Date().toISOString();return{id:typeof c.id=="string"?c.id:`${Math.random()}`,type:typeof c.type=="string"?c.type:void 0,message:typeof c.message=="string"?c.message:"",createdAt:p}})}a(J,"getDeploymentLogs");async function M(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/status`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment status failed: ${e.status} ${r}`)}return{status:(await e.json().catch(()=>({}))).deployment?.status}}a(M,"getDeploymentStatus");async function F(o,n,t,e){let s=new URLSearchParams;e?.status&&e.status.length>0&&s.set("status",e.status.join(",")),e?.createdAfter&&s.set("createdAfter",e.createdAfter),e?.branch&&s.set("branch",e.branch);let r=s.toString(),c=await i(o,n,`/apps/${t}/deployments/latest${r?`?${r}`:""}`,{method:"GET"});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`Latest deployment lookup failed: ${c.status} ${d}`)}let p=await c.json().catch(()=>({}));return p.deployment?{id:p.deployment.id,status:p.deployment.status}:null}a(F,"getLatestDeploymentForApp");async function H(o,n,t){let e=await i(o,n,`/apps/deployments/${t}`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment fetch failed: ${e.status} ${r}`)}return(await e.json().catch(()=>({}))).deployment??null}a(H,"getDeploymentDetail");var V=new URL(I).hostname,D=new URL(v).hostname;async function ae(o,n,t){let e=new URLSearchParams;t?.handle&&e.set("handle",t.handle),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&e.set("limit",String(Math.max(1,Math.floor(t.limit)))),typeof t?.offset=="number"&&Number.isFinite(t.offset)&&e.set("offset",String(Math.max(0,Math.floor(t.offset)))),typeof t?.includeScheduled=="boolean"&&e.set("includeScheduled",t.includeScheduled?"true":"false");let s=e.toString(),r=await i(o,n,`/apps/list${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let p=await r.text().catch(()=>"");throw new Error(`Apps list failed: ${r.status} ${p}`)}let c=await r.json().catch(()=>({}));return Array.isArray(c.apps)?c.apps:[]}a(ae,"listApps");async function ie(o,n,t){let e=await i(o,n,"/api/projects/local",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Create project failed: ${e.status} ${s}`)}return await e.json()}a(ie,"createLocalProject");async function ce(o,n,t){let e=await i(o,n,"/apps/repo/create",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Repo create failed: ${e.status} ${s}`)}return await e.json()}a(ce,"createRepo");async function pe(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/code-visibility`,{method:"PATCH",body:JSON.stringify({codeVisibility:e})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Code visibility update failed: ${s.status} ${r}`)}return await s.json()}a(pe,"updateAppCodeVisibility");async function ue(o,n,t,e){let s=await i(o,n,"/v4/apps/headless",{method:"POST",body:JSON.stringify({items:t,...e?{teamId:e}:{}})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Headless create failed: ${s.status} ${r}`)}return await s.json()}a(ue,"createHeadlessApps");async function le(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/status`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template status failed: ${e.status} ${s}`)}return await e.json()}a(le,"getTemplateStatus");async function de(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/branches`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template branches failed: ${e.status} ${s}`)}return await e.json()}a(de,"listTemplateBranches");async function me(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/template/deploy-latest`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Template deploy failed: ${s.status} ${r}`)}return await s.json()}a(me,"deployLatestTemplate");async function ge(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/environment`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Environment update failed: ${s.status} ${r}`)}return await s.json()}a(ge,"updateAppEnvironment");async function he(o,n,t){let e=await i(o,n,`/v4/apps/${t}/environment`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Environment get failed: ${e.status} ${s}`)}return await e.json()}a(he,"getAppEnvironment");async function ye(o,n){let t=await i(o,n,"/api/tools/manifest",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Manifest fetch failed: ${t.status} ${e}`)}return await t.json()}a(ye,"fetchToolManifest");async function fe(o,n){let t=await i(o,n,"/apps/tools",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Tools lookup failed: ${t.status} ${e}`)}return await t.json()}a(fe,"listUserTools");async function Re(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Schedules lookup failed: ${e.status} ${r}`)}let s=await e.json().catch(()=>({}));return{schedules:Array.isArray(s.schedules)?s.schedules:[]}}a(Re,"listAppSchedules");async function we(o,n,t={}){let e=new URLSearchParams;t.domain&&e.set("domain",t.domain),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion),typeof t.limit=="number"&&e.set("limit",String(t.limit));for(let c of t.tags??[])e.append("tag",c);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe list")}a(we,"listOpenToolRecipes");async function Se(o,n,t){let e=await i(o,n,"/v1/opentool/recipes/search",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool recipe search")}a(Se,"searchOpenToolRecipes");async function xe(o,n,t){let e=new URLSearchParams;typeof t.includeExamples=="boolean"&&e.set("includeExamples",String(t.includeExamples)),typeof t.includeTests=="boolean"&&e.set("includeTests",String(t.includeTests)),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes/${encodeURIComponent(t.id)}${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe get")}a(xe,"getOpenToolRecipe");async function Te(o,n,t){let e=await i(o,n,"/v1/opentool/rules",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool rules get")}a(Te,"getOpenToolRules");function b(o){let n=new URLSearchParams;typeof o=="number"&&Number.isFinite(o)&&n.set("limit",String(Math.max(1,Math.floor(o))));let t=n.toString();return t?`?${t}`:""}a(b,"buildLimitQuery");function N(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];let n=o;return Array.isArray(n.logs)?n.logs:Array.isArray(n.runs)?n.runs:Array.isArray(n.scheduleRuns)?n.scheduleRuns:Array.isArray(n.items)?n.items:[]}a(N,"normalizeScheduleExecutionLogs");async function Pe(o,n,t,e){let s={...e?.preferredScheduleId?{preferredScheduleId:e.preferredScheduleId}:{},...e?.scheduleId?{scheduleId:e.scheduleId}:{},...e?.startAt?{startAt:e.startAt}:{},...e&&"endAt"in e?{endAt:e.endAt??null}:{}},r=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/start`,{method:"POST",body:JSON.stringify(s)});return l(r,"Schedule start")}a(Pe,"startAppSchedules");async function Ae(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/stop`,{method:"POST",body:JSON.stringify({})});return l(e,"Schedule stop")}a(Ae,"stopAppSchedules");async function Ee(o,n){let t=await i(o,n,"/apps/schedules/current/stop",{method:"POST",body:JSON.stringify({})});return l(t,"Current schedule stop")}a(Ee,"stopCurrentAppSchedules");async function Oe(o,n,t){let e=await i(o,n,"/v1/schedules/run",{method:"POST",body:JSON.stringify({scheduleId:t.scheduleId})});return l(e,"Schedule run")}a(Oe,"runScheduleNow");async function be(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/${encodeURIComponent(e)}`,{method:"DELETE"});return l(s,"Schedule delete")}a(be,"deleteOrArchiveSchedule");async function $e(o,n,t,e){let s=await i(o,n,`/v1/schedules/${encodeURIComponent(t)}/execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Schedule execution logs");return{logs:N(r)}}a($e,"listScheduleExecutionLogs");async function ke(o,n,t,e){let s=await i(o,n,`/v1/deployments/${encodeURIComponent(t)}/schedule-execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Deployment schedule execution logs");return{logs:N(r)}}a(ke,"listDeploymentScheduleExecutionLogs");async function Le(o,n,t){let e=await i(o,n,`/v1/schedule-execution-logs/${encodeURIComponent(t)}`,{method:"GET"});return l(e,"Schedule execution log")}a(Le,"getScheduleExecutionLog");async function ve(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/execution-timeline${b(e?.limit)}`,{method:"GET"});return l(s,"App execution timeline")}a(ve,"getAppExecutionTimeline");async function Ie(o,n,t){return i(o,n,"/apps/agent/create",{method:"POST",body:JSON.stringify(t)})}a(Ie,"createAgentFromPrompt");async function De(o,n,t){let e=new URLSearchParams;t?.appId&&e.set("appId",t.appId);let s=e.toString(),r=await i(o,n,`/apps/performance${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Performance lookup failed: ${r.status} ${c}`)}return await r.json()}a(De,"getUserPerformance");async function Ne(o,n,t){let e=new URLSearchParams({appId:t}),s=await i(o,n,`/apps/summary?${e.toString()}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Summary lookup failed: ${s.status} ${r}`)}return await s.json()}a(Ne,"getAppRuntimeSummary");async function z(o,n){let t=await i(o,n,"/v1/account",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Account lookup failed: ${t.status} ${e}`)}return await t.json()}a(z,"getOpenPondAccount");async function qe(o,n){let t=new Date().toISOString(),e=Date.now(),s=o.replace(/\/$/,"");try{let r=await i(s,null,"/health",{method:"GET",headers:{Accept:"application/json"}}),c=Date.now()-e,p=await r.json().catch(()=>({})),d=null,m=null;if(n?.trim())try{let g=await z(s,n);d=!0,m=g.account}catch{d=!1}return{reachable:r.ok,authenticated:d,apiBase:s,latencyMs:c,status:r.status,service:typeof p.service=="string"?p.service:null,checkedAt:t,account:m,...r.ok?{}:{error:r.statusText||`HTTP ${r.status}`}}}catch(r){return{reachable:!1,authenticated:n?.trim()?!1:null,apiBase:s,latencyMs:Date.now()-e,status:null,service:null,checkedAt:t,error:r instanceof Error?r.message:String(r)}}}a(qe,"checkOpenPondApiHealth");async function Ce(o,n,t){let e=await i(o,n,"/apps/assistant/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Assistant run failed: ${e.status} ${s}`)}return await e.json()}a(Ce,"runAssistantMode");async function Ue(o,n,t){let e=await i(o,n,"/apps/agent/digest",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Agent digest failed: ${e.status} ${s}`)}return await e.json()}a(Ue,"postAgentDigest");async function _e(o,n,t){let e=await i(o,n,"/apps/tools/execute",{method:"POST",body:JSON.stringify(t)}),s=await e.text().catch(()=>""),r=null;try{r=s?JSON.parse(s):null}catch{r=s}return e.ok?{ok:!0,status:e.status,data:r}:{ok:!1,status:e.status,error:r&&typeof r=="object"&&"error"in r?String(r.error):s||e.statusText}}a(_e,"executeUserTool");async function je(o,n,t){let e=await i(o,n,"/apps/backtests/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Backtest run failed: ${e.status} ${s}`)}return await e.json()}a(je,"submitBacktestRun");async function Be(o,n,t){let e=t.query&&Object.keys(t.query).length>0?`?${new URLSearchParams(t.query).toString()}`:"",s=await i(o,n,`/apps/backtests/tx${e}`,{method:t.method,body:t.method==="POST"&&t.body!==void 0?JSON.stringify(t.body):void 0});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtests request failed: ${s.status} ${r}`)}return await s.json()}a(Be,"submitBacktestTx");async function Ge(o,n,t){let e=new URLSearchParams(t).toString(),s=await i(o,n,`/apps/backtests/detail?${e}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtest detail failed: ${s.status} ${r}`)}return await s.json()}a(Ge,"submitBacktestDetail");function K(o){let n=o.trim().replace(/^\/+/,"");return encodeURIComponent(n||"tool")}a(K,"normalizeToolPathSegment");function W(o){let n=o.replace(/\/$/,""),t=process.env.OPENPOND_TOOL_URL;if(t)return t.replace(/\/$/,"");try{let e=new URL(n),s=e.hostname.toLowerCase(),r=s==="apps.openpond.live"?null:s===V||s===D||s===`www.${D}`||s==="openpond.live"||s==="www.openpond.live"?"https://apps.openpond.live":null;if(r)return r;let c=s==="localhost"||s==="127.0.0.1",p=e.port||(e.protocol==="https:"?"443":"80");if(c&&p==="3000")return n}catch{}return n}a(W,"resolveWorkerBaseUrl");async function Je(o,n,t){let e=W(o),s=K(t.toolName),c=`${t.deploymentId?`/${t.appId}/deployments/${t.deploymentId}`:`/${t.appId}`}/${s}`,p=new Headers(t.headers||{}),d=t.method??"POST",m=t.body===void 0||d==="GET"?void 0:JSON.stringify(t.body),g=await i(e,n,c,{method:d,body:m,headers:p}),h=await g.text().catch(()=>""),u=null;try{u=h?JSON.parse(h):null}catch{u=h}let x=u&&typeof u=="object"&&"ok"in u?!!u.ok:!0,y=g.ok&&x,f=u&&typeof u=="object"&&"status"in u&&Number(u.status)||g.status,R=u&&typeof u=="object"&&"error"in u?String(u.error):g.ok?void 0:h||g.statusText,P=u&&typeof u=="object"&&"data"in u?u.data:u;return{ok:y,status:f,data:P,error:R}}a(Je,"executeHostedTool");import{createHash as Y}from"node:crypto";var X=3600*1e3;function $(o){return Y("sha256").update(JSON.stringify([o.apiBase.replace(/\/$/,""),o.apiKey.trim()])).digest("hex")}a($,"buildCacheKey");async function q(o,n){let t=await L(w(),o,$(n),{allowStale:!0});return!t||Date.now()-Date.parse(t.updatedAt)>=(n.ttlMs??X)?null:t.payload}a(q,"cached");async function ot(o){return q("cloud.apps",o)}a(ot,"getCachedApps");async function st(o){await E(w(),"cloud.apps",$(o),o.apps)}a(st,"setCachedApps");async function rt(o){return q("cloud.tools",o)}a(rt,"getCachedTools");async function at(o){await E(w(),"cloud.tools",$(o),o.tools)}a(at,"setCachedTools");var pt=["openpond-generic-v1","openpond-work-v1","openpond-coding-core-v1","openpond-agent-harness-v1"];export{i as a,_ as b,j as c,B as d,G as e,J as f,M as g,F as h,H as i,ae as j,ie as k,ce as l,pe as m,ue as n,le as o,de as p,me as q,ge as r,he as s,ye as t,fe as u,Re as v,we as w,Se as x,xe as y,Te as z,Pe as A,Ae as B,Ee as C,Oe as D,be as E,$e as F,ke as G,Le as H,ve as I,Ie as J,De as K,Ne as L,z as M,qe as N,Ce as O,Ue as P,_e as Q,je as R,Be as S,Ge as T,W as U,Je as V,X as W,ot as X,st as Y,rt as Z,at as _,pt as $};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{j as y}from"./chunk-I6DQSOSF.js";import{E as u,J as j,K as E}from"./chunk-PKBU37CH.js";import{Ga as R,Ja as M,Ka as O,Qa as w}from"./chunk-BLXEK5F7.js";import{Ba as U}from"./chunk-QUNRWDVO.js";import{c as I,e as h,f as b,g as x,i as H,kb as k}from"./chunk-L6NNQUAT.js";import{b as i}from"./chunk-ES2ISFJC.js";import{a as f,c as v,f as S,h as l}from"./chunk-H7IWJN7L.js";import{a as n}from"./chunk-FTQLQJQV.js";import m from"node:path";import{AsyncLocalStorage as J}from"node:async_hooks";import{promises as C}from"node:fs";var T=new J;function Z(r,e=!1){let t=T.getStore();t&&(e&&(t.length=0),t.push(r))}n(Z,"onStartupFailure");async function ee(r,e){await k(r);let t;try{t=await x(m.join(l(r).runtime,"server-owner"),100)}catch(s){if(s instanceof v&&s.issue.code==="STORAGE_BUSY"){let a=await H(m.join(l(r).runtime,"endpoint.json"),()=>null);throw new v({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw s}let o=[];try{let s=await f(r,()=>T.run(o,e)),a=s.close.bind(s);o.length=0;let d;return{...s,close:n(()=>d??=(async()=>{try{await f(r,a)}finally{await C.rm(m.join(l(r).runtime,"endpoint.json"),{force:!0}),await t()}})(),"close")}}catch(s){try{for(let a of o.reverse())await Promise.resolve().then(()=>f(r,a)).catch(()=>{});await C.rm(m.join(l(r).runtime,"endpoint.json"),{force:!0})}finally{await t()}throw s}}n(ee,"ownHomeRuntime");async function te(r,e,t){await h(m.join(l(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:e,serverId:t}))}n(te,"publishRuntimeEndpoint");function ne(r){return W({runtime:E(r.ports),close:r.close})}n(ne,"createAppServer");function W(r){let e=!1;return{runtime:r.runtime,close:n(async()=>{e||(e=!0,await r.close?.())},"close")}}n(W,"attachAppServer");async function ie(r){let e=typeof r.appServer=="function"?null:r.appServer;try{await j({host:e?.runtime??(async()=>(e=await r.appServer(),e.runtime)),readable:r.readable,writable:r.writable,hostStorageClient:r.hostStorageClient})}finally{await e?.close()}}n(ie,"runAppServerJsonl");import{randomBytes as z}from"node:crypto";function pe(){return S()}n(pe,"appDataDir");function ue(r){return l(r).config}n(ue,"providersConfigPath");function me(r){return l(r).credentials}n(me,"providerSecretsConfigPath");function ge(r){return l(r).key}n(ge,"providerSecretsKeyPath");async function fe(r){let e=l(r).token;return b(e,async()=>{let t=(await I(e))?.trim(),o=process.env.OPENPOND_APP_TOKEN||t||z(32).toString("base64url");return o!==t&&await h(e,o),{token:o,tokenFile:e}})}n(fe,"ensureCapabilityToken");import p from"node:path";import{readFile as _}from"node:fs/promises";var F=i.object({profileId:i.string().min(1),sourceRevision:i.string().min(1),repositoryId:i.string().min(1),harnessRelease:i.object({id:i.string().min(1),contentHash:i.string().regex(/^[a-f0-9]{64}$/)}).strict(),workspaceId:i.string().min(1),assetsPath:i.string().min(1).refine(p.isAbsolute)}).strict();async function Ie(r,e){let t=F.parse(e),o=await y(r,t.harnessRelease);if(!o||p.resolve(o.release.bundlePath)!==p.resolve(t.assetsPath))throw new Error("Hosted Profile release changed after admission.");let s=o.release.harnessRelease.metadata.profile;if(!s||typeof s!="object"||s.id!==t.profileId||s.sourceRevision!==t.sourceRevision||s.repositoryId!==void 0&&s.repositoryId!==t.repositoryId)throw new Error("Hosted Profile provenance differs from admitted release.");return{profile:O(),profileLibrary:M()}}n(Ie,"loadHostedProfileStateAndLibrary");async function be(r,e){let t=F.parse(e),o=await y(r,t.harnessRelease);if(!o||p.resolve(o.release.bundlePath)!==p.resolve(t.assetsPath))throw new Error("Hosted Profile workflow release is unavailable.");let s=o.release.harnessRelease.metadata.profile;if(s?.id!==t.profileId||s.sourceRevision!==t.sourceRevision||s.repositoryId!==void 0&&s.repositoryId!==t.repositoryId)throw new Error("Hosted Profile workflow provenance changed.");let a=t.harnessRelease,d={source:"openpond_git",repositoryId:t.repositoryId,profileId:t.profileId};if(!o.release.harnessRelease.files.some(g=>g.path==="workflows/catalog.json"))return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:[]};let c=p.join(o.release.bundlePath,"source","workflows"),A=U({agentSnapshot:o.release.agentSnapshot,harnessRelease:o.release.harnessRelease,catalogBytes:await _(p.join(c,"catalog.json")),actionBytes:await _(p.join(c,"actions.json"))});return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:A.catalog.workflows.map(g=>({workflow:g,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:t.profileId,sourceRevision:t.sourceRevision,harnessRelease:a,catalogHash:A.catalogHash,workflowId:g.id}}))}}n(be,"listHostedProfileWorkflows");import{createHash as G,randomUUID as P}from"node:crypto";var N=i.object({approval:R,revision:i.number().int().positive()}).strict(),B=i.object({record:w}).strict(),$=i.object({startedAt:i.string().min(1),requestOrdinal:i.number().int().nonnegative(),id:i.string().min(1)}).strict(),q=i.object({records:i.array(w).max(200),nextBefore:$.nullable()}).strict(),V=1e4,L=class{constructor(e){this.client=e}client;static{n(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:u,requestId:P(),operation:"approval/get",params:{approvalId:e}});return t===null?null:N.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=R.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return N.parse(await this.client.request({contractVersion:u,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},D=class{constructor(e){this.client=e}client;static{n(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=w.parse(e),o=G("sha256").update(JSON.stringify(t)).digest("hex"),s=await this.client.request({contractVersion:u,requestId:`usage:${o}`,operation:"usage/upsert",params:{record:t}}),a=B.parse(s).record;if(a.requestId!==t.requestId)throw new Error("Host usage upsert changed request identity.");return a}async getModelUsageRecordByRequestId(e){let t=await this.client.request({contractVersion:u,requestId:P(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:B.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=V,o=e.limit===void 0?V:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),s={...e.sessionId?{sessionId:e.sessionId}:{},...e.turnId?{turnId:e.turnId}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.startedAtFrom?{startedAtFrom:e.startedAtFrom}:{},...e.startedAtTo?{startedAtTo:e.startedAtTo}:{},...e.visibility&&e.visibility!=="all"?{visibility:e.visibility}:{},...e.status&&e.status!=="all"?{status:e.status}:{}},a=[],d=null;for(;a.length<o+(t?1:0);){let c=q.parse(await this.client.request({contractVersion:u,requestId:P(),operation:"usage/page",params:{query:s,before:d,limit:Math.min(200,o+(t?1:0)-a.length)}}));if(a.push(...c.records),a.length>o)throw new Error(`Hosted usage query exceeds ${o} rows; narrow its filters or use a streamed aggregation.`);if(c.nextBefore===null)break;if(c.records.length===0||JSON.stringify(c.nextBefore)===JSON.stringify(d))throw new Error("Host usage cursor did not advance.");d=c.nextBefore}return a}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};export{Z as a,ee as b,te as c,ne as d,ie as e,pe as f,ue as g,me as h,ge as i,fe as j,L as k,D as l,F as m,Ie as n,be as o};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{e as g,g as $,h as O,i as C}from"./chunk-E4U7LXSW.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
2
+ import{e as g,g as $,h as O,i as C}from"./chunk-3LG4G5JR.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-DR3XPQRZ.js";import{c as O,i as L}from"./chunk-QPZNN5Q3.js";import{a as Re}from"./chunk-6FA3GG5B.js";import{f as Oe}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";var J=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,n){let o=n.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,o.length?`Missing setup: ${o.join(", ")}`:""].filter(Boolean).join(`
2
+ import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-3YA2CD22.js";import{c as O,i as L}from"./chunk-6EAQL7YX.js";import{a as Re}from"./chunk-6FA3GG5B.js";import{f as Oe}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";var J=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,n){let o=n.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,o.length?`Missing setup: ${o.join(", ")}`:""].filter(Boolean).join(`
3
3
  `)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:t,setupGate:n,missing:o,blockingSetupRequirements:n.blockingRequirements,setupRequirements:n.requirements}}};function W(e){let t=new Map;for(let a of e.sourceSetupRequirements??[]){let l=bt(a);if(e.actionId&&l&&l!==e.actionId&&h(a.actionName)!==e.actionId&&h(a.sourceActionId)!==e.actionId)continue;let c=Ee({record:a,source:"source_upload_metadata",actionId:l});c&&t.set(c.ref,c)}for(let a of e.actionCatalog)if(!(e.actionId&&a.id!==e.actionId&&a.name!==e.actionId))for(let l of a.setupRequirements??[]){let c=Ee({record:l,source:"action_catalog",actionId:a.id});c&&t.set(c.ref,c)}let n=Array.from(t.values()),o=n.filter(a=>a.blocking),r=n.filter(a=>!a.required&&!ne(a.status)).length,i=n.filter(a=>ne(a.status)).length;return{status:It(o),requirementCount:n.length,blockingCount:o.length,optionalMissingCount:r,readyCount:i,requirements:n,blockingRequirements:o}}s(W,"buildOpenPondProfileSetupGate");function oe(e,t){if(t.blockingRequirements.length>0)throw new J(e,t)}s(oe,"assertOpenPondProfileActionReady");function Rt(e){let t=e.actionId?`${e.actionId}: `:"",n=e.required?"required":"optional";return`${t}${e.label} (${n}, ${e.status})`}s(Rt,"formatOpenPondProfileSetupRequirement");function Ee(e){let t=e.source==="action_catalog"&&h(e.record.source)==="source_upload_metadata"?"source_upload_metadata":e.source,n=h(e.record.kind)??h(e.record.type),o=h(e.record.label)??h(e.record.name)??h(e.record.key)??h(e.record.provider)??h(e.record.tool)??h(e.record.command)??h(e.record.packageName)??h(e.record.path)??h(e.record.repo)??h(e.record.url)??h(e.record.id)??n??"setup requirement",r=e.record.required!==!1,i=At(e.record);return{ref:[t,e.actionId??"source",n??"requirement",o].join(":"),source:t,actionId:e.actionId,kind:n,label:o,status:i,required:r,blocking:r&&!ne(i)}}s(Ee,"setupRequirementFromRecord");function bt(e){return h(e.actionId)??h(e.sourceActionId)??h(e.actionName)}s(bt,"setupRequirementActionId");function At(e){let t=h(e.status)??h(e.state);return t?t==="satisfied"||t==="connected"||t==="provided"?"ready":t:typeof e.satisfied=="boolean"?e.satisfied?"ready":"setup_required":typeof e.ready=="boolean"&&e.ready?"ready":"setup_required"}s(At,"setupStatus");function It(e){return e.length===0?"ready":e.some(t=>["blocked","unsupported","unsupported_dependency","stale"].includes(t.status))?"blocked":"setup_required"}s(It,"gateStatus");function ne(e){return e==="ready"||e==="disabled"}s(ne,"isReadyStatus");function h(e){return typeof e=="string"&&e.trim()?e.trim():null}s(h,"text");import{stat as qt}from"node:fs/promises";import se from"node:path";import{spawn as vt}from"node:child_process";import{existsSync as re}from"node:fs";import{readFile as Et,rm as Kn,writeFile as _e}from"node:fs/promises";import ie from"node:path";var Le=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
4
4
  `);async function Me(e){if(!re(ie.join(e,".git"))){let i=await R(e,["init","-b","main"]);if(i.code!==0)throw new Error(H("git init",i))}let t=ie.join(e,".gitignore");if(re(t)?await xt(t):await _e(t,Le,"utf8"),await _t(e))return;let n=await N(e);if(!n.dirty&&n.files.length===0)return;let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m","Initialize OpenPond profile"],{env:{...process.env,GIT_AUTHOR_NAME:process.env.GIT_AUTHOR_NAME||"OpenPond",GIT_AUTHOR_EMAIL:process.env.GIT_AUTHOR_EMAIL||"openpond@example.invalid",GIT_COMMITTER_NAME:process.env.GIT_COMMITTER_NAME||"OpenPond",GIT_COMMITTER_EMAIL:process.env.GIT_COMMITTER_EMAIL||"openpond@example.invalid"}});if(r.code!==0&&!/nothing to commit/i.test(r.stdout+r.stderr))throw new Error(H("git commit",r))}s(Me,"ensureProfileGitRepo");async function xt(e){let t=await Et(e,"utf8").catch(()=>""),n=Le.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!t.split(/\r?\n/).some(i=>i.trim()===r));if(n.length===0)return;let o=t.endsWith(`
5
5
  `)||t.length===0?"":`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as n}from"./chunk-FTQLQJQV.js";var s="127.0.0.1";var f="0.2.35",m="You are OpenPond Chat. Respond in the user's language. If the user's latest message is language-neutral, ambiguous, or only a short test, respond in English. Be concise and directly answer the latest request. Do not use emojis. Use Markdown when it improves scanability. If you emit reasoning or thinking content, keep it sparse and user-readable: at most one short sentence for major progress, decisions, or blockers. Omit reasoning for routine searches, reads, tool calls, and obvious next steps. Do not restate the user request, narrate every action, or include code blocks, code excerpts, diffs, raw tool payloads, or markdown examples in reasoning. Put necessary code or exact snippets only in the final assistant answer. When the user asks to show or preview an image that is available as a workspace path or signed image URL, use Markdown image syntax like ![description](path-or-url) instead of a bare path or raw HTML. For workspace-backed answers, use a Codex-style shape: brief outcome first, then Changed Files if files changed, then Verification if checks ran. End with a concise final answer that summarizes the result and verification when relevant. Do not mention raw tool JSON, internal repo paths, or origin/remote URLs unless the user explicitly asks for them or they are necessary to explain a git/deploy failure.";import{randomUUID as p}from"node:crypto";import i from"node:path";import{fileURLToPath as c}from"node:url";function u(){return new Date().toISOString()}n(u,"now");function l(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}n(l,"textFromUnknown");function w(e){if(!e||typeof e!="object")return"";let t=e;for(let r of["delta","text","output","chunk","message"])if(typeof t[r]=="string")return t[r];return t.delta&&typeof t.delta=="object"?l(t.delta):""}n(w,"extractDelta");function x(e){return{id:p(),timestamp:u(),...e}}n(x,"event");function k(e){let t=e.replace(/^https?:\/\//,""),[r,o]=t.split(":");return{host:r||s,port:o?Number.parseInt(o,10):17874}}n(k,"parseListen");function b(e){return(process.argv[1]?i.resolve(process.argv[1]):"")===i.resolve(c(e))}n(b,"isCliEntrypoint");export{s as a,f as b,m as c,u as d,l as e,w as f,x as g,k as h,b as i};
2
+ import{a as n}from"./chunk-FTQLQJQV.js";var s="127.0.0.1";var f="0.2.37",m="You are OpenPond Chat. Respond in the user's language. If the user's latest message is language-neutral, ambiguous, or only a short test, respond in English. Be concise and directly answer the latest request. Do not use emojis. Use Markdown when it improves scanability. If you emit reasoning or thinking content, keep it sparse and user-readable: at most one short sentence for major progress, decisions, or blockers. Omit reasoning for routine searches, reads, tool calls, and obvious next steps. Do not restate the user request, narrate every action, or include code blocks, code excerpts, diffs, raw tool payloads, or markdown examples in reasoning. Put necessary code or exact snippets only in the final assistant answer. When the user asks to show or preview an image that is available as a workspace path or signed image URL, use Markdown image syntax like ![description](path-or-url) instead of a bare path or raw HTML. For workspace-backed answers, use a Codex-style shape: brief outcome first, then Changed Files if files changed, then Verification if checks ran. End with a concise final answer that summarizes the result and verification when relevant. Do not mention raw tool JSON, internal repo paths, or origin/remote URLs unless the user explicitly asks for them or they are necessary to explain a git/deploy failure.";import{randomUUID as p}from"node:crypto";import i from"node:path";import{fileURLToPath as c}from"node:url";function u(){return new Date().toISOString()}n(u,"now");function l(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}n(l,"textFromUnknown");function w(e){if(!e||typeof e!="object")return"";let t=e;for(let r of["delta","text","output","chunk","message"])if(typeof t[r]=="string")return t[r];return t.delta&&typeof t.delta=="object"?l(t.delta):""}n(w,"extractDelta");function x(e){return{id:p(),timestamp:u(),...e}}n(x,"event");function k(e){let t=e.replace(/^https?:\/\//,""),[r,o]=t.split(":");return{host:r||s,port:o?Number.parseInt(o,10):17874}}n(k,"parseListen");function b(e){return(process.argv[1]?i.resolve(process.argv[1]):"")===i.resolve(c(e))}n(b,"isCliEntrypoint");export{s as a,f as b,m as c,u as d,l as e,w as f,x as g,k as h,b as i};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{i as a,j as b,k as c}from"./chunk-OO7JG7KM.js";import"./chunk-XISNUB62.js";import"./chunk-DXOOJFFU.js";import"./chunk-I6DQSOSF.js";import"./chunk-FQOVC2GR.js";import"./chunk-PKBU37CH.js";import"./chunk-Z3RBK6LN.js";import"./chunk-BLXEK5F7.js";import"./chunk-FOW3LI6G.js";import"./chunk-L3KS6MOV.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as resolveWebLaunchMessages,c as runOpenPondAppServerCli,b as runOpenPondServerCli};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as f}from"./chunk-XLVFY2BA.js";import{$a as I,Ba as J,Qa as N,Ra as q,Ua as k,Wa as A,Xa as B,_a as H,b as d,c as w,e as b,hb as E,ib as M,ja as C,jb as T,la as m,ma as j,na as x,oa as F,pa as v,qa as P}from"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{d as O,f as S,h as g}from"./chunk-H7IWJN7L.js";import"./chunk-3LG4G5JR.js";import"./chunk-3M53YXEI.js";import{a as l}from"./chunk-FTQLQJQV.js";import R from"node:path";import{readFile as p}from"node:fs/promises";var n=l((t,s)=>typeof t[s]=="string"?t[s]:void 0,"stringOption");function a(t){console.log(JSON.stringify(t,null,2))}l(a,"print");function U(t,s){let i=n(t,"keyPath");if(i){let r=JSON.parse(i);if(Array.isArray(r)&&r.length&&r.every(c=>typeof c=="string"&&c.length))return r;throw new f("--key-path must be a JSON array of key segments.")}if(!s)throw new f("Specify a setting key, or --key-path for keys containing dots.");return s.split(".")}l(U,"keyPath");async function G(t,s){let i=S({home:n(t,"home")}),r=s[0]??"get",c=g(i).config;if(r==="path"){console.log(c);return}if(r==="export"){let e=await T(i),o=n(t,"file");o?(await b(R.resolve(o),JSON.stringify(e,null,2),{privateParent:!1}),a({path:R.resolve(o),requiresRebinding:e.requiresRebinding})):a(e);return}if(r==="backup"||r==="restore"){let e=n(t,"file"),o=n(t,"keyFile");if(!e||!o)throw new f(`config ${r} requires --file <encrypted-backup> and --key-file <separate-32-byte-key-file>.`);let u=await p(o),y=u.length===32?u:Buffer.from(u.toString("utf8").trim(),"base64");try{a(r==="backup"?await E(i,e,y):await M(e,i,y))}finally{y.fill(0),u.fill(0)}return}if(r==="collect-orphans"){a(await N(i));return}if(r==="schema"){a(F());return}if(r==="migrate"){let e=n(t,"resolutionFile"),o=e?q.parse(JSON.parse(await p(e,"utf8"))):void 0;a(await k(i,{resolutions:o,sourceAppHome:n(t,"sourceAppHome"),sourceConfig:n(t,"sourceConfig"),sourceBrowserState:n(t,"sourceBrowserState"),dryRun:t.dryRun===!0||t.dryRun==="true"}));return}if(r==="recover"){let e=n(t,"revision");a(e?await x(i,e,n(t,"expectedRevision")??d(await w(c))):await A(i));return}if(r==="restart-migration"){a(await B(i));return}if(r==="effective"){a(await I(i,{projectRoot:n(t,"projectRoot"),accountId:n(t,"accountId")}));return}if(r==="trust"||r==="untrust"){let e=n(t,"projectRoot")??s[1];if(!e)throw new f("Specify the canonical project root with --project-root.");await H(i,e,n(t,"accountId")??"local",r==="trust"),a({root:e,trusted:r==="trust"});return}if(r==="revisions"){a(await m(i));return}if(r==="validate"){let e=n(t,"file")??c;C(await p(e,"utf8"),e,t.project===!0||t.project==="true"?"project":"user"),a({valid:!0,path:e});return}if(r==="replace"){let e=n(t,"file");if(!e)throw new f("config replace requires --file <validated-toml-file>.");a(await j(i,n(t,"expectedRevision")??d(await w(c)),await p(e,"utf8")));return}if(r==="doctor"){let e=await w(c),o=null;try{await v(i)}catch(u){o=O(u,c)}a({home:i,path:c,rawRevision:d(e),issue:o,recoverableRevisions:await m(i),migration:await w(R.join(g(i).runtime,"migration.json"))!==null}),o&&(process.exitCode=1);return}if(await k(i),r==="clear-cache"){await J(i),a({cleared:!0,path:g(i).cache});return}let h=await v(i);if(r==="get"){if(!s[1]&&!t.keyPath){a(h);return}let e=h.document;for(let o of U(t,s[1]))e=e&&typeof e=="object"?e[o]:void 0;a(e??null);return}if(r==="set"||r==="unset"){let e=U(t,s[1]),o;if(r==="set"){let u=n(t,"value")??s[2];if(u===void 0)throw new f("config set requires a value. Use JSON for arrays, tables, numbers and booleans.");try{o=JSON.parse(u)}catch{o=u}}a(await P(i,n(t,"expectedRevision")??h.rawRevision,[r==="set"?{op:"set",path:e,value:o}:{op:"unset",path:e}]));return}throw new f(`Unknown config command: ${r}`)}l(G,"runConfigurationCommand");export{G as runConfigurationCommand};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-KCFVJDIV.js";import"./chunk-5YUITAUN.js";import"./chunk-FFEI7IRU.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZ6N7WFI.js";import"./chunk-UJLZRM2M.js";import"./chunk-6EAQL7YX.js";import"./chunk-GLUWATL5.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-XLVFY2BA.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-3LG4G5JR.js";import"./chunk-3M53YXEI.js";import"./chunk-FTQLQJQV.js";export{m as resolveGitBranch,f as runAccount,j as runBacktestRun,p as runCheckUpdate,k as runDeployWatch,g as runHealth,d as runLogin,o as runOpentool,e as runProfiles,l as runRepoCreate,n as runRepoPush,b as runTemplateBranches,a as runTemplateStatus,c as runTemplateUpdate,h as runToolList,i as runToolRun};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{u as f}from"./chunk-5YUITAUN.js";import"./chunk-FFEI7IRU.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZ6N7WFI.js";import"./chunk-UJLZRM2M.js";import"./chunk-6EAQL7YX.js";import"./chunk-GLUWATL5.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import{a as c}from"./chunk-XLVFY2BA.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-3LG4G5JR.js";import{c as p,f as u}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";import d from"node:path";import{access as v}from"node:fs/promises";import{constants as C}from"node:fs";import{createRequire as P}from"node:module";var l=d.join("scripts","desktop-harness.ts");async function $(n,t){let o=await j({options:n,rest:t}),e=await f(o.command,o.args,{cwd:o.cwd,inherit:!0,timeoutMs:0});if(e.code!==0)throw new m(e.code)}r($,"runDesktopTestCommand");async function j(n){let t=n.options,o=n.rest,e=o[0];if(e!=="run"&&e!=="attach")throw new c(D());let a=o.slice(1);if(a.length===0)throw new c("usage: openpond desktop-test run <scenario...> [options]");let g=p(t,"cwd")||n.cwd||process.cwd(),w=await O(g),k=(n.env??process.env).OPENPOND_NODE_BINARY?.trim()||process.execPath,s=[P(import.meta.url).resolve("tsx/cli"),l,"run",...a],h=x(t,e);return h&&s.push(`--${h}`),i(s,"--app",t,"app"),i(s,"--server",t,"server"),i(s,"--token",t,"token"),i(s,"--token-file",t,"tokenFile"),i(s,"--devtools-port",t,"devtoolsPort"),i(s,"--artifacts-dir",t,"artifactsDir"),H(s,t),i(s,"--grep",t,"grep"),i(s,"--timeout-ms",t,"timeoutMs"),u(t.keepHome)&&s.push("--keep-home"),{command:k,args:s,cwd:w}}r(j,"buildDesktopHarnessInvocation");async function O(n){let t=d.resolve(n);for(;;){let o=d.join(t,l);if(await R(o))return t;let e=d.dirname(t);if(e===t)throw new c(`Could not find ${l}. Run this command from the OpenPond source checkout or pass --cwd <repo>.`);t=e}}r(O,"resolveDesktopHarnessRepoRoot");function x(n,t){let o=t==="attach"?"attach":null;for(let e of["isolated","attach","packaged","none"])if(u(n[e])){if(o&&o!==e)throw new c("Choose only one desktop harness launch mode: --isolated, --attach, --packaged, or --none.");o=e}return o}r(x,"resolveLaunchMode");function i(n,t,o,e){let a=p(o,e);a&&n.push(t,a)}r(i,"appendStringFlag");function H(n,t){let o=p(t,"json"),e=p(t,"jsonPath");if(o&&y(o))throw new c("harness --json requires a report path. Use --json <path> or --json-path <path>.");if(o&&e&&o!==e)throw new c("Use only one JSON report path: --json <path> or --json-path <path>.");let a=o||e;a&&n.push("--json",a)}r(H,"appendJsonFlag");function y(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(y,"isBooleanLiteral");async function R(n){try{return await v(n,C.R_OK),!0}catch{return!1}}r(R,"fileExists");function D(){return["usage: openpond desktop-test run <scenario...> [options]"," openpond desktop-test attach <scenario...> [options]","","Options include --isolated, --attach, --packaged, --none, --app <path>,","--server <url>, --token <token>, --token-file <path>, --devtools-port <port>, --artifacts-dir <path>,","--json <path>, --json-path <path>, --grep <pattern>, --timeout-ms <ms>,","--keep-home, and --cwd <repo>."].join(`
3
+ `)}r(D,"desktopHarnessCliUsage");var m=class extends Error{static{r(this,"HarnessCommandFailedError")}exitCode;constructor(t){let o=typeof t=="number"&&t>0?t:1;super(`desktop harness failed with exit code ${o}`),this.name="HarnessCommandFailedError",this.exitCode=o}};export{j as buildDesktopHarnessInvocation,O as resolveDesktopHarnessRepoRoot,$ as runDesktopTestCommand};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{$a as xa,Aa as Y,Ba as Z,Ca as _,Da as $,Ea as aa,Fa as ba,Ga as ca,Ha as da,Ia as ea,Ja as fa,Ka as ga,La as ha,Ma as ia,Na as ja,Oa as ka,Pa as la,Qa as ma,Ra as na,Sa as oa,Ta as pa,Ua as qa,Va as ra,Wa as sa,Xa as ta,Ya as ua,Za as va,_a as wa,a as l,ab as ya,b as m,bb as za,c as n,cb as Aa,d as o,db as Ba,e as p,ea as v,eb as Ca,f as q,fa as w,fb as Da,g as r,ga as x,gb as Ea,h as s,ha as y,hb as Fa,i as t,ia as z,ib as Ga,j as u,ja as A,jb as Ha,ka as B,kb as Ia,la as C,ma as D,na as E,oa as F,pa as G,qa as H,ra as I,sa as J,ta as K,ua as L,va as M,wa as N,xa as O,ya as W,za as X}from"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{a,b,c,d,e,f,g,h,i,k as j,l as k,m as P,n as Q,o as R,p as S,q as T,r as U,s as V}from"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{Ca as CLIENT_CHOICE_KEYS,Ba as ClientChoicesSchema,w as ConfigSchema,v as CredentialReferenceSchema,L as LAYOUT_PREFERENCE_KEYS,l as MISSING_REVISION,na as MigrationResolutionsSchema,P as PERSISTENCE_TABLES_SQL,c as PersistenceError,ea as accountId,r as acquireFileLock,ja as artifactReference,za as assertConfigRunCurrent,Ia as assertHomeCompatible,k as assertStorageAncestors,p as atomicWriteFile,b as bindHomeCallbacks,ya as captureConfigRun,Z as clearCache,ma as collectArtifactOrphans,F as configEditorSchema,C as configRecoveryRevisions,N as configToPreferences,da as credentialVersions,ba as deleteCredential,V as deleteLocalRecord,y as diffConfig,Aa as effectivePreferences,g as expandHome,Fa as exportRecoveryBackup,Ha as exportSettings,m as fileRevision,S as getLocalRecord,qa as initializeHome,e as isMissing,O as layoutPreferences,Y as listCache,T as listLocalRecords,J as mergeConfig,ca as newCredentialId,Q as openStorageDatabase,H as patchConfig,d as persistenceIssue,M as preferencesToConfig,o as privateDirectory,s as processIsDead,j as protectPrivateDirectory,ia as publishManagedArtifact,U as putLocalRecord,fa as readAccountConfiguration,W as readCache,Da as readClientChoices,G as readConfig,_ as readCredential,$ as readCredentials,t as readJsonFile,oa as readMigrationJournal,n as readOptionalFile,ua as readPreferences,sa as recoverMigration,la as releaseArtifactReference,B as rememberValidConfig,D as replaceConfigText,i as resolveConfigPath,xa as resolveEffectiveConfig,f as resolveOpenPondHome,pa as resolveStoredPath,ta as restartMigration,E as restoreConfigRevision,Ga as restoreRecoveryBackup,z as serializeConfig,wa as setProjectTrust,h as storagePaths,ga as updateAccountConfiguration,Ea as updateClientChoices,I as updateConfig,u as updateJsonFile,va as updatePreferences,x as validateConfigDocument,A as validateConfigText,ha as validateManagedArtifacts,ra as validateMigratedHome,K as watchConfig,q as withFileLock,R as withLocalDatabase,ka as withManagedArtifact,a as withOpenPondHome,X as writeCache,aa as writeCredential};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{A as D,B as E,C as F,D as G,E as H,F as I,G as J,H as K,I as L,J as M,K as N,L as O,M as P,N as Q,O as R,P as S,Q as T,R as U,S as V,T as W,U as X,V as Y,a as d,b as e,c as f,d as g,e as h,f as i,g as j,h as k,i as l,j as m,k as n,l as o,m as p,n as q,o as r,p as s,q as t,r as u,s as v,t as w,u as x,v as y,w as z,x as A,y as B,z as C}from"./chunk-PKBU37CH.js";import{ta as a,ua as b,va as c}from"./chunk-QUNRWDVO.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-FTQLQJQV.js";export{l as AGENT_PROTOCOL_VERSION,m as AGENT_RPC_METHODS,P as AgentCheckpointSchema,O as AgentEffectiveSurfaceSchema,i as AgentEventNameSchema,L as AgentHostStorageClient,t as AgentJsonRpcDispatcher,r as AgentProtocolEnvelopeSchema,u as AgentRpcClient,j as CanonicalAgentEventSchema,H as HOST_STORAGE_CONTRACT_VERSION,x as HarnessReviewStorageParamsSchema,K as HostStorageCapabilitySchema,J as HostStorageRequestSchema,I as HostStorageScopeSchema,z as HostedOutputBeginParamsSchema,A as HostedOutputChunkParamsSchema,B as HostedOutputCompleteParamsSchema,y as HostedOutputIdentitySchema,D as HostedOutputSaveSandboxFileParamsSchema,E as HostedSandboxActionSchema,C as HostedSandboxOutputIdentitySchema,F as HostedSandboxRequestParamsSchema,G as HostedToolAuthorizationParamsSchema,s as InitializeParamsSchema,q as JsonRpcErrorSchema,o as JsonRpcNotificationSchema,n as JsonRpcRequestSchema,p as JsonRpcSuccessSchema,w as RefinerStorageActionSchema,v as TaskInboxStorageParamsSchema,Y as TaskSerialExecutor,X as TaskSignals,f as agentCompactionDecision,k as canonicalEventHash,e as canonicalHash,d as canonicalJson,R as checkpointHash,N as createAgentRuntimeService,T as createAgentToolCatalog,V as createAgentToolCatalogProjection,Q as effectiveSurfaceHash,U as executeAgentTool,W as executeProjectedAgentTool,S as materializeAgentPrompt,a as providerRoundSequence,g as runAgentCompaction,h as runAgentCompactionProgram,M as runAgentJsonlServer,c as runProviderRound,b as runProviderRoundLoop};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as se}from"./chunk-CWW2EK77.js";import"./chunk-BX4J2VDU.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-4QX2I2DX.js";import"./chunk-22UARBPW.js";import"./chunk-JEVA7YQL.js";import{a as T,x as D}from"./chunk-K6EGNB2A.js";import"./chunk-DR3XPQRZ.js";import"./chunk-Z6F6PYF4.js";import"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-5BFWDFPX.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{f as N}from"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import{f as ne,h as z,p as B,r as oe}from"./chunk-H7IWJN7L.js";import{f as G}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var u=class extends Error{static{r(this,"GithubExtensionError")}code;status;constructor(t,o){super(t),this.name="GithubExtensionError",this.code=o.code,this.status=o.status??400}};import{createHash as ce}from"node:crypto";import J from"node:path";var ie="HEAD",ae=64,de=512,le=20*1024*1024,K=5*1024*1024,me=8,Ue=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pe=/^[A-Za-z0-9_.-]+$/,ue=new Set(["agents","assets","references","scripts"]);function Se(e={}){let t=e.fetch??fetch,o=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let s=await qe(n,t,o);return{preview:await Te(s,t,o),files:ge(s)}},async download(n,s){await _e({resolution:n,fetchImpl:t,githubToken:o,writeFile:s})}}}r(Se,"createGithubSourceClient");function I(e){let t=e.trim(),o="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let d=new URL(t.startsWith("http")?t:`https://${t}`);if(d.hostname.toLowerCase()!=="github.com")throw j(e);let a=d.pathname.replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}else{let a=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}if(n=n.replace(/\.git$/i,""),!pe.test(o)||!pe.test(n))throw j(e);let s=o.toLowerCase(),i=n.toLowerCase();return{id:`github:${s}/${i}`,owner:s,repo:i,repositoryUrl:`https://github.com/${s}/${i}`}}r(I,"parseGithubExtensionSource");async function qe(e,t,o){let n=I(e.source),s=e.ref?.trim()||ie,i=await H(t,o,`/repos/${n.owner}/${n.repo}`),d=s===ie?i.default_branch?.trim()||"main":s,a=await H(t,o,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(d)}`),b=a.sha?.trim(),f=a.commit?.tree?.sha?.trim();if(!b||!f)throw new u("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let y=await H(t,o,`/repos/${n.owner}/${n.repo}/git/trees/${f}?recursive=1`);if(y.truncated)throw new u("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let w=(y.tree??[]).filter(ze),x=Le(w);if(x.length===0)throw new u("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(x.length>ae)throw new u(`Extension contains more than ${ae} skills.`,{code:"extension_too_many_skills"});Ge(x);let A=w.find(m=>m.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(m.path))??null;return{identity:n,requestedRef:s,resolvedCommit:b,tree:w,skillPackages:x,readme:A}}r(qe,"resolveSource");async function Te(e,t,o){let n=await xe(e.skillPackages,me,async a=>{let b=await Fe(e,a.entry,t,o);return je(a,b)}),s=De(n.map(a=>a.name));for(let a of n)s.has(a.name)&&(a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`]);let i=n.flatMap(a=>a.validationMessages.map(b=>`${a.relativePath}: ${b}`)),d=ge(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:Ne(d),skills:n.sort((a,b)=>a.name.localeCompare(b.name)),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(Te,"buildPreview");function je(e,t){let o=T(t),n=e.root==="."?null:J.posix.basename(e.root),s=o.name??n??"invalid-skill",i=[...o.messages];Ue.test(s)||i.push("Skill name must be lowercase kebab-case."),n&&s!==n&&i.push(`Skill name must match its directory name (${n}).`);let d=e.files.filter(a=>a.path!==e.entry.path).map(a=>Be(e.root,a.path)).sort();return{name:s,description:o.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:ce("sha256").update(t).digest("hex"),resourceFiles:d,validationStatus:i.length===0?"valid":"error",validationMessages:[...new Set(i)]}}r(je,"previewSkill");function Le(e){let t=[],o=e.find(a=>a.type==="blob"&&a.path==="SKILL.md");o&&t.push({root:".",entry:o});let n=e.filter(a=>a.type==="blob"&&a.path.endsWith("/SKILL.md")),s=n.filter(a=>Me(a.path)),i=s.length>0?s:n,d=new Set(i.map(a=>J.posix.dirname(a.path)));for(let a of i){let b=J.posix.dirname(a.path);[...d].some(f=>f!==b&&b.startsWith(`${f}/`))||t.push({root:b,entry:a})}return t.map(({root:a,entry:b})=>{let f=e.filter(x=>{if(x.type!=="blob")return!1;if(a!==".")return x.path.startsWith(`${a}/`);if(x.path==="SKILL.md")return!0;let A=x.path.split("/",1)[0]??"";return ue.has(A)}),y=e.find(x=>x.type!=="blob"&&x.type!=="tree"&&(a==="."?x.path==="SKILL.md"||ue.has(x.path.split("/",1)[0]??""):x.path.startsWith(`${a}/`))),w=f.find(x=>x.mode==="120000");if(y||w)throw new u(`Skill package ${a} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:a,entry:b,files:f}})}r(Le,"discoverSkillPackages");function Me(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let o=t.slice(0,-1);if(o.length<2)return!1;let n=o.lastIndexOf("skills");if(n<0||n>2)return!1;let s=o.slice(0,n),i=o.slice(n+1);if(i.length<1||i.length>2)return!1;if(n===0)return!0;let d=s[0]??"";return d.startsWith(".")||d==="agent"||d==="data"}r(Me,"isStandardAgentSkillsPath");function ge(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let o of e.skillPackages)for(let n of o.files)t.set(n.path,n);return[...t.values()].sort((o,n)=>o.path.localeCompare(n.path))}r(ge,"filesToDownload");async function _e(e){let t=0;await xe(e.resolution.files,me,async o=>{let n=await be({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:o,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>le)throw new u("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(o.path,n,o.mode==="100755")})}r(_e,"downloadFiles");async function Fe(e,t,o,n){let s=await be({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:o,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(s)}r(Fe,"downloadText");async function be(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),o=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(o,{headers:he(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new u(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let s=Number(n.headers.get("content-length"));if(Number.isFinite(s)&&s>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let i=new Uint8Array(await n.arrayBuffer());if(i.byteLength>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return i}r(be,"downloadBytes");async function H(e,t,o){let n=await e(`https://api.github.com${o}`,{headers:he(t,"application/vnd.github+json")});if(!n.ok){let s=await n.json().catch(()=>null),i=typeof s?.message=="string"?`: ${s.message}`:"";throw new u(`GitHub request failed (${n.status})${i}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}r(H,"githubJson");function he(e,t){let o=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&o.set("Authorization",`Bearer ${e}`),o}r(he,"githubHeaders");function Ge(e){let t=new Map;for(let n of e)for(let s of n.files)t.set(s.path,s);if(t.size>de)throw new u(`Extension contains more than ${de} skill files.`,{code:"extension_too_many_files"});let o=0;for(let n of t.values()){if((n.size??0)>K)throw new u(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});o+=n.size??0}if(o>le)throw new u("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}r(Ge,"validateDownloadLimits");function ze(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}r(ze,"validTreeEntry");function Ne(e){let t=ce("sha256");for(let o of e)t.update(`${o.path}\0${o.sha}\0${o.size??""}
2
+ import{a as se}from"./chunk-EIB7GHIQ.js";import"./chunk-BX4J2VDU.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-3N4GQL6I.js";import"./chunk-22UARBPW.js";import"./chunk-JEVA7YQL.js";import{a as T,x as D}from"./chunk-YQPECTJ2.js";import"./chunk-3YA2CD22.js";import"./chunk-UJLZRM2M.js";import"./chunk-6EAQL7YX.js";import"./chunk-GLUWATL5.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{f as N}from"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{f as ne,h as z,p as B,r as oe}from"./chunk-H7IWJN7L.js";import{f as G}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var u=class extends Error{static{r(this,"GithubExtensionError")}code;status;constructor(t,o){super(t),this.name="GithubExtensionError",this.code=o.code,this.status=o.status??400}};import{createHash as ce}from"node:crypto";import J from"node:path";var ie="HEAD",ae=64,de=512,le=20*1024*1024,K=5*1024*1024,me=8,Ue=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pe=/^[A-Za-z0-9_.-]+$/,ue=new Set(["agents","assets","references","scripts"]);function Se(e={}){let t=e.fetch??fetch,o=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let s=await qe(n,t,o);return{preview:await Te(s,t,o),files:ge(s)}},async download(n,s){await _e({resolution:n,fetchImpl:t,githubToken:o,writeFile:s})}}}r(Se,"createGithubSourceClient");function I(e){let t=e.trim(),o="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let d=new URL(t.startsWith("http")?t:`https://${t}`);if(d.hostname.toLowerCase()!=="github.com")throw j(e);let a=d.pathname.replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}else{let a=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}if(n=n.replace(/\.git$/i,""),!pe.test(o)||!pe.test(n))throw j(e);let s=o.toLowerCase(),i=n.toLowerCase();return{id:`github:${s}/${i}`,owner:s,repo:i,repositoryUrl:`https://github.com/${s}/${i}`}}r(I,"parseGithubExtensionSource");async function qe(e,t,o){let n=I(e.source),s=e.ref?.trim()||ie,i=await H(t,o,`/repos/${n.owner}/${n.repo}`),d=s===ie?i.default_branch?.trim()||"main":s,a=await H(t,o,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(d)}`),b=a.sha?.trim(),f=a.commit?.tree?.sha?.trim();if(!b||!f)throw new u("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let y=await H(t,o,`/repos/${n.owner}/${n.repo}/git/trees/${f}?recursive=1`);if(y.truncated)throw new u("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let w=(y.tree??[]).filter(ze),x=Le(w);if(x.length===0)throw new u("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(x.length>ae)throw new u(`Extension contains more than ${ae} skills.`,{code:"extension_too_many_skills"});Ge(x);let A=w.find(m=>m.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(m.path))??null;return{identity:n,requestedRef:s,resolvedCommit:b,tree:w,skillPackages:x,readme:A}}r(qe,"resolveSource");async function Te(e,t,o){let n=await xe(e.skillPackages,me,async a=>{let b=await Fe(e,a.entry,t,o);return je(a,b)}),s=De(n.map(a=>a.name));for(let a of n)s.has(a.name)&&(a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`]);let i=n.flatMap(a=>a.validationMessages.map(b=>`${a.relativePath}: ${b}`)),d=ge(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:Ne(d),skills:n.sort((a,b)=>a.name.localeCompare(b.name)),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(Te,"buildPreview");function je(e,t){let o=T(t),n=e.root==="."?null:J.posix.basename(e.root),s=o.name??n??"invalid-skill",i=[...o.messages];Ue.test(s)||i.push("Skill name must be lowercase kebab-case."),n&&s!==n&&i.push(`Skill name must match its directory name (${n}).`);let d=e.files.filter(a=>a.path!==e.entry.path).map(a=>Be(e.root,a.path)).sort();return{name:s,description:o.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:ce("sha256").update(t).digest("hex"),resourceFiles:d,validationStatus:i.length===0?"valid":"error",validationMessages:[...new Set(i)]}}r(je,"previewSkill");function Le(e){let t=[],o=e.find(a=>a.type==="blob"&&a.path==="SKILL.md");o&&t.push({root:".",entry:o});let n=e.filter(a=>a.type==="blob"&&a.path.endsWith("/SKILL.md")),s=n.filter(a=>Me(a.path)),i=s.length>0?s:n,d=new Set(i.map(a=>J.posix.dirname(a.path)));for(let a of i){let b=J.posix.dirname(a.path);[...d].some(f=>f!==b&&b.startsWith(`${f}/`))||t.push({root:b,entry:a})}return t.map(({root:a,entry:b})=>{let f=e.filter(x=>{if(x.type!=="blob")return!1;if(a!==".")return x.path.startsWith(`${a}/`);if(x.path==="SKILL.md")return!0;let A=x.path.split("/",1)[0]??"";return ue.has(A)}),y=e.find(x=>x.type!=="blob"&&x.type!=="tree"&&(a==="."?x.path==="SKILL.md"||ue.has(x.path.split("/",1)[0]??""):x.path.startsWith(`${a}/`))),w=f.find(x=>x.mode==="120000");if(y||w)throw new u(`Skill package ${a} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:a,entry:b,files:f}})}r(Le,"discoverSkillPackages");function Me(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let o=t.slice(0,-1);if(o.length<2)return!1;let n=o.lastIndexOf("skills");if(n<0||n>2)return!1;let s=o.slice(0,n),i=o.slice(n+1);if(i.length<1||i.length>2)return!1;if(n===0)return!0;let d=s[0]??"";return d.startsWith(".")||d==="agent"||d==="data"}r(Me,"isStandardAgentSkillsPath");function ge(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let o of e.skillPackages)for(let n of o.files)t.set(n.path,n);return[...t.values()].sort((o,n)=>o.path.localeCompare(n.path))}r(ge,"filesToDownload");async function _e(e){let t=0;await xe(e.resolution.files,me,async o=>{let n=await be({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:o,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>le)throw new u("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(o.path,n,o.mode==="100755")})}r(_e,"downloadFiles");async function Fe(e,t,o,n){let s=await be({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:o,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(s)}r(Fe,"downloadText");async function be(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),o=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(o,{headers:he(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new u(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let s=Number(n.headers.get("content-length"));if(Number.isFinite(s)&&s>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let i=new Uint8Array(await n.arrayBuffer());if(i.byteLength>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return i}r(be,"downloadBytes");async function H(e,t,o){let n=await e(`https://api.github.com${o}`,{headers:he(t,"application/vnd.github+json")});if(!n.ok){let s=await n.json().catch(()=>null),i=typeof s?.message=="string"?`: ${s.message}`:"";throw new u(`GitHub request failed (${n.status})${i}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}r(H,"githubJson");function he(e,t){let o=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&o.set("Authorization",`Bearer ${e}`),o}r(he,"githubHeaders");function Ge(e){let t=new Map;for(let n of e)for(let s of n.files)t.set(s.path,s);if(t.size>de)throw new u(`Extension contains more than ${de} skill files.`,{code:"extension_too_many_files"});let o=0;for(let n of t.values()){if((n.size??0)>K)throw new u(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});o+=n.size??0}if(o>le)throw new u("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}r(Ge,"validateDownloadLimits");function ze(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}r(ze,"validTreeEntry");function Ne(e){let t=ce("sha256");for(let o of e)t.update(`${o.path}\0${o.sha}\0${o.size??""}
3
3
  `);return t.digest("hex")}r(Ne,"hashTree");function Be(e,t){return e==="."?t:t.slice(e.length+1)}r(Be,"relativeSkillPath");function De(e){let t=new Set,o=new Set;for(let n of e)t.has(n)&&o.add(n),t.add(n);return o}r(De,"duplicateValues");async function xe(e,t,o){let n=new Array(e.length),s=0;async function i(){for(;s<e.length;){let d=s;s+=1,n[d]=await o(e[d])}}return r(i,"worker"),await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}r(xe,"mapConcurrent");function j(e){return new u(`Invalid GitHub extension source: ${e}. Use owner/repo or https://github.com/owner/repo.`,{code:"github_invalid_source"})}r(j,"invalidSource");import{createHash as He,randomUUID as we}from"node:crypto";import{existsSync as v}from"node:fs";import{mkdir as W,readFile as Je,rename as k,rm as E,stat as Ke,writeFile as Re}from"node:fs/promises";import g from"node:path";var M=1,We=15e3;function Oe(e={}){let t=g.resolve(e.home??e.rootPath??ne()),o=g.resolve(e.rootPath??g.join(t,"library","extensions")),n=z(t).database,s=Se({fetch:e.fetch,githubToken:e.githubToken}),i=e.now??(()=>new Date);async function d(){try{let m=await O(t),p=await Promise.all(m.extensions.map(S=>V(o,S)));return Ze(p,await C(e.reservedSkillNames)),{rootPath:o,registryPath:n,extensions:p.sort(Q),error:null}}catch(m){return{rootPath:o,registryPath:n,extensions:[],error:m instanceof Error?m.message:String(m)}}}r(d,"list");async function a(m){let p=await s.resolve(m),S=await O(t),c=S.extensions.find(l=>l.id===p.preview.id)??null;return U(p.preview,S.extensions.filter(l=>l.id!==c?.id),await C(e.reservedSkillNames)),p.preview}r(a,"preview");async function b(m){let p=I(m.source);return Y(o,p.id,async()=>{let S=await O(t);if(S.extensions.some(h=>h.id===p.id))throw new u(`${p.owner}/${p.repo} is already installed.`,{code:"extension_already_installed",status:409});let c=await s.resolve(m);Ie(c.preview),U(c.preview,S.extensions,await C(e.reservedSkillNames));let l=i().toISOString(),R=await fe({rootPath:o,resolution:c,installedAt:l,updatedAt:l,github:s});try{let h=await C(e.reservedSkillNames);return await X(t,i,P=>({...P,extensions:Xe(P,R,h)})),await Pe(o,R.id),R}catch(h){throw await ye(o,R.id),h}})}r(b,"add");async function f(m){let p=I(m.source);return Y(o,p.id,async()=>{let S=await O(t),c=L(S,p.id),l=await s.resolve({source:c.repositoryUrl,ref:m.ref?.trim()||c.requestedRef});if(Ie(l.preview),U(l.preview,S.extensions.filter(h=>h.id!==c.id),await C(e.reservedSkillNames)),c.resolvedCommit===l.preview.resolvedCommit&&c.packageHash===l.preview.packageHash&&c.requestedRef===l.preview.requestedRef)return V(o,c);let R=await fe({rootPath:o,resolution:l,installedAt:c.installedAt,updatedAt:i().toISOString(),github:s});try{let h=await C(e.reservedSkillNames);return await X(t,i,P=>({...P,extensions:Ye(P,R,h)})),await Pe(o,R.id),R}catch(h){throw await ye(o,R.id),h}})}r(f,"update");async function y(){let m=await d();if(m.error)throw new u(m.error,{code:"extension_registry_error"});let p={updated:[],unchanged:[],failed:[]};for(let S of m.extensions)try{let c=await f({source:S.repositoryUrl,ref:S.requestedRef});c.resolvedCommit===S.resolvedCommit&&c.packageHash===S.packageHash?p.unchanged.push(c):p.updated.push(c)}catch(c){p.failed.push({id:S.id,error:c instanceof Error?c.message:String(c)})}return p}r(y,"updateAll");async function w(m){let p=I(m),S=await O(t);return V(o,L(S,p.id))}r(w,"inspect");async function x(m){let p=I(m);return Y(o,p.id,async()=>{let S=await O(t),c=L(S,p.id),l=q(o,p.owner,p.repo),R=`${l}.${we()}.remove`;v(l)&&await k(l,R);try{return await X(t,i,h=>({...h,extensions:h.extensions.filter(P=>P.id!==c.id)})),await E(R,{recursive:!0,force:!0}),c}catch(h){throw v(R)&&!v(l)&&await k(R,l),h}})}r(x,"remove");async function A(m){let p=m.trim();if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(p))throw new u("Extension skill name must be lowercase kebab-case.",{code:"extension_skill_invalid_name"});let S=await d();if(S.error)throw new u(S.error,{code:"extension_registry_error"});let c=S.extensions.flatMap(te=>te.skills.filter(F=>F.name===p).map(F=>({extension:te,skill:F})));if(c.length===0)throw new u(`Extension skill not found: ${p}`,{code:"extension_skill_not_found",status:404});if(c.length>1)throw new u(`Extension skill name is ambiguous: ${p}`,{code:"extension_skill_conflict",status:409});let l=c[0];if(l.extension.validationStatus!=="valid"||l.skill.validationStatus!=="valid")throw new u(`Extension skill ${p} is not valid.`,{code:"extension_skill_invalid"});let R=$e(l.extension.sourcePath,l.skill.relativePath),h=await Je(R,"utf8"),P=He("sha256").update(h).digest("hex");if(P!==l.skill.sourceHash)throw new u(`Extension skill ${p} changed on disk. Update or reinstall its extension before using it.`,{code:"extension_skill_modified"});let $=T(h);if($.messages.length>0||$.name!==p||!$.description)throw new u(`Extension skill ${p} is not valid. ${$.messages.join(" ")}`.trim(),{code:"extension_skill_invalid"});return{name:p,description:$.description,body:$.body,path:l.skill.relativePath,sourcePath:l.extension.sourcePath,sourceHash:P,charCount:h.length,packagePath:g.dirname(R),resourceFiles:l.skill.resourceFiles}}return r(A,"readSkill"),{rootPath:o,registryPath:n,list:d,preview:a,add:b,update:f,updateAll:y,inspect:w,remove:x,readSkill:A}}r(Oe,"createGithubExtensionManager");async function fe(e){let t=e.resolution.preview,o=q(e.rootPath,t.owner,t.repo),n=`${o}.${we()}.install`,s=Z(e.rootPath,t.id),i=g.join(n,"current");await E(n,{recursive:!0,force:!0}),await E(s,{recursive:!0,force:!0}),await W(i,{recursive:!0,mode:448});try{await e.github.download(e.resolution,async(a,b,f)=>{let y=$e(i,a);await W(g.dirname(y),{recursive:!0,mode:448}),await Re(y,b,{mode:f?448:384})});let d=Ve(t,o,e.installedAt,e.updatedAt);return await Re(g.join(n,"extension.json"),`${JSON.stringify(d,null,2)}
4
4
  `,{mode:384}),await W(g.dirname(o),{recursive:!0,mode:448}),v(o)&&await k(o,s),await k(n,o),d}catch(d){throw await E(n,{recursive:!0,force:!0}),v(s)&&!v(o)&&await k(s,o),d}}r(fe,"materializeExtension");function Ve(e,t,o,n){let s=g.join(t,"current");return{...e,sourcePath:s,readmePath:e.readmePath?g.join(s,e.readmePath):null,installedAt:o,updatedAt:n,skills:e.skills.map(i=>({...i,sourcePath:g.join(s,i.relativePath)}))}}r(Ve,"installedExtension");async function Pe(e,t){await E(Z(e,t),{recursive:!0,force:!0})}r(Pe,"finalizeMaterialization");async function ye(e,t){let o=I(t.replace(/^github:/,"")),n=q(e,o.owner,o.repo),s=Z(e,t);await E(n,{recursive:!0,force:!0}),v(s)&&await k(s,n)}r(ye,"rollbackMaterialization");async function V(e,t){let o=q(e,t.owner,t.repo),n=g.join(o,"current"),s=(await Ke(g.join(o,"extension.json")).catch(()=>null))?.isFile()??!1,i=t.validationMessages.filter(d=>d!=="Installed files are missing.");return s||i.push("Installed files are missing."),{...t,sourcePath:n,readmePath:t.readmePath?g.join(n,g.basename(t.readmePath)):null,skills:t.skills.map(d=>({...d,sourcePath:g.join(n,d.relativePath)})),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(V,"hydrateExtension");function Ie(e){if(e.validationStatus!=="valid")throw new u(`Extension contains invalid skills: ${e.validationMessages.join(" ")}`,{code:"extension_invalid"})}r(Ie,"assertInstallable");function U(e,t,o){let n=new Map;for(let i of o)n.set(i,"a shipped OpenPond skill");for(let i of t)for(let d of i.skills)n.set(d.name,i.id);let s=e.skills.map(i=>({name:i.name,owner:n.get(i.name)})).filter(i=>!!i.owner);if(s.length!==0)throw new u(`Skill name conflict: ${s.map(i=>`${i.name} (${i.owner})`).join(", ")}.`,{code:"extension_skill_conflict",status:409})}r(U,"assertSkillNamesAvailable");function Xe(e,t,o){if(e.extensions.some(n=>n.id===t.id))throw new u(`${t.owner}/${t.repo} is already installed.`,{code:"extension_already_installed",status:409});return U(t,e.extensions,o),[...e.extensions,t].sort(Q)}r(Xe,"appendInstalledExtension");function Ye(e,t,o){return L(e,t.id),U(t,e.extensions.filter(n=>n.id!==t.id),o),e.extensions.map(n=>n.id===t.id?t:n).sort(Q)}r(Ye,"replaceInstalledExtension");function Ze(e,t){let o=new Map;for(let n of t)o.set(n,"built-in");for(let n of e)for(let s of n.skills){let i=o.get(s.name);if(!i){o.set(s.name,n.id);continue}let d=`Skill name conflicts with ${i}: ${s.name}`;s.validationStatus="error",s.validationMessages=[...new Set([...s.validationMessages,d])],n.validationStatus="error",n.validationMessages=[...new Set([...n.validationMessages,d])]}}r(Ze,"markInstalledSkillConflicts");async function C(e){let t=typeof e=="function"?await e():e??[];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}r(C,"reservedSkillNames");function L(e,t){let o=e.extensions.find(n=>n.id===t);if(o)return o;throw new u(`${t.replace(/^github:/,"")} is not installed.`,{code:"extension_not_installed",status:404})}r(L,"requireInstalled");async function O(e){let t=B(e,"extension_installations","registry")?.value;if(!t)return et();if(t.schemaVersion!==M||!Array.isArray(t.extensions)||!t.extensions.every(ve))throw new Error("Extension registry has an unsupported format.");return Qe(t)}r(O,"readRegistry");async function X(e,t,o){await N(g.join(z(e).runtime,"extension-registry"),async()=>{let n=B(e,"extension_installations","registry"),s=o(await O(e));oe(e,"extension_installations","registry",{...s,schemaVersion:M,updatedAt:t().toISOString()},n?.revision??null)})}r(X,"writeRegistry");function Qe(e){return{schemaVersion:M,updatedAt:typeof e?.updatedAt=="string"?e.updatedAt:null,extensions:Array.isArray(e?.extensions)?e.extensions.filter(ve):[]}}r(Qe,"normalizeRegistry");function et(){return{schemaVersion:M,updatedAt:null,extensions:[]}}r(et,"emptyRegistry");function ve(e){if(!e||typeof e!="object")return!1;let t=e;return t.source==="github"&&typeof t.id=="string"&&typeof t.owner=="string"&&typeof t.repo=="string"&&typeof t.repositoryUrl=="string"&&typeof t.requestedRef=="string"&&typeof t.resolvedCommit=="string"&&Array.isArray(t.skills)}r(ve,"isStoredExtension");function $e(e,t){if(g.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new u(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});let o=g.resolve(e,...t.split("/")),n=`${g.resolve(e)}${g.sep}`;if(!o.startsWith(n))throw new u(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});return o}r($e,"safeDestination");function q(e,t,o){return g.join(e,"github",t,o)}r(q,"extensionDirectory");function Z(e,t){let o=I(t.replace(/^github:/,""));return`${q(e,o.owner,o.repo)}.previous`}r(Z,"backupDirectory");async function Y(e,t,o){let n=t.replace(/[^a-z0-9.-]+/gi,"-");return N(g.join(e,".locks",n),o,We)}r(Y,"withExtensionLock");function Q(e,t){return e.id.localeCompare(t.id)}r(Q,"extensionSort");async function Ln(e,t,o=Oe({reservedSkillNames:r(async()=>{let n=await D();return[...se,...n.skills.map(s=>s.name)]},"reservedSkillNames")})){let n=t[0]?.toLowerCase()||"list",s=G(e.json);if(n==="list"){let i=await o.list();if(i.error)throw new Error(i.error);tt(i.extensions,s);return}if(n==="add"||n==="preview"){let d={source:_(t[1],n),ref:Ce(e.ref)},a=n==="preview"?await o.preview(d):await o.add(d);ee(a,s,n==="preview"?"Preview":"Installed");return}if(n==="inspect"){ee(await o.inspect(_(t[1],n)),s,"Installed");return}if(n==="update"){if(G(e.all)){let a=await o.updateAll();if(s)console.log(JSON.stringify(a,null,2));else{console.log(`Updated ${a.updated.length}; unchanged ${a.unchanged.length}; failed ${a.failed.length}.`);for(let b of a.failed)console.log(`- ${b.id}: ${b.error}`)}a.failed.length>0&&(process.exitCode=1);return}let i=_(t[1],n),d=await o.update({source:i,ref:Ce(e.ref)});ee(d,s,"Updated");return}if(n==="remove"){let i=await o.remove(_(t[1],n));console.log(s?JSON.stringify({removed:i},null,2):`Removed ${i.owner}/${i.repo} and ${i.skills.length} skill(s).`);return}throw new Error("usage: openpond extension <add|preview|list|inspect|update|remove> [owner/repo] [--ref <ref>] [--all] [--json]")}r(Ln,"runOpenPondExtensionCommand");function ee(e,t,o){if(t){console.log(JSON.stringify(e,null,2));return}console.log(`${o} ${e.owner}/${e.repo}@${e.resolvedCommit.slice(0,12)} (${e.requestedRef}).`);for(let n of e.skills){let s=n.resourceFiles.length>0?`, ${n.resourceFiles.length} resource(s)`:"";console.log(`- ${n.name}${s}: ${n.description}`)}}r(ee,"printExtension");function tt(e,t){if(t){console.log(JSON.stringify({extensions:e},null,2));return}if(e.length===0){console.log("No third-party extensions installed.");return}console.log(`Third-party extensions (${e.length}):`);for(let o of e)console.log(`- ${o.owner}/${o.repo}@${o.resolvedCommit.slice(0,12)} \xB7 ${o.skills.length} skill(s) \xB7 ${o.validationStatus}`)}r(tt,"printExtensionList");function _(e,t){let o=e?.trim();if(o)return o;throw new Error(`usage: openpond extension ${t} <owner/repo>`)}r(_,"requiredSource");function Ce(e){return typeof e=="string"&&e.trim()?e.trim():void 0}r(Ce,"optionText");export{Ln as runOpenPondExtensionCommand};
@@ -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-E4U7LXSW.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-3LG4G5JR.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
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{j as a,k as b}from"./chunk-I6DQSOSF.js";import"./chunk-FQOVC2GR.js";import"./chunk-PKBU37CH.js";import"./chunk-Z3RBK6LN.js";import"./chunk-BLXEK5F7.js";import"./chunk-FOW3LI6G.js";import"./chunk-L3KS6MOV.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as loadHostedHarnessRuntime,b as loadHostedHarnessRuntimeForSession};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{la as l,pa as c}from"./chunk-FQOVC2GR.js";import"./chunk-Z3RBK6LN.js";import{M as n}from"./chunk-BLXEK5F7.js";import"./chunk-FOW3LI6G.js";import"./chunk-L3KS6MOV.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as t}from"./chunk-FTQLQJQV.js";import{mkdir as f}from"node:fs/promises";import p from"node:path";import a from"node:path";function d(e,o){let s=a.resolve(e),r=a.resolve(o);return r===s||r.startsWith(`${s}${a.sep}`)}t(d,"isHostedProfileSourceWithinRepo");async function m(e){if(!p.isAbsolute(e.repoPath)||!p.isAbsolute(e.outputDir)||!/^[a-f0-9]{40,64}$/.test(e.sourceRevision)||!e.workspaceId.trim()||!e.repositoryId.trim()||!e.profileId.trim())throw new Error("Hosted Profile compile request is invalid.");let o=await n({repoPath:e.repoPath,profileId:e.profileId});if(o.error||o.mode!=="local"||o.activeProfile!==e.profileId||!o.sourcePath||!d(e.repoPath,o.sourcePath))throw new Error("Hosted Profile source is unavailable.");await f(e.outputDir,{recursive:!0});let s=await l({storeDir:e.outputDir,workspaceId:e.workspaceId,name:e.profileId,profile:o,sourceRevision:e.sourceRevision,repositoryId:e.repositoryId}),r=s.harnessRelease.metadata.profile;if(!r||typeof r!="object"||r.id!==e.profileId||r.sourceRevision!==e.sourceRevision||r.repositoryId!==e.repositoryId)throw new Error("Hosted Profile release provenance is invalid.");let i=await c({storeDir:e.outputDir,workspaceId:e.workspaceId,compiled:s,createdAt:new Date().toISOString()});return{workspaceId:e.workspaceId,sourceRevision:i.sourceRevision,harnessRelease:i.harnessRelease,agentSnapshot:i.agentSnapshot,bundlePath:i.bundlePath}}t(m,"compileHostedProfileRelease");async function H(e){if(e.length!==1||e[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(e[0]))throw new Error("Hosted Profile compile argument is invalid.");let o=JSON.parse(Buffer.from(e[0],"base64url").toString("utf8")),s=await m(o);process.stdout.write(`${JSON.stringify(s)}
3
+ `)}t(H,"runHostedProfileCompilerCli");export{m as compileHostedProfileRelease,H as runHostedProfileCompilerCli};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-CWW2EK77.js";import"./chunk-MXLB6MEW.js";import{c as B}from"./chunk-XCTFXXVY.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-OGPHXXCD.js";import"./chunk-BAKCGJ5D.js";import"./chunk-Z6F6PYF4.js";import{d as k}from"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-PZ2ZILPN.js";import{ga as y}from"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import{f as m}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({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 x({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,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
2
+ import"./chunk-EIB7GHIQ.js";import"./chunk-5YUITAUN.js";import{c as B}from"./chunk-FFEI7IRU.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZ6N7WFI.js";import"./chunk-UJLZRM2M.js";import{d as k}from"./chunk-6EAQL7YX.js";import"./chunk-GLUWATL5.js";import"./chunk-IYROEHYB.js";import"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-XLVFY2BA.js";import{R as y}from"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-3LG4G5JR.js";import{f as m}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({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 x({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,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
3
3
  `),console.log(JSON.stringify({finishReason:h,usage:w,text:g},null,2));return}if(e==="smoke"){let a=await R({apiBaseUrl:c,token:l,defaultModel:o(r,"model")||void 0,compatibilityModel:o(r,"compatibilityModel")||o(r,"compatModel")||void 0,skipStream:m(r.skipStream),skipTool:m(r.skipTool),log:i(p=>console.log(p),"log")});m(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>] [chat --model <id> --effort <off|low|medium|high|xhigh|max>]")}i(G,"runOpChatCommand");async function E(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":b()}});if(!n.ok)throw new Error(`Hosted provider catalog failed: ${n.status} ${await T(n)}`);return n.json()}i(E,"getOpChatProviderCatalog");async function T(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(T,"readResponseError");function P(r,t){let e=o(t,"opchatApiBaseUrl")||o(t,"opchatApiBaseurl")||o(t,"opChatApiBaseUrl")||o(t,"opChatApiBaseurl")||o(t,"opchatApiUrl")||o(t,"opChatApiUrl");return e?u({opChatApiBaseUrl:e}):u({apiBaseUrl:U(t)||r.apiBaseUrl,chatApiBaseUrl:C(t)||r.chatApiBaseUrl})}i(P,"resolveOpChatCliBaseUrl");function o(r,t){let e=r[t];return typeof e=="string"?e.trim():""}i(o,"optionString");export{G as runOpChatCommand};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{m as B}from"./chunk-5YUITAUN.js";import"./chunk-FFEI7IRU.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-BLXEK5F7.js";import"./chunk-L3KS6MOV.js";import"./chunk-DAOLQUAK.js";import"./chunk-6MI4KKWF.js";import"./chunk-DG4DIFF4.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZ6N7WFI.js";import"./chunk-UJLZRM2M.js";import"./chunk-6EAQL7YX.js";import"./chunk-GLUWATL5.js";import"./chunk-IYROEHYB.js";import{d as x,e as C}from"./chunk-MJC26GOX.js";import"./chunk-2O5UZOYL.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-XLVFY2BA.js";import"./chunk-L6NNQUAT.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-3LG4G5JR.js";import{a as E,f as b,h as k,i as _}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,Ee=new URL(x).hostname,_e=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function M(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(M,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??M(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 N(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(N,"resolveMcpProbeResourceUrl");function D(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(D,"resolveMcpProbeOrigin");function $(e=32){return ae(e).toString("base64url")}o($,"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 j(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(j,"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 j(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 j(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 q(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 q(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(q,"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 q(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 F(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=E(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(F,"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 J(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(J,"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.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function yo(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=N(i,e),p=D(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=F(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await J({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=N(i,e),p=D(c,e),a=ge(e),l=fe(e),d=$(18),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}),K=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",G=F(e),W=await J({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:G,toolName:K}),V=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",...V?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:W},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(yo,"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,j 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,F as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,J as probeOrganizationMcp,$ as randomOauthToken,q as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,D as resolveMcpProbeOrigin,N as resolveMcpProbeResourceUrl,yo as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};