openpond 0.2.47 → 0.2.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-server.d.ts +61 -0
- package/dist/app-server.js +1 -1
- package/dist/chunks/{app-server-runtime-3KFJJUJH.js → app-server-runtime-RWO4KGPU.js} +1 -1
- package/dist/chunks/{chunk-LL4QP2IM.js → chunk-2ZJJFBIA.js} +1 -1
- package/dist/chunks/{chunk-CNTGL5IX.js → chunk-42GOV5ZU.js} +3 -3
- package/dist/chunks/{chunk-PGKEDR3S.js → chunk-5CMKGD43.js} +1 -1
- package/dist/chunks/{chunk-K6S4TY5W.js → chunk-7K72KS5C.js} +5 -5
- package/dist/chunks/{chunk-36YNUUZL.js → chunk-7MXZJQS7.js} +1 -1
- package/dist/chunks/chunk-DFM5JTS2.js +2 -0
- package/dist/chunks/chunk-EPY7M5XS.js +2 -0
- package/dist/chunks/{chunk-D7DA5G2U.js → chunk-HEPLG5FY.js} +2 -2
- package/dist/chunks/{chunk-3HBCQNRN.js → chunk-IOQUF34U.js} +1 -1
- package/dist/chunks/chunk-JCCU3VFK.js +2 -0
- package/dist/chunks/chunk-NHJ26KXF.js +518 -0
- package/dist/chunks/{chunk-6MH55NGW.js → chunk-O7VGFMDO.js} +1 -1
- package/dist/chunks/chunk-PNE3IETM.js +190 -0
- package/dist/chunks/{chunk-A2GVVXFV.js → chunk-QJRXTIOC.js} +1 -1
- package/dist/chunks/{chunk-YBVIFIXN.js → chunk-TIUSKRBP.js} +4 -4
- package/dist/chunks/chunk-VOIH2BQA.js +2162 -0
- package/dist/chunks/{cli-WPAYXAJX.js → cli-ZLDLOKPL.js} +1 -1
- package/dist/chunks/{dist-VDVI7KIO.js → dist-BLBZENVB.js} +1 -1
- package/dist/chunks/{hosted-experiment-improvement-T6Q7ASMI.js → hosted-experiment-improvement-MGMZWTZY.js} +1 -1
- package/dist/chunks/{hosted-harness-runtime-2R5QRZCG.js → hosted-harness-runtime-FZZLWLBR.js} +1 -1
- package/dist/chunks/{hosted-profile-candidate-TKOY3M4S.js → hosted-profile-candidate-LVNKOTKJ.js} +1 -1
- package/dist/chunks/{hosted-profile-compiler-VLBFIEWK.js → hosted-profile-compiler-SI3EWWUM.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-inspection-3MB6MWO6.js → hosted-profile-evaluation-inspection-FPCV42DD.js} +1 -1
- package/dist/chunks/hosted-profile-evaluation-preparation-QHARNR4M.js +3 -0
- package/dist/chunks/{src-R4TSYNTK.js → src-GKWEQK2T.js} +115 -115
- package/dist/chunks/{workspaces-WTPFRJMS.js → workspaces-XIQNPAP7.js} +1 -1
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-4UTBLHFC.js +0 -2
- package/dist/chunks/chunk-526PVA3V.js +0 -2678
- package/dist/chunks/chunk-BM7TU6NX.js +0 -190
- package/dist/chunks/chunk-F7RCOLZD.js +0 -2
- package/dist/chunks/chunk-TT46OISU.js +0 -2
- package/dist/chunks/chunk-XON44M6V.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-preparation-C7WEABZ5.js +0 -3
package/dist/app-server.d.ts
CHANGED
|
@@ -20866,6 +20866,53 @@ type AgentRuntimeHost = {
|
|
|
20866
20866
|
type JsonRpcRequest = z.infer<typeof JsonRpcRequestSchema>;
|
|
20867
20867
|
type JsonRpcNotification = z.infer<typeof JsonRpcNotificationSchema>;
|
|
20868
20868
|
declare const HostStorageRequestSchema: z.ZodDiscriminatedUnion<[
|
|
20869
|
+
z.ZodObject<{
|
|
20870
|
+
contractVersion: z.ZodLiteral<1>;
|
|
20871
|
+
requestId: z.ZodString;
|
|
20872
|
+
operation: z.ZodLiteral<"profile-evaluations/grade">;
|
|
20873
|
+
params: z.ZodObject<{
|
|
20874
|
+
action: z.ZodEnum<{
|
|
20875
|
+
upload: "upload";
|
|
20876
|
+
execute: "execute";
|
|
20877
|
+
}>;
|
|
20878
|
+
callId: z.ZodString;
|
|
20879
|
+
sessionId: z.ZodString;
|
|
20880
|
+
turnId: z.ZodString;
|
|
20881
|
+
sha256: z.ZodString;
|
|
20882
|
+
sizeBytes: z.ZodNumber;
|
|
20883
|
+
timeoutMs: z.ZodNumber;
|
|
20884
|
+
offset: z.ZodOptional<z.ZodNumber>;
|
|
20885
|
+
contentsBase64: z.ZodOptional<z.ZodString>;
|
|
20886
|
+
}, z.core.$strict>;
|
|
20887
|
+
}, z.core.$strict>,
|
|
20888
|
+
z.ZodObject<{
|
|
20889
|
+
contractVersion: z.ZodLiteral<1>;
|
|
20890
|
+
requestId: z.ZodString;
|
|
20891
|
+
operation: z.ZodLiteral<"profile-evaluations/sandbox">;
|
|
20892
|
+
params: z.ZodObject<{
|
|
20893
|
+
sessionId: z.ZodString;
|
|
20894
|
+
turnId: z.ZodString;
|
|
20895
|
+
action: z.ZodEnum<{
|
|
20896
|
+
stop: "stop";
|
|
20897
|
+
exec: "exec";
|
|
20898
|
+
upload: "upload";
|
|
20899
|
+
read: "read";
|
|
20900
|
+
}>;
|
|
20901
|
+
area: z.ZodOptional<z.ZodEnum<{
|
|
20902
|
+
runtime: "runtime";
|
|
20903
|
+
policy: "policy";
|
|
20904
|
+
}>>;
|
|
20905
|
+
path: z.ZodOptional<z.ZodString>;
|
|
20906
|
+
sha256: z.ZodOptional<z.ZodString>;
|
|
20907
|
+
sizeBytes: z.ZodOptional<z.ZodNumber>;
|
|
20908
|
+
offset: z.ZodOptional<z.ZodNumber>;
|
|
20909
|
+
contentsBase64: z.ZodOptional<z.ZodString>;
|
|
20910
|
+
command: z.ZodOptional<z.ZodString>;
|
|
20911
|
+
stdin: z.ZodOptional<z.ZodString>;
|
|
20912
|
+
cwd: z.ZodOptional<z.ZodString>;
|
|
20913
|
+
timeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
20914
|
+
}, z.core.$strict>;
|
|
20915
|
+
}, z.core.$strict>,
|
|
20869
20916
|
z.ZodObject<{
|
|
20870
20917
|
contractVersion: z.ZodLiteral<1>;
|
|
20871
20918
|
requestId: z.ZodString;
|
|
@@ -20885,6 +20932,20 @@ declare const HostStorageRequestSchema: z.ZodDiscriminatedUnion<[
|
|
|
20885
20932
|
pageCount: z.ZodOptional<z.ZodNumber>;
|
|
20886
20933
|
}, z.core.$strict>;
|
|
20887
20934
|
}, z.core.$strict>,
|
|
20935
|
+
z.ZodObject<{
|
|
20936
|
+
contractVersion: z.ZodLiteral<1>;
|
|
20937
|
+
requestId: z.ZodString;
|
|
20938
|
+
operation: z.ZodLiteral<"output/readBytes">;
|
|
20939
|
+
params: z.ZodObject<{
|
|
20940
|
+
sessionId: z.ZodString;
|
|
20941
|
+
turnId: z.ZodString;
|
|
20942
|
+
fileId: z.ZodString;
|
|
20943
|
+
revision: z.ZodNumber;
|
|
20944
|
+
sha256: z.ZodString;
|
|
20945
|
+
sizeBytes: z.ZodNumber;
|
|
20946
|
+
offset: z.ZodNumber;
|
|
20947
|
+
}, z.core.$strict>;
|
|
20948
|
+
}, z.core.$strict>,
|
|
20888
20949
|
z.ZodObject<{
|
|
20889
20950
|
contractVersion: z.ZodLiteral<1>;
|
|
20890
20951
|
requestId: z.ZodString;
|
package/dist/app-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{lc as r}from"./chunks/chunk-PNE3IETM.js";import"./chunks/chunk-NHJ26KXF.js";import"./chunks/chunk-EMKZVP7Z.js";import{e as p}from"./chunks/chunk-JCCU3VFK.js";import"./chunks/chunk-O7VGFMDO.js";import"./chunks/chunk-DLZP22WV.js";import"./chunks/chunk-DFM5JTS2.js";import"./chunks/chunk-VOIH2BQA.js";import"./chunks/chunk-T5LE6R5S.js";import"./chunks/chunk-QJRXTIOC.js";import"./chunks/chunk-SDO4FC4Q.js";import"./chunks/chunk-IR3YJWPW.js";import{i as e}from"./chunks/chunk-7K72KS5C.js";import"./chunks/chunk-XM26DGML.js";import"./chunks/chunk-EPY7M5XS.js";import"./chunks/chunk-7MXZJQS7.js";import"./chunks/chunk-7YR6CBNU.js";import"./chunks/chunk-2ZJJFBIA.js";import"./chunks/chunk-5CMKGD43.js";import"./chunks/chunk-XEOEKFG6.js";import"./chunks/chunk-HA7EFTPF.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-7QEE4PBI.js";import"./chunks/chunk-XDMUD4FW.js";import"./chunks/chunk-IKWDL3RB.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-QRWPEW3Z.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-YL6VFJ4P.js";import"./chunks/chunk-Z3D4C7BG.js";import"./chunks/chunk-WV2APYWG.js";import"./chunks/chunk-PJM2G7SG.js";import"./chunks/chunk-SDEDAHV6.js";import"./chunks/chunk-DALJMSJG.js";import"./chunks/chunk-TGIB24K4.js";import"./chunks/chunk-NNF6KCHD.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{kc as c,lc as d}from"./chunk-PNE3IETM.js";import"./chunk-NHJ26KXF.js";import"./chunk-EMKZVP7Z.js";import{e as b}from"./chunk-JCCU3VFK.js";import"./chunk-O7VGFMDO.js";import"./chunk-DLZP22WV.js";import"./chunk-DFM5JTS2.js";import"./chunk-VOIH2BQA.js";import"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{i as a}from"./chunk-7K72KS5C.js";import"./chunk-XM26DGML.js";import"./chunk-EPY7M5XS.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-2ZJJFBIA.js";import"./chunk-5CMKGD43.js";import"./chunk-XEOEKFG6.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{d as F}from"./chunk-
|
|
2
|
+
import{d as F}from"./chunk-5CMKGD43.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
|
|
3
3
|
|
|
4
4
|
[diff truncated]`}o(X,"truncatePatch");function jt(e){return e.length<=ot?e:`${e.slice(0,ot)}
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{b as Oe,c as He,e as ee,f as _e,l as Ue,m as Me,p as Ne,q as qe}from"./chunk-
|
|
2
|
+
import{b as Oe,c as He,e as ee,f as _e,l as Ue,m as Me,p as Ne,q as qe}from"./chunk-JCCU3VFK.js";import{i as Ce,o as ke,q as Ae}from"./chunk-DLZP22WV.js";import{F as b,J as Ee}from"./chunk-7K72KS5C.js";import{a as Q,b as Pe,h as xe}from"./chunk-5CMKGD43.js";import{Cd as _,Fd as W,Gd as Te,I as H,J as Ie,M as F,N,a as $}from"./chunk-XDMUD4FW.js";import{va as oe}from"./chunk-SDEDAHV6.js";import{X as he,Y as ve,_ as Z,b as le,ba as we,c as ue,ea as be,fa as V,ja as Se,la as ye,ma as Re,p as ce,r as pe,s as de,t as me,u as ge,w as fe}from"./chunk-DALJMSJG.js";import{y as M}from"./chunk-TGIB24K4.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ie,d as B,f as ae,h as U}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{promises as re}from"node:fs";import pt from"node:os";import dt from"node:path";import{createServer as mt}from"node:http";import{randomBytes as gt}from"node:crypto";var st=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),ot=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(st).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:Se,importOnly:o.boolean().optional()})]);function De(n){let e=null;async function t(s,i){let l=U(n).config,c=null,p=null,u=null;try{c=await ue(l),u=await V(n,{projectRoot:s,accountId:i}),s||(e=u)}catch(w){p=B(w,l)}let g=u??(s?null:e);return{path:l,text:c,rawRevision:le(c),issue:p,effective:g,usingLastValid:!u&&!!g,applies:"next_turn",recoverableRevisions:await pe(n),clientState:p?null:await ye(n)}}a(t,"status");async function r(s){let i=ot.parse(s);return i.action==="validate"?{valid:!0,document:ce(i.text,U(n).config)}:(i.action==="patch"&&await fe(n,i.expectedRevision,i.operations),i.action==="replace"&&await de(n,i.expectedRevision,i.text),i.action==="restore"&&await me(n,i.revision,i.expectedRevision),i.action==="trust"&&await be(n,i.root,i.accountId,i.trusted),i.action==="client-state"?Re(n,i.owner,i.patch,i.importOnly):t())}return a(r,"mutate"),{status:t,mutate:r,schema:ge}}a(De,"createConfigurationPayloads");import{Buffer as Be}from"node:buffer";var G={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id, idempotency-key","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},it=25*1024*1024,j=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{a(this,"HttpBodyError")}};function je(n,e,t={}){for(let[s,i]of Object.entries(G))e.setHeader(s,i);let r=Ve(n.headers.origin);return r?(e.setHeader("Vary",ct(e.getHeader("Vary"))),at(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}a(je,"applyCorsHeaders");function at(n,e={}){if(n==="null")return!0;let t=Fe(n);return t?ut(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Fe(s):null).filter(s=>!!s)).has(t):!1}a(at,"isAllowedCorsOrigin");function P(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...G}),n.end(JSON.stringify(t))}a(P,"sendJson");function zt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...G}),n.end(t)}a(zt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...G}),n.end(t)}a(Yt,"sendBinary");async function te(n,e={}){let t=e.maxBytes??it,r=Ve(n.headers["content-type"]),s=[],i=0;for await(let c of n){let p=Be.from(c);if(i+=p.byteLength,i>t)throw new j(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(p)}let l=Be.concat(s).toString("utf8").trim();if(!l)return{};if(!lt(r))throw new j(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(l)}catch{throw new j(400,"invalid_json","Request body is not valid JSON.")}}a(te,"readJson");function Le(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}a(Le,"hasAuth");function Ve(n){return Array.isArray(n)?n[0]??null:n??null}a(Ve,"headerValue");function lt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}a(lt,"isJsonContentType");function Fe(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}a(Fe,"normalizeOrigin");function ut(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}a(ut,"isLoopbackOrigin");function ct(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}a(ct,"appendVaryOrigin");function $e(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
3
|
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
4
|
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
5
|
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
@@ -20,7 +20,7 @@ for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart'
|
|
|
20
20
|
el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
|
|
21
21
|
el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
|
|
22
22
|
(async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
|
|
23
|
-
</script></html>`}a($e,"startupRecoveryPage");var ft=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:he.optional()});function We(n){return n instanceof ie&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}a(We,"isRecoverableStartupError");async function Ge(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await re.mkdtemp(dt.join(pt.tmpdir(),"openpond-recovery-")):n;return Oe(s,async()=>{let{token:i,tokenFile:l}=await Ue(s),c=De(n),p=t.issue,u,g=new Promise(f=>{u=f}),w=mt((f,h)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!je(f,h).allowed){P(h,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){P(h,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){P(h,200,{ok:!0,server:"openpond-app-server",version:Pe,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let v=gt(18).toString("base64");h.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${v}'; style-src 'nonce-${v}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),h.end($e(v));return}if(!Le(f,S,i)){P(h,401,{error:"Unauthorized"});return}let T=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){P(h,200,{issue:p,configEditable:T,config:r?{path:U(n).config,text:null,rawRevision:"unavailable",issue:p,recoverableRevisions:[]}:await c.status(),migration:await ve(n).catch(v=>({issue:B(v,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&T){P(h,200,await c.mutate(await te(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let v=ft.parse(await te(f));if(r&&v.action!=="retry"&&v.action!=="preview")throw t;if(v.action==="restart"){P(h,200,await we(n));return}if(v.action==="preview"||v.action==="migrate"){P(h,200,await Z(n,{sourceAppHome:v.sourceAppHome,sourceConfig:v.sourceConfig,resolutions:v.resolutions,dryRun:v.action==="preview"}));return}await Z(n),await V(n),P(h,200,{ready:!0}),u();return}P(h,503,{error:`${p.message} ${p.action}`,issue:p,recovery:!0})})().catch(S=>{p=B(S,n),P(h,422,{error:`${p.message} ${p.action}`,issue:p})})});await new Promise((f,h)=>{w.once("error",h),w.listen(e,"127.0.0.1",()=>{w.off("error",h),f()})});let x=w.address().port,k=`http://127.0.0.1:${x}`;return await He(s,k,"startup-recovery"),{url:k,port:x,token:i,tokenFile:l,storePath:U(n).database,repaired:g,close:a(async()=>{w.closeIdleConnections(),await new Promise((f,h)=>w.close(S=>S?h(S):f())),r&&await re.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await re.rm(s,{recursive:!0,force:!0}),i})}a(Ge,"startRecoveryServer");import{createHash as Ht}from"node:crypto";import{createHash as ht,randomUUID as Je}from"node:crypto";var vt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),wt=o.object({entries:o.array(H).max(200),nextBefore:vt.nullable()}).strict(),bt=o.object({run:H,replayed:o.boolean()}).strict(),J=class{constructor(e){this.client=e}client;static{a(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:b,requestId:Je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:H.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let l=wt.parse(await this.client.request({contractVersion:b,requestId:Je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&l.entries.some(c=>c.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...l.entries),!l.nextBefore)break;if(l.entries.length===0||i&&(l.nextBefore.updatedAt>i.updatedAt||l.nextBefore.updatedAt===i.updatedAt&&l.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=l.nextBefore}return s}async upsertCreateImproveRun(e){let t=H.parse(e),r=`create-improve:${ht("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:b,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return H.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=Ie.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=H.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return bt.parse(await this.client.request({contractVersion:b,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as yt}from"node:crypto";async function L(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!St(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}a(L,"hostedBoundedPage");function St(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}a(St,"isOversizeResponse");var Rt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:$})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),z=class{constructor(e){this.client=e}client;static{a(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],l=Math.max(0,t.afterSequence??0),c=0,p=t.names?new Set(t.names):null;for(;i.length<=s;){let u=await this.runtimeEventPageRows({sessionId:e,afterSequence:l,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let g of u.entries){if(g.sequence<=l)throw new Error("Host event cursor did not advance.");if(l=g.sequence,c+=1,c>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!p||p.has(g.event.name))&&i.push(g.event)}if(u.entries.length===0||u.remainingMatchingEvents<=u.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=$.parse(e),r=await this.client.request({contractVersion:b,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:$}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],l=0,c=0;for(;i.length<t;){let p=Math.min(200,t-i.length),u=await L(p,async g=>Rt.parse(await this.client.request({contractVersion:b,requestId:`event-page:${yt()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:g,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(l=u.totalMatchingEvents,c=u.remainingMatchingEvents),i=s===null?[...i,...u.entries]:[...u.entries,...i],u.entries.length===0||u.remainingMatchingEvents<=u.entries.length)break;if(s===null){let g=u.entries.at(-1).sequence;if(g<=r)throw new Error("Host event cursor did not advance.");r=g}else{let g=u.entries[0].sequence;if(g>=s)throw new Error("Host event cursor did not advance.");s=g}}return{entries:i,totalMatchingEvents:l,remainingMatchingEvents:c}}};import{randomUUID as I}from"node:crypto";var ze=o.object({revision:o.number().int().min(1),session:F}).strict(),Ye=o.object({revision:o.number().int().min(1),turn:N}).strict(),It=o.object({sessions:o.array(F).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),Tt=o.object({turns:o.array(N).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),Y=class{constructor(e){this.client=e}client;static{a(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:b,requestId:I(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"session/get",params:{sessionId:e}});return t===null?null:ze.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await L(Math.min(10,1001-e.length),async s=>It.parse(await this.client.request({contractVersion:b,requestId:I(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:I()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=F.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:I()})).session}async put(e){let t=F.parse(e.session);return ze.parse(await this.client.request({contractVersion:b,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ye.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let l=await L(Math.min(200,r-s.length),async c=>Tt.parse(await this.client.request({contractVersion:b,requestId:I(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:c}})));if(s.push(...l.turns),l.nextBeforeSortIndex===null)break;if(i!==null&&l.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=l.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:N.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:I()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=N.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:I()})).turn}async putTurn(e){let t=N.parse(e.turn);return Ye.parse(await this.client.request({contractVersion:b,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as Pt,randomUUID as xt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),K=o.array(_),Et=o.array(o.string()),Ct=o.object({turnId:o.string(),run:M}).strict(),kt=o.object({inputs:o.array(_).max(10),hasMore:o.boolean()}).strict(),At=o.object({items:o.array(W).max(10),hasMore:o.boolean()}).strict(),Ot=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function X(n,e){return`inbox:${n}:${Pt("sha256").update(JSON.stringify(e)).digest("hex")}`}a(X,"retryKey");var q=class{constructor(e){this.client=e}client;static{a(this,"HostedTaskInboxStorage")}async call(e,t,r=xt()){let s=await this.client.request({contractVersion:b,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),kt);for(let l of i.inputs){if(l.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=l.sequence,r.push(l),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},Te),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Et)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},_)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},K)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},_.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let l=Math.min(10,r-s.length),c=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:l}},K);if(!c.length)break;for(let p of c){if(p.sequence<=i)throw new Error("Host task input cursor did not advance.");i=p.sequence,s.push(p)}if(c.length<l)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},_,X("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,X("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},K,X("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},K)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},_.nullable(),X("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Ot);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},W)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},W)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},At);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(Ct).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:M.parse(e)},M)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},M.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let l=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(M).max(10));for(let c of l){if(c.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=c.id,r.push(c),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(l.length<10)break}return r.sort((l,c)=>(c.updatedAt??c.createdAt).localeCompare(l.updatedAt??l.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ne=class extends q{static{a(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new Y(e),this.events=new z(e),this.approvals=new Ne(e),this.usage=new qe(e),this.createImprove=new J(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}async runtimeEventsForTurn(e,t){let r=await this.getTurn(e);if(!r)return[];let s=(await this.events.runtimeEventsForSession(r.sessionId)).filter(i=>i.turnId===e&&(!t?.names||t.names.includes(i.name)));return t?.limit==null?s:s.slice(0,Math.max(0,t.limit))}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ht("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function Ke(n){return new ne(n)}a(Ke,"createHostedRuntimeCoreStorage");function se(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return a(async function*(l){if(l.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Ee({...l,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}a(se,"createHostedModelStreamFromEnvironment");import{existsSync as _t}from"node:fs";import{lstat as Ut,readFile as Mt,realpath as Nt}from"node:fs/promises";import y from"node:path";import{fileURLToPath as qt}from"node:url";var Xe=y.dirname(qt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}a(R,"requireValue");function Ze(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}a(Ze,"parsePort");function tt(n){let e="serve",t=Q,r=17874,s=null,i=!1,l=!1,c=null,p,u=!1,g,w,x,k=null,f=null,h=null,S=null,T,v="sqlite_bundle",A=0,E=n[0];if(E&&!E.startsWith("-")){if(E==="serve"||E==="server")e="serve";else if(E==="app-server")e="app-server";else if(E==="web")e="web";else{if(E==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,help:!0};throw new Error(`Unknown command: ${E}`)}A=1}for(let m=A;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,help:!0};if(d==="--listen"){let O=xe(R(n,m,d));t=O.host,r=Ze(String(O.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Ze(R(n,m,d),d),m+=1;else if(d==="--web-root")s=y.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")x=y.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")c=y.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")p=y.resolve(R(n,m,d)),m+=1;else if(d==="--experiment-owner")u=!0;else if(d==="--experiment-harness-package"){if(g)throw new Error("Duplicate Experiment Harness source package.");g=y.resolve(R(n,m,d)),m+=1}else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");v="hosted_postgres",m+=1}else if(d==="--profile-external-dataset-package"){if(w)throw new Error("Duplicate private external Dataset package.");w=y.resolve(R(n,m,d)),m+=1}else if(d==="--profile-source-root")k=y.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")f=R(n,m,d),m+=1;else if(d==="--profile-id")h=R(n,m,d),m+=1;else if(d==="--profile-revision")S=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(T)throw new Error("Duplicate hosted Profile release descriptor.");let O=R(n,m,d);if(O.length>16e3||!/^[A-Za-z0-9_-]+$/.test(O))throw new Error("Invalid hosted Profile release descriptor.");try{T=Me.parse(JSON.parse(Buffer.from(O,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")l=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&l)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||l))throw new Error("Browser options are only available in web mode.");let D=[k,f,h,S].filter(Boolean).length;if(D&&(D!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(v==="hosted_postgres"&&(e!=="app-server"||c||D))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(T&&v!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(p&&v!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");if(u&&(e!=="app-server"||v!=="sqlite_bundle"||D||!c))throw new Error("Experiment owner mode requires an isolated app-server home without Profile selection.");if(g&&(!u||y.dirname(g)!==c))throw new Error("Experiment Harness source must be provisioned directly inside its isolated owner home.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,sourceBrowserState:x,...w?{profileExternalDatasetPackage:w}:{},...D?{profileSource:{repoPath:k,repositoryId:f,profileId:h,sourceRevision:S}}:{},...T?{admittedProfileRelease:T}:{},...p?{hostedCacheHome:p}:{},...u?{experimentOwner:!0}:{},...g?{experimentHarnessPackage:g}:{},help:!1}}a(tt,"parseCliArgs");function Dt(){return[process.env.OPENPOND_WEB_ROOT,y.resolve(process.cwd(),"apps/web/dist"),y.resolve(Xe,"../../web/dist"),y.resolve(process.cwd(),"web"),y.resolve(Xe,"../web")].filter(n=>!!n)}a(Dt,"defaultWebRootCandidates");function Bt(n){let e=n?[n]:Dt();for(let t of e){let r=y.resolve(t);if(_t(y.join(r,"index.html")))return r}return null}a(Bt,"resolveWebRoot");function Ft(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}a(Ft,"formatHostForUrl");function jt(n){return`http://${Ft(n.status.host)}:${n.status.port}`}a(jt,"browserBaseUrl");function Lt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}a(Lt,"tokenizedWebUrl");async function Qe(n,e=ke){let t=Lt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}a(Qe,"resolveWebLaunchMessages");function rt(){console.log(`Usage:
|
|
23
|
+
</script></html>`}a($e,"startupRecoveryPage");var ft=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:he.optional()});function We(n){return n instanceof ie&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}a(We,"isRecoverableStartupError");async function Ge(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await re.mkdtemp(dt.join(pt.tmpdir(),"openpond-recovery-")):n;return Oe(s,async()=>{let{token:i,tokenFile:l}=await Ue(s),c=De(n),p=t.issue,u,g=new Promise(f=>{u=f}),w=mt((f,h)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!je(f,h).allowed){P(h,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){P(h,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){P(h,200,{ok:!0,server:"openpond-app-server",version:Pe,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let v=gt(18).toString("base64");h.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${v}'; style-src 'nonce-${v}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),h.end($e(v));return}if(!Le(f,S,i)){P(h,401,{error:"Unauthorized"});return}let T=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){P(h,200,{issue:p,configEditable:T,config:r?{path:U(n).config,text:null,rawRevision:"unavailable",issue:p,recoverableRevisions:[]}:await c.status(),migration:await ve(n).catch(v=>({issue:B(v,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&T){P(h,200,await c.mutate(await te(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let v=ft.parse(await te(f));if(r&&v.action!=="retry"&&v.action!=="preview")throw t;if(v.action==="restart"){P(h,200,await we(n));return}if(v.action==="preview"||v.action==="migrate"){P(h,200,await Z(n,{sourceAppHome:v.sourceAppHome,sourceConfig:v.sourceConfig,resolutions:v.resolutions,dryRun:v.action==="preview"}));return}await Z(n),await V(n),P(h,200,{ready:!0}),u();return}P(h,503,{error:`${p.message} ${p.action}`,issue:p,recovery:!0})})().catch(S=>{p=B(S,n),P(h,422,{error:`${p.message} ${p.action}`,issue:p})})});await new Promise((f,h)=>{w.once("error",h),w.listen(e,"127.0.0.1",()=>{w.off("error",h),f()})});let x=w.address().port,k=`http://127.0.0.1:${x}`;return await He(s,k,"startup-recovery"),{url:k,port:x,token:i,tokenFile:l,storePath:U(n).database,repaired:g,close:a(async()=>{w.closeIdleConnections(),await new Promise((f,h)=>w.close(S=>S?h(S):f())),r&&await re.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await re.rm(s,{recursive:!0,force:!0}),i})}a(Ge,"startRecoveryServer");import{createHash as Ht}from"node:crypto";import{createHash as ht,randomUUID as Je}from"node:crypto";var vt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),wt=o.object({entries:o.array(H).max(200),nextBefore:vt.nullable()}).strict(),bt=o.object({run:H,replayed:o.boolean()}).strict(),J=class{constructor(e){this.client=e}client;static{a(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:b,requestId:Je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:H.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let l=wt.parse(await this.client.request({contractVersion:b,requestId:Je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&l.entries.some(c=>c.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...l.entries),!l.nextBefore)break;if(l.entries.length===0||i&&(l.nextBefore.updatedAt>i.updatedAt||l.nextBefore.updatedAt===i.updatedAt&&l.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=l.nextBefore}return s}async upsertCreateImproveRun(e){let t=H.parse(e),r=`create-improve:${ht("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:b,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return H.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=Ie.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=H.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return bt.parse(await this.client.request({contractVersion:b,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as yt}from"node:crypto";async function L(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!St(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}a(L,"hostedBoundedPage");function St(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}a(St,"isOversizeResponse");var Rt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:$})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),z=class{constructor(e){this.client=e}client;static{a(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],l=Math.max(0,t.afterSequence??0),c=0,p=t.names?new Set(t.names):null;for(;i.length<=s;){let u=await this.runtimeEventPageRows({sessionId:e,afterSequence:l,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let g of u.entries){if(g.sequence<=l)throw new Error("Host event cursor did not advance.");if(l=g.sequence,c+=1,c>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!p||p.has(g.event.name))&&i.push(g.event)}if(u.entries.length===0||u.remainingMatchingEvents<=u.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=$.parse(e),r=await this.client.request({contractVersion:b,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:$}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],l=0,c=0;for(;i.length<t;){let p=Math.min(200,t-i.length),u=await L(p,async g=>Rt.parse(await this.client.request({contractVersion:b,requestId:`event-page:${yt()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:g,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(l=u.totalMatchingEvents,c=u.remainingMatchingEvents),i=s===null?[...i,...u.entries]:[...u.entries,...i],u.entries.length===0||u.remainingMatchingEvents<=u.entries.length)break;if(s===null){let g=u.entries.at(-1).sequence;if(g<=r)throw new Error("Host event cursor did not advance.");r=g}else{let g=u.entries[0].sequence;if(g>=s)throw new Error("Host event cursor did not advance.");s=g}}return{entries:i,totalMatchingEvents:l,remainingMatchingEvents:c}}};import{randomUUID as I}from"node:crypto";var ze=o.object({revision:o.number().int().min(1),session:F}).strict(),Ye=o.object({revision:o.number().int().min(1),turn:N}).strict(),It=o.object({sessions:o.array(F).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),Tt=o.object({turns:o.array(N).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),Y=class{constructor(e){this.client=e}client;static{a(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:b,requestId:I(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"session/get",params:{sessionId:e}});return t===null?null:ze.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await L(Math.min(10,1001-e.length),async s=>It.parse(await this.client.request({contractVersion:b,requestId:I(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:I()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=F.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:I()})).session}async put(e){let t=F.parse(e.session);return ze.parse(await this.client.request({contractVersion:b,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ye.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let l=await L(Math.min(200,r-s.length),async c=>Tt.parse(await this.client.request({contractVersion:b,requestId:I(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:c}})));if(s.push(...l.turns),l.nextBeforeSortIndex===null)break;if(i!==null&&l.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=l.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:b,requestId:I(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:b,requestId:I(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:N.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:I()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=N.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:I()})).turn}async putTurn(e){let t=N.parse(e.turn);return Ye.parse(await this.client.request({contractVersion:b,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as Pt,randomUUID as xt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),K=o.array(_),Et=o.array(o.string()),Ct=o.object({turnId:o.string(),run:M}).strict(),kt=o.object({inputs:o.array(_).max(10),hasMore:o.boolean()}).strict(),At=o.object({items:o.array(W).max(10),hasMore:o.boolean()}).strict(),Ot=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function X(n,e){return`inbox:${n}:${Pt("sha256").update(JSON.stringify(e)).digest("hex")}`}a(X,"retryKey");var q=class{constructor(e){this.client=e}client;static{a(this,"HostedTaskInboxStorage")}async call(e,t,r=xt()){let s=await this.client.request({contractVersion:b,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),kt);for(let l of i.inputs){if(l.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=l.sequence,r.push(l),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},Te),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Et)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},_)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},K)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},_.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let l=Math.min(10,r-s.length),c=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:l}},K);if(!c.length)break;for(let p of c){if(p.sequence<=i)throw new Error("Host task input cursor did not advance.");i=p.sequence,s.push(p)}if(c.length<l)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},_,X("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,X("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},K,X("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},K)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},_.nullable(),X("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Ot);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},W)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},W)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},At);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(Ct).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:M.parse(e)},M)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},M.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let l=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(M).max(10));for(let c of l){if(c.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=c.id,r.push(c),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(l.length<10)break}return r.sort((l,c)=>(c.updatedAt??c.createdAt).localeCompare(l.updatedAt??l.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ne=class extends q{static{a(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new Y(e),this.events=new z(e),this.approvals=new Ne(e),this.usage=new qe(e),this.createImprove=new J(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}async runtimeEventsForTurn(e,t){let r=await this.getTurn(e);if(!r)return[];let s=(await this.events.runtimeEventsForSession(r.sessionId)).filter(i=>i.turnId===e&&(!t?.names||t.names.includes(i.name)));return t?.limit==null?s:s.slice(0,Math.max(0,t.limit))}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ht("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function Ke(n){return new ne(n)}a(Ke,"createHostedRuntimeCoreStorage");function se(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return a(async function*(l){if(l.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Ce({...l,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}a(se,"createHostedModelStreamFromEnvironment");import{existsSync as _t}from"node:fs";import{lstat as Ut,readFile as Mt,realpath as Nt}from"node:fs/promises";import y from"node:path";import{fileURLToPath as qt}from"node:url";var Xe=y.dirname(qt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}a(R,"requireValue");function Ze(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}a(Ze,"parsePort");function tt(n){let e="serve",t=Q,r=17874,s=null,i=!1,l=!1,c=null,p,u=!1,g,w,x,k=null,f=null,h=null,S=null,T,v="sqlite_bundle",A=0,E=n[0];if(E&&!E.startsWith("-")){if(E==="serve"||E==="server")e="serve";else if(E==="app-server")e="app-server";else if(E==="web")e="web";else{if(E==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,help:!0};throw new Error(`Unknown command: ${E}`)}A=1}for(let m=A;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,help:!0};if(d==="--listen"){let O=xe(R(n,m,d));t=O.host,r=Ze(String(O.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Ze(R(n,m,d),d),m+=1;else if(d==="--web-root")s=y.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")x=y.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")c=y.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")p=y.resolve(R(n,m,d)),m+=1;else if(d==="--experiment-owner")u=!0;else if(d==="--experiment-harness-package"){if(g)throw new Error("Duplicate Experiment Harness source package.");g=y.resolve(R(n,m,d)),m+=1}else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");v="hosted_postgres",m+=1}else if(d==="--profile-external-dataset-package"){if(w)throw new Error("Duplicate private external Dataset package.");w=y.resolve(R(n,m,d)),m+=1}else if(d==="--profile-source-root")k=y.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")f=R(n,m,d),m+=1;else if(d==="--profile-id")h=R(n,m,d),m+=1;else if(d==="--profile-revision")S=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(T)throw new Error("Duplicate hosted Profile release descriptor.");let O=R(n,m,d);if(O.length>16e3||!/^[A-Za-z0-9_-]+$/.test(O))throw new Error("Invalid hosted Profile release descriptor.");try{T=Me.parse(JSON.parse(Buffer.from(O,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")l=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&l)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||l))throw new Error("Browser options are only available in web mode.");let D=[k,f,h,S].filter(Boolean).length;if(D&&(D!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(v==="hosted_postgres"&&(e!=="app-server"||c||D))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(T&&v!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(p&&v!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");if(u&&(e!=="app-server"||v!=="sqlite_bundle"||D||!c))throw new Error("Experiment owner mode requires an isolated app-server home without Profile selection.");if(g&&(!u||y.dirname(g)!==c))throw new Error("Experiment Harness source must be provisioned directly inside its isolated owner home.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:c,runtimeStorage:v,sourceBrowserState:x,...w?{profileExternalDatasetPackage:w}:{},...D?{profileSource:{repoPath:k,repositoryId:f,profileId:h,sourceRevision:S}}:{},...T?{admittedProfileRelease:T}:{},...p?{hostedCacheHome:p}:{},...u?{experimentOwner:!0}:{},...g?{experimentHarnessPackage:g}:{},help:!1}}a(tt,"parseCliArgs");function Dt(){return[process.env.OPENPOND_WEB_ROOT,y.resolve(process.cwd(),"apps/web/dist"),y.resolve(Xe,"../../web/dist"),y.resolve(process.cwd(),"web"),y.resolve(Xe,"../web")].filter(n=>!!n)}a(Dt,"defaultWebRootCandidates");function Bt(n){let e=n?[n]:Dt();for(let t of e){let r=y.resolve(t);if(_t(y.join(r,"index.html")))return r}return null}a(Bt,"resolveWebRoot");function Ft(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}a(Ft,"formatHostForUrl");function jt(n){return`http://${Ft(n.status.host)}:${n.status.port}`}a(jt,"browserBaseUrl");function Lt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}a(Lt,"tokenizedWebUrl");async function Qe(n,e=Ae){let t=Lt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}a(Qe,"resolveWebLaunchMessages");function rt(){console.log(`Usage:
|
|
24
24
|
openpond-app-server serve [--hostname HOST] [--port PORT]
|
|
25
25
|
openpond-app-server app-server [--home DIR]
|
|
26
26
|
openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
|
|
@@ -39,4 +39,4 @@ Options:
|
|
|
39
39
|
--profile-revision REV Accepted immutable source revision
|
|
40
40
|
--open-browser Open the authenticated web URL in the system browser
|
|
41
41
|
--print-access-url Print the authenticated URL instead of opening it
|
|
42
|
-
`)}a(rt,"printHelp");async function wn(n){let e=tt(process.argv.slice(2));if(e.help){rt();return}let t=e.mode==="web"?Bt(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await nt(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome,e.experimentOwner,e.experimentHarnessPackage,e.profileExternalDatasetPackage);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(p){if(!We(p))throw p;let u=await Ge(ae({home:e.storeDir??void 0}),s,p);s=u.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:u.url,tokenFile:u.tokenFile,storePath:u.storePath})}`),console.error(`${p.issue.code}: ${p.issue.message} ${p.issue.action}`);let g=await Qe({baseUrl:u.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:u.token});for(let x of g.stdout)console.log(x);for(let x of g.stderr)console.error(x);let w=a(()=>{u.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",w),process.once("SIGTERM",w);try{await u.repaired}finally{process.off("SIGINT",w),process.off("SIGTERM",w),await u.close()}}let i=e.mode==="web"?jt(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:
|
|
42
|
+
`)}a(rt,"printHelp");async function wn(n){let e=tt(process.argv.slice(2));if(e.help){rt();return}let t=e.mode==="web"?Bt(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await nt(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome,e.experimentOwner,e.experimentHarnessPackage,e.profileExternalDatasetPackage);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(p){if(!We(p))throw p;let u=await Ge(ae({home:e.storeDir??void 0}),s,p);s=u.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:u.url,tokenFile:u.tokenFile,storePath:u.storePath})}`),console.error(`${p.issue.code}: ${p.issue.message} ${p.issue.action}`);let g=await Qe({baseUrl:u.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:u.token});for(let x of g.stdout)console.log(x);for(let x of g.stderr)console.error(x);let w=a(()=>{u.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",w),process.once("SIGTERM",w);try{await u.repaired}finally{process.off("SIGINT",w),process.off("SIGTERM",w),await u.close()}}let i=e.mode==="web"?jt(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:ke()})}`),i){let p=await Qe({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let u of p.stderr)console.error(u);for(let u of p.stdout)console.log(u)}else console.log(`OpenPond API server: ${r.url}`);let l=!1,c=a(async()=>{l||(l=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{c()}),process.on("SIGTERM",()=>{c()}),await new Promise(()=>{})}a(wn,"runOpenPondServerCli");async function bn(n){let e=process.argv.slice(2),t=tt(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){rt();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await nt(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease,t.hostedCacheHome,t.experimentOwner,t.experimentHarnessPackage,t.profileExternalDatasetPackage)}a(bn,"runOpenPondAppServerCli");async function nt(n,e,t,r="sqlite_bundle",s,i,l=!1,c,p){let u=new Ee;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await ee({appServer:a(()=>n({...i?{storeDir:i}:{},hostStorageClient:u,runtimeStorage:{kind:"hosted_postgres",client:u,core:Ke(u),inbox:new q(u),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:se()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:u});return}e&&(process.env.OPENPOND_HOME=e);let g;if(c){if(!l||!e||y.dirname(c)!==e||await Nt(c)!==c)throw new Error("Experiment Harness source escaped its isolated owner home.");let f=await Ut(c);if(!f.isFile()||f.size>67108864)throw new Error("Experiment Harness source package is not a bounded regular file.");g={ownerId:"host-experiment-case",sourcePackage:oe(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(await Mt(c))))}}let w=p?await(e&&t&&!l?_e(p,e):Promise.reject(new Error("External Dataset bootstrap requires a private explicit Profile owner."))):void 0,x=w?se():void 0,k=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},...w?{profileExternalDataset:w,profileExternalDatasetClient:u,streamOpenPondHostedChatTurn:a(async function*(f){let h=a(async()=>{await u.request({contractVersion:1,requestId:crypto.randomUUID(),operation:"profile.externalDataset.authorize",params:{bindingHash:w.binding.contentHash}})},"fence");await h();let S=new AbortController,T=!1,v=setInterval(()=>{T||S.signal.aborted||(T=!0,h().catch(A=>S.abort(A)).finally(()=>{T=!1}))},2e3);try{let A=AbortSignal.any([...f.signal?[f.signal]:[],S.signal]);A.throwIfAborted();for await(let E of x({...f,signal:A}))await h(),A.throwIfAborted(),yield E}finally{clearInterval(v),S.abort()}},"streamOpenPondHostedChatTurn"),services:{webSearch:!1,scheduling:!1,connectedApps:!1,tasksets:!1,projectActions:!1,profileActions:!1,backgroundReview:!1}}:{},...g?{experimentHarnessSource:g}:{},...l?{experimentPolicyClient:u,services:{webSearch:!1,scheduling:!1,connectedApps:!1,tasksets:!1,projectActions:!1,profileActions:!1,backgroundReview:!1}}:{},hostStorageClient:u});await ee({appServer:k,readable:process.stdin,writable:process.stdout,hostStorageClient:u})}a(nt,"runAgentServer");export{De as a,j as b,je as c,P as d,zt as e,Yt as f,te as g,Le as h,Qe as i,wn as j,bn as k};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as n}from"./chunk-FTQLQJQV.js";var s="127.0.0.1";var f="0.2.
|
|
2
|
+
import{a as n}from"./chunk-FTQLQJQV.js";var s="127.0.0.1";var f="0.2.46",m="You are OpenPond Chat. Respond in the user's language. If the user's latest message is language-neutral, ambiguous, or only a short test, respond in English. Be concise and directly answer the latest request. Do not use emojis. Use Markdown when it improves scanability. If you emit reasoning or thinking content, keep it sparse and user-readable: at most one short sentence for major progress, decisions, or blockers. Omit reasoning for routine searches, reads, tool calls, and obvious next steps. Do not restate the user request, narrate every action, or include code blocks, code excerpts, diffs, raw tool payloads, or markdown examples in reasoning. Put necessary code or exact snippets only in the final assistant answer. When the user asks to show or preview an image that is available as a workspace path or signed image URL, use Markdown image syntax like  instead of a bare path or raw HTML. For workspace-backed answers, use a Codex-style shape: brief outcome first, then Changed Files if files changed, then Verification if checks ran. End with a concise final answer that summarizes the result and verification when relevant. Do not mention raw tool JSON, internal repo paths, or origin/remote URLs unless the user explicitly asks for them or they are necessary to explain a git/deploy failure.";import{randomUUID as p}from"node:crypto";import i from"node:path";import{fileURLToPath as c}from"node:url";function u(){return new Date().toISOString()}n(u,"now");function l(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}n(l,"textFromUnknown");function w(e){if(!e||typeof e!="object")return"";let t=e;for(let r of["delta","text","output","chunk","message"])if(typeof t[r]=="string")return t[r];return t.delta&&typeof t.delta=="object"?l(t.delta):""}n(w,"extractDelta");function x(e){return{id:p(),timestamp:u(),...e}}n(x,"event");function k(e){let t=e.replace(/^https?:\/\//,""),[r,o]=t.split(":");return{host:r||s,port:o?Number.parseInt(o,10):17874}}n(k,"parseListen");function b(e){return(process.argv[1]?i.resolve(process.argv[1]):"")===i.resolve(c(e))}n(b,"isCliEntrypoint");export{s as a,f as b,m as c,u as d,l as e,w as f,x as g,k as h,b as i};
|