openpond 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{actions-command-QP3NMDK4.js → actions-command-F55CBR2K.js} +1 -1
- package/dist/chunks/{app-layer-N7VFRVJ2.js → app-layer-GNYLOBCX.js} +1 -1
- package/dist/chunks/{app-server-runtime-OCLPUI7F.js → app-server-runtime-COMMPGJI.js} +1 -1
- package/dist/chunks/{apps-AMG75TI4.js → apps-HZ5JGBDR.js} +1 -1
- package/dist/chunks/{chunk-KV553EWX.js → chunk-A42DFLOR.js} +1 -1
- package/dist/chunks/{chunk-FY7OQ5RK.js → chunk-AF57BF75.js} +1 -1
- package/dist/chunks/{chunk-VCLCFK3O.js → chunk-AYNQVLKC.js} +1 -1
- package/dist/chunks/{chunk-FGJ5LFPL.js → chunk-CCJG7GLE.js} +1 -1
- package/dist/chunks/{chunk-PI36UHRA.js → chunk-CS2YWVB2.js} +1 -1
- package/dist/chunks/chunk-EG3XB6M6.js +5 -0
- package/dist/chunks/{chunk-MGN6GLNZ.js → chunk-GEANXBLX.js} +1 -1
- package/dist/chunks/{chunk-F65NIZLM.js → chunk-GPZYIVFV.js} +11 -11
- package/dist/chunks/{chunk-C5LOZSVS.js → chunk-I7G35U7K.js} +1 -1
- package/dist/chunks/{chunk-5O7ZVCMV.js → chunk-K35OOAW2.js} +1 -1
- package/dist/chunks/{chunk-UKUVMXOW.js → chunk-KDXLNQNF.js} +4 -4
- package/dist/chunks/{chunk-BBG546O6.js → chunk-KV2IXO2T.js} +1 -1
- package/dist/chunks/chunk-NVGMZ2IN.js +2 -0
- package/dist/chunks/{chunk-XDHAGACI.js → chunk-T5XCPX4P.js} +2 -2
- package/dist/chunks/{chunk-5BBVEWG3.js → chunk-VRJOWJD7.js} +1 -1
- package/dist/chunks/{chunk-OG5Q6NXK.js → chunk-XAYIETBO.js} +17 -17
- package/dist/chunks/{chunk-KU7QOHFT.js → chunk-XBIPACT7.js} +272 -272
- package/dist/chunks/{cli-M2FG7SSI.js → cli-7MM63CRQ.js} +1 -1
- package/dist/chunks/{configuration-command-XBKBIZBO.js → configuration-command-HAPIYG25.js} +1 -1
- package/dist/chunks/{core-commands-LUZVWXQR.js → core-commands-N37UZEVE.js} +1 -1
- package/dist/chunks/{desktop-test-KGC4JVJ7.js → desktop-test-V7FBEG7U.js} +1 -1
- package/dist/chunks/{extension-NQ7N5LEY.js → extension-NEPOQ44P.js} +1 -1
- package/dist/chunks/{help-MWK66XZK.js → help-HC4N5ZQC.js} +1 -1
- package/dist/chunks/{opchat-XJZA3QKZ.js → opchat-C7XRN4ZW.js} +1 -1
- package/dist/chunks/{organizations-UECDFEYE.js → organizations-LQGRZJ2V.js} +1 -1
- package/dist/chunks/{profile-KUMIZURM.js → profile-UWM24A7R.js} +1 -1
- package/dist/chunks/{project-agent-NILMJHLV.js → project-agent-2ME52ZJW.js} +1 -1
- package/dist/chunks/{sandbox-command-QHH65OSE.js → sandbox-command-53L3ZICT.js} +1 -1
- package/dist/chunks/{sandbox-template-N7I63PNU.js → sandbox-template-55HUM5H7.js} +1 -1
- package/dist/chunks/{src-VTKTTKQO.js → src-B2N4TLGC.js} +70 -70
- package/dist/chunks/{src-724HF43W.js → src-VGW2UEMV.js} +1 -1
- package/dist/chunks/{teams-bot-UV4RU53M.js → teams-bot-FHD2HCHN.js} +1 -1
- package/dist/chunks/{workspaces-XXT4KUD3.js → workspaces-TT47MTQ5.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/{App-DxecRQUL.js → App-BoJQRfeu.js} +29 -29
- package/dist/web/assets/{AppDialog-B65Eo3gp.js → AppDialog-rdfmJsGF.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-B2EKQM7W.js → AppTerminalPanel-CLW0kxtg.js} +2 -2
- package/dist/web/assets/{AppsView-BBoVe7s2.js → AppsView-DxMXadnp.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-CSM1atSJ.js → BrowserSidebar-BH_jl0JS.js} +1 -1
- package/dist/web/assets/{CartesianChart-CJKfXiEG.js → CartesianChart-oT_rMYpf.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-BMZamWFC.js → CollaborationTabs-CukgFGE0.js} +1 -1
- package/dist/web/assets/{CommandMenu-B3U1z2eo.js → CommandMenu-2btBTgOF.js} +1 -1
- package/dist/web/assets/{CommunityView-CTyRUcfy.js → CommunityView-DMTREmN5.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-D7usvRtK.js → ComposerCreateImproveStrip-3tN55cg9.js} +1 -1
- package/dist/web/assets/{GetStartedView-Ibu7oKWJ.js → GetStartedView-CMHL24_w.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-CqkSelkC.js +1 -0
- package/dist/web/assets/HostedModelLearningSettings-xqd2lSW3.js +1 -0
- package/dist/web/assets/{LabModelVersionDetailPage-s9uUN6fV.js → LabModelVersionDetailPage-Bpnya5DM.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-BKYseMiJ.js → LabSkillSidebar-BKZjScr8.js} +1 -1
- package/dist/web/assets/LabsRoute-BhPFmA_Z.js +32 -0
- package/dist/web/assets/{MainChatThread-DvuyMcMB.js → MainChatThread-Bosxokt-.js} +2 -2
- package/dist/web/assets/{MainPane-BWwcxgHD.js → MainPane-Di-Rwe7x.js} +4 -4
- package/dist/web/assets/{MarkdownText-D8XC5UT_.js → MarkdownText-dK4SBPp_.js} +1 -1
- package/dist/web/assets/{Messages-e4A8JUjD.js → Messages-ftYRMKYa.js} +5 -5
- package/dist/web/assets/{NativeSkillSidebar-D2Joh8XB.js → NativeSkillSidebar-Cwo7JdB2.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-CzGebt2E.js → NewExperienceSwitcher-C1_JzTq2.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-CdMTSxUE.js → NewProjectDialog-CxP6v6YW.js} +1 -1
- package/dist/web/assets/{OutputsPage-m7cSb8dW.js → OutputsPage-DL21_Alp.js} +1 -1
- package/dist/web/assets/{ProjectsPage-C9mz8W1g.js → ProjectsPage-BO9VyvMA.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-B4LEqKEj.js → RightChatPanelStack-DaqAnzdR.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-DOeUsH7h.js → RightSidebarHomePanel-PbUG12AO.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-UXZSSWgA.js → ScheduledWorkPage-BhL-cXML.js} +1 -1
- package/dist/web/assets/{SettingsView-CQm1ai73.js → SettingsView-D6-s7G88.js} +3 -3
- package/dist/web/assets/{TeamChatView-C4haojB7.js → TeamChatView-DbS1N-fo.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-p2GZsuyQ.js → TerminalOverlay-CphyBXJR.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-BYJSlO8X.js → TrainingCreationPanel-Czsdraix.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-DR5KlayH.js → TrainingDraftPanel-Bq3B5pUk.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-BQToNXE4.js → UsageSettingsSection-B74FNwaP.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel--EeytWeg.js → WorkSidebarPanel-BgaK4XSg.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-BrovSYhn.js → WorkspaceDiffPanel-C3seHnVY.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-l-keRgvj.js → WorkspaceEnvironmentMenu-DPghQUdv.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-aicWzaZu.js → WorkspaceGitDialogs-D8c6Okb_.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-CO_E74jM.js → WorkspaceMonacoEditor-2kjRFf4l.js} +3 -3
- package/dist/web/assets/{arrow-up-right-rwPXNfVn.js → arrow-up-right-C5X-29oa.js} +1 -1
- package/dist/web/assets/{chat-file-links-B3jDstSC.js → chat-file-links-Bmz9kVct.js} +1 -1
- package/dist/web/assets/chevron-up-NbP9vY4E.js +1 -0
- package/dist/web/assets/{clipboard-DwEExyU4.js → clipboard-fvHMXPWa.js} +1 -1
- package/dist/web/assets/{cloud-upload-D2he0-vQ.js → cloud-upload-BAycsdHL.js} +1 -1
- package/dist/web/assets/{cssMode-DS4k0NcI.js → cssMode-Yis679a5.js} +1 -1
- package/dist/web/assets/{folder-open-CAOLduKD.js → folder-open-bii4KUCv.js} +1 -1
- package/dist/web/assets/{folder-plus-D56MrxVT.js → folder-plus-B0B7mUCx.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CeNM0oKJ.js → git-commit-horizontal-B6yTdtnB.js} +1 -1
- package/dist/web/assets/{htmlMode-Xkni5erh.js → htmlMode-DHeBSKVF.js} +1 -1
- package/dist/web/assets/{index-KwyAyscP.js → index-667pXXsu.js} +1 -1
- package/dist/web/assets/{info-CcrBaEE_.js → info-NCOESX3I.js} +1 -1
- package/dist/web/assets/{jsonMode-C4YPbQB7.js → jsonMode-C4oxy1cU.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-CF5oMTz6.js → lspLanguageFeatures-CLj3WGZW.js} +1 -1
- package/dist/web/assets/{minimize-2-DzHQnInk.js → minimize-2-DtI1vgd7.js} +1 -1
- package/dist/web/assets/{monaco.contribution-CkPGKNd-.js → monaco.contribution-DZPgekIQ.js} +2 -2
- package/dist/web/assets/{monaco.contribution-0EN4mGCC.js → monaco.contribution-Ddw-TznO.js} +2 -2
- package/dist/web/assets/{monaco.contribution-B4qcTP0w.js → monaco.contribution-DhVPJ-oY.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CJK_NrBm.js → monaco.contribution-DrW6DjWP.js} +2 -2
- package/dist/web/assets/{play-p3-AMTPL.js → play-DB3XFAnG.js} +1 -1
- package/dist/web/assets/{python-B0kpTxAZ.js → python-DLyUeEeL.js} +1 -1
- package/dist/web/assets/{refresh-cw-_jbTIzzr.js → refresh-cw-0zSLZtfp.js} +1 -1
- package/dist/web/assets/{save-Cy6hEotx.js → save-BCZlshOA.js} +1 -1
- package/dist/web/assets/{square-DKQkcrOH.js → square-CRytZWR_.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-Bnk1VVVq.js → toggleHighContrast-TXg0rI_R.js} +1 -1
- package/dist/web/assets/{tsMode-BDrSVy7V.js → tsMode-Bj1019AY.js} +1 -1
- package/dist/web/assets/{upload-COn0my_O.js → upload-CnE9u7GB.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-iZNB4Oee.js → useLocalAgentSchedules-qI87RHVI.js} +1 -1
- package/dist/web/assets/{wifi-off-Cqt-ZLXY.js → wifi-off-CfuwRBx7.js} +1 -1
- package/dist/web/assets/{workers-hu0Ym93h.js → workers-CXdUI7wU.js} +1 -1
- package/dist/web/assets/{yaml-D-JLDGL6.js → yaml-AP8aiwLm.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-SAE4OIPC.js +0 -2
- package/dist/chunks/chunk-ZF7TEGY5.js +0 -5
- package/dist/web/assets/HostedModelLearningReview-qnzIkT70.js +0 -1
- package/dist/web/assets/HostedModelLearningSettings--PKjpYsy.js +0 -1
- package/dist/web/assets/LabsRoute-DoRs0K6v.js +0 -32
- package/dist/web/assets/chevron-up-D089nvYQ.js +0 -1
|
@@ -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-
|
|
2
|
+
import{e as g,g as $,h as O,i as C}from"./chunk-T5XCPX4P.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{q as z,r as V,s as G,t as q}from"./chunk-
|
|
2
|
+
import{q as z,r as V,s as G,t as q}from"./chunk-CCJG7GLE.js";import{a as A,f as v,g as k,h as p,i as f}from"./chunk-3M53YXEI.js";import{a}from"./chunk-FTQLQJQV.js";import{Buffer as Y}from"node:buffer";import{readdirSync as H,readFileSync as Q,statSync as F}from"node:fs";import b from"node:path";var K=500,Z=8*1024*1024,W=8*1024*1024;async function me(e,t){if(!t.sandboxRuntime&&!t.runtimeId)return{sandbox:await X(e,await e.create(t.sandbox,{async:!0}))};let n=t.runtimeId?void 0:await e.createSandboxRuntime(t.sandboxRuntime),r=t.runtimeId??n.id,o=await e.createSandboxRuntimeSandbox(r,t.sandbox);return{sandbox:await X(e,o.sandbox),runtime:o.runtime??n}}a(me,"createSandboxFromPlan");async function X(e,t){if(t.state==="running"||t.state==="stopped")return t;if(t.state==="error")throw new Error(`sandbox create failed: ${t.id}
|
|
3
3
|
${t.logs.join(`
|
|
4
4
|
`)}`);let n=12*6e4,r=3e3,o=Date.now()+n,i=t;for(;Date.now()<o;){if(await new Promise(s=>setTimeout(s,r)),i=await e.get(t.id),i.state==="running"||i.state==="stopped")return i;if(i.state==="error")throw new Error(`sandbox create failed: ${i.id}
|
|
5
5
|
${i.logs.join(`
|
|
@@ -1,12 +1,12 @@
|
|
|
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 N="https://openpond.ai",$="https://api.openpond.ai",k="https://api.openpond.ai/opchat/v1";function C(o){let e=o.trim().replace(/\/$/,"");if(!e)throw new Error("sandbox API URL must be non-empty");let t=new URL(e),r=t.pathname.replace(/\/$/,"");return r.endsWith("/v1/sandboxes")||r.endsWith("/api/sandboxes")?`${t.origin}${r}`:r.endsWith("/v1")?`${t.origin}${r}/sandboxes`:Q(t.hostname)?`${t.origin}${r}/v1/sandboxes`:t.origin===N?`${$}/v1/sandboxes`:`${t.origin}${r}/api/sandboxes`}n(C,"normalizeSandboxApiUrl");function L(o){let e="/sandboxes";if(!o.endsWith(e))throw new Error("sandbox API URL must end with /sandboxes");return o.slice(0,-e.length)}n(L,"apiRootUrlFromSandboxApiUrl");function Q(o){return o==="api.openpond.ai"||o.startsWith("api")&&o.endsWith(".openpond.ai")}n(Q,"isOpenPondHostedApiHost");function B(o){return{list:n((e={})=>o.listSandboxRuntimes(e),"list"),create:n(e=>o.createSandboxRuntime(e),"create"),handle:n((e,t=null)=>o.sandboxRuntime(e,t),"handle"),get:n(e=>o.getSandboxRuntime(e),"get"),createSandbox:n((e,t={},r={})=>o.createSandboxRuntimeSandbox(e,t,r),"createSandbox"),updateStatus:n((e,t)=>o.updateSandboxRuntimeStatus(e,t),"updateStatus"),events:n(e=>o.listSandboxRuntimeEvents(e),"events"),event:n((e,t)=>o.emitSandboxRuntimeEvent(e,t),"event"),checkpoint:n((e,t={})=>o.checkpointSandboxRuntime(e,t),"checkpoint"),promote:n((e,t,r={})=>o.promoteSandboxRuntime(e,t,r),"promote"),preserveSource:n((e,t={},r={})=>o.preserveSandboxRuntimeSource(e,t,r),"preserveSource")}}n(B,"createSandboxRuntimeNamespace");function z(o){return{list:n((e={})=>o.list(e),"list"),create:n(e=>o.create(e),"create"),get:n(e=>o.get(e),"get"),pricing:n(()=>o.pricing(),"pricing"),costs:n((e={})=>o.costs(e),"costs")}}n(z,"createSandboxNamespace");function D(o){return{list:n(e=>o.listProjects(e),"list"),upsert:n(e=>o.upsertProject(e),"upsert"),upsertGitRemote:n(e=>o.upsertProjectGitRemote(e),"upsertGitRemote"),get:n((e,t)=>o.getProject(e,t),"get"),update:n((e,t)=>o.updateProject(e,t),"update"),sync:n((e,t)=>o.syncProject(e,t),"sync"),ensureGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"ensureGitRemote"),getGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"getGitRemote"),git:n((e,t)=>o.ensureProjectGitRemote(e,t),"git"),uploadSource:n((e,t)=>o.uploadProjectSource(e,t),"uploadSource"),archive:n((e,t)=>o.archiveProject(e,t),"archive")}}n(D,"createSandboxProjectNamespace");function J(o){return{get:n(e=>o.getHostedProfile(e),"get"),status:n(e=>o.getHostedProfile(e),"status"),ensureHosted:n(e=>o.ensureHostedProfile(e),"ensureHosted"),push:n(e=>o.pushHostedProfile(e),"push")}}n(J,"createSandboxProfileNamespace");function M(o){return{list:n(e=>o.listAgents(e),"list"),upsert:n(e=>o.upsertAgent(e),"upsert"),get:n((e,t)=>o.getAgent(e,t),"get"),update:n((e,t)=>o.updateAgent(e,t),"update"),archive:n((e,t)=>o.archiveAgent(e,t),"archive"),run:n((e,t)=>o.runAgent(e,t),"run"),sourceDeployPlan:n((e,t)=>o.getAgentSourceDeployPlan(e,t),"sourceDeployPlan"),manifestSnapshots:n((e,t)=>o.listAgentManifestSnapshots(e,t),"manifestSnapshots"),requestSourceChecks:n((e,t)=>o.requestAgentSourceChecks(e,t),"requestSourceChecks"),configureSourceSetup:n((e,t)=>o.configureAgentSourceSetup(e,t),"configureSourceSetup"),publishSource:n((e,t)=>o.publishAgentSource(e,t),"publishSource")}}n(M,"createSandboxAgentNamespace");function F(o,e,t=null){let r=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);return h.sandboxId?o.get(h.sandboxId):o.createSandboxRuntimeSandbox(e,a,d).then(u=>u.sandbox)},"currentSandbox"),s=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);if(!h.sandboxId)return o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox);let u=await o.get(h.sandboxId);return u.state==="stopped"?o.start(u.id,d).then(p=>p.sandbox):u.state==="archived"?o.restore(u.id).then(p=>p.sandbox):u.state==="deleted"||u.state==="error"?o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox):u},"resume");return{id:e,initial:t,get:n(()=>o.getSandboxRuntime(e),"get"),sandbox:r,resume:s,createSandbox:n((a={},d={})=>o.createSandboxRuntimeSandbox(e,a,d),"createSandbox"),status:n(async a=>{if(typeof a!="string")return o.updateSandboxRuntimeStatus(e,a);let d=await o.getSandboxRuntime(e);return o.updateSandboxRuntimeStatus(e,{status:a,expectedVersion:d.version})},"status"),events:n(()=>o.listSandboxRuntimeEvents(e),"events"),event:n(a=>o.emitSandboxRuntimeEvent(e,a),"event"),recordCommit:n((a,d={})=>o.emitSandboxRuntimeEvent(e,{...d,type:d.type??"git.commit",commitSha:a}),"recordCommit"),checkpointHint:n((a={})=>o.emitSandboxRuntimeEvent(e,{type:"workflow.checkpoint_hint",summary:a.summary??a.reason??"Workflow checkpoint hint",payload:{...a.payload,reason:a.reason??null},artifactRefs:a.artifactRefs,lifecycleHint:{kind:"checkpoint",reason:a.reason??null}}),"checkpointHint"),waitForUser:n(async(a={})=>{await o.emitSandboxRuntimeEvent(e,{type:"workflow.waiting_for_user",summary:a.summary??a.reason??"Waiting for user",payload:{...a.payload,reason:a.reason??null},lifecycleHint:{kind:"waiting_for_user",reason:a.reason??null}});let d=await o.getSandboxRuntime(e);return d.status==="waiting_for_user"?d:o.updateSandboxRuntimeStatus(e,{status:"waiting_for_user",expectedVersion:d.version,summary:a.summary??a.reason,metadata:{workflowWaitForUserReason:a.reason??null}})},"waitForUser"),keepAlive:n((a={})=>{let d=Z(a);return o.emitSandboxRuntimeEvent(e,{type:"workflow.keepalive",summary:a.summary??a.reason??"Workflow keepalive",payload:{...a.payload,reason:a.reason??null,keepaliveUntil:d},lifecycleHint:{kind:"keepalive",reason:a.reason??null,keepaliveUntil:d}})},"keepAlive"),checkpoint:n(a=>o.checkpointSandboxRuntime(e,a),"checkpoint"),files:{write:n(async(a,d)=>o.uploadFile((await s()).id,a,d),"write"),read:n(async a=>o.downloadFile((await s()).id,a),"read"),readResponse:n(async a=>o.downloadFileResponse((await s()).id,a),"readResponse"),list:n(async(a={})=>o.listFiles((await s()).id,a),"list"),delete:n(async(a,d={})=>o.deleteFile((await s()).id,a,d),"delete"),search:n(async a=>o.searchFiles((await s()).id,a),"search"),stat:n(async a=>o.statFile((await s()).id,a),"stat"),mkdir:n(async a=>o.mkdir((await s()).id,a),"mkdir"),move:n(async a=>o.moveFile((await s()).id,a),"move")},commands:{run:n(async a=>o.exec((await s()).id,typeof a=="string"?{command:a}:a),"run")},ports:{expose:n(async a=>o.openPort((await s()).id,typeof a=="number"?{port:a}:a),"expose")},promote:n((a,d={})=>o.promoteSandboxRuntime(e,a,d),"promote"),preserveSource:n((a={},d={})=>o.preserveSandboxRuntimeSource(e,a,d),"preserveSource"),archive:n(async a=>{let d=a??(await o.getSandboxRuntime(e)).version;return o.updateSandboxRuntimeStatus(e,{status:"archived",expectedVersion:d})},"archive")}}n(F,"createSandboxRuntimeHandle");function Z(o){if(o?.until instanceof Date)return o.until.toISOString();if(typeof o?.until=="string"&&o.until.trim())return new Date(o.until).toISOString();let e=typeof o?.seconds=="number"&&Number.isFinite(o.seconds)?Math.max(1,Math.trunc(o.seconds)):60;return new Date(Date.now()+e*1e3).toISOString()}n(Z,"runtimeKeepaliveUntilIso");async function W(o,e={}){let t=`openpond-code-smoke-${Date.now()}`,r=`openpond-code-exec-ok:${t}`,s=`openpond-code-preview-ok:${t}`,i=`openpond-code-file-ok:${t}`,c=4173,m=null,a=null,d=!1,h=!1;try{let u=await G(o,await o.create({repo:e.repo??"https://github.com/octocat/Hello-World",resources:{cpu:e.cpu??1,memoryGb:e.memoryGb??1,diskGb:e.diskGb??8},budget:{maxUsd:e.budgetUsd??"0.05"},quotas:{maxSpendUsd:e.budgetUsd??"0.05",maxDurationSeconds:600,idleTimeoutSeconds:600,maxOpenPorts:2},metadata:{runId:t,source:"openpond-code-sandbox-smoke"}},{async:!0}));m=u.id;let p=e.expectedMppMode;if(p&&u.reservation.mpp?.mode!==p)throw new Error(`expected ${p} reservation, got ${u.reservation.mpp?.mode??"none"}`);if(!p&&!u.reservation.mpp?.mode)throw new Error("expected sandbox reservation MPP metadata");let S=await o.exec(u.id,{command:[`printf '${r}\\n'`,"test -f README && printf 'repo-clone-ok\\n'","cat > server.cjs <<'EOF'","const { createServer } = require('node:http');",`createServer((_request, response) => response.end('${s}')).listen(${c}, '0.0.0.0');`,"EOF","nohup node server.cjs > server.log 2>&1 & sleep 1"].join(`
|
|
3
|
-
`),timeoutSeconds:120});if(S.command.status!=="succeeded")throw new Error(`expected command success, got ${S.command.status}`);if(!S.command.output.includes(r))throw new Error("expected exec marker");if(await o.uploadFile(u.id,"openpond-code-smoke.txt",i),await o.downloadFile(u.id,"openpond-code-smoke.txt")!==i)throw new Error("expected file roundtrip marker");let
|
|
2
|
+
import{a as n}from"./chunk-FTQLQJQV.js";var N="https://openpond.ai",$="https://api.openpond.ai",k="https://api.openpond.ai/opchat/v1";function C(o){let e=o.trim().replace(/\/$/,"");if(!e)throw new Error("sandbox API URL must be non-empty");let t=new URL(e),r=t.pathname.replace(/\/$/,"");return r.endsWith("/v1/sandboxes")||r.endsWith("/api/sandboxes")?`${t.origin}${r}`:r.endsWith("/v1")?`${t.origin}${r}/sandboxes`:Q(t.hostname)?`${t.origin}${r}/v1/sandboxes`:t.origin===N?`${$}/v1/sandboxes`:`${t.origin}${r}/api/sandboxes`}n(C,"normalizeSandboxApiUrl");function L(o){let e="/sandboxes";if(!o.endsWith(e))throw new Error("sandbox API URL must end with /sandboxes");return o.slice(0,-e.length)}n(L,"apiRootUrlFromSandboxApiUrl");function Q(o){return o==="api.openpond.ai"||o==="staging-api.openpond.ai"||o.startsWith("api")&&o.endsWith(".openpond.ai")}n(Q,"isOpenPondHostedApiHost");function B(o){return{list:n((e={})=>o.listSandboxRuntimes(e),"list"),create:n(e=>o.createSandboxRuntime(e),"create"),handle:n((e,t=null)=>o.sandboxRuntime(e,t),"handle"),get:n(e=>o.getSandboxRuntime(e),"get"),createSandbox:n((e,t={},r={})=>o.createSandboxRuntimeSandbox(e,t,r),"createSandbox"),updateStatus:n((e,t)=>o.updateSandboxRuntimeStatus(e,t),"updateStatus"),events:n(e=>o.listSandboxRuntimeEvents(e),"events"),event:n((e,t)=>o.emitSandboxRuntimeEvent(e,t),"event"),checkpoint:n((e,t={})=>o.checkpointSandboxRuntime(e,t),"checkpoint"),promote:n((e,t,r={})=>o.promoteSandboxRuntime(e,t,r),"promote"),preserveSource:n((e,t={},r={})=>o.preserveSandboxRuntimeSource(e,t,r),"preserveSource")}}n(B,"createSandboxRuntimeNamespace");function z(o){return{list:n((e={})=>o.list(e),"list"),create:n(e=>o.create(e),"create"),get:n(e=>o.get(e),"get"),pricing:n(()=>o.pricing(),"pricing"),costs:n((e={})=>o.costs(e),"costs")}}n(z,"createSandboxNamespace");function D(o){return{list:n(e=>o.listProjects(e),"list"),upsert:n(e=>o.upsertProject(e),"upsert"),upsertGitRemote:n(e=>o.upsertProjectGitRemote(e),"upsertGitRemote"),get:n((e,t)=>o.getProject(e,t),"get"),update:n((e,t)=>o.updateProject(e,t),"update"),sync:n((e,t)=>o.syncProject(e,t),"sync"),ensureGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"ensureGitRemote"),getGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"getGitRemote"),git:n((e,t)=>o.ensureProjectGitRemote(e,t),"git"),uploadSource:n((e,t)=>o.uploadProjectSource(e,t),"uploadSource"),archive:n((e,t)=>o.archiveProject(e,t),"archive")}}n(D,"createSandboxProjectNamespace");function J(o){return{get:n(e=>o.getHostedProfile(e),"get"),status:n(e=>o.getHostedProfile(e),"status"),ensureHosted:n(e=>o.ensureHostedProfile(e),"ensureHosted"),push:n(e=>o.pushHostedProfile(e),"push")}}n(J,"createSandboxProfileNamespace");function M(o){return{list:n(e=>o.listAgents(e),"list"),upsert:n(e=>o.upsertAgent(e),"upsert"),get:n((e,t)=>o.getAgent(e,t),"get"),update:n((e,t)=>o.updateAgent(e,t),"update"),archive:n((e,t)=>o.archiveAgent(e,t),"archive"),run:n((e,t)=>o.runAgent(e,t),"run"),sourceDeployPlan:n((e,t)=>o.getAgentSourceDeployPlan(e,t),"sourceDeployPlan"),manifestSnapshots:n((e,t)=>o.listAgentManifestSnapshots(e,t),"manifestSnapshots"),requestSourceChecks:n((e,t)=>o.requestAgentSourceChecks(e,t),"requestSourceChecks"),configureSourceSetup:n((e,t)=>o.configureAgentSourceSetup(e,t),"configureSourceSetup"),publishSource:n((e,t)=>o.publishAgentSource(e,t),"publishSource")}}n(M,"createSandboxAgentNamespace");function F(o,e,t=null){let r=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);return h.sandboxId?o.get(h.sandboxId):o.createSandboxRuntimeSandbox(e,a,d).then(u=>u.sandbox)},"currentSandbox"),s=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);if(!h.sandboxId)return o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox);let u=await o.get(h.sandboxId);return u.state==="stopped"?o.start(u.id,d).then(p=>p.sandbox):u.state==="archived"?o.restore(u.id).then(p=>p.sandbox):u.state==="deleted"||u.state==="error"?o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox):u},"resume");return{id:e,initial:t,get:n(()=>o.getSandboxRuntime(e),"get"),sandbox:r,resume:s,createSandbox:n((a={},d={})=>o.createSandboxRuntimeSandbox(e,a,d),"createSandbox"),status:n(async a=>{if(typeof a!="string")return o.updateSandboxRuntimeStatus(e,a);let d=await o.getSandboxRuntime(e);return o.updateSandboxRuntimeStatus(e,{status:a,expectedVersion:d.version})},"status"),events:n(()=>o.listSandboxRuntimeEvents(e),"events"),event:n(a=>o.emitSandboxRuntimeEvent(e,a),"event"),recordCommit:n((a,d={})=>o.emitSandboxRuntimeEvent(e,{...d,type:d.type??"git.commit",commitSha:a}),"recordCommit"),checkpointHint:n((a={})=>o.emitSandboxRuntimeEvent(e,{type:"workflow.checkpoint_hint",summary:a.summary??a.reason??"Workflow checkpoint hint",payload:{...a.payload,reason:a.reason??null},artifactRefs:a.artifactRefs,lifecycleHint:{kind:"checkpoint",reason:a.reason??null}}),"checkpointHint"),waitForUser:n(async(a={})=>{await o.emitSandboxRuntimeEvent(e,{type:"workflow.waiting_for_user",summary:a.summary??a.reason??"Waiting for user",payload:{...a.payload,reason:a.reason??null},lifecycleHint:{kind:"waiting_for_user",reason:a.reason??null}});let d=await o.getSandboxRuntime(e);return d.status==="waiting_for_user"?d:o.updateSandboxRuntimeStatus(e,{status:"waiting_for_user",expectedVersion:d.version,summary:a.summary??a.reason,metadata:{workflowWaitForUserReason:a.reason??null}})},"waitForUser"),keepAlive:n((a={})=>{let d=Z(a);return o.emitSandboxRuntimeEvent(e,{type:"workflow.keepalive",summary:a.summary??a.reason??"Workflow keepalive",payload:{...a.payload,reason:a.reason??null,keepaliveUntil:d},lifecycleHint:{kind:"keepalive",reason:a.reason??null,keepaliveUntil:d}})},"keepAlive"),checkpoint:n(a=>o.checkpointSandboxRuntime(e,a),"checkpoint"),files:{write:n(async(a,d)=>o.uploadFile((await s()).id,a,d),"write"),read:n(async a=>o.downloadFile((await s()).id,a),"read"),readResponse:n(async a=>o.downloadFileResponse((await s()).id,a),"readResponse"),list:n(async(a={})=>o.listFiles((await s()).id,a),"list"),delete:n(async(a,d={})=>o.deleteFile((await s()).id,a,d),"delete"),search:n(async a=>o.searchFiles((await s()).id,a),"search"),stat:n(async a=>o.statFile((await s()).id,a),"stat"),mkdir:n(async a=>o.mkdir((await s()).id,a),"mkdir"),move:n(async a=>o.moveFile((await s()).id,a),"move")},commands:{run:n(async a=>o.exec((await s()).id,typeof a=="string"?{command:a}:a),"run")},ports:{expose:n(async a=>o.openPort((await s()).id,typeof a=="number"?{port:a}:a),"expose")},promote:n((a,d={})=>o.promoteSandboxRuntime(e,a,d),"promote"),preserveSource:n((a={},d={})=>o.preserveSandboxRuntimeSource(e,a,d),"preserveSource"),archive:n(async a=>{let d=a??(await o.getSandboxRuntime(e)).version;return o.updateSandboxRuntimeStatus(e,{status:"archived",expectedVersion:d})},"archive")}}n(F,"createSandboxRuntimeHandle");function Z(o){if(o?.until instanceof Date)return o.until.toISOString();if(typeof o?.until=="string"&&o.until.trim())return new Date(o.until).toISOString();let e=typeof o?.seconds=="number"&&Number.isFinite(o.seconds)?Math.max(1,Math.trunc(o.seconds)):60;return new Date(Date.now()+e*1e3).toISOString()}n(Z,"runtimeKeepaliveUntilIso");async function W(o,e={}){let t=`openpond-code-smoke-${Date.now()}`,r=`openpond-code-exec-ok:${t}`,s=`openpond-code-preview-ok:${t}`,i=`openpond-code-file-ok:${t}`,c=4173,m=null,a=null,d=!1,h=!1;try{let u=await G(o,await o.create({repo:e.repo??"https://github.com/octocat/Hello-World",resources:{cpu:e.cpu??1,memoryGb:e.memoryGb??1,diskGb:e.diskGb??8},budget:{maxUsd:e.budgetUsd??"0.05"},quotas:{maxSpendUsd:e.budgetUsd??"0.05",maxDurationSeconds:600,idleTimeoutSeconds:600,maxOpenPorts:2},metadata:{runId:t,source:"openpond-code-sandbox-smoke"}},{async:!0}));m=u.id;let p=e.expectedMppMode;if(p&&u.reservation.mpp?.mode!==p)throw new Error(`expected ${p} reservation, got ${u.reservation.mpp?.mode??"none"}`);if(!p&&!u.reservation.mpp?.mode)throw new Error("expected sandbox reservation MPP metadata");let S=await o.exec(u.id,{command:[`printf '${r}\\n'`,"test -f README && printf 'repo-clone-ok\\n'","cat > server.cjs <<'EOF'","const { createServer } = require('node:http');",`createServer((_request, response) => response.end('${s}')).listen(${c}, '0.0.0.0');`,"EOF","nohup node server.cjs > server.log 2>&1 & sleep 1"].join(`
|
|
3
|
+
`),timeoutSeconds:120});if(S.command.status!=="succeeded")throw new Error(`expected command success, got ${S.command.status}`);if(!S.command.output.includes(r))throw new Error("expected exec marker");if(await o.uploadFile(u.id,"openpond-code-smoke.txt",i),await o.downloadFile(u.id,"openpond-code-smoke.txt")!==i)throw new Error("expected file roundtrip marker");let g=null;if(e.snapshot||e.fork){let f=await o.createSnapshot(u.id,{async:!0,name:`openpond-code-smoke-${t}`,replay:{entrypoints:[{command:"cat openpond-code-smoke.txt",name:"default"}],retention:{class:"pinned"},safety:{cleanup:"delete",idleTimeoutSeconds:600,internetEgress:"block",maxDurationSeconds:600,maxSpendUsd:e.budgetUsd??"0.05",publicPreview:!1},validation:{commands:[{command:"test -f openpond-code-smoke.txt"}]}}}),l=f.snapshot??(await re(o,u.id,f.snapshotJob?.snapshotId)).snapshot;if(g=l.id,l.state!=="ready")throw new Error(`expected ready snapshot, got ${l.state}`)}if(e.fork){if(!g)throw new Error("expected snapshot id before fork");let f=await G(o,(await o.forkSnapshot(g,{budget:{maxUsd:e.budgetUsd??"0.05"},metadata:{source:"openpond-code-sandbox-smoke-fork",templateSnapshotId:g}},{async:!0})).sandbox);a=f.id;let l=await o.exec(f.id,{command:"cat openpond-code-smoke.txt",timeoutSeconds:120});if(l.command.status!=="succeeded")throw new Error(`expected fork command success, got ${l.command.status}`);if(!l.command.output.includes(i))throw new Error("expected fork snapshot marker");e.keep||(await v(o,f.id),h=!0)}let P=null;if(e.preview!==!1){let f=await o.openPort(u.id,{label:"openpond-code-smoke",port:c}),l=await fetch(f.preview.url);P=l.status;let X=await l.text();if(l.status!==200)throw new Error(`expected preview HTTP 200, got ${l.status}`);if(!X.includes(s))throw new Error("expected preview marker")}let{sandbox:U,receipts:I}=await ee(o,u.id);return e.keep||(await v(o,u.id),d=!0),{deleted:d,execOutput:S.command.output.trim(),fileRoundtrip:!0,forkSandboxId:a,previewStatus:P,receiptRefs:I.map(f=>f.mpp.receiptRef??null),reservationRef:u.reservation.mpp?.reservationRef??null,runId:t,sandboxId:u.id,snapshotId:g,state:U.state}}finally{a&&!e.keep&&!h&&await H(o,a),m&&!e.keep&&!d&&await H(o,m)}}n(W,"runSandboxSmoke");async function ee(o,e){try{await o.stop(e)}catch{await o.stop(e,{async:!0})}let t=await K(o,e,new Set(["stopped","deleted"]),"stop"),r=await te(o,e);if(r.length===0)throw new Error("expected receipt readback");return{sandbox:t,receipts:r}}n(ee,"stopSandboxForSmoke");async function v(o,e){try{let t=await o.delete(e);if(t.state==="deleted")return t;await o.delete(e,{async:!0})}catch{await o.delete(e,{async:!0})}return K(o,e,new Set(["deleted"]),"delete")}n(v,"deleteSandboxForSmoke");async function H(o,e){try{await v(o,e)}catch{await o.delete(e,{async:!0}).catch(()=>{})}}n(H,"cleanupSandboxBestEffort");async function K(o,e,t,r){let c=Date.now()+3e5,m=await o.get(e);for(;Date.now()<c;){if(t.has(m.state))return m;if(m.state==="error")throw new Error(`sandbox ${r} failed: ${e}`);await q(3e3),m=await o.get(e)}throw new Error(`sandbox ${r} did not reach ${[...t].join("/")} before timeout: ${e} (${m.state})`)}n(K,"waitForSandboxState");async function te(o,e){let s=Date.now()+12e4,i=await o.receipts(e);for(;Date.now()<s;){if(i.length>0)return i;await q(3e3),i=await o.receipts(e)}return i}n(te,"waitForReceipts");async function G(o,e){if(e.state==="running"||e.state==="stopped")return e;if(e.state==="error")throw new Error(`sandbox create failed: ${e.id}
|
|
4
4
|
${e.logs.join(`
|
|
5
5
|
`)}`);let t=12*6e4,r=3e3,s=Date.now()+t,i=e;for(;Date.now()<s;){if(await q(r),i=await o.get(e.id),i.state==="running"||i.state==="stopped")return i;if(i.state==="error")throw new Error(`sandbox create failed: ${i.id}
|
|
6
6
|
${i.logs.join(`
|
|
7
|
-
`)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${i.id} (${i.state})`)}n(G,"waitForCreateReady");async function re(o,e,t){if(!t)throw new Error("snapshot job did not return snapshot id");let r=12*6e4,s=3e3,i=Date.now()+r,c=await o.get(e);for(;Date.now()<i;){let m=c.snapshots?.find(d=>d.id===t);if(m?.state==="ready")return{sandbox:c,snapshot:m};let a=c.snapshotJobs?.find(d=>d.snapshotId===t);if(a?.status==="failed")throw new Error(`snapshot job failed: ${a.error??t}`);await q(s),c=await o.get(e)}throw new Error(`snapshot did not reach ready state before timeout: ${t}`)}n(re,"waitForSnapshotReady");function q(o){return new Promise(e=>setTimeout(e,o))}n(q,"sleep");function R(o={}){return o.async||o.respondAsync?{Prefer:"respond-async"}:void 0}n(R,"asyncRequestHeaders");var O=class extends Error{static{n(this,"ApiTimeoutError")}timeoutMs;requestUrl;code="OPENPOND_API_TIMEOUT";constructor(e,t){super(`API request timed out after ${e}ms: ${t}`),this.timeoutMs=e,this.requestUrl=t,this.name="ApiTimeoutError"}},b=class extends Error{static{n(this,"ApiResponseTooLargeError")}maximumBytes;requestUrl;code="OPENPOND_API_RESPONSE_TOO_LARGE";constructor(e,t){super(`API response exceeded ${e} bytes: ${t}`),this.maximumBytes=e,this.requestUrl=t,this.name="ApiResponseTooLargeError"}},E=class extends Error{static{n(this,"OpenPondApiError")}status;apiMessage;code;constructor(e,t,r,s=null){let i=s||t;super(`${r} failed: ${e}${i?` ${i}`:""}`),this.status=e,this.apiMessage=s,this.name="OpenPondApiError",this.code=t||"OPENPOND_API_ERROR"}};async function w(o,e,t,r={}){let{timeoutMs:s=3e4,maxResponseBytes:i=8388608,...c}=r,m=`${o}${t}`,a=new Headers(c.headers);a.set("Content-Type","application/json");let d=process.env.OPENPOND_API_KEY,h=e?.trim()||"",u=h.startsWith("opk_"),p=d||(u?h:null);p&&!a.has("openpond-api-key")&&a.set("openpond-api-key",p),e?a.set("Authorization",u?`ApiKey ${h}`:`Bearer ${e}`):d&&!a.has("Authorization")&&a.set("Authorization",`ApiKey ${d}`);let S=new AbortController,x=new O(s,m),
|
|
7
|
+
`)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${i.id} (${i.state})`)}n(G,"waitForCreateReady");async function re(o,e,t){if(!t)throw new Error("snapshot job did not return snapshot id");let r=12*6e4,s=3e3,i=Date.now()+r,c=await o.get(e);for(;Date.now()<i;){let m=c.snapshots?.find(d=>d.id===t);if(m?.state==="ready")return{sandbox:c,snapshot:m};let a=c.snapshotJobs?.find(d=>d.snapshotId===t);if(a?.status==="failed")throw new Error(`snapshot job failed: ${a.error??t}`);await q(s),c=await o.get(e)}throw new Error(`snapshot did not reach ready state before timeout: ${t}`)}n(re,"waitForSnapshotReady");function q(o){return new Promise(e=>setTimeout(e,o))}n(q,"sleep");function R(o={}){return o.async||o.respondAsync?{Prefer:"respond-async"}:void 0}n(R,"asyncRequestHeaders");var O=class extends Error{static{n(this,"ApiTimeoutError")}timeoutMs;requestUrl;code="OPENPOND_API_TIMEOUT";constructor(e,t){super(`API request timed out after ${e}ms: ${t}`),this.timeoutMs=e,this.requestUrl=t,this.name="ApiTimeoutError"}},b=class extends Error{static{n(this,"ApiResponseTooLargeError")}maximumBytes;requestUrl;code="OPENPOND_API_RESPONSE_TOO_LARGE";constructor(e,t){super(`API response exceeded ${e} bytes: ${t}`),this.maximumBytes=e,this.requestUrl=t,this.name="ApiResponseTooLargeError"}},E=class extends Error{static{n(this,"OpenPondApiError")}status;apiMessage;code;constructor(e,t,r,s=null){let i=s||t;super(`${r} failed: ${e}${i?` ${i}`:""}`),this.status=e,this.apiMessage=s,this.name="OpenPondApiError",this.code=t||"OPENPOND_API_ERROR"}};async function w(o,e,t,r={}){let{timeoutMs:s=3e4,maxResponseBytes:i=8388608,...c}=r,m=`${o}${t}`,a=new Headers(c.headers);a.set("Content-Type","application/json");let d=process.env.OPENPOND_API_KEY,h=e?.trim()||"",u=h.startsWith("opk_"),p=d||(u?h:null);p&&!a.has("openpond-api-key")&&a.set("openpond-api-key",p),e?a.set("Authorization",u?`ApiKey ${h}`:`Bearer ${e}`):d&&!a.has("Authorization")&&a.set("Authorization",`ApiKey ${d}`);let S=new AbortController,x=new O(s,m),g=s>0?setTimeout(()=>S.abort(x),s):null;g?.unref?.();let P=se(c.signal,S.signal,s),U=n(()=>{g&&clearTimeout(g)},"cleanup");try{let I=await fetch(m,{...c,headers:a,signal:P});return oe(I,{cleanup:U,maximumBytes:i,requestUrl:m,timeoutController:S,timeoutError:x})}catch(I){throw U(),S.signal.aborted?x:I}}n(w,"apiFetch");async function T(o,e){let t;try{let r=await o.text();t=r?JSON.parse(r):{}}catch(r){if(r instanceof O||r instanceof b)throw r;t={}}if(!o.ok){let r=typeof t.error=="string"?t.error:null,s=typeof t.message=="string"?t.message:null;throw new E(o.status,r,e,s)}return t}n(T,"readApiJson");function oe(o,e){if(!o.body)return e.cleanup(),o;let t=Number(o.headers.get("content-length"));if(e.maximumBytes>0&&Number.isFinite(t)&&t>e.maximumBytes)throw e.cleanup(),o.body.cancel(),new b(e.maximumBytes,e.requestUrl);let r=o.body.getReader(),s=0,i=new ReadableStream({async pull(c){try{let m=await r.read();if(m.done){e.cleanup(),c.close();return}if(s+=m.value.byteLength,e.maximumBytes>0&&s>e.maximumBytes){e.cleanup(),await r.cancel(),c.error(new b(e.maximumBytes,e.requestUrl));return}c.enqueue(m.value)}catch(m){e.cleanup(),c.error(e.timeoutController.signal.aborted?e.timeoutError:m)}},async cancel(c){e.cleanup(),await r.cancel(c)}});return new Response(i,{headers:o.headers,status:o.status,statusText:o.statusText})}n(oe,"boundedResponse");function se(o,e,t){return t<=0?o??void 0:o?AbortSignal.any([o,e]):e}n(se,"composedSignal");async function j(o){let e=await w(o.sandboxApiUrl,o.apiKey,o.path,{timeoutMs:0,maxResponseBytes:0});if(!e.body)return;let t=e.body.getReader(),r=new TextDecoder,s="";try{for(;;){let{done:i,value:c}=await t.read();if(i)break;s+=r.decode(c,{stream:!0});let m=s.indexOf(`
|
|
8
8
|
|
|
9
9
|
`);for(;m!==-1;){let a=s.slice(0,m);s=s.slice(m+2);let d=ne(a);d&&process.stdout.write(d),m=s.indexOf(`
|
|
10
10
|
|
|
11
11
|
`)}}}finally{t.releaseLock()}}n(j,"streamSandboxEventOutput");function Y(o){return typeof o=="string"?{dataBase64:Buffer.from(o,"utf-8").toString("base64")}:o instanceof Uint8Array?{dataBase64:Buffer.from(o).toString("base64")}:o}n(Y,"normalizePtyInput");function ne(o){if(!o.includes("event: output"))return null;let e=o.split(/\r?\n/).filter(t=>t.startsWith("data: ")).map(t=>t.slice(6));if(e.length===0)return null;try{let t=JSON.parse(e.join(`
|
|
12
|
-
`));return typeof t.output=="string"?t.output:null}catch{return null}}n(ne,"parseProcessOutputEvent");var A=class{static{n(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;constructor(e){this.apiKey=e.apiKey,this.sandboxApiUrl=C(e.sandboxApiUrl??e.baseUrl??$),this.apiRootUrl=L(this.sandboxApiUrl)}create(e,t={}){return this.request("",{method:"POST",headers:R(t),body:JSON.stringify(e)}).then(r=>r.sandbox)}get(e){return this.request(`/${encodeURIComponent(e)}`).then(t=>t.sandbox)}exec(e,t){return this.request(`/${encodeURIComponent(e)}/exec`,{method:"POST",body:JSON.stringify(t)})}startProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes`,{method:"POST",body:JSON.stringify(t)})}listProcesses(e){return this.request(`/${encodeURIComponent(e)}/processes`)}getProcess(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}stopProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamProcessOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}startPty(e,t={}){return this.request(`/${encodeURIComponent(e)}/pty`,{method:"POST",body:JSON.stringify(t)})}listPtys(e){return this.request(`/${encodeURIComponent(e)}/pty`)}getPty(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}writePtyInput(e,t,r){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/input`,{method:"POST",body:JSON.stringify(Y(r))})}stopPty(e,t){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamPtyOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}uploadFile(e,t,r){return this.uploadFileBase64(e,t,Buffer.from(r,"utf-8").toString("base64"))}uploadFileBase64(e,t,r){return this.request(`/${encodeURIComponent(e)}/files`,{method:"POST",body:JSON.stringify({path:t,contentsBase64:r})})}async downloadFile(e,t){let r=await this.downloadFileResponse(e,t);return Buffer.from(r.file.contentsBase64,"base64").toString("utf-8")}downloadFileResponse(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.offsetBytes!==void 0&&s.set("offsetBytes",String(r.offsetBytes)),r.maxBytes!==void 0&&s.set("maxBytes",String(r.maxBytes)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`)}listFiles(e,t={}){let r=new URLSearchParams({list:"1"});return t.path&&r.set("path",t.path),t.recursive!==void 0&&r.set("recursive",String(t.recursive)),t.maxEntries!==void 0&&r.set("maxEntries",String(t.maxEntries)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}deleteFile(e,t,r={}){let s=new URLSearchParams({path:t});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"DELETE"})}statFile(e,t){let r=new URLSearchParams({stat:"1",path:t});return this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}mkdir(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"PUT"})}moveFile(e,t){let r=new URLSearchParams({fromPath:t.fromPath,toPath:t.toPath});return t.overwrite!==void 0&&r.set("overwrite",String(t.overwrite)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`,{method:"PATCH"})}searchFiles(e,t){let r=new URLSearchParams({search:"1",query:t.query});return t.path&&r.set("path",t.path),t.maxResults!==void 0&&r.set("maxResults",String(t.maxResults)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}openPort(e,t){return this.request(`/${encodeURIComponent(e)}/ports`,{method:"POST",body:JSON.stringify(t)})}createSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots`,{method:"POST",body:JSON.stringify(t)})}updateSnapshot(e,t,r){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})}validateSnapshot(e,t,r={}){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(r)})}publishSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/publish`,{method:"POST"})}fork(e,t={}){return this.request(`/${encodeURIComponent(e)}/fork`,{method:"POST",body:JSON.stringify(t)})}stop(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}/stop${r.size>0?`?${r.toString()}`:""}`,{method:"POST",headers:R(t)})}start(e,t={}){return this.request(`/${encodeURIComponent(e)}/start`,{method:"POST",headers:R(t)})}restore(e){return this.request(`/${encodeURIComponent(e)}/restore`,{method:"POST"})}delete(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE",headers:R(t)}).then(s=>s.sandbox)}receipts(e){return this.request(`/${encodeURIComponent(e)}/receipts`).then(t=>t.receipts)}logs(e){return this.request(`/${encodeURIComponent(e)}/logs`).then(t=>t.logs)}gitStatus(e){return this.request(`/${encodeURIComponent(e)}/git/status`)}gitDiff(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/diff`,{method:"POST",body:JSON.stringify(t)})}gitExportPatch(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/export-patch`,{method:"POST",body:JSON.stringify(t)})}gitBranch(e,t){return this.request(`/${encodeURIComponent(e)}/git/branch`,{method:"POST",body:JSON.stringify(t)})}gitCommit(e,t){return this.request(`/${encodeURIComponent(e)}/git/commit`,{method:"POST",body:JSON.stringify(t)})}gitPull(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/pull`,{method:"POST",body:JSON.stringify(t)})}gitPush(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/push`,{method:"POST",body:JSON.stringify(t)})}billing(e){return this.request(`/${encodeURIComponent(e)}/billing`)}pricing(){return this.request("/pricing")}costs(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(`/costs${t.size>0?`?${t.toString()}`:""}`)}integrationLeases(e){return this.request(`/${encodeURIComponent(e)}/integrations`)}attachIntegrationConnection(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"POST",body:JSON.stringify(t)})}removeIntegrationLease(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:t})})}async request(e,t={}){let r=await w(this.sandboxApiUrl,this.apiKey,e,t);return T(r,"Sandbox request")}async requestApiRoot(e,t={}){let r=await w(this.apiRootUrl,this.apiKey,e,t);return T(r,"OpenPond API request")}};var _=class extends A{static{n(this,"OpenPondSandboxClient")}runtimes=B(this);sandboxes=z(this);profile=J(this);projects=D(this);agents=M(this);list(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(t.size>0?`?${t.toString()}`:"").then(r=>r.sandboxes)}listSecrets(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets${t.size>0?`?${t.toString()}`:""}`).then(r=>r.secrets)}getSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`).then(s=>s.secret)}createSecret(e){return this.requestApiRoot("/sandbox-secrets",{method:"POST",body:JSON.stringify(e)}).then(t=>t.secret)}rotateSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/rotate${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}attachSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/attach${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}revokeSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/revoke${r.size>0?`?${r.toString()}`:""}`,{method:"POST"}).then(s=>s.secret)}deleteSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE"}).then(s=>s.secret)}snapshotCatalog(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.q&&t.set("q",e.q),e.kind&&t.set("kind",e.kind),e.replayState&&t.set("replayState",e.replayState),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/catalog/snapshots${t.size>0?`?${t.toString()}`:""}`)}listSandboxRuntimes(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.requestApiRoot(`/runtimes${t.size>0?`?${t.toString()}`:""}`).then(r=>r.runtimes)}listProjects(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`).then(r=>r.projects)}upsertProject(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.project)}getHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile?${t.toString()}`).then(r=>r.profile)}ensureHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile/ensure?${t.toString()}`,{method:"POST"}).then(r=>{if(!r.profile)throw new Error("hosted_profile_missing");return r.profile})}pushHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId}),{teamId:r,...s}=e;return this.requestApiRoot(`/profile/push?${t.toString()}`,{method:"POST",body:JSON.stringify(s)})}async upsertProjectGitRemote(e){let t=await this.upsertProject(e);return this.ensureProjectGitRemote(t.id,{teamId:e.teamId})}getProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.project)}syncProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/sync?${r.toString()}`,{method:"POST"}).then(s=>s.project)}ensureProjectGitRemote(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/git?${r.toString()}`,{method:"POST"})}uploadProjectSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/source?${r.toString()}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.project)}updateProject(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.project)}archiveProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.project)}listAgents(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`).then(r=>r.agents)}upsertAgent(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.agent)}getAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.agent)}archiveAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.agent)}updateAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.agent)}runAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/run?${r.toString()}`,{method:"POST",headers:{Prefer:"respond-async"},body:JSON.stringify(i)})}getAgentSourceDeployPlan(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/deploy-plan?${r.toString()}`).then(s=>s.deployPlan)}listAgentManifestSnapshots(e,t){let r=new URLSearchParams({teamId:t.teamId});return t.limit!==void 0&&r.set("limit",String(t.limit)),this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/manifest-snapshots?${r.toString()}`).then(s=>s.manifestSnapshots)}requestAgentSourceChecks(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/checks?${r.toString()}`,{method:"POST",body:JSON.stringify(i),timeoutMs:900*1e3})}configureAgentSourceSetup(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/setup?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}publishAgentSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/publish?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}getMicrosoftTeamsBotOverview(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/teams/bot/overview?${t.toString()}`)}bindMicrosoftTeamsBotConversation(e){return this.requestApiRoot("/teams/bot/bindings",{method:"POST",body:JSON.stringify(e)})}rebindMicrosoftTeamsBotConversation(e,t){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}unlinkMicrosoftTeamsBotConversation(e){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e.bindingId)}`,{method:"DELETE",body:JSON.stringify({teamId:e.teamId})})}sendMicrosoftTeamsBotDiagnostic(e){return this.requestApiRoot("/teams/bot/diagnostics",{method:"POST",body:JSON.stringify(e)})}sendMicrosoftTeamsBotDiagnosticRun(e){return this.requestApiRoot("/teams/bot/diagnostics/run",{method:"POST",body:JSON.stringify(e)})}createSandboxRuntime(e){return this.requestApiRoot("/runtimes",{method:"POST",body:JSON.stringify(e)}).then(t=>t.runtime)}sandboxRuntime(e,t=null){return F(this,e,t)}getSandboxRuntime(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}`).then(t=>t.runtime)}createSandboxRuntimeSandbox(e,t={},r={}){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/sandbox`,{method:"POST",headers:R(r),body:JSON.stringify(t)})}updateSandboxRuntimeStatus(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/status`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.runtime)}listSandboxRuntimeEvents(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`)}emitSandboxRuntimeEvent(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`,{method:"POST",body:JSON.stringify(t)})}checkpointSandboxRuntime(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/checkpoints`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.runtime)}promoteSandboxRuntime(e,t,r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/promote${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}preserveSandboxRuntimeSource(e,t={},r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/preserve-source${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}forkSnapshot(e,t={},r={}){let s=new URLSearchParams;t.teamId&&s.set("teamId",t.teamId),t.projectId&&s.set("projectId",t.projectId),r.async&&s.set("async","1");let{teamId:i,projectId:c,...m}=t;return this.request(`/catalog/snapshots/${encodeURIComponent(e)}/fork${s.size>0?`?${s.toString()}`:""}`,{method:"POST",headers:r.async?{Prefer:"respond-async"}:void 0,body:JSON.stringify({...m,snapshotId:e})})}templates(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/templates${t.size>0?`?${t.toString()}`:""}`)}publishedSnapshots(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/published-snapshots${t.size>0?`?${t.toString()}`:""}`).then(r=>{let s=r.publishedSnapshots??r.templates;return{...r,templates:s,publishedSnapshots:s}})}launchTemplate(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/templates/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}runPublishedSnapshot(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/published-snapshots/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>{let m=c.publishedSnapshot??c.template;return{...c,template:m,publishedSnapshot:m}})}listSchedules(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.sourceSandboxId&&t.set("sourceSandboxId",e.sourceSandboxId),this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`)}createSchedule(e){let t=new URLSearchParams;e.projectId&&t.set("projectId",e.projectId);let{projectId:r,...s}=e;return this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(s)})}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}listScheduleRuns(e,t={}){let r=new URLSearchParams;return t.limit!==void 0&&r.set("limit",String(t.limit)),this.request(`/schedules/${encodeURIComponent(e)}/runs${r.size>0?`?${r.toString()}`:""}`)}runScheduleNow(e,t={}){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t)})}listTemplateBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/sandbox-template-builds?${t.toString()}`).then(r=>r.builds)}createTemplateBuild(e){return this.requestApiRoot("/sandbox-template-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getTemplateBuildLogs(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/logs`)}cancelTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listPublishedSnapshotBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/published-snapshot-builds?${t.toString()}`).then(r=>r.builds)}createPublishedSnapshotBuild(e){return this.requestApiRoot("/published-snapshot-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getPublishedSnapshotBuildLogs(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/logs`)}cancelPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listOrganizations(){return this.requestApiRoot("/organizations").then(e=>e.organizations??e.teams??[])}createOrganization(e){return this.requestApiRoot("/organizations",{method:"POST",body:JSON.stringify(e)}).then(t=>t.organization)}getOrganization(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`).then(t=>t.organization)}updateOrganization(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.organization)}listOrganizationMembers(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`).then(t=>t.members)}upsertOrganizationMember(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.member)}getOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`).then(t=>t.mcpServer)}generateOrganizationMcpServer(e,t={}){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.mcpServer)}rotateOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/rotate`,{method:"POST"}).then(t=>t.mcpServer)}disableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/disable`,{method:"POST"}).then(t=>t.mcpServer)}enableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/enable`,{method:"POST"}).then(t=>t.mcpServer)}startReplay(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}listReplays(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`)}getReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`)}getReplayLogs(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/logs${r.size>0?`?${r.toString()}`:""}`)}getReplayArtifacts(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/artifacts${r.size>0?`?${r.toString()}`:""}`)}cancelReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/cancel${r.size>0?`?${r.toString()}`:""}`,{method:"POST"})}integrationConnections(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),this.requestApiRoot(`/integrations/connections${t.size>0?`?${t.toString()}`:""}`)}mcpServerConfig(){return{name:"openpond-sandboxes",transport:"streamable-http",url:`${this.sandboxApiUrl}/mcp`,headers:{"openpond-api-key":this.apiKey}}}smoke(e={}){return W(this,e)}};function De(o){return new _(o)}n(De,"createOpenPondSandboxClient");import{randomUUID as ae}from"node:crypto";function ie(o){let e=g(o);if(!e)throw new Error("apiBaseUrl is required");return e}n(ie,"normalizeApiBaseUrl");function V(o){return o.replace(/\/+$/,"")}n(V,"trimTrailingSlashes");function g(o){let e=V(o?.trim()??"");return e?(e=e.replace(/\/chat\/completions$/i,"").replace(/\/models(?:\/[^/]+)?$/i,""),e.endsWith("/opchat/v1")?e:e.endsWith("/opchat")?`${e}/v1`:(e.endsWith("/v1")&&(e=e.slice(0,-3)),`${V(e)}/opchat/v1`)):null}n(g,"normalizeOptionalOpChatApiBaseUrl");function We(o={}){let e=o.env??(typeof process<"u"?process.env:{}),t=g(o.opChatApiBaseUrl)??g(e.OPENPOND_OPCHAT_API_URL);if(t)return t;let r=g(o.chatApiBaseUrl)??g(e.OPENPOND_CHAT_API_URL)??g(e.OPENPOND_GATEWAY_URL);return r||(g(o.apiBaseUrl)??g(e.OPENPOND_API_URL)??k)}n(We,"resolveOpChatApiBaseUrl");function de(o){let e=o.trim();if(!e)throw new Error("OpenPond API key is required");return e}n(de,"requireToken");function ce(o,e,t){let r=new Headers;return r.set("Authorization",`Bearer ${de(o)}`),r.set("Content-Type","application/json"),r.set("Accept",e),r.set("x-openpond-client","openpond-code"),r.set("x-openpond-request-id",t||ae()),r}n(ce,"hostedHeaders");async function me(o){let e=await o.text().catch(()=>"");if(!e)return o.statusText||`HTTP ${o.status}`;try{let t=JSON.parse(e),r=typeof t.error=="string"||t.error&&typeof t.error=="object"&&!Array.isArray(t.error)?t.error:null,s=typeof t.code=="string"?t.code:r&&typeof r!="string"&&typeof r.code=="string"?r.code:null,i=typeof t.message=="string"?t.message:r&&typeof r!="string"&&typeof r.message=="string"?r.message:null,c=typeof r=="string"?r:r&&typeof r.type=="string"?r.type:null;return[s,c,i].filter(Boolean).join(": ")||e}catch{return e}}n(me,"readError");function ue(o,e){let t={model:o.model,messages:o.messages,stream:e};typeof o.temperature=="number"&&(t.temperature=o.temperature),typeof o.maxTokens=="number"&&(t.max_tokens=o.maxTokens),o.tools&&(t.tools=o.tools);let r=o.toolChoice??o.tool_choice;return r!==void 0&&(t.tool_choice=r),o.metadata&&(t.metadata=o.metadata),t}n(ue,"buildHostedChatBody");async function Ke(o){let t=`${ie(o.apiBaseUrl)}/chat/completions`,r=await fetch(t,{method:"POST",headers:ce(o.token,"application/json",o.requestId),body:JSON.stringify(ue(o,!1)),signal:o.signal});if(!r.ok)throw new Error(`Hosted chat failed: ${r.status} ${await me(r)}`);return await r.json()}n(Ke,"sendHostedChatTurn");export{E as a,w as b,T as c,N as d,$ as e,C as f,_ as g,De as h,We as i,Ke as j};
|
|
12
|
+
`));return typeof t.output=="string"?t.output:null}catch{return null}}n(ne,"parseProcessOutputEvent");var A=class{static{n(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;constructor(e){this.apiKey=e.apiKey,this.sandboxApiUrl=C(e.sandboxApiUrl??e.baseUrl??$),this.apiRootUrl=L(this.sandboxApiUrl)}create(e,t={}){return this.request("",{method:"POST",headers:R(t),body:JSON.stringify(e)}).then(r=>r.sandbox)}get(e){return this.request(`/${encodeURIComponent(e)}`).then(t=>t.sandbox)}exec(e,t){return this.request(`/${encodeURIComponent(e)}/exec`,{method:"POST",body:JSON.stringify(t)})}startProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes`,{method:"POST",body:JSON.stringify(t)})}listProcesses(e){return this.request(`/${encodeURIComponent(e)}/processes`)}getProcess(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}stopProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamProcessOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}startPty(e,t={}){return this.request(`/${encodeURIComponent(e)}/pty`,{method:"POST",body:JSON.stringify(t)})}listPtys(e){return this.request(`/${encodeURIComponent(e)}/pty`)}getPty(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}writePtyInput(e,t,r){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/input`,{method:"POST",body:JSON.stringify(Y(r))})}stopPty(e,t){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamPtyOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}uploadFile(e,t,r){return this.uploadFileBase64(e,t,Buffer.from(r,"utf-8").toString("base64"))}uploadFileBase64(e,t,r){return this.request(`/${encodeURIComponent(e)}/files`,{method:"POST",body:JSON.stringify({path:t,contentsBase64:r})})}async downloadFile(e,t){let r=await this.downloadFileResponse(e,t);return Buffer.from(r.file.contentsBase64,"base64").toString("utf-8")}downloadFileResponse(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.offsetBytes!==void 0&&s.set("offsetBytes",String(r.offsetBytes)),r.maxBytes!==void 0&&s.set("maxBytes",String(r.maxBytes)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`)}listFiles(e,t={}){let r=new URLSearchParams({list:"1"});return t.path&&r.set("path",t.path),t.recursive!==void 0&&r.set("recursive",String(t.recursive)),t.maxEntries!==void 0&&r.set("maxEntries",String(t.maxEntries)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}deleteFile(e,t,r={}){let s=new URLSearchParams({path:t});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"DELETE"})}statFile(e,t){let r=new URLSearchParams({stat:"1",path:t});return this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}mkdir(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"PUT"})}moveFile(e,t){let r=new URLSearchParams({fromPath:t.fromPath,toPath:t.toPath});return t.overwrite!==void 0&&r.set("overwrite",String(t.overwrite)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`,{method:"PATCH"})}searchFiles(e,t){let r=new URLSearchParams({search:"1",query:t.query});return t.path&&r.set("path",t.path),t.maxResults!==void 0&&r.set("maxResults",String(t.maxResults)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}openPort(e,t){return this.request(`/${encodeURIComponent(e)}/ports`,{method:"POST",body:JSON.stringify(t)})}createSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots`,{method:"POST",body:JSON.stringify(t)})}updateSnapshot(e,t,r){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})}validateSnapshot(e,t,r={}){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(r)})}publishSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/publish`,{method:"POST"})}fork(e,t={}){return this.request(`/${encodeURIComponent(e)}/fork`,{method:"POST",body:JSON.stringify(t)})}stop(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}/stop${r.size>0?`?${r.toString()}`:""}`,{method:"POST",headers:R(t)})}start(e,t={}){return this.request(`/${encodeURIComponent(e)}/start`,{method:"POST",headers:R(t)})}restore(e){return this.request(`/${encodeURIComponent(e)}/restore`,{method:"POST"})}delete(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE",headers:R(t)}).then(s=>s.sandbox)}receipts(e){return this.request(`/${encodeURIComponent(e)}/receipts`).then(t=>t.receipts)}logs(e){return this.request(`/${encodeURIComponent(e)}/logs`).then(t=>t.logs)}gitStatus(e){return this.request(`/${encodeURIComponent(e)}/git/status`)}gitDiff(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/diff`,{method:"POST",body:JSON.stringify(t)})}gitExportPatch(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/export-patch`,{method:"POST",body:JSON.stringify(t)})}gitBranch(e,t){return this.request(`/${encodeURIComponent(e)}/git/branch`,{method:"POST",body:JSON.stringify(t)})}gitCommit(e,t){return this.request(`/${encodeURIComponent(e)}/git/commit`,{method:"POST",body:JSON.stringify(t)})}gitPull(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/pull`,{method:"POST",body:JSON.stringify(t)})}gitPush(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/push`,{method:"POST",body:JSON.stringify(t)})}billing(e){return this.request(`/${encodeURIComponent(e)}/billing`)}pricing(){return this.request("/pricing")}costs(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(`/costs${t.size>0?`?${t.toString()}`:""}`)}integrationLeases(e){return this.request(`/${encodeURIComponent(e)}/integrations`)}attachIntegrationConnection(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"POST",body:JSON.stringify(t)})}removeIntegrationLease(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:t})})}async request(e,t={}){let r=await w(this.sandboxApiUrl,this.apiKey,e,t);return T(r,"Sandbox request")}async requestApiRoot(e,t={}){let r=await w(this.apiRootUrl,this.apiKey,e,t);return T(r,"OpenPond API request")}};var _=class extends A{static{n(this,"OpenPondSandboxClient")}runtimes=B(this);sandboxes=z(this);profile=J(this);projects=D(this);agents=M(this);list(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(t.size>0?`?${t.toString()}`:"").then(r=>r.sandboxes)}listSecrets(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets${t.size>0?`?${t.toString()}`:""}`).then(r=>r.secrets)}getSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`).then(s=>s.secret)}createSecret(e){return this.requestApiRoot("/sandbox-secrets",{method:"POST",body:JSON.stringify(e)}).then(t=>t.secret)}rotateSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/rotate${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}attachSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/attach${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}revokeSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/revoke${r.size>0?`?${r.toString()}`:""}`,{method:"POST"}).then(s=>s.secret)}deleteSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE"}).then(s=>s.secret)}snapshotCatalog(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.q&&t.set("q",e.q),e.kind&&t.set("kind",e.kind),e.replayState&&t.set("replayState",e.replayState),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/catalog/snapshots${t.size>0?`?${t.toString()}`:""}`)}listSandboxRuntimes(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.requestApiRoot(`/runtimes${t.size>0?`?${t.toString()}`:""}`).then(r=>r.runtimes)}listProjects(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`).then(r=>r.projects)}upsertProject(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.project)}getHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile?${t.toString()}`).then(r=>r.profile)}ensureHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile/ensure?${t.toString()}`,{method:"POST"}).then(r=>{if(!r.profile)throw new Error("hosted_profile_missing");return r.profile})}pushHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId}),{teamId:r,...s}=e;return this.requestApiRoot(`/profile/push?${t.toString()}`,{method:"POST",body:JSON.stringify(s)})}async upsertProjectGitRemote(e){let t=await this.upsertProject(e);return this.ensureProjectGitRemote(t.id,{teamId:e.teamId})}getProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.project)}syncProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/sync?${r.toString()}`,{method:"POST"}).then(s=>s.project)}ensureProjectGitRemote(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/git?${r.toString()}`,{method:"POST"})}uploadProjectSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/source?${r.toString()}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.project)}updateProject(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.project)}archiveProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.project)}listAgents(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`).then(r=>r.agents)}upsertAgent(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.agent)}getAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.agent)}archiveAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.agent)}updateAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.agent)}runAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/run?${r.toString()}`,{method:"POST",headers:{Prefer:"respond-async"},body:JSON.stringify(i)})}getAgentSourceDeployPlan(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/deploy-plan?${r.toString()}`).then(s=>s.deployPlan)}listAgentManifestSnapshots(e,t){let r=new URLSearchParams({teamId:t.teamId});return t.limit!==void 0&&r.set("limit",String(t.limit)),this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/manifest-snapshots?${r.toString()}`).then(s=>s.manifestSnapshots)}requestAgentSourceChecks(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/checks?${r.toString()}`,{method:"POST",body:JSON.stringify(i),timeoutMs:900*1e3})}configureAgentSourceSetup(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/setup?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}publishAgentSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/publish?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}getMicrosoftTeamsBotOverview(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/teams/bot/overview?${t.toString()}`)}bindMicrosoftTeamsBotConversation(e){return this.requestApiRoot("/teams/bot/bindings",{method:"POST",body:JSON.stringify(e)})}rebindMicrosoftTeamsBotConversation(e,t){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}unlinkMicrosoftTeamsBotConversation(e){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e.bindingId)}`,{method:"DELETE",body:JSON.stringify({teamId:e.teamId})})}sendMicrosoftTeamsBotDiagnostic(e){return this.requestApiRoot("/teams/bot/diagnostics",{method:"POST",body:JSON.stringify(e)})}sendMicrosoftTeamsBotDiagnosticRun(e){return this.requestApiRoot("/teams/bot/diagnostics/run",{method:"POST",body:JSON.stringify(e)})}createSandboxRuntime(e){return this.requestApiRoot("/runtimes",{method:"POST",body:JSON.stringify(e)}).then(t=>t.runtime)}sandboxRuntime(e,t=null){return F(this,e,t)}getSandboxRuntime(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}`).then(t=>t.runtime)}createSandboxRuntimeSandbox(e,t={},r={}){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/sandbox`,{method:"POST",headers:R(r),body:JSON.stringify(t)})}updateSandboxRuntimeStatus(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/status`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.runtime)}listSandboxRuntimeEvents(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`)}emitSandboxRuntimeEvent(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`,{method:"POST",body:JSON.stringify(t)})}checkpointSandboxRuntime(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/checkpoints`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.runtime)}promoteSandboxRuntime(e,t,r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/promote${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}preserveSandboxRuntimeSource(e,t={},r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/preserve-source${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}forkSnapshot(e,t={},r={}){let s=new URLSearchParams;t.teamId&&s.set("teamId",t.teamId),t.projectId&&s.set("projectId",t.projectId),r.async&&s.set("async","1");let{teamId:i,projectId:c,...m}=t;return this.request(`/catalog/snapshots/${encodeURIComponent(e)}/fork${s.size>0?`?${s.toString()}`:""}`,{method:"POST",headers:r.async?{Prefer:"respond-async"}:void 0,body:JSON.stringify({...m,snapshotId:e})})}templates(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/templates${t.size>0?`?${t.toString()}`:""}`)}publishedSnapshots(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/published-snapshots${t.size>0?`?${t.toString()}`:""}`).then(r=>{let s=r.publishedSnapshots??r.templates;return{...r,templates:s,publishedSnapshots:s}})}launchTemplate(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/templates/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}runPublishedSnapshot(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/published-snapshots/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>{let m=c.publishedSnapshot??c.template;return{...c,template:m,publishedSnapshot:m}})}listSchedules(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.sourceSandboxId&&t.set("sourceSandboxId",e.sourceSandboxId),this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`)}createSchedule(e){let t=new URLSearchParams;e.projectId&&t.set("projectId",e.projectId);let{projectId:r,...s}=e;return this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(s)})}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}listScheduleRuns(e,t={}){let r=new URLSearchParams;return t.limit!==void 0&&r.set("limit",String(t.limit)),this.request(`/schedules/${encodeURIComponent(e)}/runs${r.size>0?`?${r.toString()}`:""}`)}runScheduleNow(e,t={}){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t)})}listTemplateBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/sandbox-template-builds?${t.toString()}`).then(r=>r.builds)}createTemplateBuild(e){return this.requestApiRoot("/sandbox-template-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getTemplateBuildLogs(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/logs`)}cancelTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listPublishedSnapshotBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/published-snapshot-builds?${t.toString()}`).then(r=>r.builds)}createPublishedSnapshotBuild(e){return this.requestApiRoot("/published-snapshot-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getPublishedSnapshotBuildLogs(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/logs`)}cancelPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listOrganizations(){return this.requestApiRoot("/organizations").then(e=>e.organizations??e.teams??[])}createOrganization(e){return this.requestApiRoot("/organizations",{method:"POST",body:JSON.stringify(e)}).then(t=>t.organization)}getOrganization(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`).then(t=>t.organization)}updateOrganization(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.organization)}listOrganizationMembers(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`).then(t=>t.members)}upsertOrganizationMember(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.member)}getOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`).then(t=>t.mcpServer)}generateOrganizationMcpServer(e,t={}){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.mcpServer)}rotateOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/rotate`,{method:"POST"}).then(t=>t.mcpServer)}disableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/disable`,{method:"POST"}).then(t=>t.mcpServer)}enableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/enable`,{method:"POST"}).then(t=>t.mcpServer)}startReplay(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}listReplays(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`)}getReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`)}getReplayLogs(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/logs${r.size>0?`?${r.toString()}`:""}`)}getReplayArtifacts(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/artifacts${r.size>0?`?${r.toString()}`:""}`)}cancelReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/cancel${r.size>0?`?${r.toString()}`:""}`,{method:"POST"})}integrationConnections(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),this.requestApiRoot(`/integrations/connections${t.size>0?`?${t.toString()}`:""}`)}mcpServerConfig(){return{name:"openpond-sandboxes",transport:"streamable-http",url:`${this.sandboxApiUrl}/mcp`,headers:{"openpond-api-key":this.apiKey}}}smoke(e={}){return W(this,e)}};function De(o){return new _(o)}n(De,"createOpenPondSandboxClient");import{randomUUID as ae}from"node:crypto";function ie(o){let e=y(o);if(!e)throw new Error("apiBaseUrl is required");return e}n(ie,"normalizeApiBaseUrl");function V(o){return o.replace(/\/+$/,"")}n(V,"trimTrailingSlashes");function y(o){let e=V(o?.trim()??"");return e?(e=e.replace(/\/chat\/completions$/i,"").replace(/\/models(?:\/[^/]+)?$/i,""),e.endsWith("/opchat/v1")?e:e.endsWith("/opchat")?`${e}/v1`:(e.endsWith("/v1")&&(e=e.slice(0,-3)),`${V(e)}/opchat/v1`)):null}n(y,"normalizeOptionalOpChatApiBaseUrl");function We(o={}){let e=o.env??(typeof process<"u"?process.env:{}),t=y(o.opChatApiBaseUrl)??y(e.OPENPOND_OPCHAT_API_URL);if(t)return t;let r=y(o.chatApiBaseUrl)??y(e.OPENPOND_CHAT_API_URL)??y(e.OPENPOND_GATEWAY_URL);return r||(y(o.apiBaseUrl)??y(e.OPENPOND_API_URL)??k)}n(We,"resolveOpChatApiBaseUrl");function de(o){let e=o.trim();if(!e)throw new Error("OpenPond API key is required");return e}n(de,"requireToken");function ce(o,e,t){let r=new Headers;return r.set("Authorization",`Bearer ${de(o)}`),r.set("Content-Type","application/json"),r.set("Accept",e),r.set("x-openpond-client","openpond-code"),r.set("x-openpond-request-id",t||ae()),r}n(ce,"hostedHeaders");async function me(o){let e=await o.text().catch(()=>"");if(!e)return o.statusText||`HTTP ${o.status}`;try{let t=JSON.parse(e),r=typeof t.error=="string"||t.error&&typeof t.error=="object"&&!Array.isArray(t.error)?t.error:null,s=typeof t.code=="string"?t.code:r&&typeof r!="string"&&typeof r.code=="string"?r.code:null,i=typeof t.message=="string"?t.message:r&&typeof r!="string"&&typeof r.message=="string"?r.message:null,c=typeof r=="string"?r:r&&typeof r.type=="string"?r.type:null;return[s,c,i].filter(Boolean).join(": ")||e}catch{return e}}n(me,"readError");function ue(o,e){let t={model:o.model,messages:o.messages,stream:e};typeof o.temperature=="number"&&(t.temperature=o.temperature),typeof o.maxTokens=="number"&&(t.max_tokens=o.maxTokens),o.tools&&(t.tools=o.tools);let r=o.toolChoice??o.tool_choice;return r!==void 0&&(t.tool_choice=r),o.metadata&&(t.metadata=o.metadata),t}n(ue,"buildHostedChatBody");async function Ke(o){let t=`${ie(o.apiBaseUrl)}/chat/completions`,r=await fetch(t,{method:"POST",headers:ce(o.token,"application/json",o.requestId),body:JSON.stringify(ue(o,!1)),signal:o.signal});if(!r.ok)throw new Error(`Hosted chat failed: ${r.status} ${await me(r)}`);return await r.json()}n(Ke,"sendHostedChatTurn");export{E as a,w as b,T as c,N as d,$ as e,C as f,_ as g,De as h,We as i,Ke as j};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{W as ge,a as ue,b as de,d as pe,e as K,f as N,g as fe,h as me,i as he,j as ye}from"./chunk-
|
|
2
|
+
import{W as ge,a as ue,b as de,d as pe,e as K,f as N,g as fe,h as me,i as he,j as ye}from"./chunk-AF57BF75.js";import{d as R,e as U}from"./chunk-KDXLNQNF.js";import{K as ne,q as ce}from"./chunk-FYCJSUFV.js";import{a}from"./chunk-FTQLQJQV.js";import{randomUUID as He}from"node:crypto";var _e=new URL(U).hostname,Se=new URL(R).hostname,Ce=`${U}/opchat/v1`;function l(e){if(!e)return null;let n=e.trim();return n?n.replace(/\/+$/,""):null}a(l,"normalizeBaseUrl");function V(e){let n=l(e);if(!n)return null;try{let o=new URL(n).hostname.toLowerCase();if(o===_e)return U;if(o===Se||o==="openpond.live"||o==="www.openpond.live")return U;if(o.startsWith("api."))return n}catch{return null}return null}a(V,"mapUiBaseToApiBase");function G(e,n){let t=l(process.env.OPENPOND_API_URL);if(t)return t;let o=l(e?.apiBaseUrl);if(o)return o;let r=l(n.apiBaseUrl);if(r)return r;let s=V(process.env.OPENPOND_BASE_URL);return s||(V(e?.baseUrl||n.baseUrl)??U)}a(G,"resolvePublicApiBaseUrl");function J(e,n,t){return Ie(e,n,t)}a(J,"resolveHostedChatApiBaseUrl");function Ie(e,n,t){let o=typeof process<"u"?process.env:{};return W(o.OPENPOND_OPCHAT_API_URL)??W(e?.chatApiBaseUrl??n.chatApiBaseUrl)??W(o.OPENPOND_CHAT_API_URL)??Re(t)}a(Ie,"resolveOpChatApiBaseUrl");function W(e){let n=l(e);if(!n)return null;try{let t=new URL(n),o=t.pathname.split("/").filter(Boolean),r=o.findIndex(i=>i.toLowerCase()==="opchat");return r>=0?(t.pathname=`/${[...o.slice(0,r+1),"v1"].join("/")}`,t.search="",t.hash="",l(t.toString())??null):o.findIndex(i=>i.toLowerCase()==="v1")>=0?(t.pathname="/opchat/v1",t.search="",t.hash="",l(t.toString())??null):(t.pathname=`${t.pathname.replace(/\/+$/,"")}/opchat/v1`.replace(/\/{2,}/g,"/"),t.search="",t.hash="",l(t.toString())??null)}catch{return null}}a(W,"normalizeOpChatApiBaseUrl");function Re(e){return W(e)??Ce}a(Re,"opChatBaseFromPublicApiBase");function T(e){return e?.trim()?e.trim():"production"}a(T,"deriveEnvironment");function Y(e,n=process.env){let t=[e?.apiKey,e?.session?.token,e?.token,n.OPENPOND_API_KEY];for(let o of t){let r=typeof o=="string"?o.trim():"";if(r)return r}return null}a(Y,"accountToken");function P(e,n){return!!(e&&n&&e.toLowerCase()===n.toLowerCase())}a(P,"handleEquals");function v(e,n){return l(e)===l(n)}a(v,"baseUrlEquals");function z(e,n){return`${e?.trim().toLowerCase()||""}|${l(n)??"default"}`}a(z,"profileKey");function Q(e){return l(e?.baseUrl)}a(Q,"selectorBaseUrl");function F(e){let n=l(e.baseUrl);return n?{handle:e.handle,baseUrl:n}:{handle:e.handle}}a(F,"selectorFromAccount");function g(e){let n=typeof e?.handle=="string"?e.handle.trim():"";if(!n)return null;let t=l(e?.baseUrl);return t?{handle:n,baseUrl:t}:{handle:n}}a(g,"normalizeActiveProfile");function k(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(k,"accountMatchesSelector");function te(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(te,"profileMatchesSelector");function Ae(e,n,t){let o=Array.isArray(e.accounts)?e.accounts:[],r=n||process.env.OPENPOND_ACCOUNT?g({handle:n||process.env.OPENPOND_ACCOUNT||"",baseUrl:t??process.env.OPENPOND_BASE_URL??null}):g(e.activeProfile);if(r){let s=o.find(c=>k(c,r));if(s)return s;let i=o.filter(c=>P(c.handle,r.handle));return i.length===1?i[0]??null:null}return o[0]?o[0]:null}a(Ae,"findActiveAccount");function Pe(e){let n=Array.isArray(e.accounts)?e.accounts:[],t=g(e.activeProfile)??(n[0]?F(n[0]):null);return oe(n.map(o=>({handle:o.handle,baseUrl:l(o.baseUrl),apiBaseUrl:l(o.apiBaseUrl),chatApiBaseUrl:l(o.chatApiBaseUrl),environment:T(o.environment),isActive:t?k(o,t):!1,hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!(o.session?.token?.trim()||o.token?.trim()),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null})))}a(Pe,"fallbackProfilesFromConfig");function oe(e){let n=new Map;for(let t of e){let o=l(t.baseUrl),r=`${t.handle.toLowerCase()}|${o??"default"}`,s={...t,baseUrl:o,apiBaseUrl:l(t.apiBaseUrl),chatApiBaseUrl:l(t.chatApiBaseUrl),environment:T(t.environment),isActive:t.isActive},i=n.get(r);(!i||s.isActive&&!i.isActive||s.hasApiKey&&!i.hasApiKey)&&n.set(r,s)}return Array.from(n.values())}a(oe,"normalizeProfiles");function we(e){return e.hasApiKey||e.hasSessionToken?"signed_in":"signed_out"}a(we,"profileAuthHealth");function Ne(e,n){return e?{reachable:e.reachable,authenticated:e.authenticated,apiBase:e.apiBase||n,latencyMs:e.latencyMs,status:e.status,service:e.service,checkedAt:e.checkedAt,error:e.error??null}:null}a(Ne,"normalizeHealth");function Oe(e){let n=e?.account;return n?{id:n.id??null,email:n.email??null,name:n.name??null,handle:n.handle??null,image:n.image??null,timezone:n.timezone??null,isAdmin:n.isAdmin??null,isVerified:n.isVerified??null,dailyAgentAppId:n.dailyAgentAppId??null,dailyAgentDeploymentId:n.dailyAgentDeploymentId??null,credits:n.credits??null}:null}a(Oe,"normalizeProfile");function Te(e){return(e??[]).map(n=>({...n,id:n.id||n.userProductId||n.openPondProductId||n.name,name:n.name,type:n.type,status:n.status,isActive:n.isActive??null,price:n.price??null,currency:n.currency??null,credits:n.credits??null}))}a(Te,"normalizeProducts");function Le(e){return e.handle.trim().toLowerCase()==="default"&&!l(e.baseUrl)&&!e.hasApiKey&&!e.hasSessionToken}a(Le,"isEmptyDefaultProfile");function X(e){let{config:n,profiles:t,account:o,token:r,apiBaseUrl:s,accountResponse:i,accountProfiles:c,health:y,authFailed:A,error:f}=e,w=J(o,n,s),m=Oe(i??null),S=g(n.activeProfile),E=(o?F(o):null)??S,O=m?.handle||o?.handle||E?.handle||null,C=(E?t.find(p=>te(p,E)):null)??t.find(p=>p.isActive)??null,h=A?"auth_error":r?"signed_in":"signed_out",u=m?.name||m?.handle||m?.email||O||"Signed out",I=l(C?.baseUrl||o?.baseUrl||R),b=T(C?.environment||o?.environment),x=g(E)??(O?g({handle:O,baseUrl:C?.baseUrl??o?.baseUrl}):null),$=(t.length>0?t:O?[{handle:O,baseUrl:Q(x)??l(o?.baseUrl),apiBaseUrl:s,chatApiBaseUrl:w,environment:b,isActive:!0,hasApiKey:!!r,hasSessionToken:!1,sessionAppId:null,sessionConversationId:null}]:[]).filter(p=>!Le(p));return{state:h,activeProfile:x,label:u,email:m?.email??null,avatarUrl:m?.image??null,environment:b,baseUrl:I,apiBaseUrl:s,chatApiBaseUrl:w,creditsLabel:m?.credits??null,profile:m,products:Te(i?.products),apiHealth:Ne(y??null,s),accounts:$.map(p=>{let H=l(p.baseUrl),le=c?.[z(p.handle,H)]??null,M=Oe(le?.response??null);return{handle:p.handle,baseUrl:H,apiBaseUrl:l(p.apiBaseUrl),chatApiBaseUrl:l(p.chatApiBaseUrl),environment:T(p.environment),isActive:x?te(p,x):!1,authHealth:le?.authFailed?"auth_error":we(p),displayLabel:M?.name||M?.handle||M?.email||p.handle,email:M?.email??null,avatarUrl:M?.image??null}}),error:f??y?.error??null}}a(X,"toAccountState");async function De(e){try{return oe(await me())}catch{return Pe(e)}}a(De,"loadProfiles");async function d(e,n){let t=await fe(),o=await De(t),r=Ae(t,e,n),s=Y(r),i=G(r,t),c=J(r,t,i);return{config:t,profiles:o,account:r,token:s,apiBaseUrl:i,chatApiBaseUrl:c,accountState:X({config:t,profiles:o,account:r,token:s,apiBaseUrl:i})}}a(d,"loadOpenPondAccountContext");async function $e(e){let n=l(e.baseUrl);return await he(e.handle,{baseUrl:n}),d(e.handle,n)}a($e,"switchOpenPondAccount");function L(e){return e instanceof Error?e.message:String(e)}a(L,"errorMessage");var Me=15e3;function ze(e){return e===ne?"OpenPond Chat":e==="deepseek-v4-flash"?"DeepSeek V4 Flash":e.replace(/[-_/]+/g," ")}a(ze,"displayNameForHostedModel");function Fe(e){let n=typeof e.id=="string"?e.id:null;return n?{id:n,displayName:ze(n),ownedBy:typeof e.owned_by=="string"?e.owned_by:null,streaming:!0,raw:e}:null}a(Fe,"normalizeHostedModel");async function je(){let e=await d();if(!e.token)return{models:[],error:"No OpenPond API key or session token is configured."};try{return{models:(await We({apiBaseUrl:e.chatApiBaseUrl,token:e.token})).data.map(o=>Fe(o)).filter(o=>!!o),error:null}}catch(n){return{models:[],error:L(n)}}}a(je,"loadOpenPondHostedModels");async function qe(){let e=await d();if(!e.token)return{catalog:null,error:"No OpenPond API key or session token is configured."};let n=new AbortController,t=setTimeout(()=>{n.abort(new Error("OpenPond provider catalog request timed out."))},Me);try{return{catalog:await Ue({apiBaseUrl:e.chatApiBaseUrl,token:e.token,signal:n.signal}),error:null}}catch(o){return{catalog:null,error:L(o)}}finally{clearTimeout(t)}}a(qe,"loadOpenPondProviderCatalog");async function*Ke(e){let n=await d();if(!n.token)throw new Error("OpenPond is signed out. Add an account in Settings before using OpenPond Chat.");yield*Ve({apiBaseUrl:n.chatApiBaseUrl,token:n.token,model:e.model||ne,messages:e.messages,tools:e.tools,toolChoice:e.toolChoice,requestId:e.requestId,reasoningEffort:e.reasoningEffort,maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,signal:e.signal})}a(Ke,"streamOpenPondHostedChatTurn");async function We(e){let n=re(e.apiBaseUrl,"models"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat model list failed: ${t.status} ${await se(t)}`);return await t.json()}a(We,"listOpChatModels");async function Ue(e){let n=re(e.apiBaseUrl,"provider-catalog"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat provider catalog failed: ${t.status} ${await se(t)}`);return ce.parse(await t.json())}a(Ue,"listOpChatProviderCatalog");async function*Ve(e){let n=re(e.apiBaseUrl,"chat/completions"),t=await fetch(n,{method:"POST",headers:ae(e.token,"text/event-stream",e.requestId),body:JSON.stringify(Ze(e,!0)),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat request failed: ${t.status} ${await se(t)}`);if(!t.body)throw new Error("OpenPond OpChat request failed: streaming response body is missing.");let o=new Map,r=!1,s=null,i={},c="",y=null,A=Ge(t.headers),f=t.body.getReader(),w=new TextDecoder,m="",S=[],ee=a(()=>{if(S.length===0)return[];let h=S.join(`
|
|
3
3
|
`);if(S=[],h==="[DONE]")return r=!0,[];let u;try{u=JSON.parse(h)}catch{throw new Error("OpenPond OpChat request failed: malformed streaming event.")}if(u&&typeof u=="object"&&"error"in u)throw new Error(`OpenPond OpChat request failed: ${ke(u)}`);i=u;let I=u&&typeof u=="object"?u:{},b=Array.isArray(I.choices)?I.choices:[],x=b[0]&&typeof b[0]=="object"?b[0]:{},q=x.delta&&typeof x.delta=="object"?x.delta:{},$=[],p=be(q.reasoning_content);p&&(c+=p,$.push({type:"reasoning_delta",text:p,raw:u}));let H=be(q.content);return H&&$.push({type:"text_delta",text:H,raw:u}),Qe(o,q.tool_calls),s=D(x.finish_reason)??s,y=tn(u)??y,$},"consumeEvent"),E=a(h=>{let u=h.endsWith("\r")?h.slice(0,-1):h;return u?u.startsWith(":")?[]:(u.startsWith("data:")&&S.push(u.slice(5).trimStart()),[]):ee()},"consumeLine");try{for(;;){let h=await f.read();if(h.done)break;m+=w.decode(h.value,{stream:!0});let u=m.split(`
|
|
4
4
|
`);m=u.pop()??"";for(let I of u)for(let b of E(I))yield b}if(m+=w.decode(),m)for(let h of E(m))yield h;for(let h of ee())yield h}finally{f.releaseLock()}if(!r)throw new Error("OpenPond OpChat request failed: stream ended before [DONE].");let O=Xe(o);O.length>0&&(yield{type:"tool_call_delta",toolCalls:O,raw:i}),O.length>0&&c&&(yield{type:"continuation",continuation:{kind:"chat_completions_reasoning",reasoningContent:c},raw:i});let C=Je(y,A);C&&(yield{type:"usage",usage:C,raw:i}),yield{type:"finish",finishReason:s,raw:i}}a(Ve,"streamOpChatChatCompletion");function Ge(e){let n=xe(e,["fireworks-prompt-tokens","prompt-tokens"]),t=xe(e,["fireworks-cached-prompt-tokens","cached-prompt-tokens"]);return t===null?null:{...n===null?{}:{prompt_tokens:n},cached_input_tokens:t,cache_telemetry_source:"provider_response_headers"}}a(Ge,"cacheUsageFromResponseHeaders");function xe(e,n){for(let t of n){let o=e.get(t);if(o===null||!/^\d+$/.test(o.trim()))continue;let r=Number(o);if(Number.isSafeInteger(r)&&r>=0)return r}return null}a(xe,"firstHeaderTokenCount");function Je(e,n){if(!n||Ye(e))return e;let t={...e??{},cached_input_tokens:n.cached_input_tokens,cache_telemetry_source:"provider_response_headers"};return B(e?.prompt_tokens)===null&&n.prompt_tokens!==void 0&&(t.prompt_tokens=n.prompt_tokens),t}a(Je,"usageWithResponseHeaderCache");function Ye(e){return e?B(e.cached_input_tokens)!==null||B(e.cache_read_input_tokens)!==null||B(e.cache_creation_input_tokens)!==null||B(e.prompt_cache_hit_tokens)!==null||B(e.prompt_cache_miss_tokens)!==null?!0:B(e.prompt_tokens_details?.cached_tokens)!==null||B(e.input_tokens_details?.cached_tokens)!==null:!1}a(Ye,"usageHasCacheTelemetry");function B(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return e;if(typeof e!="string"||!/^\d+$/.test(e.trim()))return null;let n=Number(e);return Number.isSafeInteger(n)?n:null}a(B,"usageTokenCount");function Qe(e,n){Array.isArray(n)&&n.forEach((t,o)=>{if(!t||typeof t!="object")return;let r=t,s=typeof r.index=="number"&&Number.isInteger(r.index)?r.index:o,i=e.get(s)??{arguments:""};typeof r.id=="string"&&(i.id=r.id);let c=r.function&&typeof r.function=="object"?r.function:{};typeof c.name=="string"&&(i.name=`${i.name??""}${c.name}`),typeof c.arguments=="string"&&(i.arguments+=c.arguments),e.set(s,i)})}a(Qe,"mergeOpChatToolCallDeltas");function Xe(e){return[...e.entries()].sort(([n],[t])=>n-t).flatMap(([,n])=>n.id&&n.name?[{id:n.id,type:"function",function:{name:n.name,arguments:n.arguments}}]:[])}a(Xe,"completedOpChatToolCalls");function Ze(e,n){let t={model:e.model,messages:e.messages.map(nn),stream:n};return e.tools&&(t.tools=e.tools),e.toolChoice!==void 0&&(t.tool_choice=e.toolChoice),typeof e.maxTokens=="number"&&(t.max_tokens=e.maxTokens),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.topP=="number"&&(t.top_p=e.topP),Object.assign(t,en(e.reasoningEffort)),t}a(Ze,"buildOpChatBody");function en(e){return e?e==="low"?{thinking:{type:"disabled"}}:{thinking:{type:"enabled"},reasoning_effort:e==="xhigh"?"max":"high"}:{}}a(en,"opChatReasoningFields");function nn(e){let{continuation:n,images:t,...o}=e,r=t?.length?[...typeof e.content=="string"&&e.content.trim()?[{type:"text",text:e.content}]:[],...t.map(s=>({type:"image_url",image_url:{url:s.url,...s.detail?{detail:s.detail}:{}}}))]:e.content;return e.role==="assistant"&&n?.kind==="chat_completions_reasoning"?{...o,...r!==void 0?{content:r}:{},reasoning_content:n.reasoningContent}:{...o,...r!==void 0?{content:r}:{}}}a(nn,"opChatMessage");function re(e,n){let t=e.trim().replace(/\/+$/,"");if(!t)throw new Error("OpenPond OpChat API base URL is required.");return`${t}/${n}`}a(re,"opChatEndpointUrl");function ae(e,n,t){let o=e.trim();if(!o)throw new Error("OpenPond API key is required for OpChat.");let r=new Headers;return r.set("Authorization",`Bearer ${o}`),r.set("Content-Type","application/json"),r.set("Accept",n),r.set("x-openpond-client","openpond-app"),r.set("x-openpond-request-id",t||He()),r}a(ae,"opChatHeaders");async function se(e){let n=await e.text().catch(()=>"");if(!n)return e.statusText||`HTTP ${e.status}`;try{return ke(JSON.parse(n))}catch{return n}}a(se,"readOpChatError");function ke(e){if(!e||typeof e!="object")return String(e||"unknown_error");let n=e,t=n.error;if(t&&typeof t=="object"){let o=t;return[D(o.code),D(o.type),D(o.message)].filter(Boolean).join(": ")}return[D(n.error),D(n.message)].filter(Boolean).join(": ")||JSON.stringify(e)}a(ke,"errorMessageFromPayload");function tn(e){if(!e||typeof e!="object")return null;let n=e.usage;return!n||typeof n!="object"?null:n}a(tn,"parseUsage");function D(e){return typeof e=="string"&&e.trim()?e:null}a(D,"stringValue");function be(e){return typeof e=="string"&&e.length>0?e:null}a(be,"streamTextValue");import{readFileSync as on}from"node:fs";var j;function rn(){if(j!==void 0)return j??"openpond-code bundled";try{let e=new URL("../package.json",import.meta.resolve("openpond")),n=JSON.parse(on(e,"utf8"));j=typeof n.version=="string"?`openpond-code@${n.version}`:null}catch{j=null}return j??"openpond-code bundled"}a(rn,"getBundledRuntimeVersion");import{spawn as an}from"node:child_process";function Be(e,n=process.platform){return n==="darwin"?{command:"open",args:[e]}:n==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}a(Be,"resolveSystemBrowserCommand");async function sn(e,n={}){let t=n.command??Be(e),o=n.handoffTimeoutMs??1500;return new Promise(r=>{let s=!1,i=null,c=a(A=>{s||(s=!0,i&&clearTimeout(i),r(A))},"finish"),y=an(t.command,t.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});y.once("error",A=>{let f=A.code;c({opened:!1,error:f?`browser launcher ${t.command} failed (${f})`:`browser launcher ${t.command} failed`})}),y.once("close",(A,f)=>{if(A===0){c({opened:!0});return}let w=f?`signal ${f}`:`code ${A??"unknown"}`;c({opened:!1,error:`browser launcher ${t.command} exited with ${w}`})}),i=setTimeout(()=>{y.unref(),c({opened:!0})},o),i.unref()})}a(sn,"openUrlWithSystemBrowser");function ln(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t;if(!t||!o)return null;let r=n.latestDeployment&&typeof n.latestDeployment=="object"?n.latestDeployment:null,s=ge.safeParse(n.sandboxActionRegistry);return{id:t,name:o,description:typeof n.description=="string"?n.description:null,visibility:typeof n.visibility=="string"?n.visibility:null,gitOwner:typeof n.gitOwner=="string"?n.gitOwner:null,gitRepo:typeof n.gitRepo=="string"?n.gitRepo:null,gitHost:typeof n.gitHost=="string"?n.gitHost:null,defaultBranch:typeof n.defaultBranch=="string"?n.defaultBranch:null,sandbox:n.sandbox===!0,sandboxActionRegistry:s.success?s.data:null,sandboxManifestHash:typeof n.sandboxManifestHash=="string"?n.sandboxManifestHash:null,sandboxManifestPath:typeof n.sandboxManifestPath=="string"?n.sandboxManifestPath:null,sandboxManifestSyncedAt:typeof n.sandboxManifestSyncedAt=="string"?n.sandboxManifestSyncedAt:n.sandboxManifestSyncedAt instanceof Date?n.sandboxManifestSyncedAt.toISOString():null,sandboxManifestError:typeof n.sandboxManifestError=="string"?n.sandboxManifestError:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null,latestDeployment:r?{id:typeof r.id=="string"?r.id:void 0,status:typeof r.status=="string"?r.status:void 0,deploymentDomain:typeof r.deploymentDomain=="string"?r.deploymentDomain:null,createdAt:typeof r.createdAt=="string"?r.createdAt:void 0,isProduction:typeof r.isProduction=="boolean"?r.isProduction:null,gitBranch:typeof r.gitBranch=="string"?r.gitBranch:null}:null,scheduleSummary:un(n.scheduleSummary)}}a(ln,"normalizeApp");function _(e){return typeof e=="string"?e:e instanceof Date?e.toISOString():null}a(_,"normalizeDateString");function cn(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t,r=typeof n.deploymentId=="string"?n.deploymentId:null;return!t||!o||!r?null:{id:t,name:o,description:typeof n.description=="string"?n.description:null,scheduleType:typeof n.scheduleType=="string"?n.scheduleType:"cron",scheduleExpression:typeof n.scheduleExpression=="string"?n.scheduleExpression:"",enabled:!!n.enabled,rawEnabled:typeof n.rawEnabled=="boolean"?n.rawEnabled:void 0,syncStatus:typeof n.syncStatus=="string"?n.syncStatus:null,syncError:typeof n.syncError=="string"?n.syncError:null,startAt:_(n.startAt),endAt:_(n.endAt),maxRuns:typeof n.maxRuns=="number"?n.maxRuns:null,executionCount:typeof n.executionCount=="number"?n.executionCount:null,lifecycleStatus:typeof n.lifecycleStatus=="string"?n.lifecycleStatus:null,lifecycleReason:typeof n.lifecycleReason=="string"?n.lifecycleReason:null,lastExecutionAt:_(n.lastExecutionAt),lastExecutionStatus:typeof n.lastExecutionStatus=="string"?n.lastExecutionStatus:null,lastRunNowAt:_(n.lastRunNowAt),lastRunNowStatus:typeof n.lastRunNowStatus=="string"?n.lastRunNowStatus:null,updatedAt:_(n.updatedAt)??new Date().toISOString(),deploymentId:r,isProduction:typeof n.isProduction=="boolean"?n.isProduction:void 0,payload:n.payload}}a(cn,"normalizeSchedule");function un(e){if(!e||typeof e!="object")return null;let n=e,t=Array.isArray(n.schedules)?n.schedules.map(cn).filter(i=>!!i):[],o=typeof n.total=="number"?n.total:t.length,r=typeof n.active=="number"?n.active:t.filter(i=>i.enabled).length,s=typeof n.paused=="number"?n.paused:Math.max(0,o-r);return{total:o,active:r,paused:s,enabled:typeof n.enabled=="number"?n.enabled:r,disabled:typeof n.disabled=="number"?n.disabled:s,nextRunAt:_(n.nextRunAt),lastRunAt:_(n.lastRunAt),schedules:t,truncated:typeof n.truncated=="boolean"?n.truncated:void 0}}a(un,"normalizeScheduleSummary");async function dn(e){let n=Array.isArray(e.config.accounts)?e.config.accounts:[],t=await Promise.all(n.map(async o=>{let r=z(o.handle,o.baseUrl),s=Y(o);if(!s)return[r,{response:null,authFailed:!1,error:null}];try{return[r,{response:await K(G(o,e.config),s),authFailed:!1,error:null}]}catch(i){return[r,{response:null,authFailed:!0,error:L(i)}]}}));return Object.fromEntries(t)}a(dn,"loadAccountProfileLookups");async function Ee(e){let n=await dn(e),t=e.account?n[z(e.account.handle,e.account.baseUrl)]??null:null,o=t?.response??null,r=e.token&&t?.authFailed?t.error||"OpenPond account authentication failed.":null;return{account:X({...e,accountResponse:o,accountProfiles:n,authFailed:!!r,error:r})}}a(Ee,"loadOpenPondAccountStateForContext");async function pn(){return Ee(await d())}a(pn,"loadOpenPondAccountState");async function ve(e={}){let n=await d(),t=Ee(n);if(!n.token)return{...await t,apps:[],error:"No OpenPond API key or session token is configured."};let[o,r]=await Promise.allSettled([t,ue(n.apiBaseUrl,n.token,{handle:n.account?.handle,limit:e.limit??20,offset:e.offset??0,includeScheduled:e.includeScheduled??!0})]);if(o.status==="rejected")throw o.reason;return{account:o.value.account,apps:r.status==="fulfilled"?r.value.map(ln).filter(s=>!!s):[],error:r.status==="rejected"?L(r.reason):null}}a(ve,"loadOpenPondApps");async function fn(e){let n=await d();if(!n.token)throw new Error("No OpenPond API key or session token is configured.");return{account:n,response:await de(n.apiBaseUrl,n.token,e)}}a(fn,"createOpenPondRepoApp");import{createHash as mn}from"node:crypto";function hn(e){return`account-${mn("sha256").update(e).digest("hex").slice(0,8)}`}a(hn,"fallbackHandleForApiKey");function Z(e){let n=e?.trim();return n?n.replace(/^@/,""):null}a(Z,"normalizeDerivedHandle");async function yn(e,n){let t=Z(e.handle);if(t)return t;try{let r=(await K(n,e.apiKey)).account,s=Z(r.handle)??Z(r.email?.split("@")[0])??Z(r.id);if(s)return s}catch{}return hn(e.apiKey)}a(yn,"deriveHandleForApiKey");async function gn(e){let n=e.baseUrl??R,t=l(e.apiBaseUrl)??V(n)??U,o=l(e.chatApiBaseUrl),r=await yn(e,t);return await ye({handle:r,apiKey:e.apiKey,baseUrl:n,apiBaseUrl:t,chatApiBaseUrl:o,environment:e.environment??"production",setActive:e.setActive}),d(r,n)}a(gn,"saveOpenPondAccount");function An(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&v(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its base URL.`);return-1}a(An,"findAccountIndex");async function Pn(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");return await N(t=>{let o=(t.accounts??[]).map(c=>({...c})),r=An(o,n,e.baseUrl);if(r===-1)throw new Error(`OpenPond account not found: ${n}`);let s=o[r],i=g(t.activeProfile);if(i&&k(s,i))throw new Error("Switch to another OpenPond account before removing the active account.");o.splice(r,1),t.accounts=o}),d()}a(Pn,"removeOpenPondAccount");async function wn(){let e;return await N(n=>{let t=g(n.activeProfile),o=(n.accounts??[]).map(s=>({...s})),r=t?o.findIndex(s=>k(s,t)):0;if(r<0||!o[r])throw new Error("No active OpenPond account to log out.");e={...o[r]},delete e.apiKey,delete e.session,o[r]=e,n.accounts=o}),d(e.handle,e.baseUrl)}a(wn,"signOutOpenPondAccount");function On(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&v(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its current base URL.`);return-1}a(On,"findAccountIndex");function ie(e,n,t){if(t===void 0)return;let o=l(t);if(o){e[n]=o;return}(t===null||t.trim()==="")&&delete e[n]}a(ie,"applyOptionalUrl");async function xn(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");let t;return await N(o=>{let r=(o.accounts??[]).map(f=>({...f})),s=On(r,n,e.currentBaseUrl);if(s===-1)throw new Error(`OpenPond account not found: ${n}`);let i=r[s];if(t={...i},ie(t,"baseUrl",e.baseUrl),ie(t,"apiBaseUrl",e.apiBaseUrl),ie(t,"chatApiBaseUrl",e.chatApiBaseUrl),e.environment===null?delete t.environment:typeof e.environment=="string"&&e.environment.trim()&&(t.environment=e.environment.trim()),r.findIndex((f,w)=>w!==s&&P(f.handle,t.handle)&&v(f.baseUrl,t.baseUrl))!==-1)throw new Error("Another OpenPond account already uses that handle and base URL.");let y=g(o.activeProfile),A=!!(y&&k(i,y));r[s]=t,o.accounts=r,o.activeProfile=e.setActive||A?F(t):o.activeProfile}),d(t.handle,t.baseUrl)}a(xn,"updateOpenPondAccountConfig");async function bn(e){let n=await d();if(!n.token)throw new Error("OpenPond is signed out. Add an account before reading app config.");return pe(n.apiBaseUrl,n.token,e.appId)}a(bn,"getOpenPondAppEnvironment");function Un(e,n){let t="",o=a(r=>{r.startsWith(e)&&n(JSON.parse(r.slice(e.length)))},"processLine");return{push(r){for(t+=r;;){let s=kn(t);if(s<0)return;let i=t.slice(0,s).replace(/\r$/,""),c=t[s]==="\r"&&t[s+1]===`
|
|
5
5
|
`?2:1;t=t.slice(s+c),o(i)}},flush(){let r=t.trimEnd();t="",r&&o(r)}}}a(Un,"createReadyLineParser");function kn(e){let n=e.indexOf(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{Ab as Ie,Bb as F,Hb as ye,Jb as B,Ka as X,Kb as Ae,Ma as Y,Mb as Le,Oa as Z,Pa as V,Pb as Ce,Qa as ee,Qb as je,Ra as ie,Rb as Ee,Sa as te,Sb as N,Ua as ne,Ub as Te,Va as re,Vb as De,Wa as ae,Ya as oe,_a as se,a as m,ab as ce,cb as y,db as u,eb as de,fb as me,gb as le,hb as ue,ib as pe,kb as ge,lb as he,mb as fe,ob as be,pb as xe,qb as ve,rb as we,sb as P,tb as Se,ub as Re,vb as _,wa as H,wb as I,yb as _e,zb as ke}from"./chunk-XAYIETBO.js";import{a,b as E,c as l,e as C,l as k}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var M=e.discriminatedUnion("kind",[e.object({kind:e.literal("manual"),identity:a}).strict(),e.object({kind:e.literal("schedule"),scheduledAt:l}).strict(),e.object({kind:e.literal("approved_count"),checkedAt:l}).strict()]),$=e.object({schemaVersion:e.literal("openpond.learningChain.v1"),id:a,revision:e.number().int().positive(),modelProjectId:a,activeIterationId:a.nullable(),acceptedParent:P.nullable().optional(),latestIterationId:a,lastReservedAt:l.nullable(),updatedAt:l}).strict(),G=e.object({eligible:e.number().int().nonnegative(),awaitingReview:e.number().int().nonnegative(),excluded:e.number().int().nonnegative(),consumed:e.number().int().nonnegative()}).strict(),qe=e.object({schemaVersion:e.literal("openpond.learningConsumption.v1"),id:a,revision:e.literal(1),chainId:a,iterationId:a,evidence:u,decision:u,reservedAt:l}).strict(),Pe=e.object({schemaVersion:e.literal("openpond.learningIterationReservation.v1"),id:a,revision:e.number().int().positive(),chainId:a,iterationId:a,policy:u,trigger:M,requestHash:E,outcome:e.enum(["reserved","waiting_for_data","waiting_for_review"]),counts:G,budget:e.object({maximumSpendUsd:e.number().nonnegative(),reservedSpendUsd:e.number().nonnegative(),settledSpendUsd:e.number().nonnegative(),settledAt:l.nullable()}).strict(),createdAt:l,updatedAt:l}).strict();var v=e.object({operationId:a}),Xe=v.extend({action:e.literal("import_intake"),format:Te,files:e.array(De).min(1).max(100),expectedPreviewHash:e.string().length(64),name:e.string().trim().min(1).max(500),recordIds:e.array(e.string().min(1).max(200)).min(1).max(90)}).strict(),O=v.extend({action:e.literal("publish"),expectedRevision:e.number().int().nonnegative(),finalizeDraft:N.optional()}),Oe=e.discriminatedUnion("kind",[O.extend({kind:e.literal("asset"),content:ke}).strict(),O.extend({kind:e.literal("definition"),content:de}).strict(),O.extend({kind:e.literal("reward"),content:Z}).strict(),O.extend({kind:e.literal("binding"),content:ee}).strict(),O.extend({kind:e.literal("source"),content:le}).strict(),O.extend({kind:e.literal("policy"),content:ve}).strict()]),Ye=v.extend({action:e.literal("publish_resources"),finalizeDraft:N.optional(),resources:e.array(e.union(Oe.options.map(t=>t.omit({operationId:!0,action:!0,finalizeDraft:!0})))).min(1).max(20)}).strict(),Ze=v.extend({action:e.literal("submit_example"),example:pe}).strict(),ei=v.extend({action:e.literal("submit_feedback"),feedback:he}).strict(),ii=v.extend({action:e.literal("apply_correction"),feedbackId:a,evidence:u}).strict(),ti=v.extend({action:e.literal("resolve_feedback"),feedbackId:a,expectedRevision:e.number().int().positive(),disposition:e.enum(["applied","rejected","superseded"]),decision:u.nullable(),note:e.string().max(2e4)}).strict(),ni=v.extend({action:e.literal("queue_grade"),evidence:u,target:e.enum(["observed","proposed_target"]),proposedTarget:y.nullable(),timeoutMs:e.number().int().min(100).max(3e5).default(3e4),maximumSpendUsd:e.number().nonnegative().max(1e3).default(0)}).strict(),ri=v.extend({action:e.literal("review"),evidence:u,expectedRevision:e.number().int().nonnegative(),disposition:e.enum(["approved","rejected","pending"]),targetApproval:e.enum(["approved","rejected","pending","not_required"]),approvedTarget:y.nullable(),observedGradeId:a.nullable(),targetGradeId:a.nullable(),note:e.string().max(2e4)}).strict(),ai=v.extend({action:e.literal("seal_batch"),batchId:a,taskDefinition:u,purpose:e.enum(["supervised_training","reward_training","evaluation"]),evidence:e.array(u).min(1).max(1e4),decisions:e.array(u).min(1).max(1e4)}).strict(),oi=v.extend({action:e.literal("cancel_grade"),gradeId:a,expectedRevision:e.number().int().positive()}).strict(),si=v.extend({action:e.literal("save_draft"),expectedRevision:e.number().int().nonnegative(),draft:je}).strict(),ci=v.extend({action:e.literal("archive_draft"),draft:u}).strict(),di=v.extend({action:e.literal("queue_reward_check"),draft:u,timeoutMs:e.number().int().min(100).max(3e5).default(3e4),maximumSpendUsd:e.number().nonnegative().max(1e3).default(0)}).strict(),mi=v.extend({action:e.literal("cancel_reward_check"),checkId:a,expectedRevision:e.number().int().positive()}).strict(),li=v.extend({action:e.literal("publish_checked_reward"),draft:u,checkId:a,checkRevision:e.number().int().positive()}).strict(),ui=v.extend({action:e.literal("reserve_iteration"),policy:u,trigger:M}).strict(),pi=v.extend({action:e.literal("cancel_iteration_reservation"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),gi=v.extend({action:e.literal("cancel_iteration"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),hi=v.extend({action:e.literal("retry_iteration_dispatch"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),He=e.union([li,Xe,gi,hi,pi,ui,di,mi,si,ci,Oe,Ye,Ze,ei,ii,ti,ni,ri,ai,oi]);var fi=e.object({provider:a,protocol:a,payload:y}).strict(),Fe=e.object({schemaVersion:e.literal("openpond.learningIterationDispatch.v1"),id:a,revision:e.number().int().positive(),iterationId:a,chainId:a,policy:u,batch:u,state:e.enum(["preparing","prepared","submitted","settled","blocked"]),submission:fi.nullable(),submissionHash:e.string().regex(/^[a-f0-9]{64}$/).nullable(),submissionStartedAt:l.nullable(),execution:C.nullable(),terminalReceipt:C.nullable(),cancelRequestedAt:l.nullable(),leaseOwner:a.nullable(),leaseGeneration:e.number().int().nonnegative(),leaseExpiresAt:l.nullable(),consecutiveFailures:e.number().int().nonnegative(),nextAttemptAt:l.nullable(),lastError:e.string().max(2e4).nullable(),createdAt:l,updatedAt:l}).strict().superRefine((t,i)=>{(!!t.submission!=!!t.submissionHash||t.submission&&k(t.submission)!==t.submissionHash)&&i.addIssue({code:"custom",path:["submissionHash"],message:"Dispatch submission identity changed."}),t.submissionStartedAt&&!t.submission&&i.addIssue({code:"custom",path:["submission"],message:"A started dispatch requires its persisted submission."}),t.execution&&!t.submissionStartedAt&&i.addIssue({code:"custom",path:["execution"],message:"An execution requires a started dispatch."}),["prepared","submitted"].includes(t.state)&&!t.submission&&i.addIssue({code:"custom",path:["state"],message:"A prepared dispatch requires its immutable submission."}),t.state==="submitted"&&!t.execution&&i.addIssue({code:"custom",path:["execution"],message:"A submitted dispatch requires an observed execution."}),t.state==="settled"&&t.submissionStartedAt&&!t.terminalReceipt&&i.addIssue({code:"custom",path:["terminalReceipt"],message:"A started dispatch requires terminal receipt evidence before settlement."}),!!t.leaseOwner!=!!t.leaseExpiresAt&&i.addIssue({code:"custom",path:["leaseOwner"],message:"Dispatch lease owner and expiration must be recorded together."})}),Bi=e.object({scope:a,dispatchId:a,submissionHash:e.string().regex(/^[a-f0-9]{64}$/),execution:C.nullable(),status:e.enum(["running","evaluating","succeeded","failed","cancelled"]),spendUsd:e.number().nonnegative(),cleanupComplete:e.boolean(),receipt:C.nullable(),evaluation:C.nullable(),candidate:C.nullable(),failure:e.string().max(2e4).nullable()}).strict().superRefine((t,i)=>{["succeeded","failed","cancelled"].includes(t.status)&&(!t.cleanupComplete||!t.receipt)&&i.addIssue({code:"custom",path:["receipt"],message:"Terminal execution requires an authoritative cleanup receipt."}),t.status!=="cancelled"&&!t.execution&&i.addIssue({code:"custom",path:["execution"],message:"The execution identity is required."}),t.candidate&&(t.status!=="succeeded"||!t.evaluation)&&i.addIssue({code:"custom",path:["candidate"],message:"A candidate requires successful retained evaluation."})});var Be=e.object({schemaVersion:e.literal("openpond.learningSchedule.v1"),id:a,revision:e.number().int().positive(),policy:u,modelProjectId:a,executionOwner:e.enum(["local","hosted"]),state:e.enum(["scheduled","disabled","blocked"]),intervalSeconds:e.number().int().min(60).max(31536e3).nullable(),calendar:ce.nullable().default(null),nextRunAt:l.nullable(),lastFire:u.nullable(),consecutiveFailures:e.number().int().nonnegative(),nextAttemptAt:l.nullable(),lastError:e.string().max(2e4).nullable(),createdAt:l,updatedAt:l}).strict().superRefine((t,i)=>{t.state!=="disabled"&&(!t.intervalSeconds&&!t.calendar||!t.nextRunAt)&&i.addIssue({code:"custom",path:["nextRunAt"],message:"An active timer must retain its cadence and due time."}),t.state==="disabled"&&t.nextRunAt&&i.addIssue({code:"custom",path:["nextRunAt"],message:"A disabled timer cannot have a pending occurrence."}),t.intervalSeconds&&t.calendar&&i.addIssue({code:"custom",path:["calendar"],message:"A timer uses either an interval or a nightly calendar."})}),Ue=e.object({schemaVersion:e.literal("openpond.learningScheduleFire.v1"),id:a,revision:e.literal(1),scheduleId:a,policy:u,scheduledAt:l,coalescedThroughAt:l,coalescedCount:e.number().int().nonnegative(),outcome:e.enum(["reserved","waiting_for_data","waiting_for_review","skipped"]),reason:e.enum(["active_iteration","cooldown","daily_budget"]).nullable(),iteration:e.object({id:a,revision:e.number().int().positive()}).strict().nullable(),createdAt:l,contentHash:E}).strict().superRefine((t,i)=>{(t.outcome==="skipped"!=!!t.reason||t.outcome!=="skipped"!=!!t.iteration)&&i.addIssue({code:"custom",path:["outcome"],message:"A fire retains either its reservation or its explicit skip reason."})});function $e(t){H(t,262144);let i=Ce.parse(t.fields),r=t.base?V.parse(t.base):null;if(r&&r.id!==t.id)throw new m("reward_authoring_base_mismatch",422);let o=i.fixtures?.length?F({text:JSON.stringify(i.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null,n=null,s,d;if(i.kind==="custom_verifier")n=F({text:i.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),s={kind:i.kind,verifierRef:n.asset,exportName:i.exportName,timeoutMs:T(i.timeout,"Time limit"),networkPolicy:"none"};else if(i.kind==="model_judge"||i.kind==="human"){if(!i.rubric.trim())throw new m("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(n=F({text:i.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),i.kind==="human")s={kind:i.kind,rubricRef:n.asset,reviewerRole:i.reviewerRole};else{let h={providerId:i.providerId,modelId:i.modelId,revision:i.modelRevision.trim()||null},x=T(i.temperature,"Temperature"),w=r?.implementation,b=w?.kind==="model_judge"&&w.rubricRef.contentHash===n.asset.contentHash&&w.model?.providerId===h.providerId&&w.model?.modelId===h.modelId&&w.model?.revision===h.revision&&(w.temperature??0)===x&&r?.fixtureSetRef?.contentHash===o?.asset.contentHash;s={kind:i.kind,rubricRef:n.asset,model:h,temperature:x,calibrationStatus:b?w.calibrationStatus:"pending"},b&&(d=r?.calibrationCheckRef)}}else i.kind==="learned_model"?(D(i.inputContract,"Model input contract"),n=F({text:i.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),s={kind:i.kind,modelVersion:{id:i.learnedId,contentHash:i.learnedHash},inputContract:n.asset}):i.kind==="state"?s={kind:i.kind,config:{fields:Ve(i.fields)}}:i.kind==="content"?s={kind:i.kind,config:{outputField:i.outputField,expectedField:i.expectedField,...i.expectedValue?{expectedValue:i.expectedValue}:{}}}:i.kind==="schema"?s={kind:i.kind,config:{jsonSchema:D(i.schema,"Output schema")}}:i.kind==="artifact"?s={kind:i.kind,config:{refIncludes:i.reference}}:s={kind:i.kind,config:{requiredEvents:Ve(i.events)}};let g=[...n?[n]:[],...o?[o]:[]];return{reward:ne({schemaVersion:"openpond.rewardRelease.v1",id:t.id,revision:(r?.revision??0)+1,name:i.name,description:i.description,implementation:s,rawScore:i.kind==="learned_model"?{minimum:T(i.minimum,"Minimum score"),maximum:T(i.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:g.map(h=>h.asset),...o?{fixtureSetRef:o.asset}:{},...d?{calibrationCheckRef:d}:{}}),assets:g}}c($e,"compileRewardAuthoring");function D(t,i){try{let r=JSON.parse(t);return H(r,131072),y.parse(r)}catch{throw new m("reward_authoring_json_invalid",422,`${i} must be a JSON object.`)}}c(D,"parseRewardAuthoringObject");function T(t,i){let r=Number(t);if(!t.trim()||!Number.isFinite(r))throw new m("reward_authoring_number_invalid",422,`${i} must be a finite number.`);return r}c(T,"authoringNumber");function Ve(t){return t.split(",").map(i=>i.trim()).filter(Boolean)}c(Ve,"split");var Je=e.object({id:a,name:e.string().trim().min(1).max(500),input:y,output:y,expectedOutput:y.nullable(),evaluatorContext:y.nullable(),artifactRefs:e.array(a).max(100),runtimeEventRefs:e.array(a).max(100),infrastructureError:e.string().max(2e4).nullable(),expected:e.discriminatedUnion("status",[e.object({status:e.literal("scored"),minimum:e.number().finite(),maximum:e.number().finite(),passed:e.boolean().nullable()}).strict(),e.object({status:e.enum(["pending","unavailable","failed"])}).strict()])}).strict().superRefine((t,i)=>{t.expected.status==="scored"&&t.expected.minimum>t.expected.maximum&&i.addIssue({code:"custom",path:["expected"],message:"Expected score minimum must not exceed maximum."})}),bi=e.object({id:a,packageVersion:e.string().min(1).max(100),engine:e.string().min(1).max(200)}).strict(),ze=e.object({fixture:e.object({id:a,contentHash:E}).strict(),result:te,matchesExpectation:e.boolean()}).strict(),Ne=e.object({schemaVersion:e.literal("openpond.rewardCheckRun.v1"),id:a,revision:e.number().int().positive(),draft:u,reward:u,snapshotHash:E,fixtureRefs:e.array(e.object({id:a,contentHash:E}).strict()).min(1).max(50),status:e.enum(["queued","running","completed","failed","cancelling","cancelled"]),runtime:bi.nullable(),results:e.array(ze).max(50),matchesExpectations:e.boolean().nullable(),failure:e.string().max(2e4).nullable(),timeoutMs:e.number().int().min(100).max(3e5),maximumSpendUsd:e.number().nonnegative().max(1e3),judgeCalls:e.array(se).max(1e3).optional(),requestedBy:a.optional(),leaseOwner:a.nullable(),leaseExpiresAt:l.nullable(),attemptCount:e.number().int().nonnegative(),createdAt:l,updatedAt:l}).strict();function xi(t){if(!t.length||t.length>50)throw new m("reward_check_fixtures_required",422,"Add between one and 50 fixtures before checking this Reward.");if(new Set(t.map(i=>i.id)).size!==t.length)throw new m("reward_fixture_id_duplicate",422);return t.map(i=>Je.parse({id:i.id,name:i.name,input:D(i.input,`${i.name}: input`),output:D(i.output,`${i.name}: output`),expectedOutput:i.expectedOutput.trim()?D(i.expectedOutput,`${i.name}: expected answer`):null,evaluatorContext:i.evaluatorContext.trim()?D(i.evaluatorContext,`${i.name}: evaluator context`):null,artifactRefs:i.artifactRefs.map(r=>r.trim()).filter(Boolean),runtimeEventRefs:i.runtimeEventRefs.map(r=>r.trim()).filter(Boolean),infrastructureError:i.infrastructureError||null,expected:i.expectedStatus==="scored"?{status:i.expectedStatus,minimum:T(i.minimumScore,`${i.name}: minimum score`),maximum:T(i.maximumScore,`${i.name}: maximum score`),passed:i.expectedPassed==="any"?null:i.expectedPassed==="true"}:{status:i.expectedStatus}}))}c(xi,"compileRewardFixtures");function mt(t,i){let r=$e({id:t.targetId,fields:t.fields,base:i}),o=xi(t.fields.fixtures??[]),n=o.map(s=>({id:s.id,contentHash:k(s)}));return{...r,fixtures:o,fixtureRefs:n,snapshotHash:k({reward:r.reward,fixtures:o})}}c(mt,"compileRewardCheck");async function lt(t){let i=Je.parse(t.fixture),r=X.parse({id:i.id,clusterKey:i.id,split:"validation",input:i.input,expectedOutput:i.expectedOutput,privilegedContextRef:null}),o=re({schemaVersion:"openpond.rewardBinding.v1",id:`fixture-binding-${k(_(t.reward))}`,revision:1,sources:[{graderId:t.reward.id,reward:_(t.reward),role:"evaluation",normalization:t.reward.rawScore.minimum===0&&t.reward.rawScore.maximum===1?{kind:"identity"}:{kind:"linear",minimum:t.reward.rawScore.minimum,maximum:t.reward.rawScore.maximum,direction:"higher"},weight:1,required:!0,hardGate:!1,privileged:!0,fixtureRefs:[]}],aggregation:"weighted_mean",unscorable:"exclude_optional_require_all_required"},[t.reward]);return(await oe({binding:o,rewards:[t.reward],task:r,evidence:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},signal:t.signal,customVerifier:t.customVerifier,modelJudge:t.modelJudge,purpose:"fixture_calibration"})).results[0]}c(lt,"executeRewardFixture");function ut(t,i){let r=t.expected,o=i.status===r.status&&(r.status!=="scored"||i.rawScore!==null&&i.rawScore>=r.minimum&&i.rawScore<=r.maximum&&(r.passed===null||r.passed===i.passed));return ze.parse({fixture:{id:t.id,contentHash:k(t)},result:i,matchesExpectation:o})}c(ut,"matchRewardFixture");var J={draft:Ee,reward_check:Ne,asset:Ie,definition:me,reward:V,binding:ie,source:ue,evidence:ge,feedback:fe,decision:be,batch:xe,policy:we,chain:$,consumption:qe,reservation:Pe,dispatch:Fe,schedule:Be,schedule_fire:Ue,iteration:Se,grade:Re,package:Y},Q=e.enum(Object.keys(J)),Me=class extends m{static{c(this,"LearningConflictError")}kind;id;expectedRevision;currentRevision;constructor(i,r,o,n){super("learning_revision_conflict",409,`Revision conflict for ${i} ${r}: expected ${o}, current ${n}.`),this.kind=i,this.id=r,this.expectedRevision=o,this.currentRevision=n,this.name="LearningConflictError"}};async function L(t,i,r,o){let n=await t.get(i,r,o);if(!n)throw new m("learning_resource_not_found",404,`${i}:${r}`);return J[i].parse(n)}c(L,"requireLearningResource");async function S(t,i,r){let o=await L(t,i,r.id,r.revision);if(!("contentHash"in o)||o.contentHash!==r.contentHash)throw new m("learning_release_hash_mismatch",409,`${i}:${r.id}`);return _e(o),o}c(S,"requireLearningRelease");function At(t,i,r){return`evidence-${k([t,i,r])}`}c(At,"learningEvidenceId");function Lt(t,i){return k([t,i])}c(Lt,"learningOperationId");async function Ot(t,i,r,o){let{batch:n,release:s,evidence:d,definition:g}=await K(t,i,r,o);for(let f of d)for(let h of B(f,g))await t.reserveFamilySplit(h.namespace,h.kind,h.key,h.split);return await t.put("batch",n,0,{parentId:g.id}),await t.put("package",s,0,{parentId:n.id}),[Ge("batch",n),Ge("package",s)]}c(Ot,"sealLearningBatch");async function K(t,i,r,o){let n=await S(t,"definition",i.taskDefinition),s=await S(t,"binding",n.rewardBinding),d=await Promise.all(s.sources.map(b=>S(t,"reward",b.reward)));ae(s,d);let g=await Promise.all(i.evidence.map(b=>vi(t,b))),f=await Promise.all(i.decisions.map(async b=>{let R=await S(t,"decision",b),p=await L(t,"decision",b.id);if(!I(_(p),b))throw new m("task_admission_revision_stale",409);return R})),h=[];for(let b of g)for(let R of B(b,n)){let p=await t.familySplit(R.namespace,R.kind,R.key);p!==null&&h.push({...R,split:p})}let x=Ae({id:i.batchId,definition:n,binding:s,rewards:d,purpose:i.purpose,evidence:g,decisions:f,priorSplits:h,actorId:r,now:o}),w=Le({batch:x,definition:n,binding:s,rewards:d,evidence:g,decisions:f});return{batch:x,release:w,evidence:g,definition:n}}c(K,"prepareLearningBatch");async function vi(t,i){let r=await S(t,"evidence",i),o=await L(t,"evidence",i.id);if(!I(_(o),i))throw new m("task_evidence_revision_stale",409);return r}c(vi,"requireCurrentLearningEvidence");function Ge(t,i){return{kind:t,id:i.id,revision:i.revision}}c(Ge,"pointer");async function Qe(t,i,r){let o=new Date(r).toISOString().slice(0,10),n=0,s=0,d;do{let g=await t.list("reservation",{parentId:i,limit:100,...d?{afterId:d}:{}});for(let{budget:f}of g.items)n+=f.reservedSpendUsd,f.settledAt&&new Date(f.settledAt).toISOString().slice(0,10)===o&&(s+=f.settledSpendUsd);d=g.nextCursor??void 0}while(d);return{reservedSpendUsd:n,settledSpendUsd:s,committedSpendUsd:n+s}}c(Qe,"readLearningIterationBudget");function W(t){return`chain-${k(t)}`}c(W,"learningChainId");function wi(t,i){return`consumption-${k([t,i.id,i.revision])}`}c(wi,"learningConsumptionId");async function z(t,i,r={}){let o=i.training.method==="sft"?"supervised_training":"reward_training";if(!["sft","grpo","ppo"].includes(i.training.method))throw new m("learning_batch_method_unsupported",422);if(i.admission.mode!=="human")throw new m("learning_automatic_admission_not_available",422);let n=await S(t,"definition",i.taskDefinition);if(!I(n.rewardBinding,i.rewardBinding))throw new m("learning_policy_binding_mismatch",422);let s={eligible:0,awaitingReview:0,excluded:0,consumed:0},d=[],g=[],f=W(i.modelProjectId),h=new Set,x=0;for(let w of i.sources){let b=await S(t,"source",w),R=await L(t,"source",b.id);if(!b.enabled||!R.enabled)throw new m("learning_source_disabled",409);if(!I(b.taskDefinition,i.taskDefinition))throw new m("learning_policy_source_definition_mismatch",422);let p;do{let j=await t.list("evidence",{parentId:b.id,limit:100,...p?{afterId:p}:{}});for(let A of j.items){if(h.has(A.id))continue;if(h.add(A.id),!i.sources.some(U=>I(A.source,U))||!I(A.submission.taskDefinition,i.taskDefinition)||A.submission.split!=="train"){s.excluded+=1;continue}if(await t.get("consumption",wi(f,A))){s.consumed+=1;continue}if(++x>i.limits.maxBacklogExamples)throw new m("learning_backlog_limit_exceeded",409);let q=await t.get("decision",`decision-${A.id}`);if(!q||!I(q.evidence,_(A))||q.taskAdmissibility==="pending"||q.actor.kind!=="human"){s.awaitingReview+=1;continue}try{ye({decision:q,evidence:A,definition:n,purpose:o})}catch(U){if(!(U instanceof m))throw U;s.excluded+=1;continue}s.eligible+=1,r.collectEligible&&g.push(_(A)),d.length<i.limits.maxBatchExamples&&d.push({evidence:A,decision:q})}p=j.nextCursor??void 0}while(p)}return{counts:s,selected:d,purpose:o,eligibleEvidence:g}}c(z,"inspectIterationEligibility");async function Ke(t,i,r=!1){let o=null,n;do{let s=await t.list("iteration",{parentId:i,status:"accepted",limit:100,...n?{afterId:n}:{}});for(let d of s.items){if(!d.candidateVersion||!d.candidateDecision||!d.candidateDecisionAt||!d.trainingJob){if(r)throw new m("learning_accepted_parent_evidence_missing",409);continue}let g=P.parse({iterationId:d.id,iterationRevision:d.revision,candidate:d.candidateVersion,decision:d.candidateDecision,decidedAt:d.candidateDecisionAt}),f=[Date.parse(g.decidedAt),g.decision.id,g.decision.revision],h=o?[Date.parse(o.decidedAt),o.decision.id,o.decision.revision]:null;(!h||f[0]>h[0]||f[0]===h[0]&&(f[1]>h[1]||f[1]===h[1]&&f[2]>h[2]))&&(o=g)}n=s.nextCursor??void 0}while(n);return o}c(Ke,"latestAcceptedLearningParent");async function We(t,i,r){if(!r)return{trainingParent:i.trainingParent,trainingParentSelection:null};let o=await L(t,"iteration",r.iterationId,r.iterationRevision),n=await S(t,"policy",o.policy);if(o.status!=="accepted"||!o.candidateVersion||!o.candidateDecision||!o.trainingJob||o.candidateVersion.id!==r.candidate.id||o.candidateVersion.contentHash!==r.candidate.contentHash||!I(o.candidateDecision,r.decision)||o.candidateDecisionAt!==r.decidedAt||n.modelProjectId!==i.modelProjectId||n.executionOwner!==i.executionOwner)throw new m("learning_accepted_parent_evidence_mismatch",409);if(n.trainingParent.id!==i.trainingParent.id||n.trainingParent.contentHash!==i.trainingParent.contentHash||n.training.method!==i.training.method)throw new m("learning_accepted_parent_configuration_mismatch",409,"The accepted checkpoint belongs to a different starting model or training method.");return{trainingParent:r.candidate,trainingParentSelection:r}}c(We,"resolveLearningTrainingParent");var Si=e.object({policy:u,modelProjectId:a,inspectedAt:l,chain:$.nullable(),trainingParent:e.object({reference:C,selection:P.nullable()}).strict().nullable().default(null),counts:G.nullable(),minimumApprovedExamples:e.number().int().positive(),canReserve:e.boolean(),blockers:e.array(e.object({code:e.string().min(1).max(200),message:e.string().min(1).max(2e4)}).strict()).max(20),cooldownUntil:l.nullable(),budget:e.object({reservedSpendUsd:e.number().nonnegative(),settledSpendUsd:e.number().nonnegative(),committedSpendUsd:e.number().nonnegative(),maximumIterationSpendUsd:e.number().nonnegative(),maximumDailySpendUsd:e.number().nonnegative()}).strict()}).strict();async function mn(t,i,r,o){let n=await S(t,"policy",i),s=await L(t,"policy",n.id);if(!I(_(s),i))throw new m("learning_policy_revision_stale",409);let d=W(n.modelProjectId),g=await t.get("chain",d),f=await Qe(t,d,o),h=[],x=c((p,j)=>{h.push({code:p,message:j})},"block");n.enabled||x("learning_policy_paused","Learning is paused."),(n.automation.accept||n.automation.serve)&&x("learning_automatic_acceptance_not_available","Candidates require explicit acceptance and serving selection."),g?.activeIterationId&&x("learning_iteration_active","An iteration is already active.");let w=g?.lastReservedAt&&Date.parse(o)-Date.parse(g.lastReservedAt)<n.limits.cooldownSeconds*1e3?new Date(Date.parse(g.lastReservedAt)+n.limits.cooldownSeconds*1e3).toISOString():null;w&&x("learning_iteration_cooldown","The training cooldown has not elapsed."),f.committedSpendUsd+n.limits.maxIterationSpendUsd>n.limits.maxDailySpendUsd&&x("learning_daily_budget_exhausted","The daily budget cannot cover another iteration's maximum spend.");let b=null;try{let p=await z(t,n);b=p.counts,b.eligible<n.admission.minimumApprovedExamples?b.awaitingReview>0?x("learning_waiting_for_review","More approved tasks are required before training."):x("learning_waiting_for_data","More eligible new tasks are required before training."):await K(t,{action:"seal_batch",operationId:"policy-inspection",batchId:"policy-inspection",taskDefinition:n.taskDefinition,purpose:p.purpose,evidence:p.selected.map(j=>_(j.evidence)),decisions:p.selected.map(j=>_(j.decision))},r,o)}catch(p){if(!(p instanceof m))throw p;x(p.code,p.message.slice(0,2e4))}let R=null;try{let p=await We(t,n,await Ke(t,d,!0));R={reference:p.trainingParent,selection:p.trainingParentSelection}}catch(p){if(!(p instanceof m))throw p;x(p.code,p.message.slice(0,2e4))}return Si.parse({policy:_(n),modelProjectId:n.modelProjectId,inspectedAt:o,chain:g,trainingParent:R,counts:b,minimumApprovedExamples:n.admission.minimumApprovedExamples,canReserve:h.length===0,blockers:h,cooldownUntil:w,budget:{...f,maximumIterationSpendUsd:n.limits.maxIterationSpendUsd,maximumDailySpendUsd:n.limits.maxDailySpendUsd}})}c(mn,"inspectLearningPolicy");var Ri=e.object({modelProjectId:a.nullable(),inspectedAt:l,pendingTrainingCount:e.number().int().nonnegative().nullable(),issues:e.array(e.object({policyId:a,code:e.string(),message:e.string()}).strict())}).strict();async function vn(t,i,r){let o=new Set,n=[],s;do{let d=await t.list("policy",{limit:100,...i?{parentId:i}:{},...s?{afterId:s}:{}});for(let g of d.items)try{let f=await z(t,g,{collectEligible:!0}),h=await S(t,"definition",g.taskDefinition);for(let x of f.eligibleEvidence){let w=await S(t,"evidence",x),b=!1;for(let R of B(w,h)){let p=await t.familySplit(R.namespace,R.kind,R.key);if(p!==null&&p!=="train"){b=!0;break}}b||o.add(JSON.stringify([x.id,x.revision,x.contentHash]))}}catch(f){if(!(f instanceof m))throw f;n.push({policyId:g.id,code:f.code,message:f.message})}s=d.nextCursor??void 0}while(s);return Ri.parse({modelProjectId:i,inspectedAt:r,pendingTrainingCount:n.length?null:o.size,issues:n})}c(vn,"inspectLearningTaskQueue");function Cn(t){try{H(t,16777216)}catch(i){throw new m("learning_json_invalid",400,i instanceof Error?i.message:"Expected bounded JSON.")}}c(Cn,"assertLearningRequestJson");var jn=e.object({scope:a,command:He}).strict(),En=e.discriminatedUnion("action",[e.object({action:e.literal("inspect_task_queue"),scope:a,modelProjectId:a.nullable()}).strict(),e.object({action:e.literal("inspect_policy"),scope:a,policy:u}).strict(),e.object({action:e.literal("inspect_evidence"),scope:a,evidence:u}).strict(),e.object({action:e.literal("get"),scope:a,kind:Q,id:a,revision:e.number().int().positive().optional()}).strict(),e.object({action:e.literal("list"),scope:a,kind:Q,parentId:a.optional(),status:e.string().min(1).max(200).optional(),reviewState:e.enum(["inbox","reviewed"]).optional(),afterId:a.optional(),limit:e.number().int().min(1).max(100).default(50)}).strict()]),Tn=e.object({evidence:u,definition:u,inspection:e.object({evidenceValidity:e.enum(["valid","invalid"]),taskReady:e.boolean(),observedOutputValid:e.boolean().nullable(),issues:e.array(e.object({path:e.string(),code:e.string(),message:e.string()}).strict()).max(100)}).strict()}).strict(),Dn=e.object({operationId:a,resources:e.array(e.union(Object.values(J))).max(100)}).strict();export{$ as a,qe as b,Pe as c,He as d,Fe as e,Be as f,bi as g,Ne as h,mt as i,lt as j,ut as k,J as l,Me as m,L as n,S as o,At as p,Lt as q,Ot as r,vi as s,W as t,wi as u,z as v,Qe as w,Ke as x,We as y,Si as z,mn as A,Ri as B,vn as C,Cn as D,jn as E,En as F,Tn as G,Dn as H};
|