openpond 0.2.36 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-server.d.ts +189 -3
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-GNQREIDD.js +2 -0
- package/dist/chunks/{app-layer-KPPQSL67.js → app-layer-BDAKS3DG.js} +1 -1
- package/dist/chunks/app-server-runtime-D74FFS27.js +2 -0
- package/dist/chunks/apps-2SUP5JZE.js +2 -0
- package/dist/chunks/chunk-2O5UZOYL.js +13 -0
- package/dist/chunks/{chunk-Q2Z27DCK.js → chunk-3I5BMVJI.js} +1 -1
- package/dist/chunks/{chunk-P3DI3ZMK.js → chunk-3LG4G5JR.js} +2 -2
- package/dist/chunks/{chunk-4QX2I2DX.js → chunk-3N4GQL6I.js} +1 -1
- package/dist/chunks/{chunk-DR3XPQRZ.js → chunk-3YA2CD22.js} +1 -1
- package/dist/chunks/{chunk-EFTLCT7C.js → chunk-4R4KM6LL.js} +1 -1
- package/dist/chunks/{chunk-MXLB6MEW.js → chunk-5YUITAUN.js} +1 -1
- package/dist/chunks/{chunk-QPZNN5Q3.js → chunk-6EAQL7YX.js} +1 -1
- package/dist/chunks/{chunk-DJHJIXMW.js → chunk-BLXEK5F7.js} +1 -1
- package/dist/chunks/{chunk-BFHAJTU4.js → chunk-DAOLQUAK.js} +1 -1
- package/dist/chunks/{chunk-ZF6OAPTQ.js → chunk-DG4DIFF4.js} +1 -1
- package/dist/chunks/{chunk-SHWLRMDG.js → chunk-DXOOJFFU.js} +1 -1
- package/dist/chunks/chunk-EIB7GHIQ.js +4 -0
- package/dist/chunks/{chunk-XCTFXXVY.js → chunk-FFEI7IRU.js} +1 -1
- package/dist/chunks/chunk-FOW3LI6G.js +2 -0
- package/dist/chunks/{chunk-VRY5TEEF.js → chunk-FQOVC2GR.js} +78 -78
- package/dist/chunks/chunk-HZP5U2AA.js +3 -0
- package/dist/chunks/chunk-I6DQSOSF.js +12 -0
- package/dist/chunks/chunk-IYROEHYB.js +2 -0
- package/dist/chunks/{chunk-LL3ZAZEU.js → chunk-KCFVJDIV.js} +1 -1
- package/dist/chunks/chunk-L6NNQUAT.js +53 -0
- package/dist/chunks/chunk-OO7JG7KM.js +42 -0
- package/dist/chunks/chunk-PKBU37CH.js +5 -0
- package/dist/chunks/chunk-QUNRWDVO.js +155 -0
- package/dist/chunks/{chunk-34URWDE7.js → chunk-S4RSY6CR.js} +1 -1
- package/dist/chunks/{chunk-5WFHGIQB.js → chunk-SL7XLTIT.js} +199 -199
- package/dist/chunks/{chunk-CL6YPTWP.js → chunk-TZ6N7WFI.js} +1 -1
- package/dist/chunks/{chunk-Z6F6PYF4.js → chunk-UJLZRM2M.js} +1 -1
- package/dist/chunks/chunk-XISNUB62.js +2 -0
- package/dist/chunks/{chunk-FIFGH6W3.js → chunk-XLVFY2BA.js} +1 -1
- package/dist/chunks/{chunk-K6EGNB2A.js → chunk-YQPECTJ2.js} +1 -1
- package/dist/chunks/{chunk-YZ262JZT.js → chunk-Z3RBK6LN.js} +1 -1
- package/dist/chunks/cli-A2P56J7R.js +2 -0
- package/dist/chunks/configuration-command-URDRLDNY.js +2 -0
- package/dist/chunks/core-commands-CMAAUKPQ.js +2 -0
- package/dist/chunks/desktop-test-5PKGG6H6.js +3 -0
- package/dist/chunks/dist-CEKBK32A.js +2 -0
- package/dist/chunks/dist-GKCGK44T.js +2 -0
- package/dist/chunks/{extension-LG3JL5QD.js → extension-DG2XISC6.js} +1 -1
- package/dist/chunks/{help-XP73IYAV.js → help-ZLJV3ZVW.js} +1 -1
- package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +2 -0
- package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +3 -0
- package/dist/chunks/{opchat-5NQ22CPO.js → opchat-IMGIFM4W.js} +1 -1
- package/dist/chunks/organizations-G3UOHURO.js +2 -0
- package/dist/chunks/{profile-O7NIC76F.js → profile-LMRN5QMQ.js} +1 -1
- package/dist/chunks/project-agent-DTAVYEB6.js +2 -0
- package/dist/chunks/sandbox-command-YO6RR5SD.js +2 -0
- package/dist/chunks/{sandbox-template-H5M4NV2F.js → sandbox-template-LN5OQ55F.js} +1 -1
- package/dist/chunks/{src-WN3RDFPF.js → src-A5KEQW52.js} +1 -1
- package/dist/chunks/{src-BITVDQDA.js → src-LRJO4THC.js} +1 -1
- package/dist/chunks/{teams-bot-RPZVD4UD.js → teams-bot-RY5M6AOW.js} +1 -1
- package/dist/chunks/{workspaces-XMU4772P.js → workspaces-KZ6ZJXXY.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/actions-command-U2DMVGDS.js +0 -2
- package/dist/chunks/app-server-runtime-ELR3VCKR.js +0 -2
- package/dist/chunks/apps-NBV45ZGW.js +0 -2
- package/dist/chunks/chunk-IFP6W4OW.js +0 -54
- package/dist/chunks/chunk-JB6FTAMW.js +0 -2
- package/dist/chunks/chunk-L67V63N3.js +0 -2
- package/dist/chunks/chunk-MPNHNWN6.js +0 -15
- package/dist/chunks/chunk-PBRD43CI.js +0 -42
- package/dist/chunks/chunk-RC3JXLP7.js +0 -4
- package/dist/chunks/chunk-VVKE6EYN.js +0 -166
- package/dist/chunks/cli-EG7K37TB.js +0 -2
- package/dist/chunks/configuration-command-MSDFCKOT.js +0 -2
- package/dist/chunks/core-commands-WDHXJPCY.js +0 -2
- package/dist/chunks/desktop-test-SN4BHDV3.js +0 -3
- package/dist/chunks/dist-XCT2G25K.js +0 -2
- package/dist/chunks/hosted-profile-compiler-HQ6T6NDP.js +0 -3
- package/dist/chunks/organizations-AY52SHI4.js +0 -2
- package/dist/chunks/project-agent-UKGWIFFI.js +0 -2
- package/dist/chunks/sandbox-command-WL6DAJTO.js +0 -2
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as Re,c as Ie,e as X,j as Ee,k as ke,l as Oe,m as Ae}from"./chunk-XISNUB62.js";import{i as Pe,o as xe,q as Ce}from"./chunk-DXOOJFFU.js";import{E as v,I as Te}from"./chunk-PKBU37CH.js";import{a as K,b as Se,h as ye}from"./chunk-Z3RBK6LN.js";import{Aa as k,Ba as we,Ea as q,Fa as M,U as j,ue as O,xe as L,ye as be}from"./chunk-BLXEK5F7.js";import{$a as F,F as H,Ra as pe,Sa as de,Ua as Y,Xa as me,_a as ge,b as ne,c as se,db as he,fb as fe,gb as ve,ja as oe,la as ie,ma as ae,na as ue,oa as le,qa as ce}from"./chunk-L6NNQUAT.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as te,d as N,f as re,h as _}from"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as Q}from"node:fs";import it from"node:os";import at from"node:path";import{createServer as ut}from"node:http";import{randomBytes as lt}from"node:crypto";var Qe=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)})]),et=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(Qe).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:he,importOnly:o.boolean().optional()})]);function _e(n){let e=null;async function t(s,i){let a=_(n).config,l=null,c=null,p=null;try{l=await se(a),p=await F(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){c=N(b,a)}let h=p??(s?null:e);return{path:a,text:l,rawRevision:ne(l),issue:c,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ie(n),clientState:c?null:await fe(n)}}u(t,"status");async function r(s){let i=et.parse(s);return i.action==="validate"?{valid:!0,document:oe(i.text,_(n).config)}:(i.action==="patch"&&await ce(n,i.expectedRevision,i.operations),i.action==="replace"&&await ae(n,i.expectedRevision,i.text),i.action==="restore"&&await ue(n,i.revision,i.expectedRevision),i.action==="trust"&&await ge(n,i.root,i.accountId,i.trusted),i.action==="client-state"?ve(n,i.owner,i.patch,i.importOnly):t())}return u(r,"mutate"),{status:t,mutate:r,schema:le}}u(_e,"createConfigurationPayloads");import{Buffer as He}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},tt=25*1024*1024,B=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{u(this,"HttpBodyError")}};function Ue(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=qe(n.headers.origin);return r?(e.setHeader("Vary",ot(e.getHeader("Vary"))),rt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}u(Ue,"applyCorsHeaders");function rt(n,e={}){if(n==="null")return!0;let t=Me(n);return t?st(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Me(s):null).filter(s=>!!s)).has(t):!1}u(rt,"isAllowedCorsOrigin");function I(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}u(I,"sendJson");function Ft(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}u(Ft,"sendText");function jt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}u(jt,"sendBinary");async function Z(n,e={}){let t=e.maxBytes??tt,r=qe(n.headers["content-type"]),s=[],i=0;for await(let l of n){let c=He.from(l);if(i+=c.byteLength,i>t)throw new B(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(c)}let a=He.concat(s).toString("utf8").trim();if(!a)return{};if(!nt(r))throw new B(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new B(400,"invalid_json","Request body is not valid JSON.")}}u(Z,"readJson");function Ne(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}u(Ne,"hasAuth");function qe(n){return Array.isArray(n)?n[0]??null:n??null}u(qe,"headerValue");function nt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}u(nt,"isJsonContentType");function Me(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}u(Me,"normalizeOrigin");function st(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}u(st,"isLoopbackOrigin");function ot(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(", ")}u(ot,"appendVaryOrigin");function Be(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
|
+
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
|
+
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
|
+
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
6
|
+
<details id="editor"><summary>Edit configuration</summary><textarea id="text" aria-label="Configuration TOML" spellcheck="false"></textarea><button id="save">Validate and save</button><button id="reload">Reload file</button><select id="revisions" aria-label="Restore a verified configuration revision"><option value="">Restore a verified revision\u2026</option></select></details>
|
|
7
|
+
<details><summary>Migration sources and diagnostics</summary><pre id="migration"></pre><label>Previous app home <input id="appHome"></label><label>Previous account config <input id="configSource"></label><label>Configuration conflict choices (JSON from the preview) <textarea id="resolutions" aria-label="Migration conflict choices" spellcheck="false" placeholder='[{"path":["chat","steer_active_responses"],"choice":"existing"}]'></textarea></label><button id="preview">Preview migration</button><button id="migrate">Use these sources</button><button id="restart">Restart failed preparation</button><button id="diagnostics">Export diagnostics</button></details>
|
|
8
|
+
<button id="retry">Retry startup</button><p id="message" role="status"></p>
|
|
9
|
+
<script nonce="${n}">
|
|
10
|
+
let token='',state=null,editing=false,revision=null;
|
|
11
|
+
const el=id=>document.getElementById(id);
|
|
12
|
+
async function request(route,body){const r=await fetch(route,{method:body?'POST':'GET',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:body?JSON.stringify(body):undefined});const v=await r.json();if(!r.ok)throw Error(v.error||'Recovery request failed');return v;}
|
|
13
|
+
function message(error){el('message').textContent=error instanceof Error?error.message:String(error);}
|
|
14
|
+
async function load(){state=await request('/v1/recovery');el('issue').textContent=state.issue.message;el('action').textContent=state.issue.action;el('file').textContent=state.issue.path;el('migration').textContent=JSON.stringify(state.migration,null,2);if(!editing){el('text').value=state.config.text||'schema_version = 1\\n';revision=state.config.rawRevision;}el('revisions').replaceChildren(new Option('Restore a verified revision\u2026',''),...state.config.recoverableRevisions.map(r=>new Option(r.createdAt,r.revision)));el('editor').hidden=!state.configEditable;}
|
|
15
|
+
el('text').oninput=()=>{editing=true};
|
|
16
|
+
el('reload').onclick=()=>{editing=false;load().catch(message)};
|
|
17
|
+
el('save').onclick=async()=>{try{await request('/v1/configuration',{action:'replace',text:el('text').value,expectedRevision:revision});editing=false;await load();message('Configuration saved. Retry startup when ready.')}catch(e){message(e)}};
|
|
18
|
+
el('revisions').onchange=async e=>{if(!e.target.value)return;try{await request('/v1/configuration',{action:'restore',revision:e.target.value,expectedRevision:state.config.rawRevision});editing=false;await load();message('Verified revision restored.')}catch(e){message(e)}};
|
|
19
|
+
for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart','restart']])el(id).onclick=async()=>{try{const result=await request('/v1/recovery',{action,sourceAppHome:el('appHome').value||undefined,sourceConfig:el('configSource').value||undefined,resolutions:el('resolutions').value?JSON.parse(el('resolutions').value):undefined});el('migration').textContent=JSON.stringify(result,null,2);message(action==='preview'?'Review the source paths above.':'Migration operation completed; retry startup.')}catch(e){message(e)}};
|
|
20
|
+
el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
|
|
21
|
+
el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
|
|
22
|
+
(async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
|
|
23
|
+
</script></html>`}u(Be,"startupRecoveryPage");var ct=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:pe.optional()});function De(n){return n instanceof te&&/^(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)}u(De,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await Q.mkdtemp(at.join(it.tmpdir(),"openpond-recovery-")):n;return Re(s,async()=>{let{token:i,tokenFile:a}=await Ee(s),l=_e(n),c=t.issue,p,h=new Promise(f=>{p=f}),b=ut((f,g)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!Ue(f,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){I(g,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:Se,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let w=lt(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${w}'; style-src 'nonce-${w}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(Be(w));return}if(!Ne(f,S,i)){I(g,401,{error:"Unauthorized"});return}let P=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:P,config:r?{path:_(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await de(n).catch(w=>({issue:N(w,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&P){I(g,200,await l.mutate(await Z(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let w=ct.parse(await Z(f));if(r&&w.action!=="retry"&&w.action!=="preview")throw t;if(w.action==="restart"){I(g,200,await me(n));return}if(w.action==="preview"||w.action==="migrate"){I(g,200,await Y(n,{sourceAppHome:w.sourceAppHome,sourceConfig:w.sourceConfig,resolutions:w.resolutions,dryRun:w.action==="preview"}));return}await Y(n),await F(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(S=>{c=N(S,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((f,g)=>{b.once("error",g),b.listen(e,"127.0.0.1",()=>{b.off("error",g),f()})});let x=b.address().port,A=`http://127.0.0.1:${x}`;return await Ie(s,A,"startup-recovery"),{url:A,port:x,token:i,tokenFile:a,storePath:_(n).database,repaired:h,close:u(async()=>{b.closeIdleConnections(),await new Promise((f,g)=>b.close(S=>S?g(S):f())),r&&await Q.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await Q.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as Ct}from"node:crypto";import{createHash as pt,randomUUID as je}from"node:crypto";var dt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),mt=o.object({entries:o.array(k).max(200),nextBefore:dt.nullable()}).strict(),gt=o.object({run:k,replayed:o.boolean()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:k.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 a=mt.parse(await this.client.request({contractVersion:v,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&&a.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=k.parse(e),r=`create-improve:${pt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return k.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=we.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=k.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 gt.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as ft}from"node:crypto";async function D(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}u(D,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}u(ht,"isOversizeResponse");var vt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:j})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),W=class{constructor(e){this.client=e}client;static{u(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=[],a=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=j.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:j}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await D(c,async h=>vt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${ft()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(a=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Le=o.object({revision:o.number().int().min(1),session:q}).strict(),Ve=o.object({revision:o.number().int().min(1),turn:M}).strict(),wt=o.object({sessions:o.array(q).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),bt=o.object({turns:o.array(M).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),G=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Le.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await D(Math.min(10,1001-e.length),async s=>wt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=q.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=q.parse(e.session);return Le.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ve.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 a=await D(Math.min(200,r-s.length),async l=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:M.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=M.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=M.parse(e.turn);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as St,randomUUID as yt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),J=o.array(O),Rt=o.array(o.string()),It=o.object({turnId:o.string(),run:H}).strict(),Tt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Pt=o.object({items:o.array(L).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function z(n,e){return`inbox:${n}:${St("sha256").update(JSON.stringify(e)).digest("hex")}`}u(z,"retryKey");var U=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=yt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Tt);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),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},be),[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},Rt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},J)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},J);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,z("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,z("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},J,z("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},J)}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},O.nullable(),z("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},xt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},L)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},L)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Pt);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(It).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:H.parse(e)},H)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},H.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(H).max(10));for(let l of a){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,l)=>(l.updatedAt??l.createdAt).localeCompare(a.updatedAt??a.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 ee=class extends U{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new G(e),this.events=new W(e),this.approvals=new ke(e),this.usage=new Oe(e),this.createImprove=new $(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)}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:${Ct("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 $e(n){return new ee(n)}u($e,"createHostedRuntimeCoreStorage");function We(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 u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Pe({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(We,"createHostedModelStreamFromEnvironment");import{existsSync as Et}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Ge=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(R,"requireValue");function Je(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}u(Je,"parsePort");function Ke(n){let e="serve",t=K,r=17874,s=null,i=!1,a=!1,l=null,c,p,h=null,b=null,x=null,A=null,f,g="sqlite_bundle",S=0,P=n[0];if(P&&!P.startsWith("-")){if(P==="serve"||P==="server")e="serve";else if(P==="app-server")e="app-server";else if(P==="web")e="web";else{if(P==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};throw new Error(`Unknown command: ${P}`)}S=1}for(let m=S;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:a,storeDir:l,runtimeStorage:g,help:!0};if(d==="--listen"){let E=ye(R(n,m,d));t=E.host,r=Je(String(E.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Je(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")p=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");g="hosted_postgres",m+=1}else if(d==="--profile-source-root")h=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")b=R(n,m,d),m+=1;else if(d==="--profile-id")x=R(n,m,d),m+=1;else if(d==="--profile-revision")A=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(f)throw new Error("Duplicate hosted Profile release descriptor.");let E=R(n,m,d);if(E.length>16e3||!/^[A-Za-z0-9_-]+$/.test(E))throw new Error("Invalid hosted Profile release descriptor.");try{f=Ae.parse(JSON.parse(Buffer.from(E,"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")a=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let w=[h,b,x,A].filter(Boolean).length;if(w&&(w!==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(g==="hosted_postgres"&&(e!=="app-server"||l||w))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(f&&g!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&g!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,sourceBrowserState:p,...w?{profileSource:{repoPath:h,repositoryId:b,profileId:x,sourceRevision:A}}:{},...f?{admittedProfileRelease:f}:{},...c?{hostedCacheHome:c}:{},help:!1}}u(Ke,"parseCliArgs");function Ot(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Ge,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Ge,"../web")].filter(n=>!!n)}u(Ot,"defaultWebRootCandidates");function At(n){let e=n?[n]:Ot();for(let t of e){let r=T.resolve(t);if(Et(T.join(r,"index.html")))return r}return null}u(At,"resolveWebRoot");function _t(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(_t,"formatHostForUrl");function Ht(n){return`http://${_t(n.status.host)}:${n.status.port}`}u(Ht,"browserBaseUrl");function Mt(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()}u(Mt,"tokenizedWebUrl");async function ze(n,e=Ce){let t=Mt(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}`]}}u(ze,"resolveWebLaunchMessages");function Xe(){console.log(`Usage:
|
|
24
|
+
openpond-app-server serve [--hostname HOST] [--port PORT]
|
|
25
|
+
openpond-app-server app-server [--home DIR]
|
|
26
|
+
openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
--listen HOST:PORT Set host and port together
|
|
30
|
+
--hostname HOST Bind host (default ${K})
|
|
31
|
+
--port PORT Bind port, or 0 for any free port (default ${17874})
|
|
32
|
+
--web-root DIR Directory containing the built web UI for web mode
|
|
33
|
+
--home DIR Local app-server state directory
|
|
34
|
+
--runtime-storage hosted-postgres Host-admitted Postgres app-server mode
|
|
35
|
+
--hosted-profile-release BASE64URL Host-admitted immutable Profile release descriptor
|
|
36
|
+
--profile-source-root DIR Authorized Profile repository source for app-server
|
|
37
|
+
--profile-repository-id ID Source repository identity supplied by the host
|
|
38
|
+
--profile-id ID Profile within that source
|
|
39
|
+
--profile-revision REV Accepted immutable source revision
|
|
40
|
+
--open-browser Open the authenticated web URL in the system browser
|
|
41
|
+
--print-access-url Print the authenticated URL instead of opening it
|
|
42
|
+
`)}u(Xe,"printHelp");async function an(n){let e=Ke(process.argv.slice(2));if(e.help){Xe();return}let t=e.mode==="web"?At(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 Ze(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(c){if(!De(c))throw c;let p=await Fe(re({home:e.storeDir??void 0}),s,c);s=p.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:p.url,tokenFile:p.tokenFile,storePath:p.storePath})}`),console.error(`${c.issue.code}: ${c.issue.message} ${c.issue.action}`);let h=await ze({baseUrl:p.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:p.token});for(let x of h.stdout)console.log(x);for(let x of h.stderr)console.error(x);let b=u(()=>{p.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",b),process.once("SIGTERM",b);try{await p.repaired}finally{process.off("SIGINT",b),process.off("SIGTERM",b),await p.close()}}let i=e.mode==="web"?Ht(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:xe()})}`),i){let c=await ze({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let p of c.stderr)console.error(p);for(let p of c.stdout)console.log(p)}else console.log(`OpenPond API server: ${r.url}`);let a=!1,l=u(async()=>{a||(a=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{l()}),process.on("SIGTERM",()=>{l()}),await new Promise(()=>{})}u(an,"runOpenPondServerCli");async function un(n){let e=process.argv.slice(2),t=Ke(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){Xe();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await Ze(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease,t.hostedCacheHome)}u(un,"runOpenPondAppServerCli");async function Ze(n,e,t,r="sqlite_bundle",s,i){let a=new Te;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await X({appServer:u(()=>n({...i?{storeDir:i}:{},hostStorageClient:a,runtimeStorage:{kind:"hosted_postgres",client:a,core:$e(a),inbox:new U(a),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:We()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:a});return}e&&(process.env.OPENPOND_HOME=e);let l=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},hostStorageClient:a});await X({appServer:l,readable:process.stdin,writable:process.stdout,hostStorageClient:a})}u(Ze,"runAgentServer");export{_e as a,B as b,Ue as c,I as d,Ft as e,jt as f,Z as g,Ne as h,ze as i,an as j,un as k};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as e}from"./chunk-ES2ISFJC.js";import{a}from"./chunk-FTQLQJQV.js";import{createHash as he}from"node:crypto";function V(r){if(r===null||typeof r=="boolean"||typeof r=="string")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Canonical JSON cannot encode a non-finite number.");return r}if(Array.isArray(r))return r.map(V);if(typeof r=="object"){let t={};for(let i of Object.keys(r).sort()){let n=r[i];n!==void 0&&(t[i]=V(n))}return t}throw new Error(`Canonical JSON cannot encode ${typeof r}.`)}a(V,"canonicalJson");function w(r){return he("sha256").update(JSON.stringify(V(r)),"utf8").digest("hex")}a(w,"canonicalHash");function Oe(r){if(!r.maxContextTokens||!r.usableContextTokens)return{shouldCompact:!1,projectedTokens:r.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(r.triggerPercent??85)/100)),i=Math.max(1,Math.floor(r.usableContextTokens*t));return{shouldCompact:r.projectedTokens>=i,projectedTokens:r.projectedTokens,thresholdTokens:i,usableContextTokens:r.usableContextTokens,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic"}}a(Oe,"agentCompactionDecision");async function Ne(r){await r.started();try{return await r.compact()}catch(t){throw await r.failed(t),t}}a(Ne,"runAgentCompaction");async function Be(r){let t=r.host.projectEvents(r.events),i=r.host.selectEvents(t,r.maxContextTokens),{summaryEvents:n,preservedEvents:o,preservedEventIds:l}=i;if(n.length===0)throw new Error("There is not enough prior context to compact.");let u=r.host.normalizeRecords(n),p=r.host.normalizeRecords(o),f=r.host.buildFileLedger(r.host.normalizeRecords(t)),h=r.host.serializeRecords(u,r.host.inputCharBudget(r.maxContextTokens));if(!h.text.trim())throw new Error("There is not enough prior context to compact.");let y=r.host.buildSummaryMessages({serializedHistory:h.text,fileLedger:f}),S=Date.now(),R=(await r.host.streamSummary({model:r.model,messages:y,signal:r.signal})).trim(),z=Date.now()-S;if(!R)throw new Error("Compaction summary was empty.");let m=r.host.estimateProjection({events:t,preservedEvents:o,summary:R}),g=r.host.createMetrics({sourceEvents:t.length,summarizedEvents:n.length,preservedEvents:o.length,sourceRecords:h.sourceRecordCount,includedRecords:h.includedRecordCount,omittedRecords:h.omittedRecordCount,preservedRecords:p.length,truncatedRecords:h.truncatedRecordCount,summaryInputTruncated:h.inputTruncated,sourceSelectionStrategy:h.selectionStrategy,summaryInputChars:h.inputChars,retainedTailTokens:i.retainedTailTokens,retainedTailBudgetTokens:i.retainedTailBudgetTokens,finalProviderContextTokens:m.inputTokensAfter,durationMs:z,fileLedgerEntries:f.length,splitTurnId:i.splitTurnId});return{summary:R,model:r.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:r.host.lastTurnId(t),preservedFromEventId:o[0]?.id??null,preservedEventIds:l,preservedResourceRefs:r.host.durableResourceRefs(r.events),sourceEventCount:n.length,preservedEventCount:o.length,fileLedger:f,inputTokensBefore:m.inputTokensBefore,inputTokensAfter:m.inputTokensAfter,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic",metrics:g}}a(Be,"runAgentCompactionProgram");var be=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),fe=e.object({sequence:e.number().int().nonnegative(),name:be,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function Le(r){return w(fe.parse(r))}a(Le,"canonicalEventHash");var T="2026-09-20",Ke=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],U=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),J=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),O=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),N=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),Ge=e.union([U,J,O,N]),ge=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),C=class{static{a(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let i=J.safeParse(t);if(i.success&&!("id"in t)){if(i.data.method==="initialized"){if(!this.#t)throw new x(-32002,"initialize must be called first");this.#r=!0}return null}let n=U.safeParse(t);if(!n.success)return M(null,-32600,"Invalid Request",n.error.flatten());let o=n.data;try{let l=await this.#n(o.method,o.params);return{jsonrpc:"2.0",id:o.id,result:l}}catch(l){let u=l instanceof x?l:new x(-32603,l instanceof Error?l.message:String(l));return M(o.id,u.code,u.message,u.data)}}async#n(t,i){if(t==="initialize"){let n=ge.parse(i);if(n.protocolVersion!==T)throw new x(-32001,"Incompatible agent protocol version",{requested:n.protocolVersion,supported:T});return this.#t=n,{protocolVersion:T,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new x(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(i);case"thread/start":return this.#e.threadStart(i);case"thread/resume":return this.#e.threadResume(i);case"thread/read":return this.#e.threadRead(i);case"turn/start":return this.#e.turnStart(i);case"turn/steer":return this.#e.turnSteer(i);case"task/inbox":return this.#e.taskInbox(i);case"task/queue":return this.#e.taskQueue(i);case"task/inputUpdate":return this.#e.taskInputUpdate(i);case"turn/interrupt":return this.#e.turnInterrupt(i);case"approval/resolve":return this.#e.approvalResolve(i);case"userInput/resolve":return this.#e.userInputResolve(i);case"profile/workflows":return this.#e.profileWorkflows(i);case"profile/evaluations":return this.#e.profileEvaluations(i);case"profile/trainingSource":return this.#e.profileTrainingSource(i);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(i);case"profile/evaluations/run":return this.#e.profileEvaluationRun(i);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(i);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(i);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(i);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(i);case"profile/evaluations/report":return this.#e.profileEvaluationReport(i);case"harness/inspect":return this.#e.harnessInspect(i);case"harness/proposalReview":return this.#e.harnessProposalReview(i);case"harness/review":return this.#e.harnessReview(i);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(i);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(i);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(i);case"harness/validate":return this.#e.harnessValidate(i);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(i);case"harness/diff":return this.#e.harnessDiff(i);case"harness/rollback":return this.#e.harnessRollback(i);case"refiner/inspect":return this.#e.refinerInspect(i);case"refiner/update":return this.#e.refinerUpdate(i);case"refiner/activate":return this.#e.refinerActivate(i);case"refiner/rollback":return this.#e.refinerRollback(i);default:throw new x(-32601,`Method not found: ${t}`)}}},x=class extends Error{static{a(this,"JsonRpcDispatchError")}code;data;constructor(t,i,n){super(i),this.code=t,this.data=n}};function M(r,t,i,n){return{jsonrpc:"2.0",id:r,error:{code:t,message:i,...n===void 0?{}:{data:n}}}}a(M,"jsonRpcError");var L=class{static{a(this,"AgentRpcClient")}#e;#t;constructor(t){this.#e=t.request.bind(t),this.#t=t.notify.bind(t)}async initialize(t,i={}){let n=await this.#e("initialize",{protocolVersion:T,client:t,capabilities:i});return await this.#t("initialized"),n}capabilities=a((t={})=>this.#e("runtime/capabilities",t),"capabilities");threadStart=a(t=>this.#e("thread/start",t),"threadStart");threadResume=a(t=>this.#e("thread/resume",t),"threadResume");threadRead=a(t=>this.#e("thread/read",t),"threadRead");turnStart=a(t=>this.#e("turn/start",t),"turnStart");turnSteer=a(t=>this.#e("turn/steer",t),"turnSteer");taskInbox=a(t=>this.#e("task/inbox",t),"taskInbox");taskQueue=a(t=>this.#e("task/queue",t),"taskQueue");taskInputUpdate=a(t=>this.#e("task/inputUpdate",t),"taskInputUpdate");turnInterrupt=a(t=>this.#e("turn/interrupt",t),"turnInterrupt");approvalResolve=a(t=>this.#e("approval/resolve",t),"approvalResolve");userInputResolve=a(t=>this.#e("userInput/resolve",t),"userInputResolve");profileWorkflows=a(t=>this.#e("profile/workflows",t),"profileWorkflows");profileEvaluations=a(t=>this.#e("profile/evaluations",t),"profileEvaluations");profileEvaluationPrepare=a(t=>this.#e("profile/evaluations/prepare",t),"profileEvaluationPrepare");profileEvaluationRun=a(t=>this.#e("profile/evaluations/run",t),"profileEvaluationRun");profileEvaluationRunSuite=a(t=>this.#e("profile/evaluations/runSuite",t),"profileEvaluationRunSuite");profileEvaluationExecuteCase=a(t=>this.#e("profile/evaluations/executeCase",t),"profileEvaluationExecuteCase");profileEvaluationExecuteRun=a(t=>this.#e("profile/evaluations/executeRun",t),"profileEvaluationExecuteRun");profileEvaluationCompare=a(t=>this.#e("profile/evaluations/compare",t),"profileEvaluationCompare");harnessInspect=a((t={})=>this.#e("harness/inspect",t),"harnessInspect");harnessProposalReview=a((t={})=>this.#e("harness/proposalReview",t),"harnessProposalReview");harnessReview=a((t={})=>this.#e("harness/review",t),"harnessReview");harnessAcceptEvaluationReview=a((t={})=>this.#e("harness/acceptEvaluationReview",t),"harnessAcceptEvaluationReview");harnessMaterializeEvaluationTaskset=a((t={})=>this.#e("harness/materializeEvaluationTaskset",t),"harnessMaterializeEvaluationTaskset");harnessRunEvaluationBaseline=a((t={})=>this.#e("harness/runEvaluationBaseline",t),"harnessRunEvaluationBaseline");harnessValidate=a((t={})=>this.#e("harness/validate",t),"harnessValidate");harnessBackgroundReview=a((t={})=>this.#e("harness/backgroundReview",t),"harnessBackgroundReview");harnessDiff=a((t={})=>this.#e("harness/diff",t),"harnessDiff");harnessRollback=a((t={})=>this.#e("harness/rollback",t),"harnessRollback");refinerInspect=a(t=>this.#e("refiner/inspect",t),"refinerInspect");refinerUpdate=a(t=>this.#e("refiner/update",t),"refinerUpdate");refinerActivate=a(t=>this.#e("refiner/activate",t),"refinerActivate");refinerRollback=a(t=>this.#e("refiner/rollback",t),"refinerRollback")};var c=e.string().trim().min(1).max(200),A=e.string().trim().min(1).max(32e3),E=e.number().int().nonnegative(),D=e.object({id:c,sessionId:c,senderSessionId:c.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:A,payload:e.record(e.string(),e.unknown()),idempotencyKey:c,replyTo:c.nullable(),expectedTurnId:c.nullable()}).strict(),ve=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:A}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:c}).strict()]),F=e.object({id:c,sessionId:c,turnId:c,targetSessionId:c.nullable(),targetTurnId:c.nullable(),targetInputId:c.nullable(),afterSequence:E,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),W=e.record(e.string(),e.unknown()),Ie=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),we=e.object({parentSessionId:c.nullable().optional(),childSessionId:c.nullable().optional(),status:e.array(Ie).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),K=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:c}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:c}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:c}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:c,afterSequence:E}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:c,turnId:c,ownerId:c,areas:e.array(A).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:c}).strict(),e.object({action:e.literal("admitTaskInput"),input:D}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(D).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:c,error:A}).strict(),e.object({action:e.literal("getTaskInput"),id:c}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:c,query:e.object({afterSequence:E.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:c,inputId:c,change:ve}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:c,turnId:c,afterSequence:E}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:c,afterSequence:E}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:c,turnId:c,ownerId:c,requestId:c}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:c,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:c}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:F}).strict(),e.object({action:e.literal("settleTaskWait"),id:c,state:F.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:c,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:W,turnId:c}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:c,inputId:c}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:W}).strict(),e.object({action:e.literal("getSubagentRun"),id:c}).strict(),e.object({action:e.literal("listSubagentRuns"),query:we}).strict()]);var q=e.string().trim().min(1).max(191),G=e.object({createdAt:e.string().min(1),id:q}).strict(),Q=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),X=e.discriminatedUnion("action",[e.object({action:e.literal("active_release"),workspaceId:q}).strict(),e.object({action:e.literal("put_artifact"),workspaceId:q,kind:Q,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:q,kind:Q,before:G.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:q,before:G.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var b=e.string().trim().min(1).max(240),Y=e.string().regex(/^[a-f0-9]{64}$/),Z=e.enum(["run_overlay","observation","trigger_decision","route_decision","proposal","targeted_validation","apply_receipt","refiner_outcome"]),ee=e.object({createdAt:e.string().datetime(),id:b}).strict(),te=e.discriminatedUnion("action",[e.object({action:e.literal("artifact_put"),workspaceId:b,kind:Z,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:b,kind:Z,before:ee.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("pending_page"),workspaceId:b,before:ee.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("workspace_get"),workspaceId:b}).strict(),e.object({action:e.literal("background_get"),workspaceId:b}).strict(),e.object({action:e.literal("overlay_get"),runId:b}).strict(),e.object({action:e.literal("overlay_freeze"),runId:b,expectedRevision:e.number().int().nonnegative(),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("memory_get"),workspaceId:b,sessionId:b,key:b}).strict(),e.object({action:e.literal("memory_page"),workspaceId:b,sessionId:b,before:e.object({updatedAt:e.string().datetime(),key:b}).strict().nullable(),limit:e.number().int().min(1).max(20),includeDeleted:e.boolean()}).strict(),e.object({action:e.literal("memory_write"),sessionId:b,input:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("release_get"),contentHash:Y}).strict(),e.object({action:e.literal("release_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("session_get"),sessionId:b}).strict(),e.object({action:e.literal("turn_get"),turnId:b}).strict(),e.object({action:e.literal("turn_page"),sessionId:b,before:e.number().int().positive().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_page"),turnId:b,afterSequence:e.number().int().nonnegative(),names:e.array(b).max(40),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_append"),event:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("usage_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("snapshot_restore"),turnId:b,expectedHash:Y,snapshot:e.record(e.string(),e.unknown())}).strict()]);var v=e.string().trim().min(1).max(200),re=e.string().regex(/^[a-f0-9]{64}$/),xe=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),ne=e.object({id:v,title:e.string().trim().min(1).max(240),sourceTaskId:v,sourceTurnId:v,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:re,validation:e.array(xe).max(32)}).strict(),ae=e.object({sessionId:v,turnId:v,output:ne}).strict(),ie=e.object({uploadId:v,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:re,contentsBase64:e.string().min(1).max(131072)}).strict(),se=e.object({uploadId:v}).strict(),ke=ne.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),oe=e.object({sessionId:v,turnId:v,output:ke,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var _=e.string().trim().min(1).max(200),je=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:_.optional(),payload:e.unknown().optional(),processId:_.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((r,t)=>{r.type!=="create"&&!r.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),r.type==="create"&&r.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),r.type==="process_get"&&!r.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),ce=e.object({action:je}).strict(),le=e.object({sessionId:_,turnId:_,name:_}).strict();var d=1,s=e.string().trim().min(1).max(191),k=e.number().int().min(1).max(200),gt=e.object({teamId:s,ownerUserId:s,workspaceId:s,conversationId:s,turnId:s,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),ue=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("sandbox/request"),params:ce}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("embedding/authorize"),params:le}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("output/begin"),params:ae}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("output/chunk"),params:ie}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("output/complete"),params:se}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("output/saveSandboxFile"),params:oe}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/overlay/get"),params:e.object({runId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/overlay/put"),params:e.object({runId:s,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:s,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:s,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:s,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:k}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:s,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/state/read"),params:e.object({workspaceId:s,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:s.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("profile-evaluations/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),kind:e.enum(["grade","receipt","run","comparison","suite"]),id:s}).strict(),e.object({action:e.literal("page"),kind:e.enum(["grade","receipt","run","comparison","suite"]),profileKey:e.string().regex(/^[a-f0-9]{64}$/),before:e.object({createdAt:e.string(),id:s}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("put"),kind:e.enum(["grade","receipt","run","comparison","suite"]),payload:e.record(e.string(),e.unknown()),profileKey:e.string().regex(/^[a-f0-9]{64}$/).nullable(),createdAt:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:s,workspaceId:s,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:s,workspaceId:s,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:s,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:s,workspaceId:s,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("task-inbox/execute"),params:K}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("harness/review/execute"),params:te}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("refiner/execute"),params:e.object({action:X}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:s}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:s.nullable(),targetKind:s.nullable(),targetId:s.nullable(),state:e.array(s).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:s}).strict().nullable(),limit:k}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("approval/get"),params:e.object({approvalId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:s.optional(),turnId:s.optional(),provider:s.optional(),model:s.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:s}).strict().nullable(),limit:k}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("session/get"),params:e.object({sessionId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("session/page"),params:e.object({afterId:s.nullable(),limit:k}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("session/put"),params:e.object({sessionId:s,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/count"),params:e.object({sessionId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:s,key:e.enum(["messageId","fromRunId"]),value:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/get"),params:e.object({turnId:s}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/put"),params:e.object({sessionId:s,turnId:s,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/latest"),params:e.object({sessionId:s,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("turn/page"),params:e.object({sessionId:s,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:k}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("thread/turnPage"),params:e.object({sessionId:s,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:k}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("events/page"),params:e.object({sessionId:s.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:k,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(d),requestId:s,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:s}).strict()}).strict()]),vt=e.object({contractVersion:e.literal(d),operations:e.array(e.enum(["sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","profile-evaluations/execute","harness/review/execute","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(48),allowedTools:e.array(s).max(128),maxPageSize:k,maxRequestBytes:e.number().int().min(1).max(1e6),maxInFlight:e.number().int().min(1).max(64)}).strict();var de=class{static{a(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,i=15e3){let n=ue.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let o=`host-storage:${this.#r++}`,l={jsonrpc:"2.0",id:o,method:"host/storage",params:n};if(Buffer.byteLength(JSON.stringify(l))>256e3)throw new Error("Host storage request is too large.");let u=new Promise((p,f)=>{let h=n.operation==="sandbox/request"?3e5:6e4,y=setTimeout(()=>{this.#e.delete(o),f(new Error("Host storage request timed out."))},Math.max(1,Math.min(h,i)));this.#e.set(o,{resolve:p,reject:f,timer:y})});try{await this.#t(l)}catch(p){let f=this.#e.get(o);f&&(clearTimeout(f.timer),this.#e.delete(o),f.reject(p instanceof Error?p:new Error(String(p))))}return u}accept(t){let i=O.safeParse(t),n=i.success?null:N.safeParse(t),o=i.success?i.data:n?.success?n.data:null;if(!o||typeof o.id!="string"||!o.id.startsWith("host-storage:"))return!1;let l=this.#e.get(o.id);return l?(clearTimeout(l.timer),this.#e.delete(o.id),Buffer.byteLength(JSON.stringify(o))>1e6?(l.reject(new Error("Host storage response is too large.")),!0):("error"in o?l.reject(new Error(`Host storage request failed: ${o.error.message}`)):l.resolve(o.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{once as ye}from"node:events";import{createInterface as Re}from"node:readline";async function Tt(r){let t=null,i=Promise.resolve(),n=[],o=a(m=>(i=i.then(async()=>{r.writable.write(`${JSON.stringify(m)}
|
|
3
|
+
`)||await ye(r.writable,"drain")}),i),"write");r.hostStorageClient?.bind(m=>o(m));let l=a(()=>{if(!(!t?.initialized||n.length===0))for(let m of n.splice(0))o(m)},"flushPendingNotifications"),u,p=new Set,f=Re({input:r.readable,crlfDelay:1/0}),h=[],y=!1,S=null,R=a(async m=>{let g=t;if(!g)throw new Error("Agent runtime dispatcher is unavailable.");let I=(async()=>{let $=await g.handle(m);$&&await o($),l()})(),B=m&&typeof m=="object"&&"method"in m?m.method:null;if(B==="initialize"||B==="initialized"){await I;return}p.add(I),I.finally(()=>p.delete(I))},"dispatch"),z=(async()=>{let m=typeof r.host=="function"?await r.host():r.host;for(t=new C(m),u=m.subscribe?.(g=>{if(!t?.initialized){n.push(g);return}o(g)});h.length>0;)await R(h.shift());y=!0})().catch(m=>{S=m,f.close()});try{for await(let m of f){if(!m.trim())continue;if(Buffer.byteLength(m,"utf8")>1e6){await o({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let g;try{g=JSON.parse(m)}catch{await o({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!r.hostStorageClient?.accept(g))if(y)await R(g);else if(h.length>=64){let I=g&&typeof g=="object"&&"id"in g?g.id:null;(typeof I=="string"||typeof I=="number")&&await o({jsonrpc:"2.0",id:I,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else h.push(g)}if(await z,S)throw S;await Promise.all(p),await i}finally{r.hostStorageClient?.close(),u?.()}}a(Tt,"runAgentJsonlServer");var H=e.object({threadId:e.string().trim().min(1)}).passthrough(),Se=H.extend({includeHistory:e.boolean().optional()}),Te=e.object({session:e.unknown()}).strict(),P=H.extend({input:e.unknown()}),Ee=P.extend({idempotencyKey:e.string().trim().min(1).max(200)}),qe=P.extend({inputId:e.string().trim().min(1)}),_e=H.extend({reason:e.string().trim().min(1).optional()}),Pe=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function Vt(r){let t=a(async(n,o,l)=>{let u=performance.now();r.telemetry?.({method:n,phase:"started",threadId:o,durationMs:null,errorClass:null});try{let p=await l();return r.telemetry?.({method:n,phase:"completed",threadId:o,durationMs:performance.now()-u,errorClass:null}),p}catch(p){throw r.telemetry?.({method:n,phase:"failed",threadId:o,durationMs:performance.now()-u,errorClass:p instanceof Error?p.name:"UnknownError"}),p}},"run"),i=a(async(n,o="thread/read")=>{let{threadId:l,includeHistory:u}=Se.parse(n);return t(o,l,async()=>{if(u===!1)return{thread:await r.readThread(l),turns:[],events:[]};let[p,f,h]=await Promise.all([r.readThread(l),r.listTurns(l),r.listEvents(l)]);return{thread:p,turns:f,events:h}})},"threadRead");return{capabilities:a(n=>t("runtime/capabilities",null,()=>r.capabilities(n)),"capabilities"),threadStart:a(async n=>t("thread/start",null,async()=>({thread:await r.createThread(Te.parse(n).session)})),"threadStart"),threadResume:a(n=>i(n,"thread/resume"),"threadResume"),threadRead:i,turnStart:a(async n=>{let o=P.parse(n);return t("turn/start",o.threadId,async()=>({turn:await r.startTurn(o.threadId,o.input)}))},"turnStart"),turnSteer:a(async n=>{let o=P.parse(n);return t("turn/steer",o.threadId,async()=>({receipt:await r.steerTurn(o.threadId,o.input)}))},"turnSteer"),taskInbox:a(async n=>{let{threadId:o}=H.parse(n);return t("task/inbox",o,()=>r.readTaskInbox(o))},"taskInbox"),taskQueue:a(async n=>{let o=Ee.parse(n);return t("task/queue",o.threadId,()=>r.queueTaskInput(o.threadId,o.input,o.idempotencyKey))},"taskQueue"),taskInputUpdate:a(async n=>{let o=qe.parse(n);return t("task/inputUpdate",o.threadId,()=>r.updateTaskInput(o.threadId,o.inputId,o.input))},"taskInputUpdate"),turnInterrupt:a(async n=>{let o=_e.parse(n);return t("turn/interrupt",o.threadId,async()=>({turn:await r.interruptTurn(o.threadId,o.reason)}))},"turnInterrupt"),approvalResolve:a(async n=>{let o=Pe.parse(n);return t("approval/resolve",null,async()=>({approval:await r.resolveApproval(o.approvalId,o.input)}))},"approvalResolve"),userInputResolve:a(async n=>{let o=P.parse(n);return t("userInput/resolve",o.threadId,async()=>(r.isTurnActive(o.threadId)&&await r.waitForTurnSettlement(o.threadId),{turn:await r.startTurn(o.threadId,o.input)}))},"userInputResolve"),profileWorkflows:a(()=>t("profile/workflows",null,()=>r.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:a(n=>t("profile/evaluations",null,()=>r.listProfileEvaluations(n)),"profileEvaluations"),profileTrainingSource:a(()=>t("profile/trainingSource",null,()=>r.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:a(n=>t("profile/evaluations/prepare",null,()=>r.prepareProfileEvaluationRun(n)),"profileEvaluationPrepare"),profileEvaluationRun:a(n=>t("profile/evaluations/run",null,()=>r.runPreparedProfileEvaluation(n)),"profileEvaluationRun"),profileEvaluationRunSuite:a(n=>t("profile/evaluations/runSuite",null,()=>r.runProfileEvaluationSuite(n)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:a(n=>t("profile/evaluations/executeCase",null,()=>r.executeProfileEvaluationCase(n)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:a(n=>t("profile/evaluations/executeRun",null,()=>r.executeProfileEvaluationRun(n)),"profileEvaluationExecuteRun"),profileEvaluationCompare:a(n=>t("profile/evaluations/compare",null,()=>r.compareProfileEvaluationRuns(n)),"profileEvaluationCompare"),profileEvaluationReport:a(n=>t("profile/evaluations/report",null,()=>r.buildProfileEvaluationReport(n)),"profileEvaluationReport"),harnessInspect:a(()=>t("harness/inspect",null,()=>r.inspectHarness()),"harnessInspect"),harnessProposalReview:a(n=>t("harness/proposalReview",null,()=>r.reviewHarnessProposal(n)),"harnessProposalReview"),harnessReview:a(n=>t("harness/review",null,()=>r.reviewHarness(n)),"harnessReview"),harnessAcceptEvaluationReview:a(n=>t("harness/acceptEvaluationReview",null,()=>r.acceptHarnessEvaluationReview(n)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:a(n=>t("harness/materializeEvaluationTaskset",null,()=>r.materializeHarnessEvaluationTaskset(n)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:a(n=>t("harness/runEvaluationBaseline",null,()=>r.runHarnessEvaluationBaseline(n)),"harnessRunEvaluationBaseline"),harnessValidate:a(()=>t("harness/validate",null,()=>r.validateHarness()),"harnessValidate"),harnessBackgroundReview:a(n=>t("harness/backgroundReview",null,()=>r.updateHarnessBackgroundReview(n)),"harnessBackgroundReview"),harnessDiff:a(n=>t("harness/diff",null,()=>r.diffHarness(n)),"harnessDiff"),harnessRollback:a(n=>t("harness/rollback",null,()=>r.rollbackHarness(n)),"harnessRollback"),refinerInspect:a(()=>t("refiner/inspect",null,()=>r.inspectRefiner()),"refinerInspect"),refinerUpdate:a(n=>t("refiner/update",null,()=>r.updateRefiner(n)),"refinerUpdate"),refinerActivate:a(n=>t("refiner/activate",null,()=>r.activateRefiner(n)),"refinerActivate"),refinerRollback:a(n=>t("refiner/rollback",null,()=>r.rollbackRefiner(n)),"refinerRollback"),subscribe:r.subscribeEvents&&r.eventNotification?n=>r.subscribeEvents(o=>n(r.eventNotification(o))):void 0}}a(Vt,"createAgentRuntimeService");var j=e.string().regex(/^[a-f0-9]{64}$/),Ce=e.object({harnessReleaseHash:j,instructionsHash:j,skillHashes:e.record(e.string(),j),agentAssetHashes:e.record(e.string(),j),toolCatalogHash:j,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Ae=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:j,toolCatalogHash:j,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function Mt(r){return w(Ce.parse(r))}a(Mt,"effectiveSurfaceHash");function Ut(r){return w(Ae.parse(r))}a(Ut,"checkpointHash");function Jt(r){return[r.system,...r.harnessInstructions,...r.skillInstructions,...r.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`)}a(Jt,"materializeAgentPrompt");function Kt(r){let t=new Map;for(let u of r){let p=u.name.trim();if(!p)throw new Error("Agent tool names cannot be empty.");if(t.has(p))throw new Error(`Duplicate agent tool: ${p}.`);if(!u.unavailableReason&&!u.execute)throw new Error(`Agent tool ${p} is declared as available without an executor.`);t.set(p,{...u,name:p})}let i=[...t.values()].sort((u,p)=>u.name.localeCompare(p.name)),n=i.filter(u=>!u.unavailableReason).map(u=>({name:u.name,description:u.description,inputSchema:e.toJSONSchema(u.inputSchema,{target:"draft-7",unrepresentable:"any"})})),o=i.map(u=>({name:u.name,displayLabel:u.displayLabel??u.name,placement:u.placement,available:!u.unavailableReason,unavailableReason:u.unavailableReason??null})),l=w({modelTools:n,capabilities:o});return{byName:t,tools:i,modelTools:n,capabilities:o,hash:l}}a(Kt,"createAgentToolCatalog");async function Gt(r,t){let i=r.byName.get(t.name);if(!i)throw new Error(`Unknown agent tool: ${t.name}.`);if(i.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${i.unavailableReason}`);if(!i.execute)throw new Error(`Agent tool ${t.name} has no executor.`);return i.execute(i.inputSchema.parse(t.arguments),t.context)}a(Gt,"executeAgentTool");function Qt(r){let t=new Set,i=[...r].map(l=>{let u=l.name.trim();if(!u)throw new Error("Agent tool names cannot be empty.");if(t.has(u))throw new Error(`Duplicate agent tool: ${u}.`);if(t.add(u),!l.unavailableReason&&!l.executorAvailable)throw new Error(`Agent tool ${u} is declared as available without an executor.`);return{...l,name:u}}).sort((l,u)=>l.name.localeCompare(u.name)),n=i.filter(l=>!l.unavailableReason).map(l=>({name:l.name,description:l.description,inputSchema:l.inputSchema})),o=i.map(l=>({name:l.name,displayLabel:l.displayLabel??l.name,placement:l.placement,available:!l.unavailableReason,unavailableReason:l.unavailableReason??null}));return{byName:new Map(i.map(l=>[l.name,l])),tools:i,modelTools:n,capabilities:o,hash:w({modelTools:n,capabilities:o})}}a(Qt,"createAgentToolCatalogProjection");async function Xt(r,t){let i=r.byName.get(t.name);if(!i)throw new Error(`Unknown agent tool: ${t.name}.`);if(i.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${i.unavailableReason}`);if(!i.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let n=i.validateArguments?i.validateArguments(t.arguments):t.arguments;return i.execute(n,t.context)}a(Xt,"executeProjectedAgentTool");var pe=class{static{a(this,"TaskSignals")}#e=new Map;notify(t){for(let i of[...this.#e.get(t)??[]])i()}subscribe(t,i){let n=this.#e.get(t);return n||this.#e.set(t,n=new Set),n.add(i),()=>{n.delete(i),n.size===0&&this.#e.delete(t)}}async wait(t){let i=a(()=>{},"wake"),n=0,o=a(()=>{n+=1,i()},"changed"),l=[...new Set(t.taskIds)].map(p=>this.subscribe(p,o)),u=setTimeout(o,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",o);try{for(;;){t.signal.throwIfAborted();let p=n,f=await t.read();if(f!==null)return f;if(Date.now()>=t.deadline)return null;n===p&&await new Promise(h=>{i=h,(n!==p||t.signal.aborted)&&h()})}}finally{clearTimeout(u),t.signal.removeEventListener("abort",o);for(let p of l)p()}}},me=class{static{a(this,"TaskSerialExecutor")}#e=new Map;async run(t,i){let o=(this.#e.get(t)??Promise.resolve()).then(i),l=o.then(()=>{},()=>{});this.#e.set(t,l);try{return await o}finally{this.#e.get(t)===l&&this.#e.delete(t)}}};export{V as a,w as b,Oe as c,Ne as d,Be as e,be as f,fe as g,Le as h,T as i,Ke as j,U as k,J as l,O as m,N as n,Ge as o,ge as p,C as q,L as r,K as s,X as t,te as u,ne as v,ae as w,ie as x,se as y,ke as z,oe as A,je as B,ce as C,le as D,d as E,gt as F,ue as G,vt as H,de as I,Tt as J,Vt as K,Ce as L,Ae as M,Mt as N,Ut as O,Jt as P,Kt as Q,Gt as R,Qt as S,Xt as T,pe as U,me as V};
|