openpond 0.2.41 → 0.2.43
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/app-server.d.ts +38 -0
- package/dist/app-server.js +1 -1
- package/dist/chunks/{actions-command-JPJLAR44.js → actions-command-DWQ3VGGP.js} +1 -1
- package/dist/chunks/{app-layer-ENO5MMPX.js → app-layer-OV7RVSQW.js} +1 -1
- package/dist/chunks/app-server-runtime-JVLXE5LF.js +2 -0
- package/dist/chunks/{apps-VFXTNQ25.js → apps-5DQAYDNI.js} +1 -1
- package/dist/chunks/{chunk-RT6YPMWF.js → chunk-3D4QN4NM.js} +1 -1
- package/dist/chunks/chunk-45UOD2DA.js +2 -0
- package/dist/chunks/{chunk-KCENW4ME.js → chunk-5IN3HQJU.js} +1 -1
- package/dist/chunks/{chunk-HLNJKX3S.js → chunk-6KKQXETR.js} +1 -1
- package/dist/chunks/{chunk-VKGVC26K.js → chunk-6UPCR6EL.js} +1 -1
- package/dist/chunks/{chunk-GKP2ZPKM.js → chunk-7EDOA6KD.js} +1 -1
- package/dist/chunks/{chunk-AT6XYNQ5.js → chunk-7KC5LWCU.js} +1 -1
- package/dist/chunks/{chunk-2Z6H32OC.js → chunk-7R7O2XXP.js} +1 -1
- package/dist/chunks/{chunk-LRGLV6JX.js → chunk-B3O2GAQH.js} +1 -1
- package/dist/chunks/{chunk-TPOW52DO.js → chunk-DGD52VZC.js} +1 -1
- package/dist/chunks/{chunk-R6YJY7F2.js → chunk-E6WT4HWF.js} +1 -1
- package/dist/chunks/{chunk-JXGLH7OR.js → chunk-EWQZASG4.js} +126 -126
- package/dist/chunks/{chunk-3FXZW4G7.js → chunk-G2WJC6DE.js} +2 -2
- package/dist/chunks/{chunk-6C5XPL6E.js → chunk-HI7W3IVO.js} +1 -1
- package/dist/chunks/{chunk-PU2JM765.js → chunk-IE2WZ3I3.js} +1 -1
- package/dist/chunks/chunk-IFI24VF6.js +5 -0
- package/dist/chunks/{chunk-POWZXZJ2.js → chunk-KDOS6YMH.js} +1 -1
- package/dist/chunks/{chunk-VQG25QBJ.js → chunk-KPDWQCF6.js} +1 -1
- package/dist/chunks/chunk-KRC2S5QF.js +5 -0
- package/dist/chunks/{chunk-XMXGITQE.js → chunk-LLNCHGE4.js} +1 -1
- package/dist/chunks/{chunk-MOMDY22U.js → chunk-MDE3HHLH.js} +1 -1
- package/dist/chunks/{chunk-AO753YWB.js → chunk-O277DPTX.js} +1 -1
- package/dist/chunks/{chunk-6UGTLC7Z.js → chunk-OJVIH7J6.js} +1 -1
- package/dist/chunks/{chunk-ERFHALGF.js → chunk-P45OSKQL.js} +1 -1
- package/dist/chunks/chunk-ROJX6IYW.js +578 -0
- package/dist/chunks/{chunk-VB2S5HV4.js → chunk-SXN3QOW4.js} +2 -2
- package/dist/chunks/{chunk-JXD5PNF7.js → chunk-T5QA4W2H.js} +1 -1
- package/dist/chunks/{chunk-H7JB25HO.js → chunk-T7MJBBHE.js} +1 -1
- package/dist/chunks/{chunk-DLQW5X6F.js → chunk-V44RF57H.js} +1 -1
- package/dist/chunks/{chunk-NVPKY3KE.js → chunk-VG7XO6PR.js} +7 -7
- package/dist/chunks/chunk-VJJ3UXOI.js +42 -0
- package/dist/chunks/{chunk-JLZ2TEKK.js → chunk-W3NG7YLC.js} +1 -1
- package/dist/chunks/chunk-XMKAMR7M.js +2 -0
- package/dist/chunks/{chunk-MJC26GOX.js → chunk-Z3D4C7BG.js} +6 -6
- package/dist/chunks/cli-7D7CYCIY.js +2 -0
- package/dist/chunks/{configuration-command-VXCGFVAP.js → configuration-command-ANYM5UYG.js} +1 -1
- package/dist/chunks/{core-commands-XEPFY3PQ.js → core-commands-TYWE3TNW.js} +1 -1
- package/dist/chunks/datasets-FM3UBK4R.js +13 -0
- package/dist/chunks/{desktop-test-JGSH4T5Z.js → desktop-test-Z5IKJU3P.js} +1 -1
- package/dist/chunks/dist-GC7DXKTI.js +2 -0
- package/dist/chunks/experiments-IWBRIDQE.js +2 -0
- package/dist/chunks/{extension-S2UIZH46.js → extension-5LQRULQP.js} +1 -1
- package/dist/chunks/{help-ZVAGMF3C.js → help-NTSTG6RR.js} +1 -1
- package/dist/chunks/hosted-harness-runtime-S75BLD57.js +2 -0
- package/dist/chunks/hosted-profile-compiler-JNNYWLC7.js +2 -0
- package/dist/chunks/{hosted-profile-evaluation-control-WPRPL4YW.js → hosted-profile-evaluation-control-IK4Y2EQZ.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-inspection-ULRRZDS2.js → hosted-profile-evaluation-inspection-YWKUB7RT.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-preparation-NWR4PRHS.js → hosted-profile-evaluation-preparation-JXOF73BB.js} +1 -1
- package/dist/chunks/{opchat-EOQ4PPE7.js → opchat-77PRAQ5W.js} +1 -1
- package/dist/chunks/{organizations-4IGFWOYA.js → organizations-2KWTYIPU.js} +1 -1
- package/dist/chunks/{profile-KJS7WQ3F.js → profile-HVLH672B.js} +1 -1
- package/dist/chunks/{project-agent-6WNHPBXA.js → project-agent-7NLKJMAM.js} +1 -1
- package/dist/chunks/{sandbox-command-NCRIL6NH.js → sandbox-command-FNS4JBVC.js} +1 -1
- package/dist/chunks/{sandbox-template-AAOUNWTL.js → sandbox-template-QMB6DSTS.js} +1 -1
- package/dist/chunks/{src-HLLPHEW4.js → src-N447LUPO.js} +1 -1
- package/dist/chunks/src-TZBL6NA7.js +325 -0
- package/dist/chunks/{teams-bot-LKIOF3B5.js → teams-bot-RNHQMPQA.js} +1 -1
- package/dist/chunks/{workspaces-S3NXR6VJ.js → workspaces-V5YTXJLV.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/App-BEQmrTGQ.js +226 -0
- package/dist/web/assets/{AppDialog-CmPsGOzE.js → AppDialog-v-BfV1lA.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-0_Ewf4wJ.js → AppTerminalPanel-CnKcllS2.js} +2 -2
- package/dist/web/assets/{AppsView-Ddn9R2I-.js → AppsView-Dl-37F0w.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-j2Yyiaz-.js → BrowserSidebar-DltF217k.js} +1 -1
- package/dist/web/assets/{CartesianChart-BWAkc0mY.js → CartesianChart-gK-Ll3kX.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-SVc7oX8N.js → CollaborationTabs-BuWquQYn.js} +1 -1
- package/dist/web/assets/{CommandMenu-CcX5ypdX.js → CommandMenu-Cs5S8t-Q.js} +1 -1
- package/dist/web/assets/{CommunityView-B7W1C8KG.js → CommunityView-BJBkQEMV.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-BBKdrbNP.js → ComposerCreateImproveStrip-C36fKc-v.js} +1 -1
- package/dist/web/assets/{GetStartedView-BXuTBT4U.js → GetStartedView-9A49MgYA.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-JgxDUDio.js +1 -0
- package/dist/web/assets/HostedModelLearningSettings-CH7CsAhw.js +1 -0
- package/dist/web/assets/{LabModelVersionDetailPage-CctGBUae.js → LabModelVersionDetailPage-N2qcy1Yv.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-Cl8Sdiqc.js → LabSkillSidebar-BAKym5GY.js} +1 -1
- package/dist/web/assets/LabsRoute-DooCmsN8.css +1 -0
- package/dist/web/assets/LabsRoute-Y992kQoQ.js +52 -0
- package/dist/web/assets/{MainChatThread-BaEeNsrh.js → MainChatThread-CPhREQso.js} +2 -2
- package/dist/web/assets/{MainPane-Dw90VsN-.js → MainPane-gPkr0OWu.js} +14 -14
- package/dist/web/assets/{MarkdownText-CGGUFrZe.js → MarkdownText-B-au2zEv.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-2mgh6WV4.js → NativeSkillSidebar-DHFKZ7P1.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-DMTe3jS9.js → NewExperienceSwitcher-Dhbf5KJT.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-D6pvuCoo.js → NewProjectDialog-hlAzFK2Y.js} +1 -1
- package/dist/web/assets/{OutputsPage-DMeIKxzN.js → OutputsPage-C0N2rOxE.js} +1 -1
- package/dist/web/assets/{ProjectsPage-V5oXwB-5.js → ProjectsPage-CkHBgLPx.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-B0y2XNdm.js → RightChatPanelStack-BiW6ZzPN.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-BksZR71F.js → RightSidebarHomePanel-BS9YSdYB.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-BRcVebWV.js → ScheduledWorkPage-819sQcDR.js} +1 -1
- package/dist/web/assets/{SettingsView-CtI170q1.js → SettingsView-BZrOUPZb.js} +3 -3
- package/dist/web/assets/{TeamChatView-DWGM8eXj.js → TeamChatView-CUNcbSa7.js} +2 -2
- package/dist/web/assets/{TerminalOverlay-DLSmAkbQ.js → TerminalOverlay-MIlGPpXe.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-C6e6zhC8.js → TrainingCreationPanel-BNcyNoa8.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Q1GXOAlQ.js → TrainingDraftPanel-CKV16LNC.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-UET2vS1c.js → UsageSettingsSection-SVgUHnUL.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-DMsXId2s.js → WorkSidebarPanel-CfkaaFHA.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-B_eZE-bq.js → WorkspaceDiffPanel-CQhqlqg5.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-C848cDBP.js → WorkspaceEnvironmentMenu-CJB-z2tS.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-CSnIC26s.js → WorkspaceGitDialogs-B3xtasTt.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-C5dvv9s_.js → WorkspaceMonacoEditor-DVfyICNZ.js} +3 -3
- package/dist/web/assets/{arrow-up-right-CsvQameJ.js → arrow-up-right-CYG4Vm07.js} +1 -1
- package/dist/web/assets/{clipboard-fZsv7_ot.js → clipboard-DGSnfljX.js} +1 -1
- package/dist/web/assets/{cloud-upload-CUXNsLn2.js → cloud-upload-Bw_zrS2y.js} +1 -1
- package/dist/web/assets/{cssMode-1tbsSShK.js → cssMode-CSpYOKj-.js} +1 -1
- package/dist/web/assets/{folder-open-Da8t5AtB.js → folder-open-CcGOldH7.js} +1 -1
- package/dist/web/assets/{folder-plus-X7B8dzc3.js → folder-plus-DEIDaX2B.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CajQIfK5.js → git-commit-horizontal-B-Ao6y--.js} +1 -1
- package/dist/web/assets/{htmlMode-qapgENKW.js → htmlMode-DstkgJXG.js} +1 -1
- package/dist/web/assets/{index-DUQK09vA.js → index-C8_8-lW7.js} +2 -2
- package/dist/web/assets/index-DUIWDN8o.css +1 -0
- package/dist/web/assets/{info-BYfs9_PT.js → info-DwOXHkN_.js} +1 -1
- package/dist/web/assets/{jsonMode-DYPkWxLK.js → jsonMode-txmGM7K6.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-Cbcp__rz.js → lspLanguageFeatures-D59Drc_9.js} +1 -1
- package/dist/web/assets/{minimize-2-Dp7tWjno.js → minimize-2-C5UCV16_.js} +1 -1
- package/dist/web/assets/{monaco.contribution-COP3_DCK.js → monaco.contribution-5HcktwaM.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CcL6YtdZ.js → monaco.contribution-BOmcYK8k.js} +2 -2
- package/dist/web/assets/{monaco.contribution-cIq6c5M4.js → monaco.contribution-BomZ1gys.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DApKEq_e.js → monaco.contribution-CbK7796k.js} +2 -2
- package/dist/web/assets/{monitor-nP1D5S_1.js → monitor-D4hpNTai.js} +1 -1
- package/dist/web/assets/{python-DXYfRGSs.js → python-Cie4Ghu8.js} +1 -1
- package/dist/web/assets/{refresh-cw-D_9Q01ox.js → refresh-cw-CIOzrJnj.js} +1 -1
- package/dist/web/assets/{save-BxG7d5Nm.js → save-D7EtdMHG.js} +1 -1
- package/dist/web/assets/{square--Ua9DQPL.js → square-JpDfrqp_.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-CqAtkn5E.js → toggleHighContrast-DdGkc-Be.js} +1 -1
- package/dist/web/assets/{tsMode-BCdfa4wT.js → tsMode-DwgEL7oI.js} +1 -1
- package/dist/web/assets/{upload-BkYSJcbc.js → upload-BkwOzqS-.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-CGlPbPZr.js → useLocalAgentSchedules-bO0Qycih.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-DtNQyWXl.js → useSessionTurnCache-DxUh5scW.js} +1 -1
- package/dist/web/assets/{wifi-off-DF8YmlRa.js → wifi-off-D6Keejtn.js} +1 -1
- package/dist/web/assets/{workers-BUHY0ojx.js → workers-BgG66q0n.js} +1 -1
- package/dist/web/assets/{yaml-CtBzXx8s.js → yaml-COMRGPWg.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunks/app-server-runtime-LACOVSKH.js +0 -2
- package/dist/chunks/chunk-452UKUIB.js +0 -577
- package/dist/chunks/chunk-FLWIBAHG.js +0 -2
- package/dist/chunks/chunk-KRC36KV2.js +0 -5
- package/dist/chunks/chunk-KVJF3H4N.js +0 -42
- package/dist/chunks/chunk-PKBU37CH.js +0 -5
- package/dist/chunks/chunk-QJX7UASW.js +0 -2
- package/dist/chunks/cli-QW2BELOE.js +0 -2
- package/dist/chunks/datasets-6PTDCZQ7.js +0 -13
- package/dist/chunks/dist-GKCGK44T.js +0 -2
- package/dist/chunks/experiments-WKRYHZDK.js +0 -2
- package/dist/chunks/hosted-harness-runtime-F4UPHTTT.js +0 -2
- package/dist/chunks/hosted-profile-compiler-4LKIBC75.js +0 -2
- package/dist/chunks/src-PERIQ7VT.js +0 -325
- package/dist/web/assets/App-BL1D_PLh.js +0 -226
- package/dist/web/assets/HostedModelLearningReview-C3oAdyoF.js +0 -1
- package/dist/web/assets/HostedModelLearningSettings-9e5z5eRf.js +0 -1
- package/dist/web/assets/LabsRoute-C1FWCoYb.css +0 -1
- package/dist/web/assets/LabsRoute-di9O0XV1.js +0 -32
- package/dist/web/assets/index-lqk3IxE0.css +0 -1
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as Te,c as Pe,e as Z,j as Oe,k as ke,n as Ae,o as _e}from"./chunk-V44RF57H.js";import{F as v,J as Ie}from"./chunk-KRC2S5QF.js";import{i as xe,o as Ce,q as Ee}from"./chunk-7EDOA6KD.js";import{a as X,b as ye,h as Re}from"./chunk-T7MJBBHE.js";import{Cd as O,Fd as L,Gd as ne,I as E,J as re,M as q,N as _,a as j}from"./chunk-6KKQXETR.js";import{X as ge,Y as fe,_ as K,b as ie,ba as he,c as ae,ea as ve,fa as V,ja as we,la as be,ma as Se,p as ue,r as le,s as ce,t as pe,u as de,w as me}from"./chunk-ALZRXBEC.js";import{y as A}from"./chunk-MTJNKRXL.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as se,d as B,f as oe,h as H}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{promises as ee}from"node:fs";import at from"node:os";import ut from"node:path";import{createServer as lt}from"node:http";import{randomBytes as ct}from"node:crypto";var et=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),tt=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(et).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:we,importOnly:o.boolean().optional()})]);function He(n){let e=null;async function t(s,i){let u=H(n).config,l=null,c=null,p=null;try{l=await ae(u),p=await V(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(S){c=B(S,u)}let h=p??(s?null:e);return{path:u,text:l,rawRevision:ie(l),issue:c,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await le(n),clientState:c?null:await be(n)}}a(t,"status");async function r(s){let i=tt.parse(s);return i.action==="validate"?{valid:!0,document:ue(i.text,H(n).config)}:(i.action==="patch"&&await me(n,i.expectedRevision,i.operations),i.action==="replace"&&await ce(n,i.expectedRevision,i.text),i.action==="restore"&&await pe(n,i.revision,i.expectedRevision),i.action==="trust"&&await ve(n,i.root,i.accountId,i.trusted),i.action==="client-state"?Se(n,i.owner,i.patch,i.importOnly):t())}return a(r,"mutate"),{status:t,mutate:r,schema:de}}a(He,"createConfigurationPayloads");import{Buffer as Me}from"node:buffer";var $={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},rt=25*1024*1024,D=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{a(this,"HttpBodyError")}};function Ne(n,e,t={}){for(let[s,i]of Object.entries($))e.setHeader(s,i);let r=Be(n.headers.origin);return r?(e.setHeader("Vary",it(e.getHeader("Vary"))),nt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}a(Ne,"applyCorsHeaders");function nt(n,e={}){if(n==="null")return!0;let t=Ue(n);return t?ot(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Ue(s):null).filter(s=>!!s)).has(t):!1}a(nt,"isAllowedCorsOrigin");function I(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...$}),n.end(JSON.stringify(t))}a(I,"sendJson");function jt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...$}),n.end(t)}a(jt,"sendText");function Lt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...$}),n.end(t)}a(Lt,"sendBinary");async function Q(n,e={}){let t=e.maxBytes??rt,r=Be(n.headers["content-type"]),s=[],i=0;for await(let l of n){let c=Me.from(l);if(i+=c.byteLength,i>t)throw new D(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(c)}let u=Me.concat(s).toString("utf8").trim();if(!u)return{};if(!st(r))throw new D(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(u)}catch{throw new D(400,"invalid_json","Request body is not valid JSON.")}}a(Q,"readJson");function qe(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}a(qe,"hasAuth");function Be(n){return Array.isArray(n)?n[0]??null:n??null}a(Be,"headerValue");function st(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}a(st,"isJsonContentType");function Ue(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}a(Ue,"normalizeOrigin");function ot(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}a(ot,"isLoopbackOrigin");function it(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}a(it,"appendVaryOrigin");function De(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
|
+
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
|
+
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
|
+
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
6
|
+
<details id="editor"><summary>Edit configuration</summary><textarea id="text" aria-label="Configuration TOML" spellcheck="false"></textarea><button id="save">Validate and save</button><button id="reload">Reload file</button><select id="revisions" aria-label="Restore a verified configuration revision"><option value="">Restore a verified revision\u2026</option></select></details>
|
|
7
|
+
<details><summary>Migration sources and diagnostics</summary><pre id="migration"></pre><label>Previous app home <input id="appHome"></label><label>Previous account config <input id="configSource"></label><label>Configuration conflict choices (JSON from the preview) <textarea id="resolutions" aria-label="Migration conflict choices" spellcheck="false" placeholder='[{"path":["chat","steer_active_responses"],"choice":"existing"}]'></textarea></label><button id="preview">Preview migration</button><button id="migrate">Use these sources</button><button id="restart">Restart failed preparation</button><button id="diagnostics">Export diagnostics</button></details>
|
|
8
|
+
<button id="retry">Retry startup</button><p id="message" role="status"></p>
|
|
9
|
+
<script nonce="${n}">
|
|
10
|
+
let token='',state=null,editing=false,revision=null;
|
|
11
|
+
const el=id=>document.getElementById(id);
|
|
12
|
+
async function request(route,body){const r=await fetch(route,{method:body?'POST':'GET',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:body?JSON.stringify(body):undefined});const v=await r.json();if(!r.ok)throw Error(v.error||'Recovery request failed');return v;}
|
|
13
|
+
function message(error){el('message').textContent=error instanceof Error?error.message:String(error);}
|
|
14
|
+
async function load(){state=await request('/v1/recovery');el('issue').textContent=state.issue.message;el('action').textContent=state.issue.action;el('file').textContent=state.issue.path;el('migration').textContent=JSON.stringify(state.migration,null,2);if(!editing){el('text').value=state.config.text||'schema_version = 1\\n';revision=state.config.rawRevision;}el('revisions').replaceChildren(new Option('Restore a verified revision\u2026',''),...state.config.recoverableRevisions.map(r=>new Option(r.createdAt,r.revision)));el('editor').hidden=!state.configEditable;}
|
|
15
|
+
el('text').oninput=()=>{editing=true};
|
|
16
|
+
el('reload').onclick=()=>{editing=false;load().catch(message)};
|
|
17
|
+
el('save').onclick=async()=>{try{await request('/v1/configuration',{action:'replace',text:el('text').value,expectedRevision:revision});editing=false;await load();message('Configuration saved. Retry startup when ready.')}catch(e){message(e)}};
|
|
18
|
+
el('revisions').onchange=async e=>{if(!e.target.value)return;try{await request('/v1/configuration',{action:'restore',revision:e.target.value,expectedRevision:state.config.rawRevision});editing=false;await load();message('Verified revision restored.')}catch(e){message(e)}};
|
|
19
|
+
for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart','restart']])el(id).onclick=async()=>{try{const result=await request('/v1/recovery',{action,sourceAppHome:el('appHome').value||undefined,sourceConfig:el('configSource').value||undefined,resolutions:el('resolutions').value?JSON.parse(el('resolutions').value):undefined});el('migration').textContent=JSON.stringify(result,null,2);message(action==='preview'?'Review the source paths above.':'Migration operation completed; retry startup.')}catch(e){message(e)}};
|
|
20
|
+
el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
|
|
21
|
+
el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
|
|
22
|
+
(async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
|
|
23
|
+
</script></html>`}a(De,"startupRecoveryPage");var pt=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:ge.optional()});function Fe(n){return n instanceof se&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}a(Fe,"isRecoverableStartupError");async function je(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await ee.mkdtemp(ut.join(at.tmpdir(),"openpond-recovery-")):n;return Te(s,async()=>{let{token:i,tokenFile:u}=await Oe(s),l=He(n),c=t.issue,p,h=new Promise(w=>{p=w}),S=lt((w,g)=>{(async()=>{let b=new URL(w.url??"/","http://127.0.0.1");if(!Ne(w,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(w.method==="OPTIONS"){I(g,204,{});return}if(w.method==="GET"&&b.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:ye,recovery:!0});return}if(w.method==="GET"&&b.pathname==="/"){let f=ct(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${f}'; style-src 'nonce-${f}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(De(f));return}if(!qe(w,b,i)){I(g,401,{error:"Unauthorized"});return}let U=!r;if(w.method==="GET"&&b.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:U,config:r?{path:H(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await fe(n).catch(f=>({issue:B(f,n)}))});return}if(w.method==="POST"&&b.pathname==="/v1/configuration"&&U){I(g,200,await l.mutate(await Q(w)));return}if(w.method==="POST"&&b.pathname==="/v1/recovery"){let f=pt.parse(await Q(w));if(r&&f.action!=="retry"&&f.action!=="preview")throw t;if(f.action==="restart"){I(g,200,await he(n));return}if(f.action==="preview"||f.action==="migrate"){I(g,200,await K(n,{sourceAppHome:f.sourceAppHome,sourceConfig:f.sourceConfig,resolutions:f.resolutions,dryRun:f.action==="preview"}));return}await K(n),await V(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(b=>{c=B(b,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((w,g)=>{S.once("error",g),S.listen(e,"127.0.0.1",()=>{S.off("error",g),w()})});let P=S.address().port,k=`http://127.0.0.1:${P}`;return await Pe(s,k,"startup-recovery"),{url:k,port:P,token:i,tokenFile:u,storePath:H(n).database,repaired:h,close:a(async()=>{S.closeIdleConnections(),await new Promise((w,g)=>S.close(b=>b?g(b):w())),r&&await ee.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await ee.rm(s,{recursive:!0,force:!0}),i})}a(je,"startRecoveryServer");import{createHash as Et}from"node:crypto";import{createHash as dt,randomUUID as Le}from"node:crypto";var mt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),gt=o.object({entries:o.array(E).max(200),nextBefore:mt.nullable()}).strict(),ft=o.object({run:E,replayed:o.boolean()}).strict(),W=class{constructor(e){this.client=e}client;static{a(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:Le(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:E.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let u=gt.parse(await this.client.request({contractVersion:v,requestId:Le(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&u.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...u.entries),!u.nextBefore)break;if(u.entries.length===0||i&&(u.nextBefore.updatedAt>i.updatedAt||u.nextBefore.updatedAt===i.updatedAt&&u.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=u.nextBefore}return s}async upsertCreateImproveRun(e){let t=E.parse(e),r=`create-improve:${dt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return E.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=re.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=E.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return ft.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as vt}from"node:crypto";async function F(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}a(F,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}a(ht,"isOversizeResponse");var wt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:j})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),G=class{constructor(e){this.client=e}client;static{a(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],u=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:u,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=u)throw new Error("Host event cursor did not advance.");if(u=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=j.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:j}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],u=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await F(c,async h=>wt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${vt()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(u=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:u,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Ve=o.object({revision:o.number().int().min(1),session:q}).strict(),$e=o.object({revision:o.number().int().min(1),turn:_}).strict(),bt=o.object({sessions:o.array(q).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),St=o.object({turns:o.array(_).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),J=class{constructor(e){this.client=e}client;static{a(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Ve.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await F(Math.min(10,1001-e.length),async s=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=q.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=q.parse(e.session);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:$e.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let u=await F(Math.min(200,r-s.length),async l=>St.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...u.turns),u.nextBeforeSortIndex===null)break;if(i!==null&&u.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=u.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:_.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=_.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=_.parse(e.turn);return $e.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as yt,randomUUID as Rt}from"node:crypto";var x=o.object({ok:o.literal(!0)}).strict(),z=o.array(O),It=o.array(o.string()),Tt=o.object({turnId:o.string(),run:A}).strict(),Pt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(L).max(10),hasMore:o.boolean()}).strict(),Ct=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function Y(n,e){return`inbox:${n}:${yt("sha256").update(JSON.stringify(e)).digest("hex")}`}a(Y,"retryKey");var M=class{constructor(e){this.client=e}client;static{a(this,"HostedTaskInboxStorage")}async call(e,t,r=Rt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Pt);for(let u of i.inputs){if(u.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=u.sequence,r.push(u),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},ne),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},x)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},It)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},z)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},x)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let u=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:u}},z);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<u)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,Y("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},x,Y("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},x)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},x)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},z,Y("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},x)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},z)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},x)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),Y("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Ct);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},L)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},L)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},xt);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},x)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(Tt).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},x)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:A.parse(e)},A)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},A.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let u=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(A).max(10));for(let l of u){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(u.length<10)break}return r.sort((u,l)=>(l.updatedAt??l.createdAt).localeCompare(u.updatedAt??u.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var te=class extends M{static{a(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new J(e),this.events=new G(e),this.approvals=new Ae(e),this.usage=new _e(e),this.createImprove=new W(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}async runtimeEventsForTurn(e,t){let r=await this.getTurn(e);if(!r)return[];let s=(await this.events.runtimeEventsForSession(r.sessionId)).filter(i=>i.turnId===e&&(!t?.names||t.names.includes(i.name)));return t?.limit==null?s:s.slice(0,Math.max(0,t.limit))}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Et("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function We(n){return new te(n)}a(We,"createHostedRuntimeCoreStorage");function Ge(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return a(async function*(u){if(u.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*xe({...u,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}a(Ge,"createHostedModelStreamFromEnvironment");import{existsSync as Ot}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Je=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}a(R,"requireValue");function ze(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}a(ze,"parsePort");function Xe(n){let e="serve",t=X,r=17874,s=null,i=!1,u=!1,l=null,c,p=!1,h,S=null,P=null,k=null,w=null,g,b="sqlite_bundle",U=0,f=n[0];if(f&&!f.startsWith("-")){if(f==="serve"||f==="server")e="serve";else if(f==="app-server")e="app-server";else if(f==="web")e="web";else{if(f==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:b,help:!0};throw new Error(`Unknown command: ${f}`)}U=1}for(let m=U;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:b,help:!0};if(d==="--listen"){let C=Re(R(n,m,d));t=C.host,r=ze(String(C.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=ze(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")h=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--experiment-owner")p=!0;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");b="hosted_postgres",m+=1}else if(d==="--profile-source-root")S=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")P=R(n,m,d),m+=1;else if(d==="--profile-id")k=R(n,m,d),m+=1;else if(d==="--profile-revision")w=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(g)throw new Error("Duplicate hosted Profile release descriptor.");let C=R(n,m,d);if(C.length>16e3||!/^[A-Za-z0-9_-]+$/.test(C))throw new Error("Invalid hosted Profile release descriptor.");try{g=ke.parse(JSON.parse(Buffer.from(C,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")u=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&u)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||u))throw new Error("Browser options are only available in web mode.");let N=[S,P,k,w].filter(Boolean).length;if(N&&(N!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(b==="hosted_postgres"&&(e!=="app-server"||l||N))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(g&&b!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&b!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");if(p&&(e!=="app-server"||b!=="sqlite_bundle"||N||!l))throw new Error("Experiment owner mode requires an isolated app-server home without Profile selection.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:b,sourceBrowserState:h,...N?{profileSource:{repoPath:S,repositoryId:P,profileId:k,sourceRevision:w}}:{},...g?{admittedProfileRelease:g}:{},...c?{hostedCacheHome:c}:{},...p?{experimentOwner:!0}:{},help:!1}}a(Xe,"parseCliArgs");function At(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Je,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Je,"../web")].filter(n=>!!n)}a(At,"defaultWebRootCandidates");function _t(n){let e=n?[n]:At();for(let t of e){let r=T.resolve(t);if(Ot(T.join(r,"index.html")))return r}return null}a(_t,"resolveWebRoot");function Ht(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}a(Ht,"formatHostForUrl");function Mt(n){return`http://${Ht(n.status.host)}:${n.status.port}`}a(Mt,"browserBaseUrl");function Ut(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}a(Ut,"tokenizedWebUrl");async function Ye(n,e=Ee){let t=Ut(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}a(Ye,"resolveWebLaunchMessages");function Ze(){console.log(`Usage:
|
|
24
|
+
openpond-app-server serve [--hostname HOST] [--port PORT]
|
|
25
|
+
openpond-app-server app-server [--home DIR]
|
|
26
|
+
openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
--listen HOST:PORT Set host and port together
|
|
30
|
+
--hostname HOST Bind host (default ${X})
|
|
31
|
+
--port PORT Bind port, or 0 for any free port (default ${17874})
|
|
32
|
+
--web-root DIR Directory containing the built web UI for web mode
|
|
33
|
+
--home DIR Local app-server state directory
|
|
34
|
+
--runtime-storage hosted-postgres Host-admitted Postgres app-server mode
|
|
35
|
+
--hosted-profile-release BASE64URL Host-admitted immutable Profile release descriptor
|
|
36
|
+
--profile-source-root DIR Authorized Profile repository source for app-server
|
|
37
|
+
--profile-repository-id ID Source repository identity supplied by the host
|
|
38
|
+
--profile-id ID Profile within that source
|
|
39
|
+
--profile-revision REV Accepted immutable source revision
|
|
40
|
+
--open-browser Open the authenticated web URL in the system browser
|
|
41
|
+
--print-access-url Print the authenticated URL instead of opening it
|
|
42
|
+
`)}a(Ze,"printHelp");async function un(n){let e=Xe(process.argv.slice(2));if(e.help){Ze();return}let t=e.mode==="web"?_t(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await Qe(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome,e.experimentOwner);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(c){if(!Fe(c))throw c;let p=await je(oe({home:e.storeDir??void 0}),s,c);s=p.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:p.url,tokenFile:p.tokenFile,storePath:p.storePath})}`),console.error(`${c.issue.code}: ${c.issue.message} ${c.issue.action}`);let h=await Ye({baseUrl:p.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:p.token});for(let P of h.stdout)console.log(P);for(let P of h.stderr)console.error(P);let S=a(()=>{p.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",S),process.once("SIGTERM",S);try{await p.repaired}finally{process.off("SIGINT",S),process.off("SIGTERM",S),await p.close()}}let i=e.mode==="web"?Mt(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:Ce()})}`),i){let c=await Ye({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let p of c.stderr)console.error(p);for(let p of c.stdout)console.log(p)}else console.log(`OpenPond API server: ${r.url}`);let u=!1,l=a(async()=>{u||(u=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{l()}),process.on("SIGTERM",()=>{l()}),await new Promise(()=>{})}a(un,"runOpenPondServerCli");async function ln(n){let e=process.argv.slice(2),t=Xe(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){Ze();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await Qe(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease,t.hostedCacheHome,t.experimentOwner)}a(ln,"runOpenPondAppServerCli");async function Qe(n,e,t,r="sqlite_bundle",s,i,u=!1){let l=new Ie;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await Z({appServer:a(()=>n({...i?{storeDir:i}:{},hostStorageClient:l,runtimeStorage:{kind:"hosted_postgres",client:l,core:We(l),inbox:new M(l),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:Ge()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:l});return}e&&(process.env.OPENPOND_HOME=e);let c=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},...u?{experimentPolicyClient:l,services:{webSearch:!1,scheduling:!1,connectedApps:!1,tasksets:!1,projectActions:!1,profileActions:!1,backgroundReview:!1}}:{},hostStorageClient:l});await Z({appServer:c,readable:process.stdin,writable:process.stdout,hostStorageClient:l})}a(Qe,"runAgentServer");export{He as a,D as b,Ne as c,I as d,jt as e,Lt as f,Q as g,qe as h,Ye as i,un as j,ln as k};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{$b as $,Lb as z,Nb as P,Qb as x,Tb as G,Wb as N,Xb as J,Yb as U,Zb as W}from"./chunk-NVPKY3KE.js";import{G as M,I as B,e as C,f as O,fa as L,g as F,q as V}from"./chunk-TPOW52DO.js";import{j as E,k as H,l as h}from"./chunk-HZP5U2AA.js";import{a as l}from"./chunk-FTQLQJQV.js";import{constants as Q}from"node:fs";import{lstat as ie,open as ce,readdir as le}from"node:fs/promises";import A from"node:path";import{createHash as q}from"node:crypto";import{mkdir as K,readdir as ae,readFile as I,writeFile as X}from"node:fs/promises";import d from"node:path";async function je(e,t){let a=x.parse(e),r=["tasks","assets","environment","graders","rubrics","comparisons","metrics","fixtures"];await Promise.all(r.map(g=>K(d.join(t,g),{recursive:!0})));let o=await re(a,t);if(a.metrics.customAggregator){let g=d.join(t,a.metrics.customAggregator.module),k=q("sha256").update(await I(g)).digest("hex");a=x.parse({...a,metrics:{...a.metrics,customAggregator:{...a.metrics.customAggregator,contentHash:k}}})}let n=d.join(t,"taskset.json"),s=d.join(t,"tasks","tasks.jsonl"),f=d.join(t,"graders","graders.json"),i=d.join(t,"fixtures","grader-fixtures.json"),u=d.join(t,"metrics","policy.json"),c=d.join(t,"assets","manifest.json"),m=d.join(t,"environment","contract.json"),w=d.join(t,"rubrics","preference-review.md"),v=d.join(t,"comparisons","policy.json");return await Promise.all([...J(a)].map(([g,k])=>X(d.join(t,g),k,"utf8"))),{directory:t,files:[n,s,c,m,f,w,v,u,i,...o],draft:a}}l(je,"writeTasksetDraftPackage");async function Re(e){let t=await se(e),a=q("sha256");for(let r of t)a.update(d.relative(e,r).replaceAll(d.sep,"/")),a.update("\0"),a.update(await I(r)),a.update("\0");return a.digest("hex")}l(Re,"hashTasksetDraftPackage");async function Y(e,t){let a=d.basename(e)==="taskset.json"?e:d.join(e,"taskset.json"),r=d.dirname(a),o=l(async f=>{if(!t)return I(f,"utf8");let i=t.get(d.relative(r,f).replaceAll(d.sep,"/"));if(!i)throw Object.assign(new Error("Authored file is absent."),{code:"ENOENT"});return new TextDecoder("utf-8",{fatal:!0}).decode(i)},"read"),n=JSON.parse(await o(a)),s=x.safeParse(n);if(s.success){let[f,i,u,c,m,w]=await Promise.all([ne(d.join(r,"tasks","tasks.jsonl"),o),S(d.join(r,"graders","graders.json"),o),S(d.join(r,"fixtures","grader-fixtures.json"),o),S(d.join(r,"metrics","policy.json"),o),S(d.join(r,"environment","contract.json"),o),S(d.join(r,"comparisons","policy.json"),o)]);return x.parse({...s.data,...f===null?{}:{tasks:f},...i===null?{}:{graders:i},...u===null?{}:{graderFixtures:u},...c===null?{}:{metrics:c},...m===null?{}:{environment:m},...w===null?{}:{review:w}})}return $(n)}l(Y,"readTasksetDraftPackage");async function re(e,t){let a=N(e),r=[];for(let o of a){let n=d.join(t,o.relativePath);await K(d.dirname(n),{recursive:!0});try{await X(n,o.source,{encoding:"utf8",flag:"wx"})}catch(s){if(!oe(s))throw s}r.push(n)}return r}l(re,"writeConfiguredStarterCode");async function se(e){let t=[];async function a(r){let o=await ae(r,{withFileTypes:!0});o.sort((n,s)=>n.name.localeCompare(s.name));for(let n of o){let s=d.join(r,n.name);if(n.isSymbolicLink())throw new Error(`Taskset workspaces cannot contain symbolic links: ${s}`);n.isDirectory()?await a(s):n.isFile()&&t.push(s)}}return l(a,"visit"),await a(e),t}l(se,"packageFiles");async function S(e,t=a=>I(a,"utf8")){try{return JSON.parse(await t(e))}catch(a){if(Z(a))return null;throw a}}l(S,"readOptionalJson");async function ne(e,t=a=>I(a,"utf8")){try{return(await t(e)).split(/\r?\n/).map(r=>r.trim()).filter(Boolean).map(r=>JSON.parse(r))}catch(a){if(Z(a))return null;throw a}}l(ne,"readOptionalJsonLines");function Z(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}l(Z,"isMissingFile");function oe(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}l(oe,"isFileExists");async function Oe(e){let t=A.resolve(e.directory);if(!(await ie(t)).isDirectory())throw new Error("Dataset upload requires a regular authored folder.");let a=new Map,r=0;async function o(c,m){if(m>30)throw new Error("Dataset folder nesting exceeds 30 levels.");for(let w of(await le(c,{withFileTypes:!0})).sort((v,g)=>v.name<g.name?-1:v.name>g.name?1:0)){if(w.name.startsWith("."))throw new Error("Dataset folders cannot include hidden files or directories.");if(w.isSymbolicLink()||!w.isDirectory()&&!w.isFile())throw new Error("Dataset folders can contain only regular files and directories.");let v=A.join(c,w.name);if(w.isDirectory()){await o(v,m+1);continue}if(a.size>=1e4)throw new Error("Dataset folder exceeds 10,000 files.");let g=await ce(v,Q.O_RDONLY|Q.O_NOFOLLOW);try{let k=await g.stat();if(!k.isFile()||k.size>U-r)throw new Error("Dataset folder exceeds the 64 MiB capture limit.");let j=new Uint8Array(k.size),R=0;for(;R<j.length;){let D=await g.read(j,R,j.length-R,R);if(!D.bytesRead)throw new Error("Dataset file changed during capture.");R+=D.bytesRead}let _=await g.stat();if(_.size!==k.size||_.mtimeMs!==k.mtimeMs||_.ctimeMs!==k.ctimeMs)throw new Error("Dataset file changed during capture.");r+=j.length,a.set(A.relative(t,v).replaceAll(A.sep,"/"),j)}finally{await g.close()}}}l(o,"visit"),await o(t,0);let n=await Y(t,a),s=[...a].map(([c,m])=>({path:c,contentHash:H(m),sizeBytes:m.byteLength})),f=h(s),i=x.parse({...n,id:e.datasetId??n.id,profileId:e.teamId,revision:e.expectedRevision+1,modelScope:null,status:"draft",publishedTasksetRef:null,metadata:{...n.metadata,importedTasksetPackage:{packageHash:f}}});return{workspace:W({schemaVersion:"openpond.tasksetDraftWorkspace.v1",draft:i,files:[...a].filter(([c])=>!G(c)).map(([c,m])=>({path:c,base64:Buffer.from(m).toString("base64"),contentHash:H(m),sizeBytes:m.byteLength}))}),sourceHash:f,sourceFiles:s,capturedBytes:r}}l(Oe,"captureTasksetDraftWorkspace");async function ee(e){let{binding:t,rewards:a}=e.learning,r=M(t,a);if(e.graders.length!==r.length||r.some(({source:i,reward:u})=>!e.graders.some(c=>c.id===i.graderId&&c.version===String(u.revision)&&h(c.metadata.rewardBinding)===h(L(t)))))throw new Error("Prepared Taskset graders do not match their immutable Reward binding.");let o=V.parse({id:e.task.id,clusterKey:e.task.clusterKey,split:e.task.split,input:e.task.input,expectedOutput:e.task.expectedOutput,policyVisibleContext:e.task.policyVisibleContext,privilegedContextRef:e.task.privilegedContextRef,artifactRefs:[],tags:e.task.tags}),n=await B({binding:t,rewards:a,task:o,signal:e.signal,evidence:{output:e.attempt.output,artifactRefs:e.attempt.artifactRefs,runtimeEventRefs:e.attempt.runtimeEventRefs,infrastructureError:e.attempt.infrastructureError},customVerifier:e.customVerifier?async({grader:i})=>{let u=e.graders.find(m=>m.id===i.id);if(u?.kind!=="custom_verifier")throw new Error("Bound verifier projection is missing.");let c=await e.customVerifier({grader:u,task:e.task,attempt:e.attempt,signal:e.signal});return{score:c.score,passed:c.passed,rewardEligible:i.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs??[]}}:void 0,modelJudge:e.modelJudge?async({grader:i})=>{let u=e.graders.find(m=>m.id===i.id);if(u?.kind!=="model_judge")throw new Error("Bound judge projection is missing.");let c=await e.modelJudge({grader:u,task:e.task,attempt:e.attempt});return{score:c.score,passed:c.passed,rewardEligible:i.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs??[]}}:void 0}),s=n.training.status==="not_configured"?n.evaluation:n.training,f=h(e.graders);return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${h([e.attempt.id,n.contentHash]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:f,score:s.score,passed:s.passed===!0,components:n.results.map(i=>{let u=t.sources.find(m=>m.graderId===i.graderId),c=e.graders.find(m=>m.id===i.graderId);return{graderId:i.graderId,graderVersion:c.version,score:i.normalizedScore,passed:i.passed===!0,hardGate:u.hardGate,rewardEligible:u.role==="training"&&i.status==="scored",feedback:i.message?.trim()||null,evidenceRefs:i.evidenceHashes,judge:c.kind==="model_judge"?c.judge:null,calibrationStatus:c.kind==="model_judge"?c.calibrationStatus:"not_applicable"}}),failureClass:e.attempt.infrastructureError?"infrastructure_failure":s.status!=="scored"?"grader_failure":s.passed?null:"policy_failure",feedback:n.results.flatMap(i=>i.message?.trim()?[i.message.trim()]:[]),rewardEligible:n.training.status==="scored",rewardComposition:n,createdAt:e.now?.()??new Date().toISOString()}}l(ee,"gradeLearningBatchAttempt");async function at(e){if(e.learning)return ee({...e,learning:e.learning});if(e.graders.some(o=>o.metadata.rewardBinding!==void 0))throw new Error("This Taskset requires its immutable public Reward binding to grade an attempt.");let t=h(e.graders),a=[];for(let o of e.graders)e.signal?.throwIfAborted(),a.push(e.attempt.infrastructureError?b(o,null,!1,"Infrastructure failure; no reward was produced.",[],!1):await me(o,e.task,e.attempt,e.modelJudge,e.customVerifier,e.signal));let r=F({graders:e.graders,infrastructureError:e.attempt.infrastructureError,components:a.map(o=>({...o,failureClass:o.score===null?"grader_failure":o.passed?null:"policy_failure"}))});return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${h([e.attempt.id,t,a]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:t,score:r.score,passed:r.passed,components:a,failureClass:r.failureClass,feedback:e.attempt.infrastructureError?[e.attempt.infrastructureError]:a.flatMap(o=>o.feedback?[o.feedback]:[]),rewardEligible:r.rewardEligible,createdAt:e.now?.()??new Date().toISOString()}}l(at,"gradeAttempt");async function me(e,t,a,r,o,n){if(e.kind==="model_judge"){if(!r)return b(e,null,!1,"Model judge runner is unavailable.",[],!1);if(e.calibrationStatus!=="passed")return b(e,null,!1,"Model judge calibration has not passed.",[],!1);let f=await r({grader:e,task:t,attempt:a});return b(e,f.score,f.passed,f.feedback,f.evidenceRefs??[])}if(e.kind==="human")return b(e,null,!1,"Human review is pending.",[],!1);if(e.kind==="custom_verifier"){if(!o)return b(e,null,!1,"Sandboxed verifier runner is unavailable.",[],!1);let f=await o({grader:e,task:t,attempt:a,signal:n});return b(e,f.score,f.passed,f.feedback,f.evidenceRefs??[])}let s=C({grader:O(e),task:t,evidence:a});return b(e,s.score,s.passed,s.feedback,[...a.artifactRefs,...a.runtimeEventRefs])}l(me,"runGrader");function b(e,t,a,r,o,n=e.rewardEligible){let s=t!==null&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null;return{graderId:e.id,graderVersion:e.version,score:s,passed:s!==null&&a,hardGate:e.hardGate,rewardEligible:s!==null&&n,feedback:r,evidenceRefs:o,judge:e.kind==="model_judge"?e.judge:null,calibrationStatus:e.kind==="model_judge"?e.calibrationStatus:"not_applicable"}}l(b,"component");import{access as ue,mkdir as T,readFile as Vt,writeFile as y}from"node:fs/promises";import p from"node:path";async function Gt(e,t,a={}){let r=z.parse(e),o=P(r);if(!o.valid)throw new Error(o.issues.map(s=>`${s.code}: ${s.message}`).join(`
|
|
2
|
+
import{$b as W,Mb as z,Ob as P,Rb as x,Ub as G,Xb as N,Yb as J,Zb as U,gc as $}from"./chunk-VG7XO6PR.js";import{G as M,I as B,e as C,f as O,fa as L,g as F,q as V}from"./chunk-DGD52VZC.js";import{j as E,k as H,l as h}from"./chunk-HZP5U2AA.js";import{a as l}from"./chunk-FTQLQJQV.js";import{constants as Q}from"node:fs";import{lstat as ie,open as ce,readdir as le}from"node:fs/promises";import A from"node:path";import{createHash as q}from"node:crypto";import{mkdir as K,readdir as ae,readFile as I,writeFile as X}from"node:fs/promises";import d from"node:path";async function je(e,t){let a=x.parse(e),r=["tasks","assets","environment","graders","rubrics","comparisons","metrics","fixtures"];await Promise.all(r.map(g=>K(d.join(t,g),{recursive:!0})));let o=await re(a,t);if(a.metrics.customAggregator){let g=d.join(t,a.metrics.customAggregator.module),k=q("sha256").update(await I(g)).digest("hex");a=x.parse({...a,metrics:{...a.metrics,customAggregator:{...a.metrics.customAggregator,contentHash:k}}})}let n=d.join(t,"taskset.json"),s=d.join(t,"tasks","tasks.jsonl"),f=d.join(t,"graders","graders.json"),i=d.join(t,"fixtures","grader-fixtures.json"),u=d.join(t,"metrics","policy.json"),c=d.join(t,"assets","manifest.json"),m=d.join(t,"environment","contract.json"),w=d.join(t,"rubrics","preference-review.md"),v=d.join(t,"comparisons","policy.json");return await Promise.all([...J(a)].map(([g,k])=>X(d.join(t,g),k,"utf8"))),{directory:t,files:[n,s,c,m,f,w,v,u,i,...o],draft:a}}l(je,"writeTasksetDraftPackage");async function Re(e){let t=await se(e),a=q("sha256");for(let r of t)a.update(d.relative(e,r).replaceAll(d.sep,"/")),a.update("\0"),a.update(await I(r)),a.update("\0");return a.digest("hex")}l(Re,"hashTasksetDraftPackage");async function Y(e,t){let a=d.basename(e)==="taskset.json"?e:d.join(e,"taskset.json"),r=d.dirname(a),o=l(async f=>{if(!t)return I(f,"utf8");let i=t.get(d.relative(r,f).replaceAll(d.sep,"/"));if(!i)throw Object.assign(new Error("Authored file is absent."),{code:"ENOENT"});return new TextDecoder("utf-8",{fatal:!0}).decode(i)},"read"),n=JSON.parse(await o(a)),s=x.safeParse(n);if(s.success){let[f,i,u,c,m,w]=await Promise.all([ne(d.join(r,"tasks","tasks.jsonl"),o),S(d.join(r,"graders","graders.json"),o),S(d.join(r,"fixtures","grader-fixtures.json"),o),S(d.join(r,"metrics","policy.json"),o),S(d.join(r,"environment","contract.json"),o),S(d.join(r,"comparisons","policy.json"),o)]);return x.parse({...s.data,...f===null?{}:{tasks:f},...i===null?{}:{graders:i},...u===null?{}:{graderFixtures:u},...c===null?{}:{metrics:c},...m===null?{}:{environment:m},...w===null?{}:{review:w}})}return $(n)}l(Y,"readTasksetDraftPackage");async function re(e,t){let a=N(e),r=[];for(let o of a){let n=d.join(t,o.relativePath);await K(d.dirname(n),{recursive:!0});try{await X(n,o.source,{encoding:"utf8",flag:"wx"})}catch(s){if(!oe(s))throw s}r.push(n)}return r}l(re,"writeConfiguredStarterCode");async function se(e){let t=[];async function a(r){let o=await ae(r,{withFileTypes:!0});o.sort((n,s)=>n.name.localeCompare(s.name));for(let n of o){let s=d.join(r,n.name);if(n.isSymbolicLink())throw new Error(`Taskset workspaces cannot contain symbolic links: ${s}`);n.isDirectory()?await a(s):n.isFile()&&t.push(s)}}return l(a,"visit"),await a(e),t}l(se,"packageFiles");async function S(e,t=a=>I(a,"utf8")){try{return JSON.parse(await t(e))}catch(a){if(Z(a))return null;throw a}}l(S,"readOptionalJson");async function ne(e,t=a=>I(a,"utf8")){try{return(await t(e)).split(/\r?\n/).map(r=>r.trim()).filter(Boolean).map(r=>JSON.parse(r))}catch(a){if(Z(a))return null;throw a}}l(ne,"readOptionalJsonLines");function Z(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}l(Z,"isMissingFile");function oe(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}l(oe,"isFileExists");async function Oe(e){let t=A.resolve(e.directory);if(!(await ie(t)).isDirectory())throw new Error("Dataset upload requires a regular authored folder.");let a=new Map,r=0;async function o(c,m){if(m>30)throw new Error("Dataset folder nesting exceeds 30 levels.");for(let w of(await le(c,{withFileTypes:!0})).sort((v,g)=>v.name<g.name?-1:v.name>g.name?1:0)){if(w.name.startsWith("."))throw new Error("Dataset folders cannot include hidden files or directories.");if(w.isSymbolicLink()||!w.isDirectory()&&!w.isFile())throw new Error("Dataset folders can contain only regular files and directories.");let v=A.join(c,w.name);if(w.isDirectory()){await o(v,m+1);continue}if(a.size>=1e4)throw new Error("Dataset folder exceeds 10,000 files.");let g=await ce(v,Q.O_RDONLY|Q.O_NOFOLLOW);try{let k=await g.stat();if(!k.isFile()||k.size>U-r)throw new Error("Dataset folder exceeds the 64 MiB capture limit.");let j=new Uint8Array(k.size),R=0;for(;R<j.length;){let D=await g.read(j,R,j.length-R,R);if(!D.bytesRead)throw new Error("Dataset file changed during capture.");R+=D.bytesRead}let _=await g.stat();if(_.size!==k.size||_.mtimeMs!==k.mtimeMs||_.ctimeMs!==k.ctimeMs)throw new Error("Dataset file changed during capture.");r+=j.length,a.set(A.relative(t,v).replaceAll(A.sep,"/"),j)}finally{await g.close()}}}l(o,"visit"),await o(t,0);let n=await Y(t,a),s=[...a].map(([c,m])=>({path:c,contentHash:H(m),sizeBytes:m.byteLength})),f=h(s),i=x.parse({...n,id:e.datasetId??n.id,profileId:e.teamId,revision:e.expectedRevision+1,modelScope:null,status:"draft",publishedTasksetRef:null,metadata:{...n.metadata,importedTasksetPackage:{packageHash:f}}});return{workspace:W({schemaVersion:"openpond.tasksetDraftWorkspace.v1",draft:i,files:[...a].filter(([c])=>!G(c)).map(([c,m])=>({path:c,base64:Buffer.from(m).toString("base64"),contentHash:H(m),sizeBytes:m.byteLength}))}),sourceHash:f,sourceFiles:s,capturedBytes:r}}l(Oe,"captureTasksetDraftWorkspace");async function ee(e){let{binding:t,rewards:a}=e.learning,r=M(t,a);if(e.graders.length!==r.length||r.some(({source:i,reward:u})=>!e.graders.some(c=>c.id===i.graderId&&c.version===String(u.revision)&&h(c.metadata.rewardBinding)===h(L(t)))))throw new Error("Prepared Taskset graders do not match their immutable Reward binding.");let o=V.parse({id:e.task.id,clusterKey:e.task.clusterKey,split:e.task.split,input:e.task.input,expectedOutput:e.task.expectedOutput,policyVisibleContext:e.task.policyVisibleContext,privilegedContextRef:e.task.privilegedContextRef,artifactRefs:[],tags:e.task.tags}),n=await B({binding:t,rewards:a,task:o,signal:e.signal,evidence:{output:e.attempt.output,artifactRefs:e.attempt.artifactRefs,runtimeEventRefs:e.attempt.runtimeEventRefs,infrastructureError:e.attempt.infrastructureError},customVerifier:e.customVerifier?async({grader:i})=>{let u=e.graders.find(m=>m.id===i.id);if(u?.kind!=="custom_verifier")throw new Error("Bound verifier projection is missing.");let c=await e.customVerifier({grader:u,task:e.task,attempt:e.attempt,signal:e.signal});return{score:c.score,passed:c.passed,rewardEligible:i.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs??[]}}:void 0,modelJudge:e.modelJudge?async({grader:i})=>{let u=e.graders.find(m=>m.id===i.id);if(u?.kind!=="model_judge")throw new Error("Bound judge projection is missing.");let c=await e.modelJudge({grader:u,task:e.task,attempt:e.attempt});return{score:c.score,passed:c.passed,rewardEligible:i.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs??[]}}:void 0}),s=n.training.status==="not_configured"?n.evaluation:n.training,f=h(e.graders);return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${h([e.attempt.id,n.contentHash]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:f,score:s.score,passed:s.passed===!0,components:n.results.map(i=>{let u=t.sources.find(m=>m.graderId===i.graderId),c=e.graders.find(m=>m.id===i.graderId);return{graderId:i.graderId,graderVersion:c.version,score:i.normalizedScore,passed:i.passed===!0,hardGate:u.hardGate,rewardEligible:u.role==="training"&&i.status==="scored",feedback:i.message?.trim()||null,evidenceRefs:i.evidenceHashes,judge:c.kind==="model_judge"?c.judge:null,calibrationStatus:c.kind==="model_judge"?c.calibrationStatus:"not_applicable"}}),failureClass:e.attempt.infrastructureError?"infrastructure_failure":s.status!=="scored"?"grader_failure":s.passed?null:"policy_failure",feedback:n.results.flatMap(i=>i.message?.trim()?[i.message.trim()]:[]),rewardEligible:n.training.status==="scored",rewardComposition:n,createdAt:e.now?.()??new Date().toISOString()}}l(ee,"gradeLearningBatchAttempt");async function at(e){if(e.learning)return ee({...e,learning:e.learning});if(e.graders.some(o=>o.metadata.rewardBinding!==void 0))throw new Error("This Taskset requires its immutable public Reward binding to grade an attempt.");let t=h(e.graders),a=[];for(let o of e.graders)e.signal?.throwIfAborted(),a.push(e.attempt.infrastructureError?b(o,null,!1,"Infrastructure failure; no reward was produced.",[],!1):await me(o,e.task,e.attempt,e.modelJudge,e.customVerifier,e.signal));let r=F({graders:e.graders,infrastructureError:e.attempt.infrastructureError,components:a.map(o=>({...o,failureClass:o.score===null?"grader_failure":o.passed?null:"policy_failure"}))});return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${h([e.attempt.id,t,a]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:t,score:r.score,passed:r.passed,components:a,failureClass:r.failureClass,feedback:e.attempt.infrastructureError?[e.attempt.infrastructureError]:a.flatMap(o=>o.feedback?[o.feedback]:[]),rewardEligible:r.rewardEligible,createdAt:e.now?.()??new Date().toISOString()}}l(at,"gradeAttempt");async function me(e,t,a,r,o,n){if(e.kind==="model_judge"){if(!r)return b(e,null,!1,"Model judge runner is unavailable.",[],!1);if(e.calibrationStatus!=="passed")return b(e,null,!1,"Model judge calibration has not passed.",[],!1);let f=await r({grader:e,task:t,attempt:a});return b(e,f.score,f.passed,f.feedback,f.evidenceRefs??[])}if(e.kind==="human")return b(e,null,!1,"Human review is pending.",[],!1);if(e.kind==="custom_verifier"){if(!o)return b(e,null,!1,"Sandboxed verifier runner is unavailable.",[],!1);let f=await o({grader:e,task:t,attempt:a,signal:n});return b(e,f.score,f.passed,f.feedback,f.evidenceRefs??[])}let s=C({grader:O(e),task:t,evidence:a});return b(e,s.score,s.passed,s.feedback,[...a.artifactRefs,...a.runtimeEventRefs])}l(me,"runGrader");function b(e,t,a,r,o,n=e.rewardEligible){let s=t!==null&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null;return{graderId:e.id,graderVersion:e.version,score:s,passed:s!==null&&a,hardGate:e.hardGate,rewardEligible:s!==null&&n,feedback:r,evidenceRefs:o,judge:e.kind==="model_judge"?e.judge:null,calibrationStatus:e.kind==="model_judge"?e.calibrationStatus:"not_applicable"}}l(b,"component");import{access as ue,mkdir as T,readFile as Vt,writeFile as y}from"node:fs/promises";import p from"node:path";async function Gt(e,t,a={}){let r=z.parse(e),o=P(r);if(!o.valid)throw new Error(o.issues.map(s=>`${s.code}: ${s.message}`).join(`
|
|
3
3
|
`));await T(p.join(t,"data"),{recursive:!0}),await T(p.join(t,"graders"),{recursive:!0}),await T(p.join(t,"environment"),{recursive:!0}),await T(p.join(t,"fixtures"),{recursive:!0});let n=[p.join(t,"taskset.json"),p.join(t,"capabilities.json"),p.join(t,"data","tasks.jsonl"),p.join(t,"graders","graders.json"),p.join(t,"fixtures","grader-fixtures.json"),p.join(t,"environment","taskset.ts")];await y(n[0],E(r),"utf8"),await y(n[1],E(r.capabilities),"utf8"),await y(n[2],r.tasks.map(s=>JSON.stringify(s)).join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`,"utf8"),await y(n[3],E(r.graders),"utf8"),await y(n[4],E(r.graderFixtures),"utf8"),await y(n[5],pe(r),"utf8");for(let s of a.generatedFiles??[]){let f=te(s.path,s.role),i=p.join(t,f);await T(p.dirname(i),{recursive:!0}),await y(i,s.content,"utf8"),n.push(i)}for(let s of r.graders){if(s.kind!=="custom_verifier")continue;let f=te(s.module,"verifier");try{await ue(p.join(t,f))}catch{throw new Error(`Custom verifier ${s.id} is missing generated source ${f}.`)}}return{directory:t,files:n,taskset:r}}l(Gt,"buildTaskset");function te(e,t){let a=e.replaceAll("\\","/");if(p.posix.isAbsolute(a)||a.split("/").includes(".."))throw new Error(`Generated ${t} path must stay inside the Taskset: ${e}.`);let r=t==="verifier"?"graders/":t==="environment"?"environment/":"fixtures/";if(!a.startsWith(r))throw new Error(`Generated ${t} path must start with ${r}.`);return a}l(te,"safeGeneratedPath");function pe(e){return`// Generated by @openpond/taskset-sdk.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{Ab as Ne,Ac as Xe,Cc as be,Da as Ve,Dc as Se,Eb as We,Fa as qe,Fc as xe,H as ne,K as N,Ka as $e,L as p,Ma as Le,Mb as V,Na as oe,Pb as U,Qa as Re,Ra as W,Rb as ce,Sa as K,Ta as ie,Ua as Oe,Ub as de,Va as ze,W as Ce,Xa as Y,Y as Fe,Ya as A,Za as Q,d as ge,f as we,fc as Ke,g as G,h as re,wa as je,xb as Ge,yc as Je,zc as Te}from"./chunk-VG7XO6PR.js";import{n as ve,o as ke,p as Ae}from"./chunk-7R7O2XXP.js";import{B as Ie,E as He,F as Ee,G as Me,H as De,O,P as J,R as $,T as ee,W as X,Y as te,_ as _e,a as B,fa as v,ga as j,ha as H,ia as Be,ka as se,ma as ae,s as Z,xa as z}from"./chunk-DGD52VZC.js";import{b as g}from"./chunk-ES2ISFJC.js";import{a as S}from"./chunk-FTQLQJQV.js";var me=J.shape.id,Ye=g.object({schemaVersion:g.literal("openpond.modelBatchReviewInspection.v1"),packageHash:g.string().regex(/^[a-f0-9]{64}$/),definition:$,binding:Ie,evidence:g.array(X).min(1).max(1e4),decisions:g.array(_e).min(1).max(1e4)}).strict(),ye=g.object({schemaVersion:g.literal("openpond.modelBatchReviewRequest.v1"),operationId:me,modelId:me,expectedModelRevision:g.number().int().positive(),tasksetRef:J,rewardBindingRef:J.nullable(),definition:g.object({name:g.string().trim().min(1).max(500).optional(),instructions:g.string().trim().min(1).max(2e4).optional(),inputSchema:O.optional(),outputSchema:O.optional(),requiredOutputs:$.shape.requiredOutputs}).strict(),examples:g.array(g.object({evidence:J,input:O.optional(),expected:O.nullable().optional(),evaluatorContext:O.nullable().optional(),proposedTarget:O.nullable().optional()}).strict()).max(1e4)}).strict(),Qe=g.object({schemaVersion:g.literal("openpond.modelBatchReviewReceipt.v1"),operationId:me,modelId:me,source:ee,evidence:g.array(X).min(1).max(1e4),proposals:g.array(te).max(1e4)}).strict();function rt(s){let e=A(s.source),t=A(s.edited),a=s.preparation;if(a.authoringGraph!=="bound"||!e.modelResources||e.learningResources||t.modelResources||t.learningResources)throw new Error("Bound task editing requires its source Reward and an ordinary edited workspace.");if(e.contentHash!==a.sourcePackageHash||!j(v(e.taskset),a.sourceTasksetRef))throw new Error("Bound draft differs from its retained source package.");let i=S(b=>b.taskset.graders.map(F=>F.kind==="custom_verifier"?{...F,exportName:F.exportName??"verify"}:F),"normalizedGraders");if(p(i(e))!==p(i(t)))throw new Error("Edit the saved Reward in Rewards before changing this Taskset's graders.");let m=e.modelResources,u=new Map(m.assets.map(b=>[b.id,b])),k=K(t),x=K(e),R=S(b=>{let{id:F,revision:fe,contentHash:ue,metadata:he,...st}=b,{javascriptEnvironment:vt,...Pe}=he;return{...st,metadata:{...Pe,resources:Pe.resources??[]}}},"environmentContent"),o=S(b=>{if(!b)return null;let{id:F,revision:fe,contentHash:ue,...he}=b.execution.javascript;return he},"javascriptContent"),w=p(R(e.environment))===p(R(t.environment))&&p(o(x))===p(o(k)),c=w?e.environment:t.environment,l=w?x:k,d=new Set([...m.assets.map(b=>b.id),...t.taskset.tasks.flatMap(b=>b.privilegedContextRef?[b.privilegedContextRef]:[]),...[t.environment.actionSchemaRef,t.environment.observationSchemaRef,t.environment.stateSchemaRef].flatMap(b=>b?[b.id]:[]),...k?.assets.map(b=>b.id)??[]]);for(let b of d){let F=t.files.find(ue=>ue.asset.id===b);if(!F)throw new Error(`Bound Taskset asset is missing: ${b}.`);let fe=new TextDecoder("utf-8",{fatal:!0}).decode(W(F));u.set(b,se.parse(H({schemaVersion:"openpond.learningTextAsset.v1",id:b,revision:1,asset:F.asset,text:fe})))}let I=Y(t),{contentHash:E,...D}=m.taskDefinition,{policy:h,environment:y,environmentRelease:C,tools:q,capabilities:r,verifierSetRelease:f}=t.taskset,T=$.parse(H({...D,instructions:I,execution:{policy:h,environment:y,environmentRelease:C,tools:q,capabilities:r,verifierSetRelease:f}})),{contentHash:M,...n}=t.taskset,P=Z.parse(H({...n,tasks:t.taskset.tasks.map(b=>m.instructionMode==="per_task"?b:{...b,policyVisibleContext:{...b.policyVisibleContext,instructions:I}})})),_=oe({owner:a.lineage.owner,source:{...m,taskset:e.taskset,executionResources:{environment:e.environment,verifierSet:e.verifierSet}},rewardBinding:m.rewardBinding,rewards:m.rewards,assets:[...u.values()],edits:{taskset:P,taskDefinition:T,executionResources:{environment:c,verifierSet:t.verifierSet},...l?{execution:l.execution}:{}}}),L=$e.parse(_.taskset.metadata.modelTasksetDerivation);if(_.taskset.id!==a.tasksetId||_.taskset.revision!==a.tasksetRevision||p({...L,schemaVersion:a.lineage.schemaVersion})!==p(a.lineage))throw new Error("Bound draft differs from its retained ownership lineage.");let{taskset:pe,executionResources:et,...tt}=_;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:pe,...et,modelResources:tt,files:t.files})}S(rt,"publishBoundModelTasksetDraftPackage");function nt(s){let e=we.parse(s.request),t=ge.parse(s.owner),a=A(s.source);if(a.learningResources)throw new Error("Reviewed Tasksets require their reviewed authoring workflow.");if(a.contentHash!==e.sourcePackageHash)throw new Error("Taskset draft source package changed.");if(a.modelResources){let x=Le({owner:t,source:{...a.modelResources,taskset:a.taskset,executionResources:{environment:a.environment,verifierSet:a.verifierSet}},rewardBinding:a.modelResources.rewardBinding,rewards:a.modelResources.rewards,assets:a.modelResources.assets}),R=x.taskset.metadata.modelTasksetDerivation;return G.parse({schemaVersion:"openpond.modelTasksetDraftPreparation.v1",draftId:`model-taskset-draft-${p({owner:t,operationId:e.operationId})}`,requestHash:p(e),sourcePackageHash:a.contentHash,sourceTasksetRef:v(a.taskset),tasksetId:x.taskset.id,tasksetRevision:x.taskset.revision,lineage:{...R,schemaVersion:"openpond.modelTasksetAuthoring.v1"},authoringGraph:"bound"})}let i=ze(a.taskset),m=i&&p(i.owner)===p(t),u=m?i.root:v(a.taskset),k={schemaVersion:"openpond.modelTasksetAuthoring.v1",owner:t,root:u,parent:v(a.taskset)};return G.parse({schemaVersion:"openpond.modelTasksetDraftPreparation.v1",draftId:`model-taskset-draft-${p({owner:t,operationId:e.operationId})}`,requestHash:p(e),sourcePackageHash:a.contentHash,sourceTasksetRef:v(a.taskset),tasksetId:Oe(k),tasksetRevision:m?a.taskset.revision+1:1,lineage:k})}S(nt,"prepareModelTasksetDraft");function ot(s){let e=G.parse(s.preparation);if(!j(e.sourceTasksetRef,e.lineage.parent))throw new Error("Taskset draft preparation differs from its source lineage.");if(e.authoringGraph==="bound"){if(!s.source)throw new Error("Bound Taskset authoring requires its retained source package.");return rt({preparation:e,source:s.source,edited:s.edited})}let t=it(s.edited),{contentHash:a,...i}=t.verifierSet,m=Fe({...i,id:`${e.tasksetId}-verifiers`,revision:e.tasksetRevision,calibrationReceiptRefs:[],metadata:{sourceVerifierSet:v(t.verifierSet)}}),{contentHash:u,...k}=t.taskset,x=Z.parse(H({...k,id:e.tasksetId,revision:e.tasksetRevision,verifierSetRelease:{id:m.id,contentHash:m.contentHash},metadata:{modelTasksetAuthoring:e.lineage,...t.taskset.metadata.environmentResources===void 0?{}:{environmentResources:t.taskset.metadata.environmentResources},...t.taskset.metadata.ordinaryAuthoring===void 0?{}:{ordinaryAuthoring:t.taskset.metadata.ordinaryAuthoring}}})),R=K(t),o=R?[...t.files.filter(w=>w.asset.id!==qe(t.taskset)),ie({...R.execution,verifierSet:m})]:t.files;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:x,environment:t.environment,verifierSet:m,files:o})}S(ot,"publishModelTasksetDraftPackage");function it(s){let e=A(s);if(e.modelResources||e.learningResources)throw new Error("This Taskset requires its bound or reviewed authoring workflow.");return e}S(it,"requireOrdinaryPackage");function ct(s,e,t,a){if(s.environment.entrypoint!=="openpond.javascript-environment.v1")return{taskset:s,inventory:t,generatedFiles:[]};let i="environment/execution.json",m=e.get(i);if(!m||m.length>524288)throw new Error("Authored tool environment requires its bounded private execution declaration.");let u=Ve.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m))),k=S(D=>{if(!D)return null;let h=t.find(y=>y.asset.id===D.id&&y.asset.path===D.path);if(!h)throw new Error(`Authored environment dependency is missing: ${D.id}.`);return h.asset},"repin"),{contentHash:x,...R}=u.javascript,o=je.parse(H({...R,id:`javascript-${s.id}`,revision:s.revision,module:k(u.javascript.module)}));if(p(o.tools)!==p(s.environment.metadata.portableTools)||p(o.tools.map(D=>D.name))!==p(s.environment.toolNames))throw new Error("Authored environment tools differ from the Taskset's declared tools.");let w=Ce({schemaVersion:"openpond.environmentRelease.v1",id:`environment-${s.id}`,revision:s.revision,contract:Se(s),actionSchemaRef:k(u.environment.actionSchemaRef),observationSchemaRef:k(u.environment.observationSchemaRef),stateSchemaRef:k(u.environment.stateSchemaRef),artifactCollection:u.environment.artifactCollection,adapterConformanceHashes:{},metadata:{javascriptEnvironment:v(o),resources:s.environment.resources??[]}}),c=V.parse({...s,environment:{...s.environment,metadata:{...s.environment.metadata,portableExecutionResources:{environment:w}}}}),l=be({taskset:c,adapterId:a}),d=ie({javascript:o,environment:w,verifierSet:l.verifierSetRelease}),I=[...t.filter(D=>D.sourcePath!==i),{asset:d.asset,sourcePath:i}],E=V.parse({...c,metadata:{...c.metadata,portableFileInventory:I}});return{taskset:V.parse({...E,contentHash:U(E)}),inventory:I,generatedFiles:[{path:i,role:"environment",content:new TextDecoder().decode(W(d))}]}}S(ct,"prepareAuthoredToolEnvironment");var le=g.array(g.object({asset:ne,sourcePath:g.string().min(1)}).strict()).max(1e4),dt=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","environment/taskset.ts"]);function mt(s){return dt.has(s)}S(mt,"isGeneratedTasksetPublicationFilePath");function lt(s,e,t){let a=V.parse(s);if(a.metadata.taskDefinition!==void 0||a.metadata.rewardBinding!==void 0)return{taskset:a,generatedFiles:[]};let i=new Map,m=0;for(let[r,f]of e){if(re.parse(r),m+=f.byteLength,i.size>=1e4||m>Re*3/4)throw new Error("Taskset source exceeds the package byte limit.");i.set(r,f.slice())}let u=a.metrics?.customAggregator,k=u?i.get(u.module):void 0;if(u&&!k)throw new Error("Declared Taskset metric module is missing.");let x=u&&k?{...a.metrics,customAggregator:{...u,contentHash:N(k)}}:a.metrics,R=new Map,o=new Set,w=[],c=S((r,f,T,M)=>{let n=i.get(f);if(!n)throw new Error(`Declared Taskset file is missing: ${f}.`);return{id:r,path:f,contentHash:N(n),sizeBytes:n.byteLength,mediaType:T,visibility:M}},"ref"),l=S((r,f=r.path)=>{let T=R.get(r.id);if(T&&p(T)!==p({asset:r,sourcePath:f}))throw new Error(`Conflicting Taskset file identity: ${r.id}.`);let M=i.get(f);if(!M||M.length!==r.sizeBytes||N(M)!==r.contentHash)throw new Error(`Taskset file differs from its declared bytes: ${r.id}.`);R.set(r.id,{asset:r,sourcePath:f}),o.add(f)},"add");for(let r of a.tasks){let f=xe(r);for(let T of f.artifactRefs)l(T,r.assets?.find(M=>M.id===T.id)?.artifactRef??T.path);for(let T of f.requiredOutputs??[])T.schemaRef&&l(T.schemaRef)}for(let r of a.environment.resources??[])l(c(r.id,r.path,r.mediaType??"application/octet-stream",r.visibility==="policy_visible"?"policy":"host_private"));let d=a.graders.map(r=>{if(r.kind==="custom_verifier"){let f=c(`verifier-${r.id}`,r.module,"application/javascript","host_private"),T=ne.safeParse(r.metadata.portableVerifierRef);return T.success&&T.data.contentHash===f.contentHash&&T.data.sizeBytes===f.sizeBytes&&(f=T.data),l(f,r.module),{...r,metadata:{...r.metadata,portableVerifierRef:f}}}if(r.kind==="human"||r.kind==="model_judge"){let f=new TextEncoder().encode(r.rubric),T=`graders/rubric-${N(f)}.md`;i.set(T,f);let M=c(`rubric-${r.id}`,T,"text/markdown","verifier"),n=ne.safeParse(r.metadata.portableRubricRef);if(n.success&&n.data.contentHash===M.contentHash&&n.data.sizeBytes===M.sizeBytes){if(n.data.visibility==="policy")throw new Error("A grader rubric cannot become policy-visible.");M=n.data}return l(M,T),w.push({path:T,role:"verifier",content:r.rubric}),{...r,metadata:{...r.metadata,portableRubricRef:M}}}return r});u&&![...R.values()].some(r=>r.asset.path===u.module&&r.sourcePath===u.module&&r.asset.visibility!=="policy")&&l(c(`metric-${p(u.module)}`,u.module,"application/javascript","host_private"));let I=le.parse(a.metadata.portableFileInventory??[]);for(let r of[...i.keys()].sort())if(!o.has(r)){let f=I.find(T=>T.sourcePath===r&&!R.has(T.asset.id));l(f?{...c(f.asset.id,r,f.asset.mediaType,f.asset.visibility),path:f.asset.path}:c(`taskset-file-${p(r)}`,r,"application/octet-stream","host_private"),r)}let{importedPackageHash:E,derivedPortableMetadata:D,...h}=a.metadata,y={...a.environment.metadata};if(y.portableExecutionResources!==void 0){let r=g.object({environment:g.unknown(),verifierSet:g.unknown().optional()}).parse(y.portableExecutionResources);y.portableExecutionResources={environment:r.environment}}let C=V.parse({...a,graders:d,metrics:x,environment:{...a.environment,metadata:y},metadata:{...h,...E===void 0?{}:{sourceImportedPackageHash:E},portableFileInventory:le.parse([...R.values()].sort((r,f)=>r.asset.id.localeCompare(f.asset.id)))}}),q=ct(C,i,[...R.values()],t);return{taskset:V.parse({...q.taskset,contentHash:U(q.taskset)}),generatedFiles:[...w,...q.generatedFiles]}}S(lt,"prepareAuthoredTasksetSource");function Is(s){let e=A(s.source);if(e.modelResources||e.learningResources)throw new Error("Binding an ordinary Reward requires an ordinary source package.");let t=Y(e);if(!t.trim())throw new Error("Add collection instructions before selecting a saved Reward.");let a=new Map,i=K(e);for(let h of i?.assets??[])a.set(h.id,h);let m=new Set([...e.taskset.tasks.flatMap(h=>h.privilegedContextRef?[h.privilegedContextRef]:[]),...[e.environment.actionSchemaRef,e.environment.observationSchemaRef,e.environment.stateSchemaRef].flatMap(h=>h?[h.id]:[])]);for(let h of m){if(a.has(h))continue;let y=e.files.find(q=>q.asset.id===h);if(!y)throw new Error(`Source Taskset context is missing: ${h}.`);let C=new TextDecoder("utf-8",{fatal:!0}).decode(W(y));a.set(h,se.parse(H({schemaVersion:"openpond.learningTextAsset.v1",id:h,revision:1,asset:y.asset,text:C})))}for(let h of s.assets){let y=e.files.find(C=>C.asset.id===h.id);if(y&&H({asset:y.asset}).contentHash!==H({asset:h.asset}).contentHash)throw new Error(`Selected Reward conflicts with a source asset: ${h.id}.`);a.set(h.id,h)}let{policy:u,environment:k,environmentRelease:x,tools:R,capabilities:o,verifierSetRelease:w}=e.taskset,c=$.parse(H({schemaVersion:"openpond.taskDefinition.v1",id:`${e.taskset.id}-definition`,revision:1,name:e.taskset.id,description:"",instructions:t,category:"custom",familyNamespace:e.taskset.id,inputSchema:{type:"object"},outputSchema:{type:"object"},rewardBinding:v(s.rewardBinding),harness:null,execution:{policy:u,environment:k,environmentRelease:x,tools:R,capabilities:o,verifierSetRelease:w}})),l=oe({...s,assets:[...a.values()],source:{taskset:e.taskset,taskDefinition:c,instructionMode:"per_task",executionResources:{environment:e.environment,verifierSet:e.verifierSet},...i?{execution:i.execution}:{}}}),d=new Map(e.files.map(h=>[h.asset.id,h]));for(let h of l.assets){let y="";for(let C of new TextEncoder().encode(h.text))y+=String.fromCharCode(C);d.set(h.id,{asset:h.asset,base64:btoa(y)})}let{taskset:I,executionResources:E,...D}=l;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:I,...E,modelResources:D,files:[...d.values()]})}S(Is,"bindOrdinaryModelTasksetReward");function pt(s){let{request:e,package:t}=s,a=t.learningResources;if(!a)throw new B("model_review_batch_required",422);let i=z(t.taskset),m=`model-review-${p([s.scope,e.modelId,e.operationId])}`,u=new Map(e.examples.map(n=>[p(n.evidence),n])),k=new Set(a.evidence.map(n=>p(v(n)))),x=new Map(a.decisions.map(n=>[p(n.evidence),n]));if(u.size!==e.examples.length||e.examples.some(n=>!k.has(p(n.evidence))))throw new B("model_review_evidence_mismatch",409);for(let n of[s.binding,...s.rewards,...s.assets])Be(n);Me(s.binding,s.rewards);let R=new Map;for(let n of s.binding.sources){let P=s.rewards.find(pe=>j(v(pe),n.reward)),{contentHash:_,...L}=P;R.set(P.contentHash,He({...L,id:`${m}-reward-${P.contentHash}`,revision:1}))}let o=[...R.values()],{contentHash:w,recipeRef:c,...l}=s.binding,d=Ee({...l,id:`${m}-binding`,revision:1,sources:s.binding.sources.map(n=>({...n,reward:v(R.get(n.reward.contentHash))}))},o),I=o.flatMap(n=>[...n.assets,..."verifierRef"in n.implementation?[n.implementation.verifierRef]:[],..."rubricRef"in n.implementation?[n.implementation.rubricRef]:[],..."inputContract"in n.implementation?[n.implementation.inputContract]:[]]),E=[...new Map(I.map(n=>{let P=s.assets.find(_=>_.id===n.id);if(!P)throw new B("model_review_reward_asset_missing",422);if(ae(P,n),n.visibility==="policy")throw new B("reward_asset_visibility_invalid",422);return[P.id,P]})).values()],{environmentRelease:D,verifierSetRelease:h,...y}=i.definition.execution,{contentHash:C,...q}=i.definition,r=$.parse(H({...q,...e.definition,id:`${m}-definition`,revision:1,rewardBinding:v(d),execution:{...y,policy:{...y.policy,hiddenGraderRefs:De(d,o).filter(n=>n.privileged).map(n=>n.id)}}})),f=ee.parse(H({schemaVersion:"openpond.learningSource.v1",id:m,revision:1,name:`${r.name} review`,kind:"direct",taskDefinition:v(r),enabled:!0,allowedSplits:[...new Set(a.evidence.map(n=>n.submission.split))],mapping:null,adapterVersion:null,reviewOrigin:{modelId:e.modelId,packageHash:t.contentHash,taskset:v(t.taskset),batch:v(a.batch),rewardBinding:v(s.binding)}})),T=a.evidence.map(n=>{let P=u.get(p(v(n))),_=`review-${n.contentHash}`,L=p({instructions:r.instructions,inputSchema:r.inputSchema,outputSchema:r.outputSchema,requiredOutputs:r.requiredOutputs??[],input:P?.input??n.submission.input})!==p({instructions:i.definition.instructions,inputSchema:i.definition.inputSchema,outputSchema:i.definition.outputSchema,requiredOutputs:i.definition.requiredOutputs??[],input:n.submission.input});return X.parse(H({schemaVersion:"openpond.taskEvidence.v1",id:Ae(f.id,n.submission.exampleId,_),revision:1,source:v(f),submission:{...n.submission,sourceId:f.id,taskDefinition:v(r),attemptId:_,observedOutput:L?null:n.submission.observedOutput,idempotencyKey:`${m}-${n.contentHash}`,...P?.input===void 0?{}:{input:P.input},...P?.expected===void 0?{}:{expected:P.expected},...P?.evaluatorContext===void 0?{}:{evaluatorContext:P.evaluatorContext}},supersedes:v(n),correctionFeedbackId:null,receivedAt:s.now}))}),M=T.flatMap(n=>{let P=u.get(p(n.supersedes)),_=x.get(p(n.supersedes)),L=P?.proposedTarget===void 0?_.approvedTarget:P.proposedTarget;return L===null?[]:[te.parse({schemaVersion:"openpond.taskFeedbackRecord.v1",id:`feedback-${p([m,n.id])}`,revision:1,submission:{schemaVersion:"openpond.taskFeedback.v1",sourceId:f.id,idempotencyKey:`${m}-${n.id}`,exampleId:n.submission.exampleId,attemptId:n.submission.attemptId,expectedEvidenceHash:n.contentHash,occurredAt:s.now,kind:"target_correction",value:L,note:"Proposed target for the revised task. Grade and review before admission."},status:"pending_review",evidence:v(n),createdAt:s.now,review:null})]});return{source:f,definition:r,binding:d,rewards:o,assets:E,evidence:T,proposals:M}}S(pt,"prepareModelBatchReview");var Ue=S(s=>`model-batch-review-${p([s.modelId,s.operationId])}`,"operation");function _s(s){let e=A(s);if(!e.learningResources)throw new B("model_review_batch_required",422);let t=z(e.taskset);return Ye.parse({schemaVersion:"openpond.modelBatchReviewInspection.v1",packageHash:e.contentHash,definition:t.definition,binding:t.binding,evidence:e.learningResources.evidence,decisions:e.learningResources.decisions})}S(_s,"inspectModelBatchPackage");async function ft(s,e){let t=ye.parse(e),a=await s.operation(Ue(t));if(!a)return null;if(a.requestHash!==p(t))throw new B("learning_idempotency_conflict",409);return Ze(s,t,a.resources)}S(ft,"findModelBatchReview");async function Bs(s,e){let t=ye.parse(e.request),a=await ft(s,t);if(a)return a;let i=A(e.package);if(!i.learningResources)throw new B("model_review_batch_required",422);let m=z(i.taskset),u=t.rewardBindingRef,k=!u||j(u,v(m.binding)),x=k?m.binding:await ke(s,"binding",u),R=k?m.rewards:await Promise.all(x.sources.map(d=>ke(s,"reward",d.reward))),o=new Set(R.flatMap(d=>[...d.assets,..."verifierRef"in d.implementation?[d.implementation.verifierRef]:[],..."rubricRef"in d.implementation?[d.implementation.rubricRef]:[],..."inputContract"in d.implementation?[d.implementation.inputContract]:[]]).map(d=>d.id)),w=k?i.learningResources.assets:await Promise.all([...o].map(d=>ve(s,"asset",d,1))),c=pt({...e,request:t,package:i,binding:x,rewards:R,assets:w}),l=[];for(let d of c.assets){let I=await s.get("asset",d.id,1);if(I&&I.contentHash!==d.contentHash)throw new B("model_review_asset_conflict",409);I||await s.put("asset",d,0)}for(let d of c.rewards)await s.put("reward",d,0);await s.put("binding",c.binding,0),await s.put("definition",c.definition,0),await s.put("source",c.source,0,{parentId:t.modelId}),l.push({kind:"source",id:c.source.id,revision:1});for(let d of c.evidence)await s.put("evidence",d,0,{parentId:c.source.id}),l.push({kind:"evidence",id:d.id,revision:1});for(let d of c.proposals)await s.put("feedback",d,0,{parentId:d.evidence.id,status:d.status}),l.push({kind:"feedback",id:d.id,revision:1});return await s.saveOperation(Ue(t),{requestHash:p(t),resources:l}),Ze(s,t,l)}S(Bs,"beginModelBatchReview");async function Ze(s,e,t){let a=await Promise.all(t.map(i=>ve(s,i.kind,i.id,i.revision)));return Qe.parse({schemaVersion:"openpond.modelBatchReviewReceipt.v1",operationId:e.operationId,modelId:e.modelId,source:a.find(i=>i.schemaVersion==="openpond.learningSource.v1"),evidence:a.filter(i=>i.schemaVersion==="openpond.taskEvidence.v1"),proposals:a.filter(i=>i.schemaVersion==="openpond.taskFeedbackRecord.v1")})}S(Ze,"readReceipt");function Cs(s){let e=A(s.package),t=e.taskset,a=e.modelResources,i=e.learningResources?z(t):void 0,m=Ge.parse({schemaVersion:"openpond.uploadedFileDatasetSource.v1",kind:"uploaded_file",id:`package-source-${p({profileId:s.profileId,packageHash:e.contentHash})}`,profileId:s.profileId,title:s.name,sourceHash:e.contentHash,occurredAt:s.createdAt,licensingStatus:"pending",secretScanStatus:"pending",piiScanStatus:"pending",originalFileNames:["taskset-package.json"],mediaTypes:["application/json"],sourceFileHashes:[e.contentHash],totalBytes:new TextEncoder().encode(JSON.stringify(e)).byteLength,parserVersion:"openpond.tasksetPackage.v1",metadata:{}}),u=Ke({profileId:s.profileId,id:`${t.id}-import`,name:s.name,now:s.createdAt}),k=[];for(let c of t.graders)if(c.kind==="custom_verifier"){let l=a?.assets.find(E=>E.id===c.verifierRef.id),d=e.files.find(E=>E.asset.id===c.verifierRef.id);if(!d)throw new Error(`Imported verifier source is missing: ${c.id}.`);let I=Xe(c.verifierRef.contentHash);k.some(E=>E.path===I)||k.push({path:I,role:"verifier",content:l?ae(l,c.verifierRef):new TextDecoder("utf-8",{fatal:!0}).decode(W(d))})}let x=t.metadata.ordinaryAuthoring??t.metadata.starterAuthoring,R=We.array().max(1e5).parse(x?.graderFixtures??[]),o=t.environment.kind==="text"?"chat":t.environment.kind==="custom_program"?"program":t.environment.kind,w=V.parse({schemaVersion:"openpond.taskset.v1",id:t.id,revision:t.revision,profileId:s.profileId,profileRelease:null,createImproveRunId:null,name:s.name,objective:Y(e),status:"needs_review",sourceRefs:[m],datasetArtifact:null,policy:t.policy,environment:{...u.environment,kind:o,entrypoint:t.environment.entrypoint,resources:Ne.array().max(1e4).parse(t.metadata.environmentResources??[]),stateful:t.environment.stateful,deterministicSeeds:t.environment.deterministicSeeds,toolNames:t.tools.map(c=>c.name),defaultTimeoutMs:t.environment.defaultTimeoutMs,networkPolicy:t.environment.networkPolicy,metadata:{runtimeSourceTasksetId:ut(s.profileId,e.contentHash),portableEnvironment:t.environment,portableTools:t.tools,portableExecutionResources:{environment:e.environment,verifierSet:e.verifierSet}}},capabilities:{...u.capabilities,taskKind:o==="chat"?"chat":o==="program"?"custom_program":"single_agent",compatibleMethods:["none"],requiresTools:t.tools.length>0,requiresState:t.environment.stateful,rewardKinds:[...new Set(t.graders.map(c=>c.kind==="human"?"human":c.kind==="model_judge"?"model_judge":"deterministic"))]},tasks:t.tasks.map(c=>({...c,schemaVersion:"openpond.taskData.v1",sourceRefs:[m.id],assets:c.artifactRefs.map(l=>({id:l.id,sourceRefId:m.id,artifactRef:l.path,fileName:l.path.split("/").at(-1),mediaType:l.mediaType,sha256:l.contentHash,sizeBytes:l.sizeBytes,split:c.split,metadata:{portableAsset:l}})),...c.requiredOutputs?{requiredOutputs:c.requiredOutputs.map(l=>({...l,schemaRef:l.schemaRef?.id??null,maxBytes:l.maxBytes??void 0}))}:{},metadata:{portableTaskRecord:c,exampleOrigin:"imported"}})),graders:a?Te(a.rewardBinding,a.rewards,a.assets):i?Te(i.binding,i.rewards,e.learningResources.assets):Je(e),graderFixtures:R,learningSignals:u.learningSignals,...t.metrics?{metrics:t.metrics}:{},authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:p("openpond-package-import-v1"),promptTemplateVersion:"package-import-v1",buildIntent:"discovery",buildSpecification:null,evidenceHashes:[e.contentHash],tasksetSdkVersion:"package-import-v1",sourceCommit:null,repairHistory:[],createdAt:s.createdAt},readiness:null,contentHash:"00000000",createdAt:s.createdAt,updatedAt:s.createdAt,metadata:{importedPackageHash:e.contentHash,...i?{learning:i}:{},portableFileInventory:e.files.map(c=>({asset:c.asset,sourcePath:c.asset.path})),...a?{taskDefinition:v(a.taskDefinition),rewardBinding:v(a.rewardBinding),rewardExecution:{binding:a.rewardBinding,rewards:a.rewards}}:{},portableCapabilities:t.capabilities,derivedPortableMetadata:t.metadata,...t.metadata.modelTasksetDerivation?{modelTasksetDerivation:t.metadata.modelTasksetDerivation}:{}}});return{package:e,taskset:V.parse({...w,contentHash:U(w)}),generatedFiles:k}}S(Cs,"prepareImportedTasksetPackage");function ut(s,e){return`package-${p({profileId:s,packageHash:e})}`}S(ut,"tasksetPackageSourceId");var ht=g.object({draft:ce,filePaths:g.array(g.object({assetId:g.string().min(1),paths:g.array(re).min(1).max(1e4)}).strict()).max(1e4)}).strict();function Vs(s){let e=A(s.source),t=ce.parse(s.sourceDraft),a=G.parse(s.preparation);if(e.contentHash!==a.sourcePackageHash||!j(v(e.taskset),a.sourceTasksetRef))throw new Error("Taskset draft preparation differs from its source package.");if(e.learningResources)throw new Error("Reviewed Tasksets require their reviewed authoring workflow.");if(!!e.modelResources!=(a.authoringGraph==="bound"))throw new Error("Taskset draft authoring graph differs from its source.");let i=le.parse(t.metadata.portableFileInventory??[]),m=S(o=>de(o)?`source-artifacts/${e.contentHash}/${p(o)}/${o.split("/").at(-1)}`:o,"sourcePath");if([...t.tasks.flatMap(o=>(o.assets??[]).map(w=>w.artifactRef)),...(t.environment.resources??[]).map(o=>o.path),...e.taskset.tasks.flatMap(o=>(o.requiredOutputs??[]).flatMap(w=>w.schemaRef?[w.schemaRef.path]:[])),...t.metrics.customAggregator?[t.metrics.customAggregator.module]:[],...t.graders.flatMap(o=>o.kind==="custom_verifier"?[o.module]:[])].some(de))throw new Error("A referenced source asset occupies a reserved Taskset authoring path.");let k=e.files.map(o=>{let w=new Set([o.asset.path]);for(let c of i)c.asset.id===o.asset.id&&w.add(c.sourcePath);for(let c of t.tasks)for(let l of c.assets??[])l.id===o.asset.id&&w.add(l.artifactRef);for(let c of e.taskset.graders)if(c.kind==="custom_verifier"&&c.verifierRef.id===o.asset.id){let l=t.graders.find(d=>d.id===c.id);l?.kind==="custom_verifier"&&w.add(l.module)}return{assetId:o.asset.id,paths:[...w].map(m)}}),x={...t.metadata};if(e.modelResources)for(let o of["taskDefinition","rewardBinding","rewardExecution","derivedPortableMetadata","modelTasksetDerivation","importedPackageHash"])delete x[o];let R=ce.parse({...t,id:a.draftId,revision:1,status:"draft",graders:t.graders.map(o=>({...o,metadata:{...o.metadata,portableGrader:e.taskset.graders.find(w=>w.id===o.id)}})),environment:{...t.environment,metadata:{...t.environment.metadata,portableExecutionResources:{environment:e.environment}}},modelScope:{modelId:a.lineage.owner.modelId,expectedModelRevision:s.expectedModelRevision,source:a},publishedTasksetRef:a.tasksetRevision>1?a.sourceTasksetRef:null,metadata:{...x,modelTasksetAuthoring:a.lineage,portableFileInventory:i.map(o=>({...o,sourcePath:m(o.sourcePath),asset:{...o.asset,id:de(o.sourcePath)?`source-artifact-${p({packageHash:e.contentHash,assetId:o.asset.id})}`:o.asset.id,path:m(o.asset.path)}}))}});return ht.parse({draft:R,filePaths:k})}S(Vs,"prepareTasksetDraftSource");export{ye as a,nt as b,ot as c,le as d,mt as e,lt as f,Is as g,_s as h,ft as i,Bs as j,Cs as k,ut as l,ht as m,Vs as n};
|
|
@@ -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 k="https://openpond.ai",U="https://api.openpond.ai",N="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`:
|
|
3
|
-
`),timeoutSeconds:120});if(y.command.status!=="succeeded")throw new Error(`expected command success, got ${y.command.status}`);if(!y.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 S=null;if(e.snapshot||e.fork){let h=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"}]}}}),f=h.snapshot??(await
|
|
2
|
+
import{a as n}from"./chunk-FTQLQJQV.js";var k="https://openpond.ai",U="https://api.openpond.ai",N="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`:te(t.hostname)?`${t.origin}${r}/v1/sandboxes`:t.origin===k?`${U}/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 te(o){return o==="api.openpond.ai"||o==="staging-api.openpond.ai"||o.startsWith("api")&&o.endsWith(".openpond.ai")}n(te,"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 l=await o.getSandboxRuntime(e);return l.sandboxId?o.get(l.sandboxId):o.createSandboxRuntimeSandbox(e,a,d).then(u=>u.sandbox)},"currentSandbox"),s=n(async(a={},d={})=>{let l=await o.getSandboxRuntime(e);if(!l.sandboxId)return o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox);let u=await o.get(l.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=re(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 re(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(re,"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,l=!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 y=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(y.command.status!=="succeeded")throw new Error(`expected command success, got ${y.command.status}`);if(!y.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 S=null;if(e.snapshot||e.fork){let h=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"}]}}}),f=h.snapshot??(await ne(o,u.id,h.snapshotJob?.snapshotId)).snapshot;if(S=f.id,f.state!=="ready")throw new Error(`expected ready snapshot, got ${f.state}`)}if(e.fork){if(!S)throw new Error("expected snapshot id before fork");let h=await G(o,(await o.forkSnapshot(S,{budget:{maxUsd:e.budgetUsd??"0.05"},metadata:{source:"openpond-code-sandbox-smoke-fork",templateSnapshotId:S}},{async:!0})).sandbox);a=h.id;let f=await o.exec(h.id,{command:"cat openpond-code-smoke.txt",timeoutSeconds:120});if(f.command.status!=="succeeded")throw new Error(`expected fork command success, got ${f.command.status}`);if(!f.command.output.includes(i))throw new Error("expected fork snapshot marker");e.keep||(await v(o,h.id),l=!0)}let I=null;if(e.preview!==!1){let h=await o.openPort(u.id,{label:"openpond-code-smoke",port:c}),f=await fetch(h.preview.url);I=f.status;let ee=await f.text();if(f.status!==200)throw new Error(`expected preview HTTP 200, got ${f.status}`);if(!ee.includes(s))throw new Error("expected preview marker")}let{sandbox:A,receipts:P}=await oe(o,u.id);return e.keep||(await v(o,u.id),d=!0),{deleted:d,execOutput:y.command.output.trim(),fileRoundtrip:!0,forkSandboxId:a,previewStatus:I,receiptRefs:P.map(h=>h.mpp.receiptRef??null),reservationRef:u.reservation.mpp?.reservationRef??null,runId:t,sandboxId:u.id,snapshotId:S,state:A.state}}finally{a&&!e.keep&&!l&&await H(o,a),m&&!e.keep&&!d&&await H(o,m)}}n(W,"runSandboxSmoke");async function oe(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 se(o,e);if(r.length===0)throw new Error("expected receipt readback");return{sandbox:t,receipts:r}}n(oe,"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 $(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 se(o,e){let s=Date.now()+12e4,i=await o.receipts(e);for(;Date.now()<s;){if(i.length>0)return i;await $(3e3),i=await o.receipts(e)}return i}n(se,"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 $(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
|
|
7
|
+
`)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${i.id} (${i.state})`)}n(G,"waitForCreateReady");async function ne(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 $(s),c=await o.get(e)}throw new Error(`snapshot did not reach ready state before timeout: ${t}`)}n(ne,"waitForSnapshotReady");function $(o){return new Promise(e=>setTimeout(e,o))}n($,"sleep");function R(o={}){return o.async||o.respondAsync?{Prefer:"respond-async"}:void 0}n(R,"asyncRequestHeaders");var q=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"}},w=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 x(o,e,t,r={}){let{timeoutMs:s=3e4,maxResponseBytes:i=8388608,explicitBearerAuth:c=!1,...m}=r,a=`${o}${t}`,d=new Headers(m.headers);d.set("Content-Type","application/json");let l=c?void 0:process.env.OPENPOND_API_KEY,u=e?.trim()||"",p=!c&&u.startsWith("opk_"),y=l||(p?u:null);y&&!d.has("openpond-api-key")&&d.set("openpond-api-key",y),e?d.set("Authorization",p?`ApiKey ${u}`:`Bearer ${e}`):l&&!d.has("Authorization")&&d.set("Authorization",`ApiKey ${l}`);let b=new AbortController,S=new q(s,a),I=s>0?setTimeout(()=>b.abort(S),s):null;I?.unref?.();let A=ie(m.signal,b.signal,s),P=n(()=>{I&&clearTimeout(I)},"cleanup");try{let h=await fetch(a,{...m,headers:d,signal:A});return ae(h,{cleanup:P,maximumBytes:i,requestUrl:a,timeoutController:b,timeoutError:S})}catch(h){throw P(),b.signal.aborted?S:h}}n(x,"apiFetch");async function T(o,e){let t;try{let r=await o.text();t=r?JSON.parse(r):{}}catch(r){if(r instanceof q||r instanceof w)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 ae(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 w(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 w(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(ae,"boundedResponse");function ie(o,e,t){return t<=0?o??void 0:o?AbortSignal.any([o,e]):e}n(ie,"composedSignal");async function _(o){let e=await x(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
|
-
`);for(;m!==-1;){let a=s.slice(0,m);s=s.slice(m+2);let d=
|
|
9
|
+
`);for(;m!==-1;){let a=s.slice(0,m);s=s.slice(m+2);let d=de(a);d&&process.stdout.write(d),m=s.indexOf(`
|
|
10
10
|
|
|
11
|
-
`)}}}finally{t.releaseLock()}}n(_,"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
|
|
12
|
-
`));return typeof t.output=="string"?t.output:null}catch{return null}}n(ne,"parseProcessOutputEvent");var O=class{static{n(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;customEndpoint;constructor(e){this.apiKey=e.apiKey,this.customEndpoint=e.customEndpoint??!1,this.sandboxApiUrl=C(e.sandboxApiUrl??e.baseUrl??U),this.apiRootUrl=L(this.sandboxApiUrl)}create(e,t={}){return this.request("",{method:"POST",...this.customEndpoint?{timeoutMs:18e4}:{},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 _({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 _({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 x(this.sandboxApiUrl,this.apiKey,e,this.customEndpoint?{...t,explicitBearerAuth:!0,redirect:"error"}:t);return T(r,"Sandbox request")}async requestApiRoot(e,t={}){let r=await x(this.apiRootUrl,this.apiKey,e,this.customEndpoint?{...t,explicitBearerAuth:!0,redirect:"error"}:t);return T(r,"OpenPond API request")}};var j=class extends O{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 j(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)??N)}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.reasoningEffort==="off"?t.thinking={type:"disabled"}:o.reasoningEffort&&(t.reasoning_effort=o.reasoningEffort),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,x as b,T as c,k as d,U as e,C as f,j as g,De as h,We as i,Ke as j};
|
|
11
|
+
`)}}}finally{t.releaseLock()}}n(_,"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 de(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(de,"parseProcessOutputEvent");var O=class{static{n(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;customEndpoint;constructor(e){this.apiKey=e.apiKey,this.customEndpoint=e.customEndpoint??!1,this.sandboxApiUrl=C(e.sandboxApiUrl??e.baseUrl??U),this.apiRootUrl=L(this.sandboxApiUrl)}create(e,t={}){return this.request("",{method:"POST",...this.customEndpoint?{timeoutMs:18e4}:{},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 _({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 _({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 x(this.sandboxApiUrl,this.apiKey,e,this.customEndpoint?{...t,explicitBearerAuth:!0,redirect:"error"}:t);return T(r,"Sandbox request")}async requestApiRoot(e,t={}){let r=await x(this.apiRootUrl,this.apiKey,e,this.customEndpoint?{...t,explicitBearerAuth:!0,redirect:"error"}:t);return T(r,"OpenPond API request")}};var j=class extends O{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 j(o)}n(De,"createOpenPondSandboxClient");import{randomUUID as ce}from"node:crypto";function X(o){let e=g(o);if(!e)throw new Error("apiBaseUrl is required");return e}n(X,"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)??N)}n(We,"resolveOpChatApiBaseUrl");function me(o){let e=o.trim();if(!e)throw new Error("OpenPond API key is required");return e}n(me,"requireToken");function Q(o,e,t){let r=new Headers;return r.set("Authorization",`Bearer ${me(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||ce()),r}n(Q,"hostedHeaders");async function Z(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(Z,"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.reasoningEffort==="off"?t.thinking={type:"disabled"}:o.reasoningEffort&&(t.reasoning_effort=o.reasoningEffort),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=`${X(o.apiBaseUrl)}/models`,r=await fetch(t,{method:"GET",headers:Q(o.token,"application/json"),signal:o.signal});if(!r.ok)throw new Error(`Hosted model list failed: ${r.status} ${await Z(r)}`);return await r.json()}n(Ke,"listOpChatModels");async function Ye(o){let t=`${X(o.apiBaseUrl)}/chat/completions`,r=await fetch(t,{method:"POST",headers:Q(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 Z(r)}`);return await r.json()}n(Ye,"sendHostedChatTurn");export{E as a,x as b,T as c,k as d,U as e,C as f,j as g,De as h,We as i,Ke as j,Ye as k};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{i as a,j as b,k as c}from"./chunk-VJJ3UXOI.js";import"./chunk-V44RF57H.js";import"./chunk-O277DPTX.js";import"./chunk-KRC2S5QF.js";import"./chunk-7EDOA6KD.js";import"./chunk-T5QA4W2H.js";import"./chunk-EWQZASG4.js";import"./chunk-T7MJBBHE.js";import"./chunk-MDE3HHLH.js";import"./chunk-KDOS6YMH.js";import"./chunk-HI7W3IVO.js";import"./chunk-W3NG7YLC.js";import"./chunk-6KKQXETR.js";import"./chunk-L3KS6MOV.js";import"./chunk-XMKAMR7M.js";import"./chunk-3D4QN4NM.js";import"./chunk-6MI4KKWF.js";import"./chunk-VG7XO6PR.js";import"./chunk-7R7O2XXP.js";import"./chunk-Z3D4C7BG.js";import"./chunk-DGD52VZC.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-ALZRXBEC.js";import"./chunk-MTJNKRXL.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as resolveWebLaunchMessages,c as runOpenPondAppServerCli,b as runOpenPondServerCli};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as f}from"./chunk-
|
|
2
|
+
import{a as f}from"./chunk-6UPCR6EL.js";import"./chunk-SXN3QOW4.js";import"./chunk-3M53YXEI.js";import{H as J,W as N,X as q,_ as k,aa as A,b as d,ba as B,c as w,e as b,ea as H,fa as I,na as E,oa as M,p as C,pa as T,r as m,s as j,t as x,u as F,v,w as P}from"./chunk-ALZRXBEC.js";import"./chunk-MTJNKRXL.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{d as O,f as S,h as g}from"./chunk-H7IWJN7L.js";import{a as l}from"./chunk-FTQLQJQV.js";import R from"node:path";import{readFile as p}from"node:fs/promises";var n=l((t,s)=>typeof t[s]=="string"?t[s]:void 0,"stringOption");function a(t){console.log(JSON.stringify(t,null,2))}l(a,"print");function U(t,s){let i=n(t,"keyPath");if(i){let r=JSON.parse(i);if(Array.isArray(r)&&r.length&&r.every(c=>typeof c=="string"&&c.length))return r;throw new f("--key-path must be a JSON array of key segments.")}if(!s)throw new f("Specify a setting key, or --key-path for keys containing dots.");return s.split(".")}l(U,"keyPath");async function G(t,s){let i=S({home:n(t,"home")}),r=s[0]??"get",c=g(i).config;if(r==="path"){console.log(c);return}if(r==="export"){let e=await T(i),o=n(t,"file");o?(await b(R.resolve(o),JSON.stringify(e,null,2),{privateParent:!1}),a({path:R.resolve(o),requiresRebinding:e.requiresRebinding})):a(e);return}if(r==="backup"||r==="restore"){let e=n(t,"file"),o=n(t,"keyFile");if(!e||!o)throw new f(`config ${r} requires --file <encrypted-backup> and --key-file <separate-32-byte-key-file>.`);let u=await p(o),y=u.length===32?u:Buffer.from(u.toString("utf8").trim(),"base64");try{a(r==="backup"?await E(i,e,y):await M(e,i,y))}finally{y.fill(0),u.fill(0)}return}if(r==="collect-orphans"){a(await N(i));return}if(r==="schema"){a(F());return}if(r==="migrate"){let e=n(t,"resolutionFile"),o=e?q.parse(JSON.parse(await p(e,"utf8"))):void 0;a(await k(i,{resolutions:o,sourceAppHome:n(t,"sourceAppHome"),sourceConfig:n(t,"sourceConfig"),sourceBrowserState:n(t,"sourceBrowserState"),dryRun:t.dryRun===!0||t.dryRun==="true"}));return}if(r==="recover"){let e=n(t,"revision");a(e?await x(i,e,n(t,"expectedRevision")??d(await w(c))):await A(i));return}if(r==="restart-migration"){a(await B(i));return}if(r==="effective"){a(await I(i,{projectRoot:n(t,"projectRoot"),accountId:n(t,"accountId")}));return}if(r==="trust"||r==="untrust"){let e=n(t,"projectRoot")??s[1];if(!e)throw new f("Specify the canonical project root with --project-root.");await H(i,e,n(t,"accountId")??"local",r==="trust"),a({root:e,trusted:r==="trust"});return}if(r==="revisions"){a(await m(i));return}if(r==="validate"){let e=n(t,"file")??c;C(await p(e,"utf8"),e,t.project===!0||t.project==="true"?"project":"user"),a({valid:!0,path:e});return}if(r==="replace"){let e=n(t,"file");if(!e)throw new f("config replace requires --file <validated-toml-file>.");a(await j(i,n(t,"expectedRevision")??d(await w(c)),await p(e,"utf8")));return}if(r==="doctor"){let e=await w(c),o=null;try{await v(i)}catch(u){o=O(u,c)}a({home:i,path:c,rawRevision:d(e),issue:o,recoverableRevisions:await m(i),migration:await w(R.join(g(i).runtime,"migration.json"))!==null}),o&&(process.exitCode=1);return}if(await k(i),r==="clear-cache"){await J(i),a({cleared:!0,path:g(i).cache});return}let h=await v(i);if(r==="get"){if(!s[1]&&!t.keyPath){a(h);return}let e=h.document;for(let o of U(t,s[1]))e=e&&typeof e=="object"?e[o]:void 0;a(e??null);return}if(r==="set"||r==="unset"){let e=U(t,s[1]),o;if(r==="set"){let u=n(t,"value")??s[2];if(u===void 0)throw new f("config set requires a value. Use JSON for arrays, tables, numbers and booleans.");try{o=JSON.parse(u)}catch{o=u}}a(await P(i,n(t,"expectedRevision")??h.rawRevision,[r==="set"?{op:"set",path:e,value:o}:{op:"unset",path:e}]));return}throw new f(`Unknown config command: ${r}`)}l(G,"runConfigurationCommand");export{G as runConfigurationCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-IE2WZ3I3.js";import"./chunk-B3O2GAQH.js";import"./chunk-65BW2QXY.js";import"./chunk-BSHAIAXY.js";import"./chunk-6UPCR6EL.js";import"./chunk-SXN3QOW4.js";import"./chunk-XWPC3AN4.js";import"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-IFI24VF6.js";import"./chunk-Z2BYC6TP.js";import"./chunk-DXAZUJPA.js";import"./chunk-GLUWATL5.js";import"./chunk-5IN3HQJU.js";import"./chunk-7R7O2XXP.js";import"./chunk-Z3D4C7BG.js";import"./chunk-DGD52VZC.js";import"./chunk-QUNRWDVO.js";import"./chunk-ALZRXBEC.js";import"./chunk-MTJNKRXL.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{m as resolveGitBranch,f as runAccount,j as runBacktestRun,p as runCheckUpdate,k as runDeployWatch,g as runHealth,d as runLogin,o as runOpentool,e as runProfiles,l as runRepoCreate,n as runRepoPush,b as runTemplateBranches,a as runTemplateStatus,c as runTemplateUpdate,h as runToolList,i as runToolRun};
|