openpond 0.2.68 → 0.2.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/account-context-V3KLSNKS.js +12 -0
  3. package/dist/chunks/{acp-2OIXATRY.js → acp-ER6CUXG2.js} +1 -1
  4. package/dist/chunks/{acp-agent-PAGX2B47.js → acp-agent-AYJ5RPVF.js} +1 -1
  5. package/dist/chunks/{actions-command-2VE6YI4W.js → actions-command-BBUS3HDK.js} +1 -1
  6. package/dist/chunks/{app-layer-YNEUEOEP.js → app-layer-JCEWGUDH.js} +1 -1
  7. package/dist/chunks/{app-server-connected-apps-TZOAUOYR.js → app-server-connected-apps-ILXBFD3S.js} +1 -1
  8. package/dist/chunks/{app-server-runtime-GBX65JJ7.js → app-server-runtime-43MCH5SY.js} +1 -1
  9. package/dist/chunks/{apps-RSFEJOQN.js → apps-VNFGMQFG.js} +1 -1
  10. package/dist/chunks/{chunk-DWM5G7BU.js → chunk-22RLEU3Q.js} +1 -1
  11. package/dist/chunks/chunk-7EQLW2KM.js +12 -0
  12. package/dist/chunks/chunk-BDZDWHBJ.js +6 -0
  13. package/dist/chunks/{chunk-GEYZVOGD.js → chunk-EWDDDHJN.js} +1 -1
  14. package/dist/chunks/{chunk-XQAUHXL4.js → chunk-G4FRBT7G.js} +2 -2
  15. package/dist/chunks/{chunk-FKUWCJ73.js → chunk-LSKMALD6.js} +1 -1
  16. package/dist/chunks/chunk-M5X7XKXY.js +12 -0
  17. package/dist/chunks/{chunk-OIH2LPIT.js → chunk-NW6WGGSL.js} +1 -1
  18. package/dist/chunks/{chunk-JPUSTFZC.js → chunk-NZDLL6JN.js} +1 -1
  19. package/dist/chunks/{chunk-RBTDSI4L.js → chunk-R6I623SZ.js} +6 -6
  20. package/dist/chunks/{chunk-MEJLWNRS.js → chunk-RCRZXHAI.js} +1 -1
  21. package/dist/chunks/{chunk-BHKXPWFB.js → chunk-TB5P3FWM.js} +1 -1
  22. package/dist/chunks/{chunk-73TW6BKK.js → chunk-Z5CQXPIS.js} +1 -1
  23. package/dist/chunks/{configuration-command-CNITTZRP.js → configuration-command-C3QBDFND.js} +1 -1
  24. package/dist/chunks/{connected-app-executor-FGWCLOJO.js → connected-app-executor-LAEAQUJS.js} +1 -1
  25. package/dist/chunks/{connected-evidence-5VZBYNWN.js → connected-evidence-VKY6O2JW.js} +1 -1
  26. package/dist/chunks/{connected-starting-assets-KWOFEIE4.js → connected-starting-assets-5LAJ7CZY.js} +1 -1
  27. package/dist/chunks/{core-commands-BPYXVT7O.js → core-commands-5TNBVR72.js} +1 -1
  28. package/dist/chunks/{datasets-E5TXSVIY.js → datasets-BIDZJYDC.js} +1 -1
  29. package/dist/chunks/{desktop-test-FX7DTY4N.js → desktop-test-BY2MS3UL.js} +1 -1
  30. package/dist/chunks/{evaluation-coordination-KUTZEEPB.js → evaluation-coordination-FXB4DXZA.js} +1 -1
  31. package/dist/chunks/{experiment-improvements-PQNR5YHN.js → experiment-improvements-JPDLKZXD.js} +1 -1
  32. package/dist/chunks/{experiments-Z4BJWT3Y.js → experiments-IEN7RXLX.js} +1 -1
  33. package/dist/chunks/{experiments-signal-3GCLKUWZ.js → experiments-signal-L32D36NH.js} +1 -1
  34. package/dist/chunks/{help-K6YLZ3KL.js → help-PLQJOP4P.js} +1 -1
  35. package/dist/chunks/{hosted-app-server-composition-LA3BZ4SE.js → hosted-app-server-composition-GZES7QXJ.js} +1 -1
  36. package/dist/chunks/{hosted-tasksets-NXVF4AQA.js → hosted-tasksets-V24IBVJX.js} +1 -1
  37. package/dist/chunks/{human-review-2ZOB7CJZ.js → human-review-6V6EMNVN.js} +1 -1
  38. package/dist/chunks/{import-YHYKZ6JN.js → import-SI24Z7EF.js} +1 -1
  39. package/dist/chunks/{opchat-XXI2ZM53.js → opchat-SV67HVMX.js} +1 -1
  40. package/dist/chunks/{opchat-bounded-chat-3MZGCRLY.js → opchat-bounded-chat-KLMIYSZZ.js} +1 -1
  41. package/dist/chunks/{organizations-W7HI2JA4.js → organizations-OZZFX7RG.js} +1 -1
  42. package/dist/chunks/{profile-P2SJPBOJ.js → profile-TD5U3INY.js} +1 -1
  43. package/dist/chunks/{project-action-payload-LTIQBX77.js → project-action-payload-TK6G4VMC.js} +1 -1
  44. package/dist/chunks/{project-agent-XRIXMXQK.js → project-agent-FFXPNXCO.js} +1 -1
  45. package/dist/chunks/sandbox-command-4BCUDAED.js +2 -0
  46. package/dist/chunks/{sandbox-template-U536EEWY.js → sandbox-template-GOY7QQUY.js} +1 -1
  47. package/dist/chunks/{saved-work-KSIQPXC2.js → saved-work-M6PUHKCC.js} +1 -1
  48. package/dist/chunks/{src-SGQYVBNQ.js → src-MT4B43TD.js} +1 -1
  49. package/dist/chunks/{teams-bot-MPWL2PP4.js → teams-bot-YCUTDDDC.js} +1 -1
  50. package/dist/cli.js +1 -1
  51. package/dist/index.js +1 -1
  52. package/dist/sandbox/runtime-handle.d.ts +3 -5
  53. package/dist/sandbox/sandbox-instance-client.d.ts +11 -5
  54. package/dist/sandbox/types/billing.d.ts +53 -0
  55. package/dist/sandbox/types/responses.d.ts +11 -1
  56. package/dist/sandbox/types/snapshots.d.ts +52 -3
  57. package/dist/skills/manifest.json +1 -1
  58. package/docs/command-reference.md +11 -0
  59. package/package.json +1 -1
  60. package/dist/chunks/account-context-MWB6HN6I.js +0 -12
  61. package/dist/chunks/chunk-27JGS3KB.js +0 -12
  62. package/dist/chunks/chunk-DRTHKWHK.js +0 -6
  63. package/dist/chunks/chunk-KOC3YJEU.js +0 -12
  64. package/dist/chunks/sandbox-command-HVA5FJU4.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as gc,b as hc,c as gi,d as hi}from"./chunk-B66QCXH2.js";import{A as Kd,B as Vd,C as po,D as Jd,E as di,F as Gd,G as Xd,H as Qd,I as Yd,J as Zd,K as ec,L as ci,N as bc,d as vd,e as yd,f as kd,g as Sd,h as Id,i as Rd,j as xd,k as Sr,l as ii,m as ai,n as Nd,o as jd,p as Fd,q as li,r as qd,s as $d,t as Hd,u as Dd,w as Tr,y as zd,z as uo}from"./chunk-MOXIGLN2.js";import{a as kc,b as yt,c as Sc,d as ln}from"./chunk-RHMULF56.js";import{b as wc}from"./chunk-UOFDKMRU.js";import{b as pt,c as Md,d as si}from"./chunk-AN525SPP.js";import{k as yr}from"./chunk-KOC3YJEU.js";import{A as mi,C as lc,F as mc,G as fc,I as Lt,K as Gn,b as Ul,c as zl,e as kr,f as md,p as Tn,r as gd,t as hd,u as wd,w as Td,x as Pd,y as Bd,z as Vn}from"./chunk-6I5AUTVO.js";import{f as fd}from"./chunk-DKOVZ6R2.js";import{a as yc}from"./chunk-N73MU2C3.js";import{E as sc,F as ic,I as pi,N as an,O as ac,c as Wd,d as Ir,e as Rr,f as xr,g as Jn,h as Ud,j as tc,k as ui,l as nc,q as rc}from"./chunk-WZ35ICTE.js";import{a as Ld}from"./chunk-DMFUEUAZ.js";import{a as Pr,d as oc,e as Cr}from"./chunk-GF55VEMR.js";import{a as cc,b as uc,d as pc}from"./chunk-FAKDGLZQ.js";import{c as vc}from"./chunk-GW766ZSO.js";import{c as mo,e as dc,f as fo}from"./chunk-VJYOKU3C.js";import{a as bd}from"./chunk-7KWD2I6W.js";import{a as oi,c as pd,i as Kn}from"./chunk-RY46UPBO.js";import{B as Ll}from"./chunk-OFJPOTES.js";import{d as ri,k as Od}from"./chunk-PLROXHG2.js";import{B as Ed,b as Z,j as Cd,s as _d,t as Ad}from"./chunk-YU3C6U5V.js";import{h as fi}from"./chunk-PHZZBXDO.js";import{a as co}from"./chunk-KVTBX2UP.js";import{a as Y,b as se,d as L}from"./chunk-U7D6Q744.js";import{$ as wr,Ec as vr,Gc as ni,Hc as ud,Jb as br,K as td,M as Xs,Mb as id,Nb as Zs,Ob as ad,P as Dt,Pb as ld,Sb as zn,T as nd,Tb as vt,Ub as dd,c as Yl,d as Zl,g as ed,ha as od,ia as ge,ib as Ys,ja as sn,jc as ei,kc as lo,lc as cd,ma as rd,na as ct,oc as ti,pc as ut,qa as Qs,ra as sd,u as rn}from"./chunk-HG2YFMVU.js";import{a as Fl,c as ql,g as $l,h as Hl,k as Bs,m as Dl,n as Ws}from"./chunk-OQPJ7FJF.js";import{df as Ql}from"./chunk-VEBW7NKD.js";import{A as Vl,D as Gs,E as Jl,F as Gl,G as Xl,s as Ks,y as Js}from"./chunk-4BUM6JEC.js";import{b as hr,c as Vs}from"./chunk-SSHE6B7Z.js";import{j as Ht}from"./chunk-DXJC3QW7.js";import{G as zs}from"./chunk-OKKNDQJF.js";import{X as Kl,x as gr}from"./chunk-ZY32SZ2P.js";import{c as fr,e as jl,m as Us,n as Bl,o as Wl}from"./chunk-KUE46HTH.js";import{C as Tl,E as Al,F as El,c as io,e as ml,f as ar,fa as Ol,ha as Ml,ia as Nl,v as ur,x as pr}from"./chunk-SV7ZBEK2.js";import{A as kl,B as Rn,C as xn,E as lr,I as Ls,J as Sl,L as Il,O as dr,V as Rl,W as cr,X as ao,Z as xl,c as hl,f as wl,h as bl,j as vl,w as yl,y as et,z as ye}from"./chunk-2MEOUS24.js";import{e as fl,f as gl}from"./chunk-HNQPEOJD.js";import{l as Ds,m as In,n as Ue}from"./chunk-RCT3O3HQ.js";import{b as ul,c as Un,e as pl,f as on,h as Sn,i as Hs,r as Pl,s as Cl,t as mr,u as _l}from"./chunk-UGOK7VTC.js";import{A as P}from"./chunk-X2J2P5ZT.js";import{a as r}from"./chunk-FTQLQJQV.js";function Ic(e){let t,n,o=new Set;function s(i){if(n)return Promise.reject(new Error("Runtime service is closing"));t??=Promise.resolve().then(e);let a=t.then(l=>{if(n)throw new Error("Runtime service is closing");return i(l)});return o.add(a),a.then(()=>o.delete(a),()=>o.delete(a)),a}return r(s,"use"),{use:s,methods(i){return Object.fromEntries(i.map(a=>[a,(...l)=>s(u=>u[a].apply(u,l))]))},close(){return n??=Promise.resolve().then(async()=>{try{await(await t?.catch(()=>{}))?.close()}finally{await Promise.allSettled([...o])}})}}}r(Ic,"lazyRuntimeService");function xc(e){let t=Hg();for(let n of e)t.accept(n);return t.values()}r(xc,"activeFileOutputRefs");function Hg(e=Number.POSITIVE_INFINITY){let t=new Map,n=new Set;function o(s){let i=Pn(s.data);if(t.size+n.size+i.length>e)throw new Error("remote_output_reference_limit");if(s.action==="work_output_delete"&&s.status==="completed"){for(let a of i){let l=Rc(a);n.add(l),t.delete(l)}return}if(s.action!=="work_output_read")for(let a of i){let l=Rc(a);n.has(l)||t.set(l,a)}}return r(o,"accept"),{accept:o,values:r(()=>[...t.values()],"values")}}r(Hg,"createOutputReferenceAccumulator");function Rc(e){return`${e.sourceTaskId}:${e.id}:${e.revision}`}r(Rc,"fileOutputRevisionKey");function Pn(e,t=0){if(t>8||e==null)return[];let n=sn.safeParse(e);if(n.success)return[n.data];if(Array.isArray(e))return e.flatMap(s=>Pn(s,t+1));let o=Dg(e);return Object.values(o).flatMap(s=>Pn(s,t+1))}r(Pn,"fileOutputRefs");function Dg(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Dg,"asRecord");import{createHash as ho,randomUUID as Cc}from"node:crypto";import{promises as nt}from"node:fs";import Ie from"node:path";function go(e){return!!(e.experience==="work"&&!e.workspaceKind&&!e.localProjectId&&!e.cloudProjectId&&e.metadata?.workspaceTarget==="local"&&e.cwd)}r(go,"isManagedLocalWorkSession");function pS(e){let t=Ie.join(e.storeDir,"work","outputs"),n=e.sandboxRequest??yr;async function o(m){let w=_r(m.suggestedName);if(m.bytes.byteLength>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let C=Qs[Ie.extname(w).toLowerCase()];if(!C)throw new Error(`${w} is not an advertised Work output format. Save it as a supported file type or keep it in scratch space.`);let S=Ug({bytes:m.bytes,contentType:C,title:w,supplied:m.validation,policy:m.validationPolicy}),R=await Tc({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:m.session.id,title:w,...e.managedPersistence?{firstId:`hosted-${ho("sha256").update(`${m.session.id}\0${w}`).digest("hex")}`}:{}});if(e.managedPersistence){let b=await e.managedPersistence.sourceTurnStartedAt(m.session.id,m.sourceTurnId),f={id:R.id,title:w,contentType:C,sizeBytes:m.bytes.byteLength,sha256:ho("sha256").update(m.bytes).digest("hex"),sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:R.revision,createdAt:new Date(b).toISOString(),validation:S};return e.managedPersistence.save({sessionId:m.session.id,turnId:m.sourceTurnId,identity:f,bytes:m.bytes})}let g=Ie.join(t,Ar(m.session.id));await nt.mkdir(g,{recursive:!0,mode:448});let d=Ie.join(g,`${String(R.revision).padStart(3,"0")}-${Ar(R.id)}-${w}`),k=Ie.join(g,`.${Ie.basename(d)}.${Cc()}.tmp`);await nt.writeFile(k,m.bytes,{mode:384,flag:"wx"});try{await nt.rename(k,d)}catch(b){throw await nt.rm(k,{force:!0}),b}return{outputRef:sn.parse({kind:"file",id:R.id,title:w,contentType:C,sizeBytes:m.bytes.byteLength,sha256:ho("sha256").update(m.bytes).digest("hex"),sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:R.revision,createdAt:new Date().toISOString(),location:{kind:"local",path:d,deviceId:e.deviceId},validation:S}),artifact:{artifactRef:d,path:d,title:w,contentType:C,sizeBytes:m.bytes.byteLength}}}r(o,"persistWorkOutputBytes");async function s(m){if(m.session.experience!=="work")throw new Error("Only Work tasks can save Work outputs.");if(m.session.workspaceKind!=="sandbox"||!m.session.workspaceId)throw new Error("A running Work sandbox is required to save an output.");let w=Jg(m.sandboxPath),C=Xn(await n({type:"download_file",sandboxId:m.session.workspaceId,payload:{path:w,maxBytes:ct}})),S=Xn(C.file);if(S.truncated===!0)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let R=typeof S.contentsBase64=="string"?S.contentsBase64:"";if(!R)throw new Error("Sandbox output download did not return file contents.");let g=Buffer.from(R,"base64"),d=Pc(S.totalSizeBytes)??Pc(S.sizeBytes);if(g.byteLength>ct||d!==null&&d>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);if(d!==null&&g.byteLength!==d)throw new Error("Sandbox output download was incomplete.");return o({session:m.session,sourceTurnId:m.sourceTurnId,suggestedName:m.suggestedName||Ie.posix.basename(w),bytes:g,validation:m.validation??[],validationPolicy:m.validationPolicy??"strict"})}r(s,"saveWorkOutput");async function i(m){if(!go(m.session)||!m.session.cwd)throw new Error("A managed local Work task is required to save a local output.");let w=await nt.realpath(m.session.cwd),C=Ie.isAbsolute(m.localPath)?Ie.resolve(m.localPath):Ie.resolve(w,m.localPath),S=await nt.realpath(C);if(!_c(w,S))throw new Error("Local Work outputs must stay inside the managed task workspace.");let R=await nt.stat(S);if(!R.isFile())throw new Error("A local Work output must be a file.");if(R.size>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let g=await nt.readFile(S);return o({session:m.session,sourceTurnId:m.sourceTurnId,suggestedName:m.suggestedName??Ie.basename(S),bytes:g,validation:[],validationPolicy:"preserve"})}r(i,"saveLocalWorkOutput");async function a(m){if(go(m.session))return l(m);if(m.session.experience!=="work"||m.session.workspaceKind!=="sandbox"||!m.session.workspaceId)return[];let w=Xn(await n({type:"list_files",sandboxId:m.session.workspaceId,payload:{path:"outputs",recursive:!0,maxEntries:500}})),C=Array.isArray(w.files)?w.files:[],S=await e.runtimeEventsForSession(m.session.id),R=new Set(Pn(S).filter(d=>d.sourceTurnId===m.sourceTurnId).map(d=>d.title)),g=[];for(let d of C){let k=Xn(d);if(k.type!=="file"||typeof k.path!="string")continue;let v=k.path.replace(/^\/workspace\//,""),b=_r(Ie.posix.basename(v));if(!R.has(b)){if(e.managedPersistence){let f=await Tc({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:m.session.id,title:b,firstId:`hosted-${ho("sha256").update(`${m.session.id}\0${b}`).digest("hex")}`}),_=await e.managedPersistence.sourceTurnStartedAt(m.session.id,m.sourceTurnId);g.push(await e.managedPersistence.saveSandboxFile({sessionId:m.session.id,turnId:m.sourceTurnId,identity:{id:f.id,title:b,sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:f.revision,createdAt:new Date(_).toISOString(),validation:[]},sandboxPath:v}))}else g.push(await s({session:m.session,sourceTurnId:m.sourceTurnId,sandboxPath:v,suggestedName:b,validationPolicy:"preserve"}));R.add(b)}}return g}r(a,"saveAllWorkOutputs");async function l(m){if(!m.session.cwd)return[];let w=await e.runtimeEventsForSession(m.session.id),C=w.filter(d=>d.turnId===m.sourceTurnId&&d.name==="assistant.delta"&&typeof d.output=="string").map(d=>d.output??"").join(""),S=await Lg({assistantText:C,workspaceRoot:m.session.cwd,declaredPaths:m.session.metadata?.profileEvaluationRun!==void 0?P.array(Kl).max(1e3).parse(m.session.metadata.profileEvaluationOutputs??[]).map(d=>d.path):[]}),R=new Set(Pn(w).filter(d=>d.sourceTurnId===m.sourceTurnId).map(d=>d.title)),g=[];for(let d of S){let k=_r(Ie.basename(d));R.has(k)||(g.push(await i({session:m.session,sourceTurnId:m.sourceTurnId,localPath:d,suggestedName:k})),R.add(k))}return g}r(l,"saveReferencedLocalWorkOutputs");async function u(m){if(m.experience!=="work")return[];let w=await e.runtimeEventsForSession(m.id),C=new Map;for(let S of Pn(w)){if(S.location.kind!=="local")continue;let R=C.get(S.title);(!R||S.revision>R.revision)&&C.set(S.title,S)}return[...C.values()].map(S=>({localPath:S.location.kind==="local"?S.location.path:"",storageName:`${Ar(S.id)}-${_r(S.title)}`,sha256:S.sha256,sizeBytes:S.sizeBytes}))}r(u,"workInputsForSession");async function c(m){let w=await Promise.all(m.filter(C=>C.experience==="work").map(async C=>xc(await e.runtimeEventsForSession(C.id))));return rd.parse({outputs:w.flat().sort((C,S)=>S.createdAt.localeCompare(C.createdAt))})}r(c,"listWorkOutputs");async function h(m){if(m.session.experience!=="work")throw new Error("Only Work tasks can access Work outputs.");let w=m.outputId.trim();if(!w)throw new Error("A Work output id is required.");let C=await e.runtimeEventsForSession(m.session.id),S=bi(C,w,m.revision);if(!S)throw new Error("Work output not found.");return p(m.session,S)}r(h,"resolveLocalOutput");function p(m,w){if(m.experience!=="work"||w.sourceTaskId!==m.id||w.location.kind!=="local")throw new Error("This Work output is not stored on this device.");let C=Ie.resolve(t,Ar(m.id)),S=Ie.resolve(w.location.path);if(S===C||!S.startsWith(`${C}${Ie.sep}`))throw new Error("Work output path is outside managed local storage.");return{outputRef:w,target:S}}r(p,"localOutputTarget");async function y(m){let{outputRef:w,target:C}=await h(m),S=await nt.rm(C).then(()=>!0).catch(R=>{if(R.code==="ENOENT")return!1;throw R});return{outputRef:w,deleted:S}}r(y,"deleteWorkOutput");async function x(m){let{outputRef:w}=await h(m);return T(m.session,w)}r(x,"readWorkOutput");async function T(m,w){let{target:C}=p(m,w),S=await nt.stat(C);if(S.size>ct||S.size!==w.sizeBytes)throw new Error("The saved Work output no longer matches its OutputRef.");let R=await nt.readFile(C);if(R.byteLength>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let g=ho("sha256").update(R).digest("hex");if(R.byteLength!==w.sizeBytes||g!==w.sha256)throw new Error("The saved Work output no longer matches its OutputRef.");return{outputRef:w,contentsBase64:R.toString("base64")}}return r(T,"readQualifiedWorkOutput"),{outputRoot:t,deleteWorkOutput:y,listWorkOutputs:c,readWorkOutput:x,readQualifiedWorkOutput:T,saveAllWorkOutputs:a,saveLocalWorkOutput:i,saveOwnedOutputBytes:o,saveWorkOutput:s,workInputsForSession:u}}r(pS,"createWorkOutputService");async function Lg(e){let t=await nt.realpath(e.workspaceRoot),n=new Set;for(let o of[...e.declaredPaths??[],...Bg(e.assistantText)]){let s=Wg(o);if(!s)continue;let i=Ie.isAbsolute(s)?Ie.resolve(s):Ie.resolve(t,s),a;try{if(a=await nt.realpath(i),!(await nt.stat(a)).isFile())continue}catch{continue}if(_c(t,a)&&Qs[Ie.extname(a).toLowerCase()]&&(n.add(a),n.size>=100))break}return[...n]}r(Lg,"resolveReferencedLocalFiles");function Bg(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n]==="!"?n+1:n;if(e[o]!=="[")continue;let s=e.indexOf("]",o+1);if(s<0||e[s+1]!=="(")continue;let i=s+2;if(e[i]==="<"){let l=e.indexOf(">",i+1);l>=0&&e[l+1]===")"&&(t.push(e.slice(i+1,l)),n=l+1);continue}let a=0;for(let l=i;l<e.length;l+=1){let u=e[l];if(u==="\\"){l+=1;continue}if(u==="("){a+=1;continue}if(u!==")")continue;if(a>0){a-=1;continue}let c=e.slice(i,l).trim();c&&t.push(c),n=l;break}}return t}r(Bg,"markdownLinkTargets");function Wg(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!t||/^(?:https?|data|mailto):/i.test(t))return null;if(t=t.replace(/^(?:workspace|sandbox):file:/i,""),/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}else try{t=decodeURIComponent(t)}catch{}return t.replace(/:\d+(?::\d+)?$/,"")}r(Wg,"normalizeLocalFileReference");function _c(e,t){let n=Ie.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${Ie.sep}`)&&!Ie.isAbsolute(n)}r(_c,"isPathInside");function Ug(e){let t=sd(e.contentType);if(!t)return e.supplied;let n=zg(e);if(n.status!=="passed")throw new Error(`Work output failed structural validation: ${n.detail}`);let o=[n,...e.supplied],s=t.validation.flatMap(i=>i==="visual"?["visual"]:i==="playback"||i==="browser"?["test"]:[]);for(let i of s)if(!o.some(a=>a.kind===i&&a.status==="passed")){if(e.policy==="strict")throw new Error(`${e.title} requires passed ${i} validation evidence before it can be saved as a completed Work output.`);o.push({kind:i,status:"not_run",label:`${e.title} ${i} validation was not run before automatic preservation`,detail:"The file was preserved automatically at turn completion; review this revision before relying on presentation or playback quality."})}return o}r(Ug,"validateWorkOutput");function zg(e){let t=Kg(e.bytes,e.contentType);return{kind:"structural",status:t?"passed":"failed",label:`Validated ${e.title} structure`,detail:t?`Content matches ${e.contentType}.`:`Content does not match ${e.contentType}.`}}r(zg,"structuralValidation");function Kg(e,t){if(e.byteLength===0)return!1;if(t.startsWith("text/")||t==="application/json"||t==="image/svg+xml"){let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return!1}if(t==="application/json")try{JSON.parse(n)}catch{return!1}return t==="text/html"?/<(?:!doctype\s+html|html|body)\b/i.test(n):t==="image/svg+xml"?/<svg\b/i.test(n):n.trim().length>0}if(t==="application/pdf")return e.subarray(0,5).toString("ascii")==="%PDF-"&&e.subarray(Math.max(0,e.byteLength-1024)).toString("ascii").includes("%%EOF");if(t.includes("wordprocessingml")||t.includes("spreadsheetml")||t.includes("presentationml")){let n=Vg(e),o=t.includes("wordprocessingml")?"word/document.xml":t.includes("spreadsheetml")?"xl/workbook.xml":"ppt/presentation.xml";return n.has("[Content_Types].xml")&&n.has("_rels/.rels")&&n.has(o)}return t==="image/png"?e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])):t==="image/jpeg"?e[0]===255&&e[1]===216:t==="image/gif"?e.subarray(0,4).toString("ascii")==="GIF8":t==="image/webp"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WEBP":t==="image/avif"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="audio/wav"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WAVE":t==="audio/mpeg"?e.subarray(0,3).toString("ascii")==="ID3"||e[0]===255&&(e[1]&224)===224:t==="audio/mp4"||t==="video/mp4"||t==="video/quicktime"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="video/webm"?e.subarray(0,4).equals(Buffer.from([26,69,223,163])):!0}r(Kg,"structuralContentMatches");function Vg(e){let t=new Set;for(let n=0;n+46<=e.byteLength;){if(e.readUInt32LE(n)!==33639248){n+=1;continue}let o=e.readUInt16LE(n+28),s=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32),a=n+46+o+s+i;if(a>e.byteLength)return new Set;let l=e.subarray(n+46,n+46+o).toString("utf8").replaceAll("\\","/").replace(/^\/+/,"");l&&t.add(l),n=a}return t}r(Vg,"zipCentralDirectoryEntries");function Jg(e){let t=e.trim().replaceAll("\\","/");if(!t||t.startsWith("/"))throw new Error("Work output path must be relative to /workspace.");let n=Ie.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../")||!n.startsWith("outputs/")||n==="outputs/")throw new Error("Completed Work outputs must be inside /workspace/outputs.");return n}r(Jg,"normalizeOutputCandidatePath");async function Tc(e){let t=await e.runtimeEventsForSession(e.sessionId),n=null;for(let o of t){let s=wi(o.data);s?.kind!=="file"||s.title!==e.title||(!n||s.revision>n.revision)&&(n=s)}return{id:n?.id??e.firstId??Cc(),revision:(n?.revision??0)+1}}r(Tc,"nextOutputIdentity");function wi(e,t=0){if(t>6||e==null)return null;let n=sn.safeParse(e);if(n.success)return n.data;if(Array.isArray(e)){for(let s of e){let i=wi(s,t+1);if(i)return i}return null}let o=Xn(e);for(let s of Object.values(o)){let i=wi(s,t+1);if(i)return i}return null}r(wi,"findOutputRef");function bi(e,t,n,o=0){if(o>8||e==null)return null;let s=sn.safeParse(e);if(s.success&&s.data.id===t&&(n==null||s.data.revision===n))return s.data;if(Array.isArray(e)){let l=null;for(let u of e){let c=bi(u,t,n,o+1);c&&(!l||c.revision>l.revision)&&(l=c)}return l}let i=Xn(e),a=null;for(let l of Object.values(i)){let u=bi(l,t,n,o+1);u&&(!a||u.revision>a.revision)&&(a=u)}return a}r(bi,"findOutputRefById");function _r(e){let n=Ie.basename(e.trim()).replace(/[^a-zA-Z0-9._ -]+/g,"-").replace(/\s+/g," ").trim().slice(0,180);if(!n||n==="."||n==="..")throw new Error("A valid output file name is required.");return n}r(_r,"safeOutputName");function Ar(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,100)||"item"}r(Ar,"safePathSegment");function Xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Xn,"asRecord");function Pc(e){return typeof e=="number"&&Number.isFinite(e)?e:null}r(Pc,"numberValue");import{promises as Er}from"node:fs";import Gg from"node:path";async function Ac(e,t,n=Date.now()){let o=[];for(let i of await Er.readdir(e,{withFileTypes:!0})){if(!i.isFile()||!/\.log(?:\.\d+)?$/.test(i.name))continue;let a=Gg.join(e,i.name),l=await Er.lstat(a).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&o.push({file:a,size:l.size,modified:l.mtimeMs})}let s=o.reduce((i,a)=>i+a.size,0);for(let i of o.sort((a,l)=>a.modified-l.modified)){if(i.file===t||i.modified>=n-14*864e5&&s<=256*1024*1024)continue;let a=await Er.lstat(i.file).catch(()=>null);a?.isFile()&&a.size===i.size&&a.mtimeMs===i.modified&&(await Er.rm(i.file,{force:!0}),s-=i.size)}}r(Ac,"pruneLogs");import{promises as wo}from"node:fs";import Xg from"node:path";var Ec=1024*1024,Qg=5,vi=/authorization|api[_-]?key|token|session[_-]?token|secret|password/i,Yg=/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,Zg=/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi;function eh(e){return{name:e.name,message:e.message,stack:e.stack}}r(eh,"serializeError");function Or(e){if(e instanceof Error)return Or(eh(e));if(typeof e=="string")return th(e);if(Array.isArray(e))return e.map(n=>Or(n));if(!e||typeof e!="object")return e;let t={};for(let[n,o]of Object.entries(e))t[n]=vi.test(n)?"[REDACTED]":Or(o);return t}r(Or,"redact");async function Oc(e,t){try{await wo.rm(t,{force:!0}),await wo.rename(e,t)}catch(n){if(n.code!=="ENOENT")throw n}}r(Oc,"renameIfExists");function th(e){return e.replace(Yg,"Bearer [REDACTED]").replace(Zg,t=>nh(t))}r(th,"redactString");function nh(e){let{url:t,suffix:n}=oh(e);try{let o=new URL(t);return(o.username||o.password)&&(o.username="[REDACTED]",o.password="[REDACTED]"),Mc(o.searchParams),o.hash&&(o.hash=rh(o.hash.slice(1))),`${o.toString()}${n}`}catch{return e}}r(nh,"redactUrl");function oh(e){let t=e,n="";for(;/[),.;!?]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{url:t,suffix:n}}r(oh,"splitUrlSuffix");function Mc(e){for(let t of Array.from(e.keys()))vi.test(t)&&e.set(t,"[REDACTED]")}r(Mc,"redactSearchParams");function rh(e){if(!e.includes("="))return vi.test(e)?"[REDACTED]":e;let t=new URLSearchParams(e.startsWith("?")?e.slice(1):e);return Mc(t),t.toString()}r(rh,"redactHash");function SS(e){let t=e.maxBytes??Ec,n=e.maxFiles??Qg,o=Xg.join(e.logDir,e.filename??`${e.channel}.log`),s=Promise.resolve(),i=0;async function a(u){let c=0;try{c=(await wo.stat(o)).size}catch(h){if(h.code!=="ENOENT")throw h}if(!(c+u<=t)){for(let h=n-1;h>=1;h-=1)await Oc(`${o}.${h}`,`${o}.${h+1}`);await Oc(o,`${o}.1`)}}r(a,"rotateIfNeeded");function l(u,c,h={}){let p={ts:new Date().toISOString(),level:u,channel:e.channel,message:c,pid:process.pid,platform:process.platform,...e.metadata??{},...h},y=`${JSON.stringify(Or(p))}
2
+ import{a as gc,b as hc,c as gi,d as hi}from"./chunk-B66QCXH2.js";import{A as Kd,B as Vd,C as po,D as Jd,E as di,F as Gd,G as Xd,H as Qd,I as Yd,J as Zd,K as ec,L as ci,N as bc,d as vd,e as yd,f as kd,g as Sd,h as Id,i as Rd,j as xd,k as Sr,l as ii,m as ai,n as Nd,o as jd,p as Fd,q as li,r as qd,s as $d,t as Hd,u as Dd,w as Tr,y as zd,z as uo}from"./chunk-MOXIGLN2.js";import{a as kc,b as yt,c as Sc,d as ln}from"./chunk-RHMULF56.js";import{b as wc}from"./chunk-UOFDKMRU.js";import{b as pt,c as Md,d as si}from"./chunk-AN525SPP.js";import{k as yr}from"./chunk-M5X7XKXY.js";import{A as mi,C as lc,F as mc,G as fc,I as Lt,K as Gn,b as Ul,c as zl,e as kr,f as md,p as Tn,r as gd,t as hd,u as wd,w as Td,x as Pd,y as Bd,z as Vn}from"./chunk-6I5AUTVO.js";import{f as fd}from"./chunk-DKOVZ6R2.js";import{a as yc}from"./chunk-N73MU2C3.js";import{E as sc,F as ic,I as pi,N as an,O as ac,c as Wd,d as Ir,e as Rr,f as xr,g as Jn,h as Ud,j as tc,k as ui,l as nc,q as rc}from"./chunk-WZ35ICTE.js";import{a as Ld}from"./chunk-DMFUEUAZ.js";import{a as Pr,d as oc,e as Cr}from"./chunk-GF55VEMR.js";import{a as cc,b as uc,d as pc}from"./chunk-FAKDGLZQ.js";import{c as vc}from"./chunk-GW766ZSO.js";import{c as mo,e as dc,f as fo}from"./chunk-VJYOKU3C.js";import{a as bd}from"./chunk-7KWD2I6W.js";import{a as oi,c as pd,i as Kn}from"./chunk-RY46UPBO.js";import{B as Ll}from"./chunk-OFJPOTES.js";import{d as ri,k as Od}from"./chunk-PLROXHG2.js";import{B as Ed,b as Z,j as Cd,s as _d,t as Ad}from"./chunk-YU3C6U5V.js";import{h as fi}from"./chunk-PHZZBXDO.js";import{a as co}from"./chunk-KVTBX2UP.js";import{a as Y,b as se,d as L}from"./chunk-U7D6Q744.js";import{$ as wr,Ec as vr,Gc as ni,Hc as ud,Jb as br,K as td,M as Xs,Mb as id,Nb as Zs,Ob as ad,P as Dt,Pb as ld,Sb as zn,T as nd,Tb as vt,Ub as dd,c as Yl,d as Zl,g as ed,ha as od,ia as ge,ib as Ys,ja as sn,jc as ei,kc as lo,lc as cd,ma as rd,na as ct,oc as ti,pc as ut,qa as Qs,ra as sd,u as rn}from"./chunk-HG2YFMVU.js";import{a as Fl,c as ql,g as $l,h as Hl,k as Bs,m as Dl,n as Ws}from"./chunk-OQPJ7FJF.js";import{df as Ql}from"./chunk-VEBW7NKD.js";import{A as Vl,D as Gs,E as Jl,F as Gl,G as Xl,s as Ks,y as Js}from"./chunk-4BUM6JEC.js";import{b as hr,c as Vs}from"./chunk-SSHE6B7Z.js";import{j as Ht}from"./chunk-DXJC3QW7.js";import{G as zs}from"./chunk-OKKNDQJF.js";import{X as Kl,x as gr}from"./chunk-ZY32SZ2P.js";import{c as fr,e as jl,m as Us,n as Bl,o as Wl}from"./chunk-KUE46HTH.js";import{C as Tl,E as Al,F as El,c as io,e as ml,f as ar,fa as Ol,ha as Ml,ia as Nl,v as ur,x as pr}from"./chunk-SV7ZBEK2.js";import{A as kl,B as Rn,C as xn,E as lr,I as Ls,J as Sl,L as Il,O as dr,V as Rl,W as cr,X as ao,Z as xl,c as hl,f as wl,h as bl,j as vl,w as yl,y as et,z as ye}from"./chunk-2MEOUS24.js";import{e as fl,f as gl}from"./chunk-HNQPEOJD.js";import{l as Ds,m as In,n as Ue}from"./chunk-RCT3O3HQ.js";import{b as ul,c as Un,e as pl,f as on,h as Sn,i as Hs,r as Pl,s as Cl,t as mr,u as _l}from"./chunk-UGOK7VTC.js";import{A as P}from"./chunk-X2J2P5ZT.js";import{a as r}from"./chunk-FTQLQJQV.js";function Ic(e){let t,n,o=new Set;function s(i){if(n)return Promise.reject(new Error("Runtime service is closing"));t??=Promise.resolve().then(e);let a=t.then(l=>{if(n)throw new Error("Runtime service is closing");return i(l)});return o.add(a),a.then(()=>o.delete(a),()=>o.delete(a)),a}return r(s,"use"),{use:s,methods(i){return Object.fromEntries(i.map(a=>[a,(...l)=>s(u=>u[a].apply(u,l))]))},close(){return n??=Promise.resolve().then(async()=>{try{await(await t?.catch(()=>{}))?.close()}finally{await Promise.allSettled([...o])}})}}}r(Ic,"lazyRuntimeService");function xc(e){let t=Hg();for(let n of e)t.accept(n);return t.values()}r(xc,"activeFileOutputRefs");function Hg(e=Number.POSITIVE_INFINITY){let t=new Map,n=new Set;function o(s){let i=Pn(s.data);if(t.size+n.size+i.length>e)throw new Error("remote_output_reference_limit");if(s.action==="work_output_delete"&&s.status==="completed"){for(let a of i){let l=Rc(a);n.add(l),t.delete(l)}return}if(s.action!=="work_output_read")for(let a of i){let l=Rc(a);n.has(l)||t.set(l,a)}}return r(o,"accept"),{accept:o,values:r(()=>[...t.values()],"values")}}r(Hg,"createOutputReferenceAccumulator");function Rc(e){return`${e.sourceTaskId}:${e.id}:${e.revision}`}r(Rc,"fileOutputRevisionKey");function Pn(e,t=0){if(t>8||e==null)return[];let n=sn.safeParse(e);if(n.success)return[n.data];if(Array.isArray(e))return e.flatMap(s=>Pn(s,t+1));let o=Dg(e);return Object.values(o).flatMap(s=>Pn(s,t+1))}r(Pn,"fileOutputRefs");function Dg(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Dg,"asRecord");import{createHash as ho,randomUUID as Cc}from"node:crypto";import{promises as nt}from"node:fs";import Ie from"node:path";function go(e){return!!(e.experience==="work"&&!e.workspaceKind&&!e.localProjectId&&!e.cloudProjectId&&e.metadata?.workspaceTarget==="local"&&e.cwd)}r(go,"isManagedLocalWorkSession");function pS(e){let t=Ie.join(e.storeDir,"work","outputs"),n=e.sandboxRequest??yr;async function o(m){let w=_r(m.suggestedName);if(m.bytes.byteLength>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let C=Qs[Ie.extname(w).toLowerCase()];if(!C)throw new Error(`${w} is not an advertised Work output format. Save it as a supported file type or keep it in scratch space.`);let S=Ug({bytes:m.bytes,contentType:C,title:w,supplied:m.validation,policy:m.validationPolicy}),R=await Tc({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:m.session.id,title:w,...e.managedPersistence?{firstId:`hosted-${ho("sha256").update(`${m.session.id}\0${w}`).digest("hex")}`}:{}});if(e.managedPersistence){let b=await e.managedPersistence.sourceTurnStartedAt(m.session.id,m.sourceTurnId),f={id:R.id,title:w,contentType:C,sizeBytes:m.bytes.byteLength,sha256:ho("sha256").update(m.bytes).digest("hex"),sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:R.revision,createdAt:new Date(b).toISOString(),validation:S};return e.managedPersistence.save({sessionId:m.session.id,turnId:m.sourceTurnId,identity:f,bytes:m.bytes})}let g=Ie.join(t,Ar(m.session.id));await nt.mkdir(g,{recursive:!0,mode:448});let d=Ie.join(g,`${String(R.revision).padStart(3,"0")}-${Ar(R.id)}-${w}`),k=Ie.join(g,`.${Ie.basename(d)}.${Cc()}.tmp`);await nt.writeFile(k,m.bytes,{mode:384,flag:"wx"});try{await nt.rename(k,d)}catch(b){throw await nt.rm(k,{force:!0}),b}return{outputRef:sn.parse({kind:"file",id:R.id,title:w,contentType:C,sizeBytes:m.bytes.byteLength,sha256:ho("sha256").update(m.bytes).digest("hex"),sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:R.revision,createdAt:new Date().toISOString(),location:{kind:"local",path:d,deviceId:e.deviceId},validation:S}),artifact:{artifactRef:d,path:d,title:w,contentType:C,sizeBytes:m.bytes.byteLength}}}r(o,"persistWorkOutputBytes");async function s(m){if(m.session.experience!=="work")throw new Error("Only Work tasks can save Work outputs.");if(m.session.workspaceKind!=="sandbox"||!m.session.workspaceId)throw new Error("A running Work sandbox is required to save an output.");let w=Jg(m.sandboxPath),C=Xn(await n({type:"download_file",sandboxId:m.session.workspaceId,payload:{path:w,maxBytes:ct}})),S=Xn(C.file);if(S.truncated===!0)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let R=typeof S.contentsBase64=="string"?S.contentsBase64:"";if(!R)throw new Error("Sandbox output download did not return file contents.");let g=Buffer.from(R,"base64"),d=Pc(S.totalSizeBytes)??Pc(S.sizeBytes);if(g.byteLength>ct||d!==null&&d>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);if(d!==null&&g.byteLength!==d)throw new Error("Sandbox output download was incomplete.");return o({session:m.session,sourceTurnId:m.sourceTurnId,suggestedName:m.suggestedName||Ie.posix.basename(w),bytes:g,validation:m.validation??[],validationPolicy:m.validationPolicy??"strict"})}r(s,"saveWorkOutput");async function i(m){if(!go(m.session)||!m.session.cwd)throw new Error("A managed local Work task is required to save a local output.");let w=await nt.realpath(m.session.cwd),C=Ie.isAbsolute(m.localPath)?Ie.resolve(m.localPath):Ie.resolve(w,m.localPath),S=await nt.realpath(C);if(!_c(w,S))throw new Error("Local Work outputs must stay inside the managed task workspace.");let R=await nt.stat(S);if(!R.isFile())throw new Error("A local Work output must be a file.");if(R.size>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let g=await nt.readFile(S);return o({session:m.session,sourceTurnId:m.sourceTurnId,suggestedName:m.suggestedName??Ie.basename(S),bytes:g,validation:[],validationPolicy:"preserve"})}r(i,"saveLocalWorkOutput");async function a(m){if(go(m.session))return l(m);if(m.session.experience!=="work"||m.session.workspaceKind!=="sandbox"||!m.session.workspaceId)return[];let w=Xn(await n({type:"list_files",sandboxId:m.session.workspaceId,payload:{path:"outputs",recursive:!0,maxEntries:500}})),C=Array.isArray(w.files)?w.files:[],S=await e.runtimeEventsForSession(m.session.id),R=new Set(Pn(S).filter(d=>d.sourceTurnId===m.sourceTurnId).map(d=>d.title)),g=[];for(let d of C){let k=Xn(d);if(k.type!=="file"||typeof k.path!="string")continue;let v=k.path.replace(/^\/workspace\//,""),b=_r(Ie.posix.basename(v));if(!R.has(b)){if(e.managedPersistence){let f=await Tc({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:m.session.id,title:b,firstId:`hosted-${ho("sha256").update(`${m.session.id}\0${b}`).digest("hex")}`}),_=await e.managedPersistence.sourceTurnStartedAt(m.session.id,m.sourceTurnId);g.push(await e.managedPersistence.saveSandboxFile({sessionId:m.session.id,turnId:m.sourceTurnId,identity:{id:f.id,title:b,sourceTaskId:m.session.id,sourceTurnId:m.sourceTurnId,revision:f.revision,createdAt:new Date(_).toISOString(),validation:[]},sandboxPath:v}))}else g.push(await s({session:m.session,sourceTurnId:m.sourceTurnId,sandboxPath:v,suggestedName:b,validationPolicy:"preserve"}));R.add(b)}}return g}r(a,"saveAllWorkOutputs");async function l(m){if(!m.session.cwd)return[];let w=await e.runtimeEventsForSession(m.session.id),C=w.filter(d=>d.turnId===m.sourceTurnId&&d.name==="assistant.delta"&&typeof d.output=="string").map(d=>d.output??"").join(""),S=await Lg({assistantText:C,workspaceRoot:m.session.cwd,declaredPaths:m.session.metadata?.profileEvaluationRun!==void 0?P.array(Kl).max(1e3).parse(m.session.metadata.profileEvaluationOutputs??[]).map(d=>d.path):[]}),R=new Set(Pn(w).filter(d=>d.sourceTurnId===m.sourceTurnId).map(d=>d.title)),g=[];for(let d of S){let k=_r(Ie.basename(d));R.has(k)||(g.push(await i({session:m.session,sourceTurnId:m.sourceTurnId,localPath:d,suggestedName:k})),R.add(k))}return g}r(l,"saveReferencedLocalWorkOutputs");async function u(m){if(m.experience!=="work")return[];let w=await e.runtimeEventsForSession(m.id),C=new Map;for(let S of Pn(w)){if(S.location.kind!=="local")continue;let R=C.get(S.title);(!R||S.revision>R.revision)&&C.set(S.title,S)}return[...C.values()].map(S=>({localPath:S.location.kind==="local"?S.location.path:"",storageName:`${Ar(S.id)}-${_r(S.title)}`,sha256:S.sha256,sizeBytes:S.sizeBytes}))}r(u,"workInputsForSession");async function c(m){let w=await Promise.all(m.filter(C=>C.experience==="work").map(async C=>xc(await e.runtimeEventsForSession(C.id))));return rd.parse({outputs:w.flat().sort((C,S)=>S.createdAt.localeCompare(C.createdAt))})}r(c,"listWorkOutputs");async function h(m){if(m.session.experience!=="work")throw new Error("Only Work tasks can access Work outputs.");let w=m.outputId.trim();if(!w)throw new Error("A Work output id is required.");let C=await e.runtimeEventsForSession(m.session.id),S=bi(C,w,m.revision);if(!S)throw new Error("Work output not found.");return p(m.session,S)}r(h,"resolveLocalOutput");function p(m,w){if(m.experience!=="work"||w.sourceTaskId!==m.id||w.location.kind!=="local")throw new Error("This Work output is not stored on this device.");let C=Ie.resolve(t,Ar(m.id)),S=Ie.resolve(w.location.path);if(S===C||!S.startsWith(`${C}${Ie.sep}`))throw new Error("Work output path is outside managed local storage.");return{outputRef:w,target:S}}r(p,"localOutputTarget");async function y(m){let{outputRef:w,target:C}=await h(m),S=await nt.rm(C).then(()=>!0).catch(R=>{if(R.code==="ENOENT")return!1;throw R});return{outputRef:w,deleted:S}}r(y,"deleteWorkOutput");async function x(m){let{outputRef:w}=await h(m);return T(m.session,w)}r(x,"readWorkOutput");async function T(m,w){let{target:C}=p(m,w),S=await nt.stat(C);if(S.size>ct||S.size!==w.sizeBytes)throw new Error("The saved Work output no longer matches its OutputRef.");let R=await nt.readFile(C);if(R.byteLength>ct)throw new Error(`Work output exceeds the ${ct.toLocaleString()} byte limit.`);let g=ho("sha256").update(R).digest("hex");if(R.byteLength!==w.sizeBytes||g!==w.sha256)throw new Error("The saved Work output no longer matches its OutputRef.");return{outputRef:w,contentsBase64:R.toString("base64")}}return r(T,"readQualifiedWorkOutput"),{outputRoot:t,deleteWorkOutput:y,listWorkOutputs:c,readWorkOutput:x,readQualifiedWorkOutput:T,saveAllWorkOutputs:a,saveLocalWorkOutput:i,saveOwnedOutputBytes:o,saveWorkOutput:s,workInputsForSession:u}}r(pS,"createWorkOutputService");async function Lg(e){let t=await nt.realpath(e.workspaceRoot),n=new Set;for(let o of[...e.declaredPaths??[],...Bg(e.assistantText)]){let s=Wg(o);if(!s)continue;let i=Ie.isAbsolute(s)?Ie.resolve(s):Ie.resolve(t,s),a;try{if(a=await nt.realpath(i),!(await nt.stat(a)).isFile())continue}catch{continue}if(_c(t,a)&&Qs[Ie.extname(a).toLowerCase()]&&(n.add(a),n.size>=100))break}return[...n]}r(Lg,"resolveReferencedLocalFiles");function Bg(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n]==="!"?n+1:n;if(e[o]!=="[")continue;let s=e.indexOf("]",o+1);if(s<0||e[s+1]!=="(")continue;let i=s+2;if(e[i]==="<"){let l=e.indexOf(">",i+1);l>=0&&e[l+1]===")"&&(t.push(e.slice(i+1,l)),n=l+1);continue}let a=0;for(let l=i;l<e.length;l+=1){let u=e[l];if(u==="\\"){l+=1;continue}if(u==="("){a+=1;continue}if(u!==")")continue;if(a>0){a-=1;continue}let c=e.slice(i,l).trim();c&&t.push(c),n=l;break}}return t}r(Bg,"markdownLinkTargets");function Wg(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!t||/^(?:https?|data|mailto):/i.test(t))return null;if(t=t.replace(/^(?:workspace|sandbox):file:/i,""),/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}else try{t=decodeURIComponent(t)}catch{}return t.replace(/:\d+(?::\d+)?$/,"")}r(Wg,"normalizeLocalFileReference");function _c(e,t){let n=Ie.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${Ie.sep}`)&&!Ie.isAbsolute(n)}r(_c,"isPathInside");function Ug(e){let t=sd(e.contentType);if(!t)return e.supplied;let n=zg(e);if(n.status!=="passed")throw new Error(`Work output failed structural validation: ${n.detail}`);let o=[n,...e.supplied],s=t.validation.flatMap(i=>i==="visual"?["visual"]:i==="playback"||i==="browser"?["test"]:[]);for(let i of s)if(!o.some(a=>a.kind===i&&a.status==="passed")){if(e.policy==="strict")throw new Error(`${e.title} requires passed ${i} validation evidence before it can be saved as a completed Work output.`);o.push({kind:i,status:"not_run",label:`${e.title} ${i} validation was not run before automatic preservation`,detail:"The file was preserved automatically at turn completion; review this revision before relying on presentation or playback quality."})}return o}r(Ug,"validateWorkOutput");function zg(e){let t=Kg(e.bytes,e.contentType);return{kind:"structural",status:t?"passed":"failed",label:`Validated ${e.title} structure`,detail:t?`Content matches ${e.contentType}.`:`Content does not match ${e.contentType}.`}}r(zg,"structuralValidation");function Kg(e,t){if(e.byteLength===0)return!1;if(t.startsWith("text/")||t==="application/json"||t==="image/svg+xml"){let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return!1}if(t==="application/json")try{JSON.parse(n)}catch{return!1}return t==="text/html"?/<(?:!doctype\s+html|html|body)\b/i.test(n):t==="image/svg+xml"?/<svg\b/i.test(n):n.trim().length>0}if(t==="application/pdf")return e.subarray(0,5).toString("ascii")==="%PDF-"&&e.subarray(Math.max(0,e.byteLength-1024)).toString("ascii").includes("%%EOF");if(t.includes("wordprocessingml")||t.includes("spreadsheetml")||t.includes("presentationml")){let n=Vg(e),o=t.includes("wordprocessingml")?"word/document.xml":t.includes("spreadsheetml")?"xl/workbook.xml":"ppt/presentation.xml";return n.has("[Content_Types].xml")&&n.has("_rels/.rels")&&n.has(o)}return t==="image/png"?e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])):t==="image/jpeg"?e[0]===255&&e[1]===216:t==="image/gif"?e.subarray(0,4).toString("ascii")==="GIF8":t==="image/webp"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WEBP":t==="image/avif"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="audio/wav"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WAVE":t==="audio/mpeg"?e.subarray(0,3).toString("ascii")==="ID3"||e[0]===255&&(e[1]&224)===224:t==="audio/mp4"||t==="video/mp4"||t==="video/quicktime"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="video/webm"?e.subarray(0,4).equals(Buffer.from([26,69,223,163])):!0}r(Kg,"structuralContentMatches");function Vg(e){let t=new Set;for(let n=0;n+46<=e.byteLength;){if(e.readUInt32LE(n)!==33639248){n+=1;continue}let o=e.readUInt16LE(n+28),s=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32),a=n+46+o+s+i;if(a>e.byteLength)return new Set;let l=e.subarray(n+46,n+46+o).toString("utf8").replaceAll("\\","/").replace(/^\/+/,"");l&&t.add(l),n=a}return t}r(Vg,"zipCentralDirectoryEntries");function Jg(e){let t=e.trim().replaceAll("\\","/");if(!t||t.startsWith("/"))throw new Error("Work output path must be relative to /workspace.");let n=Ie.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../")||!n.startsWith("outputs/")||n==="outputs/")throw new Error("Completed Work outputs must be inside /workspace/outputs.");return n}r(Jg,"normalizeOutputCandidatePath");async function Tc(e){let t=await e.runtimeEventsForSession(e.sessionId),n=null;for(let o of t){let s=wi(o.data);s?.kind!=="file"||s.title!==e.title||(!n||s.revision>n.revision)&&(n=s)}return{id:n?.id??e.firstId??Cc(),revision:(n?.revision??0)+1}}r(Tc,"nextOutputIdentity");function wi(e,t=0){if(t>6||e==null)return null;let n=sn.safeParse(e);if(n.success)return n.data;if(Array.isArray(e)){for(let s of e){let i=wi(s,t+1);if(i)return i}return null}let o=Xn(e);for(let s of Object.values(o)){let i=wi(s,t+1);if(i)return i}return null}r(wi,"findOutputRef");function bi(e,t,n,o=0){if(o>8||e==null)return null;let s=sn.safeParse(e);if(s.success&&s.data.id===t&&(n==null||s.data.revision===n))return s.data;if(Array.isArray(e)){let l=null;for(let u of e){let c=bi(u,t,n,o+1);c&&(!l||c.revision>l.revision)&&(l=c)}return l}let i=Xn(e),a=null;for(let l of Object.values(i)){let u=bi(l,t,n,o+1);u&&(!a||u.revision>a.revision)&&(a=u)}return a}r(bi,"findOutputRefById");function _r(e){let n=Ie.basename(e.trim()).replace(/[^a-zA-Z0-9._ -]+/g,"-").replace(/\s+/g," ").trim().slice(0,180);if(!n||n==="."||n==="..")throw new Error("A valid output file name is required.");return n}r(_r,"safeOutputName");function Ar(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,100)||"item"}r(Ar,"safePathSegment");function Xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Xn,"asRecord");function Pc(e){return typeof e=="number"&&Number.isFinite(e)?e:null}r(Pc,"numberValue");import{promises as Er}from"node:fs";import Gg from"node:path";async function Ac(e,t,n=Date.now()){let o=[];for(let i of await Er.readdir(e,{withFileTypes:!0})){if(!i.isFile()||!/\.log(?:\.\d+)?$/.test(i.name))continue;let a=Gg.join(e,i.name),l=await Er.lstat(a).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&o.push({file:a,size:l.size,modified:l.mtimeMs})}let s=o.reduce((i,a)=>i+a.size,0);for(let i of o.sort((a,l)=>a.modified-l.modified)){if(i.file===t||i.modified>=n-14*864e5&&s<=256*1024*1024)continue;let a=await Er.lstat(i.file).catch(()=>null);a?.isFile()&&a.size===i.size&&a.mtimeMs===i.modified&&(await Er.rm(i.file,{force:!0}),s-=i.size)}}r(Ac,"pruneLogs");import{promises as wo}from"node:fs";import Xg from"node:path";var Ec=1024*1024,Qg=5,vi=/authorization|api[_-]?key|token|session[_-]?token|secret|password/i,Yg=/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,Zg=/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi;function eh(e){return{name:e.name,message:e.message,stack:e.stack}}r(eh,"serializeError");function Or(e){if(e instanceof Error)return Or(eh(e));if(typeof e=="string")return th(e);if(Array.isArray(e))return e.map(n=>Or(n));if(!e||typeof e!="object")return e;let t={};for(let[n,o]of Object.entries(e))t[n]=vi.test(n)?"[REDACTED]":Or(o);return t}r(Or,"redact");async function Oc(e,t){try{await wo.rm(t,{force:!0}),await wo.rename(e,t)}catch(n){if(n.code!=="ENOENT")throw n}}r(Oc,"renameIfExists");function th(e){return e.replace(Yg,"Bearer [REDACTED]").replace(Zg,t=>nh(t))}r(th,"redactString");function nh(e){let{url:t,suffix:n}=oh(e);try{let o=new URL(t);return(o.username||o.password)&&(o.username="[REDACTED]",o.password="[REDACTED]"),Mc(o.searchParams),o.hash&&(o.hash=rh(o.hash.slice(1))),`${o.toString()}${n}`}catch{return e}}r(nh,"redactUrl");function oh(e){let t=e,n="";for(;/[),.;!?]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{url:t,suffix:n}}r(oh,"splitUrlSuffix");function Mc(e){for(let t of Array.from(e.keys()))vi.test(t)&&e.set(t,"[REDACTED]")}r(Mc,"redactSearchParams");function rh(e){if(!e.includes("="))return vi.test(e)?"[REDACTED]":e;let t=new URLSearchParams(e.startsWith("?")?e.slice(1):e);return Mc(t),t.toString()}r(rh,"redactHash");function SS(e){let t=e.maxBytes??Ec,n=e.maxFiles??Qg,o=Xg.join(e.logDir,e.filename??`${e.channel}.log`),s=Promise.resolve(),i=0;async function a(u){let c=0;try{c=(await wo.stat(o)).size}catch(h){if(h.code!=="ENOENT")throw h}if(!(c+u<=t)){for(let h=n-1;h>=1;h-=1)await Oc(`${o}.${h}`,`${o}.${h+1}`);await Oc(o,`${o}.1`)}}r(a,"rotateIfNeeded");function l(u,c,h={}){let p={ts:new Date().toISOString(),level:u,channel:e.channel,message:c,pid:process.pid,platform:process.platform,...e.metadata??{},...h},y=`${JSON.stringify(Or(p))}
3
3
  `;Buffer.byteLength(y)>Math.max(Ec,t)&&(y=`${JSON.stringify({ts:p.ts,level:u,channel:e.channel,message:"Oversized log record omitted",originalBytes:Buffer.byteLength(y)})}
4
4
  `),s=s.then(async()=>{await wo.mkdir(e.logDir,{recursive:!0}),await a(Buffer.byteLength(y,"utf8")),await wo.appendFile(o,y,{encoding:"utf8",mode:384}),Date.now()-i>=6e4&&(await Ac(e.logDir,o),i=Date.now())}).catch(x=>{console.error("OpenPond logger failed",x)})}return r(l,"write"),{debug:r((u,c)=>l("debug",u,c),"debug"),info:r((u,c)=>l("info",u,c),"info"),warn:r((u,c)=>l("warn",u,c),"warn"),error:r((u,c)=>l("error",u,c),"error"),flush:r(()=>s,"flush"),filePath:o}}r(SS,"createLogger");function yi(e){let t=e.environment??process.env;if(e.provider!=="openpond"||e.model!==t.OPENPOND_HOSTED_MODEL_ID?.trim())return null;let n=t.OPENPOND_HOSTED_MODEL_CONTEXT_WINDOW,o=t.OPENPOND_HOSTED_MODEL_OUTPUT_LIMIT;if(n===void 0&&o===void 0)return null;let s=r(i=>{if(i===void 0)return null;let a=Number(i);if(!/^\d+$/.test(i)||!Number.isSafeInteger(a)||a<=0)throw new Error("Hosted admitted model limit is invalid.");return a},"parse");return{contextWindow:s(n),outputLimit:s(o)}}r(yi,"admittedHostedModelLimits");var qc=4,sh=128e3,ih=8e3,Nc=8192,jc=1024;function Mr(e){return e==="openpond"?e:null}r(Mr,"hostedContextProvider");function Nr(e,t){let o=t.trim().toLowerCase().match(/(?:^|[-_])(\d+)\s*k(?:[-_]|$)/);return o?.[1]?Number.parseInt(o[1],10)*1e3:sh}r(Nr,"hostedContextLimit");function bo(e){let t=Math.min(ih,Math.ceil(e*.25)),n=Math.min(e-1,Math.max(t,Math.ceil(e*.08)));return Math.max(1,e-n)}r(bo,"usableHostedContextLimit");function dn(e){let t=e.model?.trim();if(!t)return null;let n=yi({provider:e.provider,model:t});if(n?.contextWindow)return n.contextWindow;let s=e.settings?.modelCaches[e.provider]?.models.find(a=>a.id===t);if(s?.contextWindow)return s.contextWindow;let i=Mr(e.provider);return i?Nr(i,t):null}r(dn,"trustedProviderContextLimit");function Si(e){let t=e.model?.trim();if(!t)return null;let n=yi({provider:e.provider,model:t});return n?.outputLimit?n.outputLimit:e.settings?.modelCaches[e.provider]?.models.find(s=>s.id===t)?.outputLimit??null}r(Si,"trustedProviderOutputLimit");function jr(e){let t=e.reduce((n,o)=>n+o.role.length+(o.name?.length??0)+(o.content?.length??0)+8,0);return Math.max(1,Math.ceil(t/qc)+e.length*4)}r(jr,"estimateHostedMessageTokens");function Fr(e){let t=ch(e.provider,e.model);if(!t)return{tokens:jr(e.messages),source:"heuristic",modelFamily:null};let n=e.messages.reduce((o,s)=>o+4+ki(s.role,t)+ki(s.name??"",t)+ki(s.content??"",t),1);return{tokens:Math.max(1,n),source:"model_family",modelFamily:t}}r(Fr,"estimateHostedMessageTokensForProvider");function Qn(e){let t=e.maxContextTokens?Math.max(256,Math.floor(e.maxContextTokens/8)):Nc,n=e.modelOutputLimit&&e.modelOutputLimit>0?Math.floor(e.modelOutputLimit):Number.MAX_SAFE_INTEGER;return Math.max(1,Math.min(e.requestedOutputTokens??Nc,t,n))}r(Qn,"hostedRequestedOutputTokens");function Cn(e){let t=e.maxContextTokens??null,n=Fr({provider:e.provider,model:e.model,messages:e.messages}),o=n.tokens,s=Fc(e.tools??[]),i=Fc(e.messages.flatMap(u=>{let c={};return u.continuation!==void 0&&(c.continuation=u.continuation),u.tool_calls!==void 0&&(c.tool_calls=u.tool_calls),u.tool_call_id!==void 0&&(c.tool_call_id=u.tool_call_id),Object.keys(c).length>0?[c]:[]})),a=Math.max(1,Math.floor(e.maxOutputTokens)),l=ah(e.provider,t);return{messageTokens:o,toolDefinitionTokens:s,continuationTokens:i,outputAllowanceTokens:a,safetyReserveTokens:l,projectedTokens:o+s+i+a+l,maxContextTokens:t,tokenSource:n.source,tokenModelFamily:n.modelFamily}}r(Cn,"estimateHostedRequestBudget");function Fc(e){if(Array.isArray(e)&&e.length===0)return 0;let t=JSON.stringify(e);return!t||t==="[]"||t==="{}"?0:Math.max(1,Math.ceil(t.length/qc))}r(Fc,"estimatedSerializedTokens");function ah(e,t){return t?Math.min(Math.max(1,Math.floor(t/8)),Math.max(jc,Math.ceil(t*.02))):jc*2}r(ah,"requestSafetyReserveTokens");function lh(e,t){if(!e||typeof e!="object")return null;let n=e;for(let o of t){let s=n[o];if(typeof s=="number"&&Number.isFinite(s)&&s>=0)return Math.round(s)}return null}r(lh,"numericUsageValue");function dh(e,t){let n=bd(e),o=n.promptTokens,s=n.completionTokens,i=lh(e,["total_tokens","totalTokens"]);return t?i!==null?i:o!==null&&s!==null?o+s:null:o??i}r(dh,"tokenCountFromUsage");function $c(e){let t=e.usage===void 0?null:dh(e.usage,!!e.includeCompletion),n=Fr({provider:e.provider,model:e.model,messages:e.messages}),o=t??n.tokens,s=e.maxContextTokens??dn({provider:e.provider,model:e.model});if(!s)throw new Error(`Cannot create context usage snapshot without a trusted context limit for ${e.provider}.`);let i=Math.min(100,Math.round(o/s*100));return dr.parse({provider:e.provider,model:e.model,usedTokens:o,maxContextTokens:s,usableContextTokens:bo(s),percentFull:i,source:t===null?n.source:"provider_usage",updatedAtEventId:e.updatedAtEventId})}r($c,"createContextUsageSnapshot");function ch(e,t){let n=`${e}/${t??""}`.toLowerCase();return/\b(?:gpt|o[1-9]|codex)\b/.test(n)?"openai_cl100k":n.includes("claude")||e==="anthropic"?"anthropic_claude":n.includes("deepseek")||n.includes("kimi")||n.includes("glm")?"multilingual_code":null}r(ch,"modelTokenFamily");function ki(e,t){if(!e)return 0;let n=[...e].filter(i=>/[\u3000-\u9fff\uf900-\ufaff]/u.test(i)).length,o=Math.max(0,e.length-n);return Math.max(1,n+Math.ceil(o/(t==="anthropic_claude"?3.85:t==="multilingual_code"?3.65:3.75)))}r(ki,"estimateModelFamilyTextTokens");import{randomUUID as uh}from"node:crypto";import{promises as Dc}from"node:fs";import qr from"node:path";var Hc=8e3;function Ii(e,t){if(!/^custom:[a-zA-Z0-9_-]+$/.test(t))throw new Error("Invalid custom personality identifier.");return qr.join(Sn(e).instructions,"personalities",`${t.slice(7)}.md`)}r(Ii,"personalityPath");function Ri(e,t){if(e.trim().length>Hc)throw new Un({code:"INVALID_INSTRUCTIONS",path:t??"personalization",message:`Personality text exceeds ${Hc} characters.`,action:"Shorten the personality text before using it."});return e.trim()}r(Ri,"validateText");async function ph(e){let t=qr.join(Sn(e).instructions,"personalities"),n=await Dc.readdir(t,{withFileTypes:!0}).catch(s=>{if(pl(s))return[];throw s}),o=[...ao];for(let s of n.sort((i,a)=>i.name.localeCompare(a.name))){if(!s.isFile()||!/^[a-zA-Z0-9_-]+\.md$/.test(s.name))continue;let i=qr.join(t,s.name),a=await io(i);a!==null&&o.push({id:`custom:${s.name.slice(0,-3)}`,name:s.name.slice(0,-3).replace(/[-_]+/g," "),source:"custom",description:"",content:Ri(a,i)})}return o}r(ph,"templatesWithFiles");async function mh(e,t){let{document:n}=await ur(t),o=await ph(t),s=n.personalization?.active??`builtin:${cr}`,i=s.startsWith("builtin:")?s.slice(8):s,a=o.find(u=>u.id===i);if(!a)throw new Un({code:"MISSING_PERSONALITY",path:s.startsWith("custom:")?Ii(t,s):Sn(t).config,message:`Selected personality ${s} is unavailable.`,action:"Restore its Markdown file or select an available personality in Settings."});let l=s.startsWith("custom:")?Ii(t,s):null;return xl.parse({activeTemplateId:i,customized:a.source==="custom",soul:n.personalization?.mode==="disabled"?"":a.content,soulPath:l,updatedAt:l?(await Dc.stat(l)).mtime.toISOString():null,templates:o})}r(mh,"loadPersonalizationSettings");async function qS(e,t,n){return await ar(qr.join(Sn(t).runtime,"personalization"),async()=>{let o=Ri(n.soul),s=ao.find(a=>a.id===n.activeTemplateId),i;if(!n.saveAsNew&&s&&o===s.content.trim())i=`builtin:${s.id}`;else{let a=n.templateName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,56)||"custom";i=!n.saveAsNew&&n.activeTemplateId.startsWith("custom:")?n.activeTemplateId:`custom:${a}-${uh().slice(0,8)}`,await ml(Ii(t,i),`${o}
5
5
  `)}await pr(t,a=>({...a,personalization:{...a.personalization,active:i}}))}),mh(e,t)}r(qS,"savePersonalizationSettings");function Lc(e,t){return[Ri(e),t.trim()].filter(Boolean).join(`
@@ -0,0 +1,12 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{b as Ne}from"./chunk-SYUKES6H.js";import{a as B,b as W,c as ze,d as Le,e as q,f as ie,i as de,o as Be,q as ce}from"./chunk-U7X5ZLAL.js";import{a as ue}from"./chunk-RY46UPBO.js";import{k as ae,m as se,n as Pe}from"./chunk-OQPJ7FJF.js";import{c as Te}from"./chunk-Y4I6CFZJ.js";import{E as L}from"./chunk-WGQ3FMRF.js";import{f as G,m as f,n as _e}from"./chunk-HIQPGYVH.js";import{a as Ce}from"./chunk-2LJCJOJ7.js";import{a as Oe,c as $e,d as je}from"./chunk-AMC4Z7G4.js";import{l as K,m as qe}from"./chunk-I6VMRQF4.js";import{h as Ue}from"./chunk-4PUOWSDE.js";import{Sa as Ae,ea as Ee,wb as ke}from"./chunk-ZY32SZ2P.js";import{a as re,b as oe}from"./chunk-KUE46HTH.js";import{b as z}from"./chunk-JCLTFDVW.js";import{A as a}from"./chunk-X2J2P5ZT.js";import{a as d}from"./chunk-FTQLQJQV.js";function jt(t,e){let n=t.token?.trim();if(!n||t.accountState.state!=="signed_in"||!t.accountState.activeProfile)throw new Error("A signed-in OpenPond account is required.");let r=Ce(t.apiBaseUrl,{apiBaseUrl:t.apiBaseUrl}),o=/\/api\/sandboxes\/?$/.test(r)?r.replace(/\/api\/sandboxes\/?$/,"/v1"):r.replace(/\/sandboxes\/?$/,"");return{audience:new URL(o).origin,async request(s){let i=n.startsWith("opk_"),u=await z(o,n,s.path,{method:s.method??"GET",signal:s.signal,explicitBearerAuth:!i,headers:{...i?{"openpond-api-key":n}:{},...s.idempotencyKey?{"idempotency-key":s.idempotencyKey}:{},...e?{"X-OpenPond-Team-Id":e}:{}},...s.body?{body:JSON.stringify(s.body)}:{},...s.timeoutMs!==void 0?{timeoutMs:s.timeoutMs}:{}}),c=await u.json().catch(()=>({}));if(!u.ok)throw new Error(typeof c.error=="string"?c.error:`OpenPond API request failed with status ${u.status}`);return c}}}d(jt,"createCapturedOpenPondPublicApiClient");var _t=3e4,Tt=8*1024*1024,Mn={timeoutMs:900*1e3,maxResponseBytes:64*1024*1024},Fe=class extends Error{static{d(this,"ApiTimeoutError")}timeoutMs;requestUrl;code="OPENPOND_API_TIMEOUT";constructor(t,e){super(`API request timed out after ${t}ms: ${e}`),this.timeoutMs=t,this.requestUrl=e,this.name="ApiTimeoutError"}},pe=class extends Error{static{d(this,"ApiResponseTooLargeError")}maximumBytes;requestUrl;code="OPENPOND_API_RESPONSE_TOO_LARGE";constructor(t,e){super(`API response exceeded ${t} bytes: ${e}`),this.maximumBytes=t,this.requestUrl=e,this.name="ApiResponseTooLargeError"}},He=class extends Error{static{d(this,"OpenPondApiError")}status;apiMessage;code;constructor(t,e,n,r=null){let o=r||e;super(`${n} failed: ${t}${o?` ${o}`:""}`),this.status=t,this.apiMessage=r,this.name="OpenPondApiError",this.code=e||"OPENPOND_API_ERROR"}};async function X(t,e,n,r={}){let{timeoutMs:o=_t,maxResponseBytes:s=Tt,explicitBearerAuth:i=!1,...u}=r,c=`${t}${n}`,p=new Headers(u.headers);p.set("Content-Type","application/json");let b=i?void 0:process.env.OPENPOND_API_KEY,l=e?.trim()||"",g=!i&&l.startsWith("opk_"),C=b||(g?l:null);C&&!p.has("openpond-api-key")&&p.set("openpond-api-key",C),e?p.set("Authorization",g?`ApiKey ${l}`:`Bearer ${e}`):b&&!p.has("Authorization")&&p.set("Authorization",`ApiKey ${b}`);let T=new AbortController,U=new Fe(o,c),j=o>0?setTimeout(()=>T.abort(U),o):null;j?.unref?.();let ne=Lt(u.signal,T.signal,o),J=d(()=>{j&&clearTimeout(j)},"cleanup");try{let P=await fetch(c,{...u,headers:p,signal:ne});return zt(P,{cleanup:J,maximumBytes:s,requestUrl:c,timeoutController:T,timeoutError:U})}catch(P){throw J(),T.signal.aborted?U:P}}d(X,"apiFetch");async function me(t,e){let n;try{let r=await t.text();n=r?JSON.parse(r):{}}catch(r){if(r instanceof Fe||r instanceof pe)throw r;n={}}if(!t.ok){let r=typeof n.error=="string"?n.error:null,o=typeof n.message=="string"?n.message:null;throw new He(t.status,r,e,o)}return n}d(me,"readApiJson");function zt(t,e){if(!t.body)return e.cleanup(),t;let n=Number(t.headers.get("content-length"));if(e.maximumBytes>0&&Number.isFinite(n)&&n>e.maximumBytes)throw e.cleanup(),t.body.cancel(),new pe(e.maximumBytes,e.requestUrl);let r=t.body.getReader(),o=0,s=new ReadableStream({async pull(i){try{let u=await r.read();if(u.done){e.cleanup(),i.close();return}if(o+=u.value.byteLength,e.maximumBytes>0&&o>e.maximumBytes){e.cleanup(),await r.cancel(),i.error(new pe(e.maximumBytes,e.requestUrl));return}i.enqueue(u.value)}catch(u){e.cleanup(),i.error(e.timeoutController.signal.aborted?e.timeoutError:u)}},async cancel(i){e.cleanup(),await r.cancel(i)}});return new Response(s,{headers:t.headers,status:t.status,statusText:t.statusText})}d(zt,"boundedResponse");function Lt(t,e,n){return n<=0?t??void 0:t?AbortSignal.any([t,e]):e}d(Lt,"composedSignal");var R=a.string().min(1).max(200),_=a.string().regex(/^[a-f0-9]{64}$/),le=a.object({operationId:R,name:a.string().trim().min(1).max(500),projectId:R,dataset:G.extend({revision:a.number().int().positive()}).strict(),caseIds:a.array(R).min(1).max(1e4)}).strict().superRefine((t,e)=>{new Set(t.caseIds).size!==t.caseIds.length&&e.addIssue({code:"custom",message:"Select each case once."})}),Bt=B.extend({inputHash:_,outputHash:_.nullable(),task:Ee,taskHash:_}).strict(),Nt=a.object({schemaVersion:a.literal("openpond.connectedRecordedExecution.v1"),id:R,teamId:R,ownerUserId:R,request:le,manifest:ke,sources:a.array(Bt).min(1).max(1e4),contentHash:_}).strict();function Me(t){let e=Nt.parse(t),{contentHash:n,...r}=e,{contentHash:o,...s}=e.manifest;if(f(r)!==n||f(s)!==o||e.manifest.teamId!==e.teamId||e.manifest.id!==e.id||e.manifest.operationId!==e.request.operationId||f(e.manifest.dataset)!==f(e.request.dataset)||e.sources.length!==e.request.caseIds.length||e.sources.length!==e.manifest.population.length||e.sources.some((i,u)=>i.taskHash!==f(i.task)||i.task.id!==e.request.caseIds[u]||i.boundaryId!==i.task.id||e.manifest.population[u]?.caseId!==i.boundaryId))throw new Error("Recorded execution identity or population integrity failed.");return e}d(Me,"verifyConnectedRecordedExecution");var Ft=a.object({projectId:R.optional(),cursor:R.optional(),limit:a.number().int().min(1).max(50).default(20)}).strict(),Ht=a.object({id:R,teamId:R,ownerUserId:R,projectId:R,name:a.string().min(1).max(500),dataset:le.shape.dataset,manifestHash:_,contentHash:_,caseCount:a.number().int().min(1).max(1e4),createdAt:a.string().datetime()}).strict(),Mt=a.object({teamId:R,items:a.array(Ht).max(50),nextCursor:R.nullable()}).strict(),Dt=a.object({datasetId:a.string().trim().min(1).max(240),expectedRevision:a.number().int().positive(),operationId:a.string().trim().min(1).max(240),graders:a.array(Ae).min(1).max(100).optional()}).strict().superRefine((t,e)=>{t.graders&&new Set(t.graders.map(n=>n.id)).size!==t.graders.length&&e.addIssue({code:"custom",path:["graders"],message:"Choose one exact revision of each grader."})}),N=a.string().min(1).max(500),k=a.number().int().nonnegative(),Jt=a.object({teamId:N,ownerUserId:N,projectId:N.nullable(),status:a.enum(["active","paused","archived"]),revision:k,state:a.enum(["collecting","pending","attention","paused","archived"]),lastReconciledAt:a.string().datetime().nullable(),lastCapturedAt:a.string().datetime().nullable(),historyDays:a.number().int().positive(),sources:k,tasks:k,datasets:a.array(a.object({datasetId:N,projection:a.enum(["turn","conversation"]),revision:k}).strict()).max(2),latestBatch:a.object({operationId:N,updatedAt:a.string().datetime(),scanned:k,captured:k,unchanged:k,pending:k,failed:k,excluded:k,paused:k,hasMore:a.boolean()}).strict().nullable()}).strict(),h=a.string().min(1).max(500),E=a.string().regex(/^[a-f0-9]{64}$/),De=a.object({teamId:h,projectId:h.nullable(),status:a.enum(["active","paused","archived"]),revision:a.number().int().nonnegative()}).strict(),Kt=a.object({teamId:h,operationId:h,projectId:h.nullable(),outcomes:a.array(a.object({conversationId:h,state:a.enum(["captured","unchanged","pending","paused","excluded","failed"]),sourceId:h.optional(),snapshotHash:E.optional(),reason:a.string().optional()}).strict()).max(50),nextCursor:h.nullable()}).strict(),Gt=a.object({teamId:h,ref:B,origin:W.shape.source,sessionId:h,projectId:h,capturedAt:a.string().datetime(),unmappedEvidence:a.object({count:a.number().int().nonnegative().max(1e5),contentHash:E}).strict(),evidence:a.object({input:a.array(K),observed:a.array(K),answer:a.json(),boundary:qe}).strict()}).strict(),Wt=a.object({teamId:h,sourceId:h,snapshotHash:E,contentHash:E,count:a.number().int().nonnegative(),offset:a.number().int().nonnegative(),events:a.array(K).max(50),nextOffset:a.number().int().nonnegative().nullable()}).strict(),Xt=a.object({teamId:h,source:q.shape.source,sourceHash:E,previewHash:E,destination:q.shape.destination,issues:a.array(a.object({file:a.string(),message:a.string()}).strict()).max(100),sessions:a.array(a.object({sessionHash:E,sessionId:h,origin:W.shape.source,exporterVersion:a.string().nullable(),eventCount:a.number().int().nonnegative(),boundaries:a.array(a.object({id:h,projection:a.enum(["turn","conversation"]),answer:a.boolean(),process:a.enum(["retained","partial","absent"]),terminal:a.enum(["completed","failed","cancelled","unknown"])}).strict()).max(5001),warnings:a.array(a.string()).max(100),sample:a.array(a.object({role:a.enum(["user","assistant","system","tool"]).nullable(),text:a.string().max(4e3)}).strict()).max(3)}).strict()).max(1e3)}).strict(),Je=a.object({teamId:h,operationId:h,requestHash:E,previewHash:E,projectId:h.optional(),state:a.enum(["admitting","publishing","completed","failed"]),outcomes:a.array(a.object({sessionHash:E,sourceId:h,status:a.enum(["imported","already_present"]),datasets:a.array(a.object({datasetId:h,revision:a.number().int().positive(),changed:a.boolean()}).strict()).max(2)}).strict()).max(1e3),error:a.string().optional()}).strict(),Ke=class extends Error{static{d(this,"ConnectedEvidenceError")}constructor(t,e,n){super(n),this.status=t,this.code=e,this.name="ConnectedEvidenceError"}status;code},ir=class{static{d(this,"ConnectedEvidenceClient")}constructor(t){this.options=t;let e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash||!t.apiKey.trim()||!t.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=e.toString().replace(/\/+$/,"")}options;baseUrl;async capture(t,e){let n=ze.parse(t),r=Kt.parse(await this.request("/capture","POST",n,e));if(this.scope(r.teamId),r.operationId!==n.operationId||r.outcomes.length>n.limit||n.conversationId&&r.outcomes.some(o=>o.conversationId!==n.conversationId))throw new Error("Capture receipt differs from its requested source or operation.");return r}async retainStartingAssets(t,e){let n=Be.parse(t),r=ce(await this.request("/starting-assets","POST",n,e));if(this.scope(r.teamId),r.operationId!==n.operationId||r.requestHash!==f(n)||f(r.source)!==f(n.source)||r.assets.length!==n.proofs.length||r.assets.some((o,s)=>o.path!==n.proofs[s].path))throw new Error("Starting assets differ from the exact source, operation or selected paths.");return r}async startingAssets(t,e){let n=ce(await this.request(`/starting-assets/${encodeURIComponent(h.parse(t))}`,"GET",void 0,e));if(this.scope(n.teamId),n.id!==t)throw new Error("Starting assets identity mismatch.");return n}async list(t={},e){let n=a.object({projectId:h.optional(),cursor:h.optional(),limit:a.number().int().min(1).max(50).default(20)}).strict().parse(t),r=new URLSearchParams(Object.entries(n).filter(([,s])=>s!==void 0).map(([s,i])=>[s,String(i)])),o=a.object({teamId:h,items:a.array(W).max(50),nextCursor:h.nullable()}).strict().parse(await this.request(`?${r}`,"GET",void 0,e));if(this.scope(o.teamId),o.items.length>n.limit||new Set(o.items.map(s=>s.sourceId)).size!==o.items.length||o.nextCursor!==null&&o.nextCursor===n.cursor||n.projectId&&o.items.some(s=>s.projectId!==n.projectId))throw new Error("Connected source page differs from its requested scope.");return o}async read(t,e){let n=B.parse(t),r=Gt.parse(await this.request(`/${encodeURIComponent(n.id)}/cases/${encodeURIComponent(n.boundaryId)}?snapshotHash=${n.snapshotHash}&revisionHash=${n.boundaryRevisionHash}`,"GET",void 0,e));if(this.scope(r.teamId),f(r.ref)!==f(n)||r.evidence.boundary.id!==n.boundaryId||r.evidence.boundary.revisionHash!==n.boundaryRevisionHash||f(r.evidence.input)!==r.evidence.boundary.inputHash||f(r.evidence.observed)!==n.boundaryRevisionHash||r.evidence.boundary.outputHash!==null&&f(r.evidence.answer)!==r.evidence.boundary.outputHash)throw new Error("Connected case readback differs from its exact snapshot or cutoff.");return r}async setCollection(t,e){let n=De.parse(await this.request("/collection","PUT",a.object({paused:a.boolean()}).strict().parse({paused:t}),e));return this.scope(n.teamId),n}async collection(t){let e=De.parse(await this.request("/collection","GET",void 0,t));return this.scope(e.teamId),e}async collectionStatus(t){let e=Jt.parse(await this.request("/collection/status","GET",void 0,t));return this.scope(e.teamId),e}async unmappedEvents(t,e){let n=a.object({id:h,snapshotHash:E,contentHash:E,offset:a.number().int().nonnegative().default(0),limit:a.number().int().min(1).max(50).default(20)}).strict().parse(t),r=Wt.parse(await this.request(`/${encodeURIComponent(n.id)}/unmapped-events?snapshotHash=${n.snapshotHash}&offset=${n.offset}&limit=${n.limit}`,"GET",void 0,e));if(this.scope(r.teamId),r.sourceId!==n.id||r.snapshotHash!==n.snapshotHash||r.contentHash!==n.contentHash||r.offset!==n.offset||r.events.length>n.limit||r.events.some((o,s)=>o.sequence!==n.offset+s)||r.nextOffset!==null&&r.nextOffset!==n.offset+r.events.length)throw new Error("Unmapped source event page differs from its pinned snapshot.");return r}async homeSummary(t,e){let n=a.object({from:a.string().datetime(),to:a.string().datetime(),projectId:h.optional()}).strict(),r=n.parse(t),o=new URLSearchParams(Object.entries(r)),s=a.object({teamId:h,range:n,activity:a.object({conversations:a.number().int().nonnegative(),turns:a.number().int().nonnegative(),chatTurns:a.number().int().nonnegative(),workTurns:a.number().int().nonnegative()}).strict(),accounting:a.object({contextSnapshots:a.number().int().nonnegative()}).strict(),usage:Oe}).strict().parse(await this.request(`/summary?${o}`,"GET",void 0,e));if(this.scope(s.teamId),f(s.range)!==f(r)||s.activity.chatTurns+s.activity.workTurns!==s.activity.turns)throw new Error("Activity summary differs from its requested range.");for(let i of[s.usage.days,s.usage.modes,s.usage.models]){if(new Set(i.map(u=>u.key)).size!==i.length)throw new Error("Duplicate usage summary group.");for(let u of Object.keys(s.usage.total))if(i.reduce((c,p)=>c+p[u],0)!==s.usage.total[u])throw new Error("Usage totals differ from their displayed groups.")}return s}async uploadPart(t,e){let n=Le.parse(t),r=a.object({teamId:h,hash:E,parts:a.number().int(),index:a.number().int()}).strict().parse(await this.request("/imports/upload","POST",n,e));if(this.scope(r.teamId),r.hash!==n.hash||r.parts!==n.parts||r.index!==n.index)throw new Error("Upload receipt differs from its part identity.");return r}async preview(t,e){let n=q.parse(t),r=Xt.parse(await this.request("/imports/preview","POST",n,e));if(this.scope(r.teamId),r.source!==n.source||f(r.destination)!==f(n.destination)||r.sessions.some(o=>o.origin!==n.source)||new Set(r.sessions.map(o=>o.sessionHash)).size!==r.sessions.length)throw new Error("Import preview differs from its source or destination.");return r}async commit(t,e){let n=ie.parse(t),r=Je.parse(await this.request("/imports/commit","POST",n,e));if(this.scope(r.teamId),r.operationId!==n.operationId||r.previewHash!==n.previewHash||r.requestHash!==f(n)||r.outcomes.some(o=>!n.selection.some(s=>s.sessionHash===o.sessionHash))||r.state==="completed"&&r.outcomes.length!==n.selection.length)throw new Error("Import receipt differs from its exact selection or operation.");return r}async readImport(t,e){let n=h.parse(t),r=Je.parse(await this.request(`/imports/${encodeURIComponent(n)}`,"GET",void 0,e));if(this.scope(r.teamId),r.operationId!==n)throw new Error("Import identity mismatch.");return r}async prepareRecorded(t,e){let n=le.parse(t),r=Me(await this.request("/recorded-executions","POST",n,e));if(this.scope(r.teamId),f(r.request)!==f(n))throw new Error("Recorded admission differs from its selected Dataset/cases.");return r}async listRecordedExecutions(t={},e){let n=Ft.parse(t),r=new URLSearchParams(Object.entries(n).filter(([,s])=>s!==void 0).map(([s,i])=>[s,String(i)])),o=Mt.parse(await this.request(`/recorded-executions?${r}`,"GET",void 0,e));if(this.scope(o.teamId),o.items.length>n.limit||o.items.some((s,i)=>s.teamId!==o.teamId||n.projectId&&s.projectId!==n.projectId||n.cursor&&s.id<=n.cursor||i>0&&s.id<=o.items[i-1].id)||o.items.some(s=>s.ownerUserId!==o.items[0]?.ownerUserId)||o.nextCursor!==null&&(n.cursor!==void 0&&o.nextCursor<=n.cursor||o.items.length>0&&o.nextCursor<o.items.at(-1).id))throw new Error("Recorded execution page differs from its requested scope or cursor.");return o}async recordedExecution(t,e){let n=Me(await this.request(`/recorded-executions/${encodeURIComponent(h.parse(t))}`,"GET",void 0,e));if(this.scope(n.teamId),n.id!==t)throw new Error("Recorded execution identity mismatch.");return n}async publishDataset(t,e){let n=Dt.parse(t),r=de.parse(await this.request("/datasets/publish","POST",n,e));this.scope(r.teamId);let o=r.workspace.draft.metadata.connectedPublication;if(r.datasetId!==n.datasetId||!r.publication||!o||typeof o!="object"||!("requestHash"in o)||o.requestHash!==f(n))throw new Error("Published Dataset identity or original selection mismatch.");return r}async createSelection(t,e){let n=a.object({operationId:h.max(240),projectId:h.max(240),name:a.string().trim().min(1).max(200),cases:a.array(B).min(1).max(500)}).strict().parse(t),r=de.parse(await this.request("/datasets/selection","POST",n,e));if(this.scope(r.teamId),r.originProjectId!==n.projectId||r.workspace.draft.tasks.length!==n.cases.length||r.workspace.draft.tasks.some((o,s)=>f(o.input&&typeof o.input=="object"&&!Array.isArray(o.input)?o.input.connectedEvidenceRef:null)!==f(n.cases[s])))throw new Error("Selected Dataset differs from its exact source population.");return r}scope(t){if(t!==this.options.teamId)throw new Error("Connected evidence workspace mismatch.")}async request(t,e,n,r){let{response:o,value:s}=await Te(this.options.fetch??fetch,`${this.baseUrl}/v1/connected-evidence${t}`,{method:e,signal:r,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,"Content-Type":"application/json",Accept:"application/json"},...n===void 0?{}:{body:JSON.stringify(n)}},(i,u,c)=>new Ke(i,u,c));if(!o.ok){let i=a.object({code:a.string(),message:a.string()}).safeParse(s);throw new Ke(o.status,i.success?i.data.code:"connected_request_failed",i.success?i.data.message:"Connected evidence request failed.")}return s}},I=a.string().trim().min(1).max(240),ur=a.object({id:I,expectedRevision:a.number().int().positive(),manifest:$e}).strict().refine(t=>t.id===t.manifest.connectionId&&t.expectedRevision===t.manifest.connectionRevision,"Collector coverage scope differs from its connection."),pr=a.object({id:I,cutoff:a.iso.datetime().optional()}).strict(),mr=a.object({schemaVersion:a.literal("openpond.connectedSyncCoverageReceipt.v1"),id:I,teamId:I,ownerUserId:I,connectionId:I,connectionRevision:a.number().int().positive(),receivedAt:a.iso.datetime(),summary:je}).strict(),lr=a.object({id:I,source:q.shape.source,machineId:I,sourceInstanceId:I,sourceLabel:a.string().trim().min(1).max(200),sourceRoot:a.string().min(1).max(2e3),destination:q.shape.destination,since:a.string().datetime().nullable(),keepSyncing:a.boolean(),expectedRevision:a.number().int().nonnegative()}).strict(),hr=a.object({id:I,expectedRevision:a.number().int().positive(),action:a.enum(["pause","resume","disconnect"])}).strict(),fr=a.object({id:I,operationId:I,expectedRevision:a.number().int().positive()}).strict(),yr=a.object({id:I,expectedRevision:a.number().int().positive(),pendingOperations:a.number().int().min(0).max(1e4),error:a.string().max(500).nullable(),completedSyncRevision:a.number().int().nonnegative().default(0)}).strict(),gr=a.object({teamId:I,id:I,revision:a.number().int().positive(),source:q.shape.source,sourceLabel:a.string(),sourceRoot:a.string(),taskDatasetId:I.nullable(),conversationDatasetId:I.nullable(),machineId:I,sourceInstanceId:I,projectId:I,datasetIds:a.array(I).max(2),since:a.string().datetime().nullable(),keepSyncing:a.boolean(),state:a.enum(["active","paused","disconnected"]),health:a.enum(["online","offline"]),lastHeartbeatAt:a.string().datetime().nullable(),lastAdmissionAt:a.string().datetime().nullable(),pendingOperations:a.number().int().nonnegative(),admittedTasks:a.number().int().nonnegative(),error:a.string().nullable(),requestedSyncRevision:a.number().int().nonnegative().default(0),completedSyncRevision:a.number().int().nonnegative().default(0),syncRequestedAt:a.string().datetime().nullable().default(null),syncCompletedAt:a.string().datetime().nullable().default(null)}).strict().refine(t=>t.completedSyncRevision<=t.requestedSyncRevision&&t.requestedSyncRevision<=t.revision,"Invalid sync acknowledgement generation."),br=a.object({connectionId:I,expectedRevision:a.number().int().positive(),request:ie}).strict();function Pr(t){let e=d(r=>`/v1/training/candidate-evaluations/${encodeURIComponent(r)}`,"path");function n(r,o,s){let i=Zt.parse(r);if(i.teamId!==o||s&&i.id!==s)throw new Error("The preparation belongs to another workspace or candidate operation.");return i}return d(n,"read"),{async options(r,o={}){let s=new URLSearchParams({teamId:r,...o}),i=Yt.parse(await t(`/v1/training/candidates?${s}`));if(i.teamId!==r)throw new Error("The candidate catalog belongs to another workspace.");return i},async save(r){let o=We.parse(r),s=n(await t(`/v1/training/candidate-evaluations?teamId=${encodeURIComponent(o.teamId)}`,{method:"POST",body:JSON.stringify(o)}),o.teamId);if(s.requestHash!==f(o))throw new Error("The saved preparation differs from the selected candidate or frozen evaluation.");return s},async get(r,o){return n(await t(`${e(o)}?teamId=${encodeURIComponent(r)}`),r,o)},async control(r,o,s,i){let u=Qt.parse(i),c=n(await t(`${e(o)}/${s}?teamId=${encodeURIComponent(r)}`,{method:"POST",body:JSON.stringify(u)}),r,o);if(c.requestHash!==u.requestHash)throw new Error("The command returned a different frozen evaluation.");return c}}}d(Pr,"createCandidateEvaluationClient");var S=a.string().trim().min(1).max(200),he=a.string().regex(/^[a-f0-9]{64}$/),Ge=a.object({id:S,contentHash:he}).strict(),Vt=a.object({artifact:Ge,trainingJobId:S,configurationId:S,baseProfileId:S,ready:a.boolean(),reason:a.string().max(1e3).nullable()}).strict(),Yt=a.object({teamId:S,ownerUserId:S,items:a.array(Vt).max(100),nextCursor:S.nullable()}).strict(),We=a.object({teamId:S,operationId:S,artifact:Ge,configuration:L}).strict().superRefine((t,e)=>{(t.configuration.request.teamId!==t.teamId||t.configuration.request.policy.kind==="fixture"||t.configuration.request.policy.candidate)&&e.addIssue({code:"custom",message:"Choose one exact model-backed evaluation before preparing the trained version."})}),Zt=a.object({schemaVersion:a.literal("openpond.candidateEvaluationPreparation.v1"),teamId:S,ownerUserId:S,id:S,revision:a.number().int().positive(),requestHash:he,request:We,trainingJobId:S,dispatchId:S,lastOperationId:S.nullable(),runtime:a.object({poolId:S,endpointId:S.nullable(),baseProfileId:S,workerImageDigest:a.string().regex(/^sha256:[a-f0-9]{64}$/),modelId:S.nullable()}).strict().nullable(),state:a.enum(["configured","preparing","ready","dispatching","submitted","cleaning","completed","failed","cancelled"]),experimentId:S.nullable(),authorizedAt:a.iso.datetime().nullable(),cancelledAt:a.iso.datetime().nullable(),reason:a.string().max(1e3).nullable(),createdAt:a.iso.datetime(),updatedAt:a.iso.datetime()}).strict().superRefine((t,e)=>{(t.requestHash!==f(t.request)||!t.runtime&&["ready","dispatching","submitted","completed"].includes(t.state))&&e.addIssue({code:"custom",message:"The exact candidate preparation request or runtime changed."})}),Qt=a.object({operationId:S,expectedRevision:a.number().int().positive(),requestHash:he}).strict();var x=a.string().trim().min(1).max(200),F=a.string().regex(/^[a-f0-9]{64}$/),H=a.string().datetime(),Xe=a.object({operationId:x,id:x.optional(),expectedRevision:a.number().int().nonnegative(),teamId:x,projectId:x.nullable(),enabled:a.boolean(),configuration:L,cadence:a.discriminatedUnion("kind",[a.object({kind:a.literal("interval"),seconds:a.number().int().min(60).max(31536e3)}).strict(),a.object({kind:a.literal("nightly"),calendar:Ue}).strict()]),maximumTotalSpendUsd:a.number().finite().positive().max(1e4),maximumAttempts:a.number().int().min(1).max(20)}).strict().superRefine((t,e)=>{(t.configuration.request.teamId!==t.teamId||(t.configuration.request.project?.id??null)!==t.projectId)&&e.addIssue({code:"custom",message:"The scheduled Experiment must retain its actual workspace and Project."}),t.configuration.maximumCostUsd>t.maximumTotalSpendUsd&&e.addIssue({code:"custom",message:"The run ceiling exceeds the approved cumulative schedule ceiling."})}),en=a.object({id:x,scheduledAt:H,coalescedThroughAt:H,coalescedCount:a.number().int().nonnegative(),configurationHash:F,operationId:x,state:a.enum(["reserved","dispatching","running","cleaning","completed","failed","cancelled","uncertain"]),executionId:x.nullable(),attempt:a.number().int().positive(),maximumCostUsd:a.number().finite().positive(),actualSpendUsd:a.number().finite().nonnegative().nullable(),cleanupComplete:a.boolean(),error:a.string().max(4e3).nullable()}).strict(),tn=a.object({schemaVersion:a.literal("openpond.experimentEvaluationSchedule.v1"),id:x,revision:a.number().int().positive(),actorId:x,teamId:x,projectId:x.nullable(),operationId:x,requestHash:F,configuration:L,configurationHash:F,cadence:Xe.shape.cadence,state:a.enum(["scheduled","disabled","blocked"]),nextRunAt:H.nullable(),maximumTotalSpendUsd:a.number().finite().positive(),maximumAttempts:a.number().int().positive(),lastEvaluatedConfigurationHash:F.nullable(),newerUnevaluatedRelease:G.nullable(),fires:a.array(en).max(1e4),reason:a.string().max(4e3).nullable(),createdAt:H,updatedAt:H,contentHash:F}).strict();function nn(t){let{operationId:e,request:n,...r}=t,{operationId:o,...s}=n;return f({...r,request:s})}d(nn,"scheduledExperimentHash");function rn(t){let e=tn.parse(t);if(_e(e,"Scheduled Experiment"),e.configurationHash!==nn(e.configuration)||e.configuration.request.teamId!==e.teamId||(e.configuration.request.project?.id??null)!==e.projectId)throw new Error("Scheduled Experiment immutable authority differs from its recipe.");return e}d(rn,"verifyExperimentEvaluationSchedule");function $r(t){return rn({...t,contentHash:f(t)})}d($r,"sealExperimentEvaluationSchedule");var on=a.object({teamId:x,id:x,operationId:x,expectedRevision:a.number().int().positive(),action:a.enum(["cancel_active","retry_active","pause"])}).strict(),jr=a.discriminatedUnion("operation",[a.object({operation:a.literal("publish"),request:Xe}).strict(),a.object({operation:a.literal("control"),request:on}).strict(),a.object({operation:a.literal("read"),id:x}).strict(),a.object({operation:a.literal("list"),cursor:x.optional(),limit:a.number().int().min(1).max(100).default(50)}).strict()]);function an(t){return{list:d((e={})=>t.listSandboxRuntimes(e),"list"),create:d(e=>t.createSandboxRuntime(e),"create"),handle:d((e,n=null)=>t.sandboxRuntime(e,n),"handle"),get:d(e=>t.getSandboxRuntime(e),"get"),createSandbox:d((e,n={},r={})=>t.createSandboxRuntimeSandbox(e,n,r),"createSandbox"),updateStatus:d((e,n)=>t.updateSandboxRuntimeStatus(e,n),"updateStatus"),events:d(e=>t.listSandboxRuntimeEvents(e),"events"),event:d((e,n)=>t.emitSandboxRuntimeEvent(e,n),"event"),checkpoint:d((e,n={})=>t.checkpointSandboxRuntime(e,n),"checkpoint"),promote:d((e,n,r={})=>t.promoteSandboxRuntime(e,n,r),"promote"),preserveSource:d((e,n={},r={})=>t.preserveSandboxRuntimeSource(e,n,r),"preserveSource")}}d(an,"createSandboxRuntimeNamespace");function sn(t){return{list:d((e={})=>t.list(e),"list"),create:d(e=>t.create(e),"create"),get:d(e=>t.get(e),"get"),pricing:d(()=>t.pricing(),"pricing"),costs:d((e={})=>t.costs(e),"costs")}}d(sn,"createSandboxNamespace");function dn(t){return{list:d(e=>t.listProjects(e),"list"),upsert:d(e=>t.upsertProject(e),"upsert"),upsertGitRemote:d(e=>t.upsertProjectGitRemote(e),"upsertGitRemote"),get:d((e,n)=>t.getProject(e,n),"get"),update:d((e,n)=>t.updateProject(e,n),"update"),sync:d((e,n)=>t.syncProject(e,n),"sync"),ensureGitRemote:d((e,n)=>t.ensureProjectGitRemote(e,n),"ensureGitRemote"),getGitRemote:d((e,n)=>t.ensureProjectGitRemote(e,n),"getGitRemote"),git:d((e,n)=>t.ensureProjectGitRemote(e,n),"git"),uploadSource:d((e,n)=>t.uploadProjectSource(e,n),"uploadSource"),archive:d((e,n)=>t.archiveProject(e,n),"archive")}}d(dn,"createSandboxProjectNamespace");function cn(t){return{get:d(e=>t.getHostedProfile(e),"get"),status:d(e=>t.getHostedProfile(e),"status"),ensureHosted:d(e=>t.ensureHostedProfile(e),"ensureHosted"),push:d(e=>t.pushHostedProfile(e),"push")}}d(cn,"createSandboxProfileNamespace");function un(t){return{list:d(e=>t.listAgents(e),"list"),upsert:d(e=>t.upsertAgent(e),"upsert"),get:d((e,n)=>t.getAgent(e,n),"get"),update:d((e,n)=>t.updateAgent(e,n),"update"),archive:d((e,n)=>t.archiveAgent(e,n),"archive"),run:d((e,n)=>t.runAgent(e,n),"run"),sourceDeployPlan:d((e,n)=>t.getAgentSourceDeployPlan(e,n),"sourceDeployPlan"),manifestSnapshots:d((e,n)=>t.listAgentManifestSnapshots(e,n),"manifestSnapshots"),requestSourceChecks:d((e,n)=>t.requestAgentSourceChecks(e,n),"requestSourceChecks"),configureSourceSetup:d((e,n)=>t.configureAgentSourceSetup(e,n),"configureSourceSetup"),publishSource:d((e,n)=>t.publishAgentSource(e,n),"publishSource")}}d(un,"createSandboxAgentNamespace");function pn(t,e,n=null){let r=d(async(c={},p={})=>{let b=await t.getSandboxRuntime(e);return b.sandboxId?t.get(b.sandboxId):t.createSandboxRuntimeSandbox(e,c,p).then(l=>l.sandbox)},"currentSandbox"),o=d(async(c={},p={})=>{let b=await t.getSandboxRuntime(e);if(!b.sandboxId)return t.createSandboxRuntimeSandbox(e,c,p).then(g=>g.sandbox);let l=await t.get(b.sandboxId);return l.state==="stopped"?t.start(l.id,p).then(g=>g.sandbox):l.state==="archived"?t.restore(l.id).then(g=>g.sandbox):l.state==="deleted"||l.state==="error"?t.createSandboxRuntimeSandbox(e,c,p).then(g=>g.sandbox):l},"resume");return{id:e,initial:n,get:d(()=>t.getSandboxRuntime(e),"get"),sandbox:r,resume:o,createSandbox:d((c={},p={})=>t.createSandboxRuntimeSandbox(e,c,p),"createSandbox"),status:d(async c=>{if(typeof c!="string")return t.updateSandboxRuntimeStatus(e,c);let p=await t.getSandboxRuntime(e);return t.updateSandboxRuntimeStatus(e,{status:c,expectedVersion:p.version})},"status"),events:d(()=>t.listSandboxRuntimeEvents(e),"events"),event:d(c=>t.emitSandboxRuntimeEvent(e,c),"event"),recordCommit:d((c,p={})=>t.emitSandboxRuntimeEvent(e,{...p,type:p.type??"git.commit",commitSha:c}),"recordCommit"),checkpointHint:d((c={})=>t.emitSandboxRuntimeEvent(e,{type:"workflow.checkpoint_hint",summary:c.summary??c.reason??"Workflow checkpoint hint",payload:{...c.payload,reason:c.reason??null},artifactRefs:c.artifactRefs,lifecycleHint:{kind:"checkpoint",reason:c.reason??null}}),"checkpointHint"),waitForUser:d(async(c={})=>{await t.emitSandboxRuntimeEvent(e,{type:"workflow.waiting_for_user",summary:c.summary??c.reason??"Waiting for user",payload:{...c.payload,reason:c.reason??null},lifecycleHint:{kind:"waiting_for_user",reason:c.reason??null}});let p=await t.getSandboxRuntime(e);return p.status==="waiting_for_user"?p:t.updateSandboxRuntimeStatus(e,{status:"waiting_for_user",expectedVersion:p.version,summary:c.summary??c.reason,metadata:{workflowWaitForUserReason:c.reason??null}})},"waitForUser"),keepAlive:d((c={})=>{let p=mn(c);return t.emitSandboxRuntimeEvent(e,{type:"workflow.keepalive",summary:c.summary??c.reason??"Workflow keepalive",payload:{...c.payload,reason:c.reason??null,keepaliveUntil:p},lifecycleHint:{kind:"keepalive",reason:c.reason??null,keepaliveUntil:p}})},"keepAlive"),checkpoint:d(c=>t.checkpointSandboxRuntime(e,c),"checkpoint"),files:{write:d(async(c,p)=>t.uploadFile((await o()).id,c,p),"write"),read:d(async c=>t.downloadFile((await o()).id,c),"read"),readResponse:d(async c=>t.downloadFileResponse((await o()).id,c),"readResponse"),list:d(async(c={})=>t.listFiles((await o()).id,c),"list"),delete:d(async(c,p={})=>t.deleteFile((await o()).id,c,p),"delete"),search:d(async c=>t.searchFiles((await o()).id,c),"search"),stat:d(async c=>t.statFile((await o()).id,c),"stat"),mkdir:d(async c=>t.mkdir((await o()).id,c),"mkdir"),move:d(async c=>t.moveFile((await o()).id,c),"move")},commands:{run:d(async c=>t.exec((await o()).id,typeof c=="string"?{command:c}:c),"run")},ports:{expose:d(async c=>t.openPort((await o()).id,typeof c=="number"?{port:c}:c),"expose")},promote:d((c,p={})=>t.promoteSandboxRuntime(e,c,p),"promote"),preserveSource:d((c={},p={})=>t.preserveSandboxRuntimeSource(e,c,p),"preserveSource"),archive:d(async c=>{let p=c??(await t.getSandboxRuntime(e)).version;return t.updateSandboxRuntimeStatus(e,{status:"archived",expectedVersion:p})},"archive")}}d(pn,"createSandboxRuntimeHandle");function mn(t){if(t?.until instanceof Date)return t.until.toISOString();if(typeof t?.until=="string"&&t.until.trim())return new Date(t.until).toISOString();let e=typeof t?.seconds=="number"&&Number.isFinite(t.seconds)?Math.max(1,Math.trunc(t.seconds)):60;return new Date(Date.now()+e*1e3).toISOString()}d(mn,"runtimeKeepaliveUntilIso");async function ln(t,e={}){let n=`openpond-code-smoke-${Date.now()}`,r=`openpond-code-exec-ok:${n}`,o=`openpond-code-preview-ok:${n}`,s=`openpond-code-file-ok:${n}`,i=4173,u=null,c=null,p=!1,b=!1;try{let l=await Ye(t,await t.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:n,source:"openpond-code-sandbox-smoke"}},{async:!0}));u=l.id;let g=e.expectedMppMode;if(g&&l.reservation.mpp?.mode!==g)throw new Error(`expected ${g} reservation, got ${l.reservation.mpp?.mode??"none"}`);if(!g&&!l.reservation.mpp?.mode)throw new Error("expected sandbox reservation MPP metadata");let C=await t.exec(l.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('${o}')).listen(${i}, '0.0.0.0');`,"EOF","nohup node server.cjs > server.log 2>&1 & sleep 1"].join(`
3
+ `),timeoutSeconds:120});if(C.command.status!=="succeeded")throw new Error(`expected command success, got ${C.command.status}`);if(!C.command.output.includes(r))throw new Error("expected exec marker");if(await t.uploadFile(l.id,"openpond-code-smoke.txt",s),await t.downloadFile(l.id,"openpond-code-smoke.txt")!==s)throw new Error("expected file roundtrip marker");let U=null;if(e.snapshot||e.fork){let P=await t.createSnapshot(l.id,{async:!0,name:`openpond-code-smoke-${n}`,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"}]}}}),{snapshot:A}=await yn(t,l.id,P.snapshotJob.snapshotId);if(U=A.id,A.state!=="ready")throw new Error(`expected ready snapshot, got ${A.state}`)}if(e.fork){if(!U)throw new Error("expected snapshot id before fork");let P=await Ye(t,(await t.forkSnapshot(U,{budget:{maxUsd:e.budgetUsd??"0.05"},metadata:{source:"openpond-code-sandbox-smoke-fork",templateSnapshotId:U}},{async:!0})).sandbox);c=P.id;let A=await t.exec(P.id,{command:"cat openpond-code-smoke.txt",timeoutSeconds:120});if(A.command.status!=="succeeded")throw new Error(`expected fork command success, got ${A.command.status}`);if(!A.command.output.includes(s))throw new Error("expected fork snapshot marker");e.keep||(await fe(t,P.id),b=!0)}let j=null;if(e.preview!==!1){let P=await t.openPort(l.id,{label:"openpond-code-smoke",port:i}),A=await fetch(P.preview.url);j=A.status;let $t=await A.text();if(A.status!==200)throw new Error(`expected preview HTTP 200, got ${A.status}`);if(!$t.includes(o))throw new Error("expected preview marker")}let{sandbox:ne,receipts:J}=await hn(t,l.id);return e.keep||(await fe(t,l.id),p=!0),{deleted:p,execOutput:C.command.output.trim(),fileRoundtrip:!0,forkSandboxId:c,previewStatus:j,receiptRefs:J.map(P=>P.mpp.receiptRef??null),reservationRef:l.reservation.mpp?.reservationRef??null,runId:n,sandboxId:l.id,snapshotId:U,state:ne.state}}finally{c&&!e.keep&&!b&&await Ve(t,c),u&&!e.keep&&!p&&await Ve(t,u)}}d(ln,"runSandboxSmoke");async function hn(t,e){try{await t.stop(e)}catch{await t.stop(e,{async:!0})}let n=await Qe(t,e,new Set(["stopped","deleted"]),"stop"),r=await fn(t,e);if(r.length===0)throw new Error("expected receipt readback");return{sandbox:n,receipts:r}}d(hn,"stopSandboxForSmoke");async function fe(t,e){try{let n=await t.delete(e);if(n.state==="deleted")return n;await t.delete(e,{async:!0})}catch{await t.delete(e,{async:!0})}return Qe(t,e,new Set(["deleted"]),"delete")}d(fe,"deleteSandboxForSmoke");async function Ve(t,e){try{await fe(t,e)}catch{await t.delete(e,{async:!0}).catch(()=>{})}}d(Ve,"cleanupSandboxBestEffort");async function Qe(t,e,n,r){let i=Date.now()+3e5,u=await t.get(e);for(;Date.now()<i;){if(n.has(u.state))return u;if(u.state==="error")throw new Error(`sandbox ${r} failed: ${e}`);await V(3e3),u=await t.get(e)}throw new Error(`sandbox ${r} did not reach ${[...n].join("/")} before timeout: ${e} (${u.state})`)}d(Qe,"waitForSandboxState");async function fn(t,e){let o=Date.now()+12e4,s=await t.receipts(e);for(;Date.now()<o;){if(s.length>0)return s;await V(3e3),s=await t.receipts(e)}return s}d(fn,"waitForReceipts");async function Ye(t,e){if(e.state==="running"||e.state==="stopped")return e;if(e.state==="error")throw new Error(`sandbox create failed: ${e.id}
4
+ ${e.logs.join(`
5
+ `)}`);let n=12*6e4,r=3e3,o=Date.now()+n,s=e;for(;Date.now()<o;){if(await V(r),s=await t.get(e.id),s.state==="running"||s.state==="stopped")return s;if(s.state==="error")throw new Error(`sandbox create failed: ${s.id}
6
+ ${s.logs.join(`
7
+ `)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${s.id} (${s.state})`)}d(Ye,"waitForCreateReady");async function yn(t,e,n){if(!n)throw new Error("snapshot job did not return snapshot id");let r=12*6e4,o=3e3,s=Date.now()+r,i=await t.get(e);for(;Date.now()<s;){let u=i.snapshots?.find(p=>p.id===n);if(u?.state==="ready")return{sandbox:i,snapshot:u};let c=i.snapshotJobs?.find(p=>p.snapshotId===n);if(c?.status==="failed")throw new Error(`snapshot job failed: ${c.error??n}`);await V(o),i=await t.get(e)}throw new Error(`snapshot did not reach ready state before timeout: ${n}`)}d(yn,"waitForSnapshotReady");function V(t){return new Promise(e=>setTimeout(e,t))}d(V,"sleep");function M(t={}){return t.async||t.respondAsync?{Prefer:"respond-async"}:void 0}d(M,"asyncRequestHeaders");var gn="https://openpond.ai",ye="https://api.openpond.ai";async function Ze(t){let e=await X(t.sandboxApiUrl,t.apiKey,t.path,{timeoutMs:0,maxResponseBytes:0});if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:s,value:i}=await n.read();if(s)break;o+=r.decode(i,{stream:!0});let u=o.indexOf(`
8
+
9
+ `);for(;u!==-1;){let c=o.slice(0,u);o=o.slice(u+2);let p=In(c);p&&process.stdout.write(p),u=o.indexOf(`
10
+
11
+ `)}}}finally{n.releaseLock()}}d(Ze,"streamSandboxEventOutput");function bn(t){return typeof t=="string"?{dataBase64:Buffer.from(t,"utf-8").toString("base64")}:t instanceof Uint8Array?{dataBase64:Buffer.from(t).toString("base64")}:t}d(bn,"normalizePtyInput");function In(t){if(!t.includes("event: output"))return null;let e=t.split(/\r?\n/).filter(n=>n.startsWith("data: ")).map(n=>n.slice(6));if(e.length===0)return null;try{let n=JSON.parse(e.join(`
12
+ `));return typeof n.output=="string"?n.output:null}catch{return null}}d(In,"parseProcessOutputEvent");function O(t,e={}){let n=t.trim().replace(/\/$/,"");if(!n)throw new Error("sandbox API URL must be non-empty");let r=new URL(n),o=r.pathname.replace(/\/$/,"");if(o.endsWith("/v1/sandboxes")||o.endsWith("/api/sandboxes"))return`${r.origin}${o}`;if(o.endsWith("/v1"))return`${r.origin}${o}/sandboxes`;if(r.origin===gn)return`${ye}/v1/sandboxes`;let s=e.apiBaseUrl?new URL(e.apiBaseUrl).origin:ye;return r.origin===s?`${r.origin}${o}/v1/sandboxes`:`${r.origin}${o}/api/sandboxes`}d(O,"normalizeSandboxApiUrl");function Sn(t){let e="/sandboxes";if(!t.endsWith(e))throw new Error("sandbox API URL must end with /sandboxes");return t.slice(0,-e.length)}d(Sn,"apiRootUrlFromSandboxApiUrl");var wn=class{static{d(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;customEndpoint;constructor(t){this.apiKey=t.apiKey,this.customEndpoint=t.customEndpoint??!1;let e=t.sandboxApiUrl??t.baseUrl??ye;this.sandboxApiUrl=O(e,{apiBaseUrl:this.customEndpoint?void 0:e}),this.apiRootUrl=Sn(this.sandboxApiUrl)}create(t,e={}){return this.request("",{method:"POST",...this.customEndpoint?{timeoutMs:18e4}:{},headers:M(e),body:JSON.stringify(t)}).then(n=>n.sandbox)}get(t){return this.request(`/${encodeURIComponent(t)}`).then(e=>e.sandbox)}exec(t,e){return this.request(`/${encodeURIComponent(t)}/exec`,{method:"POST",body:JSON.stringify(e)})}startProcess(t,e){return this.request(`/${encodeURIComponent(t)}/processes`,{method:"POST",body:JSON.stringify(e)})}listProcesses(t){return this.request(`/${encodeURIComponent(t)}/processes`)}getProcess(t,e,n={}){let r=new URLSearchParams;return n.since!==void 0&&r.set("since",String(Math.max(0,n.since))),this.request(`/${encodeURIComponent(t)}/processes/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`)}stopProcess(t,e){return this.request(`/${encodeURIComponent(t)}/processes/${encodeURIComponent(e)}`,{method:"DELETE"})}async streamProcessOutput(t,e,n={}){let r=new URLSearchParams;n.since!==void 0&&r.set("since",String(Math.max(0,n.since))),await Ze({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(t)}/processes/${encodeURIComponent(e)}/stream${r.size>0?`?${r.toString()}`:""}`})}startPty(t,e={}){return this.request(`/${encodeURIComponent(t)}/pty`,{method:"POST",body:JSON.stringify(e)})}listPtys(t){return this.request(`/${encodeURIComponent(t)}/pty`)}getPty(t,e,n={}){let r=new URLSearchParams;return n.since!==void 0&&r.set("since",String(Math.max(0,n.since))),this.request(`/${encodeURIComponent(t)}/pty/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`)}writePtyInput(t,e,n){return this.request(`/${encodeURIComponent(t)}/pty/${encodeURIComponent(e)}/input`,{method:"POST",body:JSON.stringify(bn(n))})}stopPty(t,e){return this.request(`/${encodeURIComponent(t)}/pty/${encodeURIComponent(e)}`,{method:"DELETE"})}async streamPtyOutput(t,e,n={}){let r=new URLSearchParams;n.since!==void 0&&r.set("since",String(Math.max(0,n.since))),await Ze({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(t)}/pty/${encodeURIComponent(e)}/stream${r.size>0?`?${r.toString()}`:""}`})}uploadFile(t,e,n){return this.uploadFileBase64(t,e,Buffer.from(n,"utf-8").toString("base64"))}uploadFileBase64(t,e,n){return this.request(`/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify({path:e,contentsBase64:n})})}async downloadFile(t,e){let n=await this.downloadFileResponse(t,e);return Buffer.from(n.file.contentsBase64,"base64").toString("utf-8")}downloadFileResponse(t,e){let n=typeof e=="string"?{path:e}:e,r=new URLSearchParams({path:n.path});return n.offsetBytes!==void 0&&r.set("offsetBytes",String(n.offsetBytes)),n.maxBytes!==void 0&&r.set("maxBytes",String(n.maxBytes)),this.request(`/${encodeURIComponent(t)}/files?${r.toString()}`)}listFiles(t,e={}){let n=new URLSearchParams({list:"1"});return e.path&&n.set("path",e.path),e.recursive!==void 0&&n.set("recursive",String(e.recursive)),e.maxEntries!==void 0&&n.set("maxEntries",String(e.maxEntries)),this.request(`/${encodeURIComponent(t)}/files?${n.toString()}`)}deleteFile(t,e,n={}){let r=new URLSearchParams({path:e});return n.recursive!==void 0&&r.set("recursive",String(n.recursive)),this.request(`/${encodeURIComponent(t)}/files?${r.toString()}`,{method:"DELETE"})}statFile(t,e){let n=new URLSearchParams({stat:"1",path:e});return this.request(`/${encodeURIComponent(t)}/files?${n.toString()}`)}mkdir(t,e){let n=typeof e=="string"?{path:e}:e,r=new URLSearchParams({path:n.path});return n.recursive!==void 0&&r.set("recursive",String(n.recursive)),this.request(`/${encodeURIComponent(t)}/files?${r.toString()}`,{method:"PUT"})}moveFile(t,e){let n=new URLSearchParams({fromPath:e.fromPath,toPath:e.toPath});return e.overwrite!==void 0&&n.set("overwrite",String(e.overwrite)),this.request(`/${encodeURIComponent(t)}/files?${n.toString()}`,{method:"PATCH"})}searchFiles(t,e){let n=new URLSearchParams({search:"1",query:e.query});return e.path&&n.set("path",e.path),e.maxResults!==void 0&&n.set("maxResults",String(e.maxResults)),this.request(`/${encodeURIComponent(t)}/files?${n.toString()}`)}openPort(t,e){return this.request(`/${encodeURIComponent(t)}/ports`,{method:"POST",body:JSON.stringify(e)})}createSnapshot(t,e){return this.request(`/${encodeURIComponent(t)}/snapshots`,{method:"POST",body:JSON.stringify(e)})}updateSnapshot(t,e,n){return this.request(`/${encodeURIComponent(t)}/snapshots/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}validateSnapshot(t,e,n={}){return this.request(`/${encodeURIComponent(t)}/snapshots/${encodeURIComponent(e)}/validate`,{method:"POST",body:JSON.stringify(n)})}publishSnapshot(t,e){return this.request(`/${encodeURIComponent(t)}/snapshots/${encodeURIComponent(e)}/publish`,{method:"POST"})}fork(t,e={}){return this.request(`/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify(e)})}stop(t,e={}){let n=new URLSearchParams;return e.failOnUnpreservedChanges&&n.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(t)}/stop${n.size>0?`?${n.toString()}`:""}`,{method:"POST",headers:M(e)})}start(t,e={}){return this.request(`/${encodeURIComponent(t)}/start`,{method:"POST",headers:M(e),...e.restore?{body:JSON.stringify({restore:e.restore})}:{}})}restore(t,e){return this.request(`/${encodeURIComponent(t)}/restore`,{method:"POST",...e?{body:JSON.stringify(e)}:{}})}delete(t,e={}){let n=new URLSearchParams;return e.failOnUnpreservedChanges&&n.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(t)}${n.size>0?`?${n.toString()}`:""}`,{method:"DELETE",headers:M(e)}).then(r=>r.sandbox)}receipts(t){return this.request(`/${encodeURIComponent(t)}/receipts`).then(e=>e.receipts)}logs(t){return this.request(`/${encodeURIComponent(t)}/logs`).then(e=>e.logs)}gitStatus(t){return this.request(`/${encodeURIComponent(t)}/git/status`)}gitDiff(t,e={}){return this.request(`/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(e)})}gitExportPatch(t,e={}){return this.request(`/${encodeURIComponent(t)}/git/export-patch`,{method:"POST",body:JSON.stringify(e)})}gitBranch(t,e){return this.request(`/${encodeURIComponent(t)}/git/branch`,{method:"POST",body:JSON.stringify(e)})}gitCommit(t,e){return this.request(`/${encodeURIComponent(t)}/git/commit`,{method:"POST",body:JSON.stringify(e)})}gitPull(t,e={}){return this.request(`/${encodeURIComponent(t)}/git/pull`,{method:"POST",body:JSON.stringify(e)})}gitPush(t,e={}){return this.request(`/${encodeURIComponent(t)}/git/push`,{method:"POST",body:JSON.stringify(e)})}billing(t,e){let n=new URLSearchParams;return e&&(n.set("snapshotRetentionTtlSeconds",String(e.snapshotRetentionTtlSeconds)),n.set("snapshotRetentionClass",e.snapshotRetentionClass)),this.request(`/${encodeURIComponent(t)}/billing${n.size?`?${n}`:""}`)}pricing(){return this.request("/pricing")}costs(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.agentId&&e.set("agentId",t.agentId),this.request(`/costs${e.size>0?`?${e.toString()}`:""}`)}integrationLeases(t){return this.request(`/${encodeURIComponent(t)}/integrations`)}attachIntegrationConnection(t,e){return this.request(`/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(e)})}removeIntegrationLease(t,e){return this.request(`/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:e})})}async request(t,e={}){let n=await X(this.sandboxApiUrl,this.apiKey,t,this.customEndpoint?{...e,explicitBearerAuth:!0,redirect:"error"}:e);return me(n,"Sandbox request")}async requestApiRoot(t,e={}){let n=await X(this.apiRootUrl,this.apiKey,t,this.customEndpoint?{...e,explicitBearerAuth:!0,redirect:"error"}:e);return me(n,"OpenPond API request")}},xn=class extends wn{static{d(this,"OpenPondSandboxClient")}runtimes=an(this);sandboxes=sn(this);profile=cn(this);projects=dn(this);agents=un(this);list(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.agentId&&e.set("agentId",t.agentId),this.request(e.size>0?`?${e.toString()}`:"").then(n=>n.sandboxes)}listSecrets(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets${e.size>0?`?${e.toString()}`:""}`).then(n=>n.secrets)}getSecret(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(t)}${n.size>0?`?${n.toString()}`:""}`).then(r=>r.secret)}createSecret(t){return this.requestApiRoot("/sandbox-secrets",{method:"POST",body:JSON.stringify(t)}).then(e=>e.secret)}rotateSecret(t,e){let n=new URLSearchParams;e.teamId&&n.set("teamId",e.teamId);let{teamId:r,...o}=e;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(t)}/rotate${n.size>0?`?${n.toString()}`:""}`,{method:"POST",body:JSON.stringify(o)}).then(s=>s.secret)}attachSecret(t,e){let n=new URLSearchParams;e.teamId&&n.set("teamId",e.teamId);let{teamId:r,...o}=e;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(t)}/attach${n.size>0?`?${n.toString()}`:""}`,{method:"POST",body:JSON.stringify(o)}).then(s=>s.secret)}revokeSecret(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(t)}/revoke${n.size>0?`?${n.toString()}`:""}`,{method:"POST"}).then(r=>r.secret)}deleteSecret(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(t)}${n.size>0?`?${n.toString()}`:""}`,{method:"DELETE"}).then(r=>r.secret)}snapshotCatalog(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.agentId&&e.set("agentId",t.agentId),t.q&&e.set("q",t.q),t.kind&&e.set("kind",t.kind),t.replayState&&e.set("replayState",t.replayState),t.visibility&&e.set("visibility",t.visibility),t.tag&&e.set("tag",t.tag),t.useCase&&e.set("useCase",t.useCase),t.limit&&e.set("limit",String(t.limit)),this.request(`/catalog/snapshots${e.size>0?`?${e.toString()}`:""}`)}listSandboxRuntimes(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.agentId&&e.set("agentId",t.agentId),this.requestApiRoot(`/runtimes${e.size>0?`?${e.toString()}`:""}`).then(n=>n.runtimes)}listProjects(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects?${e.toString()}`).then(n=>n.projects)}upsertProject(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects?${e.toString()}`,{method:"POST",body:JSON.stringify(t)}).then(n=>n.project)}getHostedProfile(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/profile?${e.toString()}`).then(n=>n.profile)}ensureHostedProfile(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/profile/ensure?${e.toString()}`,{method:"POST"}).then(n=>{if(!n.profile)throw new Error("hosted_profile_missing");return n.profile})}pushHostedProfile(t){let e=new URLSearchParams({teamId:t.teamId}),{teamId:n,...r}=t;return this.requestApiRoot(`/profile/push?${e.toString()}`,{method:"POST",body:JSON.stringify(r)})}async upsertProjectGitRemote(t){let e=await this.upsertProject(t);return this.ensureProjectGitRemote(e.id,{teamId:t.teamId})}getProject(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(t)}?${n.toString()}`).then(r=>r.project)}syncProject(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(t)}/sync?${n.toString()}`,{method:"POST"}).then(r=>r.project)}ensureProjectGitRemote(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(t)}/git?${n.toString()}`,{method:"POST"})}uploadProjectSource(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/projects/${encodeURIComponent(t)}/source?${n.toString()}`,{method:"POST",body:JSON.stringify(o)}).then(s=>s.project)}updateProject(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/projects/${encodeURIComponent(t)}?${n.toString()}`,{method:"PATCH",body:JSON.stringify(o)}).then(s=>s.project)}archiveProject(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(t)}?${n.toString()}`,{method:"DELETE"}).then(r=>r.project)}listAgents(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents?${e.toString()}`).then(n=>n.agents)}upsertAgent(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents?${e.toString()}`,{method:"POST",body:JSON.stringify(t)}).then(n=>n.agent)}getAgent(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(t)}?${n.toString()}`).then(r=>r.agent)}archiveAgent(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(t)}?${n.toString()}`,{method:"DELETE"}).then(r=>r.agent)}updateAgent(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/agents/${encodeURIComponent(t)}?${n.toString()}`,{method:"PATCH",body:JSON.stringify(o)}).then(s=>s.agent)}runAgent(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/agents/${encodeURIComponent(t)}/run?${n.toString()}`,{method:"POST",headers:{Prefer:"respond-async"},body:JSON.stringify(o)})}getAgentSourceDeployPlan(t,e){let n=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(t)}/source/deploy-plan?${n.toString()}`).then(r=>r.deployPlan)}listAgentManifestSnapshots(t,e){let n=new URLSearchParams({teamId:e.teamId});return e.limit!==void 0&&n.set("limit",String(e.limit)),this.requestApiRoot(`/agents/${encodeURIComponent(t)}/source/manifest-snapshots?${n.toString()}`).then(r=>r.manifestSnapshots)}requestAgentSourceChecks(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/agents/${encodeURIComponent(t)}/source/checks?${n.toString()}`,{method:"POST",body:JSON.stringify(o),timeoutMs:900*1e3})}configureAgentSourceSetup(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/agents/${encodeURIComponent(t)}/source/setup?${n.toString()}`,{method:"POST",body:JSON.stringify(o)})}publishAgentSource(t,e){let n=new URLSearchParams({teamId:e.teamId}),{teamId:r,...o}=e;return this.requestApiRoot(`/agents/${encodeURIComponent(t)}/source/publish?${n.toString()}`,{method:"POST",body:JSON.stringify(o)})}getMicrosoftTeamsBotOverview(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/teams/bot/overview?${e.toString()}`)}bindMicrosoftTeamsBotConversation(t){return this.requestApiRoot("/teams/bot/bindings",{method:"POST",body:JSON.stringify(t)})}rebindMicrosoftTeamsBotConversation(t,e){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)})}unlinkMicrosoftTeamsBotConversation(t){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(t.bindingId)}`,{method:"DELETE",body:JSON.stringify({teamId:t.teamId})})}sendMicrosoftTeamsBotDiagnostic(t){return this.requestApiRoot("/teams/bot/diagnostics",{method:"POST",body:JSON.stringify(t)})}sendMicrosoftTeamsBotDiagnosticRun(t){return this.requestApiRoot("/teams/bot/diagnostics/run",{method:"POST",body:JSON.stringify(t)})}createSandboxRuntime(t){return this.requestApiRoot("/runtimes",{method:"POST",body:JSON.stringify(t)}).then(e=>e.runtime)}sandboxRuntime(t,e=null){return pn(this,t,e)}getSandboxRuntime(t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}`).then(e=>e.runtime)}createSandboxRuntimeSandbox(t,e={},n={}){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/sandbox`,{method:"POST",headers:M(n),body:JSON.stringify(e)})}updateSandboxRuntimeStatus(t,e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/status`,{method:"PATCH",body:JSON.stringify(e)}).then(n=>n.runtime)}listSandboxRuntimeEvents(t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/events`)}emitSandboxRuntimeEvent(t,e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/events`,{method:"POST",body:JSON.stringify(e)})}checkpointSandboxRuntime(t,e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/checkpoints`,{method:"POST",body:JSON.stringify(e)}).then(n=>n.runtime)}promoteSandboxRuntime(t,e,n={}){let r=new URLSearchParams;return n.teamId&&r.set("teamId",n.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/promote${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(e)})}preserveSandboxRuntimeSource(t,e={},n={}){let r=new URLSearchParams;return n.teamId&&r.set("teamId",n.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(t)}/preserve-source${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(e)})}forkSnapshot(t,e={},n={}){let r=new URLSearchParams;e.teamId&&r.set("teamId",e.teamId),e.projectId&&r.set("projectId",e.projectId),n.async&&r.set("async","1");let{teamId:o,projectId:s,...i}=e;return this.request(`/catalog/snapshots/${encodeURIComponent(t)}/fork${r.size>0?`?${r.toString()}`:""}`,{method:"POST",headers:n.async?{Prefer:"respond-async"}:void 0,body:JSON.stringify({...i,snapshotId:t})})}templates(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.q&&e.set("q",t.q),t.name&&e.set("name",t.name),t.version&&e.set("version",t.version),t.visibility&&e.set("visibility",t.visibility),t.tag&&e.set("tag",t.tag),t.useCase&&e.set("useCase",t.useCase),t.limit&&e.set("limit",String(t.limit)),this.request(`/templates${e.size>0?`?${e.toString()}`:""}`)}publishedSnapshots(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.q&&e.set("q",t.q),t.name&&e.set("name",t.name),t.version&&e.set("version",t.version),t.visibility&&e.set("visibility",t.visibility),t.tag&&e.set("tag",t.tag),t.useCase&&e.set("useCase",t.useCase),t.limit&&e.set("limit",String(t.limit)),this.request(`/published-snapshots${e.size>0?`?${e.toString()}`:""}`).then(n=>{let r=n.publishedSnapshots??n.templates;return{...n,templates:r,publishedSnapshots:r}})}launchTemplate(t){let e=new URLSearchParams;t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId);let{teamId:n,projectId:r,...o}=t;return this.request(`/templates/launch${e.size>0?`?${e.toString()}`:""}`,{method:"POST",body:JSON.stringify(o)})}runPublishedSnapshot(t){let e=new URLSearchParams;t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId);let{teamId:n,projectId:r,...o}=t;return this.request(`/published-snapshots/launch${e.size>0?`?${e.toString()}`:""}`,{method:"POST",body:JSON.stringify(o)}).then(s=>{let i=s.publishedSnapshot??s.template;return{...s,template:i,publishedSnapshot:i}})}listSchedules(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.sourceSandboxId&&e.set("sourceSandboxId",t.sourceSandboxId),this.request(`/schedules${e.size>0?`?${e.toString()}`:""}`)}createSchedule(t){let e=new URLSearchParams;t.projectId&&e.set("projectId",t.projectId);let{projectId:n,...r}=t;return this.request(`/schedules${e.size>0?`?${e.toString()}`:""}`,{method:"POST",body:JSON.stringify(r)})}getSchedule(t){return this.request(`/schedules/${encodeURIComponent(t)}`)}updateSchedule(t,e){return this.request(`/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)})}deleteSchedule(t){return this.request(`/schedules/${encodeURIComponent(t)}`,{method:"DELETE"})}listScheduleRuns(t,e={}){let n=new URLSearchParams;return e.limit!==void 0&&n.set("limit",String(e.limit)),this.request(`/schedules/${encodeURIComponent(t)}/runs${n.size>0?`?${n.toString()}`:""}`)}runScheduleNow(t,e={}){return this.request(`/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(e)})}listTemplateBuilds(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/sandbox-template-builds?${e.toString()}`).then(n=>n.builds)}createTemplateBuild(t){return this.requestApiRoot("/sandbox-template-builds",{method:"POST",body:JSON.stringify(t)}).then(e=>e.build)}getTemplateBuild(t){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(t)}`).then(e=>e.build)}getTemplateBuildLogs(t){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(t)}/logs`)}cancelTemplateBuild(t){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(t)}/cancel`,{method:"POST"}).then(e=>e.build)}listPublishedSnapshotBuilds(t){let e=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/published-snapshot-builds?${e.toString()}`).then(n=>n.builds)}createPublishedSnapshotBuild(t){return this.requestApiRoot("/published-snapshot-builds",{method:"POST",body:JSON.stringify(t)}).then(e=>e.build)}getPublishedSnapshotBuild(t){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(t)}`).then(e=>e.build)}getPublishedSnapshotBuildLogs(t){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(t)}/logs`)}cancelPublishedSnapshotBuild(t){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(t)}/cancel`,{method:"POST"}).then(e=>e.build)}listOrganizations(){return this.requestApiRoot("/organizations").then(t=>t.organizations??t.teams??[])}createOrganization(t){return this.requestApiRoot("/organizations",{method:"POST",body:JSON.stringify(t)}).then(e=>e.organization)}getOrganization(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}`).then(e=>e.organization)}updateOrganization(t,e){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)}).then(n=>n.organization)}listOrganizationMembers(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/members`).then(e=>e.members)}upsertOrganizationMember(t,e){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(e)}).then(n=>n.member)}getOrganizationMcpServer(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/mcp-server`).then(e=>e.mcpServer)}generateOrganizationMcpServer(t,e={}){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(e)}).then(n=>n.mcpServer)}rotateOrganizationMcpServer(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/mcp-server/rotate`,{method:"POST"}).then(e=>e.mcpServer)}disableOrganizationMcpServer(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/mcp-server/disable`,{method:"POST"}).then(e=>e.mcpServer)}enableOrganizationMcpServer(t){return this.requestApiRoot(`/organizations/${encodeURIComponent(t)}/mcp-server/enable`,{method:"POST"}).then(e=>e.mcpServer)}startReplay(t){let e=new URLSearchParams;t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId);let{teamId:n,projectId:r,...o}=t;return this.requestApiRoot(`/sandbox-replays${e.size>0?`?${e.toString()}`:""}`,{method:"POST",body:JSON.stringify(o)})}listReplays(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays${e.size>0?`?${e.toString()}`:""}`)}getReplay(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),e.projectId&&n.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(t)}${n.size>0?`?${n.toString()}`:""}`)}getReplayLogs(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),e.projectId&&n.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(t)}/logs${n.size>0?`?${n.toString()}`:""}`)}getReplayArtifacts(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),e.projectId&&n.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(t)}/artifacts${n.size>0?`?${n.toString()}`:""}`)}cancelReplay(t,e={}){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),e.projectId&&n.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(t)}/cancel${n.size>0?`?${n.toString()}`:""}`,{method:"POST"})}integrationConnections(t={}){let e=new URLSearchParams;return t.teamId&&e.set("teamId",t.teamId),t.projectId&&e.set("projectId",t.projectId),t.agentId&&e.set("agentId",t.agentId),t.status&&e.set("status",t.status),this.requestApiRoot(`/integrations/connections${e.size>0?`?${e.toString()}`:""}`)}mcpServerConfig(){return{name:"openpond-sandboxes",transport:"streamable-http",url:`${this.sandboxApiUrl}/mcp`,headers:{"openpond-api-key":this.apiKey}}}smoke(t={}){return ln(this,t)}};function Y(t){return new xn(t)}d(Y,"createOpenPondSandboxClient");var Br=a.object({choices:a.array(a.object({message:a.object({content:a.string().nullable().optional(),tool_calls:a.array(a.object({id:a.string().min(1),type:a.literal("function"),function:a.object({name:a.string().min(1),arguments:a.string()})})).optional()})})).min(1)});var Nr=100*1024*1024;var Fr=Object.freeze({".avif":"image/avif",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".m4a":"audio/mp4",".md":"text/markdown",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});function $(t){let e=t?.trim();return e?e.replace(/\/$/,""):null}d($,"normalizeOptionalUrl");function m(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}d(m,"asRecord");var et=["workspacePurpose","purpose"];function tt(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={...t};for(let n of et)delete e[n];return e}d(tt,"sanitizeCreateMetadata");function vn(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={...t};for(let r of et)delete e[r];let n=tt(e.metadata);return n?e.metadata=n:delete e.metadata,e}d(vn,"sanitizeSandboxRuntimeInput");function Z(t){let e=m(t);if(e.sandboxRuntime)throw new Error("Sandbox runtime settings must use /v1/runtimes before materializing a sandbox.");let n={};typeof e.repo=="string"&&e.repo.trim()&&(n.repo=e.repo.trim()),typeof e.teamId=="string"&&e.teamId.trim()&&(n.teamId=e.teamId.trim()),typeof e.projectId=="string"&&e.projectId.trim()&&(n.projectId=e.projectId.trim()),typeof e.agentId=="string"&&e.agentId.trim()&&(n.agentId=e.agentId.trim()),typeof e.command=="string"&&e.command.trim()&&(n.command=e.command.trim()),typeof e.runtimeProfileId=="string"&&e.runtimeProfileId.trim()&&(n.runtimeProfileId=e.runtimeProfileId.trim()),e.workloadSource&&typeof e.workloadSource=="object"&&!Array.isArray(e.workloadSource)&&(n.workloadSource=e.workloadSource),e.sourceArchive&&typeof e.sourceArchive=="object"&&!Array.isArray(e.sourceArchive)&&(n.sourceArchive=e.sourceArchive),(e.visibility==="private"||e.visibility==="team")&&(n.visibility=e.visibility),e.resources&&typeof e.resources=="object"&&!Array.isArray(e.resources)&&(n.resources=e.resources),e.budget&&typeof e.budget=="object"&&!Array.isArray(e.budget)&&(n.budget=e.budget),"env"in e&&(n.env=ve(e.env)),e.networkPolicy&&typeof e.networkPolicy=="object"&&!Array.isArray(e.networkPolicy)&&(n.networkPolicy=e.networkPolicy),e.quotas&&typeof e.quotas=="object"&&!Array.isArray(e.quotas)&&(n.quotas=e.quotas),Array.isArray(e.volumes)&&(n.volumes=e.volumes),"integrationLeases"in e&&(n.integrationLeases=ot(e.integrationLeases)),Array.isArray(e.integrationConnectionLeases)&&(n.integrationConnectionLeases=e.integrationConnectionLeases);let r=tt(e.metadata);return r&&(n.metadata=r),n}d(Z,"normalizeCreateInput");function be(t){let e=m(t),n=vn(e)??{},r={};return typeof n.teamId=="string"&&n.teamId.trim()&&(r.teamId=n.teamId.trim()),typeof n.projectId=="string"&&n.projectId.trim()&&(r.projectId=n.projectId.trim()),typeof n.agentId=="string"&&n.agentId.trim()&&(r.agentId=n.agentId.trim()),typeof n.workflowMode=="string"&&n.workflowMode.trim()?r.workflowMode=n.workflowMode.trim():typeof n.mode=="string"&&n.mode.trim()&&(r.workflowMode=n.mode.trim()),typeof n.baseBranch=="string"&&n.baseBranch.trim()&&(r.baseBranch=n.baseBranch.trim()),typeof n.baseSha=="string"&&n.baseSha.trim()&&(r.baseSha=n.baseSha.trim()),typeof n.sandboxId=="string"&&n.sandboxId.trim()&&(r.sandboxId=n.sandboxId.trim()),typeof n.rootfsSnapshotId=="string"&&n.rootfsSnapshotId.trim()&&(r.rootfsSnapshotId=n.rootfsSnapshotId.trim()),typeof n.dependencySnapshotId=="string"&&n.dependencySnapshotId.trim()&&(r.dependencySnapshotId=n.dependencySnapshotId.trim()),typeof n.runtimeProfileId=="string"&&n.runtimeProfileId.trim()&&(r.runtimeProfileId=n.runtimeProfileId.trim()),typeof n.promotionPolicy=="string"&&n.promotionPolicy.trim()&&(r.promotionPolicy=n.promotionPolicy.trim()),n.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)&&(r.metadata=n.metadata),r}d(be,"normalizeSandboxRuntimeCreateInput");function Q(t){return Z(t)}d(Q,"normalizeSandboxRuntimeSandboxCreateInput");function nt(t){return m(t)}d(nt,"normalizeSnapshotCreateInput");function y(t){let e=m(t),n=typeof e.teamId=="string"?e.teamId.trim():"",r=typeof e.projectId=="string"?e.projectId.trim():"",o=typeof e.agentId=="string"?e.agentId.trim():"";return{...n?{teamId:n}:{},...r?{projectId:r}:{},...o?{agentId:o}:{}}}d(y,"normalizeSandboxListInput");function rt(t){let e=m(t),n=typeof e.teamId=="string"?e.teamId.trim():"",r=typeof e.projectId=="string"?e.projectId.trim():"",{teamId:o,projectId:s,appId:i,...u}=e,c=u;return n&&(c.teamId=n),r&&(c.projectId=r),c}d(rt,"normalizeReplayStartInput");function Ie(t){if(t==="active"||t==="revoked"||t==="error"||t==="all")return t}d(Ie,"normalizeIntegrationStatusFilter");function Se(t){let e=m(t),n=typeof e.connectionId=="string"?e.connectionId.trim():"";if(!n)throw new Error("Sandbox integration connection is required.");let r=st(e.capabilities);if(r.length===0)throw new Error("Sandbox integration capabilities are required.");at(e.provider,r);let o=it(e.scopes,"Sandbox integration scopes"),s=dt(e.expiresAt),i=En(e.ttlSeconds),u=ct(e.resourcePolicy);return{connectionId:n,capabilities:r,...o.length>0?{scopes:o}:{},...u?{resourcePolicy:u}:{},...s?{expiresAt:s}:{},...i!==void 0?{ttlSeconds:i}:{},...typeof e.required=="boolean"?{required:e.required}:{}}}d(Se,"normalizeIntegrationAttachInput");function ot(t){if(t==null)return[];if(!Array.isArray(t))throw new Error("Sandbox integration leases must be an array.");return t.map(e=>Rn(e))}d(ot,"normalizeIntegrationLeaseRefsForRuntime");function Rn(t){let e=m(t),n=typeof e.leaseId=="string"?e.leaseId.trim():"";if(!n)throw new Error("Sandbox integration leaseId is required.");if("connectionId"in e)throw new Error("Sandbox integration leases must use leaseId/proxy refs, not connection ids.");Pn(e);let r=Cn(e.provider),o=st(e.capabilities);if(o.length===0)throw new Error("Sandbox integration lease capabilities are required.");at(r,o);let s=it(e.scopes,"Sandbox integration lease scopes"),i=ct(e.resourcePolicy),u=dt(e.expiresAt),c=typeof e.proxyUrl=="string"?e.proxyUrl.trim():"";return{leaseId:n,provider:r,capabilities:o,...s.length>0?{scopes:s}:{},...i?{resourcePolicy:i}:{},...u?{expiresAt:u}:{},...c?{proxyUrl:c}:{},...typeof e.required=="boolean"?{required:e.required}:{}}}d(Rn,"normalizeIntegrationLeaseRefForRuntime");function Cn(t){if(typeof t!="string")throw new Error("Sandbox integration lease provider is required.");let e=se(t);if(!e)throw new Error(`Sandbox integration provider is not supported: ${t}`);if(!ae(e)?.leasePolicy.leaseable)throw new Error(`Sandbox integration provider is not leaseable: ${e}`);return e}d(Cn,"normalizeLeaseableIntegrationProvider");function Pn(t){for(let e of Object.keys(t))if(ut(e))throw new Error("Sandbox integration leases must not include secrets or credentials.")}d(Pn,"assertNoSensitiveIntegrationLeaseKeys");function at(t,e){if(t==null||t==="")return;if(typeof t!="string")throw new Error("Sandbox integration provider must be a string.");let n=se(t);if(!n)throw new Error(`Sandbox integration provider is not supported: ${t}`);let r=ae(n);if(!r?.leasePolicy.leaseable)throw new Error(`Sandbox integration provider is not leaseable: ${n}`);let o=new Set(r.leasePolicy.allowedCapabilityIds),s=e.filter(i=>!o.has(i));if(s.length>0)throw new Error(`Sandbox integration capabilities are not allowed for ${n}: ${s.join(", ")}`)}d(at,"validateIntegrationCapabilitiesForProvider");function we(t){let e=m(t),n=typeof e.leaseId=="string"?e.leaseId.trim():"";if(!n)throw new Error("Sandbox integration lease is required.");return n}d(we,"normalizeIntegrationLeaseId");function st(t){return Array.isArray(t)?t.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):[]}d(st,"normalizeStringArray");function it(t,e){if(t==null)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array of strings.`);return t.map(n=>{if(typeof n!="string")throw new Error(`${e} must contain only strings.`);let r=n.trim();if(!r)throw new Error(`${e} must not contain empty values.`);return r})}d(it,"normalizeOptionalStringArray");function En(t){if(t==null||t==="")return;let e=Number(t);if(!Number.isFinite(e)||e<=0)throw new Error("Sandbox integration ttlSeconds must be a positive number.");return Math.max(1,Math.floor(e))}d(En,"normalizeIntegrationTtlSeconds");function dt(t){if(t==null||t==="")return;if(typeof t!="string")throw new Error("Sandbox integration expiresAt must be an ISO timestamp string.");let e=t.trim();if(!e)return;let n=Date.parse(e);if(!Number.isFinite(n))throw new Error("Sandbox integration expiresAt must be a valid ISO timestamp.");return e}d(dt,"normalizeIntegrationExpiresAt");function ct(t){if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new Error("Sandbox integration resourcePolicy must be an object.");if(ge(t,[]),JSON.stringify(t).length>16*1024)throw new Error("Sandbox integration resourcePolicy is too large.");return t}d(ct,"normalizeIntegrationResourcePolicy");function ge(t,e){if(!(!t||typeof t!="object")){if(e.length>8)throw new Error("Sandbox integration resourcePolicy is too deeply nested.");if(Array.isArray(t)){for(let n of t)ge(n,e);return}for(let[n,r]of Object.entries(t)){if(ut(n))throw new Error("Sandbox integration resourcePolicy must not include secrets or credentials.");ge(r,[...e,n])}}}d(ge,"assertNoSensitiveResourcePolicyKeys");function ut(t){let e=t.toLowerCase().replace(/[^a-z0-9]/g,"");return e.includes("accesstoken")||e.includes("refreshtoken")||e.includes("idtoken")||e.includes("oauth")||e.includes("bearer")||e.includes("authorization")||e.includes("cookie")||e.includes("secret")||e.includes("password")||e.includes("credential")}d(ut,"isSensitivePolicyKey");function pt(t){let e=m(t),n=typeof e.command=="string"?e.command.trim():"";if(!n)throw new Error("Sandbox command is required.");let r=typeof e.timeoutSeconds=="number"&&Number.isFinite(e.timeoutSeconds)?Math.max(1,Math.floor(e.timeoutSeconds)):void 0,o=Ne(n);return r?{command:o,timeoutSeconds:r}:{command:o}}d(pt,"normalizeExecInput");function mt(t){let e=m(t),n=typeof e.command=="string"?e.command.trim():"";if(!n)throw new Error("Sandbox process command is required.");let r=typeof e.timeoutSeconds=="number"&&Number.isFinite(e.timeoutSeconds)?Math.max(1,Math.floor(e.timeoutSeconds)):void 0;return r?{command:n,timeoutSeconds:r}:{command:n}}d(mt,"normalizeProcessStartInput");function lt(t){let e=m(t),n=Number(e.since);return Number.isFinite(n)?{since:Math.max(0,Math.floor(n))}:{}}d(lt,"normalizeProcessCursorInput");function ht(t){let e=m(t),n=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(n)||n<re||n>oe)throw new Error(`Sandbox preview port must be between ${re} and ${oe}.`);let r=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,o=e.access==="public"||e.access==="private"?e.access:void 0,s=e.autoStart===!0,i=typeof e.customDomain=="string"&&e.customDomain.trim()?e.customDomain.trim():void 0,u={port:n,...r?{label:r}:{},...o?{access:o}:{},...s?{autoStart:s}:{},...i?{customDomain:i}:{}};return e.cors&&typeof e.cors=="object"&&!Array.isArray(e.cors)&&(u.cors=e.cors),e.headerPolicy&&typeof e.headerPolicy=="object"&&!Array.isArray(e.headerPolicy)&&(u.headerPolicy=e.headerPolicy),e.authPolicy&&typeof e.authPolicy=="object"&&!Array.isArray(e.authPolicy)&&(u.authPolicy=e.authPolicy),u}d(ht,"normalizeOpenPortInput");function ft(t){let e=m(t),n={};if(e.template&&typeof e.template=="object"&&!Array.isArray(e.template)){let r=m(e.template),o={};typeof r.description=="string"?o.description=r.description.trim():r.description===null&&(o.description=null),Array.isArray(r.tags)&&(o.tags=r.tags.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).slice(0,20)),(r.visibility==="private"||r.visibility==="team")&&(o.visibility=r.visibility),typeof r.useCase=="string"?o.useCase=r.useCase.trim():r.useCase===null&&(o.useCase=null),Object.keys(o).length>0&&(n.template=o)}if(e.retention&&typeof e.retention=="object"&&!Array.isArray(e.retention)){let r=m(e.retention),o={};(r.class==="ephemeral"||r.class==="cached"||r.class==="pinned")&&(o.class=r.class),r.ttlSeconds===null?o.ttlSeconds=null:typeof r.ttlSeconds=="number"&&Number.isFinite(r.ttlSeconds)&&(o.ttlSeconds=Math.max(1,Math.floor(r.ttlSeconds))),Object.keys(o).length>0&&(n.retention=o)}if(!n.template&&!n.retention)throw new Error("Snapshot update requires template or retention changes.");return n}d(ft,"normalizeSnapshotUpdateInput");function yt(t){let e=m(t),n=typeof e.cleanup=="string"?e.cleanup.trim():"";return n==="delete"||n==="stop"||n==="archive"?{cleanup:n}:{}}d(yt,"normalizeSnapshotValidateInput");function xe(t){let e=m(t),n={};return typeof e.snapshotId=="string"&&e.snapshotId.trim()&&(n.snapshotId=e.snapshotId.trim()),(e.visibility==="private"||e.visibility==="team")&&(n.visibility=e.visibility),e.resources&&typeof e.resources=="object"&&!Array.isArray(e.resources)&&(n.resources=e.resources),e.budget&&typeof e.budget=="object"&&!Array.isArray(e.budget)&&(n.budget=e.budget),e.networkPolicy&&typeof e.networkPolicy=="object"&&!Array.isArray(e.networkPolicy)&&(n.networkPolicy=e.networkPolicy),e.quotas&&typeof e.quotas=="object"&&!Array.isArray(e.quotas)&&(n.quotas=e.quotas),Array.isArray(e.volumes)&&(n.volumes=e.volumes),"integrationLeases"in e&&(n.integrationLeases=ot(e.integrationLeases)),"env"in e&&(n.env=ve(e.env)),e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)&&(n.metadata=e.metadata),n}d(xe,"normalizeForkInput");function ve(t){if(t==null)return[];if(!Array.isArray(t))throw new Error("Sandbox env must be an array.");return t.map(e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Sandbox env entries must be objects.");let n=e;if("value"in n)throw new Error("Sandbox env entries must use secretRef, not inline values.");let r=typeof n.name=="string"?n.name.trim():"",o=typeof n.secretRef=="string"?n.secretRef.trim():"";if(!r||!o)throw new Error("Sandbox env entries require name and secretRef.");return{name:r,secretRef:o}})}d(ve,"normalizeSandboxEnvRefsForApp");function gt(t){let e=m(t),n=typeof e.teamId=="string"?e.teamId.trim():"",r=typeof e.projectId=="string"?e.projectId.trim():"",o=typeof e.snapshotId=="string"?e.snapshotId.trim():"",s=typeof e.templateName=="string"?e.templateName.trim():"",i=typeof e.version=="string"?e.version.trim():"",u=typeof e.useCase=="string"?e.useCase.trim():"";if(!o&&!s&&!u)throw new Error("Sandbox template launch requires snapshotId, templateName, or useCase.");return{...xe(t),...n?{teamId:n}:{},...r?{projectId:r}:{},...o?{snapshotId:o}:{},...s?{templateName:s}:{},...i?{version:i}:{},...u?{useCase:u}:{}}}d(gt,"normalizeTemplateLaunchInput");function bt(t){let e=m(t),n=typeof e.path=="string"?e.path.trim():"",r=Number(e.maxEntries);return{...n?{path:n}:{},...typeof e.recursive=="boolean"?{recursive:e.recursive}:{},...Number.isFinite(r)?{maxEntries:r}:{}}}d(bt,"normalizeListFilesInput");function It(t){let e=m(t),n=typeof e.query=="string"?e.query.trim():"";if(!n)throw new Error("Sandbox file search query is required.");let r=typeof e.path=="string"?e.path.trim():"",o=Number(e.maxResults);return{query:n,...r?{path:r}:{},...Number.isFinite(o)?{maxResults:o}:{}}}d(It,"normalizeSearchFilesInput");function D(t){let e=m(t),n=typeof e.path=="string"?e.path.trim():"";if(!n)throw new Error("Sandbox file path is required.");return{path:n,recursive:typeof e.recursive=="boolean"?e.recursive:void 0}}d(D,"normalizeDeleteFileInput");function St(t){let e=D(t),n=m(t),r=Number(n.offsetBytes),o=Number(n.maxBytes);return{path:e.path,...Number.isFinite(r)?{offsetBytes:r}:{},...Number.isFinite(o)?{maxBytes:o}:{}}}d(St,"normalizeDownloadFileInput");function wt(t){let e=m(t),n=typeof e.path=="string"?e.path.trim():"",r=typeof e.contents=="string"?e.contents:"",o=typeof e.contentsBase64=="string"?e.contentsBase64.trim():"";if(!n)throw new Error("Sandbox file path is required.");if(!r&&!o)throw new Error("Sandbox file contents are required.");return{path:n,contents:r,contentsBase64:o}}d(wt,"normalizeUploadFileInput");function xt(t){let e=m(t),n=typeof e.fromPath=="string"?e.fromPath.trim():"",r=typeof e.toPath=="string"?e.toPath.trim():"";if(!n||!r)throw new Error("Sandbox file source and target paths are required.");return{fromPath:n,toPath:r,overwrite:typeof e.overwrite=="boolean"?e.overwrite:void 0}}d(xt,"normalizeMoveFileInput");function vt(t){let e=m(t),n=typeof e.branch=="string"?e.branch.trim():"",r=typeof e.startPoint=="string"?e.startPoint.trim():"";if(!n)throw new Error("Sandbox git branch name is required.");return{branch:n,create:e.create===!0,...r?{startPoint:r}:{}}}d(vt,"normalizeGitBranchInput");function Rt(t){let e=m(t),n=typeof e.message=="string"?e.message.trim():"",r=e.all===!0,o=Array.isArray(e.paths)?e.paths.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!n)throw new Error("Sandbox git commit message is required.");if(!r&&o.length===0)throw new Error("Sandbox git commit requires all=true or at least one path.");return{message:n,...r?{all:!0}:{paths:o.map(s=>s.trim())}}}d(Rt,"normalizeGitCommitInput");function Ct(t){let e=m(t),n=typeof e.remote=="string"?e.remote.trim():"",r=typeof e.branch=="string"?e.branch.trim():"",o=e.rebase===!0,s=typeof e.ffOnly=="boolean"?e.ffOnly:void 0;if(o&&s)throw new Error("Sandbox git pull cannot use rebase and ff-only together.");return{...n?{remote:n}:{},...r?{branch:r}:{},...o?{rebase:o}:{},...typeof s=="boolean"?{ffOnly:s}:{}}}d(Ct,"normalizeGitPullInput");function Pt(t){let e=m(t),n=typeof e.remote=="string"?e.remote.trim():"",r=typeof e.branch=="string"?e.branch.trim():"";return{...n?{remote:n}:{},...r?{branch:r}:{},...e.setUpstream===!0?{setUpstream:!0}:{},...e.forceWithLease===!0?{forceWithLease:!0}:{}}}d(Pt,"normalizeGitPushInput");async function ro(){return(await te()).client}d(ro,"resolveOpenPondSandboxClient");var An="https://api.openpond.ai";async function oo(t){let{client:e,context:n,apiKey:r,sandboxApiUrl:o}=await te(),s=zn(n,o);if(t.type==="list")return{sandboxes:await e.list(y(t.payload)),account:s};if(t.type==="snapshot_catalog"){let i=m(t.payload),u=typeof i.teamId=="string"?i.teamId.trim():"",c=typeof i.projectId=="string"?i.projectId.trim():"",p=typeof i.agentId=="string"?i.agentId.trim():"",b=typeof i.q=="string"?i.q.trim():"",l=typeof i.tag=="string"?i.tag.trim():"",g=typeof i.useCase=="string"?i.useCase.trim():"",C=i.replayState==="draft"||i.replayState==="validated"||i.replayState==="published"?i.replayState:void 0;return{...await e.snapshotCatalog({...u?{teamId:u}:{},...c?{projectId:c}:{},...p?{agentId:p}:{},...b?{q:b}:{},...l?{tag:l}:{},...g?{useCase:g}:{},...C?{replayState:C}:{}}),account:s}}if(t.type==="snapshot_create")return{...await e.createSnapshot(t.sandboxId,nt(t.payload)),account:s};if(t.type==="template_catalog"){let i=m(t.payload),u=typeof i.teamId=="string"?i.teamId.trim():"",c=typeof i.projectId=="string"?i.projectId.trim():"",p=typeof i.q=="string"?i.q.trim():"",b=typeof i.name=="string"?i.name.trim():"",l=typeof i.version=="string"?i.version.trim():"",g=typeof i.tag=="string"?i.tag.trim():"",C=typeof i.useCase=="string"?i.useCase.trim():"";return{...await e.templates({...u?{teamId:u}:{},...c?{projectId:c}:{},...p?{q:p}:{},...b?{name:b}:{},...l?{version:l}:{},...g?{tag:g}:{},...C?{useCase:C}:{}}),account:s}}if(t.type==="integration_connections"){let i=m(t.payload),u=typeof i.teamId=="string"?i.teamId.trim():"",c=typeof i.projectId=="string"?i.projectId.trim():"",p=typeof i.agentId=="string"?i.agentId.trim():"",b=Ie(i.status),l={...c?{projectId:c}:{},...p?{agentId:p}:{},status:b??"all"};return{...u?await e.integrationConnections({teamId:u,...l}):await Re(e,l),account:s}}if(t.type==="connected_app_status"){let i=m(t.payload),u=typeof i.teamId=="string"?i.teamId.trim():"",c=typeof i.projectId=="string"?i.projectId.trim():"",p=typeof i.agentId=="string"?i.agentId.trim():"",b=Ie(i.status)??"all",l={...c?{projectId:c}:{},...p?{agentId:p}:{},status:b},g=u?await e.integrationConnections({teamId:u,...l}):await Re(e,l);return{teamId:g.teamId,apps:Pe({connections:g.connections}),account:s}}if(t.type==="sandbox_runtime_list")return{runtimes:await e.listSandboxRuntimes(y(t.payload)),account:s};if(t.type==="sandbox_runtime_get")return{runtime:await e.getSandboxRuntime(t.runtimeId),account:s};if(t.type==="sandbox_runtime_create")return{runtime:await e.createSandboxRuntime(be(t.payload)),account:s};if(t.type==="sandbox_runtime_sandbox_create")return{...await e.createSandboxRuntimeSandbox(t.runtimeId,Q(t.payload),{respondAsync:!0}),account:s};if(t.type==="sandbox_runtime_resume"){let i=await e.sandboxRuntime(t.runtimeId).resume(Q(t.payload),{respondAsync:!0});return{runtime:await e.getSandboxRuntime(t.runtimeId),sandbox:i,account:s}}if(t.type==="sandbox_runtime_preserve_source"){let i=m(t.payload);return{...await e.preserveSandboxRuntimeSource(t.runtimeId,{...typeof i.sandboxId=="string"&&i.sandboxId.trim()?{sandboxId:i.sandboxId.trim()}:{},...typeof i.message=="string"&&i.message.trim()?{message:i.message.trim()}:{},...i.source==="profile"?{source:"profile"}:{}},y(t.payload)),account:s}}if(t.type==="sandbox_runtime_promote"){let i=m(t.payload);return{...await e.promoteSandboxRuntime(t.runtimeId,{expectedTargetSha:typeof i.expectedTargetSha=="string"?i.expectedTargetSha.trim():"",...i.validationState==="pending"||i.validationState==="passed"?{validationState:i.validationState}:{},...typeof i.summary=="string"&&i.summary.trim()?{summary:i.summary.trim()}:{}},y(t.payload)),account:s}}if(t.type==="project_list")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/projects",y(t.payload))}),account:s};if(t.type==="profile_get")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/profile",y(t.payload))}),account:s};if(t.type==="profile_ensure")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/profile/ensure",y(t.payload)),method:"POST"}),account:s};if(t.type==="profile_push"){let i=m(t.payload),{teamId:u,...c}=i;return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/profile/push",y(i)),method:"POST",body:c}),account:s}}if(t.type==="project_upsert")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/projects",y(t.payload)),method:"POST",body:m(t.payload)}),account:s};if(t.type==="project_get")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}`,y(t.payload))}),account:s};if(t.type==="project_workspace")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}/workspace`,y(t.payload))}),account:s};if(t.type==="project_git")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}/git`,y(t.payload)),method:"POST"}),account:s};if(t.type==="project_sync")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}/sync`,y(t.payload)),method:"POST"}),account:s};if(t.type==="project_source_upload"){let i=m(t.payload),{teamId:u,...c}=i;return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}/source`,y(i)),method:"POST",body:c}),account:s}}if(t.type==="project_archive")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/projects/${encodeURIComponent(t.projectId)}`,y(t.payload)),method:"DELETE"}),account:s};if(t.type==="agent_list")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/agents",y(t.payload))}),account:s};if(t.type==="agent_upsert")return{...await w({apiKey:r,sandboxApiUrl:o,path:v("/agents",y(t.payload)),method:"POST",body:m(t.payload)}),account:s};if(t.type==="agent_run")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/agents/${encodeURIComponent(t.agentId)}/run`,y(t.payload)),method:"POST",body:m(t.payload)}),account:s};if(t.type==="agent_source_deploy_plan")return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/agents/${encodeURIComponent(t.agentId)}/source/deploy-plan`,y(t.payload))}),account:s};if(t.type==="agent_source_checks"){let i=m(t.payload),{teamId:u,...c}=i;return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/agents/${encodeURIComponent(t.agentId)}/source/checks`,y(i)),method:"POST",body:c,timeoutMs:900*1e3}),account:s}}if(t.type==="agent_source_publish"){let i=m(t.payload),{teamId:u,...c}=i;return{...await w({apiKey:r,sandboxApiUrl:o,path:v(`/agents/${encodeURIComponent(t.agentId)}/source/publish`,y(i)),method:"POST",body:c}),account:s}}if(t.type==="create")return{sandbox:await e.create(Z(t.payload)),account:s};if(t.type==="get")return{sandbox:await e.get(t.sandboxId),account:s};if(t.type==="start")return{...await e.start(t.sandboxId,{respondAsync:!0}),account:s};if(t.type==="delete"){let i=await Et(e,t.sandboxId,{failOnUnpreservedChanges:t.failOnUnpreservedChanges}),u=await e.delete(t.sandboxId,i).catch(c=>kt("delete",e,t.sandboxId,c));return At("delete",u),{sandbox:u,account:s}}if(t.type==="exec")return{...await e.exec(t.sandboxId,pt(t.payload)),account:s};if(t.type==="action_run")return{...await Tn({apiKey:r,sandboxApiUrl:o,path:`/sandboxes/${encodeURIComponent(t.sandboxId)}/actions/${encodeURIComponent(t.actionName)}/run`,method:"POST",body:m(t.payload)}),account:s};if(t.type==="open_port")return{...await e.openPort(t.sandboxId,ht(t.payload)),account:s};if(t.type==="snapshot_update")return{...await e.updateSnapshot(t.sandboxId,t.snapshotId,ft(t.payload)),account:s};if(t.type==="snapshot_validate")return{...await e.validateSnapshot(t.sandboxId,t.snapshotId,yt(t.payload)),account:s};if(t.type==="snapshot_publish")return{...await e.publishSnapshot(t.sandboxId,t.snapshotId),account:s};if(t.type==="replays")return{...await e.listReplays(y(t.payload)),account:s};if(t.type==="replay_start")return{...await e.startReplay(rt(t.payload)),account:s};if(t.type==="replay_get")return{...await e.getReplay(t.replayId,y(t.payload)),account:s};if(t.type==="replay_logs")return{...await e.getReplayLogs(t.replayId,y(t.payload)),account:s};if(t.type==="replay_artifacts")return{...await e.getReplayArtifacts(t.replayId,y(t.payload)),account:s};if(t.type==="replay_cancel")return{...await e.cancelReplay(t.replayId,y(t.payload)),account:s};if(t.type==="schedule_create")return{...await e.createSchedule(m(t.payload)),account:s};if(t.type==="template_launch")return{...await e.launchTemplate(gt(t.payload)),account:s};if(t.type==="fork")return{...await e.fork(t.sandboxId,xe(t.payload)),account:s};if(t.type==="stop"){let i=await Et(e,t.sandboxId,{failOnUnpreservedChanges:t.failOnUnpreservedChanges}),u=await e.stop(t.sandboxId,i).catch(c=>kt("stop",e,t.sandboxId,c));return At("stop",u.sandbox),{...u,account:s}}if(t.type==="receipts")return{receipts:await e.receipts(t.sandboxId),account:s};if(t.type==="logs")return{logs:await e.logs(t.sandboxId),account:s};if(t.type==="integration_leases")return{...await e.integrationLeases(t.sandboxId),account:s};if(t.type==="integration_attach")return{...await e.attachIntegrationConnection(t.sandboxId,Se(t.payload)),account:s};if(t.type==="integration_remove")return{...await e.removeIntegrationLease(t.sandboxId,we(t.payload)),account:s};if(t.type==="process_start")return{...await e.startProcess(t.sandboxId,mt(t.payload)),account:s};if(t.type==="process_get")return{...await e.getProcess(t.sandboxId,t.processId,lt(t.payload)),account:s};if(t.type==="upload_file"){let i=wt(t.payload);return{...i.contentsBase64?await e.uploadFileBase64(t.sandboxId,i.path,i.contentsBase64):await e.uploadFile(t.sandboxId,i.path,i.contents),account:s}}if(t.type==="download_file"){let i=St(t.payload);return{...await e.downloadFileResponse(t.sandboxId,i),account:s}}if(t.type==="list_files")return{...await e.listFiles(t.sandboxId,bt(t.payload)),account:s};if(t.type==="search_files")return{...await e.searchFiles(t.sandboxId,It(t.payload)),account:s};if(t.type==="delete_file"){let i=D(t.payload);return{...await e.deleteFile(t.sandboxId,i.path,{recursive:i.recursive}),account:s}}if(t.type==="stat_file"){let i=D(t.payload);return{...await e.statFile(t.sandboxId,i.path),account:s}}if(t.type==="mkdir"){let i=D(t.payload);return{...await e.mkdir(t.sandboxId,{path:i.path,recursive:i.recursive}),account:s}}if(t.type==="move_file"){let i=xt(t.payload);return{...await e.moveFile(t.sandboxId,i),account:s}}if(t.type==="git_status")return{...await e.gitStatus(t.sandboxId),account:s};if(t.type==="git_diff"){let i=m(t.payload),u=typeof i.baseRef=="string"?i.baseRef.trim():"";return{...await e.gitDiff(t.sandboxId,{...u?{baseRef:u}:{}}),account:s}}if(t.type==="git_export_patch"){let i=m(t.payload),u=typeof i.baseRef=="string"?i.baseRef.trim():"";return{...await e.gitExportPatch(t.sandboxId,{...u?{baseRef:u}:{}}),account:s}}if(t.type==="git_branch")return{...await e.gitBranch(t.sandboxId,vt(t.payload)),account:s};if(t.type==="git_commit")return{...await e.gitCommit(t.sandboxId,Rt(t.payload)),account:s};if(t.type==="git_pull")return{...await e.gitPull(t.sandboxId,Ct(t.payload)),account:s};if(t.type==="git_push")return{...await e.gitPush(t.sandboxId,Pt(t.payload)),account:s};throw new Error(`Unsupported sandbox action: ${t.type}`)}d(oo,"sandboxRequestPayload");async function ao(t={}){let{client:e}=await te();return t.teamId?e.integrationConnections(t):Re(e,{...t.projectId?{projectId:t.projectId}:{},...t.agentId?{agentId:t.agentId}:{},status:t.status??"all"})}d(ao,"listSandboxIntegrationConnections");async function Et(t,e,n={}){let r=await t.get(e).then(o=>!Ut(o)).catch(()=>!0);return{failOnUnpreservedChanges:n.failOnUnpreservedChanges,...r?{respondAsync:!0}:{}}}d(Et,"sandboxLifecycleRequestOptions");function Ut(t){return t.reservation.status==="reserved"&&(t.state==="creating"||qt.has(t.state))}d(Ut,"sandboxLifecycleRequiresSynchronousAccounting");function At(t,e){if(qt.has(e.state)&&e.reservation.status==="reserved")throw new Error(`Sandbox ${t} reached ${e.state}, but reservation ${e.reservation.id} is still reserved. Cleanup accounting has not settled; retry status before treating cleanup as complete.`)}d(At,"assertTerminalSandboxLifecycleSettled");async function kt(t,e,n,r){let o=await e.get(n).catch(()=>null);if(o&&Ut(o)){let s=r instanceof Error?r.message:String(r);throw new Error(`Sandbox ${t} failed while sandbox ${n} is still creating with active reservation ${o.reservation.id}. Cleanup accounting has not settled; retry status before treating cleanup as complete. Original error: ${s}`)}throw r instanceof Error?r:new Error(String(r))}d(kt,"throwSandboxLifecycleRequestFailure");var qt=new Set(["stopped","archived","deleted","error"]);async function Re(t,e){let n=await t.listOrganizations().catch(()=>{throw new Error("Connected app status is unavailable because organizations could not be loaded.")}),r=$n(n),o=On(n)||null;if(r.length===0)return{teamId:o,connections:[]};let s=await Promise.all(r.map(u=>t.integrationConnections({teamId:u,...e.projectId?{projectId:e.projectId}:{},...e.agentId?{agentId:e.agentId}:{},status:e.status}).catch(()=>null))),i=qn(s);return{teamId:kn(i)??o??i.find(u=>u.teamId.trim())?.teamId.trim()??null,connections:Un(i)}}d(Re,"resolveImplicitConnectedAppStatusConnections");function kn(t){for(let e of t){if((e.connections?.length??0)===0)continue;let n=e.teamId?.trim();if(n)return n}return null}d(kn,"connectedAppStatusTeamIdWithConnections");function Un(t){let e=[],n=new Set;for(let r of t)for(let o of r.connections??[]){let s=o.id.trim()||[o.teamId,o.provider,o.providerAccountId].join(":");n.has(s)||(n.add(s),e.push(o))}return e}d(Un,"mergeConnectedAppStatusConnectionResults");function qn(t){let e=t.filter(o=>o!==null),n=t.length-e.length,r=e.reduce((o,s)=>o+(s.connections?.length??0),0);if(n>0&&r===0)throw new Error("Connected app status is unavailable because one or more team integration connection lookups could not be loaded.");return e}d(qn,"successfulConnectedAppStatusConnectionResults");function On(t){let e=t.filter(n=>Ot(n)==="active");return ee(e.find(n=>n.role==="owner"))??ee(e.find(n=>n.role==="admin"))??ee(e[0])??""}d(On,"selectImplicitConnectedAppStatusTeamId");function $n(t){let e=[],n=new Set;for(let r of t){if(Ot(r)!=="active")continue;let o=ee(r);!o||n.has(o)||(n.add(o),e.push(o))}return e}d($n,"implicitConnectedAppStatusTeamIds");function ee(t){if(!t)return null;let e=t.id;return(typeof t.teamId=="string"?t.teamId:typeof e=="string"?e:"").trim()||null}d(ee,"organizationTeamId");function Ot(t){return typeof t.status=="string"?t.status:"active"}d(Ot,"organizationStatus");async function te(){let t=$(process.env.OPENPOND_SANDBOX_API_URL),e=process.env.OPENPOND_SANDBOX_API_KEY?.trim();if(e&&t)return{client:Y({apiKey:e,sandboxApiUrl:t}),context:await ue().catch(()=>null),apiKey:e,sandboxApiUrl:O(t,{apiBaseUrl:t})};let n=await ue(),r=n.token?.trim();if(!r)throw new Error("OpenPond account API key is required to manage sandboxes.");if(t)return{client:Y({apiKey:r,sandboxApiUrl:t}),context:n,apiKey:r,sandboxApiUrl:O(t,{apiBaseUrl:t})};let o=Ln(n);return{client:Y({apiKey:r,baseUrl:o}),context:n,apiKey:r,sandboxApiUrl:O(o,{apiBaseUrl:o})}}d(te,"resolveSandboxClient");function jn(t){return O(t,{apiBaseUrl:t}).replace(/\/sandboxes\/?$/,"")}d(jn,"sandboxApiRootUrl");function _n(t){let e=O(t,{apiBaseUrl:t});return/\/api\/sandboxes\/?$/.test(e)?e.replace(/\/api\/sandboxes\/?$/,"/v1"):e.replace(/\/sandboxes\/?$/,"")}d(_n,"sandboxPublicApiRootUrl");function v(t,e){let n=new URLSearchParams;return e.teamId&&n.set("teamId",e.teamId),e.projectId&&n.set("projectId",e.projectId),e.agentId&&n.set("agentId",e.agentId),`${t}${n.size>0?`?${n.toString()}`:""}`}d(v,"sandboxScopedCollectionPath");async function Tn(t){let e=await z(jn(t.sandboxApiUrl),t.apiKey,t.path,{method:t.method??"GET",...t.body?{body:JSON.stringify(t.body)}:{}}),n=await e.json().catch(()=>({}));if(!e.ok){let r=typeof n.error=="string"?n.error:`Sandbox API request failed with status ${e.status}`;throw new Error(r)}return n}d(Tn,"requestSandboxApiRoot");async function w(t){let e=await z(_n(t.sandboxApiUrl),t.apiKey,t.path,{method:t.method??"GET",signal:t.signal,headers:{...t.idempotencyKey?{"idempotency-key":t.idempotencyKey}:{},...t.teamId?{"X-OpenPond-Team-Id":t.teamId}:{}},...t.body?{body:JSON.stringify(t.body)}:{},...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}),n=await e.json().catch(()=>({}));if(!e.ok){let r=typeof n.error=="string"?n.error:`Sandbox API request failed with status ${e.status}`;throw new Error(r)}return n}d(w,"requestSandboxPublicApiRoot");async function so(t){let{apiKey:e,sandboxApiUrl:n}=await te();return w({apiKey:e,sandboxApiUrl:n,...t})}d(so,"requestOpenPondPublicApi");function zn(t,e){if(!t)return{label:"Sandbox API",handle:null,baseUrl:null,sandboxApiUrl:e,state:"signed_out"};let n=t.accountState;return{label:n.label,handle:n.activeProfile?.handle??t.account?.handle??null,baseUrl:n.baseUrl??t.account?.baseUrl??null,sandboxApiUrl:e,state:n.state}}d(zn,"sandboxAccountSummary");function Ln(t){return $(process.env.OPENPOND_SANDBOX_BASE_URL)??$(process.env.OPENPOND_API_URL)??$(t.apiBaseUrl)??$(t.account?.baseUrl)??$(t.config.baseUrl)??An}d(Ln,"resolveSandboxBaseUrl");export{ir as a,Pr as b,Xe as c,nn as d,rn as e,$r as f,on as g,jr as h,jt as i,ro as j,oo as k,ao as l,so as m};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as he,b as G,c as j,d as z,e as H,g as be,i as T,j as ve,k as S,l as Re,v as B,x as F}from"./chunk-JPUSTFZC.js";import{a as se,b as D,c as P}from"./chunk-RFQD6B44.js";import{a as ne,b as oe,c as re}from"./chunk-XRKFTPHD.js";import{L as fe,M as me,Q as ye,U as we,g as $,h as ce,k as le,m as de,n as pe,o as ue,p as ge}from"./chunk-JEMECEQH.js";import{d as y,e as ie,f as ae,g as L}from"./chunk-RPM4FDRX.js";import{b as C,c as Z,d as ee,f as w,h as R,i as te}from"./chunk-BSHAIAXY.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=await pe(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=await ue(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await ge(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await D();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await L({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ie();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await ae(r,{baseUrl:C(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await D(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await L({handle:r,apiKey:i,baseUrl:C(e),apiBaseUrl:Z(e),chatApiBaseUrl:ee(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=R(e),r=await P(e,o),n=await fe(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=R(o),r=se(o),n=await me(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ce(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=R(r),a=await P(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await we(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=R(r),a=await P(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await ye(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await ve({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await P(n,i),s=R(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=te(c,i),k=(await de(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await Re(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await le(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=he(E);H(O);let J=v(e.token)||v(e.setRemoteToken),Oe=G(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${z(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?j(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${j(O)}`);try{await be({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await P(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");H(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=G(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${z(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=ne(),t=await re(e),r=`npm i -g ${e}@${t}`,n=oe(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
2
+ import{a as he,b as G,c as j,d as z,e as H,g as be,i as T,j as ve,k as S,l as Re,v as B,x as F}from"./chunk-NZDLL6JN.js";import{a as se,b as D,c as P}from"./chunk-RFQD6B44.js";import{a as ne,b as oe,c as re}from"./chunk-XRKFTPHD.js";import{L as fe,M as me,Q as ye,U as we,g as $,h as ce,k as le,m as de,n as pe,o as ue,p as ge}from"./chunk-JEMECEQH.js";import{d as y,e as ie,f as ae,g as L}from"./chunk-RPM4FDRX.js";import{b as C,c as Z,d as ee,f as w,h as R,i as te}from"./chunk-BSHAIAXY.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=await pe(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=await ue(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await ge(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await D();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await L({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ie();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await ae(r,{baseUrl:C(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await D(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await L({handle:r,apiKey:i,baseUrl:C(e),apiBaseUrl:Z(e),chatApiBaseUrl:ee(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=R(e),r=await P(e,o),n=await fe(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=R(o),r=se(o),n=await me(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ce(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=R(r),a=await P(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await we(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=R(r),a=await P(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await ye(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=R(t),i=await P(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await ve({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await P(n,i),s=R(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=te(c,i),k=(await de(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await Re(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await le(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=he(E);H(O);let J=v(e.token)||v(e.setRemoteToken),Oe=G(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${z(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?j(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${j(O)}`);try{await be({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await P(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");H(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=G(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${z(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=ne(),t=await re(e),r=`npm i -g ${e}@${t}`,n=oe(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{c as _}from"./chunk-RFQD6B44.js";import{V as y,W as C,X as N,Y as D,Z as k,_ as K,e as L,f as U,i as M,t as $}from"./chunk-JEMECEQH.js";import{b as O}from"./chunk-27JGS3KB.js";import{d as I}from"./chunk-RPM4FDRX.js";import{e as B,f as T,g as A}from"./chunk-BSHAIAXY.js";import{f as w}from"./chunk-3M53YXEI.js";import{b as v}from"./chunk-GLUWATL5.js";import{a as o}from"./chunk-FTQLQJQV.js";function ce(e){if(e.repoUrl)return e.repoUrl;if(e.gitHost&&e.gitOwner&&e.gitRepo)return`https://${e.gitHost}/${e.gitOwner}/${e.gitRepo}.git`;throw new Error("repoUrl missing from API response")}o(ce,"resolveRepoUrl");function le(e,t){let n=new URL(e),r=encodeURIComponent(t);return`${n.protocol}//x-access-token:${r}@${n.host}${n.pathname}`}o(le,"formatTokenizedRepoUrl");function fe(e){let t=new URL(e);return`${t.protocol}//x-access-token:$OPENPOND_API_KEY@${t.host}${t.pathname}`}o(fe,"formatTokenizedRepoUrlForPrint");function me(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}o(me,"redactToken");function pe(e){let t=process.env.OPENPOND_BASE_URL;if(t)try{let n=new URL(t).hostname,r=new URL(e).hostname;n&&r&&n!==r&&(console.warn(`warning: repo host (${r}) does not match OPENPOND_BASE_URL (${n})`),console.warn("warning: verify your git host configuration matches OPENPOND_BASE_URL."))}catch{}}o(pe,"warnOnRepoHostMismatch");function W(e){let t=e.split("/").filter(Boolean);if(t.length!==2)throw new Error("expected <handle>/<repo>");return{handle:t[0],repo:t[1]}}o(W,"parseHandleRepo");function S(e){return(e||"").trim().toLowerCase()}o(S,"normalizeRepoName");async function ee(e){if(!e.forceRefresh){let n=await C({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(n)return n}let t=await M(e.apiBase,e.apiKey);return await N({apiBase:e.apiBase,apiKey:e.apiKey,apps:t}),t}o(ee,"fetchAppsWithCache");async function Re(e){if(!e.forceRefresh){let r=await D({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(r)return r}let t=await $(e.apiBase,e.apiKey),n=Array.isArray(t.tools)?t.tools:[];return await k({apiBase:e.apiBase,apiKey:e.apiKey,tools:n}),n}o(Re,"fetchToolsWithCache");async function Pe(e,t,n){let{handle:r,repo:s}=W(n),i=await ee({apiBase:e,apiKey:t}),a=S(s),d=i.find(u=>u.handle&&u.handle!==r?!1:[u.repo,u.gitRepo,u.id].map(S).includes(a));if(!d)throw new Error(`app not found for ${r}/${s}`);return{app:d,handle:r,repo:s}}o(Pe,"resolveAppTarget");async function Ee(e){let t=e.intervalMs??5e3,n=e.timeoutMs??240*1e3,r=new Set,s=Date.now();for(;Date.now()-s<n;){let a=(await L(e.baseUrl,e.apiKey,e.deploymentId)).filter(u=>!r.has(u.id));for(let u of a)r.add(u.id);for(let u of a)console.log(`${e.prefix}${u.message}`);let d=await U(e.baseUrl,e.apiKey,e.deploymentId);if(d.status==="failed"){console.log(`${e.prefix}deployment failed`);return}if(d.status==="running"||d.status==="deployed"){console.log(`${e.prefix}deployment complete`);return}await new Promise(u=>setTimeout(u,t))}console.log(`${e.prefix}deployment still in progress`)}o(Ee,"pollDeploymentLogs");import{stdin as q,stdout as H}from"node:process";import{createInterface as F}from"node:readline/promises";async function z(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8").replace(/\r?\n$/,"")}o(z,"readAllStdin");function V(e){return new Promise((t,n)=>{let r=process.stdin,s=process.stderr,i="",a=r.isRaw;function d(){r.off("data",u),r.setRawMode&&r.setRawMode(a),r.pause(),s.write(`
2
+ import{c as _}from"./chunk-RFQD6B44.js";import{V as y,W as C,X as N,Y as D,Z as k,_ as K,e as L,f as U,i as M,t as $}from"./chunk-JEMECEQH.js";import{b as O}from"./chunk-7EQLW2KM.js";import{d as I}from"./chunk-RPM4FDRX.js";import{e as B,f as T,g as A}from"./chunk-BSHAIAXY.js";import{f as w}from"./chunk-3M53YXEI.js";import{b as v}from"./chunk-GLUWATL5.js";import{a as o}from"./chunk-FTQLQJQV.js";function ce(e){if(e.repoUrl)return e.repoUrl;if(e.gitHost&&e.gitOwner&&e.gitRepo)return`https://${e.gitHost}/${e.gitOwner}/${e.gitRepo}.git`;throw new Error("repoUrl missing from API response")}o(ce,"resolveRepoUrl");function le(e,t){let n=new URL(e),r=encodeURIComponent(t);return`${n.protocol}//x-access-token:${r}@${n.host}${n.pathname}`}o(le,"formatTokenizedRepoUrl");function fe(e){let t=new URL(e);return`${t.protocol}//x-access-token:$OPENPOND_API_KEY@${t.host}${t.pathname}`}o(fe,"formatTokenizedRepoUrlForPrint");function me(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}o(me,"redactToken");function pe(e){let t=process.env.OPENPOND_BASE_URL;if(t)try{let n=new URL(t).hostname,r=new URL(e).hostname;n&&r&&n!==r&&(console.warn(`warning: repo host (${r}) does not match OPENPOND_BASE_URL (${n})`),console.warn("warning: verify your git host configuration matches OPENPOND_BASE_URL."))}catch{}}o(pe,"warnOnRepoHostMismatch");function W(e){let t=e.split("/").filter(Boolean);if(t.length!==2)throw new Error("expected <handle>/<repo>");return{handle:t[0],repo:t[1]}}o(W,"parseHandleRepo");function S(e){return(e||"").trim().toLowerCase()}o(S,"normalizeRepoName");async function ee(e){if(!e.forceRefresh){let n=await C({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(n)return n}let t=await M(e.apiBase,e.apiKey);return await N({apiBase:e.apiBase,apiKey:e.apiKey,apps:t}),t}o(ee,"fetchAppsWithCache");async function Re(e){if(!e.forceRefresh){let r=await D({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(r)return r}let t=await $(e.apiBase,e.apiKey),n=Array.isArray(t.tools)?t.tools:[];return await k({apiBase:e.apiBase,apiKey:e.apiKey,tools:n}),n}o(Re,"fetchToolsWithCache");async function Pe(e,t,n){let{handle:r,repo:s}=W(n),i=await ee({apiBase:e,apiKey:t}),a=S(s),d=i.find(u=>u.handle&&u.handle!==r?!1:[u.repo,u.gitRepo,u.id].map(S).includes(a));if(!d)throw new Error(`app not found for ${r}/${s}`);return{app:d,handle:r,repo:s}}o(Pe,"resolveAppTarget");async function Ee(e){let t=e.intervalMs??5e3,n=e.timeoutMs??240*1e3,r=new Set,s=Date.now();for(;Date.now()-s<n;){let a=(await L(e.baseUrl,e.apiKey,e.deploymentId)).filter(u=>!r.has(u.id));for(let u of a)r.add(u.id);for(let u of a)console.log(`${e.prefix}${u.message}`);let d=await U(e.baseUrl,e.apiKey,e.deploymentId);if(d.status==="failed"){console.log(`${e.prefix}deployment failed`);return}if(d.status==="running"||d.status==="deployed"){console.log(`${e.prefix}deployment complete`);return}await new Promise(u=>setTimeout(u,t))}console.log(`${e.prefix}deployment still in progress`)}o(Ee,"pollDeploymentLogs");import{stdin as q,stdout as H}from"node:process";import{createInterface as F}from"node:readline/promises";async function z(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8").replace(/\r?\n$/,"")}o(z,"readAllStdin");function V(e){return new Promise((t,n)=>{let r=process.stdin,s=process.stderr,i="",a=r.isRaw;function d(){r.off("data",u),r.setRawMode&&r.setRawMode(a),r.pause(),s.write(`
3
3
  `)}o(d,"cleanup");function u(m){let f=Buffer.isBuffer(m)?m:Buffer.from(m);for(let c of f){if(c===3){d(),n(new Error("secret prompt cancelled"));return}if(c===13||c===10){d(),t(i);return}if(c===127||c===8){i.length>0&&(i=i.slice(0,-1),s.write("\b \b"));continue}i+=Buffer.from([c]).toString("utf8"),s.write("*")}}o(u,"onData"),s.write(e),r.resume(),r.setRawMode&&r.setRawMode(!0),r.on("data",u)})}o(V,"readMaskedLine");async function Ae(e,t=!1){let n=F({input:q,output:H});try{let r=t?"[Y/n]":"[y/N]",s=(await n.question(`${e} ${r} `)).trim().toLowerCase();return s?s==="y"||s==="yes":t}finally{n.close()}}o(Ae,"promptConfirm");async function Ie(e){let t=F({input:q,output:H});try{return(await t.question(`Local path (default: ${e}): `)).trim()||e}finally{t.close()}}o(Ie,"promptForPath");var X=["readonly","attempt","feature","rollout","replay","template_build","scheduled_run","patch_only","hotfix","multi_feature_batch"],j=["none","manual","auto_after_checks"],G=[...K];function te(e,t){return(process.env.OPENPOND_SANDBOX_BASE_URL||process.env.OPENPOND_API_URL||e.apiBaseUrl||A(process.env.OPENPOND_BASE_URL||e.baseUrl)||v).replace(/\/$/,"")}o(te,"resolveSandboxBaseUrl");async function We(e){let t=await ne(e),n=T(t),r=await _(t,n),s=B(e)||process.env.OPENPOND_SANDBOX_API_URL?.trim()||null,i=te(t,e);return O(s?{apiKey:r,sandboxApiUrl:s}:{apiKey:r,baseUrl:i})}o(We,"resolveSandboxClient");async function ne(e){return I()}o(ne,"loadSandboxConfig");function qe(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new Error("workflow-mode must be a non-empty value");let t=e.trim();if(!X.includes(t))throw new Error(`workflow-mode must be one of ${X.join(", ")}`);return t}o(qe,"parseSandboxWorkflowModeOption");function He(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new Error("runtime-promotion-policy must be a non-empty value");let t=e.trim();if(!j.includes(t))throw new Error(`runtime-promotion-policy must be one of ${j.join(", ")}`);return t}o(He,"parseSandboxRuntimePromotionPolicyOption");function Fe(e){if(typeof e!="string"||!e.trim())return;let t=e.trim();if(!G.includes(t))throw new Error(`runtime-profile-id must be one of ${G.join(", ")}`);return t}o(Fe,"parseSandboxRuntimeProfileIdOption");function re(e){let t=Y(e.envRef,"env-ref").map(({name:i,value:a})=>({name:i,secretRef:a})),n=Y(e.envLiteral,"env-literal").map(({name:i,value:a})=>{if(oe(i)&&!w(e.allowPlainSecretEnv))throw new Error(`refusing plaintext value for secret-like env ${i}; create a sandbox secret and pass --env-ref ${i}=openpond://secret/...`);return{name:i,value:a}}),r=[...t,...n],s=new Set;for(let i of r){if(s.has(i.name))throw new Error(`duplicate sandbox env var: ${i.name}`);s.add(i.name)}return r}o(re,"parseSandboxEnvOptions");function ze(e,t){let n=re(t),r=new Set(n.map(a=>a.name)),s=new Map(n.map(a=>[a.name,a]));for(let a of e.inputs.env)if(s.get(a.name)?.value!==void 0&&a.secret!==!1)throw new Error(`sandbox template env ${a.name} requires a secret ref. Pass --env-ref ${a.name}=openpond://secret/...`);let i=e.inputs.env.filter(a=>a.required&&!r.has(a.name)).map(a=>a.name);if(i.length>0)throw new Error(`missing required sandbox template env refs: ${i.join(", ")}. Pass --env-ref NAME=openpond://secret/...`);return n}o(ze,"parseSandboxTemplateEnvOptions");function Y(e,t){return typeof e!="string"?[]:e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let r=n.indexOf("=");if(r<=0)throw new Error(`${t} entries must use NAME=value`);let s=n.slice(0,r).trim(),i=n.slice(r+1).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw new Error(`${t} has invalid env name: ${s}`);if(!i)throw new Error(`${t} value is required for ${s}`);return{name:s,value:i}})}o(Y,"parseSandboxEnvAssignments");function oe(e){return/(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|DATABASE_URL|DSN)/i.test(e)}o(oe,"isSecretLikeEnvName");async function Ve(e,t){if(typeof e.value=="string"||typeof e.secretValue=="string")throw new Error("sandbox secret values must be provided with --stdin or the masked prompt");if(w(e.stdin)){let s=await z();if(!s)throw new Error(`${t} read no secret value from stdin`);return s}if(!process.stdin.isTTY)throw new Error(`${t} requires --stdin when not running in a TTY`);let r=await V(`${t}: `);if(!r)throw new Error(`${t} cannot be empty`);return r}o(Ve,"readSandboxSecretValue");function Xe(e){return{id:e.id,teamId:e.teamId,name:e.name,scope:e.scope,status:e.status,secretRef:e.secretRef,currentVersion:e.currentVersion,updatedAt:e.updatedAt,lastUsedAt:e.lastUsedAt,attachedDestinations:e.attachments?.length??0}}o(Xe,"summarizeSandboxSecret");import{Buffer as b}from"node:buffer";import{spawn as Q}from"node:child_process";var ie=600*1e3,se=2*1024*1024;function R(e,t=[],n={}){return n.inherit&&n.terminateWhenStdoutIncludes!==void 0?Promise.reject(new Error("terminateWhenStdoutIncludes requires captured stdout")):n.terminateWhenStdoutIncludes===""?Promise.reject(new Error("terminateWhenStdoutIncludes must not be empty")):new Promise((r,s)=>{let i=Q(e,t,{cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,shell:n.shell,detached:n.detached??process.platform!=="win32",stdio:n.inherit?"inherit":[n.stdin===void 0?"ignore":"pipe","pipe","pipe"]}),a=new h(J(n)),d=new h(J(n)),u=!1,m=n.timeoutMs??ie,f,c,x=null,g=!1,P=o(()=>{f&&clearTimeout(f),c&&clearTimeout(c)},"clearTimers"),E=o(l=>{x!==null||g||(x=l,u=l==="timeout",f&&(clearTimeout(f),f=void 0),Z(i.pid,"SIGTERM"),c=setTimeout(()=>{i.exitCode===null&&i.signalCode===null&&Z(i.pid,"SIGKILL")},5e3))},"requestTermination");m>0&&(f=setTimeout(()=>{E("timeout")},m)),n.inherit||(i.stdout?.on("data",l=>{a.append(l);let p=n.terminateWhenStdoutIncludes;p!==void 0&&a.text().includes(p)&&E("output")}),i.stderr?.on("data",l=>{d.append(l)})),i.on("error",l=>{P(),g=!0,s(l)}),i.on("close",(l,p)=>{g||(g=!0,P(),r({code:l,signal:p,terminationReason:x??(p?"signal":"exit"),stdout:a.text(),stderr:d.text(),timedOut:u,stdoutTruncated:a.truncated,stderrTruncated:d.truncated}))}),n.stdin!==void 0&&i.stdin?.end(n.stdin)})}o(R,"runProcessCommand");var h=class{static{o(this,"BoundedOutput")}#t=[];#n;#e=0;truncated=!1;constructor(t){this.#n=t}append(t){let n=b.isBuffer(t)?t:b.from(t),r=this.#n-this.#e;if(r<=0){n.byteLength>0&&(this.truncated=!0);return}if(n.byteLength<=r){this.#t.push(n),this.#e+=n.byteLength;return}this.#t.push(n.subarray(0,r)),this.#e+=r,this.truncated=!0}text(){let t=b.concat(this.#t,this.#e).toString("utf8");return this.truncated?`${t}
4
4
  [truncated after ${this.#n} bytes]
5
5
  `:t}};function J(e){let t=e.maxOutputBytes??se;return Math.max(0,Math.floor(t))}o(J,"maxOutputBytes");function Z(e,t){if(e){if(process.platform==="win32"){let n=["/PID",String(e),"/T"];t==="SIGKILL"&&n.push("/F"),Q("taskkill",n,{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-e,t)}catch(n){if(n.code!=="ESRCH")throw n}}}o(Z,"terminateProcessTree");async function ae(e,t,n={}){return R(e,t,{cwd:n.cwd,inherit:n.inherit,timeoutMs:n.timeoutMs,maxOutputBytes:n.maxOutputBytes,terminateWhenStdoutIncludes:n.terminateWhenStdoutIncludes})}o(ae,"runCommand");async function rt(e,t={}){let n=t.timeoutSeconds===void 0?void 0:t.timeoutSeconds*1e3;return R(e,[],{cwd:t.cwd,env:t.env,shell:!0,inherit:t.inherit,timeoutMs:n,maxOutputBytes:t.maxOutputBytes})}o(rt,"runShellCommand");async function ot(e,t){let n=await ae("git",["remote","get-url",t],{cwd:e});if(n.code!==0)return null;let r=n.stdout.trim();return r.length>0?r:null}o(ot,"getGitRemoteUrl");export{ce as a,le as b,fe as c,me as d,pe as e,S as f,ee as g,Re as h,Pe as i,Ee as j,Ae as k,Ie as l,We as m,qe as n,He as o,Fe as p,re as q,ze as r,Ve as s,Xe as t,R as u,ae as v,rt as w,ot as x};