openpond 0.2.50 → 0.2.52
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.js +1 -1
- package/dist/chunks/{app-server-runtime-OG7GYIIA.js → app-server-runtime-NITNSHYS.js} +1 -1
- package/dist/chunks/{chunk-42GOV5ZU.js → chunk-AV3WI7JZ.js} +1 -1
- package/dist/chunks/{chunk-OC6UWKBL.js → chunk-CFLMKFOE.js} +1 -1
- package/dist/chunks/{chunk-UBFRWC6I.js → chunk-FQZFLNLY.js} +1 -1
- package/dist/chunks/{chunk-JCCU3VFK.js → chunk-HJEY5LBD.js} +1 -1
- package/dist/chunks/{chunk-TBNBCOW7.js → chunk-L3V4QKRV.js} +1 -1
- package/dist/chunks/chunk-PVSUQGWK.js +9 -0
- package/dist/chunks/{chunk-ZCWHVLJ4.js → chunk-T5T7NCHJ.js} +1 -1
- package/dist/chunks/{chunk-2ZJJFBIA.js → chunk-USMZT5FZ.js} +12 -12
- package/dist/chunks/{chunk-V67DJQQ3.js → chunk-XC7AHL57.js} +114 -113
- package/dist/chunks/{chunk-O7VGFMDO.js → chunk-ZBZBV5TB.js} +1 -1
- package/dist/chunks/{cli-ZLDLOKPL.js → cli-ZYFSCHZK.js} +1 -1
- package/dist/chunks/{dist-BLBZENVB.js → dist-5VFPYEIV.js} +1 -1
- package/dist/chunks/{hosted-experiment-improvement-NTYYSPQX.js → hosted-experiment-improvement-MGBPXXW2.js} +1 -1
- package/dist/chunks/{hosted-harness-runtime-FZZLWLBR.js → hosted-harness-runtime-WOLADXXP.js} +1 -1
- package/dist/chunks/{hosted-profile-compiler-JODGZCA7.js → hosted-profile-compiler-NBMUCZVS.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-preparation-F2SPAEKK.js → hosted-profile-evaluation-preparation-I6H6RFT6.js} +1 -1
- package/dist/chunks/{src-4RLFNNVK.js → src-MGP3OYHL.js} +115 -115
- package/dist/chunks/{workspaces-XIQNPAP7.js → workspaces-MFZ3OO6O.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/web/assets/App-Dg6mZIQk.js +234 -0
- package/dist/web/assets/{AppDialog-1iGodoot.js → AppDialog-gcj3rrTZ.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-udtBdWFn.js → AppTerminalPanel-Be-E4qZF.js} +2 -2
- package/dist/web/assets/{AppsView-DhKsU4yi.js → AppsView-BdyPNSpT.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-BnOyqIQT.js → BrowserSidebar-CcQxU0uO.js} +1 -1
- package/dist/web/assets/{CartesianChart-C24DAywn.js → CartesianChart-CN5hB6rV.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-DgmOF5Fe.js → CollaborationTabs-BiDPHgXG.js} +1 -1
- package/dist/web/assets/{CommandMenu-CUNGtHwS.js → CommandMenu-B2qJCgWH.js} +1 -1
- package/dist/web/assets/{CommunityView-CE7qeJnr.js → CommunityView-D1aOQKfS.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-BixNsg2a.js → ComposerCreateImproveStrip-f1tdD0QS.js} +1 -1
- package/dist/web/assets/{GetStartedView-B8gCwmBX.js → GetStartedView-CPYs0fYN.js} +1 -1
- package/dist/web/assets/{HostedModelLearningReview-CitgUNfC.js → HostedModelLearningReview-DVfJyUW_.js} +1 -1
- package/dist/web/assets/{HostedModelLearningSettings-WUaqzNsa.js → HostedModelLearningSettings-IEKRXOkG.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-Cx0kL69J.js → LabModelVersionDetailPage-DkIa0oG_.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-DRggqZ1j.js → LabSkillSidebar-BUlU1Ti-.js} +1 -1
- package/dist/web/assets/{LabsRoute-BujTZhqC.js → LabsRoute-8cKFNq19.js} +4 -4
- package/dist/web/assets/{MainChatThread-CyA_644R.js → MainChatThread-C5GwaIl_.js} +2 -2
- package/dist/web/assets/MainPane-SMqq5YAM.js +19 -0
- package/dist/web/assets/{MarkdownText-DJI5LwT0.js → MarkdownText-CLnvdLVg.js} +21 -21
- package/dist/web/assets/{NativeSkillSidebar-CkFpWxjd.js → NativeSkillSidebar-B9bVb00x.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-DXcRHHsu.js → NewExperienceSwitcher-CelgG7Ua.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-gDzX_ZIJ.js → NewProjectDialog-eEnsg9s2.js} +1 -1
- package/dist/web/assets/{OutputsPage-J_k-_N82.js → OutputsPage-ByvsTUW-.js} +1 -1
- package/dist/web/assets/{ProjectsPage-BsyZmvlg.js → ProjectsPage-Cl2zFh8X.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-Bz8puMUB.js → RightChatPanelStack-MnGscF87.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-DmorYb6p.js → RightSidebarHomePanel-C6NXMYuy.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-BFDzQUyL.js → ScheduledWorkPage-DCb6d7Lg.js} +1 -1
- package/dist/web/assets/{SettingsView-BB7wCdbr.js → SettingsView-BMFfrxmo.js} +3 -3
- package/dist/web/assets/{TeamChatView-CZ3b7rq2.js → TeamChatView-DW_v2B9E.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-Ck43Qri3.js → TerminalOverlay-BJ7qsr9F.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-ejqPZm3g.js → TrainingCreationPanel-GSIwP6f1.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Cy2AQxxL.js → TrainingDraftPanel-DorY6I29.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-B7nyMItm.js → UsageSettingsSection-DmzStI9q.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-BfjAc097.js → WorkSidebarPanel-zsJrGaaL.js} +1 -1
- package/dist/web/assets/WorkspaceDiffPanel-CiFsZjMm.js +14 -0
- package/dist/web/assets/{WorkspaceEnvironmentMenu-B-K9XgFB.js → WorkspaceEnvironmentMenu-vJw9hE0y.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-BJVFx_L3.js → WorkspaceGitDialogs-BpL-xtRX.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-p-FWMXoZ.js → WorkspaceMonacoEditor-CJ3x0GHH.js} +3 -3
- package/dist/web/assets/{arrow-up-right-CFGI2YSt.js → arrow-up-right-C60QSULo.js} +1 -1
- package/dist/web/assets/{chunk-UHVJOMWN-BAlur2vw.js → chunk-UHVJOMWN-BxgPi0yP.js} +1 -1
- package/dist/web/assets/{clipboard-DIIxBort.js → clipboard-QIy0Jd_K.js} +1 -1
- package/dist/web/assets/{cloud-upload-BaQFNCTp.js → cloud-upload-B9L-_gy0.js} +1 -1
- package/dist/web/assets/{cssMode-6LOkSggB.js → cssMode-ffPyPUW9.js} +1 -1
- package/dist/web/assets/{folder-open-DZSxfPtr.js → folder-open-BFy7KXWm.js} +1 -1
- package/dist/web/assets/{folder-plus-21v4D_Vx.js → folder-plus-C3iGtUOI.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CgGixL64.js → git-commit-horizontal-DsTniKvi.js} +1 -1
- package/dist/web/assets/{htmlMode-B5uRraNd.js → htmlMode-7ytlsiyK.js} +1 -1
- package/dist/web/assets/{index-DOMrqhcz.js → index-BK8GmZmB.js} +2 -2
- package/dist/web/assets/index-C0H85uUI.css +1 -0
- package/dist/web/assets/{info-BGTcmow7.js → info-C8mwoaIJ.js} +1 -1
- package/dist/web/assets/{jsonMode-D3m8N4Gi.js → jsonMode-BT35NJi4.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-DoyipLsB.js → lspLanguageFeatures-BKAwIewO.js} +1 -1
- package/dist/web/assets/{minimize-2-B01qSko4.js → minimize-2-34MApatV.js} +1 -1
- package/dist/web/assets/{monaco.contribution-BJyfaGX2.js → monaco.contribution-9diduNNi.js} +2 -2
- package/dist/web/assets/{monaco.contribution-Bc22foTx.js → monaco.contribution-CxtX0z-m.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DuRhJ6zU.js → monaco.contribution-DVnPUDsR.js} +2 -2
- package/dist/web/assets/{monaco.contribution--U8v3jpa.js → monaco.contribution-Dj4R5U8Z.js} +2 -2
- package/dist/web/assets/{monitor-eZP8ZTHe.js → monitor-4JxqJ7wz.js} +1 -1
- package/dist/web/assets/{play-CGsWFR_B.js → play-C4PtpamL.js} +1 -1
- package/dist/web/assets/{python-BNrLZWud.js → python-0GVncePC.js} +1 -1
- package/dist/web/assets/{save-BLgjrccP.js → save-DjB16eou.js} +1 -1
- package/dist/web/assets/{square-CI1qNtvE.js → square-Coz7UQqd.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-B_GcTCnw.js → toggleHighContrast-D-3108_3.js} +1 -1
- package/dist/web/assets/{tsMode-CmruH_ys.js → tsMode-CV4ktqqR.js} +1 -1
- package/dist/web/assets/{upload-DnlgGS2x.js → upload-D007T9Hm.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-BBhGUfK-.js → useLocalAgentSchedules-BXjFbAVS.js} +1 -1
- package/dist/web/assets/{useProviderSettings-DfhdkKdC.js → useProviderSettings-SY7mp-5B.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-BwscKl5i.js → useSessionTurnCache-Bee6zbC_.js} +1 -1
- package/dist/web/assets/{wifi-off-Dz-4EDCc.js → wifi-off-BbNZc0za.js} +1 -1
- package/dist/web/assets/{workers-Bi9u46cp.js → workers-DNQ5ne3z.js} +1 -1
- package/dist/web/assets/{yaml-DVTkiRnh.js → yaml-BfAho-gB.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-7K72KS5C.js +0 -9
- package/dist/web/assets/App-BI-uOpnP.js +0 -234
- package/dist/web/assets/MainPane-LaEtxydD.js +0 -19
- package/dist/web/assets/WorkspaceDiffPanel-D9hAV8l7.js +0 -14
- package/dist/web/assets/index-DJcUXSsN.css +0 -1
package/dist/app-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{jc as r}from"./chunks/chunk-XC7AHL57.js";import"./chunks/chunk-L3V4QKRV.js";import"./chunks/chunk-EMKZVP7Z.js";import{e as p}from"./chunks/chunk-HJEY5LBD.js";import"./chunks/chunk-ZBZBV5TB.js";import"./chunks/chunk-DLZP22WV.js";import"./chunks/chunk-T5T7NCHJ.js";import"./chunks/chunk-OE2VF6KU.js";import"./chunks/chunk-T5LE6R5S.js";import"./chunks/chunk-QJRXTIOC.js";import"./chunks/chunk-SDO4FC4Q.js";import"./chunks/chunk-IR3YJWPW.js";import{i as e}from"./chunks/chunk-PVSUQGWK.js";import"./chunks/chunk-XM26DGML.js";import"./chunks/chunk-EPY7M5XS.js";import"./chunks/chunk-7MXZJQS7.js";import"./chunks/chunk-7YR6CBNU.js";import"./chunks/chunk-USMZT5FZ.js";import"./chunks/chunk-5CMKGD43.js";import"./chunks/chunk-XEOEKFG6.js";import"./chunks/chunk-HA7EFTPF.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-7QEE4PBI.js";import"./chunks/chunk-XDMUD4FW.js";import"./chunks/chunk-IKWDL3RB.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-QRWPEW3Z.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-YL6VFJ4P.js";import"./chunks/chunk-Z3D4C7BG.js";import"./chunks/chunk-WV2APYWG.js";import"./chunks/chunk-PJM2G7SG.js";import"./chunks/chunk-SDEDAHV6.js";import"./chunks/chunk-DALJMSJG.js";import"./chunks/chunk-TGIB24K4.js";import"./chunks/chunk-NNF6KCHD.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{ic as c,jc as d}from"./chunk-XC7AHL57.js";import"./chunk-L3V4QKRV.js";import"./chunk-EMKZVP7Z.js";import{e as b}from"./chunk-HJEY5LBD.js";import"./chunk-ZBZBV5TB.js";import"./chunk-DLZP22WV.js";import"./chunk-T5T7NCHJ.js";import"./chunk-OE2VF6KU.js";import"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{i as a}from"./chunk-PVSUQGWK.js";import"./chunk-XM26DGML.js";import"./chunk-EPY7M5XS.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-USMZT5FZ.js";import"./chunk-5CMKGD43.js";import"./chunk-XEOEKFG6.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{b as Oe,c as He,e as ee,f as _e,l as Ue,m as Me,p as Ne,q as qe}from"./chunk-
|
|
2
|
+
import{b as Oe,c as He,e as ee,f as _e,l as Ue,m as Me,p as Ne,q as qe}from"./chunk-HJEY5LBD.js";import{i as Ce,o as ke,q as Ae}from"./chunk-DLZP22WV.js";import{F as b,J as Ee}from"./chunk-PVSUQGWK.js";import{a as Q,b as Pe,h as xe}from"./chunk-5CMKGD43.js";import{Cd as _,Fd as W,Gd as Te,I as H,J as Ie,M as F,N,a as $}from"./chunk-XDMUD4FW.js";import{va as oe}from"./chunk-SDEDAHV6.js";import{X as he,Y as ve,_ as Z,b as le,ba as we,c as ue,ea as be,fa as V,ja as Se,la as ye,ma as Re,p as ce,r as pe,s as de,t as me,u as ge,w as fe}from"./chunk-DALJMSJG.js";import{y as M}from"./chunk-TGIB24K4.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ie,d as B,f as ae,h as U}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{promises as re}from"node:fs";import pt from"node:os";import dt from"node:path";import{createServer as mt}from"node:http";import{randomBytes as gt}from"node:crypto";var st=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),ot=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(st).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:Se,importOnly:o.boolean().optional()})]);function De(n){let e=null;async function t(s,i){let l=U(n).config,c=null,p=null,u=null;try{c=await ue(l),u=await V(n,{projectRoot:s,accountId:i}),s||(e=u)}catch(w){p=B(w,l)}let g=u??(s?null:e);return{path:l,text:c,rawRevision:le(c),issue:p,effective:g,usingLastValid:!u&&!!g,applies:"next_turn",recoverableRevisions:await pe(n),clientState:p?null:await ye(n)}}a(t,"status");async function r(s){let i=ot.parse(s);return i.action==="validate"?{valid:!0,document:ce(i.text,U(n).config)}:(i.action==="patch"&&await fe(n,i.expectedRevision,i.operations),i.action==="replace"&&await de(n,i.expectedRevision,i.text),i.action==="restore"&&await me(n,i.revision,i.expectedRevision),i.action==="trust"&&await be(n,i.root,i.accountId,i.trusted),i.action==="client-state"?Re(n,i.owner,i.patch,i.importOnly):t())}return a(r,"mutate"),{status:t,mutate:r,schema:ge}}a(De,"createConfigurationPayloads");import{Buffer as Be}from"node:buffer";var G={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id, idempotency-key","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},it=25*1024*1024,j=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{a(this,"HttpBodyError")}};function je(n,e,t={}){for(let[s,i]of Object.entries(G))e.setHeader(s,i);let r=Ve(n.headers.origin);return r?(e.setHeader("Vary",ct(e.getHeader("Vary"))),at(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}a(je,"applyCorsHeaders");function at(n,e={}){if(n==="null")return!0;let t=Fe(n);return t?ut(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Fe(s):null).filter(s=>!!s)).has(t):!1}a(at,"isAllowedCorsOrigin");function P(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...G}),n.end(JSON.stringify(t))}a(P,"sendJson");function zt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...G}),n.end(t)}a(zt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...G}),n.end(t)}a(Yt,"sendBinary");async function te(n,e={}){let t=e.maxBytes??it,r=Ve(n.headers["content-type"]),s=[],i=0;for await(let c of n){let p=Be.from(c);if(i+=p.byteLength,i>t)throw new j(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(p)}let l=Be.concat(s).toString("utf8").trim();if(!l)return{};if(!lt(r))throw new j(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(l)}catch{throw new j(400,"invalid_json","Request body is not valid JSON.")}}a(te,"readJson");function Le(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}a(Le,"hasAuth");function Ve(n){return Array.isArray(n)?n[0]??null:n??null}a(Ve,"headerValue");function lt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}a(lt,"isJsonContentType");function Fe(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}a(Fe,"normalizeOrigin");function ut(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}a(ut,"isLoopbackOrigin");function ct(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}a(ct,"appendVaryOrigin");function $e(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
3
|
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
4
|
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
5
|
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
2
|
import{na as l,ra as c}from"./chunk-7MXZJQS7.js";import{N as n}from"./chunk-HA7EFTPF.js";import{a as t}from"./chunk-FTQLQJQV.js";import{mkdir as f}from"node:fs/promises";import p from"node:path";import a from"node:path";function d(e,o){let i=a.resolve(e),r=a.resolve(o);return r===i||r.startsWith(`${i}${a.sep}`)}t(d,"isHostedProfileSourceWithinRepo");async function u(e){if(!p.isAbsolute(e.repoPath)||!p.isAbsolute(e.outputDir)||!/^[a-f0-9]{40,64}$/.test(e.sourceRevision)||!e.workspaceId.trim()||!e.repositoryId.trim()||!e.profileId.trim())throw new Error("Hosted Profile compile request is invalid.");let o=await n({repoPath:e.repoPath,profileId:e.profileId});if(o.error||o.mode!=="local"||o.activeProfile!==e.profileId||!o.sourcePath||!d(e.repoPath,o.sourcePath))throw new Error("Hosted Profile source is unavailable.");await f(e.outputDir,{recursive:!0});let i=await l({storeDir:e.outputDir,workspaceId:e.workspaceId,name:e.profileId,profile:o,sourceRevision:e.sourceRevision,repositoryId:e.repositoryId}),r=i.harnessRelease.metadata.profile;if(!r||typeof r!="object"||r.id!==e.profileId||r.sourceRevision!==e.sourceRevision||r.repositoryId!==e.repositoryId)throw new Error("Hosted Profile release provenance is invalid.");let s=await c({storeDir:e.outputDir,workspaceId:e.workspaceId,compiled:i,createdAt:new Date().toISOString()});return{workspaceId:e.workspaceId,sourceRevision:s.sourceRevision,harnessRelease:s.harnessRelease,agentSnapshot:s.agentSnapshot,bundlePath:s.bundlePath}}t(u,"compileHostedProfileRelease");async function H(e){if(e.length!==1||e[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(e[0]))throw new Error("Hosted Profile compile argument is invalid.");let o=JSON.parse(Buffer.from(e[0],"base64url").toString("utf8")),i=await u(o);process.stdout.write(`${JSON.stringify(i)}
|
|
3
|
-
`)}t(H,"runHostedProfileCompilerCli");async function y(e){await(await import("./hosted-profile-evaluation-preparation-
|
|
3
|
+
`)}t(H,"runHostedProfileCompilerCli");async function y(e){await(await import("./hosted-profile-evaluation-preparation-I6H6RFT6.js")).runHostedProfileEvaluationCli(e)}t(y,"runHostedProfileEvaluationCli");async function k(e){await(await import("./hosted-profile-evaluation-inspection-FPCV42DD.js")).runHostedProfileInspectionCli(e)}t(k,"runHostedProfileInspectionCli");export{u as a,H as b,y as c,k as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{V as Bt,Wa as ar,ab as et,ba as _t,bb as tt,db as at,ib as nr,lb as or,mb as sr,q as Ze,v as er,x as tr}from"./chunk-
|
|
2
|
+
import{V as Bt,Wa as ar,ab as et,ba as _t,bb as tt,db as at,ib as nr,lb as or,mb as sr,q as Ze,v as er,x as tr}from"./chunk-L3V4QKRV.js";import{a as rr}from"./chunk-EMKZVP7Z.js";import{i as Ya}from"./chunk-OE2VF6KU.js";import{a as Ye}from"./chunk-T5LE6R5S.js";import{f as Za,h as He}from"./chunk-QJRXTIOC.js";import{a as We,b as Sa,c as Ha,d as Ea,e as Aa,f as xa,g as Ga,h as _e,ha as Xa,i as Ka,j as Oe,ka as Xe,pa as Qe,qa as se,ra as Qa}from"./chunk-7MXZJQS7.js";import{g as he}from"./chunk-5CMKGD43.js";import{M as Ja,q as Wa}from"./chunk-HA7EFTPF.js";import{b as Va}from"./chunk-L3KS6MOV.js";import{Ib as Na,N as Be,fc as Ua,jc as Ge,lc as F,mc as Ke,od as Mt}from"./chunk-XDMUD4FW.js";import{$ as Ct,W as Da,Y as Se,Z as Je,ga as Fa,ka as $a,ma as za}from"./chunk-IKWDL3RB.js";import{Ca as qa,Dc as La,Qa as Me,Ta as Tt,xa as ja}from"./chunk-QRWPEW3Z.js";import{E as Ia,K as Pa,N as Ta,V as Ca,X as Ma,j as ba,k as Ve,p as ya}from"./chunk-WV2APYWG.js";import{Ma as Ie,Na as Ra,W as ka}from"./chunk-PJM2G7SG.js";import{B as ma,Ca as wa,D as ua,E as pa,Ma as va,S as fa,p as Le,r as ia,s as da,sa as ha,t as ca,ta as ga,u as la}from"./chunk-SDEDAHV6.js";import{Z as Oa}from"./chunk-DALJMSJG.js";import{L as Ba}from"./chunk-TGIB24K4.js";import{h as sa,k as re,l as fe,m as v}from"./chunk-NNF6KCHD.js";import{b as M}from"./chunk-ES2ISFJC.js";import{n as _a}from"./chunk-H7IWJN7L.js";import{a as h}from"./chunk-FTQLQJQV.js";import{execFile as Wr}from"node:child_process";import{readFile as Jr}from"node:fs/promises";import{promisify as Gr}from"node:util";var Kr=5,Xr=20*1024*1024,ir=4e4,jt=Gr(Wr);function Zn(e){return async({grader:t,task:a,attempt:n})=>{let s=[],o=0,i=await Qr({store:e.store,attempt:n}),d=n.modelRef?.providerId===t.judge.providerId&&n.modelRef.modelId===t.judge.modelId?tr(n.metadata.hostedTokenPricing)??void 0:void 0,g=await e.modelText({model:t.judge,hostedTokenPricing:d,signal:new AbortController().signal,requestId:`task-judge:${n.id}:${t.id}`,onUsage:h((m,r)=>{s.push(m),typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o+=r)},"onUsage"),messages:[{role:"system",content:`Apply this rubric and return JSON only with score (0..1), passed, and feedback.
|
|
3
3
|
|
|
4
4
|
${t.rubric}`},{role:"user",content:JSON.stringify({input:a.input,expectedOutput:a.expectedOutput,output:n.output,artifactEvidence:i})}]}),f=ar(g);if(!f)throw new Error("Model judge returned invalid structured output.");return{...f,usage:s,...o>0?{costUsd:o}:{}}}}h(Zn,"createTaskAttemptModelJudge");async function Qr(e){let t=(await e.store.listTaskAttemptArtifacts({attemptId:e.attempt.id})).filter(a=>a.kind==="output_artifact").slice(0,Kr);return Promise.all(t.map(async a=>{let n={artifactId:a.id,mediaType:a.mediaType??null,sha256:a.sha256,sizeBytes:a.sizeBytes,requiredOutputPath:typeof a.metadata.requiredOutputPath=="string"?a.metadata.requiredOutputPath:null};if(a.sizeBytes>Xr)return{...n,extraction:"omitted",reason:"artifact exceeds inspection bound"};try{if(a.mediaType==="application/pdf"){let{stdout:s}=await jt("pdftotext",[a.path,"-"],{env:{...process.env,PATH:_t()},maxBuffer:8388608,timeout:15e3});return{...n,extraction:"pdf_text",content:Ot(s)}}if(Zr(a.mediaType)){let s=await en(a.path,a.mediaType);return{...n,extraction:"open_xml_text",content:Ot(s.content),structure:s.structure}}return Yr(a.mediaType)?{...n,extraction:"text",content:Ot(await Jr(a.path,"utf8"))}:{...n,extraction:"metadata_only"}}catch(s){return{...n,extraction:"unavailable",reason:s instanceof Error?s.message.slice(0,500):String(s).slice(0,500)}}}))}h(Qr,"loadTaskAttemptGraderEvidence");function Yr(e){return!!(e?.startsWith("text/")||e==="application/json"||e==="application/javascript"||e==="application/sql"||e==="application/xml"||e==="application/yaml")}h(Yr,"isTextArtifact");function Zr(e){return e==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||e==="application/vnd.openxmlformats-officedocument.presentationml.presentation"}h(Zr,"isOpenXmlArtifact");async function en(e,t){let a={env:{...process.env,PATH:_t()},maxBuffer:16777216,timeout:15e3},{stdout:n}=await jt("unzip",["-Z1",e],a),s=n.split(/\r?\n/).filter(Boolean),o=tn(s,t).slice(0,250),i=[];for(let d of o){let{stdout:g}=await jt("unzip",["-p",e,d],a),f=rn(g);f&&i.push(`[${d}]
|
|
5
5
|
${f}`)}return{content:i.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{b as H}from"./chunk-O7VGFMDO.js";import{a as L}from"./chunk-T5LE6R5S.js";import{F as g,K as N,L as B}from"./chunk-7K72KS5C.js";import{qa as _}from"./chunk-7MXZJQS7.js";import{O as x,R as V,S as F,Y as R}from"./chunk-XDMUD4FW.js";import{ta as I}from"./chunk-IKWDL3RB.js";import{Ca as b}from"./chunk-QRWPEW3Z.js";import{ma as E,na as C,oa as y}from"./chunk-PJM2G7SG.js";import{Ga as A}from"./chunk-SDEDAHV6.js";import{c as D,e as v,f as U,g as M,i as O,qa as T}from"./chunk-DALJMSJG.js";import{m as p}from"./chunk-NNF6KCHD.js";import{b as o}from"./chunk-ES2ISFJC.js";import{a as w,c as P,f as j,h as c}from"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import h from"node:path";import{AsyncLocalStorage as ee}from"node:async_hooks";import{promises as z}from"node:fs";var J=new ee;function fe(r,e=!1){let t=J.getStore();t&&(e&&(t.length=0),t.push(r))}i(fe,"onStartupFailure");async function ge(r,e){await T(r);let t;try{t=await M(h.join(c(r).runtime,"server-owner"),100)}catch(n){if(n instanceof P&&n.issue.code==="STORAGE_BUSY"){let a=await O(h.join(c(r).runtime,"endpoint.json"),()=>null);throw new P({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw n}let s=[];try{let n=await w(r,()=>J.run(s,e)),a=n.close.bind(n);s.length=0;let d;return{...n,close:i(()=>d??=(async()=>{try{await w(r,a)}finally{await z.rm(h.join(c(r).runtime,"endpoint.json"),{force:!0}),await t()}})(),"close")}}catch(n){try{for(let a of s.reverse())await Promise.resolve().then(()=>w(r,a)).catch(()=>{});await z.rm(h.join(c(r).runtime,"endpoint.json"),{force:!0})}finally{await t()}throw n}}i(ge,"ownHomeRuntime");async function he(r,e,t){await v(h.join(c(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:e,serverId:t}))}i(he,"publishRuntimeEndpoint");function ye(r){return te({runtime:B(r.ports),close:r.close})}i(ye,"createAppServer");function te(r){let e=!1;return{runtime:r.runtime,close:i(async()=>{e||(e=!0,await r.close?.())},"close")}}i(te,"attachAppServer");async function Pe(r){let e=typeof r.appServer=="function"?null:r.appServer;try{await N({host:e?.runtime??(async()=>(e=await r.appServer(),e.runtime)),readable:r.readable,writable:r.writable,hostStorageClient:r.hostStorageClient})}finally{await e?.close()}}i(Pe,"runAppServerJsonl");import S from"node:path";import{lstat as re,readFile as oe,realpath as $}from"node:fs/promises";import{randomUUID as se}from"node:crypto";var ne=o.object({id:o.string(),version:o.string(),contentHash:o.string().regex(/^[a-f0-9]{64}$/),feedbackKey:o.string(),release:o.object({id:o.string(),revision:o.union([o.string(),o.number()]),contentHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict(),G=o.object({binding:C,packageValue:o.unknown(),graders:o.array(ne).max(100),actualGrading:o.object({pass:o.unknown(),evidence:o.unknown()}).strict().optional(),sourceCandidate:E.optional()}).strict();async function Me(r,e){let t=await $(e),s=S.resolve(r);if(S.dirname(s)!==t||await $(s)!==s)throw new Error("External Dataset package escaped its private owner home.");let n=await re(s);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("External Dataset package is not a bounded regular file.");let a=G.parse(JSON.parse(new TextDecoder("utf8",{fatal:!0}).decode(await oe(s))));return a.binding=y(a.binding),a.packageValue=I({...a,packageValue:b(a.packageValue)}),a}i(Me,"readHostProfileExternalDataset");async function Oe(r){let e=G.parse(r.value),t=y(e.binding),s=r.release,n={id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash};if(t.protectedProfileClosureHash!==p(s.harnessRelease.files.filter(l=>l.visibility!=="policy").map(l=>({path:l.path,asset:l}))))throw new Error("The external Dataset protected Profile closure changed.");if(e.sourceCandidate){let l=await _({workspaceId:typeof s.agentSnapshot.metadata.workspaceId=="string"?s.agentSnapshot.metadata.workspaceId:s.workspaceId,sourceDir:S.join(s.bundlePath,"source")});if(p(e.sourceCandidate.harnessRelease)!==p(n)||L(l).protectedClosureHash!==e.sourceCandidate.protectedClosureHash)throw new Error("The external Dataset candidate differs from its retained frozen compiled source.")}let a=i(async l=>{if(o.object({authorized:o.literal(!0),bindingHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(await r.client.request({contractVersion:1,requestId:se(),operation:"profile.externalDataset.authorize",params:{...l,bindingHash:t.contentHash}})).bindingHash!==t.contentHash)throw new Error("The host authorized another external Dataset binding.")},"authorize");return{authorize:a,resolveExternalDataset:i(async(l,m)=>{if(await a(),p(l)!==p(t)||m.profileRef.profileId!==t.profileId||m.sourceRevision!==r.sourceRevision||p(m.harnessRelease)!==p(n))throw new Error("External Dataset requested another actual Profile source or recipe.");let f=I({...e,binding:l,packageValue:b(e.packageValue)});return{binding:t,packageValue:f,authorize:a}},"resolveExternalDataset"),sourceCandidate:e.sourceCandidate}}i(Oe,"createHostProfileExternalDataset");import{randomBytes as ae}from"node:crypto";function Ne(){return j()}i(Ne,"appDataDir");function Be(r){return c(r).config}i(Be,"providersConfigPath");function Le(r){return c(r).credentials}i(Le,"providerSecretsConfigPath");function ze(r){return c(r).key}i(ze,"providerSecretsKeyPath");async function Je(r){let e=c(r).token;return U(e,async()=>{let t=(await D(e))?.trim(),s=process.env.OPENPOND_APP_TOKEN||t||ae(32).toString("base64url");return s!==t&&await v(e,s),{token:s,tokenFile:e}})}i(Je,"ensureCapabilityToken");import u from"node:path";import{readFile as W}from"node:fs/promises";var q=o.object({profileId:o.string().min(1),sourceRevision:o.string().min(1),repositoryId:o.string().min(1),harnessRelease:o.object({id:o.string().min(1),contentHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict(),hostExecution:o.object({conversationId:o.string().min(1),turnId:o.string().min(1)}).strict().optional(),workspaceId:o.string().min(1),assetsPath:o.string().min(1).refine(u.isAbsolute)}).strict();async function Ze(r,e){let t=q.parse(e),s=await H(r,t.harnessRelease);if(!s||u.resolve(s.release.bundlePath)!==u.resolve(t.assetsPath))throw new Error("Hosted Profile release changed after admission.");let n=s.release.harnessRelease.metadata.profile;if(!n||typeof n!="object"||n.id!==t.profileId||n.sourceRevision!==t.sourceRevision||n.repositoryId!==void 0&&n.repositoryId!==t.repositoryId)throw new Error("Hosted Profile provenance differs from admitted release.");return{profile:F(),profileLibrary:V()}}i(Ze,"loadHostedProfileStateAndLibrary");async function et(r,e){let t=q.parse(e),s=await H(r,t.harnessRelease);if(!s||u.resolve(s.release.bundlePath)!==u.resolve(t.assetsPath))throw new Error("Hosted Profile workflow release is unavailable.");let n=s.release.harnessRelease.metadata.profile;if(n?.id!==t.profileId||n.sourceRevision!==t.sourceRevision||n.repositoryId!==void 0&&n.repositoryId!==t.repositoryId)throw new Error("Hosted Profile workflow provenance changed.");let a=t.harnessRelease,d={source:"openpond_git",repositoryId:t.repositoryId,profileId:t.profileId};if(!s.release.harnessRelease.files.some(f=>f.path==="workflows/catalog.json"))return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:[]};let l=u.join(s.release.bundlePath,"source","workflows"),m=A({agentSnapshot:s.release.agentSnapshot,harnessRelease:s.release.harnessRelease,catalogBytes:await W(u.join(l,"catalog.json")),actionBytes:await W(u.join(l,"actions.json"))});return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:m.catalog.workflows.map(f=>({workflow:f,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:t.profileId,sourceRevision:t.sourceRevision,harnessRelease:a,catalogHash:m.catalogHash,workflowId:f.id}}))}}i(et,"listHostedProfileWorkflows");import{createHash as ie,randomUUID as k}from"node:crypto";var K=o.object({approval:x,revision:o.number().int().positive()}).strict(),Q=o.object({record:R}).strict(),le=o.object({startedAt:o.string().min(1),requestOrdinal:o.number().int().nonnegative(),id:o.string().min(1)}).strict(),ce=o.object({records:o.array(R).max(200),nextBefore:le.nullable()}).strict(),Y=1e4,X=class{constructor(e){this.client=e}client;static{i(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:g,requestId:k(),operation:"approval/get",params:{approvalId:e}});return t===null?null:K.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=x.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return K.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},Z=class{constructor(e){this.client=e}client;static{i(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=R.parse(e),s=ie("sha256").update(JSON.stringify(t)).digest("hex"),n=await this.client.request({contractVersion:g,requestId:`usage:${s}`,operation:"usage/upsert",params:{record:t}}),a=Q.parse(n).record;if(a.requestId!==t.requestId)throw new Error("Host usage upsert changed request identity.");return a}async getModelUsageRecordByRequestId(e){let t=await this.client.request({contractVersion:g,requestId:k(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:Q.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=Y,s=e.limit===void 0?Y:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),n={...e.sessionId?{sessionId:e.sessionId}:{},...e.turnId?{turnId:e.turnId}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.startedAtFrom?{startedAtFrom:e.startedAtFrom}:{},...e.startedAtTo?{startedAtTo:e.startedAtTo}:{},...e.visibility&&e.visibility!=="all"?{visibility:e.visibility}:{},...e.status&&e.status!=="all"?{status:e.status}:{}},a=[],d=null;for(;a.length<s+(t?1:0);){let l=ce.parse(await this.client.request({contractVersion:g,requestId:k(),operation:"usage/page",params:{query:n,before:d,limit:Math.min(200,s+(t?1:0)-a.length)}}));if(a.push(...l.records),a.length>s)throw new Error(`Hosted usage query exceeds ${s} rows; narrow its filters or use a streamed aggregation.`);if(l.nextBefore===null)break;if(l.records.length===0||JSON.stringify(l.nextBefore)===JSON.stringify(d))throw new Error("Host usage cursor did not advance.");d=l.nextBefore}return a}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};export{fe as a,ge as b,he as c,ye as d,Pe as e,Me as f,Oe as g,Ne as h,Be as i,Le as j,ze as k,Je as l,q as m,Ze as n,et as o,X as p,Z as q};
|
|
2
|
+
import{b as H}from"./chunk-ZBZBV5TB.js";import{a as L}from"./chunk-T5LE6R5S.js";import{F as g,K as N,L as B}from"./chunk-PVSUQGWK.js";import{qa as _}from"./chunk-7MXZJQS7.js";import{O as x,R as V,S as F,Y as R}from"./chunk-XDMUD4FW.js";import{ta as I}from"./chunk-IKWDL3RB.js";import{Ca as b}from"./chunk-QRWPEW3Z.js";import{ma as E,na as C,oa as y}from"./chunk-PJM2G7SG.js";import{Ga as A}from"./chunk-SDEDAHV6.js";import{c as D,e as v,f as U,g as M,i as O,qa as T}from"./chunk-DALJMSJG.js";import{m as p}from"./chunk-NNF6KCHD.js";import{b as o}from"./chunk-ES2ISFJC.js";import{a as w,c as P,f as j,h as c}from"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import h from"node:path";import{AsyncLocalStorage as ee}from"node:async_hooks";import{promises as z}from"node:fs";var J=new ee;function fe(r,e=!1){let t=J.getStore();t&&(e&&(t.length=0),t.push(r))}i(fe,"onStartupFailure");async function ge(r,e){await T(r);let t;try{t=await M(h.join(c(r).runtime,"server-owner"),100)}catch(n){if(n instanceof P&&n.issue.code==="STORAGE_BUSY"){let a=await O(h.join(c(r).runtime,"endpoint.json"),()=>null);throw new P({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw n}let s=[];try{let n=await w(r,()=>J.run(s,e)),a=n.close.bind(n);s.length=0;let d;return{...n,close:i(()=>d??=(async()=>{try{await w(r,a)}finally{await z.rm(h.join(c(r).runtime,"endpoint.json"),{force:!0}),await t()}})(),"close")}}catch(n){try{for(let a of s.reverse())await Promise.resolve().then(()=>w(r,a)).catch(()=>{});await z.rm(h.join(c(r).runtime,"endpoint.json"),{force:!0})}finally{await t()}throw n}}i(ge,"ownHomeRuntime");async function he(r,e,t){await v(h.join(c(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:e,serverId:t}))}i(he,"publishRuntimeEndpoint");function ye(r){return te({runtime:B(r.ports),close:r.close})}i(ye,"createAppServer");function te(r){let e=!1;return{runtime:r.runtime,close:i(async()=>{e||(e=!0,await r.close?.())},"close")}}i(te,"attachAppServer");async function Pe(r){let e=typeof r.appServer=="function"?null:r.appServer;try{await N({host:e?.runtime??(async()=>(e=await r.appServer(),e.runtime)),readable:r.readable,writable:r.writable,hostStorageClient:r.hostStorageClient})}finally{await e?.close()}}i(Pe,"runAppServerJsonl");import S from"node:path";import{lstat as re,readFile as oe,realpath as $}from"node:fs/promises";import{randomUUID as se}from"node:crypto";var ne=o.object({id:o.string(),version:o.string(),contentHash:o.string().regex(/^[a-f0-9]{64}$/),feedbackKey:o.string(),release:o.object({id:o.string(),revision:o.union([o.string(),o.number()]),contentHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict(),G=o.object({binding:C,packageValue:o.unknown(),graders:o.array(ne).max(100),actualGrading:o.object({pass:o.unknown(),evidence:o.unknown()}).strict().optional(),sourceCandidate:E.optional()}).strict();async function Me(r,e){let t=await $(e),s=S.resolve(r);if(S.dirname(s)!==t||await $(s)!==s)throw new Error("External Dataset package escaped its private owner home.");let n=await re(s);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("External Dataset package is not a bounded regular file.");let a=G.parse(JSON.parse(new TextDecoder("utf8",{fatal:!0}).decode(await oe(s))));return a.binding=y(a.binding),a.packageValue=I({...a,packageValue:b(a.packageValue)}),a}i(Me,"readHostProfileExternalDataset");async function Oe(r){let e=G.parse(r.value),t=y(e.binding),s=r.release,n={id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash};if(t.protectedProfileClosureHash!==p(s.harnessRelease.files.filter(l=>l.visibility!=="policy").map(l=>({path:l.path,asset:l}))))throw new Error("The external Dataset protected Profile closure changed.");if(e.sourceCandidate){let l=await _({workspaceId:typeof s.agentSnapshot.metadata.workspaceId=="string"?s.agentSnapshot.metadata.workspaceId:s.workspaceId,sourceDir:S.join(s.bundlePath,"source")});if(p(e.sourceCandidate.harnessRelease)!==p(n)||L(l).protectedClosureHash!==e.sourceCandidate.protectedClosureHash)throw new Error("The external Dataset candidate differs from its retained frozen compiled source.")}let a=i(async l=>{if(o.object({authorized:o.literal(!0),bindingHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(await r.client.request({contractVersion:1,requestId:se(),operation:"profile.externalDataset.authorize",params:{...l,bindingHash:t.contentHash}})).bindingHash!==t.contentHash)throw new Error("The host authorized another external Dataset binding.")},"authorize");return{authorize:a,resolveExternalDataset:i(async(l,m)=>{if(await a(),p(l)!==p(t)||m.profileRef.profileId!==t.profileId||m.sourceRevision!==r.sourceRevision||p(m.harnessRelease)!==p(n))throw new Error("External Dataset requested another actual Profile source or recipe.");let f=I({...e,binding:l,packageValue:b(e.packageValue)});return{binding:t,packageValue:f,authorize:a}},"resolveExternalDataset"),sourceCandidate:e.sourceCandidate}}i(Oe,"createHostProfileExternalDataset");import{randomBytes as ae}from"node:crypto";function Ne(){return j()}i(Ne,"appDataDir");function Be(r){return c(r).config}i(Be,"providersConfigPath");function Le(r){return c(r).credentials}i(Le,"providerSecretsConfigPath");function ze(r){return c(r).key}i(ze,"providerSecretsKeyPath");async function Je(r){let e=c(r).token;return U(e,async()=>{let t=(await D(e))?.trim(),s=process.env.OPENPOND_APP_TOKEN||t||ae(32).toString("base64url");return s!==t&&await v(e,s),{token:s,tokenFile:e}})}i(Je,"ensureCapabilityToken");import u from"node:path";import{readFile as W}from"node:fs/promises";var q=o.object({profileId:o.string().min(1),sourceRevision:o.string().min(1),repositoryId:o.string().min(1),harnessRelease:o.object({id:o.string().min(1),contentHash:o.string().regex(/^[a-f0-9]{64}$/)}).strict(),hostExecution:o.object({conversationId:o.string().min(1),turnId:o.string().min(1)}).strict().optional(),workspaceId:o.string().min(1),assetsPath:o.string().min(1).refine(u.isAbsolute)}).strict();async function Ze(r,e){let t=q.parse(e),s=await H(r,t.harnessRelease);if(!s||u.resolve(s.release.bundlePath)!==u.resolve(t.assetsPath))throw new Error("Hosted Profile release changed after admission.");let n=s.release.harnessRelease.metadata.profile;if(!n||typeof n!="object"||n.id!==t.profileId||n.sourceRevision!==t.sourceRevision||n.repositoryId!==void 0&&n.repositoryId!==t.repositoryId)throw new Error("Hosted Profile provenance differs from admitted release.");return{profile:F(),profileLibrary:V()}}i(Ze,"loadHostedProfileStateAndLibrary");async function et(r,e){let t=q.parse(e),s=await H(r,t.harnessRelease);if(!s||u.resolve(s.release.bundlePath)!==u.resolve(t.assetsPath))throw new Error("Hosted Profile workflow release is unavailable.");let n=s.release.harnessRelease.metadata.profile;if(n?.id!==t.profileId||n.sourceRevision!==t.sourceRevision||n.repositoryId!==void 0&&n.repositoryId!==t.repositoryId)throw new Error("Hosted Profile workflow provenance changed.");let a=t.harnessRelease,d={source:"openpond_git",repositoryId:t.repositoryId,profileId:t.profileId};if(!s.release.harnessRelease.files.some(f=>f.path==="workflows/catalog.json"))return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:[]};let l=u.join(s.release.bundlePath,"source","workflows"),m=A({agentSnapshot:s.release.agentSnapshot,harnessRelease:s.release.harnessRelease,catalogBytes:await W(u.join(l,"catalog.json")),actionBytes:await W(u.join(l,"actions.json"))});return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:m.catalog.workflows.map(f=>({workflow:f,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:t.profileId,sourceRevision:t.sourceRevision,harnessRelease:a,catalogHash:m.catalogHash,workflowId:f.id}}))}}i(et,"listHostedProfileWorkflows");import{createHash as ie,randomUUID as k}from"node:crypto";var K=o.object({approval:x,revision:o.number().int().positive()}).strict(),Q=o.object({record:R}).strict(),le=o.object({startedAt:o.string().min(1),requestOrdinal:o.number().int().nonnegative(),id:o.string().min(1)}).strict(),ce=o.object({records:o.array(R).max(200),nextBefore:le.nullable()}).strict(),Y=1e4,X=class{constructor(e){this.client=e}client;static{i(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:g,requestId:k(),operation:"approval/get",params:{approvalId:e}});return t===null?null:K.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=x.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return K.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},Z=class{constructor(e){this.client=e}client;static{i(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=R.parse(e),s=ie("sha256").update(JSON.stringify(t)).digest("hex"),n=await this.client.request({contractVersion:g,requestId:`usage:${s}`,operation:"usage/upsert",params:{record:t}}),a=Q.parse(n).record;if(a.requestId!==t.requestId)throw new Error("Host usage upsert changed request identity.");return a}async getModelUsageRecordByRequestId(e){let t=await this.client.request({contractVersion:g,requestId:k(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:Q.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=Y,s=e.limit===void 0?Y:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),n={...e.sessionId?{sessionId:e.sessionId}:{},...e.turnId?{turnId:e.turnId}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.startedAtFrom?{startedAtFrom:e.startedAtFrom}:{},...e.startedAtTo?{startedAtTo:e.startedAtTo}:{},...e.visibility&&e.visibility!=="all"?{visibility:e.visibility}:{},...e.status&&e.status!=="all"?{status:e.status}:{}},a=[],d=null;for(;a.length<s+(t?1:0);){let l=ce.parse(await this.client.request({contractVersion:g,requestId:k(),operation:"usage/page",params:{query:n,before:d,limit:Math.min(200,s+(t?1:0)-a.length)}}));if(a.push(...l.records),a.length>s)throw new Error(`Hosted usage query exceeds ${s} rows; narrow its filters or use a streamed aggregation.`);if(l.nextBefore===null)break;if(l.records.length===0||JSON.stringify(l.nextBefore)===JSON.stringify(d))throw new Error("Host usage cursor did not advance.");d=l.nextBefore}return a}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};export{fe as a,ge as b,he as c,ye as d,Pe as e,Me as f,Oe as g,Ne as h,Be as i,Le as j,ze as k,Je as l,q as m,Ze as n,et as o,X as p,Z as q};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{f as fn,h as hn}from"./chunk-DLZP22WV.js";import{b as Bo,c as Jo,d as Rc,e as pn,f as Vt,g as mn}from"./chunk-OE2VF6KU.js";import{a as Tc,c as vc,g as Ec,h as Sc}from"./chunk-QJRXTIOC.js";import{D as an,E as fr,F as Jt,G as hr,H as ic,I as cc,J as dc,K as cn,L as lc,M as Uo,N as uc,O as xe,P as pc,Q as mc,R as fc,S as hc,T as gc,U as dn,V as yc,W as ln,aa as un,e as oi,ea as wc,f as si,fa as Me,ja as kc,m as ac,n as Fo}from"./chunk-7MXZJQS7.js";import{b as gn,m as xc,p as bc,s as Ic,t as yn,y as Cc,z as wn}from"./chunk-
|
|
2
|
+
import{f as fn,h as hn}from"./chunk-DLZP22WV.js";import{b as Bo,c as Jo,d as Rc,e as pn,f as Vt,g as mn}from"./chunk-OE2VF6KU.js";import{a as Tc,c as vc,g as Ec,h as Sc}from"./chunk-QJRXTIOC.js";import{D as an,E as fr,F as Jt,G as hr,H as ic,I as cc,J as dc,K as cn,L as lc,M as Uo,N as uc,O as xe,P as pc,Q as mc,R as fc,S as hc,T as gc,U as dn,V as yc,W as ln,aa as un,e as oi,ea as wc,f as si,fa as Me,ja as kc,m as ac,n as Fo}from"./chunk-7MXZJQS7.js";import{b as gn,m as xc,p as bc,s as Ic,t as yn,y as Cc,z as wn}from"./chunk-USMZT5FZ.js";import{d as Ve,g as Xe}from"./chunk-5CMKGD43.js";import{G as oc,P as sc}from"./chunk-HA7EFTPF.js";import{b as nc,e as on,f as sn}from"./chunk-7QEE4PBI.js";import{Ac as Ut,Ad as Ki,Bc as en,Bd as _i,Cc as tn,Cd as nn,Da as Hi,Dc as J,Ec as Xi,Ed as $i,Fa as _r,Fc as Bt,Fd as Rt,Gb as Fi,Gc as zi,Ib as re,Ic as Zi,Jb as Ui,Jc as jo,Kc as Yi,Kd as tc,La as Ho,Lb as Bi,Ld as tt,Ma as Wi,N as Mi,Oa as ji,Od as Se,Rd as mr,Sd as rc,Ta as qi,Y as Li,od as rn,pd as Qi,qd as Gi,rd as qo,va as Di,xc as $,yc as Ji,zc as Vi}from"./chunk-XDMUD4FW.js";import{c as ai,ga as Wo,z as Ni}from"./chunk-IKWDL3RB.js";import{Ba as Ci,Ca as pr,Oa as Ai,Qa as Je,Ra as Oi,Sa as Pi,Ta as et,ja as Ti,ka as vi,la as Ei,m as Ee,ma as Si,oa as xi,pc as $r,wc as ec,xa as bi,ya as Ii}from"./chunk-QRWPEW3Z.js";import{qa as ii,ra as Kr,sa as ci,ta as di,ua as lr,va as Ft,wa as li,x as _a}from"./chunk-WV2APYWG.js";import{Db as Gr,Eb as ri,Jb as qt,Qa as $a,Ra as Lo,Ta as ei,U as Qr,Vc as Ue,Wc as Be,a as Za,b as G,d as Ya,ga as $e,ha as Qa,ja as Ga,ka as Mo,la as ue,sd as ni,vb as Y,wb as ti,ya as Ka,z as Yr}from"./chunk-PJM2G7SG.js";import{A as ja,B as Ro,G as Jr,H as Vr,I as To,J as Fa,K as Ua,L as vo,M as Xr,N as Eo,O as So,P as cr,T as xo,U as Ba,V as Ja,W as Va,X as Xa,Y as za,Z as bo,_ as Io,e as Ma,ga as dr,ha as Co,ia as Ao,ja as Oo,ka as Po,la as zr,ma as Zr,n as La,na as jt,o as Da,oa as No,pa as Z,w as Ha,x as Wa}from"./chunk-SDEDAHV6.js";import{E as wi,F as ki,G as Ri,e as ui,f as wt}from"./chunk-DALJMSJG.js";import{B as pi,H as Do,N as mi,y as kt}from"./chunk-TGIB24K4.js";import{b as gt,c as he,d as yt,f as Aa,h as Oa,i as Pa,k as Na,l as ve,m as y,o as qa}from"./chunk-NNF6KCHD.js";import{b as g}from"./chunk-ES2ISFJC.js";import{h as ur,n as fi,o as hi,p as gi,q as yi}from"./chunk-H7IWJN7L.js";import{a as i,c as ko,e as Cp}from"./chunk-FTQLQJQV.js";var rd=ko((pv,td)=>{"use strict";var Im=["||","&&",";;","|&","<(","<<<",">>",">&","<&","&",";","(",")","|","<",">"],ed=/[\n\r\u2028\u2029]/,Cm=/[\s#!"$&'():;<=>@\\^`|]/g;td.exports=i(function(t){return t.map(function(r){if(r==="")return"''";if(r&&typeof r=="object"){if("op"in r&&r.op==="glob"){if(typeof r.pattern!="string")throw new TypeError("glob token requires a string `pattern`");if(ed.test(r.pattern))throw new TypeError("glob `pattern` must not contain line terminators");return r.pattern.replace(Cm,"\\$&")}if("op"in r&&typeof r.op=="string"){if(Im.indexOf(r.op)<0)throw new TypeError("invalid `op` value: "+JSON.stringify(r.op));return r.op.replace(/[\s\S]/g,"\\$&")}if("comment"in r&&typeof r.comment=="string"){if(ed.test(r.comment))throw new TypeError("`comment` must not contain line terminators");return"#"+r.comment}throw new TypeError("unrecognized object token shape")}return/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")},"quote")});var dd=ko((fv,cd)=>{"use strict";var id="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",nd=new RegExp("^"+id+"$"),od="|&;()<> \\t",Am="'([^']*?)'",Om='"((\\\\"|[^"])*?)"',Pm=/^#$/,sd="'",ad='"',In="$",Et="",Nm=4294967296;for($o=0;$o<4;$o++)Et+=(Nm*Math.random()).toString(16);var $o,Mm=new RegExp("^"+Et);function Lm(e,t){for(var r=t.lastIndex,n=[],o;o=t.exec(e);)n[n.length]=o,t.lastIndex===o.index&&(t.lastIndex+=1);return t.lastIndex=r,n}i(Lm,"matchAll");function Dm(e,t,r){var n=typeof e=="function"?e(r):e[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?t+Et+JSON.stringify(n)+Et:t+n}i(Dm,"getVar");function Hm(e,t,r){r||(r={});var n=r.escape||"\\",o=r.splitUnquoted===!0?`
|
|
3
3
|
`:typeof r.splitUnquoted=="string"?r.splitUnquoted:"",s="(\\"+n+`['"`+od+`]|[^\\s'"`+od+"])+",a=new RegExp(["("+id+")","("+s+"|"+Om+"|"+Am+")+"].join("|"),"g"),c=Lm(e,a);if(c.length===0)return[];t||(t={});var d=!1;return c.map(function(l){var p=l[0];if(!p||d)return;if(nd.test(p))return{op:p};var u=!1,m=!1,f="",h=[],R=!1,w=null,k=!1,x;function C(){x+=1;var E,b,D=p.charAt(x);if(D==="{"){if(x+=1,p.charAt(x)==="}")throw new Error("Bad substitution: "+p.slice(x-2,x+1));var F=1;for(E=x;F>0&&E<p.length;)p.charAt(E)==="{"&&p.charAt(E-1)==="$"?F+=1:p.charAt(E)==="}"&&(F-=1),E+=1;if(F!==0)throw new Error("Bad substitution: "+p.slice(x));E-=1,b=p.slice(x,E),x=E}else if(/[*@#?$!_-]/.test(D))b=D,x+=1;else{var V=p.slice(x);E=V.match(/[^\w\d_]/),E?(b=V.slice(0,E.index),x+=E.index-1):(b=V,x=p.length)}return Dm(t,"",b)}i(C,"parseEnvVar");function A(){if(w!==null){if(w===0)f!==""&&(h[h.length]=f,f="");else{h[h.length]=f,f="";for(var E=1;E<w;E+=1)h[h.length]=""}w=null}}for(i(A,"flushRun"),x=0;x<p.length;x++){var T=p.charAt(x);if(o&&T!==In&&A(),k=k||!u&&(T==="*"||T==="?"),m)f+=T,m=!1;else if(u)T===u?u=!1:u==sd?f+=T:T===n?(x+=1,T=p.charAt(x),T===ad||T===n||T===In?f+=T:f+=n+T):T===In?f+=C():f+=T;else if(T===ad||T===sd)u=T,R=!0;else{if(nd.test(T))return{op:p};if(Pm.test(T)){d=!0;var P={comment:e.slice(l.index+x+1)};return f.length?[f,P]:[P]}else if(T===n)m=!0;else if(T===In){var v=C();if(!o)f+=v;else for(var I=0;I<v.length;I+=1){var S=v.charAt(I);o.indexOf(S)<0?(A(),f+=S):w===null?w=S===" "||S===" "||S===`
|
|
4
4
|
`?0:1:S!==" "&&S!==" "&&S!==`
|
|
5
5
|
`&&(w+=1)}}else f+=T}}if(k)return{op:"glob",pattern:f};if(o){if(w!==null&&w>0){h[h.length]=f,f="";for(var N=1;N<w;N+=1)h[h.length]=""}return(f!==""||R&&h.length===0)&&(h[h.length]=f),h}return f}).reduce(function(l,p){return typeof p>"u"||[].concat(p).forEach(function(u){l[l.length]=u}),l},[])}i(Hm,"parseInternal");cd.exports=i(function(t,r,n){var o=Hm(t,r,n);return typeof r!="function"?o:o.reduce(function(s,a){if(typeof a=="object")return s[s.length]=a,s;var c=a.split(RegExp("("+Et+".*?"+Et+")","g"));return c.length===1?(s[s.length]=c[0],s):(c.filter(Boolean).forEach(function(d){s[s.length]=Mm.test(d)?JSON.parse(d.split(Et)[1]):d}),s)},[])},"parse")});var ld=ko(es=>{"use strict";es.quote=rd();es.parse=dd()});import{promises as Lc}from"node:fs";import rt from"node:path";var Ap="openpond.workEvidenceReceipt.v1",Op="openpond.workProcessTrace.v1",Pp="openpond.workFeedbackReceipt.v1",hk="openpond.workEvidenceEligibility.v1",Np=g.string().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),Mp=g.string().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),Lp=g.string().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),ie=Pa.extend({id:Lp}).strict().superRefine((e,t)=>{e.id!==Pc(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),Dp=g.enum(["tool","validation","state_transition","approval","question","artifact","cleanup"]),Hp=g.enum(["agent","environment"]),Wp=g.enum(["turn_started","turn_completed","turn_failed","turn_cancelled","turn_timed_out","tool_invoked","tool_completed","tool_failed","validation_completed","validation_failed","approval_requested","approval_resolved","question_asked","question_answered","question_dismissed","artifact_created","workspace_changed","environment_created","environment_reset","environment_destroyed","cleanup_completed","cleanup_failed"]),jp=g.enum(["started","completed","failed","cancelled"]),qp=g.enum(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),Fp=g.enum(["structural","visual","test","user_review","other"]),Up=g.enum(["running","completed","failed","cancelled","timeout"]),Bp=g.enum(["requested","approved","denied","answered","dismissed"]),Jp=g.enum(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),Vp=g.enum(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),Xp=g.object({sequence:g.number().int().nonnegative().max(1e6),timestamp:yt,layer:Hp,kind:Dp,action:Wp,status:jp,inputHash:he.nullable(),outputHash:he.nullable(),receiptHash:he.nullable(),parentReceiptHash:he.nullable(),artifactRefs:g.array(ie).max(1e3),attributes:g.object({toolCategory:qp.nullable(),validationKind:Fp.nullable(),transitionState:Up.nullable(),interventionOutcome:Bp.nullable(),artifactCount:g.number().int().nonnegative().max(1e5),exitCode:g.number().int().min(-1).max(255).nullable(),durationMs:g.number().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:g.number().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:g.number().int().nonnegative().max(0x4000000000000).nullable(),errorClass:Jp.nullable()}).strict()}).strict().superRefine((e,t)=>{e.layer==="agent"&&e.parentReceiptHash!==null&&t.addIssue({code:"custom",message:"Agent-layer steps cannot have a parent environment correlation.",path:["parentReceiptHash"]}),e.layer==="environment"&&e.parentReceiptHash===null&&t.addIssue({code:"custom",message:"Environment steps must correlate to an Agent receipt.",path:["parentReceiptHash"]})}),Ac=g.object({schemaVersion:g.literal(Op),sourceRevisionHash:he,sanitationPolicyVersion:gt,incomplete:g.boolean(),incompleteReasons:g.array(Vp).max(10),droppedEventCount:g.number().int().nonnegative().max(1e6),steps:g.array(Xp).max(1e5)}).strict().superRefine((e,t)=>{e.incomplete!==e.incompleteReasons.length>0&&t.addIssue({code:"custom",message:"incomplete must match the presence of incompleteReasons.",path:["incomplete"]});for(let r=0;r<e.steps.length;r+=1)e.steps[r].sequence!==r&&t.addIssue({code:"custom",message:"Process trace sequences must be contiguous and zero-based.",path:["steps",r,"sequence"]})}),Xo=Ac.safeExtend({contentHash:he}).strict(),zp=g.enum(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),Zp=g.object({status:g.enum(["completed","failed","cancelled","timeout"]),failureClass:zp.nullable()}).strict().superRefine((e,t)=>{e.status==="completed"&&e.failureClass!==null&&t.addIssue({code:"custom",message:"Completed Work cannot carry a failure class.",path:["failureClass"]}),e.status!=="completed"&&e.failureClass===null&&t.addIssue({code:"custom",message:"Non-completed Work requires a failure class.",path:["failureClass"]}),e.status==="cancelled"&&e.failureClass!=="cancelled"&&t.addIssue({code:"custom",message:"Cancelled Work must use the cancelled failure class.",path:["failureClass"]}),e.status==="timeout"&&e.failureClass!=="timeout"&&t.addIssue({code:"custom",message:"Timed-out Work must use the timeout failure class.",path:["failureClass"]})}),zo=g.object({schemaVersion:g.literal(Ap),id:g.string().regex(/^work-evidence-[a-f0-9]{24}$/),source:g.object({surface:g.enum(["desktop","hosted"]),experience:g.enum(["work","development"]),opaqueRef:Np,revisionHash:he}).strict(),agentSnapshot:Aa.nullable(),model:qa,runtime:g.object({adapterId:gt,adapterVersion:gt,capabilityRef:ie.nullable()}).strict(),inputHash:he,terminal:Zp,trace:g.object({sanitizedRef:ie,traceHash:he,sanitationPolicyVersion:gt,incomplete:g.boolean()}).strict(),outputRefs:g.array(ie).max(1e4),artifactRefs:g.array(ie).max(1e5),validationEvidenceRefs:g.array(ie).max(1e4),interventions:g.object({approvals:g.number().int().nonnegative().max(1e6),questions:g.number().int().nonnegative().max(1e6),steeringEvents:g.number().int().nonnegative().max(1e6),otherUserInterventions:g.number().int().nonnegative().max(1e6)}).strict(),timing:g.object({startedAt:yt,completedAt:yt,latencyMs:g.number().int().nonnegative().max(31536e6)}).strict(),usage:g.object({promptTokens:g.number().int().nonnegative().nullable(),completionTokens:g.number().int().nonnegative().nullable(),totalTokens:g.number().int().nonnegative().nullable()}).strict(),costUsd:g.number().nonnegative().max(1e6).nullable(),provenance:g.object({consentReceiptRef:ie,consentScope:g.literal("work_process_and_artifacts"),consentGrantedAt:yt,policyVersion:gt,projectorVersion:gt,disclosure:g.literal("portable_sanitized"),ownershipScope:g.enum(["personal","workspace"]),workspaceRef:Mp.nullable(),participantPolicy:g.enum(["creator_only","all_participants"]),retention:g.object({policy:g.literal("source_bound"),deleteWithSource:g.literal(!0),expiresAt:yt.nullable()}).strict()}).strict()}).strict().superRefine((e,t)=>{e.trace.traceHash!==e.trace.sanitizedRef.contentHash&&t.addIssue({code:"custom",message:"Sanitized trace reference must bind traceHash.",path:["trace","traceHash"]});let r=Date.parse(e.timing.completedAt)-Date.parse(e.timing.startedAt);(r<0||r!==e.timing.latencyMs)&&t.addIssue({code:"custom",message:"latencyMs must equal completedAt minus startedAt.",path:["timing","latencyMs"]}),e.provenance.ownershipScope==="workspace"&&e.provenance.workspaceRef===null&&t.addIssue({code:"custom",message:"Workspace-owned evidence requires workspaceRef.",path:["provenance","workspaceRef"]}),e.provenance.ownershipScope==="personal"&&e.provenance.workspaceRef!==null&&t.addIssue({code:"custom",message:"Personal evidence cannot carry workspaceRef.",path:["provenance","workspaceRef"]}),Vo(e.outputRefs,["outputRefs"],t),Vo(e.artifactRefs,["artifactRefs"],t),Vo(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),kn=zo.safeExtend({contentHash:he}).strict(),Yp=g.enum(["accepted","needs_correction","not_useful"]),Qp=g.enum(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),Oc=g.object({schemaVersion:g.literal(Pp),id:g.string().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:ie,outputRevisionRef:ie.nullable(),verdict:Yp,reasonCodes:g.array(Qp).max(16),correctionRef:ie.nullable(),correctedOutputRevisionRef:ie.nullable(),actor:g.literal("user"),createdAt:yt}).strict().superRefine((e,t)=>{new Set(e.reasonCodes).size!==e.reasonCodes.length&&t.addIssue({code:"custom",message:"Feedback reason codes must be unique.",path:["reasonCodes"]}),e.verdict!=="needs_correction"&&(e.correctionRef||e.correctedOutputRevisionRef)&&t.addIssue({code:"custom",message:"Only needs_correction feedback may bind correction artifacts.",path:["verdict"]})}),Zo=Oc.safeExtend({contentHash:he}).strict();function Pc(e){return`urn:openpond:artifact:${e}`}i(Pc,"evidenceArtifactId");function gk(e){return`urn:openpond:work:${y(e)}`}i(gk,"workSourceOpaqueRef");function yk(e){return`urn:openpond:workspace:${y(e)}`}i(yk,"workWorkspaceOpaqueRef");function Gp(e){return ie.parse({id:Pc(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}i(Gp,"evidenceArtifactRef");function wk(e){let t=Ac.parse(e);return Xo.parse({...t,contentHash:y(t)})}i(wk,"createWorkProcessTrace");function kk(e){let t=zo.parse(e);return kn.parse({...t,contentHash:y(t)})}i(kk,"createWorkEvidenceReceipt");function Rk(e,t){let r=Oc.parse(e),n=Zo.parse({...r,contentHash:y(r)});return t&&Kp(n,t),n}i(Rk,"createWorkFeedbackReceipt");function Tk(e){return _p(e,kn,zo)}i(Tk,"verifyWorkEvidenceReceipt");function vk(e){return Gp({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}i(vk,"workEvidenceReceiptRef");function Kp(e,t){if(e.evidenceReceiptRef.contentHash!==t.contentHash)throw new Error("Feedback targets a different Work evidence receipt.");if(e.outputRevisionRef&&!t.outputRefs.some(r=>r.contentHash===e.outputRevisionRef.contentHash))throw new Error("Feedback targets an output revision not bound by the Work evidence receipt.")}i(Kp,"assertFeedbackTargetsEvidence");function _p(e,t,r){let n=t.safeParse(e);if(!n.success)return!1;let{contentHash:o,...s}=n.data;return y(r.parse(s))===o}i(_p,"verifyHashedValue");function Vo(e,t,r){let n=e.map(o=>o.contentHash);new Set(n).size!==n.length&&r.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}i(Vo,"addDuplicateHashIssues");import{randomUUID as $p}from"node:crypto";import{promises as Rn}from"node:fs";import Nc from"node:path";function Xt(e){return{binding:i(()=>{let t=gi(e.home,"refiner_bindings","active");return t?Xr.parse(t.value):null},"binding"),releases:i(async()=>{let t=(await Rn.readdir(e.releases)).filter(r=>r.endsWith(".json"));return Promise.all(t.map(async r=>vo.parse(JSON.parse(await Rn.readFile(Nc.join(e.releases,r),"utf8")))))},"releases"),transitions:i(()=>Object.values(yi(e.home,"refiner_transitions")).map(t=>Eo.parse(t.value)),"transitions"),release:i(async t=>{let r=vo.parse(JSON.parse(await Rn.readFile(Nc.join(e.releases,`${t.contentHash}.json`),"utf8")));if(r.id!==t.id||r.contentHash!==t.contentHash)throw new Error("Refiner release reference does not match immutable release content.");return r},"release"),persistRelease:i(async t=>Mc(e.releases+`/${t.contentHash}.json`,Na(t),!0),"persistRelease"),writeSource:i(async t=>Mc(e.source,t),"writeSource"),transition:i(async(t,r)=>{hi(e.home,n=>{n.exec("BEGIN IMMEDIATE");try{let o=n.prepare("SELECT payload FROM refiner_bindings WHERE id = 'active'").get(),s=o?Xr.parse(JSON.parse(o.payload)):null,a=new Date().toISOString(),c={id:t.id,contentHash:t.contentHash},d={schemaVersion:"openpond.refinerTransitionReceipt.v1",id:`refiner-transition-${$p()}`,operation:r.operation,bindingChanged:r.bindingChanged,previousRelease:s?.release??null,nextRelease:c,actor:r.actor,reason:r.reason,authoringSkillHash:r.authoringSkillHash,validation:{valid:!0,messages:[]},createdAt:a},l=Eo.parse({...d,contentHash:y(d)});if(n.prepare("INSERT INTO refiner_transitions VALUES (?, ?, 1)").run(l.contentHash,JSON.stringify(l)),r.bindingChanged){let p=Xr.parse({schemaVersion:"openpond.refinerBinding.v1",channel:"active",revision:(s?.revision??-1)+1,release:c,updatedAt:a});n.prepare("INSERT INTO refiner_bindings VALUES ('active', ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(JSON.stringify(p))}n.exec("COMMIT")}catch(o){throw n.exec("ROLLBACK"),o}})},"transition")}}i(Xt,"createLocalRefinerProfileRepository");async function Mc(e,t,r=!1){await wt(e,async()=>{if(r){let n=await Rn.readFile(e,"utf8").catch(()=>null);if(n!==null){if(n!==t)throw new Error("Immutable Refiner release bytes changed.");return}}await ui(e,t)})}i(Mc,"atomicWrite");var Dc="OpenPond Refiner Core: evidence admission, privacy, ownership, validation, and immutable activation boundaries.";function gr(e){let t=rt.join(e,"library","refiners");return{home:e,root:t,source:rt.join(t,"source","openpond.review.json"),releases:rt.join(t,"releases")}}i(gr,"refinerProfilePaths");function qk(e){let t=i(()=>ze(e),"inspect"),r=i(s=>em(e,s),"update"),n=i(s=>rm(e,s),"activate"),o=i(s=>om(e,s),"rollback");return{refinerHistoryPayload:t,updateRefinerProfilePayload:r,activateRefinerReleasePayload:n,rollbackRefinerReleasePayload:o,inspectRefiner:t,updateRefiner:r,activateRefiner:n,rollbackRefiner:o}}i(qk,"createRefinerProfileRoutePayloads");async function ze(e){let t=gr(e),r=Xt(t),n=r.binding();if(!n)throw new Error("Active Refiner binding is unavailable.");let o=(await r.releases()).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),s=o.find(c=>c.id===n.release.id&&c.contentHash===n.release.contentHash);if(!s)throw new Error("Active Refiner release is unavailable.");let a=r.transitions().sort((c,d)=>d.createdAt.localeCompare(c.createdAt));return Qi.parse({rootPath:t.root,sourcePath:t.source,binding:n,currentRelease:s,releases:o,transitions:a})}i(ze,"inspectRefinerProfile");async function Hc(e){return(await ze(e)).currentRelease}i(Hc,"loadActiveRefinerRelease");async function em(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>tm(e,t))}i(em,"updateRefinerProfile");async function tm(e,t){let r=Gi.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=Fa.parse(r.profile),a=So({profile:s,coreVersion:xo,corePrompt:Dc}),d=(await o.releases()).find(p=>p.composedPromptHash===a.composedPromptHash&&p.profileHash===a.profileHash)??a;await o.persistRelease(d),await o.writeSource(cr(s));let l=o.binding();if(!l)throw new Error("Active Refiner binding is unavailable.");return r.activate&&l.release.contentHash===d.contentHash||!r.activate&&o.transitions().some(m=>!m.bindingChanged&&m.nextRelease.contentHash===d.contentHash&&m.actor===r.actor&&m.reason===r.reason&&m.authoringSkillHash===r.authoringSkillHash)||await o.transition(d,{operation:"update",bindingChanged:r.activate,actor:r.actor,reason:r.reason,authoringSkillHash:r.authoringSkillHash}),ze(e)}i(tm,"updateRefinerProfileUnlocked");async function rm(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>nm(e,t))}i(rm,"activateRefinerRelease");async function nm(e,t){let r=qo.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=await o.release(r.release),a=o.binding();if(!a)throw new Error("Active Refiner binding is unavailable.");return a.release.contentHash===s.contentHash||(await o.transition(s,{operation:"activate",bindingChanged:!0,actor:r.actor,reason:r.reason,authoringSkillHash:null}),await o.writeSource(cr(s.profile))),ze(e)}i(nm,"activateRefinerReleaseUnlocked");async function om(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>sm(e,t))}i(om,"rollbackRefinerRelease");async function sm(e,t){let r=qo.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=await o.release(r.release),a=o.binding();if(!a)throw new Error("Active Refiner binding is unavailable.");return a.release.contentHash===s.contentHash||(await o.transition(s,{operation:"rollback",bindingChanged:!0,actor:r.actor,reason:r.reason,authoringSkillHash:null}),await o.writeSource(cr(s.profile))),ze(e)}i(sm,"rollbackRefinerReleaseUnlocked");async function am(e){await wt(rt.join(ur(e).runtime,"refiner-initialize"),()=>im(gr(e)))}i(am,"initializeRefinerProfile");async function Yo(e){await am(e.home)}i(Yo,"ensureInitialized");async function im(e){let t=Xt(e);if(await Promise.all([Lc.mkdir(rt.dirname(e.source),{recursive:!0,mode:448}),Lc.mkdir(e.releases,{recursive:!0,mode:448})]),t.binding())return;let r=So({profile:Ua,coreVersion:xo,corePrompt:Dc});await t.persistRelease(r),await t.writeSource(cr(r.profile)),await t.transition(r,{operation:"initialize",bindingChanged:!0,actor:"openpond",reason:"Initialize the default Refiner Review Profile.",authoringSkillHash:null})}i(im,"initialize");import{randomUUID as fm}from"node:crypto";var cm=["prompt_tokens","promptTokens","input_tokens","inputTokens"],dm=["completion_tokens","completionTokens","output_tokens","outputTokens"],lm=["total_tokens","totalTokens"];function Ze(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=Qo(t,cm),n=um(t,r),o=n.promptTokens,s=Qo(t,dm),c=Qo(t,lm)??(o!==null&&s!==null?o+s:null);return{promptTokens:o,cachedPromptTokens:n.cachedPromptTokens,uncachedPromptTokens:n.uncachedPromptTokens,cacheWritePromptTokens:n.cacheWritePromptTokens,cacheTelemetrySource:n.cacheTelemetrySource,completionTokens:s,totalTokens:c}}i(Ze,"normalizeModelUsageTokens");function um(e,t){let r=Tn(e,["cached_input_tokens","cachedInputTokens","cached_prompt_tokens","cachedPromptTokens","prompt_cache_hit_tokens","promptCacheHitTokens"]),n=Tn(e,["prompt_cache_miss_tokens","promptCacheMissTokens"]),o=Tn(e,["cache_read_input_tokens","cacheReadInputTokens"]),s=mm(e,[["prompt_tokens_details","cached_tokens"],["promptTokensDetails","cachedTokens"],["input_tokens_details","cached_tokens"],["inputTokensDetails","cachedTokens"]]),a=Tn(e,["cache_creation_input_tokens","cacheCreationInputTokens","cache_write_input_tokens","cacheWriteInputTokens"]),c=r.value!==null?r:o.value!==null?o:s,d=c.value!==null||n.value!==null||a.value!==null,l=d?pm(e):null;if(!d)return{promptTokens:t,cachedPromptTokens:null,uncachedPromptTokens:null,cacheWritePromptTokens:null,cacheTelemetrySource:null};let p=c.value,u=a.present?a.value:null,m=c===o&&o.value!==null||a.value!==null,f=t??(c.value!==null&&n.value!==null?c.value+n.value:null);if(f===null)return{promptTokens:null,cachedPromptTokens:p,uncachedPromptTokens:n.value,cacheWritePromptTokens:u,cacheTelemetrySource:l};if(m){let w=p??0,k=u??0,x=t??n.value??0;return{promptTokens:x+w+k,cachedPromptTokens:p,uncachedPromptTokens:x+k,cacheWritePromptTokens:u,cacheTelemetrySource:l}}let h=p===null?null:Math.min(f,p),R=n.value===null?h===null?null:f-h:Math.min(f-(h??0),n.value);return{promptTokens:f,cachedPromptTokens:h,uncachedPromptTokens:R,cacheWritePromptTokens:u,cacheTelemetrySource:l}}i(um,"normalizeCacheUsage");function pm(e){return(e.cache_telemetry_source??e.cacheTelemetrySource)==="provider_response_headers"?"provider_response_headers":"provider_usage_body"}i(pm,"cacheTelemetrySourceFromUsage");function Tn(e,t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r))return{present:!0,value:Go(e[r])};return{present:!1,value:null}}i(Tn,"firstPresentTokenCount");function mm(e,t){for(let[r,n]of t){let o=e[r];if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(Object.prototype.hasOwnProperty.call(s,n))return{present:!0,value:Go(s[n])}}return{present:!1,value:null}}i(mm,"firstPresentNestedTokenCount");function Qo(e,t){for(let r of t){let n=Go(e[r]);if(n!==null)return n}return null}i(Qo,"firstTokenCount");function Go(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e);if(typeof e!="string")return null;let t=e.trim();if(!/^\d+$/.test(t))return null;let r=Number(t);return Number.isSafeInteger(r)?r:null}i(Go,"tokenCount");function En(e){let t=vn(vn(vn(e.metadata).billing).pricing);return{version:zt(t.version,"pricing version"),source:zt(t.source,"pricing source"),effectiveAt:zt(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Zt(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Zt(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Zt(t.outputUsdPerMillionTokens,"output token rate")}}i(En,"hostedTokenPricingFromCatalog");function Xk(e){let t=vn(e);try{return{version:zt(t.version,"pricing version"),source:zt(t.source,"pricing source"),effectiveAt:zt(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Zt(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Zt(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Zt(t.outputUsdPerMillionTokens,"output token rate")}}catch{return null}}i(Xk,"hostedTokenPricingFromValue");function nt(e,t){let r=Ze(e);if(r.promptTokens===null&&r.completionTokens===null)return null;let n=r.cachedPromptTokens??0;return((r.uncachedPromptTokens??r.promptTokens??0)*t.inputUsdPerMillionTokens+n*t.cachedInputUsdPerMillionTokens+(r.completionTokens??0)*t.outputUsdPerMillionTokens)/1e6}i(nt,"hostedUsageCostUsd");function vn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(vn,"record");function zt(e,t){if(typeof e=="string"&&e.trim())return e.trim();throw new Error(`Hosted model catalog is missing ${t}.`)}i(zt,"requiredString");function Zt(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;throw new Error(`Hosted model catalog is missing ${t}.`)}i(Zt,"requiredRate");function qc(e={}){let t=e.catalog??fn,r=e.stream??hn;return{async prepare(n){if(n.providerId!=="openpond")throw new Error("The selected judge provider is not connected to the hosted judge transport.");if(n.revision!==null)throw new Error("This judge transport cannot enforce a model revision; select a provider with revision support.");let o=await t();if(o.error)throw new Error(`Judge model catalog unavailable: ${o.error}`);let s=o.models.find(u=>u.id===n.modelId);if(!s)throw new Error("The selected judge model is unavailable.");let a=Wc(s.raw),c=En(a),d=jc(a.context_window,"context window"),l=Math.min(4096,jc(a.output_limit,"output limit")),p=(d*Math.max(c.inputUsdPerMillionTokens,c.cachedInputUsdPerMillionTokens)+l*c.outputUsdPerMillionTokens)/1e6;if(!(p>0))throw new Error("The judge model must have a positive known charge ceiling.");return{maximumChargeUsd:p,async dispatch(u){u?.throwIfAborted();let m="",f=null,h=null,R=null,w=!1;for await(let C of r({model:n.modelId,messages:[{role:"system",content:n.system},{role:"user",content:n.data}],requestId:`learning-judge-${fm()}`,maxTokens:l,temperature:n.temperature,signal:u})){let A=Wc(C.raw);if(typeof A.model=="string"){if(f!==null&&A.model!==f)throw new Error("Judge response model identity changed during streaming.");f=A.model}if(typeof A.id=="string"){if(h!==null&&h!==A.id)throw new Error("Judge response identity changed during streaming.");h=A.id}if(C.type==="text_delta"&&(m+=C.text),m.length>1e5)throw new Error("Judge response exceeds the retained response limit.");C.type==="usage"&&(R=C.usage),C.type==="finish"&&(w=!0)}if(!w||!f||!h)throw new Error("Judge response did not include a complete model receipt.");let k=Ze(R),x=k.promptTokens!==null&&k.completionTokens!==null?nt(R,c):null;return{text:m,modelId:f,modelRevision:null,responseId:h,inputTokens:k.promptTokens,outputTokens:k.completionTokens,costUsd:x}}}},async cancel({run:n}){return!n.judgeCalls?.some(o=>o.status==="reserved")}}}i(qc,"createLearningHostedJudgeProvider");function Wc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(Wc,"record");function jc(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new Error(`Judge catalog is missing its ${t}.`);return e}i(jc,"positiveInteger");function sR(e,t=qc()){return{execute(r){if(r.definition.execution.environment.entrypoint==="openpond.javascript-environment.v1")throw new Error("Tool Tasksets require grading an owner-recorded environment attempt.");let n=ni({repository:e,scope:r.scope,run:r.run});return Qa({binding:r.binding,rewards:r.rewards,task:Gr(r.evidence,r.definition),evidence:ri(r.evidence,r.run.output),evaluatorContext:r.evidence.submission.evaluatorContext,signal:r.signal,modelJudge:$a({readRubric:i(o=>e.transaction(r.scope,async s=>ue(await Ue(s,"asset",o.id,1),o)),"readRubric"),async executeBudgeted(o,s){let a=await t.prepare(o,{scope:r.scope,run:r.run});return ei({store:n,maximumCharge:i(()=>a.maximumChargeUsd,"maximumCharge"),dispatch:i((d,l)=>a.dispatch(l),"dispatch")})(`grade-${y(o)}`,o,s)}}),customVerifier:i(async({grader:o,task:s,evidence:a})=>{let c=await yr({repository:e,scope:r.scope,grader:o,task:s,evidence:a,evaluatorContext:r.evidence.submission.evaluatorContext,timeoutMs:r.run.timeoutMs,signal:r.signal});return{score:c.score,passed:c.passed,rewardEligible:o.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs}},"customVerifier")})},async cancel({scope:r,run:n}){let o=await e.transaction(r,s=>Ue(s,"grade",n.id));return o.judgeCalls?.some(s=>s.status==="reserved")?!1:t.cancel({scope:r,run:o})}}}i(sR,"createLocalTaskGradeExecutor");async function yr(e){let t=await e.repository.transaction(e.scope,async r=>ue(await Ue(r,"asset",e.grader.verifierRef.id,1),e.grader.verifierRef));return Vt({source:t,exportName:e.grader.exportName,runtime:e.grader.runtime,timeoutMs:Math.min(e.grader.timeoutMs,e.timeoutMs??e.grader.timeoutMs),signal:e.signal,value:{task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,expectedOutput:e.task.expectedOutput,evaluatorContext:e.evaluatorContext,infrastructureError:e.evidence.infrastructureError??null}})}i(yr,"executeLocalLearningVerifier");import hm from"node:path";async function Fc(e,t,r){if(!r)throw new Error("Ordinary tool execution requires its owner's package directory.");let n=$r({taskset:e,adapterId:dn(e)}),o=await wc({root:hm.join(r,"training","tasksets",Me(e)),content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:n.tasksetRelease,environment:n.environmentRelease,verifierSet:n.verifierSetRelease},sources:ec.parse(e.metadata.portableFileInventory)}),s=Ii(o);if(!s)throw new Error("The Taskset does not declare a JavaScript execution graph.");let a=o.taskset.tasks.find(l=>l.id===t.id);if(!a)throw new Error("The selected task is missing from its executable package.");let c=s.assets.find(l=>l.id===s.execution.javascript.module.id),d=s.assets.find(l=>l.id===a.privilegedContextRef);return{execution:s.execution,module:c,initialState:JSON.parse(d.text),definition:Y(o.taskset),instructions:Ci(o),task:a}}i(Fc,"loadOrdinaryToolEnvironment");var ce="openpond.javascript-environment.v1";async function Yt(e,t,r,n){let o=t.tasks.find(s=>s.id===r.id);if(!o||y(o)!==y(r))throw new Error("Tool task differs from the selected immutable Taskset.");return t.metadata.taskDefinition===void 0?Fc(t,r,n):e.learningRepository().transaction(t.profileId,async s=>{let a=await Be(s,"definition",Ee.parse(t.metadata.taskDefinition)),c=a.execution.environment;if(c.entrypoint!==ce||t.environment.entrypoint!==ce||t.environment.kind!=="agent"||t.environment.stateful!==c.stateful||t.environment.defaultTimeoutMs!==c.defaultTimeoutMs||t.environment.networkPolicy!==c.networkPolicy||t.environment.deterministicSeeds!==c.deterministicSeeds||y(t.environment.toolNames)!==y(a.execution.tools.map(T=>T.name))||y(t.environment.metadata.portableTools)!==y(a.execution.tools)||y(t.policy)!==y(a.execution.policy)||y(t.metadata.rewardBinding)!==y(a.rewardBinding))throw new Error("Tool Taskset context differs from its pinned task definition.");let d=await Be(s,"binding",a.rewardBinding),l=await Promise.all(d.sources.map(T=>Be(s,"reward",T.reward))),p=Qr.parse({id:r.id,clusterKey:r.clusterKey,split:r.split,input:r.input,expectedOutput:r.expectedOutput,policyVisibleContext:r.policyVisibleContext,privilegedContextRef:r.privilegedContextRef,artifactRefs:[],tags:r.tags}),u={...a.execution,graders:$e(d,l),tasks:[p]},m=await Ue(s,"asset",Si(u),1),f=vi.parse(JSON.parse(ue(m,m.asset))),h=[f.javascript.module,f.environment.actionSchemaRef,f.environment.observationSchemaRef,f.environment.stateSchemaRef].filter(T=>T!==null),R=[...new Set([...h.map(T=>T.id),r.privilegedContextRef].filter(T=>T!==null))],w=await Promise.all(R.map(T=>Ue(s,"asset",T,1))),k=xi(u,m,w);if(y(t.environment.metadata.portableExecutionResources)!==y({environment:k.environment,verifierSet:k.verifierSet}))throw new Error("Tool Taskset publication differs from its private execution resources.");let x=w.find(T=>T.id===k.javascript.module.id),C=w.find(T=>T.id===r.privilegedContextRef),A=JSON.parse(ue(C,C.asset));return{execution:k,module:x,initialState:A,definition:Y(a),instructions:a.instructions,task:p}})}i(Yt,"loadStarterToolEnvironment");function Uc(e){let t=Mo({text:e.instructions,path:"policy/instructions.txt",mediaType:"text/plain",visibility:"policy"}),r=Mo({text:JSON.stringify({environment:Y(e.execution.environment),verifierSet:Y(e.execution.verifierSet),javascript:Y(e.execution.javascript)}),path:"environment/dependencies.json",mediaType:"application/json",visibility:"host_private"}),n=La({schemaVersion:"openpond.agentSnapshot.v2",id:`starter-agent-${e.definition.contentHash}`,sourceRelease:{id:e.definition.id,contentHash:e.definition.contentHash},instructions:[t.asset],skills:[],agents:[],toolDeclarations:e.execution.javascript.tools,capabilityRequirements:[],dependencyLock:r.asset,portability:{portable:!0,blockers:[],localOnlyAssetRefs:[],hostPrivateAssetRefs:[e.module.id,r.id]},metadata:{execution:ce}}),o=Da({schemaVersion:"openpond.harnessRelease.v2",id:`starter-harness-${n.contentHash}`,agentSnapshot:{id:n.id,contentHash:n.contentHash},program:e.module.asset,tools:e.execution.javascript.tools,lifecycle:{create:!0,reset:!0,step:!0,collect:!0,destroy:!0,resetScope:"attempt"},graderInterface:{visibleEvidence:["output"],privilegedEvidence:["environment_state","private_verifier"],privateVerifierIsolation:!0},files:[t.asset,r.asset,e.module.asset],metadata:{execution:ce}});return{agentSnapshot:n,harnessRelease:o,instructionContext:void 0}}i(Uc,"compileStarterToolHarness");import Sn from"node:path";import{constants as Bc}from"node:fs";import{open as gm,realpath as Jc}from"node:fs/promises";var ym=g.string().regex(/^[a-f0-9]{64}$/),wm=g.object({schemaVersion:g.literal("openpond.starterToolAttempt.v1"),requestId:g.string(),taskset:Ee,taskHash:ym,model:g.unknown(),seed:g.number().int(),attempt:g.number().int(),definition:Ee,policySource:g.enum(["model","fixture"]),environment:Ee,verifierSet:Ee,result:Ti}).strict();async function xn(e){let{store:t,taskset:r,task:n,attempt:o}=e,s=await Yt(t,r,n,e.storeDir),c=(await t.listTaskAttemptArtifacts({attemptId:o.id})).filter(x=>x.kind==="environment_state"&&x.tasksetId===r.id&&x.taskId===n.id&&x.attemptId===o.id&&o.artifactRefs.includes(x.id)&&o.privilegedOutcomeRef===x.id);if(c.length!==1)throw new Error("Tool grading requires exactly one owner-recorded environment artifact.");let d=c[0],l=await Jc(Sn.join(e.storeDir,"training","evaluation-artifacts")),p=await Jc(Sn.dirname(d.path)),u=Sn.relative(l,p);if(!u||u.startsWith("..")||Sn.isAbsolute(u))throw new Error("Tool evidence is outside the execution owner's artifact directory.");let m=await gm(d.path,Bc.O_RDONLY|Bc.O_NOFOLLOW),f;try{let x=await m.stat();if(!x.isFile()||x.size>33554432||x.size!==d.sizeBytes)throw new Error("Tool evidence exceeds its declared byte boundary.");f=await m.readFile()}finally{await m.close()}if(f.byteLength!==d.sizeBytes||ve(f)!==d.sha256)throw new Error("Owner-recorded tool evidence bytes changed.");let h=wm.parse(JSON.parse(f.toString("utf8"))),{contentHash:R,...w}=h.result,k=h.result;if(y(w)!==R||!k.snapshot||!k.environmentCleanupComplete||!["completed","budget_exhausted","policy_failure"].includes(k.status)||y(h.taskset)!==y(Y(r))||h.taskHash!==y(n)||y(h.model)!==y(o.modelRef)||h.seed!==o.seed||h.attempt!==o.attempt||o.tasksetId!==r.id||o.taskId!==n.id||o.split!==n.split||y(h.definition)!==y(s.definition)||y(h.environment)!==y(Y(s.execution.environment))||y(h.verifierSet)!==y(Y(s.execution.verifierSet))||k.taskId!==n.id||k.snapshot.seed!==o.seed||k.snapshot.inputHash!==y(n.input)||y(k.snapshot.definition)!==y(Y(s.execution.javascript))||k.snapshot.finalStateHash!==y(k.snapshot.state)||y(o.output)!==y({text:k.output??""})||o.metadata.environmentAttemptHash!==R)throw new Error("Tool evidence differs from the selected task, model or recorded attempt.");if(o.metadata.policySource!==h.policySource)throw new Error("Tool evidence policy source changed.");return{environment:{status:k.status,collected:k.collected,definition:k.snapshot.definition,initialStateHash:k.snapshot.initialStateHash,finalStateHash:k.snapshot.finalStateHash,finalState:k.snapshot.state,events:k.snapshot.events}}}i(xn,"readStarterToolEvidence");async function ot(e,t){if(t.metadata.learning!==void 0)return qt.parse(t.metadata.learning);if(t.metadata.rewardBinding===void 0)return;let r=Ee.parse(t.metadata.rewardBinding);return e.learningRepository().transaction(t.profileId,async n=>{let o=await Be(n,"binding",r),s=[...new Map(o.sources.map(c=>[`${c.reward.id}:${c.reward.revision}:${c.reward.contentHash}`,c.reward])).values()],a=await Promise.all(s.map(c=>Be(n,"reward",c)));return{binding:o,rewards:a}})}i(ot,"resolveTasksetRewardBinding");async function km(e,t,r){let n=await ot(e,t);if(!n)return{rewardExecution:void 0,verifierAssets:[]};let o=$e(n.binding,n.rewards).flatMap(c=>c.kind==="custom_verifier"?[c.verifierRef]:c.kind==="model_judge"?[c.rubricRef]:[]),s=t.metadata.learning===void 0?void 0:await un(r,t);if(s){let c=[...new Map(o.map(d=>{let l=s.learningResources.assets.find(p=>p.id===d.id);if(!l)throw new Error("Imported batch verifier is missing from its package.");return ue(l,d),[l.id,l]})).values()];return{rewardExecution:n,verifierAssets:c}}let a=await e.learningRepository().transaction(t.profileId,async c=>{let d=new Map;for(let l of o){let p=await Ue(c,"asset",l.id,1);ue(p,l),d.set(p.id,p)}return[...d.values()]});return{rewardExecution:n,verifierAssets:a}}i(km,"resolveTasksetTrainingReward");async function YR(e,t,r){let n=await km(e,t,r.storeDir);if(!n.rewardExecution)return n;let o=$e(n.rewardExecution.binding,n.rewardExecution.rewards);if(!n.rewardExecution.binding.sources.some(s=>s.role==="evaluation"&&s.weight>0))throw new Error("Managed training requires a positively weighted evaluation Reward source for retained validation.");if(o.some(s=>s.kind==="custom_verifier"&&s.runtime==="sandbox_process"))throw new Error("Managed preparation requires a qualified isolated sandbox for process verifiers.");if(r.placement!=="remote"||t.environment.kind==="work"||t.capabilities.requiresState||t.capabilities.requiresTools||o.some(s=>s.kind==="human"||s.kind==="model_judge"&&(!s.model||s.calibrationStatus!=="passed"))||t.tasks.some(s=>s.privilegedContextRef!==null)||!n.rewardExecution.binding.sources.some(s=>s.role==="training"&&s.weight>0)||r.hasLearnedPreferenceReward)throw new Error("This Reward binding requires an additional managed execution adapter.");return n}i(YR,"resolveManagedTasksetReward");async function Vc(e,t,r){let n=await ot(e,t);if(!n)throw new Error("The Taskset has no published Reward binding.");let o=$e(n.binding,n.rewards);return async({grader:s,task:a,attempt:c,signal:d})=>{let l=t.tasks.find(f=>f.id===a.id);if(!l||y(l)!==y(a))throw new Error("Task differs from the selected immutable Taskset.");let p=null;if(t.environment.entrypoint===ce){if(!r)throw new Error("Tool grading requires the execution owner's artifact directory.");p=await xn({store:e,storeDir:r,taskset:t,task:a,attempt:c})}else if(a.privilegedContextRef!==null)throw new Error("This authored Taskset requires a private evaluator-context resolver.");let u=o.find(f=>f.id===s.id);if(u?.kind!=="custom_verifier")throw new Error("The verifier is absent from the published Reward binding.");let m=Qr.parse({id:a.id,clusterKey:a.clusterKey,split:a.split,input:a.input,expectedOutput:a.expectedOutput,policyVisibleContext:a.policyVisibleContext,privilegedContextRef:a.privilegedContextRef,artifactRefs:[],tags:a.tags});return yr({repository:e.learningRepository(),scope:t.profileId,grader:u,task:m,evidence:{output:c.output,artifactRefs:c.artifactRefs,runtimeEventRefs:c.runtimeEventRefs,infrastructureError:c.infrastructureError},evaluatorContext:p,signal:d})}}i(Vc,"createTasksetBindingVerifier");async function Tt(e,t,r){let n=r?Ee.parse(r):null;if(n&&n.id!==t)throw new Error("Taskset execution reference differs from the requested Taskset.");let o=n?await e.getTasksetRevision(n.id,n.revision):await e.getTaskset(t);if(!o||n&&(o.contentHash!==n.contentHash||et(o)!==n.contentHash))throw new Error("Taskset execution revision is unavailable or differs from its immutable hash.");return o}i(Tt,"requireLocalTasksetRevision");async function tT(e,t,r){let n=await e.releaseForTaskset(t);return n||$r({taskset:t,rewardExecution:r?await ot(r,t):void 0,adapterId:dn(t)}).tasksetRelease}i(tT,"requireReleasedTaskset");import{createHash as Rm}from"node:crypto";function Xc(e,t,r){if(t.metadata.importedPackageHash!==e.contentHash)throw new Error("The Work projection differs from the admitted published package.");let n=e.taskset.tasks.find(a=>a.id===r.id);if(!n||n.split!==r.split||y(r.metadata.portableTaskRecord)!==y(n))throw new Error("The Work task differs from its exact released population.");let o=0,s=(r.assets??[]).map(a=>{let c=n.artifactRefs.find(u=>u.id===a.id&&u.contentHash===a.sha256&&u.path===a.artifactRef),d=c&&e.files.find(u=>y(u.asset)===y(c));if(!c||!d||c.visibility!=="policy")throw new Error("The Work task requests an unavailable or private evaluator file.");let l=Buffer.from(bi(d));if(Rm("sha256").update(l).digest("hex")!==a.sha256||l.length!==a.sizeBytes||a.split!==r.split)throw new Error("The published Work input manifest changed.");if(o+=l.length,o>25e7)throw new Error("Published Work inputs exceed the admitted 250 MB ceiling.");return{...a,assetId:a.id,storageName:a.fileName,bytes:l,sizeBytes:l.length}});if(s.length!==n.artifactRefs.length)throw new Error("The exact policy-visible Work asset population is incomplete.");return s}i(Xc,"advancedPublishedWorkAssets");import{AsyncLocalStorage as Tm}from"node:async_hooks";var Zc=new Tm,wr=i(()=>Zc.getStore(),"currentScheduledAdmissionGuard");function lT(e,t){return Zc.run(e,t)}i(lT,"withScheduledAdmission");var Qt=class extends Error{constructor(r,n,o){super("The scheduled request was refused before provider transport.",{cause:o});this.executionId=r;this.requestId=n}executionId;requestId;static{i(this,"ScheduledTransportNotInvokedError")}},zc=class extends Error{constructor(r,n,o){super("The scheduled admission lost its exact owner lease before Run insertion.");this.scheduleId=r;this.operationId=n;this.configurationHash=o}scheduleId;operationId;configurationHash;static{i(this,"ScheduledAdmissionRejectedError")}};function bn(e,t){let r=t.scope==="arguments"?e.action?.arguments:e[t.scope];for(let n of t.path){if(!r||typeof r!="object"||!Object.hasOwn(r,n))throw new Error("environment_service_reference_missing");r=r[n]}return r}i(bn,"resolveValue");async function kr(e,t){if(!e.executionServices?.length)return t.controller(e);if(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e4)throw new Error("environment_timeout_invalid");G(e.value,4194304);let r=e.executionServices.map(c=>ci.parse(c));if(r.length>16)throw new Error("environment_service_limit");if(new Set(r.map(c=>c.id)).size!==r.length)throw new Error("environment_service_identity_collision");let n=Date.now(),o=new AbortController,s=e.signal?AbortSignal.any([e.signal,o.signal]):o.signal,a=setTimeout(()=>o.abort(new Error("environment_timeout")),e.timeoutMs);try{let c=Object.create(null);for(let l of r){if(s.throwIfAborted(),l.operation!==e.operation||l.operation==="step"&&l.toolName!==e.value.action?.name)throw new Error("environment_service_operation_mismatch");let p=Math.min(l.timeoutMs,e.timeoutMs-(Date.now()-n));if(p<1)throw new Error("environment_timeout");let u=new AbortController,m=AbortSignal.any([s,u.signal]),f=setTimeout(()=>u.abort(new Error("environment_service_timeout")),p),h=Date.now();try{if(l.kind==="sqlite.v1"){if(!t.sql)throw new Error("environment_sql_executor_required");let R=bn(e.value,l.sql);if(typeof R!="string"||!R.length||new TextEncoder().encode(R).byteLength>65536||R.includes("\0")){c[l.id]={status:"rejected",code:"invalid_submission"};continue}let w=Kr({schemaVersion:"openpond.sqlExecution.v1",snapshot:bn(e.value,l.snapshot),sql:R,maxRows:l.maxRows,maxResultBytes:l.maxResultBytes});c[l.id]=await t.sql({request:w,timeoutMs:e.timeoutMs,signal:m})}else{let R=bn(e.value,l.source),w=bn(e.value,l.cases);if(typeof R!="string"||new TextEncoder().encode(R).byteLength>524288){c[l.id]={status:"rejected",code:"invalid_submission"};continue}if(!Array.isArray(w)||!w.length||w.length>l.maxCases||w.some(x=>!x||typeof x!="object"||!Object.hasOwn(x,"input")))throw new Error("environment_service_cases_invalid");let k=[];for(let x of w){let C=p-(Date.now()-h);if(C<1&&(u.abort(new Error("environment_service_timeout")),m.throwIfAborted()),k.push(await t.candidate({source:R,exportName:l.exportName,value:structuredClone(x.input),timeoutMs:Math.max(1,C),maxResultBytes:l.maxResultBytes,deterministic:!0,errorPrefix:"candidate",signal:m})),new TextEncoder().encode(JSON.stringify({status:"completed",cases:k})).byteLength>l.maxResultBytes)throw new Bo("candidate_result_too_large")}c[l.id]={status:"completed",cases:k}}}catch(R){if(s.throwIfAborted(),u.signal.aborted)c[l.id]={status:"rejected",code:"timeout"};else if(R instanceof Bo)c[l.id]={status:"rejected",code:"execution_failed"};else throw R}finally{clearTimeout(f)}}s.throwIfAborted();let d=e.timeoutMs-(Date.now()-n);if(d<1)throw new Error("environment_timeout");return await t.controller({...e,executionServices:void 0,value:{...e.value,services:c},timeoutMs:d,signal:s})}finally{clearTimeout(a)}}i(kr,"executeEnvironmentWithServices");async function vm(e){let t=lr.parse(e.operation);return kr(e,{candidate:Jo,controller:i(async r=>Ft.parse(await Jo({...r,exportName:t,maxResultBytes:1572864,deterministic:!0,errorPrefix:"environment"})),"controller")})}i(vm,"executeJavaScriptEnvironment");var vt=class extends Error{static{i(this,"JavaScriptEnvironmentActionError")}code;constructor(t){super(`environment_${t}`),this.code=t,this.name="JavaScriptEnvironmentActionError"}};async function Yc(e){let t=li(e.definition),r=ue(e.asset,t.module);if(!Number.isSafeInteger(e.seed))throw new Error("environment_seed_invalid");let n=e.seed;G(e.input,1048576),G(e.initialState,t.maxStateBytes);let o=structuredClone(e.input),s=structuredClone(e.initialState),a=e.execute??vm,c=new AbortController,d=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,l={},p=0,u=!1,m=!1,f=null,h=[],R=null;async function w(x,C){if(u||m)throw new Error("environment_closed");if(f)throw new Error("environment_operation_in_progress");d.throwIfAborted(),C&&(G(C,262144),C=structuredClone(C));let A=y(l),T=C?t.tools.find(v=>v.name===C.name):null;if(x==="step"){if(p>=t.maxSteps)throw new vt("step_budget_exhausted");p++}let P=i((v,I)=>h.push({sequence:h.length,operation:x,toolName:C?.name??null,arguments:C?structuredClone(C.arguments):null,observation:v,beforeStateHash:A,afterStateHash:y(l),error:I}),"record");try{if(C&&!T)throw new vt("unknown_tool");if(C&&T&&!Ya(T.inputSchema,C.arguments).valid)throw new vt("invalid_arguments");let v=t.executionServices?.filter(E=>E.operation===x&&(x!=="step"||E.toolName===C?.name)),I=a({source:r,operation:x,value:{input:o,initialState:s,seed:n,state:structuredClone(l),sequence:p,action:C?structuredClone(C):null},timeoutMs:Math.min(t.operationTimeoutMs,T?.timeoutMs??t.operationTimeoutMs),signal:d,...v?.length?{executionServices:v}:{}});f=I;let S=Ft.parse(await I);if(d.throwIfAborted(),G(S.state,t.maxStateBytes),G(S.observation,t.maxObservationBytes),(x==="collect"||T?.sideEffect==="read")&&y(S.state)!==A)throw new Error("environment_read_changed_state");l=structuredClone(S.state);let N=structuredClone(S.observation);return P(N,null),{state:structuredClone(l),observation:N}}catch(v){throw P(null,v instanceof Error?v.message:"environment_execution_failed"),v}finally{f=null}}i(w,"invoke");async function k(){return R||(m=!0,c.abort(new Error("environment_destroyed")),R=(async()=>{try{try{await f}catch{}await a({source:r,operation:"destroy",value:{input:o,initialState:s,seed:n,state:structuredClone(l),sequence:p,action:null},timeoutMs:t.operationTimeoutMs})}finally{l={},u=!0}})(),R)}i(k,"destroy");try{await w("create");let x=await w("reset"),C=y(l),A=i(()=>{if(u)throw new Error("environment_closed");return{definition:{id:t.id,revision:t.revision,contentHash:t.contentHash},inputHash:y(o),seed:n,initialStateHash:C,finalStateHash:y(l),state:structuredClone(l),events:structuredClone(h)}},"snapshot");return{definition:structuredClone(t),observation:x.observation,async step(T){return(await w("step",T)).observation},async collect(){let T=await w("collect");return{...A(),observation:T.observation}},snapshot:A,destroy:k}}catch(x){try{await k()}catch{}throw x}}i(Yc,"createJavaScriptEnvironmentSession");var Em=g.string().trim().min(1).max(500),Sm=g.string().regex(/^[a-f0-9]{64}$/),Ko=g.object({kind:g.literal("model"),id:g.string().trim().min(1).max(191),taskId:Em,admissionHash:Sm,model:tc,instructions:g.string().max(262144),harness:Ka.optional(),input:g.record(g.string(),g.unknown()),policyVisibleContext:g.record(g.string(),g.unknown()),timeoutMs:g.number().int().positive().max(36e5),environment:g.discriminatedUnion("kind",[g.object({kind:g.literal("text")}).strict(),g.object({kind:g.literal("javascript"),definition:di,asset:Ga,initialState:g.record(g.string(),g.unknown()),seed:g.number().int().safe()}).strict()])}).strict(),MT=g.discriminatedUnion("kind",[Ko,g.object({kind:g.literal("profile"),request:g.unknown()}).strict()]);var Qc=g.string().trim().min(1).max(200),JT=g.object({receiptId:Qc,taskId:Qc,seed:g.string(),request:Ko}).strict(),M=class extends Error{constructor(r,n,o=409){super(n);this.code=r;this.status=o}code;status;static{i(this,"LocalExperimentError")}};async function _o(e,t=fn,r=!1){if(e.kind==="hosted_harness")return _o({kind:"hosted_chat",modelId:e.modelId,maxOutputTokens:4096,temperature:0,topP:1},t);if(e.kind!=="hosted_chat")throw new M("local_target_not_qualified","Select an explicit model target for local execution.",422);if(e.harness&&!r)throw new M("local_harness_not_qualified","This released Harness requires its native turn executor; it cannot run as a model-only case.",422);let n=await t();if(n.error)throw new M("local_model_catalog_unavailable",n.error,422);let o=n.models.find(m=>m.id===e.modelId);if(!o)throw new M("local_model_unavailable","The selected model is unavailable.",422);let s=Gc(o.raw),a=En(s),c=Gc(s.capabilities).samplingParameters===!0;if(!c&&(e.temperature!==0||e.topP!==1))throw new M("local_sampling_unsupported","This model uses provider-managed sampling. Custom temperature or top P requires an explicit supported capability.",422);let d=Kc(s.context_window),l=Kc(s.output_limit);if(e.maxOutputTokens>l)throw new M("local_model_output_limit","The model cannot accept the configured output limit.",422);let p={providerId:"openpond",modelId:e.modelId,maxOutputTokens:e.maxOutputTokens,...c?{temperature:e.temperature,topP:e.topP}:{},messages:e.messages??[]},u=(d*Math.max(a.inputUsdPerMillionTokens,a.cachedInputUsdPerMillionTokens)+e.maxOutputTokens*a.outputUsdPerMillionTokens)/1e6;if(!(u>0))throw new M("local_model_charge_unknown","The model must publish an enforceable positive request ceiling.",422);return{model:{...p,configurationHash:y({configuration:p,contextWindow:d,outputLimit:l,pricing:a})},pricing:a,maximumChargeUsd:u}}i(_o,"prepareLocalExperimentModel");function $T(e){let t=e.admission.streamFactory?.(e)??e.admission.stream??e.stream??hn;return async function*(r){if(!r.requestId)throw new M("local_request_identity_missing","Every local model dispatch requires a stable request identity.");let n=e.admission.model;if(r.model!==n.modelId||r.maxTokens!==n.maxOutputTokens||r.temperature!==n.temperature||r.topP!==n.topP)throw new M("local_model_configuration_conflict","The native model request changed its admitted model, output limit or sampling configuration.",422);let o=wr();o?.assertExecution(e.executionId);let s={teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,requestId:r.requestId};await e.store.reserveLocalCharge({...s,caseId:e.caseId,maximumUsd:e.admission.maximumChargeUsd}),r.signal?.aborted&&(await e.store.settleLocalCharge({...s,costUsd:null,usage:null,notDispatched:!0}),r.signal.throwIfAborted());try{await e.store.markLocalChargeDispatched(s.teamId,s.id,s.requestId,s.ownerId)}catch(p){throw o&&await e.store.settleLocalCharge({...s,costUsd:null,usage:null,notDispatched:!0}),p}await e.store.appendLocalExperimentEvent({...s,caseId:e.caseId,type:"model.dispatch",payload:{requestId:s.requestId,model:r.model,messages:r.messages}});let a=null,c=!1,d=!1,l;try{for await(let p of t(r)){d=!0,p.type==="usage"&&(a=p.usage),p.type==="finish"&&(c=!0);let u=p.type==="text_delta"?{requestId:s.requestId,text:p.text}:p.type==="tool_call_delta"?{requestId:s.requestId,toolCalls:p.toolCalls}:p.type==="usage"?{requestId:s.requestId,usage:Ze(p.usage)}:p.type==="finish"?{requestId:s.requestId,finishReason:p.finishReason}:null;u&&await e.store.appendLocalExperimentEvent({...s,caseId:e.caseId,type:`model.${p.type}`,payload:u}),yield p}}catch(p){throw!d&&p instanceof Qt&&p.executionId===s.id&&p.requestId===s.requestId&&(l=p),p}finally{let p=Ze(a),u=e.admission.pricing&&c&&p.promptTokens!==null&&p.completionTokens!==null?nt(a,e.admission.pricing):null;await e.store.settleLocalCharge({...s,costUsd:u,confirmedTransportNotInvoked:l,usage:a===null?null:{promptTokens:p.promptTokens,completionTokens:p.completionTokens,cachedPromptTokens:p.cachedPromptTokens,uncachedPromptTokens:p.uncachedPromptTokens}})}}}i($T,"createLocalBudgetedModelStream");function Gc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(Gc,"record");function Kc(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new M("local_model_bound_unknown","The model catalog is missing an enforceable context/output bound.",422);return e}i(Kc,"positive");import{AsyncLocalStorage as xm}from"node:async_hooks";import bm from"node:path";var _c=new xm;function $c(){return _c.getStore()}i($c,"currentAdvancedRefinerBoundary");function dv(e){let t=fi(bm.join(e.storeDir,"library","harnesses","advanced-refiner-paid-calls.sqlite"));t.exec(`CREATE TABLE IF NOT EXISTS advanced_refiner_budgets(id TEXT PRIMARY KEY,actor_id TEXT NOT NULL,team_id TEXT NOT NULL,pin_hash TEXT NOT NULL,maximum_spend REAL NOT NULL,maximum_steps INTEGER NOT NULL,expires_at TEXT NOT NULL);
|
|
@@ -0,0 +1,9 @@
|
|
|
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 as o}from"./chunk-FTQLQJQV.js";import{createHash as Te}from"node:crypto";function W(n){if(n===null||typeof n=="boolean"||typeof n=="string")return n;if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("Canonical JSON cannot encode a non-finite number.");return n}if(Array.isArray(n))return n.map(W);if(typeof n=="object"){let t={};for(let r of Object.keys(n).sort()){let i=n[r];i!==void 0&&(t[r]=W(i))}return t}throw new Error(`Canonical JSON cannot encode ${typeof n}.`)}o(W,"canonicalJson");function R(n){return Te("sha256").update(JSON.stringify(W(n)),"utf8").digest("hex")}o(R,"canonicalHash");function rt(n){if(!n.maxContextTokens||!n.usableContextTokens)return{shouldCompact:!1,projectedTokens:n.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(n.triggerPercent??85)/100)),r=Math.max(1,Math.floor(n.usableContextTokens*t));return{shouldCompact:n.projectedTokens>=r,projectedTokens:n.projectedTokens,thresholdTokens:r,usableContextTokens:n.usableContextTokens,maxContextTokens:n.maxContextTokens,tokenSource:"heuristic"}}o(rt,"agentCompactionDecision");async function it(n){await n.started();try{return await n.compact()}catch(t){throw await n.failed(t),t}}o(it,"runAgentCompaction");async function nt(n){let t=n.host.projectEvents(n.events),r=n.host.selectEvents(t,n.maxContextTokens),{summaryEvents:i,preservedEvents:s,preservedEventIds:c}=r;if(i.length===0)throw new Error("There is not enough prior context to compact.");let l=n.host.normalizeRecords(i),d=n.host.normalizeRecords(s),m=n.host.buildFileLedger(n.host.normalizeRecords(t)),h=n.host.serializeRecords(l,n.host.inputCharBudget(n.maxContextTokens));if(!h.text.trim())throw new Error("There is not enough prior context to compact.");let y=n.host.buildSummaryMessages({serializedHistory:h.text,fileLedger:m}),b=Date.now(),v=(await n.host.streamSummary({model:n.model,messages:y,signal:n.signal})).trim(),I=Date.now()-b;if(!v)throw new Error("Compaction summary was empty.");let g=n.host.estimateProjection({events:t,preservedEvents:s,summary:v}),f=n.host.createMetrics({sourceEvents:t.length,summarizedEvents:i.length,preservedEvents:s.length,sourceRecords:h.sourceRecordCount,includedRecords:h.includedRecordCount,omittedRecords:h.omittedRecordCount,preservedRecords:d.length,truncatedRecords:h.truncatedRecordCount,summaryInputTruncated:h.inputTruncated,sourceSelectionStrategy:h.selectionStrategy,summaryInputChars:h.inputChars,retainedTailTokens:r.retainedTailTokens,retainedTailBudgetTokens:r.retainedTailBudgetTokens,finalProviderContextTokens:g.inputTokensAfter,durationMs:I,fileLedgerEntries:m.length,splitTurnId:r.splitTurnId});return{summary:v,model:n.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:n.host.lastTurnId(t),preservedFromEventId:s[0]?.id??null,preservedEventIds:c,preservedResourceRefs:n.host.durableResourceRefs(n.events),sourceEventCount:i.length,preservedEventCount:s.length,fileLedger:m,inputTokensBefore:g.inputTokensBefore,inputTokensAfter:g.inputTokensAfter,maxContextTokens:n.maxContextTokens,tokenSource:"heuristic",metrics:f}}o(nt,"runAgentCompactionProgram");var Ce=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"]),qe=e.object({sequence:e.number().int().nonnegative(),name:Ce,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 lt(n){return R(qe.parse(n))}o(lt,"canonicalEventHash");var A="2026-09-20",mt=["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","experiments/executeCase","experiments/cancelCase","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"],Z=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(),ee=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),F=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),J=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(),ht=e.union([Z,ee,F,J]),Pe=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(),B=class{static{o(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let r=ee.safeParse(t);if(r.success&&!("id"in t)){if(r.data.method==="initialized"){if(!this.#t)throw new T(-32002,"initialize must be called first");this.#r=!0}return null}let i=Z.safeParse(t);if(!i.success)return Y(null,-32600,"Invalid Request",i.error.flatten());let s=i.data;try{let c=await this.#i(s.method,s.params);return{jsonrpc:"2.0",id:s.id,result:c}}catch(c){let l=c instanceof T?c:new T(-32603,c instanceof Error?c.message:String(c));return Y(s.id,l.code,l.message,l.data)}}async#i(t,r){if(t==="initialize"){let i=Pe.parse(r);if(i.protocolVersion!==A)throw new T(-32001,"Incompatible agent protocol version",{requested:i.protocolVersion,supported:A});return this.#t=i,{protocolVersion:A,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new T(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(r);case"thread/start":return this.#e.threadStart(r);case"thread/resume":return this.#e.threadResume(r);case"thread/read":return this.#e.threadRead(r);case"turn/start":return this.#e.turnStart(r);case"turn/steer":return this.#e.turnSteer(r);case"task/inbox":return this.#e.taskInbox(r);case"task/queue":return this.#e.taskQueue(r);case"task/inputUpdate":return this.#e.taskInputUpdate(r);case"turn/interrupt":return this.#e.turnInterrupt(r);case"approval/resolve":return this.#e.approvalResolve(r);case"userInput/resolve":return this.#e.userInputResolve(r);case"profile/workflows":return this.#e.profileWorkflows(r);case"profile/evaluations":return this.#e.profileEvaluations(r);case"profile/trainingSource":return this.#e.profileTrainingSource(r);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(r);case"profile/evaluations/run":return this.#e.profileEvaluationRun(r);case"experiments/executeCase":{if(!this.#e.experimentExecuteCase)throw new Error("Experiment execution is unavailable in this runtime.");return this.#e.experimentExecuteCase(r)}case"experiments/cancelCase":{if(!this.#e.experimentCancelCase)throw new Error("Experiment cancellation is unavailable in this runtime.");return this.#e.experimentCancelCase(r)}case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(r);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(r);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(r);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(r);case"profile/evaluations/report":return this.#e.profileEvaluationReport(r);case"harness/inspect":return this.#e.harnessInspect(r);case"harness/proposalReview":return this.#e.harnessProposalReview(r);case"harness/review":return this.#e.harnessReview(r);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(r);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(r);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(r);case"harness/validate":return this.#e.harnessValidate(r);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(r);case"harness/diff":return this.#e.harnessDiff(r);case"harness/rollback":return this.#e.harnessRollback(r);case"refiner/inspect":return this.#e.refinerInspect(r);case"refiner/update":return this.#e.refinerUpdate(r);case"refiner/activate":return this.#e.refinerActivate(r);case"refiner/rollback":return this.#e.refinerRollback(r);default:throw new T(-32601,`Method not found: ${t}`)}}},T=class extends Error{static{o(this,"JsonRpcDispatchError")}code;data;constructor(t,r,i){super(r),this.code=t,this.data=i}};function Y(n,t,r,i){return{jsonrpc:"2.0",id:n,error:{code:t,message:r,...i===void 0?{}:{data:i}}}}o(Y,"jsonRpcError");var te=class{static{o(this,"AgentRpcClient")}#e;#t;constructor(t){this.#e=t.request.bind(t),this.#t=t.notify.bind(t)}async initialize(t,r={}){let i=await this.#e("initialize",{protocolVersion:A,client:t,capabilities:r});return await this.#t("initialized"),i}capabilities=o((t={})=>this.#e("runtime/capabilities",t),"capabilities");threadStart=o(t=>this.#e("thread/start",t),"threadStart");threadResume=o(t=>this.#e("thread/resume",t),"threadResume");threadRead=o(t=>this.#e("thread/read",t),"threadRead");turnStart=o(t=>this.#e("turn/start",t),"turnStart");turnSteer=o(t=>this.#e("turn/steer",t),"turnSteer");taskInbox=o(t=>this.#e("task/inbox",t),"taskInbox");taskQueue=o(t=>this.#e("task/queue",t),"taskQueue");taskInputUpdate=o(t=>this.#e("task/inputUpdate",t),"taskInputUpdate");turnInterrupt=o(t=>this.#e("turn/interrupt",t),"turnInterrupt");approvalResolve=o(t=>this.#e("approval/resolve",t),"approvalResolve");userInputResolve=o(t=>this.#e("userInput/resolve",t),"userInputResolve");profileWorkflows=o(t=>this.#e("profile/workflows",t),"profileWorkflows");profileEvaluations=o(t=>this.#e("profile/evaluations",t),"profileEvaluations");profileEvaluationPrepare=o(t=>this.#e("profile/evaluations/prepare",t),"profileEvaluationPrepare");profileEvaluationRun=o(t=>this.#e("profile/evaluations/run",t),"profileEvaluationRun");profileEvaluationRunSuite=o(t=>this.#e("profile/evaluations/runSuite",t),"profileEvaluationRunSuite");profileEvaluationExecuteCase=o(t=>this.#e("profile/evaluations/executeCase",t),"profileEvaluationExecuteCase");profileEvaluationExecuteRun=o(t=>this.#e("profile/evaluations/executeRun",t),"profileEvaluationExecuteRun");profileEvaluationCompare=o(t=>this.#e("profile/evaluations/compare",t),"profileEvaluationCompare");experimentExecuteCase=o(t=>this.#e("experiments/executeCase",t),"experimentExecuteCase");experimentCancelCase=o(t=>this.#e("experiments/cancelCase",t),"experimentCancelCase");harnessInspect=o((t={})=>this.#e("harness/inspect",t),"harnessInspect");harnessProposalReview=o((t={})=>this.#e("harness/proposalReview",t),"harnessProposalReview");harnessReview=o((t={})=>this.#e("harness/review",t),"harnessReview");harnessAcceptEvaluationReview=o((t={})=>this.#e("harness/acceptEvaluationReview",t),"harnessAcceptEvaluationReview");harnessMaterializeEvaluationTaskset=o((t={})=>this.#e("harness/materializeEvaluationTaskset",t),"harnessMaterializeEvaluationTaskset");harnessRunEvaluationBaseline=o((t={})=>this.#e("harness/runEvaluationBaseline",t),"harnessRunEvaluationBaseline");harnessValidate=o((t={})=>this.#e("harness/validate",t),"harnessValidate");harnessBackgroundReview=o((t={})=>this.#e("harness/backgroundReview",t),"harnessBackgroundReview");harnessDiff=o((t={})=>this.#e("harness/diff",t),"harnessDiff");harnessRollback=o((t={})=>this.#e("harness/rollback",t),"harnessRollback");refinerInspect=o(t=>this.#e("refiner/inspect",t),"refinerInspect");refinerUpdate=o(t=>this.#e("refiner/update",t),"refinerUpdate");refinerActivate=o(t=>this.#e("refiner/activate",t),"refinerActivate");refinerRollback=o(t=>this.#e("refiner/rollback",t),"refinerRollback")};var G=e.object({caseId:e.string().trim().min(1).max(191),admissionHash:e.string().regex(/^[a-f0-9]{64}$/),definitionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),operation:e.enum(["create","reset","step","collect","destroy"]),value:e.record(e.string(),e.unknown()),timeoutMs:e.number().int().min(1).max(3e4)}).strict();var u=e.string().trim().min(1).max(200),$=e.string().trim().min(1).max(32e3),z=e.number().int().nonnegative(),re=e.object({id:u,sessionId:u,senderSessionId:u.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:$,payload:e.record(e.string(),e.unknown()),idempotencyKey:u,replyTo:u.nullable(),expectedTurnId:u.nullable()}).strict(),Ae=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:$}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:u}).strict()]),ie=e.object({id:u,sessionId:u,turnId:u,targetSessionId:u.nullable(),targetTurnId:u.nullable(),targetInputId:u.nullable(),afterSequence:z,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),ne=e.record(e.string(),e.unknown()),ze=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),He=e.object({parentSessionId:u.nullable().optional(),childSessionId:u.nullable().optional(),status:e.array(ze).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),se=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:u}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:u}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:u}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:u,afterSequence:z}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:u,turnId:u,ownerId:u,areas:e.array($).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:u}).strict(),e.object({action:e.literal("admitTaskInput"),input:re}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(re).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:u,error:$}).strict(),e.object({action:e.literal("getTaskInput"),id:u}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:u,query:e.object({afterSequence:z.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:u,inputId:u,change:Ae}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:u,turnId:u,afterSequence:z}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:u,afterSequence:z}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:u,turnId:u,ownerId:u,requestId:u}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:u,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:u}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:ie}).strict(),e.object({action:e.literal("settleTaskWait"),id:u,state:ie.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:u,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:ne,turnId:u}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:u,inputId:u}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:ne}).strict(),e.object({action:e.literal("getSubagentRun"),id:u}).strict(),e.object({action:e.literal("listSubagentRuns"),query:He}).strict()]);var H=e.string().trim().min(1).max(191),oe=e.object({createdAt:e.string().min(1),id:H}).strict(),ae=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),ce=e.discriminatedUnion("action",[e.object({action:e.literal("active_release"),workspaceId:H}).strict(),e.object({action:e.literal("put_artifact"),workspaceId:H,kind:ae,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:H,kind:ae,before:oe.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:H,before:oe.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var w=e.string().trim().min(1).max(240),le=e.string().regex(/^[a-f0-9]{64}$/),ue=e.enum(["run_overlay","observation","trigger_decision","route_decision","proposal","targeted_validation","apply_receipt","refiner_outcome"]),de=e.object({createdAt:e.string().datetime(),id:w}).strict(),pe=e.discriminatedUnion("action",[e.object({action:e.literal("artifact_put"),workspaceId:w,kind:ue,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:w,kind:ue,before:de.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("pending_page"),workspaceId:w,before:de.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("workspace_get"),workspaceId:w}).strict(),e.object({action:e.literal("background_get"),workspaceId:w}).strict(),e.object({action:e.literal("overlay_get"),runId:w}).strict(),e.object({action:e.literal("overlay_freeze"),runId:w,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:w,sessionId:w,key:w}).strict(),e.object({action:e.literal("memory_page"),workspaceId:w,sessionId:w,before:e.object({updatedAt:e.string().datetime(),key:w}).strict().nullable(),limit:e.number().int().min(1).max(20),includeDeleted:e.boolean()}).strict(),e.object({action:e.literal("memory_write"),sessionId:w,input:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("release_get"),contentHash:le}).strict(),e.object({action:e.literal("release_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("session_get"),sessionId:w}).strict(),e.object({action:e.literal("turn_get"),turnId:w}).strict(),e.object({action:e.literal("turn_page"),sessionId:w,before:e.number().int().positive().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_page"),turnId:w,afterSequence:e.number().int().nonnegative(),names:e.array(w).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:w,expectedHash:le,snapshot:e.record(e.string(),e.unknown())}).strict()]);var j=e.string().trim().min(1).max(200),me=e.string().regex(/^[a-f0-9]{64}$/),Me=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()}),he=e.object({id:j,title:e.string().trim().min(1).max(240),sourceTaskId:j,sourceTurnId:j,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:me,validation:e.array(Me).max(32)}).strict(),fe=e.object({sessionId:j,turnId:j,output:he}).strict(),be=e.object({uploadId:j,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:me,contentsBase64:e.string().min(1).max(131072)}).strict(),ge=e.object({uploadId:j}).strict(),Ve=he.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),we=e.object({sessionId:j,turnId:j,output:Ve,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var M=e.string().trim().min(1).max(200),Ue=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:M.optional(),payload:e.unknown().optional(),processId:M.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((n,t)=>{n.type!=="create"&&!n.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),n.type==="create"&&n.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),n.type==="process_get"&&!n.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),ve=e.object({action:Ue}).strict(),xe=e.object({sessionId:M,turnId:M,name:M}).strict();var p=1,a=e.string().trim().min(1).max(191),C=e.number().int().min(1).max(200),Ot=e.object({teamId:a,ownerUserId:a,workspaceId:a,conversationId:a,turnId:a,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),Ie=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile-evaluations/grade"),params:e.object({action:e.enum(["upload","execute"]),callId:a,sessionId:a,turnId:a,sha256:e.string().regex(/^[a-f0-9]{64}$/),sizeBytes:e.number().int().positive().max(2e7),timeoutMs:e.number().int().positive().max(3e5),offset:e.number().int().nonnegative().max(2e7).optional(),contentsBase64:e.string().max(131072).optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile-evaluations/sandbox"),params:e.object({sessionId:a,turnId:a,action:e.enum(["upload","exec","read","stop"]),area:e.enum(["policy","runtime"]).optional(),path:e.string().min(1).max(4096).optional(),sha256:e.string().regex(/^[a-f0-9]{64}$/).optional(),sizeBytes:e.number().int().min(0).max(1e7).optional(),offset:e.number().int().min(0).max(1e7).optional(),contentsBase64:e.string().max(131072).optional(),command:e.string().min(1).max(2e4).optional(),stdin:e.string().max(12e4).optional(),cwd:e.string().max(4096).optional(),timeoutMs:e.number().int().min(1).max(18e4).optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/list"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/read"),params:e.object({fileId:a,revision:e.number().int().min(1),offset:e.number().int().min(0).max(1e7).optional(),maxChars:e.number().int().min(1).max(1e5).optional(),firstPage:e.number().int().min(1).max(1e3).optional(),pageCount:e.number().int().min(1).max(10).optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/readBytes"),params:e.object({sessionId:a,turnId:a,fileId:a,revision:e.number().int().positive(),sha256:e.string().regex(/^[a-f0-9]{64}$/),sizeBytes:e.number().int().min(1).max(1e7),offset:e.number().int().min(0).max(1e7)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile.externalDataset.authorize"),params:e.object({bindingHash:e.string().regex(/^[a-f0-9]{64}$/),manifestHash:e.string().regex(/^[a-f0-9]{64}$/).optional(),taskId:a.optional(),seed:e.string().min(1).max(500).optional()}).strict().refine(n=>!!n.taskId==!!n.seed,"Case authority requires both task and seed.")}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/environment"),params:G}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/policy"),params:e.object({caseId:a,admissionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),messages:e.array(e.record(e.string(),e.unknown())).max(2e3),tools:e.array(e.record(e.string(),e.unknown())).max(200)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("sandbox/request"),params:ve}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("embedding/authorize"),params:xe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/begin"),params:fe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/chunk"),params:be}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/complete"),params:ge}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/saveSandboxFile"),params:we}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/get"),params:e.object({runId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/put"),params:e.object({runId:a,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:a,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(p),requestId:a,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:a,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:a,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:C}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:a,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/state/read"),params:e.object({workspaceId:a,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:a.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,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:a}).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:a}).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(p),requestId:a,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,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:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:a,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:a,workspaceId:a,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("task-inbox/execute"),params:se}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/review/execute"),params:pe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("refiner/execute"),params:e.object({action:ce}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:a}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:a.nullable(),targetKind:a.nullable(),targetId:a.nullable(),state:e.array(a).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:a}).strict().nullable(),limit:C}).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(p),requestId:a,operation:e.literal("approval/get"),params:e.object({approvalId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,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(p),requestId:a,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:a.optional(),turnId:a.optional(),provider:a.optional(),model:a.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:a}).strict().nullable(),limit:C}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/get"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/page"),params:e.object({afterId:a.nullable(),limit:C}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/put"),params:e.object({sessionId:a,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/count"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:a,key:e.enum(["messageId","fromRunId"]),value:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/get"),params:e.object({turnId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/put"),params:e.object({sessionId:a,turnId:a,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/latest"),params:e.object({sessionId:a,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/page"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:C}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("thread/turnPage"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:C}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/page"),params:e.object({sessionId:a.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:C,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:a}).strict()}).strict()]),Bt=e.object({contractVersion:e.literal(p),operations:e.array(e.enum(["experiment/policy","experiment/environment","sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","output/list","output/read","output/readBytes","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","profile-evaluations/sandbox","profile-evaluations/grade","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(50),allowedTools:e.array(a).max(128),maxPageSize:C,maxRequestBytes:e.number().int().min(1).max(8388608),maxInFlight:e.number().int().min(1).max(64)}).strict();var ye=class{static{o(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,r=15e3){let i=Ie.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 s=`host-storage:${this.#r++}`,c={jsonrpc:"2.0",id:s,method:"host/storage",params:i},l=i.operation==="experiment/policy"||i.operation==="experiment/environment";if(Buffer.byteLength(JSON.stringify(c))>(l?8388608:256e3))throw new Error("Host storage request is too large.");let d=new Promise((m,h)=>{let y=i.operation==="sandbox/request"||l?3e5:6e4,b=setTimeout(()=>{this.#e.delete(s),h(new Error("Host storage request timed out."))},Math.max(1,Math.min(y,r)));this.#e.set(s,{resolve:m,reject:h,timer:b,maxResponseBytes:i.operation==="experiment/environment"?16e5:1e6})});try{await this.#t(c)}catch(m){let h=this.#e.get(s);h&&(clearTimeout(h.timer),this.#e.delete(s),h.reject(m instanceof Error?m:new Error(String(m))))}return d}accept(t){let r=F.safeParse(t),i=r.success?null:J.safeParse(t),s=r.success?r.data:i?.success?i.data:null;if(!s||typeof s.id!="string"||!s.id.startsWith("host-storage:"))return!1;let c=this.#e.get(s.id);return c?(clearTimeout(c.timer),this.#e.delete(s.id),Buffer.byteLength(JSON.stringify(s))>c.maxResponseBytes?(c.reject(new Error("Host storage response is too large.")),!0):("error"in s?c.reject(new Error(`Host storage request failed: ${s.error.message}`)):c.resolve(s.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 Oe}from"node:events";import{createInterface as Be}from"node:readline";async function Qt(n){let t=null,r=Promise.resolve(),i=[],s=o(g=>(r=r.then(async()=>{n.writable.write(`${JSON.stringify(g)}
|
|
3
|
+
`)||await Oe(n.writable,"drain")}),r),"write");n.hostStorageClient?.bind(g=>s(g));let c=o(()=>{if(!(!t?.initialized||i.length===0))for(let g of i.splice(0))s(g)},"flushPendingNotifications"),l,d=new Set,m=Be({input:n.readable,crlfDelay:1/0}),h=[],y=!1,b=null,v=o(async g=>{let f=t;if(!f)throw new Error("Agent runtime dispatcher is unavailable.");let E=(async()=>{let X=await f.handle(g);X&&await s(X),c()})(),Q=g&&typeof g=="object"&&"method"in g?g.method:null;if(Q==="initialize"||Q==="initialized"){await E;return}d.add(E),E.finally(()=>d.delete(E))},"dispatch"),I=(async()=>{let g=typeof n.host=="function"?await n.host():n.host;for(t=new B(g),l=g.subscribe?.(f=>{if(!t?.initialized){i.push(f);return}s(f)});h.length>0;)await v(h.shift());y=!0})().catch(g=>{b=g,m.close()});try{for await(let g of m){if(!g.trim())continue;if(Buffer.byteLength(g,"utf8")>1e6){await s({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let f;try{f=JSON.parse(g)}catch{await s({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!n.hostStorageClient?.accept(f))if(y)await v(f);else if(h.length>=64){let E=f&&typeof f=="object"&&"id"in f?f.id:null;(typeof E=="string"||typeof E=="number")&&await s({jsonrpc:"2.0",id:E,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else h.push(f)}if(await I,b)throw b;await Promise.all(d),await r}finally{n.hostStorageClient?.close(),l?.()}}o(Qt,"runAgentJsonlServer");var N=e.object({threadId:e.string().trim().min(1)}).passthrough(),$e=N.extend({includeHistory:e.boolean().optional()}),Ne=e.object({session:e.unknown()}).strict(),V=N.extend({input:e.unknown()}),Le=V.extend({idempotencyKey:e.string().trim().min(1).max(200)}),De=V.extend({inputId:e.string().trim().min(1)}),We=N.extend({reason:e.string().trim().min(1).optional()}),Fe=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function sr(n){let t=o(async(i,s,c)=>{let l=performance.now();n.telemetry?.({method:i,phase:"started",threadId:s,durationMs:null,errorClass:null});try{let d=await c();return n.telemetry?.({method:i,phase:"completed",threadId:s,durationMs:performance.now()-l,errorClass:null}),d}catch(d){throw n.telemetry?.({method:i,phase:"failed",threadId:s,durationMs:performance.now()-l,errorClass:d instanceof Error?d.name:"UnknownError"}),d}},"run"),r=o(async(i,s="thread/read")=>{let{threadId:c,includeHistory:l}=$e.parse(i);return t(s,c,async()=>{if(l===!1)return{thread:await n.readThread(c),turns:[],events:[]};let[d,m,h]=await Promise.all([n.readThread(c),n.listTurns(c),n.listEvents(c)]);return{thread:d,turns:m,events:h}})},"threadRead");return{capabilities:o(i=>t("runtime/capabilities",null,()=>n.capabilities(i)),"capabilities"),threadStart:o(async i=>t("thread/start",null,async()=>({thread:await n.createThread(Ne.parse(i).session)})),"threadStart"),threadResume:o(i=>r(i,"thread/resume"),"threadResume"),threadRead:r,turnStart:o(async i=>{let s=V.parse(i);return t("turn/start",s.threadId,async()=>({turn:await n.startTurn(s.threadId,s.input)}))},"turnStart"),turnSteer:o(async i=>{let s=V.parse(i);return t("turn/steer",s.threadId,async()=>({receipt:await n.steerTurn(s.threadId,s.input)}))},"turnSteer"),taskInbox:o(async i=>{let{threadId:s}=N.parse(i);return t("task/inbox",s,()=>n.readTaskInbox(s))},"taskInbox"),taskQueue:o(async i=>{let s=Le.parse(i);return t("task/queue",s.threadId,()=>n.queueTaskInput(s.threadId,s.input,s.idempotencyKey))},"taskQueue"),taskInputUpdate:o(async i=>{let s=De.parse(i);return t("task/inputUpdate",s.threadId,()=>n.updateTaskInput(s.threadId,s.inputId,s.input))},"taskInputUpdate"),turnInterrupt:o(async i=>{let s=We.parse(i);return t("turn/interrupt",s.threadId,async()=>({turn:await n.interruptTurn(s.threadId,s.reason)}))},"turnInterrupt"),approvalResolve:o(async i=>{let s=Fe.parse(i);return t("approval/resolve",null,async()=>({approval:await n.resolveApproval(s.approvalId,s.input)}))},"approvalResolve"),userInputResolve:o(async i=>{let s=V.parse(i);return t("userInput/resolve",s.threadId,async()=>(n.isTurnActive(s.threadId)&&await n.waitForTurnSettlement(s.threadId),{turn:await n.startTurn(s.threadId,s.input)}))},"userInputResolve"),profileWorkflows:o(()=>t("profile/workflows",null,()=>n.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:o(i=>t("profile/evaluations",null,()=>n.listProfileEvaluations(i)),"profileEvaluations"),profileTrainingSource:o(()=>t("profile/trainingSource",null,()=>n.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:o(i=>t("profile/evaluations/prepare",null,()=>n.prepareProfileEvaluationRun(i)),"profileEvaluationPrepare"),profileEvaluationRun:o(i=>t("profile/evaluations/run",null,()=>n.runPreparedProfileEvaluation(i)),"profileEvaluationRun"),...n.executeExperimentCase?{experimentExecuteCase:o(i=>t("experiments/executeCase",null,()=>n.executeExperimentCase(i)),"experimentExecuteCase")}:{},...n.cancelExperimentCase?{experimentCancelCase:o(i=>t("experiments/cancelCase",null,()=>n.cancelExperimentCase(i)),"experimentCancelCase")}:{},profileEvaluationRunSuite:o(i=>t("profile/evaluations/runSuite",null,()=>n.runProfileEvaluationSuite(i)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:o(i=>t("profile/evaluations/executeCase",null,()=>n.executeProfileEvaluationCase(i)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:o(i=>t("profile/evaluations/executeRun",null,()=>n.executeProfileEvaluationRun(i)),"profileEvaluationExecuteRun"),profileEvaluationCompare:o(i=>t("profile/evaluations/compare",null,()=>n.compareProfileEvaluationRuns(i)),"profileEvaluationCompare"),profileEvaluationReport:o(i=>t("profile/evaluations/report",null,()=>n.buildProfileEvaluationReport(i)),"profileEvaluationReport"),harnessInspect:o(()=>t("harness/inspect",null,()=>n.inspectHarness()),"harnessInspect"),harnessProposalReview:o(i=>t("harness/proposalReview",null,()=>n.reviewHarnessProposal(i)),"harnessProposalReview"),harnessReview:o(i=>t("harness/review",null,()=>n.reviewHarness(i)),"harnessReview"),harnessAcceptEvaluationReview:o(i=>t("harness/acceptEvaluationReview",null,()=>n.acceptHarnessEvaluationReview(i)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:o(i=>t("harness/materializeEvaluationTaskset",null,()=>n.materializeHarnessEvaluationTaskset(i)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:o(i=>t("harness/runEvaluationBaseline",null,()=>n.runHarnessEvaluationBaseline(i)),"harnessRunEvaluationBaseline"),harnessValidate:o(()=>t("harness/validate",null,()=>n.validateHarness()),"harnessValidate"),harnessBackgroundReview:o(i=>t("harness/backgroundReview",null,()=>n.updateHarnessBackgroundReview(i)),"harnessBackgroundReview"),harnessDiff:o(i=>t("harness/diff",null,()=>n.diffHarness(i)),"harnessDiff"),harnessRollback:o(i=>t("harness/rollback",null,()=>n.rollbackHarness(i)),"harnessRollback"),refinerInspect:o(()=>t("refiner/inspect",null,()=>n.inspectRefiner()),"refinerInspect"),refinerUpdate:o(i=>t("refiner/update",null,()=>n.updateRefiner(i)),"refinerUpdate"),refinerActivate:o(i=>t("refiner/activate",null,()=>n.activateRefiner(i)),"refinerActivate"),refinerRollback:o(i=>t("refiner/rollback",null,()=>n.rollbackRefiner(i)),"refinerRollback"),subscribe:n.subscribeEvents&&n.eventNotification?i=>n.subscribeEvents(s=>i(n.eventNotification(s))):void 0}}o(sr,"createAgentRuntimeService");var q=e.string().regex(/^[a-f0-9]{64}$/),Je=e.object({harnessReleaseHash:q,instructionsHash:q,skillHashes:e.record(e.string(),q),agentAssetHashes:e.record(e.string(),q),toolCatalogHash:q,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Ge=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:q,toolCatalogHash:q,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function ur(n){return R(Je.parse(n))}o(ur,"effectiveSurfaceHash");function dr(n){return R(Ge.parse(n))}o(dr,"checkpointHash");function pr(n){return[n.system,...n.harnessInstructions,...n.skillInstructions,...n.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`)}o(pr,"materializeAgentPrompt");function gr(n){let t=new Map;for(let l of n){let d=l.name.trim();if(!d)throw new Error("Agent tool names cannot be empty.");if(t.has(d))throw new Error(`Duplicate agent tool: ${d}.`);if(!l.unavailableReason&&!l.execute)throw new Error(`Agent tool ${d} is declared as available without an executor.`);t.set(d,{...l,name:d})}let r=[...t.values()].sort((l,d)=>l.name.localeCompare(d.name)),i=r.filter(l=>!l.unavailableReason).map(l=>({name:l.name,description:l.description,inputSchema:e.toJSONSchema(l.inputSchema,{target:"draft-7",unrepresentable:"any"})})),s=r.map(l=>({name:l.name,displayLabel:l.displayLabel??l.name,placement:l.placement,available:!l.unavailableReason,unavailableReason:l.unavailableReason??null})),c=R({modelTools:i,capabilities:s});return{byName:t,tools:r,modelTools:i,capabilities:s,hash:c}}o(gr,"createAgentToolCatalog");async function wr(n,t){let r=n.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);return r.execute(r.inputSchema.parse(t.arguments),t.context)}o(wr,"executeAgentTool");function vr(n){let t=new Set,r=[...n].map(c=>{let l=c.name.trim();if(!l)throw new Error("Agent tool names cannot be empty.");if(t.has(l))throw new Error(`Duplicate agent tool: ${l}.`);if(t.add(l),!c.unavailableReason&&!c.executorAvailable)throw new Error(`Agent tool ${l} is declared as available without an executor.`);return{...c,name:l}}).sort((c,l)=>c.name.localeCompare(l.name)),i=r.filter(c=>!c.unavailableReason).map(c=>({name:c.name,description:c.description,inputSchema:c.inputSchema})),s=r.map(c=>({name:c.name,displayLabel:c.displayLabel??c.name,placement:c.placement,available:!c.unavailableReason,unavailableReason:c.unavailableReason??null}));return{byName:new Map(r.map(c=>[c.name,c])),tools:r,modelTools:i,capabilities:s,hash:R({modelTools:i,capabilities:s})}}o(vr,"createAgentToolCatalogProjection");async function xr(n,t){let r=n.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let i=r.validateArguments?r.validateArguments(t.arguments):t.arguments;return r.execute(i,t.context)}o(xr,"executeProjectedAgentTool");var ke=class{static{o(this,"TaskSignals")}#e=new Map;notify(t){for(let r of[...this.#e.get(t)??[]])r()}subscribe(t,r){let i=this.#e.get(t);return i||this.#e.set(t,i=new Set),i.add(r),()=>{i.delete(r),i.size===0&&this.#e.delete(t)}}async wait(t){let r=o(()=>{},"wake"),i=0,s=o(()=>{i+=1,r()},"changed"),c=[...new Set(t.taskIds)].map(d=>this.subscribe(d,s)),l=setTimeout(s,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",s);try{for(;;){t.signal.throwIfAborted();let d=i,m=await t.read();if(m!==null)return m;if(Date.now()>=t.deadline)return null;i===d&&await new Promise(h=>{r=h,(i!==d||t.signal.aborted)&&h()})}}finally{clearTimeout(l),t.signal.removeEventListener("abort",s);for(let d of c)d()}}},je=class{static{o(this,"TaskSerialExecutor")}#e=new Map;async run(t,r){let s=(this.#e.get(t)??Promise.resolve()).then(r),c=s.then(()=>{},()=>{});this.#e.set(t,c);try{return await s}finally{this.#e.get(t)===c&&this.#e.delete(t)}}};var L=class extends Error{static{o(this,"AcpRpcError")}code;data;constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="AcpRpcError"}};import{execFile as Ke}from"node:child_process";function k(n,t){if(n.pid){if(process.platform==="win32"){Ke("taskkill",["/PID",String(n.pid),"/T",...t==="SIGKILL"?["/F"]:[]],{windowsHide:!0},()=>{});return}try{process.kill(-n.pid,t)}catch(r){if(r.code!=="ESRCH")throw r}}}o(k,"signalNativeProcess");import{spawn as Qe}from"node:child_process";import{StringDecoder as Xe}from"node:string_decoder";var K=8*1024*1024,D={outcome:{outcome:"cancelled"}};function P(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}o(P,"object");var _e=class{static{o(this,"AcpClient")}options;child=null;pending=new Map;sessions=new Set;activePrompts=new Set;permissions=new Map;nextId=1;buffer="";decoder=new Xe("utf8");initialized=null;updateQueue=Promise.resolve();stopped=!1;constructor(t){this.options=t}initialize(){return this.initialized?this.initialized:(this.initialized=this.connect(),this.initialized)}async connect(){if(this.stopped)throw new Error("ACP client is closed; reconnect with a new client.");let t=Qe(this.options.command,this.options.args,{cwd:this.options.cwd,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=t,t.stdout.on("data",r=>this.consume(this.decoder.write(r))),t.stderr.resume(),t.stdin.on("error",r=>this.fail(r)),t.on("error",r=>this.fail(r)),t.on("exit",(r,i)=>this.fail(new Error(`ACP agent exited (${i??r??"unknown"}).`)));try{let r=await this.request("initialize",{protocolVersion:1,clientInfo:{name:"openpond",title:"OpenPond",version:"1"},clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}});if(r.protocolVersion!==1)throw new Error(`Unsupported ACP protocol version: ${r.protocolVersion}`);return r}catch(r){throw await this.stop(),r}}async authenticate(t){let i=(await this.initialize()).authMethods?.find(s=>s.id===t);if(!i)throw new Error("The agent did not advertise this authentication method.");if(i.type==="terminal")throw new Error("Run the agent's terminal login, then reconnect.");await this.request("authenticate",{methodId:t})}async createSession(t,r=[]){await this.initialize();let i=await this.request("session/new",{cwd:t,mcpServers:r});if(typeof i.sessionId!="string"||!i.sessionId)throw new Error("Agent returned no native session identity.");return this.sessions.add(i.sessionId),i}async loadSession(t,r,i=[]){if(!(await this.initialize()).agentCapabilities?.loadSession)throw new Error("This agent does not support native session loading.");this.sessions.add(t);try{let c=await this.request("session/load",{sessionId:t,cwd:r,mcpServers:i});return await this.updateQueue,{...c,sessionId:t}}catch(c){throw this.sessions.delete(t),c}}async setModel(t,r){this.assertSession(t),await this.request("session/set_model",{sessionId:t,modelId:r})}async setMode(t,r){this.assertSession(t),await this.request("session/set_mode",{sessionId:t,modeId:r})}async setConfigOption(t,r,i){return this.assertSession(t),await this.request("session/set_config_option",{sessionId:t,configId:r,value:i})}async prompt(t,r,i){if(this.assertSession(t),i?.aborted)throw new Error("ACP prompt cancelled.");if(this.activePrompts.has(t))throw new Error("A prompt is already active for this native session.");this.activePrompts.add(t);let s,c=o(()=>{this.cancel(t),s=setTimeout(()=>{this.stop()},5e3),s.unref()},"abort");i?.addEventListener("abort",c,{once:!0});try{let l=await this.request("session/prompt",{sessionId:t,prompt:r},0);return await this.updateQueue,i?.aborted?{...l,stopReason:"cancelled"}:l}catch(l){if(i?.aborted)return{stopReason:"cancelled"};throw l}finally{s&&clearTimeout(s),i?.removeEventListener("abort",c),this.activePrompts.delete(t),this.cancelPermissions(t)}}cancel(t){this.cancelPermissions(t),this.sessions.has(t)&&this.child&&this.write({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:t}})}async stop(){if(this.stopped)return;this.stopped=!0;let t=this.child;this.fail(new Error("ACP connection closed.")),!(!t||t.exitCode!==null||t.signalCode!==null)&&await new Promise(r=>{let i=setTimeout(()=>k(t,"SIGKILL"),2e3);i.unref(),t.once("exit",()=>{clearTimeout(i),r()}),k(t,"SIGTERM")})}assertSession(t){if(!this.sessions.has(t))throw new Error("Session does not belong to this ACP connection.")}request(t,r,i=this.options.requestTimeoutMs??3e4){let s=this.nextId++;return new Promise((c,l)=>{let d=i>0?setTimeout(()=>{this.pending.delete(s),l(new Error(`ACP request timed out: ${t}`))},i):void 0;d?.unref(),this.pending.set(s,{resolve:c,reject:l,timer:d});try{this.write({jsonrpc:"2.0",id:s,method:t,params:r})}catch(m){d&&clearTimeout(d),this.pending.delete(s),l(m)}})}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("ACP connection is not running.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>K)throw new Error("ACP frame exceeds the size limit.");this.child.stdin.write(`${r}
|
|
6
|
+
`)}consume(t){this.buffer+=t;let r;for(;(r=this.buffer.indexOf(`
|
|
7
|
+
`))!==-1;){let i=this.buffer.slice(0,r);if(this.buffer=this.buffer.slice(r+1),!!i.trim())try{if(Buffer.byteLength(i)>K)throw new Error("ACP frame exceeds the size limit.");this.receive(JSON.parse(i))}catch{this.fail(new Error("Invalid ACP protocol frame.")),this.stop();return}}Buffer.byteLength(this.buffer)>K&&(this.fail(new Error("ACP frame exceeds the size limit.")),this.stop())}receive(t){if(!P(t)||t.jsonrpc!=="2.0")throw new Error("Invalid JSON-RPC envelope.");if(typeof t.method=="string"){if("id"in t){this.handleRequest(t);return}if(t.method==="session/update"&&P(t.params)){let{sessionId:i,update:s}=t.params;if(typeof i!="string"||!this.sessions.has(i)||!P(s))return;this.updateQueue=this.updateQueue.then(async()=>{await this.options.onUpdate?.(i,s)}),this.updateQueue.catch(c=>{this.fail(c),this.stop()})}return}if(typeof t.id!="number")return;let r=this.pending.get(t.id);r&&(this.pending.delete(t.id),r.timer&&clearTimeout(r.timer),P(t.error)?r.reject(new L(Number(t.error.code),String(t.error.message),t.error.data)):r.resolve(t.result))}async handleRequest(t){let r=t.id;if(!(typeof r!="number"&&typeof r!="string"))try{if(t.method!=="session/request_permission"){this.write({jsonrpc:"2.0",id:r,error:{code:-32601,message:"Client method not supported."}});return}let i=t.params;if(!P(i)||typeof i.sessionId!="string"||!Array.isArray(i.options)||!P(i.toolCall))throw new Error("Invalid permission request.");if(this.assertSession(i.sessionId),!this.activePrompts.has(i.sessionId)){this.write({jsonrpc:"2.0",id:r,result:D});return}let s=new AbortController,c=this.permissions.get(i.sessionId)??new Set;c.add(s),this.permissions.set(i.sessionId,c);let l=D;try{if(this.options.onPermission&&(l=await Promise.race([this.options.onPermission(i,s.signal),new Promise(d=>s.signal.addEventListener("abort",()=>d(D),{once:!0}))])),s.signal.aborted&&(l=D),l.outcome.outcome==="selected"){let d=l.outcome.optionId;if(!i.options.some(m=>P(m)&&m.optionId===d))throw new Error("Permission option was not advertised by the agent.")}}finally{c.delete(s),c.size||this.permissions.delete(i.sessionId)}this.child&&this.write({jsonrpc:"2.0",id:r,result:l})}catch{this.child&&this.write({jsonrpc:"2.0",id:r,error:{code:-32602,message:"Invalid or expired client request."}})}}cancelPermissions(t){for(let r of this.permissions.get(t)??[])r.abort();this.permissions.delete(t)}fail(t){let r=this.child,i=!!r;this.child=null,r&&(k(r,"SIGTERM"),setTimeout(()=>k(r,"SIGKILL"),2e3).unref());for(let s of this.pending.values())s.timer&&clearTimeout(s.timer),s.reject(t);this.pending.clear();for(let s of this.sessions)this.cancelPermissions(s);this.sessions.clear(),i&&this.options.onExit?.(t)}};var _=o(n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},"record"),S=o(n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):null,"count"),U=class{static{o(this,"ClaudeObservations")}emit;contextWindows;tools=new Map;models=new Set;latestUsage={};latestModel="unknown";compacting=!1;constructor(t,r=new Map){this.emit=t,this.contextWindows=r}tool(t){let r=String(t.toolCallId),s={...this.tools.get(r)??{},...t};this.tools.set(r,s),this.emit(s)}observe(t){if(!t.parent_tool_use_id){if(t.type==="stream_event"){let r=_(t.event),i=_(r.message);r.type==="message_start"&&this.assistant(i,!0),r.type==="message_delta"&&(this.latestUsage={...this.latestUsage,..._(r.usage)},this.context())}if(t.type==="assistant"){this.assistant(_(t.message),!1);let r=_(t.context_usage),i=S(r.total_tokens),s=S(r.raw_max_tokens);i!==null&&s&&typeof r.model=="string"&&(this.contextWindows.set(r.model,s),this.emit({sessionUpdate:"context_usage",model:r.model,usedTokens:i,maxContextTokens:s}))}if(t.type==="system"&&t.subtype==="status"&&t.status==="compacting"&&!this.compacting&&(this.compacting=!0,this.emit({sessionUpdate:"compaction_started"})),t.type==="system"&&t.subtype==="compact_boundary"){this.compacting=!1,this.latestUsage={};let r=_(t.compact_metadata);this.emit({sessionUpdate:"compaction_completed",reason:r.trigger,preTokens:r.pre_tokens})}}}assistant(t,r){typeof t.model=="string"&&!t.model.startsWith("<")&&(this.latestModel=t.model,this.models.add(t.model));let i=_(t.usage);r?this.latestUsage=i:this.latestUsage={...this.latestUsage,...i,output_tokens:Math.max(S(this.latestUsage.output_tokens)??0,S(i.output_tokens)??0)}}result(t,r){this.finishCompaction(),this.emit({sessionUpdate:"usage_update",usage:t.usage,model:this.models.size>1?"Claude Code (multiple models)":this.latestModel,status:r?"interrupted":t.is_error?"failed":"completed",scope:"main_loop_turn"});for(let[i,s]of Object.entries(_(t.modelUsage))){let c=S(_(s).contextWindow);c&&this.contextWindows.set(i,c)}this.context()}context(){let t=this.contextWindows.get(this.latestModel),r=S(this.latestUsage.input_tokens);if(t&&r!==null){let i=r+(S(this.latestUsage.cache_read_input_tokens)??0)+(S(this.latestUsage.cache_creation_input_tokens)??0)+(S(this.latestUsage.output_tokens)??0);this.emit({sessionUpdate:"context_usage",model:this.latestModel,usedTokens:i,maxContextTokens:t})}}finishCompaction(){this.compacting&&(this.compacting=!1,this.emit({sessionUpdate:"compaction_failed",error:"Claude ended before confirming compaction completed."}))}};import{spawn as Ye}from"node:child_process";import{randomUUID as O}from"node:crypto";import{StringDecoder as Se}from"node:string_decoder";var x=o(n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},"record"),Ee=[{id:"manual",name:"Ask for permissions"},{id:"plan",name:"Plan"},{id:"bypassPermissions",name:"YOLO / Full access"}],Re=class{static{o(this,"ClaudeCliClient")}options;child=null;sessionId=null;pending=new Map;turn=null;messageId="";lastTextMessageId=null;permissions=new Set;updates=Promise.resolve();closed=!1;model="default";contextWindows=new Map;observations=new U(t=>this.emit(t),this.contextWindows);stderrTail="";constructor(t){this.options=t}async initialize(){return{protocolVersion:1,agentCapabilities:{loadSession:!0,mcpCapabilities:{http:!0},promptCapabilities:{image:!0,embeddedContext:!0}},authMethods:[],agentInfo:{name:"Claude Code CLI",version:"native"}}}async authenticate(t){throw new Error("Use Claude Code's native login, then reconnect.")}async createSession(t,r=[]){return this.start(O(),t,!1,r)}async loadSession(t,r,i=[]){return this.start(t,r,!0,i)}async start(t,r,i,s){if(this.child||this.closed)throw new Error("Claude connection already owns a session or is closed.");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid native Claude session identity.");this.sessionId=t;let c=Object.fromEntries(s.map(b=>[String(b.name),{type:"http",url:b.url,headers:Object.fromEntries((Array.isArray(b.headers)?b.headers:[]).map(v=>{let I=x(v);return[String(I.name),String(I.value)]}))}])),l=["--print","--verbose","--input-format","stream-json","--output-format","stream-json","--include-partial-messages","--allow-dangerously-skip-permissions","--permission-prompt-tool","stdio","--append-system-prompt","When you create files for the user, link each deliverable using Markdown with its absolute local path so OpenPond can open it. For example: [Report](/absolute/path/report.pdf).",...(this.options.additionalDirectories??[]).flatMap(b=>["--add-dir",b]),...s.length?["--mcp-config",JSON.stringify({mcpServers:c})]:[],i?"--resume":"--session-id",t],d=Ye(this.options.command,l,{cwd:r,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=d;let m=new Se("utf8"),h="",y=new Se("utf8");d.stderr.on("data",b=>{this.stderrTail=(this.stderrTail+y.write(b)).slice(-4096)}),d.stdout.on("data",b=>{h+=m.write(b);let v;for(;(v=h.indexOf(`
|
|
8
|
+
`))>=0;){let I=h.slice(0,v);if(h=h.slice(v+1),!!I.trim())try{if(Buffer.byteLength(I)>8*1024*1024)throw new Error("Oversized frame");this.receive(x(JSON.parse(I)))}catch{this.fail(new Error("Invalid Claude CLI protocol frame.")),this.stop();return}}Buffer.byteLength(h)>8*1024*1024&&(this.fail(new Error("Claude CLI frame exceeds limit.")),this.stop())}),d.on("error",b=>this.fail(b)),d.stdin.on("error",b=>this.fail(b)),d.on("exit",b=>{this.fail(new Error(`Claude CLI exited (${b??"signal"}).${this.stderrTail.trim()?` ${this.stderrTail.trim()}`:""}`)),k(d,"SIGTERM"),setTimeout(()=>k(d,"SIGKILL"),2e3).unref(),this.child=null});try{let b=await this.control({subtype:"initialize",hooks:null}),v=Array.isArray(b.models)?b.models.map(x).filter(f=>typeof f.value=="string"):[],I=v.find(f=>f.value==="default")?.description,g=typeof I=="string"?v.find(f=>f.value!=="default"&&typeof f.displayName=="string"&&(I===f.displayName||I.startsWith(`${f.displayName} \xB7`))):void 0;return{sessionId:t,models:{currentModelId:this.model,availableModels:v.map(f=>({modelId:String(f.value),name:f.value==="default"&&g?`${g.displayName} (default)`:String(f.displayName??f.value),...typeof f.description=="string"?{description:f.description}:{}}))},modes:{currentModeId:String(b.current_permission_mode??"manual"),availableModes:Ee.map(f=>({...f}))}}}catch(b){throw await this.stop(),b}}async setModel(t,r){this.assertSession(t),await this.control({subtype:"set_model",model:r}),this.model=r}async setMode(t,r){if(this.assertSession(t),!Ee.some(i=>i.id===r))throw new Error("Unsupported Claude permission mode.");await this.control({subtype:"set_permission_mode",mode:r})}async prompt(t,r,i){if(this.assertSession(t),this.turn)throw new Error("A prompt is already active for this native session.");if(i?.aborted)throw new Error("Claude turn cancelled.");this.observations=new U(d=>this.emit(d),this.contextWindows),this.stderrTail="",this.messageId=O(),this.lastTextMessageId=null;let s=new Promise((d,m)=>{this.turn={resolve:d,reject:m,signal:i,resultReceived:!1}}),c,l=o(()=>{for(let d of this.permissions)d.abort();this.control({subtype:"interrupt"}).catch(()=>{}),c=setTimeout(()=>{this.stop()},5e3),c.unref()},"abort");i?.addEventListener("abort",l,{once:!0});try{this.write({type:"user",session_id:t,parent_tool_use_id:null,message:{role:"user",content:r.map(m=>m.type==="image"?{type:"image",source:{type:"base64",media_type:m.mimeType,data:m.data}}:m)}});let d=await s;return await this.updates,i?.aborted?{stopReason:"cancelled"}:d}catch(d){if(await this.updates.catch(()=>{}),i?.aborted)return{stopReason:"cancelled"};throw d}finally{i?.removeEventListener("abort",l),c&&clearTimeout(c),this.turn=null;for(let d of this.permissions)d.abort();this.permissions.clear()}}assertSession(t){if(!this.child||this.sessionId!==t||this.closed)throw new Error("Session does not belong to this Claude connection.")}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("Claude connection is closed.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>8*1024*1024)throw new Error("Claude input exceeds limit.");this.child.stdin.write(`${r}
|
|
9
|
+
`)}control(t){let r=O();return new Promise((i,s)=>{let c=setTimeout(()=>{this.pending.delete(r),s(new Error(`Claude control request timed out: ${t.subtype}`))},this.options.requestTimeoutMs??3e4);c.unref(),this.pending.set(r,{resolve:i,reject:s,timer:c});try{this.write({type:"control_request",request_id:r,request:t})}catch(l){clearTimeout(c),this.pending.delete(r),s(l)}})}emit(t){if(!this.turn||!this.sessionId)return;let r=this.sessionId;this.updates=this.updates.then(async()=>{await this.options.onUpdate?.(r,t)}),this.updates.catch(i=>{this.fail(i),this.stop()})}receive(t){if(typeof t.session_id=="string"&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity.")),this.stop();return}if(this.turn&&!this.turn.resultReceived&&this.observations.observe(t),t.type==="control_response"){let r=x(t.response),i=String(r.request_id),s=this.pending.get(i);if(!s)return;clearTimeout(s.timer),this.pending.delete(i),r.subtype==="error"?s.reject(new Error(String(r.error??"Claude control failed."))):s.resolve(x(r.response))}else if(t.type==="control_request")this.permission(t);else if(t.type==="stream_event"){if(!this.turn||this.turn.resultReceived||t.parent_tool_use_id)return;let r=x(t.event),i=x(r.delta),s=x(r.content_block);if(r.type==="message_start"){let c=x(r.message).id;this.messageId=typeof c=="string"?c:O(),this.lastTextMessageId=null}if(r.type==="content_block_delta"&&(i.type==="text_delta"||i.type==="thinking_delta")){let c=i.type==="text_delta";c&&(this.lastTextMessageId=this.messageId),this.emit({sessionUpdate:c?"agent_message_chunk":"agent_thought_chunk",messageId:this.messageId,phase:c?"commentary":"reasoning",content:{type:"text",text:i.text??i.thinking??""}})}r.type==="content_block_start"&&s.type==="tool_use"&&(this.lastTextMessageId=null,this.observations.tool({sessionUpdate:"tool_call",toolCallId:s.id,title:s.name,kind:"other",status:"in_progress",rawInput:s.input}))}else if(t.type==="assistant"){if(!this.turn||this.turn.resultReceived)return;let r=x(t.message),i=r.content;!t.parent_tool_use_id&&typeof r.id=="string"&&Array.isArray(i)&&i.some(s=>x(s).type==="text")&&(this.lastTextMessageId=r.id),!t.parent_tool_use_id&&Array.isArray(i)&&i.some(s=>x(s).type==="tool_use")&&(this.lastTextMessageId=null);for(let s of Array.isArray(i)?i.map(x):[])s.type==="tool_use"&&this.observations.tool({sessionUpdate:"tool_call_update",toolCallId:s.id,title:s.name,status:"in_progress",rawInput:s.input})}else if(t.type==="user"){if(!this.turn||this.turn.resultReceived)return;let r=x(t.message).content;for(let i of Array.isArray(r)?r.map(x):[])i.type==="tool_result"&&this.observations.tool({sessionUpdate:"tool_call_update",toolCallId:i.tool_use_id,status:i.is_error?"failed":"completed",content:i.content})}else if(t.type==="result"){if(!this.turn||this.turn.resultReceived)return;if(this.turn.resultReceived=!0,t.session_id&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity."));return}!t.is_error&&!this.turn.signal?.aborted&&typeof t.result=="string"&&t.result.trim()&&this.emit({sessionUpdate:"agent_message_final",messageId:this.lastTextMessageId??O(),content:{type:"text",text:t.result}}),this.observations.result(t,!!this.turn.signal?.aborted),t.is_error?this.turn?.reject(new Error(Array.isArray(t.errors)?t.errors.map(String).join("; "):"Claude turn failed.")):this.turn?.resolve({stopReason:"end_turn"})}}async permission(t){let r=x(t.request),i=String(t.request_id);if(r.subtype!=="can_use_tool"||!this.turn||!this.sessionId){this.write({type:"control_response",response:{subtype:"error",request_id:i,error:"Unsupported or inactive control request."}});return}let s=new AbortController;this.permissions.add(s);try{let c=x(r.input),l=r.tool_name==="AskUserQuestion"&&Array.isArray(c.questions)?c.questions:void 0,d=new Promise(y=>s.signal.addEventListener("abort",()=>y({outcome:{outcome:"cancelled"}}),{once:!0})),m=await Promise.race([d,this.options.onPermission?.({sessionId:this.sessionId,toolCall:{toolCallId:r.tool_use_id,title:r.title??r.tool_name,rawInput:r.input},questions:l,options:[{optionId:"allow",name:"Allow once",kind:"allow_once"},{optionId:"deny",name:"Deny",kind:"reject_once"}]},s.signal)]),h=!s.signal.aborted&&m?.outcome.outcome==="selected"&&m.outcome.optionId==="allow";this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:i,response:h?{behavior:"allow",updatedInput:l?{...c,answers:m?.answers}:r.input}:{behavior:"deny",message:"Permission declined or turn cancelled."}}})}catch{this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:i,response:{behavior:"deny",message:"Permission could not be resolved."}}})}finally{this.permissions.delete(s)}}fail(t){this.observations.finishCompaction();for(let r of this.pending.values())clearTimeout(r.timer),r.reject(t);this.pending.clear(),this.turn?.reject(t),this.turn=null;for(let r of this.permissions)r.abort();this.permissions.clear(),this.options.onExit?.(t)}async stop(){if(this.closed)return;this.closed=!0,this.fail(new Error("Claude connection closed."));let t=this.child;!t||t.exitCode!==null||t.signalCode!==null||(await new Promise(r=>{let i=setTimeout(()=>k(t,"SIGKILL"),2e3);i.unref(),t.once("exit",()=>{clearTimeout(i),r()}),k(t,"SIGTERM")}),this.child=null)}};export{W as a,R as b,rt as c,it as d,nt as e,Ce as f,qe as g,lt as h,A as i,mt as j,Z as k,ee as l,F as m,J as n,ht as o,Pe as p,B as q,te as r,G as s,se as t,ce as u,pe as v,he as w,fe as x,be as y,ge as z,Ve as A,we as B,Ue as C,ve as D,xe as E,p as F,Ot as G,Ie as H,Bt as I,ye as J,Qt as K,sr as L,Je as M,Ge as N,ur as O,dr as P,pr as Q,gr as R,wr as S,vr as T,xr as U,ke as V,je as W,L as X,_e as Y,Re as Z};
|