openpond 0.2.39 → 0.2.40
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/{actions-command-MHWHPQ66.js → actions-command-X2ERGYMA.js} +1 -1
- package/dist/chunks/{app-layer-JZTMHORT.js → app-layer-W2M7SM2L.js} +1 -1
- package/dist/chunks/app-server-runtime-IO3FDF37.js +2 -0
- package/dist/chunks/{apps-U5GIOD6W.js → apps-IBVU56HR.js} +1 -1
- package/dist/chunks/{chunk-MRGA6BKG.js → chunk-3QXPXBVG.js} +1 -1
- package/dist/chunks/{chunk-FKVP26MC.js → chunk-3UQU3KOS.js} +1 -1
- package/dist/chunks/{chunk-XHJUP7M4.js → chunk-4QURHV3Q.js} +1 -1
- package/dist/chunks/{chunk-FVALIUVY.js → chunk-5OA57RW4.js} +1 -1
- package/dist/chunks/{chunk-R6DWG5A4.js → chunk-62H5KUOS.js} +1 -1
- package/dist/chunks/{chunk-GIPSOLAY.js → chunk-ALYT2HWV.js} +1 -1
- package/dist/chunks/{chunk-25OT6IYM.js → chunk-ASRSYRE3.js} +1 -1
- package/dist/chunks/{chunk-SHCRE7B2.js → chunk-CYZOPDTW.js} +1 -1
- package/dist/chunks/{chunk-RJACNWYJ.js → chunk-DWY6YCBI.js} +198 -198
- package/dist/chunks/{chunk-WCZRDULE.js → chunk-ELUCM7CG.js} +1 -1
- package/dist/chunks/{chunk-L6ELXODL.js → chunk-FFTVDR3E.js} +1 -1
- package/dist/chunks/chunk-GTG2ODOV.js +5 -0
- package/dist/chunks/{chunk-6GLGOIMQ.js → chunk-H7YH35JO.js} +1 -1
- package/dist/chunks/chunk-IYWNO4RB.js +3 -0
- package/dist/chunks/{chunk-DHP75QSG.js → chunk-JARGGWF5.js} +1 -1
- package/dist/chunks/{chunk-SBBXUZWL.js → chunk-JIG7KQOX.js} +1 -1
- package/dist/chunks/{chunk-Q3X5WOVH.js → chunk-QCLVO56H.js} +1 -1
- package/dist/chunks/{chunk-JUX77H6K.js → chunk-TU5ITNMX.js} +1 -1
- package/dist/chunks/{chunk-ZPGTGQJT.js → chunk-WWCU4ETR.js} +1 -1
- package/dist/chunks/{chunk-ZO7DTED5.js → chunk-XRI3HLZ3.js} +1 -1
- package/dist/chunks/{chunk-7BGT6Q2D.js → chunk-YHBIGFFA.js} +1 -1
- package/dist/chunks/{chunk-RELOOVWW.js → chunk-ZCPIVNCS.js} +1 -1
- package/dist/chunks/cli-QXO6OHZJ.js +2 -0
- package/dist/chunks/{configuration-command-RPNYWBKK.js → configuration-command-6VJUXQNZ.js} +1 -1
- package/dist/chunks/{core-commands-WFTASSGL.js → core-commands-J6OY62PE.js} +1 -1
- package/dist/chunks/{datasets-V7E4I5N3.js → datasets-W24QTQL7.js} +1 -1
- package/dist/chunks/{desktop-test-NZAZVXLK.js → desktop-test-SHS2VUYP.js} +1 -1
- package/dist/chunks/experiments-O7WTSICN.js +2 -0
- package/dist/chunks/{extension-OQ7CFD4Q.js → extension-3P3JNRYN.js} +1 -1
- package/dist/chunks/{help-4BB2A5JC.js → help-23QDOMG7.js} +1 -1
- package/dist/chunks/{hosted-harness-runtime-2YI2FLU2.js → hosted-harness-runtime-U7JV7Z5T.js} +1 -1
- package/dist/chunks/{hosted-profile-compiler-35BQPVJ6.js → hosted-profile-compiler-ZCVMUTFA.js} +1 -1
- package/dist/chunks/{opchat-QVB4UIZR.js → opchat-OI2YFNNY.js} +1 -1
- package/dist/chunks/{organizations-MUKXB6MX.js → organizations-LB5QXKWT.js} +1 -1
- package/dist/chunks/{profile-LZYR4CMX.js → profile-NJMKPS6Z.js} +1 -1
- package/dist/chunks/{project-agent-FHNWIH2D.js → project-agent-SZLUVG3U.js} +1 -1
- package/dist/chunks/{sandbox-command-GJN3HSJQ.js → sandbox-command-FQBOFZGM.js} +1 -1
- package/dist/chunks/{sandbox-template-6RLQYNTY.js → sandbox-template-RCDR2FXX.js} +1 -1
- package/dist/chunks/{src-PASASTIA.js → src-H7VE4J62.js} +1 -1
- package/dist/chunks/{src-J7NT5WEH.js → src-JVSP6UKT.js} +107 -107
- package/dist/chunks/{teams-bot-UQB636V3.js → teams-bot-KCKZTM3N.js} +1 -1
- package/dist/chunks/{workspaces-RFQ4QB5A.js → workspaces-J5QQUR53.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/docs/command-reference.md +1 -1
- package/package.json +1 -1
- package/dist/chunks/app-server-runtime-72NRJAB5.js +0 -2
- package/dist/chunks/chunk-P5CFBE6Z.js +0 -3
- package/dist/chunks/chunk-TZNKOKQJ.js +0 -5
- package/dist/chunks/cli-ETZV6JZI.js +0 -2
- package/dist/chunks/experiments-7UBJCQAQ.js +0 -2
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{Nc as r}from"./chunks/chunk-DWY6YCBI.js";import{e as p}from"./chunks/chunk-5OA57RW4.js";import"./chunks/chunk-ASRSYRE3.js";import"./chunks/chunk-62H5KUOS.js";import"./chunks/chunk-FFTVDR3E.js";import{i as e}from"./chunks/chunk-PKBU37CH.js";import"./chunks/chunk-JARGGWF5.js";import"./chunks/chunk-H7YH35JO.js";import"./chunks/chunk-4QURHV3Q.js";import"./chunks/chunk-YHBIGFFA.js";import"./chunks/chunk-JIG7KQOX.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-CYZOPDTW.js";import"./chunks/chunk-XEOEKFG6.js";import"./chunks/chunk-3QXPXBVG.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-ELUCM7CG.js";import"./chunks/chunk-ZCPIVNCS.js";import"./chunks/chunk-ALYT2HWV.js";import"./chunks/chunk-MJC26GOX.js";import"./chunks/chunk-TU5ITNMX.js";import"./chunks/chunk-QUNRWDVO.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-SDO4FC4Q.js";import"./chunks/chunk-IR3YJWPW.js";import"./chunks/chunk-QK2GLRCY.js";import"./chunks/chunk-HZP5U2AA.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{a as v}from"./chunk-3HQEEZPO.js";import"./chunk-XWPC3AN4.js";import{f as b}from"./chunk-3M53YXEI.js";import{b as R,c as p,d as m}from"./chunk-XEOEKFG6.js";import{
|
|
2
|
+
import{a as v}from"./chunk-3HQEEZPO.js";import"./chunk-XWPC3AN4.js";import{f as b}from"./chunk-3M53YXEI.js";import{b as R,c as p,d as m}from"./chunk-XEOEKFG6.js";import{l as O}from"./chunk-GTG2ODOV.js";import{d as P}from"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-ZCPIVNCS.js";import"./chunk-ALYT2HWV.js";import"./chunk-MJC26GOX.js";import"./chunk-TU5ITNMX.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as c}from"./chunk-FTQLQJQV.js";import{promises as $,watch as C}from"node:fs";import y from"node:path";import{execFile as J}from"node:child_process";import{promisify as k}from"node:util";var K=k(J);async function G(t,n){let e=n[0]??"check",o=y.resolve(i(t,"cwd")??process.cwd()),l=i(t,"sourceDirectory"),u=i(t,"outputDirectory"),d=b(t.json);if(e==="check"||e==="build"){let r=await p({projectRoot:o,sourceDirectory:l,outputDirectory:u});if(d){console.log(JSON.stringify({status:"passed",actionCount:r.registry.actions.length,registry:r.registry,manifest:r.manifest,outputDirectory:r.outputDirectory},null,2));return}console.log(`${e==="check"?"Validated":"Built"} ${r.registry.actions.length} Project Action${r.registry.actions.length===1?"":"s"}.`),console.log(`Registry: ${r.registryPath}`),console.log(`Bundle: ${r.bundlePath}`);return}if(e==="run"){let r=n[1];if(!r)throw new Error("usage: openpond actions run <action-id> [--input JSON|--input-file PATH]");let a=await m({projectRoot:o,sourceDirectory:l,outputDirectory:u,build:"always"}).run({actionId:r,input:await I(t,o),timeoutMs:A(t,"timeoutMs")});console.log(JSON.stringify(a,null,2));return}if(e==="dev"){let r=n[1]??null;await _({projectRoot:o,sourceDirectory:l,outputDirectory:u,actionId:r,options:t,json:d});return}if(e==="publish"){let r=j(t,"projectId"),s=j(t,"teamId"),a=i(t,"apiKey"),w=process.env.OPENPOND_API_KEY?.trim()||null,g=a||w?null:await P({account:i(t,"account")}),h=a??w??(g?v(g):null);if(!h)throw new Error("OpenPond API key is required. Select a saved OpenPond account, set OPENPOND_API_KEY, or pass --api-key.");let N=await p({projectRoot:o,sourceDirectory:l,outputDirectory:u}),E=i(t,"sourceCommitSha")??await D(o,["rev-parse","HEAD"]),S=i(t,"sourceRef")??await D(o,["rev-parse","--abbrev-ref","HEAD"]),f=await O({apiKey:h,baseUrl:i(t,"baseUrl")??(process.env.OPENPOND_API_URL?.trim()||g?.apiBaseUrl)}).actions.publish({projectId:r,teamId:s,sourceRef:S,sourceCommitSha:E,build:N});console.log(d?JSON.stringify({release:f},null,2):`Published Project Actions release ${f.id} from ${f.sourceCommitSha}.`);return}throw new Error("usage: openpond actions <check|build|run|dev|publish> [action-id]")}c(G,"runProjectActionsCommand");async function _(t){let n=!1,e=!1,o=c(async()=>{if(n){e=!0;return}n=!0;try{let r=m({projectRoot:t.projectRoot,sourceDirectory:t.sourceDirectory,outputDirectory:t.outputDirectory,build:"always"});if(t.actionId){let s=await r.run({actionId:t.actionId,input:await I(t.options,t.projectRoot),timeoutMs:A(t.options,"timeoutMs")});console.log(JSON.stringify(s,null,2))}else{let s=await r.build(),a={status:"ready",actionCount:s.registry.actions.length,bundleHash:s.manifest.bundleHash};console.log(t.json?JSON.stringify(a):`Ready with ${a.actionCount} Project Action${a.actionCount===1?"":"s"}.`)}}catch(r){console.error(r instanceof Error?r.message:String(r))}finally{n=!1,e&&(e=!1,await o())}},"execute");await o();let l=await R(t.projectRoot),u=y.resolve(t.projectRoot,t.sourceDirectory??l.sourceDirectory??"openpond/actions");console.log(`Watching ${u}`);let d=C(u,{recursive:!0},()=>{setTimeout(()=>{o()},50)});await new Promise(r=>{let s=c(()=>{d.close(),r()},"stop");process.once("SIGINT",s),process.once("SIGTERM",s)})}c(_,"runDev");async function I(t,n){let e=i(t,"input"),o=i(t,"inputFile");if(e&&o)throw new Error("Use either --input or --input-file, not both.");return e?JSON.parse(e):o?JSON.parse(await $.readFile(y.resolve(n,o),"utf8")):{}}c(I,"actionInput");function i(t,n){let e=t[n];return typeof e=="string"&&e.trim()?e.trim():void 0}c(i,"stringOption");function j(t,n){let e=i(t,n);if(!e)throw new Error(`--${n.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`)} is required.`);return e}c(j,"requiredOption");async function D(t,n){let{stdout:e}=await K("git",n,{cwd:t}),o=e.trim();if(!o)throw new Error(`git ${n.join(" ")} returned no value.`);return o}c(D,"gitValue");function A(t,n){let e=i(t,n);if(e===void 0)return;let o=Number(e);if(!Number.isInteger(o)||o<=0)throw new Error(`--${n} must be a positive integer.`);return o}c(A,"integerOption");export{G as runProjectActionsCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{u as m}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import{a as l}from"./chunk-
|
|
2
|
+
import{u as m}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import{a as l}from"./chunk-3UQU3KOS.js";import"./chunk-IYWNO4RB.js";import"./chunk-XWPC3AN4.js";import"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-GTG2ODOV.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-ZCPIVNCS.js";import"./chunk-ALYT2HWV.js";import"./chunk-MJC26GOX.js";import"./chunk-TU5ITNMX.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{existsSync as c}from"node:fs";import{createRequire as v}from"node:module";import s from"node:path";import{fileURLToPath as E}from"node:url";var p="24.18.0";function N(e=process.versions.node){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(e),n=r?Number(r[1]):Number.NaN,o=r?Number(r[2]):Number.NaN;return n===24&&o>=18?null:[`OpenPond TUI requires Node.js ${p} or newer in the Node 24 release line; detected Node.js ${e}.`,`Switch Node versions and retry (with nvm: \`nvm install ${p} && nvm use ${p}\`).`].join(`
|
|
3
3
|
`)}i(N,"openPondTuiNodeRuntimeMessage");var u=s.dirname(E(import.meta.url)),O=class extends Error{constructor(n,o){super(n);this.exitCode=o;this.name="OpenPondChildProcessExitError"}exitCode;static{i(this,"OpenPondChildProcessExitError")}};async function F(e,r,n){let o=f(e==="app-server"?"app-server":"server"),t=[...o.args,e,...P(r),...n];e==="web"&&t.push(r.noOpen===!0||r.noOpen==="true"?"--print-access-url":"--open-browser");let a=e==="web"&&typeof r.webRoot!="string"?C():null;a&&t.push("--web-root",a),await w(o.runner,t,e==="app-server"?process.cwd():o.cwd)}i(F,"runOpenPondServerCommand");async function q(e,r){b(e);let n=N();if(n)throw new l(n);let o=f("terminal"),t=f("server"),a=[...o.args,"chat",...P(R(e)),...r];await w(o.runner,a,process.cwd(),{OPENPOND_SERVER_RUNNER:t.runner,OPENPOND_SERVER_ARGS:JSON.stringify(t.args),OPENPOND_SERVER_CWD:t.cwd})}i(q,"runOpenPondTerminalCommand");function h(){if(process.env.OPENPOND_FORCE_EMBEDDED_COMPANIONS==="1")return null;let e=[s.resolve(u,"../../../.."),s.resolve(u,"../../.."),process.cwd()];for(let r of e)if(c(s.join(r,"apps","server"))&&c(s.join(r,"apps","terminal")))return r;return null}i(h,"findWorkspaceRoot");function f(e){let r=h();if(r){let t=e==="app-server"?s.join(r,"apps","server","src","app-server-entry.ts"):s.join(r,"apps",e,"src","index.ts");if(c(t)){let d=v(s.join(r,"package.json"));return{runner:process.execPath,args:[d.resolve("tsx/cli"),t],cwd:r}}let a=e==="app-server"?s.join(r,"apps","server","dist","app-server-entry.js"):s.join(r,"apps",e,"dist","index.js");if(c(a))return{runner:process.execPath,args:[a],cwd:r}}let n=_(),o=e==="app-server"?"__app-server":e==="server"?"__server":"__terminal";if(n)return{runner:process.execPath,args:[n,o],cwd:s.dirname(s.dirname(n))};if(D())return{runner:process.execPath,args:[o],cwd:process.cwd()};throw new Error(`Could not find the installed OpenPond ${e} companion.`)}i(f,"resolveAppEntrypoint");function _(){for(let e of[s.resolve(u,"../cli.js"),s.resolve(u,"../../dist/cli.js")])if(c(e))return e;return null}i(_,"installedCliEntrypoint");function C(){if(!1){let n=s.join(s.dirname(process.execPath),"web");return c(s.join(n,"index.html"))?n:null}let e=_();if(!e)return null;let r=s.join(s.dirname(e),"web");return c(s.join(r,"index.html"))?r:null}i(C,"packagedWebRoot");function D(){if(!1)return!0;let e=process.argv[1];return!!(e&&s.resolve(e)===s.resolve(process.execPath))}i(D,"isCompiledExecutable");function P(e){let r=new Set(["account","handle","baseUrl","noOpen","tui","home"]),n=[];for(let[o,t]of Object.entries(e)){if(r.has(o))continue;let a=`--${o.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`)}`;if(t===!0||t==="true")n.push(a);else{if(t===!1||t==="false")continue;n.push(a,t)}}return n}i(P,"forwardedOptions");function R(e){let r=process.cwd(),n={...e};return typeof e.cwd=="string"&&e.cwd.trim().length>0&&(n.cwd=s.resolve(r,e.cwd)),typeof e.messageFile=="string"&&e.messageFile.trim().length>0&&(n.messageFile=s.resolve(r,e.messageFile)),n}i(R,"normalizeTerminalPaths");function b(e){if(typeof e.approvalPolicy=="string"&&!["on-request","never","on-failure","untrusted"].includes(e.approvalPolicy))throw new l("approval-policy must be on-request, never, on-failure, or untrusted");if(typeof e.sandbox=="string"&&!["read-only","workspace-write","danger-full-access"].includes(e.sandbox))throw new l("sandbox must be read-only, workspace-write, or danger-full-access")}i(b,"validateTerminalForwardingOptions");async function w(e,r,n,o){let t=await m(e,r,{cwd:n,detached:!1,env:o,inherit:!0,timeoutMs:0});if(t.code!==0||t.signal){let a=t.signal?`signal ${t.signal}`:`code ${t.code??"unknown"}`;throw new O(`${s.basename(e)} exited with ${a}`,t.code??1)}}i(w,"runChild");export{O as OpenPondChildProcessExitError,F as runOpenPondServerCommand,q as runOpenPondTerminalCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{Mc as c,Nc as d}from"./chunk-DWY6YCBI.js";import{e as b}from"./chunk-5OA57RW4.js";import"./chunk-ASRSYRE3.js";import"./chunk-62H5KUOS.js";import"./chunk-FFTVDR3E.js";import{i as a}from"./chunk-PKBU37CH.js";import"./chunk-JARGGWF5.js";import"./chunk-H7YH35JO.js";import"./chunk-4QURHV3Q.js";import"./chunk-YHBIGFFA.js";import"./chunk-JIG7KQOX.js";import"./chunk-L3KS6MOV.js";import"./chunk-CYZOPDTW.js";import"./chunk-XEOEKFG6.js";import"./chunk-3QXPXBVG.js";import"./chunk-6MI4KKWF.js";import"./chunk-ELUCM7CG.js";import"./chunk-ZCPIVNCS.js";import"./chunk-ALYT2HWV.js";import"./chunk-MJC26GOX.js";import"./chunk-TU5ITNMX.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.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,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{f as $,g as J,h as L,i as v,j as q}from"./chunk-FUFIZ37W.js";import{c as g}from"./chunk-3HQEEZPO.js";import{f as m,h as y}from"./chunk-BSHAIAXY.js";import"./chunk-
|
|
2
|
+
import{f as $,g as J,h as L,i as v,j as q}from"./chunk-FUFIZ37W.js";import{c as g}from"./chunk-3HQEEZPO.js";import{f as m,h as y}from"./chunk-BSHAIAXY.js";import"./chunk-3UQU3KOS.js";import"./chunk-IYWNO4RB.js";import"./chunk-XWPC3AN4.js";import{a as S,f as w,j as T,k as j}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-GTG2ODOV.js";import{b as H,c as Q}from"./chunk-22UARBPW.js";import{J as C,K as G,L as k,O as W,Q as M,S as z,T as F,c as D,m as K,r as V,s as _}from"./chunk-SHCKK3SU.js";import{d as f}from"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-ZCPIVNCS.js";import"./chunk-ALYT2HWV.js";import"./chunk-MJC26GOX.js";import"./chunk-TU5ITNMX.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as p}from"./chunk-FTQLQJQV.js";async function ie(){let e=await f(),s=m(e),t=await g(e,s),n=y(e),r=await L({apiBase:n,apiKey:t});console.log(JSON.stringify(r,null,2))}p(ie,"runAppsTools");async function se(e){let s=await f(),t=m(s),n=y(s),r=await g(s,t),i=typeof e.handle=="string"?String(e.handle):void 0,o=i?$(i):null,c=e.refresh!==void 0?w(e.refresh):void 0,l=await J({apiBase:n,apiKey:r,forceRefresh:c}),u=o?l.filter(a=>$(a.handle||a.gitOwner)===o):l;if(u.length===0){console.log("no apps found");return}if(w(e.json)){console.log(JSON.stringify({apps:u},null,2));return}for(let a of u){let d=a.handle||a.gitOwner||"unknown",h=a.repo||a.gitRepo||a.id,B=a.latestDeployment?.status||"no-deploy",R=a.latestDeployment?.gitBranch||a.defaultBranch||"-",I=a.codeVisibility||"unknown",E=a.sandbox?"yes":"no";console.log(`${d}/${h} ${B} ${R} code=${I} sandbox=${E} ${a.id}`)}}p(se,"runAppsList");async function oe(e,s){let t=typeof e.visibility=="string"?e.visibility.trim():typeof e.codeVisibility=="string"?e.codeVisibility.trim():"";if(t!=="public"&&t!=="private")throw new Error("usage: apps code-visibility <handle>/<repo> --visibility public|private");let n=await f(),r=m(n),i=y(n),o=await g(n,r),{app:c,handle:l,repo:u}=await v(i,o,s),a=await K(i,o,c.id,t);console.log(`${l}/${u} code_visibility=${a.app?.codeVisibility??t} app_id=${c.id}`)}p(oe,"runAppsCodeVisibility");async function ae(e){let s=await f(),t=m(s),n=await g(s,t),r=y(s),i=typeof e.appId=="string"?String(e.appId):void 0,o=await G(r,n,{appId:i});console.log(JSON.stringify(o,null,2))}p(ae,"runAppsPerformance");async function ce(e,s){let t=await f(),n=m(t),r=y(t),i=await g(t,n),{app:o}=await v(r,i,s),c=await k(r,i,o.id);console.log(JSON.stringify(c,null,2))}p(ce,"runAppsSummary");async function le(e,s,t,n){let r=(typeof e.prompt=="string"?e.prompt:null)||n.join(" ");if(!r.trim())throw new Error("usage: apps assistant <plan|performance> <handle>/<repo> --prompt <text>");let i=await f(),o=m(i),c=y(i),l=await g(i,o),{app:u}=await v(c,l,t),a=await W(c,l,{appId:u.id,mode:s,prompt:r.trim()});console.log(JSON.stringify(a,null,2))}p(le,"runAppsAssistant");async function de(e,s){let t=await f(),n=m(t),r=await g(t,n),i=y(t),o=(typeof e.prompt=="string"?e.prompt:null)||s.join(" ");if(!o.trim())throw new Error("usage: apps agent create --prompt <text> [--team-id <id>]");let c=typeof e.templateRepoUrl=="string"?e.templateRepoUrl:void 0,l=typeof e.templateBranch=="string"?e.templateBranch:void 0,u=typeof e.templateLocalPath=="string"?e.templateLocalPath:void 0,a=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0;if(u&&String(u).trim().length>0)throw new Error("templateLocalPath is not supported; use templateRepoUrl");let d=typeof e.env=="string"?S(e.env,"env"):void 0;if(d){if(typeof d!="object"||Array.isArray(d))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(d))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}let h=c||l||d?{templateRepoUrl:c,templateBranch:l,envVars:d}:void 0,B=typeof e.deployEnvironment=="string"?e.deployEnvironment==="preview"?"preview":"production":void 0,R=e.deployDisabled!==void 0?w(e.deployDisabled):void 0,I=e.streamDeployLogs!==void 0?w(e.streamDeployLogs):!0,E=await C(i,r,{prompt:o.trim(),...a?{teamId:a}:{},...h?{template:h}:{},...B?{deployEnvironment:B}:{},...R!==void 0?{deployDisabled:R}:{},streamDeployLogs:I});if(!E.ok){let b=await E.text().catch(()=>"");throw new Error(`agent create failed: ${E.status} ${b}`)}let N=null,O=null,P=null;await H(E,{onConversationId:p(b=>{N=b},"onConversationId"),onItems:p(b=>{for(let A of b){let U=Q(A);U&&console.log(U);let x=A;!O&&typeof x.appId=="string"&&(O=x.appId),!P&&typeof x.deploymentId=="string"&&(P=x.deploymentId)}},"onItems")}),N&&console.log(`conversation_id: ${N}`),O&&console.log(`app_id: ${O}`),P&&console.log(`deployment_id: ${P}`);try{await J({apiBase:i,apiKey:r,forceRefresh:!0}),await L({apiBase:i,apiKey:r,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}p(de,"runAppsAgentCreate");async function pe(e,s,t,n){let r=await f(),i=m(r),o=await g(r,i),c=y(r),l=typeof e.method=="string"?String(e.method).toUpperCase():void 0,u=l&&["GET","POST","PUT","DELETE"].includes(l)?l:void 0;if(l&&!u)throw new Error("method must be GET, POST, PUT, or DELETE");let a=typeof e.body=="string"?S(String(e.body),"body"):void 0,d=typeof e.headers=="string"?S(String(e.headers),"headers"):void 0,h=typeof e.scheduleId=="string"?String(e.scheduleId):void 0,B=w(e.notifyEmail),R=w(e.summary)||w(e.withSummary),I=await M(c,o,{appId:s,deploymentId:t,toolName:n,scheduleId:h,method:u,body:a,headers:d,notifyEmail:B||void 0});if(console.log(JSON.stringify(I,null,2)),R&&I.ok){let E=await k(c,o,s);console.log(JSON.stringify({summary:E},null,2))}}p(pe,"runAppsToolsExecute");async function ue(e,s){let t=typeof e.env=="string"?e.env:typeof e.vars=="string"?e.vars:typeof e.envVars=="string"?e.envVars:null;if(!t)throw new Error("usage: apps env set <handle>/<repo> --env <json>");let n=S(t,"env");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("env must be a JSON object");let r={};for(let[d,h]of Object.entries(n)){if(typeof h!="string")throw new Error(`env value for ${d} must be a string`);if(!d.startsWith("OPENTOOL_PUBLIC_"))throw new Error("only OPENTOOL_PUBLIC_ env vars can be set");r[d]=h}let i=await f(),o=m(i),c=y(i),l=await g(i,o),{app:u}=await v(c,l,s),a=await V(c,l,u.id,{envVars:r});console.log(JSON.stringify(a,null,2))}p(ue,"runAppsEnvSet");async function fe(e,s){let t=await f(),n=m(t),r=y(t),i=await g(t,n),{app:o}=await v(r,i,s),c=await _(r,i,o.id);console.log(JSON.stringify(c,null,2))}p(fe,"runAppsEnvGet");async function ge(e,s){let t=await f(),n=m(t),r=y(t),i=await g(t,n),{app:o,handle:c,repo:l}=await v(r,i,s),u=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,a=j(u),d=await D(r,i,o.id,{environment:a});console.log(JSON.stringify(d,null,2)),(w(e.watch)||w(e.wait)||w(e.follow))&&await q({baseUrl:r,apiKey:i,deploymentId:d.deploymentId,prefix:`[${c}/${l}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}p(ge,"runAppsDeploy");function X(e){let s={};if(typeof e.params=="string"){let n=S(String(e.params),"params");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("params must be a JSON object");for(let[r,i]of Object.entries(n))i!==void 0&&(s[r]=typeof i=="string"?i:JSON.stringify(i))}let t=p((n,r)=>{r===void 0||r===""||(s[n]=r)},"addParam");if(t("source",typeof e.source=="string"?e.source.trim():void 0),t("symbol",typeof e.symbol=="string"?e.symbol.trim():void 0),t("cursor",typeof e.cursor=="string"?e.cursor.trim():void 0),t("status",typeof e.status=="string"?e.status.trim():void 0),t("backtestRunId",typeof e.runId=="string"?e.runId.trim():typeof e.backtestRunId=="string"?e.backtestRunId.trim():void 0),t("since",T(e.since,"since")),t("until",T(e.until,"until")),typeof e.limit=="string"&&e.limit.trim().length>0){let n=Number.parseInt(e.limit,10);if(!Number.isFinite(n))throw new Error("limit must be a number");t("limit",String(n))}return Object.keys(s).length?s:void 0}p(X,"resolveBacktestEventsParams");async function me(e,s){let t=await f(),n=m(t),r=await g(t,n),i=y(t),{app:o}=await v(i,r,s),c={...X(e)??{},appId:o.id},l=await z(i,r,{method:"GET",query:c});console.log(JSON.stringify(l,null,2))}p(me,"runBacktestEvents");async function ye(e,s){let t=typeof e.runId=="string"?e.runId.trim():typeof e.backtestRunId=="string"?e.backtestRunId.trim():"";if(!t)throw new Error("usage: backtest get <handle>/<repo> --run-id <id>");let n=await f(),r=m(n),i=await g(n,r),o=y(n),{app:c}=await v(o,i,s),l=await F(o,i,{appId:c.id,runId:t});console.log(JSON.stringify(l,null,2))}p(ye,"runBacktestGet");export{X as resolveBacktestEventsParams,de as runAppsAgentCreate,le as runAppsAssistant,oe as runAppsCodeVisibility,ge as runAppsDeploy,fe as runAppsEnvGet,ue as runAppsEnvSet,se as runAppsList,ae as runAppsPerformance,ce as runAppsSummary,ie as runAppsTools,pe as runAppsToolsExecute,me as runBacktestEvents,ye as runBacktestGet};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{C as H,D as j,E as le,F as L,I as de,J as G,K as f,Lb as pe,M as Ye,N as Qe,O as et,Ob as me,Pa as at,Pb as ct,Qb as $,U as tt,cb as nt,db as rt,eb as st,fb as ot,fc as ue,gb as it,gc as he,h as Je,hc as Re,i as We,ic as Te,jc as Ie,kc as Pe,lc as Ee,mc as _e,sb as xe,sc as dt,tc as pt,uc as mt}from"./chunk-
|
|
2
|
+
import{C as H,D as j,E as le,F as L,I as de,J as G,K as f,Lb as pe,M as Ye,N as Qe,O as et,Ob as me,Pa as at,Pb as ct,Qb as $,U as tt,cb as nt,db as rt,eb as st,fb as ot,fc as ue,gb as it,gc as he,h as Je,hc as Re,i as We,ic as Te,jc as Ie,kc as Pe,lc as Ee,mc as _e,sb as xe,sc as dt,tc as pt,uc as mt}from"./chunk-ELUCM7CG.js";import{Da as C,Ea as Ge,Fa as Ue,Ga as ie,H as ze,Ha as Ke,Ia as X,Ja as ce,Ma as Xe,O as D,P as se,Qa as Ze,b as re,fa as oe,m as Q,ma as W,wa as Ve,xa as Fe}from"./chunk-TU5ITNMX.js";import{a as $e}from"./chunk-QUNRWDVO.js";import{a as lt}from"./chunk-6FA3GG5B.js";import{a as V,b as N,c as F,d as Y,e as R,h as we,l as A,n as ne}from"./chunk-HZP5U2AA.js";import{b as t}from"./chunk-ES2ISFJC.js";import{a as l}from"./chunk-FTQLQJQV.js";var Vt=t.string().trim().min(1).max(1e5),Ft=t.enum(["no_training","sft","preference","rl"]),Gt=t.object({kind:t.enum(["none","demonstrations","chosen_rejected","scalar_reward"]),strength:t.enum(["absent","weak","usable"]),calibrated:t.boolean(),confounded:t.boolean(),variance:t.number().finite().nonnegative().nullable(),evidenceRefs:t.array(R).max(1e5)}).strict(),ht=t.object({schemaVersion:t.literal("openpond.modelImprovementQualificationReceipt.v1"),id:V,review:R,harnessRelease:R,tasksetRelease:R.nullable(),baselineEvaluation:R.nullable(),model:ne,environmentHash:N.nullable(),toolContractHash:N.nullable(),permissionContractHash:N.nullable(),policyHash:N.nullable(),verifierRef:R.nullable(),sourcePolicies:t.array($e).max(1e4),trainingEvidenceRefs:t.array(R).max(1e5),frozenEvaluationEvidenceRefs:t.array(R).max(1e5),privacyApproval:R.nullable(),budgetApproval:R.nullable(),maximumCostUsd:t.number().finite().nonnegative(),signal:Gt,decision:Ft,reasons:t.array(Vt).min(1).max(100),createdAt:F,metadata:Y}).strict().superRefine((e,a)=>{let n=new Set(e.trainingEvidenceRefs.map(ut));if(e.frozenEvaluationEvidenceRefs.some(o=>n.has(ut(o)))&&a.addIssue({code:"custom",message:"frozen Evaluation evidence cannot be used as training evidence",path:["frozenEvaluationEvidenceRefs"]}),e.decision==="no_training")return;(!e.tasksetRelease||!e.baselineEvaluation||!e.environmentHash||!e.toolContractHash||!e.permissionContractHash||!e.policyHash||!e.verifierRef||!e.privacyApproval||!e.budgetApproval||e.sourcePolicies.length===0||e.sourcePolicies.some(o=>o.state!=="authorized")||e.trainingEvidenceRefs.length===0||e.signal.strength!=="usable"||!e.signal.calibrated||e.signal.confounded)&&a.addIssue({code:"custom",message:"qualified model improvement requires frozen lineage, authorized signal, privacy, and budget gates"}),e.decision==="sft"&&e.signal.kind!=="demonstrations"&&a.addIssue({code:"custom",message:"SFT qualification requires demonstration signal",path:["signal","kind"]}),e.decision==="preference"&&e.signal.kind!=="chosen_rejected"&&a.addIssue({code:"custom",message:"preference qualification requires chosen/rejected signal",path:["signal","kind"]}),e.decision==="rl"&&(e.signal.kind!=="scalar_reward"||e.signal.variance===null||e.signal.variance<=0)&&a.addIssue({code:"custom",message:"RL qualification requires a usable scalar reward with variance",path:["signal"]})}),Ut=ht.extend({contentHash:N}).strict();function gn(e){let a=ht.parse(e);return Ut.parse({...a,contentHash:A(a)})}l(gn,"createModelImprovementQualificationReceipt");function ut(e){return`${e.id}:${e.contentHash}`}l(ut,"refKey");var Kt=t.object({schemaVersion:t.literal("openpond.optimizerTrainingSample.v1"),tokenIds:t.array(t.number().int().nonnegative()).min(2).max(32768),mask:t.array(t.boolean()).min(2).max(32768),logprobs:t.array(t.number().finite()).min(2).max(32768),temperatures:t.array(t.number().positive().finite()).min(2).max(32768),envName:t.string().trim().min(1).max(200),modelRequestId:t.string().trim().min(1).max(1e3),promptTokenCount:t.number().int().positive(),completionTokenCount:t.number().int().positive(),servedPolicyVersion:t.number().int().nonnegative()}).strict().superRefine((e,a)=>{let n=e.tokenIds.length;for(let[r,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.length!==n&&a.addIssue({code:"custom",path:[r],message:`${r} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&a.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(r=>!r).length!==e.promptTokenCount&&a.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&a.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),Jt=t.object({id:V,environmentRelease:R,status:t.enum(["completed","failed","timed_out","cancelled"]),startedAt:F,completedAt:F,traceRefs:t.array(we).max(1e4),metadata:Y}).strict(),Wt=t.object({receiptRef:R,status:Ye,value:t.number().min(0).max(1).nullable(),learningEligible:t.boolean(),passed:t.boolean(),outcomeClass:et,failureOwner:Qe.nullable(),components:t.record(V,t.number().min(0).max(1).nullable())}).strict(),ft=t.object({schemaVersion:t.literal("openpond.canonicalRolloutRecord.v1"),id:V,attemptRef:R,artifactManifestRef:R,tasksetRelease:R,environmentRelease:R,verifierSetRelease:R,harnessRelease:R,taskId:V,split:Q,model:ne,seed:t.string().trim().min(1).max(500),reward:Wt,traceRef:we,optimizerSample:Kt.nullable(),environmentExecutions:t.array(Jt).min(1).max(1e5),startedAt:F,completedAt:F,metadata:Y}).strict();function gt(e,a){e.reward.status==="scored"&&(e.reward.value===null||!e.reward.learningEligible)&&a.addIssue({code:"custom",path:["reward","status"],message:"A scored rollout requires a numeric, learning-eligible reward."}),e.reward.status==="unscorable"&&(e.reward.value!==null||e.reward.learningEligible)&&a.addIssue({code:"custom",path:["reward","status"],message:"An unscorable rollout has no reward and cannot be learning-eligible."})}l(gt,"validateCanonicalRolloutRecord");var Xt=ft.superRefine(gt),Zt=t.object({...ft.shape,contentHash:N}).strict().superRefine(gt);function Rn(e){let a=Xe.parse(e.attemptReceipt);if(!Ze(a))throw new Error("Rollout Attempt Receipt failed content-hash verification.");let n=tt.parse(e.rewardReceipt);if(n.attemptRef.id!==a.id||n.attemptRef.contentHash!==a.contentHash)throw new Error("Rollout Attempt Receipt does not match its Reward Receipt.");if(n.artifactManifestRef.id!==e.artifactManifestRef.id||n.artifactManifestRef.contentHash!==e.artifactManifestRef.contentHash)throw new Error("Rollout Artifact Manifest does not match its Reward Receipt.");if(e.environmentExecutions.some(o=>o.environmentRelease.id!==e.environmentRelease.id||o.environmentRelease.contentHash!==e.environmentRelease.contentHash))throw new Error("Rollout Environment execution does not match its admitted Environment Release.");let r=Xt.parse({schemaVersion:"openpond.canonicalRolloutRecord.v1",id:e.id,attemptRef:n.attemptRef,artifactManifestRef:e.artifactManifestRef,tasksetRelease:e.tasksetRelease,environmentRelease:e.environmentRelease,verifierSetRelease:n.verifierSetRef,harnessRelease:e.harnessRelease,taskId:e.taskId,split:e.split,model:e.model,seed:e.seed,reward:{receiptRef:{id:n.id,contentHash:n.contentHash},status:n.status,value:n.reward,learningEligible:n.learningEligible,passed:n.passed,outcomeClass:n.outcomeClass,failureOwner:n.failureOwner,components:Object.fromEntries(n.components.map(o=>[o.verifierId,o.rewardContribution]))},traceRef:e.traceRef,optimizerSample:e.optimizerSample,environmentExecutions:e.environmentExecutions,startedAt:e.startedAt,completedAt:e.completedAt,metadata:e.metadata??{}});return Zt.parse({...r,contentHash:A(r)})}l(Rn,"createCanonicalRolloutRecord");function bt(e){let a=[],n=[],r="",o=!1,s=!1,c=l(()=>{n.push(r),r="",s=!1},"finishField"),i=l(()=>{if(c(),n.some(p=>p.length)&&a.push(n),n=[],a.length>C.records+1)throw new Error("CSV exceeds the 1,000-record limit.")},"finishRow");for(let p=0;p<e.length;p++){let d=e[p];if(o)d==='"'&&e[p+1]==='"'?(r+='"',p++):d==='"'?(o=!1,s=!0):r+=d;else if(d===",")c();else if(d===`
|
|
3
3
|
`||d==="\r")d==="\r"&&e[p+1]===`
|
|
4
4
|
`&&p++,i();else if(d==='"'&&!r&&!s)o=!0;else{if(s||d==='"')throw new Error("CSV has an invalid quoted field.");r+=d}}if(o)throw new Error("CSV has an unterminated quoted field.");(r||n.length||s)&&i();let u=a.shift()?.map(p=>p.trim().replace(/^\uFEFF/u,""));if(!u?.includes("instruction"))throw new Error("CSV requires an instruction column.");let h=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(u.some(p=>!h.has(p))||new Set(u).size!==u.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return a.map((p,d)=>{if(p.length!==u.length)throw new Error(`CSV record ${d+2} has a different number of columns from its header.`);return Object.fromEntries(u.map((m,g)=>[m,p[g]]).filter(([,m])=>m!==""))})}l(bt,"parseTaskIntakeCsv");function fe(e){return e.startsWith("\uFEFF")?e.slice(1):e}l(fe,"structuredIntakeText");var vt=t.object({role:t.string().min(1),content:t.json().nullable().optional()}).catchall(t.json()),Yt=t.object({id:t.string().min(1),messages:t.array(vt).min(1).max(C.messages),lineage_session_ids:t.array(t.string()).optional(),parent_session_id:t.string().nullable().optional()}).catchall(t.json());function St(e){let a=Yt.parse(e),n=a.lineage_session_ids?.[0]??a.parent_session_id??a.id,{messages:r,segments:o,...s}=a;return kt("hermes",a.id,n,a.messages,{sourceHash:A(e),metadata:{session:s},warnings:["Imported session context and tools need review before this can become an executable task."]})}l(St,"parseHermesSession");var Qt=t.object({traceSchema:t.literal("openclaw-trajectory"),schemaVersion:t.literal(1),traceId:t.string().min(1),sessionId:t.string().min(1),leafId:t.string().nullable(),eventCount:t.number().int().nonnegative(),warnings:t.array(D).optional()}).catchall(t.json()),ea=t.object({traceSchema:t.literal("openclaw-trajectory"),schemaVersion:t.literal(1),traceId:t.string(),sessionId:t.string(),seq:t.number().int().nonnegative(),type:t.string(),ts:t.string()}).catchall(t.json()),ta=t.object({header:D.nullable(),leafId:t.string().nullable(),entries:t.array(t.object({id:t.string().min(1),type:t.string().min(1),parentId:t.string().nullable().optional(),message:vt.optional()}).catchall(t.json())).max(C.messages)}).strict();function yt(e){let a=l(i=>{let u=e.find(h=>h.path===i);if(!u)throw new Error(`OpenClaw bundle is missing ${i}.`);return fe(u.text)},"read"),n=Qt.parse(JSON.parse(a("manifest.json"))),r=ta.parse(JSON.parse(a("session-branch.json")));if(r.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");let o=a("events.jsonl").split(/\r?\n/u).filter(i=>i.trim()).map(i=>ea.parse(JSON.parse(i)));if(o.length!==n.eventCount||o.some(i=>i.traceId!==n.traceId||i.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(r.header&&r.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");let s=new Set;for(let[i,u]of r.entries.entries()){if(s.has(u.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(i&&u.parentId!==r.entries[i-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");s.add(u.id)}if(r.entries.length&&r.entries.at(-1).id!==r.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");let c=r.entries.filter(i=>i.type==="message"&&i.message).map(i=>({...i.message,entryId:i.id,timestamp:typeof i.timestamp=="string"?i.timestamp:typeof i.message.timestamp=="number"?new Date(i.message.timestamp).toISOString():null}));return kt("openclaw",n.sessionId,n.sessionId,c,{sourceHash:A(e),metadata:{manifest:n,sourceFiles:e.map(i=>i.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(i=>typeof i.message=="string"?i.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}l(yt,"parseOpenClawBundle");function kt(e,a,n,r,o){let s=r.flatMap((i,u)=>i.role==="user"?[u]:[]);if(!s.length)throw new Error("This history contains no user request. Supply a session with its request context.");let c=0;return s.map((i,u)=>{let h=s[u+1]??r.length,p=r.slice(i+1,h),d=p.filter(x=>x.role==="assistant").at(-1),m=r[i],g=m.entryId??m.message_id??m.id??A({start:i,request:m}),v={id:X(e,[a,g]),familyKey:X(e,n),split:"train",kind:"attempt",input:{request:m.content??null,messages:r.slice(0,i+1)},observedOutput:d?{response:d.content??null,messages:p}:null,expected:null,sourceId:`${e}:${a}:${String(g)}`,sourceHash:o.sourceHash,occurredAt:ce(d?.timestamp??m.timestamp),metadata:o.metadata,warnings:[...o.warnings,...d?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(re(v),c+=new TextEncoder().encode(JSON.stringify(v)).length,c>C.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return ie.parse(v)})}l(kt,"historyRecords");var aa=t.object({instruction:t.string().trim().min(1).max(1e5),context:t.union([t.string(),D]).optional(),reference:t.union([t.string(),D]).optional(),labels:t.union([t.string(),t.array(t.string()),D]).optional(),id:t.string().min(1).max(200).optional(),familyKey:t.string().min(1).max(200).optional(),split:Q.optional()}).strict(),na=t.object({input:D,observedOutput:D.nullable().optional(),expectedOutput:D.nullable().optional(),id:t.string().min(1).max(200).optional(),familyKey:t.string().min(1).max(200).optional(),split:Q.optional(),occurredAt:t.string().datetime().optional(),labels:D.optional()}).strict();function Wn(e){let a=Ge.parse(e.format),n=t.array(Ue).min(1).max(C.files).parse(e.files);if(n.reduce((h,p)=>h+new TextEncoder().encode(p.text).length,0)>C.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(h=>h.path.startsWith("/")||h.path.includes("\\")||h.path.split("/").some(p=>!p||p==="."||p===".."))||new Set(n.map(h=>h.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");let r=[],o=[],s=new Map,c=new Map,i=0;function u(h,p,d){try{let m=d();if(r.length+m.length>C.records)throw new Error("Import exceeds the 1,000-record limit.");let g=new Map(s),v=new Map(c),x=0;for(let b of m){re(b);let T=A(b),I=g.get(b.id);if(I&&I!==T)throw new Error("The same record identity has different content in this upload.");I||(x+=new TextEncoder().encode(JSON.stringify(b)).length),g.set(b.id,T);for(let _ of[`family:${b.familyKey}`,`input:${A(b.input)}`]){if(v.has(_)&&v.get(_)!==b.split)throw new Error("The same task family or request occurs in different splits.");v.set(_,b.split)}}if(i+x>C.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(let b of m)s.has(b.id)||r.push(b),s.set(b.id,A(b));for(let[b,T]of v)c.set(b,T);i+=x}catch(m){o.push({file:h,row:p,message:m instanceof t.ZodError?`Unsupported record fields or values (${m.issues.slice(0,3).map(g=>g.path.join(".")||"record").join(", ")}).`:m instanceof SyntaxError?"Invalid JSON.":m instanceof Error?m.message:"Invalid import record."})}}if(l(u,"attempt"),a==="openclaw")u("manifest.json",null,()=>yt(n));else for(let h of n){let p=fe(h.text);if(a==="jsonl"||a==="hermes"){for(let[d,m]of p.split(/\r?\n/u).entries())if(m.trim()){if(o.length>=C.records)break;u(h.path,d+1,()=>a==="hermes"?St(JSON.parse(m)):[wt(JSON.parse(m))])}}else{let d;try{let m=a==="csv"?bt(p):JSON.parse(p);d=Array.isArray(m)?m:[m]}catch(m){u(h.path,null,()=>{throw m});continue}if(d.length>C.records){u(h.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}d.forEach((m,g)=>u(h.path,g+(a==="csv"?2:1),()=>[wt(m)]))}}return Ke.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:a,contentHash:A({format:a,files:n}),records:r,issues:o.slice(0,1e3)})}l(Wn,"previewTaskIntake");function wt(e){let a=t.union([aa,na]).parse(e),n="instruction"in a,r=n?{instruction:a.instruction,...a.context===void 0?{}:{context:a.context}}:a.input,o=n?a.reference===void 0?null:typeof a.reference=="string"?{text:a.reference}:a.reference:a.expectedOutput??null,s=n?null:a.observedOutput??null,c=a.familyKey??X("family",r),i=a.id??X("task",{input:r,expected:o,observedOutput:s});return ie.parse({id:i,familyKey:c,split:a.split??"train",kind:s?"attempt":"task",input:r,expected:o,observedOutput:s,sourceId:i,sourceHash:A(e),occurredAt:n?null:ce(a.occurredAt),metadata:a.labels===void 0?{}:{importedLabels:a.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}l(wt,"normalizeTask");var q=$.shape.id,M=t.number().int().positive(),U=t.string().regex(/^[a-f0-9]{64}$/),K={teamId:q,modelId:q},Zs=t.object({schemaVersion:t.literal("openpond.tasksetDraftCreate.v1"),operationId:q,modelId:q,expectedModelRevision:M,name:$.shape.name}).strict(),Ys=t.object({schemaVersion:t.literal("openpond.tasksetDraftSourceDescriptor.v1"),...K,expectedModelRevision:M,sourcePackageHash:U}).strict(),Qs=t.object({schemaVersion:t.literal("openpond.tasksetDraftReadback.v1"),...K,draft:$,workspaceHash:U,projectEtag:U}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model."),ra=t.object({id:q,revision:M,name:$.shape.name,status:ct,updatedAt:$.shape.updatedAt,sourceTasksetRef:se.nullable()}).strict(),eo=t.object({schemaVersion:t.literal("openpond.tasksetDraftList.v1"),...K,drafts:t.array(ra).max(100),nextCursor:t.string().min(1).max(2e3).nullable()}).strict(),to=t.object({expectedDraftRevision:M,draft:$}).strict(),ao=t.object({expectedDraftRevision:M,expectedModelRevision:M}).strict(),sa=t.object({expectedDraftRevision:M,expectedWorkspaceHash:U}).strict(),no=t.object({schemaVersion:t.literal("openpond.tasksetDraftValidation.v1"),...K,draftId:q,draftRevision:M,workspaceHash:U,valid:t.boolean(),issues:t.array(t.object({code:t.string().min(1),severity:t.enum(["warning","error"]),message:t.string(),path:t.string().nullable()}).strict()),packageHash:U.nullable(),tasksetRef:se.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(a=>a.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(a=>a.severity==="error"),"Validation must retain either a compiled package or publication errors."),ro=sa.extend({operationId:q,expectedPackageHash:U,expectedTasksetRef:se}).strict(),so=t.object({schemaVersion:t.literal("openpond.tasksetDraftFileList.v1"),...K,draftId:q,draftRevision:M,files:t.array(Je).max(10020)}).strict(),oo=t.object({schemaVersion:t.literal("openpond.tasksetDraftFileReadback.v1"),...K,draftId:q,draftRevision:M,file:We}).strict(),io=t.object({schemaVersion:t.literal("openpond.tasksetDraftDeletion.v1"),...K,draftId:q,revision:M,deleted:t.literal(!0)}).strict(),lo=$.shape.id,po=t.number().int().positive();var B=t.string().trim().min(1).max(500),uo=t.object({projectId:B.optional(),tasksetId:B.optional(),draftId:B.optional(),taskId:B.optional(),query:t.string().trim().max(1e3).default(""),split:t.enum(["train","validation","test","frozen_eval"]).optional(),after:t.string().min(1).max(2e3).optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),oa=t.object({id:B,method:t.enum(["code","judge","human"]),required:t.boolean()}),ia=t.object({tasksetId:B,tasksetName:t.string(),tasksetRevision:t.number().int().positive(),tasksetHash:t.string(),taskId:B,ordinal:t.number().int().nonnegative(),title:t.string(),description:t.string(),split:t.string(),scoring:t.array(oa),configuration:t.enum(["configured","needs_reward","needs_checks"]),draftId:B.nullable().default(null),modelId:B.nullable().default(null)}),ho=t.object({items:t.array(ia).max(100),nextCursor:t.string().nullable()});function fo(e,a){let n=[e.instruction,e.prompt,e.request,e.question,e.message].find(s=>typeof s=="string"&&s.trim().length>0),r=typeof e.title=="string"?e.title.trim():"",o=n?.trim()??"";return{title:(r||o||a).slice(0,180),description:o.slice(0,2e3)}}l(fo,"describeTaskInput");function go(e){return e.map(a=>({id:a.id,method:a.kind==="model_judge"?"judge":a.kind==="human"?"human":"code",required:a.hardGate}))}l(go,"summarizeTaskScoring");function bo(e){return e.some(a=>a.kind!=="human")?e.some(a=>a.kind==="model_judge"&&a.calibrationStatus!=="passed")?"needs_checks":"configured":"needs_reward"}l(bo,"taskConfiguration");var He=3e3,Oe=9999,ge="openpond.yaml",wo="openpond-template-plan.json",ca="openpond.sandboxTemplate.buildPlan.v1",la=["google","github","x"],De=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),xt=t.array(t.string().trim().min(1).max(1e3)).max(50),ee=t.string().trim().min(1).max(4096).refine(_t,{message:"path must be a relative workspace path"}),da=t.string().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),pa=t.string().trim().regex(/^sha256:[0-9a-f]{64}$/i),Tt=t.string().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),ma=t.object({ref:da,digest:pa.optional(),registrySecretRef:t.string().trim().min(1).max(500).optional(),platform:t.literal("linux/amd64").optional(),workspaceRoot:Tt.optional()}).strict(),ua=t.object({context:ee.default("."),path:ee.default("Dockerfile"),target:t.string().trim().min(1).max(191).optional(),buildArgs:t.record(t.string().max(191),t.string().max(500)).optional(),registrySecretRefs:t.array(t.string().trim().min(1).max(500)).max(10).optional(),platform:t.literal("linux/amd64").optional(),workspaceRoot:Tt.optional()}).strict(),ha=t.object({base:t.string().trim().min(1).max(120).optional(),snapshot:t.string().trim().min(1).max(191).optional(),image:ma.optional(),dockerfile:ua.optional()}).strict().superRefine((e,a)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&a.addIssue({code:t.ZodIssueCode.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),It=t.object({cpu:t.number().positive().max(8).optional(),memoryGb:t.number().positive().max(32).optional(),diskGb:t.number().positive().max(100).optional()}).strict(),fa=t.object({provider:t.enum(la),scopes:t.array(t.string().trim().min(1).max(200)).max(100).default([]),capabilities:t.array(t.string().trim().min(1).max(200)).max(100).default([])}).strict(),ga=t.object({models:t.array(t.string().trim().min(1).max(200)).max(100).default([]),scopes:t.array(t.string().trim().min(1).max(200)).max(100).default([])}).strict(),ba=t.object({opchat:ga.optional()}).catchall(t.record(t.string(),t.unknown())).default({}),va=t.object({name:t.string().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:t.string().trim().min(1).max(256).optional(),storageGb:t.number().int().positive().max(100).optional(),deleteOnSandboxDelete:t.boolean().optional()}).strict(),Sa=t.object({port:t.number().int().min(He).max(Oe).refine(e=>!De.has(e),{message:"preview port is reserved"}),protocol:t.literal("http").default("http"),label:t.string().trim().min(1).max(80).optional(),access:t.enum(["private","public"]).default("private"),path:t.string().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),Pt=t.object({command:t.string().trim().min(1).max(1e3),cwd:ee.optional(),timeoutSeconds:t.number().int().positive().max(86400).optional(),requiresStart:t.boolean().default(!1),ports:t.array(Sa).max(20).default([]),artifactPaths:t.array(ee).max(100).default([])}).strict(),Rt=Pt.extend({name:t.string().trim().min(1).max(80)}).strict(),ya=t.object({name:t.string().trim().min(1).max(80).optional(),service:t.string().trim().min(1).max(80).optional(),port:t.number().int().min(He).max(Oe).refine(e=>!De.has(e),{message:"app MCP port is reserved"}),path:t.string().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),ka=t.object({name:t.string().trim().min(1).max(80).optional(),port:t.number().int().min(He).max(Oe).refine(e=>!De.has(e),{message:"validation probe port is reserved"}),path:t.string().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:t.number().int().min(100).max(599).default(200)}).strict(),wa=t.record(t.string(),t.unknown()).refine(e=>e.type==="object","input schema must be a JSON schema object"),xa=t.object({name:t.string().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:t.boolean().default(!1),secret:t.boolean().default(!0),description:t.string().trim().max(500).optional()}).strict(),Ae=t.string().trim().min(1).max(120),Ra=t.object({name:t.string().trim().min(1).max(120),description:t.string().trim().max(500).optional(),cron:t.string().trim().min(1).max(500).optional(),rate:t.string().trim().min(1).max(500).optional(),once:Ae.optional(),scheduleType:t.enum(["rate","cron","once"]).optional(),scheduleExpression:t.string().trim().min(1).max(500).optional(),timezone:t.string().trim().min(1).max(100).optional(),enabled:t.boolean().default(!0),startAt:Ae.optional(),endAt:Ae.optional(),maxRuns:t.number().int().positive().nullable().optional(),runtimePolicy:t.enum(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:t.string().trim().min(1).max(120).optional(),actionName:t.string().trim().min(1).max(120).optional(),command:t.string().trim().min(1).max(2e3).optional(),target:t.object({kind:t.enum(["start","action","service","command"]).optional(),name:t.string().trim().min(1).max(120).optional(),actionName:t.string().trim().min(1).max(120).optional(),command:t.string().trim().min(1).max(2e3).optional(),requiresStart:t.boolean().optional()}).strict().optional(),requiresStart:t.boolean().optional(),budget:t.object({maxUsd:t.string().trim().min(1).max(40).optional()}).strict().optional(),resources:It.optional(),quotas:t.record(t.string(),t.unknown()).optional(),lifecycle:t.record(t.string(),t.unknown()).optional(),retentionPolicy:t.record(t.string(),t.unknown()).optional(),env:t.array(t.object({name:t.string().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:t.string().optional(),secretRef:t.string().optional()}).strict()).max(100).optional(),integrationLeases:t.array(t.record(t.string(),t.unknown())).max(20).optional(),metadata:t.record(t.string(),t.unknown()).optional()}).strict().superRefine((e,a)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(i=>typeof i=="string"&&i.trim()).length!==1&&a.addIssue({code:t.ZodIssueCode.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&a.addIssue({code:t.ZodIssueCode.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});let r=e.command??e.target?.command??null,o=e.target?.name??null,s=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),c=e.target?.kind??(r?"command":"action");c==="action"&&!s&&a.addIssue({code:t.ZodIssueCode.custom,path:["action"],message:"schedule action target is required"}),c==="service"&&!o&&a.addIssue({code:t.ZodIssueCode.custom,path:["target","name"],message:"schedule service target name is required"}),c==="command"&&!r&&a.addIssue({code:t.ZodIssueCode.custom,path:["command"],message:"schedule command target is required"})}),Ta=t.object({schemaVersion:t.literal(1),name:t.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:t.string().trim().min(1).max(40),useCase:t.string().trim().min(1).max(80),description:t.string().trim().min(1).max(500),runtime:ha,resources:It.optional(),setup:t.object({commands:xt.default([])}).strict().default({commands:[]}),validation:t.object({commands:xt.min(1),probes:t.array(ka).max(20).default([])}).strict(),start:Pt,actions:t.array(Rt).max(20).default([]),services:t.array(Rt).max(20).default([]),schedules:t.array(Ra).max(20).default([]),mcp:t.object({endpoints:t.array(ya).max(10).default([])}).strict().default({endpoints:[]}),volumes:t.array(va).max(5).default([]),integrations:t.object({requiredLeases:t.array(fa).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:ba,inputs:t.object({schema:wa.default({type:"object"}),env:t.array(xa).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:t.object({paths:t.array(ee).max(100).default([])}).strict().default({paths:[]}),network:t.object({egress:t.enum(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,a)=>{_a(e,a),Me(a,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Aa(e,a),Ca(e,a),ja(e,a),Ha(e,a)}),xo=t.object({path:t.string(),message:t.string(),code:t.string()});function Ro(e){let a;try{a=lt.load(e)}catch(n){return{ok:!1,manifest:null,diagnostics:[{path:"$",code:"invalid_yaml",message:n instanceof Error?n.message:"Invalid YAML"}]}}return Ia(a)}l(Ro,"validateSandboxTemplateYaml");function Ia(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,manifest:null,diagnostics:[{path:"$",code:"invalid_type",message:`${ge} must be an object`}]};if(Object.prototype.hasOwnProperty.call(e,"databases"))return{ok:!1,manifest:null,diagnostics:[{path:"$.databases",code:"database_resources_removed",message:"managed database requests are unsupported for Firecracker sandbox templates; use a durable volume with SQLite or files instead"}]};let a=Ta.safeParse(e);return a.success?{ok:!0,manifest:a.data,diagnostics:[]}:{ok:!1,manifest:null,diagnostics:a.error.issues.map(n=>({path:Ea(n.path),code:n.code,message:n.message}))}}l(Ia,"validateSandboxTemplateManifest");function To(e){return e.map(a=>`${a.path}: ${a.message}`).join(`
|
|
5
5
|
`)}l(To,"formatSandboxTemplateDiagnostics");function Et(e){return[{kind:"start",name:"start",...e.start,artifactPaths:je(e.start,e)},...e.actions.map(a=>({kind:"action",name:a.name,command:a.command,cwd:a.cwd,timeoutSeconds:a.timeoutSeconds,requiresStart:a.requiresStart,ports:a.ports,artifactPaths:je(a,e)})),...e.services.map(a=>({kind:"service",name:a.name,command:a.command,cwd:a.cwd,timeoutSeconds:a.timeoutSeconds,requiresStart:a.requiresStart,ports:a.ports,artifactPaths:je(a,e)}))]}l(Et,"sandboxTemplateExecutableEntries");function Pa(e){let a=Et(e);return{template:{name:e.name,version:e.version,useCase:e.useCase,runtime:e.runtime},resources:e.resources??null,volumes:e.volumes,executables:a.map(n=>({kind:n.kind,name:n.name,command:n.command,cwd:n.cwd??null,timeoutSeconds:n.timeoutSeconds??null,requiresStart:n.requiresStart,ports:n.ports.map(r=>r.port),artifactPaths:n.artifactPaths})),ports:a.flatMap(n=>n.ports.map(r=>({executable:n.name,kind:n.kind,port:r.port,access:r.access,label:r.label??null}))),appMcpEndpoints:e.mcp.endpoints.map(n=>({name:n.name??null,service:n.service??null,port:n.port,path:n.path})),validation:{commands:e.validation.commands,probes:e.validation.probes},schedules:e.schedules}}l(Pa,"sandboxTemplateBuildMetadata");function Io(e){return{kind:ca,schemaVersion:1,manifestFile:e.manifestFile,projectRoot:e.projectRoot,manifest:e.manifest,metadata:Pa(e.manifest),executables:Et(e.manifest)}}l(Io,"sandboxTemplateBuildPlan");function Po(e){let a=e.name.trim()||"Sandbox Template",n=Oa(a),r=e.description?.trim()||`Local scaffold for ${a}.`;return{".gitignore":["node_modules","artifacts",".DS_Store",""].join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{e as g,g as $,h as O,i as C}from"./chunk-
|
|
2
|
+
import{e as g,g as $,h as O,i as C}from"./chunk-IYWNO4RB.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as Et,b as Pe}from"./chunk-L3KS6MOV.js";import{x as bt}from"./chunk-MRGA6BKG.js";import{b as j,d as ye,e as we}from"./chunk-MJC26GOX.js";import{$ as ge,Ja as Ct,Ka as vt,Ua as De,ya as Ne,za as je}from"./chunk-QK2GLRCY.js";import{f as L,h as me,p as Le,r as It}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{createRequire as Po}from"node:module";import{createHash as po,randomUUID as ho}from"node:crypto";import{spawn as Pr}from"node:child_process";import{existsSync as U}from"node:fs";import{cp as Sr,mkdir as F,readFile as So,readdir as Ao,rename as at,rm as it,symlink as Ar,writeFile as ie}from"node:fs/promises";import d from"node:path";import Sn from"node:path";var Se="default",Rt=["apiKey","baseUrl","apiBaseUrl","chatApiBaseUrl","token","appId","conversationId"];function W(e,t){return Object.prototype.hasOwnProperty.call(e,t)}a(W,"hasOwn");function z(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}a(z,"normalizeHandle");function _(e){if(typeof e!="string")return null;let t=e.trim();return t?t.replace(/\/$/,""):null}a(_,"normalizeBaseUrl");function Bt(e){let t=z(e);if(!t)throw new Error("profile handle must be non-empty");return t}a(Bt,"requireHandle");function An(e){if(typeof e!="string")throw new Error("apiKey must be a non-empty string");let t=e.trim();if(!t)throw new Error("apiKey must be a non-empty string");return t}a(An,"requireApiKey");function de(e,t){let o=z(e),n=z(t);return!!(o&&n&&o.toLowerCase()===n.toLowerCase())}a(de,"handleEquals");function qe(e,t,o){let n=_(o);return e.findIndex(r=>de(r.handle,t)?n?_(r.baseUrl)===n:!0:!1)}a(qe,"findAccountIndex");function ne(e){let t=z(e.handle)??Se,o=_(e.baseUrl);return o?{handle:t,baseUrl:o}:{handle:t}}a(ne,"selectorFromAccount");function oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n=_(typeof t.baseUrl=="string"?t.baseUrl:void 0);return n?{handle:o,baseUrl:n}:{handle:o}}a(oe,"sanitizeActiveProfile");function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=typeof t.repoPath=="string"?t.repoPath.trim():"",n=typeof t.profile=="string"&&t.profile.trim()?t.profile.trim():"default";if(!o)return;let r={repoPath:o,profile:n,mode:"local"};if(t.lastCheck&&typeof t.lastCheck=="object"&&!Array.isArray(t.lastCheck)){let s=t.lastCheck,i=s.command,c=s.status,l=s.checkedAt;(i==="inspect"||i==="build"||i==="validate"||i==="eval"||i==="run")&&(c==="passed"||c==="failed")&&typeof l=="string"&&(r.lastCheck={command:i,status:c,checkedAt:l,...typeof s.exitCode=="number"||s.exitCode===null?{exitCode:s.exitCode}:{},...typeof s.sourceHead=="string"||s.sourceHead===null?{sourceHead:s.sourceHead}:{}})}if(t.lastPush&&typeof t.lastPush=="object"&&!Array.isArray(t.lastPush)){let s=t.lastPush,i=s.status,c=s.pushedAt;(i==="pushed"||i==="failed")&&typeof c=="string"&&(r.lastPush={status:i,pushedAt:c,...typeof s.teamId=="string"||s.teamId===null?{teamId:s.teamId}:{},...typeof s.projectId=="string"||s.projectId===null?{projectId:s.projectId}:{},...typeof s.localHead=="string"||s.localHead===null?{localHead:s.localHead}:{},...typeof s.hostedHead=="string"||s.hostedHead===null?{hostedHead:s.hostedHead}:{},...typeof s.sourceRef=="string"||s.sourceRef===null?{sourceRef:s.sourceRef}:{},...s.promotionStatus==="uploaded"||s.promotionStatus==="hosted_source_materialized"||s.promotionStatus==="hosted_source_materialize_failed"||s.promotionStatus==="hosted_source_check_pending"||s.promotionStatus==="hosted_source_check_failed"||s.promotionStatus==="hosted_source_published"||s.promotionStatus==="hosted_source_publish_failed"||s.promotionStatus==="hosted_run_pending"||s.promotionStatus==="hosted_run_passed"||s.promotionStatus==="hosted_run_failed"||s.promotionStatus===null?{promotionStatus:s.promotionStatus}:{},...s.hostedRunStatus==="not_started"||s.hostedRunStatus==="running"||s.hostedRunStatus==="passed"||s.hostedRunStatus==="failed"||s.hostedRunStatus===null?{hostedRunStatus:s.hostedRunStatus}:{},...typeof s.hostedRunAgentId=="string"||s.hostedRunAgentId===null?{hostedRunAgentId:s.hostedRunAgentId}:{},...typeof s.hostedRunId=="string"||s.hostedRunId===null?{hostedRunId:s.hostedRunId}:{},...typeof s.hostedRunAt=="string"||s.hostedRunAt===null?{hostedRunAt:s.hostedRunAt}:{},..._t(s.hostedSourceMaterialization)?{hostedSourceMaterialization:_t(s.hostedSourceMaterialization)}:{},...$t(s.hostedSourceCheck)?{hostedSourceCheck:$t(s.hostedSourceCheck)}:{},...Ot(s.hostedPublish)?{hostedPublish:Ot(s.hostedPublish)}:{},...Tt(s.hostedRun)?{hostedRun:Tt(s.hostedRun)}:{},...typeof s.error=="string"||s.error===null?{error:s.error}:{}})}if(Array.isArray(t.profiles)){let s=t.profiles.flatMap(i=>{let c=Fe(i);if(!c)return[];let l=i,u=l.source==="github"||l.source==="openpond_git"?l.source:"local",p=typeof l.repositoryId=="string"&&l.repositoryId.trim()?l.repositoryId.trim():Sn.resolve(c.repoPath);return[{source:u,repositoryId:p,repoPath:c.repoPath,profile:c.profile,...c.lastCheck?{lastCheck:c.lastCheck}:{},...c.lastPush?{lastPush:c.lastPush}:{}}]});s.length>0&&(r.profiles=s)}return r}a(Fe,"sanitizeLocalOpenPondProfile");function _t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runtimeAgentId"),...m(t,"projectId"),...m(t,"sourceRoot"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"manifestSyncedAt"),...Ut(t,"fileCount"),...Ut(t,"totalBytes"),...m(t,"generatedManifestPath"),...He(t,"synthesizedOpenPondYaml"),...m(t,"uploadMetadataPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...m(t,"materializedAt"),...m(t,"error")}:null}a(_t,"sanitizeHostedMaterializationStatus");function $t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"deployPlanStatus"),...He(t,"canRun"),...He(t,"canDeploy"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...O(t,"requiredChecks"),...O(t,"evalNames"),...O(t,"blockedReasons"),...O(t,"staleReasons"),...m(t,"runtimeId"),...m(t,"sandboxId"),...O(t,"traceArtifactRefs"),...O(t,"evalResultArtifactRefs"),...O(t,"validatorArtifactRefs"),...m(t,"checkedAt"),...m(t,"error")}:null}a($t,"sanitizeHostedSourceCheckStatus");function Ot(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"snapshotId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"buildStatus"),...m(t,"validationStatus"),...m(t,"evalStatus"),...m(t,"publishedAt"),...m(t,"error")}:null}a(Ot,"sanitizeHostedPublishStatus");function Tt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runId"),...m(t,"runtimeId"),...m(t,"sandboxId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"setupGateStatus"),...O(t,"setupRequirementRefs"),...O(t,"artifactRefs"),...O(t,"traceArtifactRefs"),...O(t,"evalArtifactRefs"),...m(t,"startedAt"),...m(t,"completedAt"),...m(t,"error")}:null}a(Tt,"sanitizeHostedRunSummary");function m(e,t){let o=e[t];return typeof o=="string"||o===null?{[t]:o}:{}}a(m,"nullableStringProp");function He(e,t){let o=e[t];return typeof o=="boolean"||o===null?{[t]:o}:{}}a(He,"nullableBooleanProp");function Ut(e,t){let o=e[t];return typeof o=="number"||o===null?{[t]:o}:{}}a(Ut,"nullableNumberProp");function O(e,t){let o=e[t];if(!Array.isArray(o))return{};let n=o.filter(r=>typeof r=="string");return{[t]:n}}a(O,"stringArrayProp");function Ae(e){return typeof e=="string"&&e.trim()?e.trim():null}a(Ae,"stringField");function Lt(e,t){if(!de(e.handle,t.handle))return!1;let o=_(t.baseUrl);return o?_(e.baseUrl)===o:!_(e.baseUrl)}a(Lt,"accountMatchesSelector");function Ge(e,t,o={}){let n=_(t.baseUrl);if(n)return qe(e,t.handle,n);let r=e.findIndex(i=>Lt(i,t));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>de(i.handle,t.handle));if(s.length>1&&o.requireUnambiguous)throw new Error(`multiple profiles found for ${t.handle}; pass --base-url to select one`);return s[0]?.index??-1}a(Ge,"findAccountIndexForSelector");function xn(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o={};return typeof t.token=="string"&&(o.token=t.token),(typeof t.appId=="string"||t.appId===null)&&(o.appId=t.appId),(typeof t.conversationId=="string"||t.conversationId===null)&&(o.conversationId=t.conversationId),Object.keys(o).length>0?o:void 0}a(xn,"sanitizeSession");function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n={handle:o};typeof t.apiKey=="string"&&(n.apiKey=t.apiKey),typeof t.baseUrl=="string"&&(n.baseUrl=t.baseUrl),typeof t.apiBaseUrl=="string"&&(n.apiBaseUrl=t.apiBaseUrl),typeof t.chatApiBaseUrl=="string"&&(n.chatApiBaseUrl=t.chatApiBaseUrl),typeof t.environment=="string"&&(n.environment=t.environment);let r=xn(t.session);return r&&(n.session=r),n}a(kn,"sanitizeAccount");function bn(e){let t={};return typeof e.token=="string"&&(t.token=e.token),(typeof e.appId=="string"||e.appId===null)&&(t.appId=e.appId),(typeof e.conversationId=="string"||e.conversationId===null)&&(t.conversationId=e.conversationId),Object.keys(t).length>0?t:void 0}a(bn,"extractLegacySession");function In(e,t){let o={handle:t};typeof e.apiKey=="string"&&(o.apiKey=e.apiKey),typeof e.baseUrl=="string"&&(o.baseUrl=e.baseUrl),typeof e.apiBaseUrl=="string"&&(o.apiBaseUrl=e.apiBaseUrl),typeof e.chatApiBaseUrl=="string"&&(o.chatApiBaseUrl=e.chatApiBaseUrl);let n=bn(e);return n&&(o.session=n),o}a(In,"extractLegacyAccount");function Nt(e){let t={};typeof e.lspEnabled=="boolean"&&(t.lspEnabled=e.lspEnabled),(e.executionMode==="local"||e.executionMode==="hosted")&&(t.executionMode=e.executionMode),(e.mode==="general"||e.mode==="builder")&&(t.mode=e.mode);let o=Fe(e.openpondProfile);o&&(t.openpondProfile=o);let n=[],r=Array.isArray(e.accounts)?e.accounts:[];for(let l of r){let u=kn(l);u&&qe(n,u.handle,u.baseUrl)===-1&&n.push(u)}if(n.length===0){let l=oe(e.activeProfile)?.handle||Se;n.push(In(e,l))}let s=oe(e.activeProfile),i=s?Ge(n,s):-1,c=n[i===-1?0:i];return t.accounts=n,t.activeProfile=ne(c),t}a(Nt,"normalizeGlobalConfig");function Cn(e,t,o){let n=e.accounts??[],r=_(o??process.env.OPENPOND_BASE_URL),s=z(t);if(s)return r?{handle:s,baseUrl:r}:{handle:s};let i=z(process.env.OPENPOND_ACCOUNT);if(i)return r?{handle:i,baseUrl:r}:{handle:i};let c=oe(e.activeProfile);return c?r?{handle:c.handle,baseUrl:r}:c:n[0]?ne(n[0]):{handle:Se}}a(Cn,"resolveRequestedProfile");function jt(e,t,o){let n=_(o);if(n){let s=qe(e,t,n);if(s!==-1)return e[s]}else{let s=e.filter(i=>de(i.handle,t));if(s.length>1)throw new Error(`multiple profiles found for ${t}; pass --base-url to select one`);if(s.length===1)return s[0]}let r={handle:t};return n&&(r.baseUrl=n),e.push(r),r}a(jt,"ensureAccount");function Mt(e){e.session&&Object.keys(e.session).length===0&&delete e.session}a(Mt,"cleanupAccount");function vn(e,t,o,n){let r=o===null||o===void 0&&n.undefinedDeletes;switch(t){case"apiKey":{if(r){delete e.apiKey;return}typeof o=="string"&&(e.apiKey=o);return}case"baseUrl":{if(r){delete e.baseUrl;return}typeof o=="string"&&(e.baseUrl=o);return}case"apiBaseUrl":{if(r){delete e.apiBaseUrl;return}typeof o=="string"&&(e.apiBaseUrl=o);return}case"chatApiBaseUrl":{if(r){delete e.chatApiBaseUrl;return}typeof o=="string"&&(e.chatApiBaseUrl=o);return}case"token":case"appId":case"conversationId":{if(e.session||(e.session={}),r){delete e.session[t],Mt(e);return}(typeof o=="string"||o===null)&&(e.session[t]=o),Mt(e);return}}}a(vn,"applyScopedKey");function En(e,t,o){if(!Rt.some(l=>W(t,l)))return!1;let r=e.accounts??[],s=oe(t.activeProfile)??Cn(e),i=_(W(t,"baseUrl")?t.baseUrl??null:s.baseUrl??process.env.OPENPOND_BASE_URL),c=jt(r,s.handle,i);for(let l of Rt)W(t,l)&&vn(c,l,t[l],o);return e.accounts=r,e.activeProfile=ne(c),!0}a(En,"applyAccountPatch");function Rn(e,t){if(W(t,"lspEnabled")&&(typeof t.lspEnabled=="boolean"?e.lspEnabled=t.lspEnabled:t.lspEnabled===null&&delete e.lspEnabled),W(t,"executionMode")&&(t.executionMode==="local"||t.executionMode==="hosted"?e.executionMode=t.executionMode:t.executionMode===null&&delete e.executionMode),W(t,"mode")&&(t.mode==="general"||t.mode==="builder"?e.mode=t.mode:t.mode===null&&delete e.mode),W(t,"activeProfile")){let o=oe(t.activeProfile);if(o){let n=Ge(e.accounts??[],o);e.activeProfile=n===-1?o:ne((e.accounts??[])[n])}else t.activeProfile===null&&delete e.activeProfile}if(W(t,"openpondProfile")){let o=Fe(t.openpondProfile);o?e.openpondProfile=o:t.openpondProfile===null&&delete e.openpondProfile}}a(Rn,"applyTopLevelPatch");async function xe(e){let t=L();return await De(t),await vt(t,o=>{let n=Nt(o);return e(n),n})}a(xe,"updateGlobalConfig");async function T(){let e=L();return await De(e),Nt(await Ct(e))}a(T,"loadGlobalConfig");async function ze(){let e=await T(),t=oe(e.activeProfile);return(e.accounts??[]).map(o=>{let n=z(o.handle)??Se;return{handle:n,baseUrl:_(o.baseUrl),apiBaseUrl:_(o.apiBaseUrl),chatApiBaseUrl:_(o.chatApiBaseUrl),environment:o.environment?.trim()||null,isActive:!!(t&&Lt({...o,handle:n},t)),hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!o.session?.token?.trim(),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null}})}a(ze,"listConfiguredProfiles");async function _n(e,t={}){let o=Bt(e),n=_(t.baseUrl),r=-1;await xe(i=>{let c=i.accounts??[];if(r=Ge(c,n?{handle:o,baseUrl:n}:{handle:o},{requireUnambiguous:!0}),r===-1)throw new Error(`profile not found: ${o}`);i.activeProfile=ne(c[r])});let s=await ze();return s.find(i=>i.isActive)??s[r]}a(_n,"setActiveProfile");async function $n(e){let t=Bt(e.handle),o=An(e.apiKey),n=_(e.baseUrl),r=_(e.apiBaseUrl),s=_(e.chatApiBaseUrl),i={handle:t};await xe(u=>{let p=u.accounts??[],h=jt(p,t,n);h.apiKey=o,n&&(h.baseUrl=n),r?h.apiBaseUrl=r:e.apiBaseUrl===null&&delete h.apiBaseUrl,s?h.chatApiBaseUrl=s:e.chatApiBaseUrl===null&&delete h.chatApiBaseUrl,e.environment===null?delete h.environment:typeof e.environment=="string"&&e.environment.trim()&&(h.environment=e.environment.trim()),u.accounts=p,i=ne(h),e.setActive!==!1&&(u.activeProfile=i)});let l=(await ze()).find(u=>de(u.handle,i.handle)?n?_(u.baseUrl)===n:!0:!1);if(!l)throw new Error(`failed to save profile: ${t}`);return l}a($n,"saveProfileApiKey");async function H(e){await xe(t=>{Rn(t,e),En(t,e,{undefinedDeletes:!1})})}a(H,"saveGlobalConfig");function Je(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}a(Je,"emptyProfileCatalogState");function Ke(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}a(Ke,"emptyProfileSkillCatalogState");function We(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}a(We,"emptyProfileSetupGate");function ke(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}a(ke,"emptyProfileDiffSummary");function Ve(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}a(Ve,"emptyProfileSummary");import{existsSync as re}from"node:fs";import{readFile as On,stat as Tn}from"node:fs/promises";import be from"node:path";var Dt=".openpond/agent-manifest.json",Ht=".openpond/action-registry.json",Un=".openpond/source-upload-metadata.json",Mn=".openpond/agent-package-origin.json";async function Gt(e){return Jt({agentId:"default",sourcePath:e,preferred:!0})}a(Gt,"loadProfileActionCatalog");async function zt(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(c=>c.preferred),...e.filter(c=>!c.preferred)],o=await Promise.all(t.map(Jt)),n=new Map,r=[];for(let c of o)for(let l of c.actionCatalog){let u=n.has(l.id)?`${l.agentId??"agent"}.${l.sourceActionId??l.id}`:l.id,p=u===l.id?l:{...l,id:u};n.set(u,p),r.push(p)}let s=Ln(o.map(c=>c.catalog.generatedAt)),i=o.map(c=>c.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:s,manifestPath:o.find(c=>c.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:o.find(c=>c.catalog.registryPath)?.catalog.registryPath??null,stale:o.some(c=>c.catalog.stale),error:i.length>0?i.join("; "):null},actionCatalog:r,sourceSetupRequirements:o.flatMap(c=>c.sourceSetupRequirements)}}a(zt,"loadProfileActionCatalogForSources");async function Jt(e){let t=e.sourcePath,o=be.join(t,Dt),n=be.join(t,Ht),r=be.join(t,Un),s=be.join(t,Mn);try{let i=await Ie(o),c=await Ie(n),l=await Ie(r),u=$(await Ie(s)),p=$($(i)?.inputSchemas),h=Ft($(l)?.setupRequirements)??[],k=Nn(h),C=new Map;for(let f of[...Ye($(i)?.actionCatalog),...Ye($(c)?.actions),...Ye($(i)?.actions)]){let y=b(f.id)??b(f.name);if(!y)continue;let x=C.get(y),v=jn({sourceRequirementsByAction:k,actionId:y,actionName:b(f.name)}),B=Dn(Ft(f.setupRequirements)??x?.setupRequirements??[],v),K={id:y,agentId:e.agentId,sourcePath:t,sourceActionId:y,name:b(f.name)??x?.name??y,label:b(f.label)??x?.label??zn(y),description:b(f.description)??x?.description??null,visibility:b(f.visibility)??x?.visibility??"default",inputSchema:Gn(f.inputSchema,p)??x?.inputSchema??null,outputSchema:Kt(f.outputSchema)??x?.outputSchema??null,approvalPolicy:$(f.approvalPolicy)??x?.approvalPolicy??null,artifactPolicy:$(f.artifactPolicy)??x?.artifactPolicy??null,setupRequirements:B,mcp:$(f.mcp)??x?.mcp??null,schedulePolicy:$(f.schedulePolicy)??x?.schedulePolicy??null,trace:Bn($(f.trace)??x?.trace??null,u),implementation:$(f.implementation)??x?.implementation??null,invokesModel:typeof f.invokesModel=="boolean"?f.invokesModel:x?.invokesModel};C.set(y,K)}let P=Array.from(C.values()).filter(f=>f.visibility!=="internal"&&f.visibility!=="debug"),g=[...i?[]:[Dt],...c?[]:[Ht]],S=await Fn([o,n]);return{catalog:{actionCount:P.length,generatedAt:S,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:g.length>0,error:g.length>0?qn(e,g):null},actionCatalog:P,sourceSetupRequirements:h}}catch(i){return{catalog:{actionCount:0,generatedAt:null,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:!0,error:i instanceof Error?i.message:String(i)},actionCatalog:[],sourceSetupRequirements:[]}}}a(Jt,"loadProfileActionCatalogSource");function Bn(e,t){if(!t)return e;let o=b(t.versionId),n=b(t.digest);return!o||!n?e:{...e??{},agentVersionId:o,agentPackageDigest:n,validationReceiptIds:qt(t.validationReceiptIds),evalReceiptIds:qt(t.evalReceiptIds)}}a(Bn,"mergeAgentPackageTrace");function qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}a(qt,"stringArray");function Ln(e){let t=0;for(let o of e){if(!o)continue;let n=Date.parse(o);Number.isFinite(n)&&(t=Math.max(t,n))}return t>0?new Date(t).toISOString():null}a(Ln,"latestIso");function Nn(e){let t=new Map;for(let o of e){let n=[b(o.actionId),b(o.sourceActionId),b(o.actionName)].filter(r=>!!r);for(let r of n){let s=t.get(r)??[];s.push(o),t.set(r,s)}}return t}a(Nn,"sourceSetupRequirementsByAction");function jn(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(o=>({...o,source:"source_upload_metadata"}))}a(jn,"setupRequirementsForActionSource");function Dn(e,t){if(t.length===0)return e;let o=[],n=new Set;for(let r of[...e,...t]){let s=Hn(r);n.has(s)||(n.add(s),o.push(r))}return o}a(Dn,"mergeSetupRequirements");function Hn(e){return[b(e.actionId)??b(e.sourceActionId)??b(e.actionName)??"",b(e.kind)??b(e.type)??"",b(e.name)??b(e.key)??b(e.provider)??b(e.tool)??b(e.command)??b(e.packageName)??b(e.path)??b(e.repo)??b(e.url)??b(e.id)??""].join(":")}a(Hn,"setupRequirementIdentity");function qn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}a(qn,"missingSourceArtifactsMessage");async function Ie(e){return re(e)?JSON.parse(await On(e,"utf8")):null}a(Ie,"readJsonIfExists");async function Fn(e){let t=0;for(let o of e){if(!re(o))continue;let n=await Tn(o);t=Math.max(t,n.mtimeMs)}return t>0?new Date(t).toISOString():null}a(Fn,"latestMtime");function $(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}a($,"asRecord");function Ye(e){return Array.isArray(e)?e.filter(t=>!!$(t)):[]}a(Ye,"records");function Ft(e){return Array.isArray(e)?e.filter(t=>!!$(t)):null}a(Ft,"recordArray");function b(e){return typeof e=="string"&&e.trim()?e.trim():null}a(b,"text");function Kt(e){return b(e)??$(e)}a(Kt,"schemaValue");function Gn(e,t){let o=Kt(e);return typeof o!="string"?o:$(t?.[o])??o}a(Gn,"resolvedSchemaValue");function zn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,o=>o.toUpperCase()):e}a(zn,"titleFromActionId");var Ce=class extends Error{static{a(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,o){let n=o.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,n.length?`Missing setup: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
2
|
+
import{a as Et,b as Pe}from"./chunk-L3KS6MOV.js";import{x as bt}from"./chunk-3QXPXBVG.js";import{b as j,d as ye,e as we}from"./chunk-MJC26GOX.js";import{$ as ge,Ja as Ct,Ka as vt,Ua as De,ya as Ne,za as je}from"./chunk-QK2GLRCY.js";import{f as L,h as me,p as Le,r as It}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{createRequire as Po}from"node:module";import{createHash as po,randomUUID as ho}from"node:crypto";import{spawn as Pr}from"node:child_process";import{existsSync as U}from"node:fs";import{cp as Sr,mkdir as F,readFile as So,readdir as Ao,rename as at,rm as it,symlink as Ar,writeFile as ie}from"node:fs/promises";import d from"node:path";import Sn from"node:path";var Se="default",Rt=["apiKey","baseUrl","apiBaseUrl","chatApiBaseUrl","token","appId","conversationId"];function W(e,t){return Object.prototype.hasOwnProperty.call(e,t)}a(W,"hasOwn");function z(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}a(z,"normalizeHandle");function _(e){if(typeof e!="string")return null;let t=e.trim();return t?t.replace(/\/$/,""):null}a(_,"normalizeBaseUrl");function Bt(e){let t=z(e);if(!t)throw new Error("profile handle must be non-empty");return t}a(Bt,"requireHandle");function An(e){if(typeof e!="string")throw new Error("apiKey must be a non-empty string");let t=e.trim();if(!t)throw new Error("apiKey must be a non-empty string");return t}a(An,"requireApiKey");function de(e,t){let o=z(e),n=z(t);return!!(o&&n&&o.toLowerCase()===n.toLowerCase())}a(de,"handleEquals");function qe(e,t,o){let n=_(o);return e.findIndex(r=>de(r.handle,t)?n?_(r.baseUrl)===n:!0:!1)}a(qe,"findAccountIndex");function ne(e){let t=z(e.handle)??Se,o=_(e.baseUrl);return o?{handle:t,baseUrl:o}:{handle:t}}a(ne,"selectorFromAccount");function oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n=_(typeof t.baseUrl=="string"?t.baseUrl:void 0);return n?{handle:o,baseUrl:n}:{handle:o}}a(oe,"sanitizeActiveProfile");function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=typeof t.repoPath=="string"?t.repoPath.trim():"",n=typeof t.profile=="string"&&t.profile.trim()?t.profile.trim():"default";if(!o)return;let r={repoPath:o,profile:n,mode:"local"};if(t.lastCheck&&typeof t.lastCheck=="object"&&!Array.isArray(t.lastCheck)){let s=t.lastCheck,i=s.command,c=s.status,l=s.checkedAt;(i==="inspect"||i==="build"||i==="validate"||i==="eval"||i==="run")&&(c==="passed"||c==="failed")&&typeof l=="string"&&(r.lastCheck={command:i,status:c,checkedAt:l,...typeof s.exitCode=="number"||s.exitCode===null?{exitCode:s.exitCode}:{},...typeof s.sourceHead=="string"||s.sourceHead===null?{sourceHead:s.sourceHead}:{}})}if(t.lastPush&&typeof t.lastPush=="object"&&!Array.isArray(t.lastPush)){let s=t.lastPush,i=s.status,c=s.pushedAt;(i==="pushed"||i==="failed")&&typeof c=="string"&&(r.lastPush={status:i,pushedAt:c,...typeof s.teamId=="string"||s.teamId===null?{teamId:s.teamId}:{},...typeof s.projectId=="string"||s.projectId===null?{projectId:s.projectId}:{},...typeof s.localHead=="string"||s.localHead===null?{localHead:s.localHead}:{},...typeof s.hostedHead=="string"||s.hostedHead===null?{hostedHead:s.hostedHead}:{},...typeof s.sourceRef=="string"||s.sourceRef===null?{sourceRef:s.sourceRef}:{},...s.promotionStatus==="uploaded"||s.promotionStatus==="hosted_source_materialized"||s.promotionStatus==="hosted_source_materialize_failed"||s.promotionStatus==="hosted_source_check_pending"||s.promotionStatus==="hosted_source_check_failed"||s.promotionStatus==="hosted_source_published"||s.promotionStatus==="hosted_source_publish_failed"||s.promotionStatus==="hosted_run_pending"||s.promotionStatus==="hosted_run_passed"||s.promotionStatus==="hosted_run_failed"||s.promotionStatus===null?{promotionStatus:s.promotionStatus}:{},...s.hostedRunStatus==="not_started"||s.hostedRunStatus==="running"||s.hostedRunStatus==="passed"||s.hostedRunStatus==="failed"||s.hostedRunStatus===null?{hostedRunStatus:s.hostedRunStatus}:{},...typeof s.hostedRunAgentId=="string"||s.hostedRunAgentId===null?{hostedRunAgentId:s.hostedRunAgentId}:{},...typeof s.hostedRunId=="string"||s.hostedRunId===null?{hostedRunId:s.hostedRunId}:{},...typeof s.hostedRunAt=="string"||s.hostedRunAt===null?{hostedRunAt:s.hostedRunAt}:{},..._t(s.hostedSourceMaterialization)?{hostedSourceMaterialization:_t(s.hostedSourceMaterialization)}:{},...$t(s.hostedSourceCheck)?{hostedSourceCheck:$t(s.hostedSourceCheck)}:{},...Ot(s.hostedPublish)?{hostedPublish:Ot(s.hostedPublish)}:{},...Tt(s.hostedRun)?{hostedRun:Tt(s.hostedRun)}:{},...typeof s.error=="string"||s.error===null?{error:s.error}:{}})}if(Array.isArray(t.profiles)){let s=t.profiles.flatMap(i=>{let c=Fe(i);if(!c)return[];let l=i,u=l.source==="github"||l.source==="openpond_git"?l.source:"local",p=typeof l.repositoryId=="string"&&l.repositoryId.trim()?l.repositoryId.trim():Sn.resolve(c.repoPath);return[{source:u,repositoryId:p,repoPath:c.repoPath,profile:c.profile,...c.lastCheck?{lastCheck:c.lastCheck}:{},...c.lastPush?{lastPush:c.lastPush}:{}}]});s.length>0&&(r.profiles=s)}return r}a(Fe,"sanitizeLocalOpenPondProfile");function _t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runtimeAgentId"),...m(t,"projectId"),...m(t,"sourceRoot"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"manifestSyncedAt"),...Ut(t,"fileCount"),...Ut(t,"totalBytes"),...m(t,"generatedManifestPath"),...He(t,"synthesizedOpenPondYaml"),...m(t,"uploadMetadataPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...m(t,"materializedAt"),...m(t,"error")}:null}a(_t,"sanitizeHostedMaterializationStatus");function $t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"deployPlanStatus"),...He(t,"canRun"),...He(t,"canDeploy"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...O(t,"requiredChecks"),...O(t,"evalNames"),...O(t,"blockedReasons"),...O(t,"staleReasons"),...m(t,"runtimeId"),...m(t,"sandboxId"),...O(t,"traceArtifactRefs"),...O(t,"evalResultArtifactRefs"),...O(t,"validatorArtifactRefs"),...m(t,"checkedAt"),...m(t,"error")}:null}a($t,"sanitizeHostedSourceCheckStatus");function Ot(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"snapshotId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"buildStatus"),...m(t,"validationStatus"),...m(t,"evalStatus"),...m(t,"publishedAt"),...m(t,"error")}:null}a(Ot,"sanitizeHostedPublishStatus");function Tt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runId"),...m(t,"runtimeId"),...m(t,"sandboxId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"setupGateStatus"),...O(t,"setupRequirementRefs"),...O(t,"artifactRefs"),...O(t,"traceArtifactRefs"),...O(t,"evalArtifactRefs"),...m(t,"startedAt"),...m(t,"completedAt"),...m(t,"error")}:null}a(Tt,"sanitizeHostedRunSummary");function m(e,t){let o=e[t];return typeof o=="string"||o===null?{[t]:o}:{}}a(m,"nullableStringProp");function He(e,t){let o=e[t];return typeof o=="boolean"||o===null?{[t]:o}:{}}a(He,"nullableBooleanProp");function Ut(e,t){let o=e[t];return typeof o=="number"||o===null?{[t]:o}:{}}a(Ut,"nullableNumberProp");function O(e,t){let o=e[t];if(!Array.isArray(o))return{};let n=o.filter(r=>typeof r=="string");return{[t]:n}}a(O,"stringArrayProp");function Ae(e){return typeof e=="string"&&e.trim()?e.trim():null}a(Ae,"stringField");function Lt(e,t){if(!de(e.handle,t.handle))return!1;let o=_(t.baseUrl);return o?_(e.baseUrl)===o:!_(e.baseUrl)}a(Lt,"accountMatchesSelector");function Ge(e,t,o={}){let n=_(t.baseUrl);if(n)return qe(e,t.handle,n);let r=e.findIndex(i=>Lt(i,t));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>de(i.handle,t.handle));if(s.length>1&&o.requireUnambiguous)throw new Error(`multiple profiles found for ${t.handle}; pass --base-url to select one`);return s[0]?.index??-1}a(Ge,"findAccountIndexForSelector");function xn(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o={};return typeof t.token=="string"&&(o.token=t.token),(typeof t.appId=="string"||t.appId===null)&&(o.appId=t.appId),(typeof t.conversationId=="string"||t.conversationId===null)&&(o.conversationId=t.conversationId),Object.keys(o).length>0?o:void 0}a(xn,"sanitizeSession");function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n={handle:o};typeof t.apiKey=="string"&&(n.apiKey=t.apiKey),typeof t.baseUrl=="string"&&(n.baseUrl=t.baseUrl),typeof t.apiBaseUrl=="string"&&(n.apiBaseUrl=t.apiBaseUrl),typeof t.chatApiBaseUrl=="string"&&(n.chatApiBaseUrl=t.chatApiBaseUrl),typeof t.environment=="string"&&(n.environment=t.environment);let r=xn(t.session);return r&&(n.session=r),n}a(kn,"sanitizeAccount");function bn(e){let t={};return typeof e.token=="string"&&(t.token=e.token),(typeof e.appId=="string"||e.appId===null)&&(t.appId=e.appId),(typeof e.conversationId=="string"||e.conversationId===null)&&(t.conversationId=e.conversationId),Object.keys(t).length>0?t:void 0}a(bn,"extractLegacySession");function In(e,t){let o={handle:t};typeof e.apiKey=="string"&&(o.apiKey=e.apiKey),typeof e.baseUrl=="string"&&(o.baseUrl=e.baseUrl),typeof e.apiBaseUrl=="string"&&(o.apiBaseUrl=e.apiBaseUrl),typeof e.chatApiBaseUrl=="string"&&(o.chatApiBaseUrl=e.chatApiBaseUrl);let n=bn(e);return n&&(o.session=n),o}a(In,"extractLegacyAccount");function Nt(e){let t={};typeof e.lspEnabled=="boolean"&&(t.lspEnabled=e.lspEnabled),(e.executionMode==="local"||e.executionMode==="hosted")&&(t.executionMode=e.executionMode),(e.mode==="general"||e.mode==="builder")&&(t.mode=e.mode);let o=Fe(e.openpondProfile);o&&(t.openpondProfile=o);let n=[],r=Array.isArray(e.accounts)?e.accounts:[];for(let l of r){let u=kn(l);u&&qe(n,u.handle,u.baseUrl)===-1&&n.push(u)}if(n.length===0){let l=oe(e.activeProfile)?.handle||Se;n.push(In(e,l))}let s=oe(e.activeProfile),i=s?Ge(n,s):-1,c=n[i===-1?0:i];return t.accounts=n,t.activeProfile=ne(c),t}a(Nt,"normalizeGlobalConfig");function Cn(e,t,o){let n=e.accounts??[],r=_(o??process.env.OPENPOND_BASE_URL),s=z(t);if(s)return r?{handle:s,baseUrl:r}:{handle:s};let i=z(process.env.OPENPOND_ACCOUNT);if(i)return r?{handle:i,baseUrl:r}:{handle:i};let c=oe(e.activeProfile);return c?r?{handle:c.handle,baseUrl:r}:c:n[0]?ne(n[0]):{handle:Se}}a(Cn,"resolveRequestedProfile");function jt(e,t,o){let n=_(o);if(n){let s=qe(e,t,n);if(s!==-1)return e[s]}else{let s=e.filter(i=>de(i.handle,t));if(s.length>1)throw new Error(`multiple profiles found for ${t}; pass --base-url to select one`);if(s.length===1)return s[0]}let r={handle:t};return n&&(r.baseUrl=n),e.push(r),r}a(jt,"ensureAccount");function Mt(e){e.session&&Object.keys(e.session).length===0&&delete e.session}a(Mt,"cleanupAccount");function vn(e,t,o,n){let r=o===null||o===void 0&&n.undefinedDeletes;switch(t){case"apiKey":{if(r){delete e.apiKey;return}typeof o=="string"&&(e.apiKey=o);return}case"baseUrl":{if(r){delete e.baseUrl;return}typeof o=="string"&&(e.baseUrl=o);return}case"apiBaseUrl":{if(r){delete e.apiBaseUrl;return}typeof o=="string"&&(e.apiBaseUrl=o);return}case"chatApiBaseUrl":{if(r){delete e.chatApiBaseUrl;return}typeof o=="string"&&(e.chatApiBaseUrl=o);return}case"token":case"appId":case"conversationId":{if(e.session||(e.session={}),r){delete e.session[t],Mt(e);return}(typeof o=="string"||o===null)&&(e.session[t]=o),Mt(e);return}}}a(vn,"applyScopedKey");function En(e,t,o){if(!Rt.some(l=>W(t,l)))return!1;let r=e.accounts??[],s=oe(t.activeProfile)??Cn(e),i=_(W(t,"baseUrl")?t.baseUrl??null:s.baseUrl??process.env.OPENPOND_BASE_URL),c=jt(r,s.handle,i);for(let l of Rt)W(t,l)&&vn(c,l,t[l],o);return e.accounts=r,e.activeProfile=ne(c),!0}a(En,"applyAccountPatch");function Rn(e,t){if(W(t,"lspEnabled")&&(typeof t.lspEnabled=="boolean"?e.lspEnabled=t.lspEnabled:t.lspEnabled===null&&delete e.lspEnabled),W(t,"executionMode")&&(t.executionMode==="local"||t.executionMode==="hosted"?e.executionMode=t.executionMode:t.executionMode===null&&delete e.executionMode),W(t,"mode")&&(t.mode==="general"||t.mode==="builder"?e.mode=t.mode:t.mode===null&&delete e.mode),W(t,"activeProfile")){let o=oe(t.activeProfile);if(o){let n=Ge(e.accounts??[],o);e.activeProfile=n===-1?o:ne((e.accounts??[])[n])}else t.activeProfile===null&&delete e.activeProfile}if(W(t,"openpondProfile")){let o=Fe(t.openpondProfile);o?e.openpondProfile=o:t.openpondProfile===null&&delete e.openpondProfile}}a(Rn,"applyTopLevelPatch");async function xe(e){let t=L();return await De(t),await vt(t,o=>{let n=Nt(o);return e(n),n})}a(xe,"updateGlobalConfig");async function T(){let e=L();return await De(e),Nt(await Ct(e))}a(T,"loadGlobalConfig");async function ze(){let e=await T(),t=oe(e.activeProfile);return(e.accounts??[]).map(o=>{let n=z(o.handle)??Se;return{handle:n,baseUrl:_(o.baseUrl),apiBaseUrl:_(o.apiBaseUrl),chatApiBaseUrl:_(o.chatApiBaseUrl),environment:o.environment?.trim()||null,isActive:!!(t&&Lt({...o,handle:n},t)),hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!o.session?.token?.trim(),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null}})}a(ze,"listConfiguredProfiles");async function _n(e,t={}){let o=Bt(e),n=_(t.baseUrl),r=-1;await xe(i=>{let c=i.accounts??[];if(r=Ge(c,n?{handle:o,baseUrl:n}:{handle:o},{requireUnambiguous:!0}),r===-1)throw new Error(`profile not found: ${o}`);i.activeProfile=ne(c[r])});let s=await ze();return s.find(i=>i.isActive)??s[r]}a(_n,"setActiveProfile");async function $n(e){let t=Bt(e.handle),o=An(e.apiKey),n=_(e.baseUrl),r=_(e.apiBaseUrl),s=_(e.chatApiBaseUrl),i={handle:t};await xe(u=>{let p=u.accounts??[],h=jt(p,t,n);h.apiKey=o,n&&(h.baseUrl=n),r?h.apiBaseUrl=r:e.apiBaseUrl===null&&delete h.apiBaseUrl,s?h.chatApiBaseUrl=s:e.chatApiBaseUrl===null&&delete h.chatApiBaseUrl,e.environment===null?delete h.environment:typeof e.environment=="string"&&e.environment.trim()&&(h.environment=e.environment.trim()),u.accounts=p,i=ne(h),e.setActive!==!1&&(u.activeProfile=i)});let l=(await ze()).find(u=>de(u.handle,i.handle)?n?_(u.baseUrl)===n:!0:!1);if(!l)throw new Error(`failed to save profile: ${t}`);return l}a($n,"saveProfileApiKey");async function H(e){await xe(t=>{Rn(t,e),En(t,e,{undefinedDeletes:!1})})}a(H,"saveGlobalConfig");function Je(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}a(Je,"emptyProfileCatalogState");function Ke(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}a(Ke,"emptyProfileSkillCatalogState");function We(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}a(We,"emptyProfileSetupGate");function ke(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}a(ke,"emptyProfileDiffSummary");function Ve(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}a(Ve,"emptyProfileSummary");import{existsSync as re}from"node:fs";import{readFile as On,stat as Tn}from"node:fs/promises";import be from"node:path";var Dt=".openpond/agent-manifest.json",Ht=".openpond/action-registry.json",Un=".openpond/source-upload-metadata.json",Mn=".openpond/agent-package-origin.json";async function Gt(e){return Jt({agentId:"default",sourcePath:e,preferred:!0})}a(Gt,"loadProfileActionCatalog");async function zt(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(c=>c.preferred),...e.filter(c=>!c.preferred)],o=await Promise.all(t.map(Jt)),n=new Map,r=[];for(let c of o)for(let l of c.actionCatalog){let u=n.has(l.id)?`${l.agentId??"agent"}.${l.sourceActionId??l.id}`:l.id,p=u===l.id?l:{...l,id:u};n.set(u,p),r.push(p)}let s=Ln(o.map(c=>c.catalog.generatedAt)),i=o.map(c=>c.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:s,manifestPath:o.find(c=>c.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:o.find(c=>c.catalog.registryPath)?.catalog.registryPath??null,stale:o.some(c=>c.catalog.stale),error:i.length>0?i.join("; "):null},actionCatalog:r,sourceSetupRequirements:o.flatMap(c=>c.sourceSetupRequirements)}}a(zt,"loadProfileActionCatalogForSources");async function Jt(e){let t=e.sourcePath,o=be.join(t,Dt),n=be.join(t,Ht),r=be.join(t,Un),s=be.join(t,Mn);try{let i=await Ie(o),c=await Ie(n),l=await Ie(r),u=$(await Ie(s)),p=$($(i)?.inputSchemas),h=Ft($(l)?.setupRequirements)??[],k=Nn(h),C=new Map;for(let f of[...Ye($(i)?.actionCatalog),...Ye($(c)?.actions),...Ye($(i)?.actions)]){let y=b(f.id)??b(f.name);if(!y)continue;let x=C.get(y),v=jn({sourceRequirementsByAction:k,actionId:y,actionName:b(f.name)}),B=Dn(Ft(f.setupRequirements)??x?.setupRequirements??[],v),K={id:y,agentId:e.agentId,sourcePath:t,sourceActionId:y,name:b(f.name)??x?.name??y,label:b(f.label)??x?.label??zn(y),description:b(f.description)??x?.description??null,visibility:b(f.visibility)??x?.visibility??"default",inputSchema:Gn(f.inputSchema,p)??x?.inputSchema??null,outputSchema:Kt(f.outputSchema)??x?.outputSchema??null,approvalPolicy:$(f.approvalPolicy)??x?.approvalPolicy??null,artifactPolicy:$(f.artifactPolicy)??x?.artifactPolicy??null,setupRequirements:B,mcp:$(f.mcp)??x?.mcp??null,schedulePolicy:$(f.schedulePolicy)??x?.schedulePolicy??null,trace:Bn($(f.trace)??x?.trace??null,u),implementation:$(f.implementation)??x?.implementation??null,invokesModel:typeof f.invokesModel=="boolean"?f.invokesModel:x?.invokesModel};C.set(y,K)}let P=Array.from(C.values()).filter(f=>f.visibility!=="internal"&&f.visibility!=="debug"),g=[...i?[]:[Dt],...c?[]:[Ht]],S=await Fn([o,n]);return{catalog:{actionCount:P.length,generatedAt:S,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:g.length>0,error:g.length>0?qn(e,g):null},actionCatalog:P,sourceSetupRequirements:h}}catch(i){return{catalog:{actionCount:0,generatedAt:null,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:!0,error:i instanceof Error?i.message:String(i)},actionCatalog:[],sourceSetupRequirements:[]}}}a(Jt,"loadProfileActionCatalogSource");function Bn(e,t){if(!t)return e;let o=b(t.versionId),n=b(t.digest);return!o||!n?e:{...e??{},agentVersionId:o,agentPackageDigest:n,validationReceiptIds:qt(t.validationReceiptIds),evalReceiptIds:qt(t.evalReceiptIds)}}a(Bn,"mergeAgentPackageTrace");function qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}a(qt,"stringArray");function Ln(e){let t=0;for(let o of e){if(!o)continue;let n=Date.parse(o);Number.isFinite(n)&&(t=Math.max(t,n))}return t>0?new Date(t).toISOString():null}a(Ln,"latestIso");function Nn(e){let t=new Map;for(let o of e){let n=[b(o.actionId),b(o.sourceActionId),b(o.actionName)].filter(r=>!!r);for(let r of n){let s=t.get(r)??[];s.push(o),t.set(r,s)}}return t}a(Nn,"sourceSetupRequirementsByAction");function jn(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(o=>({...o,source:"source_upload_metadata"}))}a(jn,"setupRequirementsForActionSource");function Dn(e,t){if(t.length===0)return e;let o=[],n=new Set;for(let r of[...e,...t]){let s=Hn(r);n.has(s)||(n.add(s),o.push(r))}return o}a(Dn,"mergeSetupRequirements");function Hn(e){return[b(e.actionId)??b(e.sourceActionId)??b(e.actionName)??"",b(e.kind)??b(e.type)??"",b(e.name)??b(e.key)??b(e.provider)??b(e.tool)??b(e.command)??b(e.packageName)??b(e.path)??b(e.repo)??b(e.url)??b(e.id)??""].join(":")}a(Hn,"setupRequirementIdentity");function qn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}a(qn,"missingSourceArtifactsMessage");async function Ie(e){return re(e)?JSON.parse(await On(e,"utf8")):null}a(Ie,"readJsonIfExists");async function Fn(e){let t=0;for(let o of e){if(!re(o))continue;let n=await Tn(o);t=Math.max(t,n.mtimeMs)}return t>0?new Date(t).toISOString():null}a(Fn,"latestMtime");function $(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}a($,"asRecord");function Ye(e){return Array.isArray(e)?e.filter(t=>!!$(t)):[]}a(Ye,"records");function Ft(e){return Array.isArray(e)?e.filter(t=>!!$(t)):null}a(Ft,"recordArray");function b(e){return typeof e=="string"&&e.trim()?e.trim():null}a(b,"text");function Kt(e){return b(e)??$(e)}a(Kt,"schemaValue");function Gn(e,t){let o=Kt(e);return typeof o!="string"?o:$(t?.[o])??o}a(Gn,"resolvedSchemaValue");function zn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,o=>o.toUpperCase()):e}a(zn,"titleFromActionId");var Ce=class extends Error{static{a(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,o){let n=o.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,n.length?`Missing setup: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
3
3
|
`)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:t,setupGate:o,missing:n,blockingSetupRequirements:o.blockingRequirements,setupRequirements:o.requirements}}};function ve(e){let t=new Map;for(let i of e.sourceSetupRequirements??[]){let c=Kn(i);if(e.actionId&&c&&c!==e.actionId&&E(i.actionName)!==e.actionId&&E(i.sourceActionId)!==e.actionId)continue;let l=Wt({record:i,source:"source_upload_metadata",actionId:c});l&&t.set(l.ref,l)}for(let i of e.actionCatalog)if(!(e.actionId&&i.id!==e.actionId&&i.name!==e.actionId))for(let c of i.setupRequirements??[]){let l=Wt({record:c,source:"action_catalog",actionId:i.id});l&&t.set(l.ref,l)}let o=Array.from(t.values()),n=o.filter(i=>i.blocking),r=o.filter(i=>!i.required&&!Xe(i.status)).length,s=o.filter(i=>Xe(i.status)).length;return{status:Vn(n),requirementCount:o.length,blockingCount:n.length,optionalMissingCount:r,readyCount:s,requirements:o,blockingRequirements:n}}a(ve,"buildOpenPondProfileSetupGate");function Ze(e,t){if(t.blockingRequirements.length>0)throw new Ce(e,t)}a(Ze,"assertOpenPondProfileActionReady");function Jn(e){let t=e.actionId?`${e.actionId}: `:"",o=e.required?"required":"optional";return`${t}${e.label} (${o}, ${e.status})`}a(Jn,"formatOpenPondProfileSetupRequirement");function Wt(e){let t=e.source==="action_catalog"&&E(e.record.source)==="source_upload_metadata"?"source_upload_metadata":e.source,o=E(e.record.kind)??E(e.record.type),n=E(e.record.label)??E(e.record.name)??E(e.record.key)??E(e.record.provider)??E(e.record.tool)??E(e.record.command)??E(e.record.packageName)??E(e.record.path)??E(e.record.repo)??E(e.record.url)??E(e.record.id)??o??"setup requirement",r=e.record.required!==!1,s=Wn(e.record);return{ref:[t,e.actionId??"source",o??"requirement",n].join(":"),source:t,actionId:e.actionId,kind:o,label:n,status:s,required:r,blocking:r&&!Xe(s)}}a(Wt,"setupRequirementFromRecord");function Kn(e){return E(e.actionId)??E(e.sourceActionId)??E(e.actionName)}a(Kn,"setupRequirementActionId");function Wn(e){let t=E(e.status)??E(e.state);return t?t==="satisfied"||t==="connected"||t==="provided"?"ready":t:typeof e.satisfied=="boolean"?e.satisfied?"ready":"setup_required":typeof e.ready=="boolean"&&e.ready?"ready":"setup_required"}a(Wn,"setupStatus");function Vn(e){return e.length===0?"ready":e.some(t=>["blocked","unsupported","unsupported_dependency","stale"].includes(t.status))?"blocked":"setup_required"}a(Vn,"gateStatus");function Xe(e){return e==="ready"||e==="disabled"}a(Xe,"isReadyStatus");function E(e){return typeof e=="string"&&e.trim()?e.trim():null}a(E,"text");import{spawn as Yn}from"node:child_process";import{randomUUID as Xn}from"node:crypto";import{existsSync as Qe}from"node:fs";import{readFile as Zn,rm as Qn,writeFile as Xt}from"node:fs/promises";import Ee from"node:path";var Zt=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
|
|
4
4
|
`);async function Qt(e){if(!Qe(Ee.join(e,".git"))){let s=await M(e,["init","-b","main"]);if(s.code!==0)throw new Error(Y("git init",s))}let t=Ee.join(e,".gitignore");if(Qe(t)?await er(t):await Xt(t,Zt,"utf8"),await or(e))return;let o=await X(e);if(!o.dirty&&o.files.length===0)return;let n=await M(e,["add","-A"]);if(n.code!==0)throw new Error(Y("git add",n));let r=await M(e,["commit","-m","Initialize OpenPond profile"],{env:{...process.env,GIT_AUTHOR_NAME:process.env.GIT_AUTHOR_NAME||"OpenPond",GIT_AUTHOR_EMAIL:process.env.GIT_AUTHOR_EMAIL||"openpond@example.invalid",GIT_COMMITTER_NAME:process.env.GIT_COMMITTER_NAME||"OpenPond",GIT_COMMITTER_EMAIL:process.env.GIT_COMMITTER_EMAIL||"openpond@example.invalid"}});if(r.code!==0&&!/nothing to commit/i.test(r.stdout+r.stderr))throw new Error(Y("git commit",r))}a(Qt,"ensureProfileGitRepo");async function er(e){let t=await Zn(e,"utf8").catch(()=>""),o=Zt.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!t.split(/\r?\n/).some(s=>s.trim()===r));if(o.length===0)return;let n=t.endsWith(`
|
|
5
5
|
`)||t.length===0?"":`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{j as y}from"./chunk-
|
|
2
|
+
import{j as y}from"./chunk-62H5KUOS.js";import{E as u,J as j,K as E}from"./chunk-PKBU37CH.js";import{O as v,R as I,S as b,Y as f}from"./chunk-JIG7KQOX.js";import{Ba as S}from"./chunk-QUNRWDVO.js";import{$ as k,Y as H,_ as w,aa as U,ca as M,kb as O}from"./chunk-QK2GLRCY.js";import{b as i}from"./chunk-ES2ISFJC.js";import{a as h,c as R,f as x,h as l}from"./chunk-H7IWJN7L.js";import{a as n}from"./chunk-FTQLQJQV.js";import m from"node:path";import{AsyncLocalStorage as J}from"node:async_hooks";import{promises as C}from"node:fs";var T=new J;function Z(r,e=!1){let t=T.getStore();t&&(e&&(t.length=0),t.push(r))}n(Z,"onStartupFailure");async function ee(r,e){await O(r);let t;try{t=await U(m.join(l(r).runtime,"server-owner"),100)}catch(s){if(s instanceof R&&s.issue.code==="STORAGE_BUSY"){let a=await M(m.join(l(r).runtime,"endpoint.json"),()=>null);throw new R({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 s}let o=[];try{let s=await h(r,()=>T.run(o,e)),a=s.close.bind(s);o.length=0;let d;return{...s,close:n(()=>d??=(async()=>{try{await h(r,a)}finally{await C.rm(m.join(l(r).runtime,"endpoint.json"),{force:!0}),await t()}})(),"close")}}catch(s){try{for(let a of o.reverse())await Promise.resolve().then(()=>h(r,a)).catch(()=>{});await C.rm(m.join(l(r).runtime,"endpoint.json"),{force:!0})}finally{await t()}throw s}}n(ee,"ownHomeRuntime");async function te(r,e,t){await w(m.join(l(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:e,serverId:t}))}n(te,"publishRuntimeEndpoint");function ne(r){return W({runtime:E(r.ports),close:r.close})}n(ne,"createAppServer");function W(r){let e=!1;return{runtime:r.runtime,close:n(async()=>{e||(e=!0,await r.close?.())},"close")}}n(W,"attachAppServer");async function ie(r){let e=typeof r.appServer=="function"?null:r.appServer;try{await j({host:e?.runtime??(async()=>(e=await r.appServer(),e.runtime)),readable:r.readable,writable:r.writable,hostStorageClient:r.hostStorageClient})}finally{await e?.close()}}n(ie,"runAppServerJsonl");import{randomBytes as z}from"node:crypto";function pe(){return x()}n(pe,"appDataDir");function ue(r){return l(r).config}n(ue,"providersConfigPath");function me(r){return l(r).credentials}n(me,"providerSecretsConfigPath");function ge(r){return l(r).key}n(ge,"providerSecretsKeyPath");async function fe(r){let e=l(r).token;return k(e,async()=>{let t=(await H(e))?.trim(),o=process.env.OPENPOND_APP_TOKEN||t||z(32).toString("base64url");return o!==t&&await w(e,o),{token:o,tokenFile:e}})}n(fe,"ensureCapabilityToken");import p from"node:path";import{readFile as _}from"node:fs/promises";var F=i.object({profileId:i.string().min(1),sourceRevision:i.string().min(1),repositoryId:i.string().min(1),harnessRelease:i.object({id:i.string().min(1),contentHash:i.string().regex(/^[a-f0-9]{64}$/)}).strict(),workspaceId:i.string().min(1),assetsPath:i.string().min(1).refine(p.isAbsolute)}).strict();async function Ie(r,e){let t=F.parse(e),o=await y(r,t.harnessRelease);if(!o||p.resolve(o.release.bundlePath)!==p.resolve(t.assetsPath))throw new Error("Hosted Profile release changed after admission.");let s=o.release.harnessRelease.metadata.profile;if(!s||typeof s!="object"||s.id!==t.profileId||s.sourceRevision!==t.sourceRevision||s.repositoryId!==void 0&&s.repositoryId!==t.repositoryId)throw new Error("Hosted Profile provenance differs from admitted release.");return{profile:b(),profileLibrary:I()}}n(Ie,"loadHostedProfileStateAndLibrary");async function be(r,e){let t=F.parse(e),o=await y(r,t.harnessRelease);if(!o||p.resolve(o.release.bundlePath)!==p.resolve(t.assetsPath))throw new Error("Hosted Profile workflow release is unavailable.");let s=o.release.harnessRelease.metadata.profile;if(s?.id!==t.profileId||s.sourceRevision!==t.sourceRevision||s.repositoryId!==void 0&&s.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(!o.release.harnessRelease.files.some(g=>g.path==="workflows/catalog.json"))return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:[]};let c=p.join(o.release.bundlePath,"source","workflows"),A=S({agentSnapshot:o.release.agentSnapshot,harnessRelease:o.release.harnessRelease,catalogBytes:await _(p.join(c,"catalog.json")),actionBytes:await _(p.join(c,"actions.json"))});return{profileRef:d,sourceRevision:t.sourceRevision,harnessRelease:a,workflows:A.catalog.workflows.map(g=>({workflow:g,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:t.profileId,sourceRevision:t.sourceRevision,harnessRelease:a,catalogHash:A.catalogHash,workflowId:g.id}}))}}n(be,"listHostedProfileWorkflows");import{createHash as G,randomUUID as P}from"node:crypto";var N=i.object({approval:v,revision:i.number().int().positive()}).strict(),B=i.object({record:f}).strict(),$=i.object({startedAt:i.string().min(1),requestOrdinal:i.number().int().nonnegative(),id:i.string().min(1)}).strict(),q=i.object({records:i.array(f).max(200),nextBefore:$.nullable()}).strict(),V=1e4,L=class{constructor(e){this.client=e}client;static{n(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:u,requestId:P(),operation:"approval/get",params:{approvalId:e}});return t===null?null:N.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=v.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return N.parse(await this.client.request({contractVersion:u,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},D=class{constructor(e){this.client=e}client;static{n(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=f.parse(e),o=G("sha256").update(JSON.stringify(t)).digest("hex"),s=await this.client.request({contractVersion:u,requestId:`usage:${o}`,operation:"usage/upsert",params:{record:t}}),a=B.parse(s).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:u,requestId:P(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:B.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=V,o=e.limit===void 0?V:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),s={...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<o+(t?1:0);){let c=q.parse(await this.client.request({contractVersion:u,requestId:P(),operation:"usage/page",params:{query:s,before:d,limit:Math.min(200,o+(t?1:0)-a.length)}}));if(a.push(...c.records),a.length>o)throw new Error(`Hosted usage query exceeds ${o} rows; narrow its filters or use a streamed aggregation.`);if(c.nextBefore===null)break;if(c.records.length===0||JSON.stringify(c.nextBefore)===JSON.stringify(d))throw new Error("Host usage cursor did not advance.");d=c.nextBefore}return a}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};export{Z as a,ee as b,te as c,ne as d,ie as e,pe as f,ue as g,me as h,ge as i,fe as j,L as k,D as l,F as m,Ie as n,be as o};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{ca as Y,fa as D,ga as Z,ha as ee,la as I,ma as re}from"./chunk-L6ELXODL.js";import{E as x}from"./chunk-PKBU37CH.js";import{kd as X}from"./chunk-SBBXUZWL.js";import{b as W}from"./chunk-L3KS6MOV.js";import{Ba as G,Ca as Q,i as B,l as K,o as J,q as $,r as P,s as U,v as L,x as q}from"./chunk-QUNRWDVO.js";import{k as N,l as _,m as A}from"./chunk-HZP5U2AA.js";import{b as S}from"./chunk-ES2ISFJC.js";import{a as w}from"./chunk-FTQLQJQV.js";import{randomUUID as Re}from"node:crypto";import{readFile as C}from"node:fs/promises";import E from"node:path";import{promises as le}from"node:fs";import y from"node:path";import{randomUUID as O}from"node:crypto";import{promises as h}from"node:fs";import{stripTypeScriptTypes as me}from"node:module";import R from"node:path";async function Oe(s){let e=$.parse(s.overlay),r=P.parse(s.proposal),t=s.validations.map(u=>U.parse(u));if((r.route==="agent"?r.edits.filter(u=>u.target!=="harness.json"&&u.operation!=="delete"):[]).length>0){let u=r.validationPlan.find(a=>a.kind==="component_activation"&&a.required);if(!u)throw new Error("Desktop Work Agent proposals require component-activation validation before review.");if(t.find(a=>a.validationId===u.id)?.status==="passed")throw new Error("Desktop Work cannot accept a passed Agent activation receipt until an Agent source executor exists.")}if(r.overlay.id!==e.id||r.overlay.revision!==e.revision||r.overlay.contentHash!==e.contentHash)throw new Error("Refiner proposal is not bound to the supplied run overlay.");if(e.status!=="frozen")throw new Error("Only a frozen run overlay can advance a Harness workspace.");let o=await s.store.getHarnessWorkspace(r.expectedWorkspace.workspaceId);if(!o)throw new Error(`Harness workspace ${r.expectedWorkspace.workspaceId} does not exist.`);if(o.location!==s.store.harnessStoragePlacement)throw new Error("Refiner workspace does not match the admitted storage placement.");let i=D(s.storeDir,o.id),l=await I({workspaceId:o.id,sourceDir:i.source});if(l.sourceRevision!==o.sourceRevision)throw new Error(`Harness source is ${l.sourceRevision}; workspace expects ${o.sourceRevision}. Record or revert the source change before refinement.`);let d=R.join(i.root,`.source-candidate-${O()}`);await h.cp(i.source,d,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{await ae(d,r);let u=await I({workspaceId:o.id,sourceDir:d}),f=(s.now??(()=>new Date().toISOString()))(),a=await re({storeDir:s.storeDir,workspaceId:o.id,compiled:u,createdAt:f});await s.store.saveHarnessReleaseRecord(a),await s.store.saveHarnessImprovementArtifact(o.id,"run_overlay",e),await s.store.saveHarnessImprovementArtifact(o.id,"proposal",r);for(let c of t)await s.store.saveHarnessImprovementArtifact(o.id,"targeted_validation",c);if(!X({workspace:o,proposal:r}).eligible&&!s.reviewAuthority)return s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});let m=R.join(i.root,`.source-backup-${O()}`),p=R.join(i.root,"source-swap.json");await ne(p,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:o.id,expectedWorkspaceRevision:o.revision,previousSourceRevision:o.sourceRevision,nextSourceRevision:a.sourceRevision,backupSource:m,candidateSource:d,createdAt:f}),await h.rename(i.source,m),await h.rename(d,i.source);try{let c=s.reviewAuthority?await s.store.advanceReviewedHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,reviewer:s.reviewAuthority.reviewer,now:f}):await s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});return c.receipt.decision!=="advanced"?await j(i.source,m):await h.rm(m,{recursive:!0,force:!0}),await h.rm(p,{force:!0}),c}catch(c){throw await j(i.source,m).catch(()=>{}),await h.rm(p,{force:!0}).catch(()=>{}),c}}finally{await h.rm(d,{recursive:!0,force:!0}).catch(()=>{})}}w(Oe,"applyLocalHarnessRefinerProposal");async function $e(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e||e.location!==s.store.harnessStoragePlacement)throw new Error(`Local Harness workspace ${s.workspaceId} does not exist.`);if(e.currentChannel.release?.id!==s.rollbackOf.id||e.currentChannel.release.contentHash!==s.rollbackOf.contentHash)throw new Error("Harness rollback source is no longer the current release.");let r=await s.store.getHarnessReleaseRecord(s.targetRelease.contentHash);if(!r||r.workspaceId!==e.id||r.harnessRelease.id!==s.targetRelease.id)throw new Error("Harness rollback target is unavailable in this workspace.");let t=D(s.storeDir,e.id);if((await I({workspaceId:e.id,sourceDir:t.source})).sourceRevision!==e.sourceRevision)throw new Error("Harness source changed before rollback.");let o=R.join(t.root,`.source-rollback-${O()}`);await h.cp(R.join(r.bundlePath,"source"),o,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{if((await I({workspaceId:e.id,sourceDir:o})).sourceRevision!==r.sourceRevision)throw new Error("Harness rollback bundle does not reproduce its registered source revision.");let l=(s.now??(()=>new Date().toISOString()))(),d=R.join(t.root,`.source-backup-${O()}`),u=R.join(t.root,"source-swap.json");await ne(u,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:e.id,expectedWorkspaceRevision:e.revision,previousSourceRevision:e.sourceRevision,nextSourceRevision:r.sourceRevision,backupSource:d,candidateSource:o,createdAt:l}),await h.rename(t.source,d),await h.rename(o,t.source);try{let f=await s.store.rollbackHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:e.id,expectedWorkspaceRevision:e.revision,expectedChannelRevision:e.currentChannel.revision,targetRelease:s.targetRelease,targetSourceRevision:r.sourceRevision,rollbackOf:s.rollbackOf,now:l});return f.receipt.decision!=="rolled_back"?await j(t.source,d):await h.rm(d,{recursive:!0,force:!0}),await h.rm(u,{force:!0}),f}catch(f){throw await j(t.source,d).catch(()=>{}),await h.rm(u,{force:!0}).catch(()=>{}),f}}finally{await h.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}w($e,"rollbackLocalHarnessWorkspaceRelease");async function We(s){let e=P.parse(s.proposal);if(e.expectedWorkspace.workspaceId!==s.workspace.id)throw new Error("Refiner proposal targets a different Harness workspace.");if(e.route==="memory")return we({proposal:e,now:s.now});let r=D(s.storeDir,s.workspace.id),t=await I({workspaceId:s.workspace.id,sourceDir:r.source});if(t.sourceRevision!==e.expectedWorkspace.sourceRevision)throw new Error("Refiner proposal source revision no longer matches the Local Harness workspace.");let n=R.join(r.root,`.validation-candidate-${O()}`);await h.cp(r.source,n,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});let o=(s.now??(()=>new Date().toISOString()))();try{await ae(n,e);let i=await I({workspaceId:s.workspace.id,sourceDir:n}),l=new Map(i.manifest.files.map(a=>[a.path,a])),d=new Map(e.edits.map(a=>[a.target,a])),u=se(t),f=se(i);return Promise.all(e.validationPlan.map(async a=>{let v="passed",m="The candidate Harness source compiles and preserves its manifest contract.";try{if(a.kind==="observed_recovery"){let p=e.evidence.filter(c=>c.kind==="recovery");if(p.length===0)throw new Error("Observed-recovery validation requires recorded recovery evidence.");m=`Validated ${p.length} immutable recovery evidence reference(s) before candidate advancement.`}else if(a.kind==="prompt"){let p=e.edits.filter(c=>c.route==="prompt"&&c.target!=="harness.json");if(p.length===0)throw new Error("Prompt validation requires an instruction-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted instruction ${c.target} remains declared.`)}else if(g?.kind!=="instruction")throw new Error(`Instruction ${c.target} is not declared in the candidate Harness.`);if(c.content!==null&&/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(c.content))throw new Error(`Instruction ${c.target} appears to contain credential material.`)}m=`Validated ${p.length} textual instruction edit(s) and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="skill"){let p=e.edits.filter(c=>c.route==="skill"&&c.target!=="harness.json");if(p.length===0)throw new Error("Skill validation requires a declared Skill-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted Skill ${c.target} remains declared.`);continue}if(g?.kind!=="skill")throw new Error(`Skill ${c.target} is not declared in the candidate Harness.`);let k=d.get(c.target)?.content;if(!k)throw new Error(`Skill edit ${c.target} has no content.`);let H=W(k);if(!H.name||!H.description||H.messages.length>0)throw new Error(`Skill ${c.target} is invalid: ${H.messages.join(" ")}`)}m=`Validated ${p.length} Skill edit(s), Skill frontmatter, and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="dependency"){let p=i.manifest.files.find(c=>c.kind==="dependency_lock");if(!p)throw new Error("Candidate Harness has no dependency lock.");JSON.parse(await h.readFile(oe(n,p.path),"utf8")),m=`Validated dependency lock ${p.path} and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="schema")P.parse(e),m=`Validated proposal, manifest, and candidate release schemas for ${i.harnessRelease.id}.`;else if(a.kind==="package"){let p=e.edits.filter(c=>c.route==="agent"&&c.operation!=="delete"&&c.target!=="harness.json");for(let c of p){if(!c.content)throw new Error(`Agent edit ${c.target} has no source.`);me(c.content,{mode:"transform",sourceUrl:c.target,sourceMap:!1})}m=p.length>0?`Syntax-checked ${p.length} Agent source edit(s) and compiled candidate ${i.harnessRelease.id}.`:`Compiled candidate package ${i.harnessRelease.id} and preserved the Harness source manifest contract.`}else if(a.kind==="component_activation"){let p=e.edits.filter(c=>c.target!=="harness.json");if(p.length===0)throw new Error("Component activation requires a concrete Harness component edit.");if(e.route==="agent"){if(p.filter(g=>g.operation!=="delete").length>0)throw new Error("Desktop Work does not compile or execute released Agent source; use an active instruction or standalone Skill, or add an Agent executor before release.");m=`Confirmed ${p.length} deleted Agent component(s) were inactive in Desktop Work.`}else{if(!["prompt","skill"].includes(e.route))throw new Error(`Desktop Work has no activation policy for ${e.route} proposals.`);let c=e.route==="prompt"?"instruction":"skill";for(let g of p){let k=f.components.find(H=>H.path===g.target&&H.kind===c);if(g.operation==="delete"?k:!k)throw new Error(`${c} ${g.target} is not reflected in the candidate Desktop Work runtime surface.`)}if(u.contentHash===f.contentHash)throw new Error("The candidate does not change the effective Desktop Work runtime surface.");m=`Activated ${p.length} ${c} edit(s) in the candidate Desktop Work runtime surface.`}}else a.kind==="business_formula"?(v="blocked",m="Business or financial logic is retained for review until an approved deterministic fixture supplies inputs and expected outputs."):a.kind==="targeted_evaluation"?(v="blocked",m="This sensitive change requires an explicit authority-preserving targeted Evaluation before release."):a.kind==="file_render"?(v="blocked",m="File-render validation requires an exact produced artifact reference; no artifact was attached to this Harness-source proposal."):(v="blocked",m=`Local targeted validation does not yet own ${a.kind}; it requires its dedicated validator.`)}catch(p){v="failed",m=p instanceof Error?p.message:String(p)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${a.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:a.id,kind:a.kind,status:v,summary:m,evidenceRefs:e.evidence,createdAt:o,metadata:{candidateHarnessRelease:{id:i.harnessRelease.id,contentHash:i.harnessRelease.contentHash},sourceRevision:i.sourceRevision,...a.kind==="component_activation"?{targetRuntime:"desktop_work",beforeEffectiveRuntimeHash:u.contentHash,afterEffectiveRuntimeHash:f.contentHash,activatedComponentRefs:f.components,inactiveAgentRefs:f.inactiveAgents}:{}}})}))}catch(i){let l=i instanceof Error?i.message:String(i);return e.validationPlan.map(d=>q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${d.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:d.id,kind:d.kind,status:"failed",summary:l,evidenceRefs:e.evidence,createdAt:o,metadata:{}}))}finally{await h.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}w(We,"validateLocalHarnessRefinerProposal");function se(s){let e=[...s.agentSnapshot.instructions.map(t=>({kind:"instruction",path:t.path,contentHash:t.contentHash})),...s.agentSnapshot.skills.map(t=>({kind:"skill",path:t.path,contentHash:t.contentHash}))].sort((t,n)=>t.path.localeCompare(n.path)),r=s.agentSnapshot.agents.map(t=>({path:t.path,contentHash:t.contentHash})).sort((t,n)=>t.path.localeCompare(n.path));return{contentHash:_({schemaVersion:"openpond.desktopWorkHarnessSurface.v1",components:e}),components:e,inactiveAgents:r}}w(se,"desktopWorkRuntimeSurface");function we(s){let e=(s.now??(()=>new Date().toISOString()))(),r=s.proposal.edits.find(t=>t.route==="memory");return s.proposal.validationPlan.map(t=>{let n="passed",o="Memory candidate is bounded, scoped, and contains no obvious credential material.";try{if(t.kind==="observed_recovery"){if(!s.proposal.evidence.some(i=>i.kind==="recovery"))throw new Error("Observed-recovery validation requires recorded recovery evidence.");o="Memory proposal is grounded in immutable recovery evidence."}else if(t.kind==="memory"){if(!r||!/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(r.target))throw new Error("Memory proposal requires one safe memory/<slug> target.");let i=s.proposal.metadata.expectedMemory;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Memory proposal requires an expected revision snapshot.");let l=i;if(l.key!==fe(r.target))throw new Error("Memory proposal expected revision targets a different key.");if(l.revision!==null&&(!Number.isInteger(l.revision)||Number(l.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(l.contentHash!==null&&typeof l.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(l.status!==null&&l.status!=="active"&&l.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");if(l.revision===null&&(l.contentHash!==null||l.status!==null))throw new Error("New memory snapshot must not claim existing content or status.");if(l.revision!==null&&(typeof l.contentHash!="string"||l.status===null))throw new Error("Existing memory snapshot requires its content hash and status.");if(r.operation==="delete"&&l.status!=="active")throw new Error("Memory deletion requires an active expected revision.");if(r.operation!=="delete"){if(!r.content?.trim()||r.content.length>24e3)throw new Error("Memory content must contain 1-24,000 characters.");if(/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(r.content))throw new Error("Memory content appears to contain credential material.")}}else n="blocked",o=`Memory validation cannot satisfy ${t.kind}.`}catch(i){n="failed",o=i instanceof Error?i.message:String(i)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${s.proposal.id}-${t.id}`,proposal:{id:s.proposal.id,contentHash:s.proposal.contentHash},validationId:t.id,kind:t.kind,status:n,summary:o,evidenceRefs:s.proposal.evidence,createdAt:e,metadata:{externalState:"harness_memory"}})})}w(we,"validateMemoryProposal");function fe(s){let e=s.replaceAll("\\","/"),r=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(e);if(!r)throw new Error(`Invalid Harness memory target: ${s}.`);return r[1]}w(fe,"memoryKeyFromTarget");async function te(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e)throw new Error(`Harness workspace ${s.workspaceId} does not exist.`);let r=D(s.storeDir,e.id),t=R.join(r.root,"source-swap.json"),n=await h.readFile(t,"utf8").then(JSON.parse).catch(l=>{if(l.code==="ENOENT")return null;throw l});if(!n)return"none";let o=await I({workspaceId:e.id,sourceDir:r.source});if(e.sourceRevision===n.nextSourceRevision&&o.sourceRevision===n.nextSourceRevision)return await h.rm(n.backupSource,{recursive:!0,force:!0}),await h.rm(t,{force:!0}),"completed";let i=await I({workspaceId:e.id,sourceDir:n.backupSource});if(e.sourceRevision===n.previousSourceRevision&&i.sourceRevision===n.previousSourceRevision)return await j(r.source,n.backupSource),await h.rm(t,{force:!0}),"restored";throw new Error("Harness source-swap recovery cannot reconcile filesystem and workspace revisions.")}w(te,"recoverLocalHarnessSourceSwap");async function ae(s,e){for(let r of e.edits){let t=oe(s,r.target);if(r.operation==="delete"){await h.rm(t,{force:!1});continue}if(r.content===null)throw new Error(`Refiner edit ${r.id} has no content.`);if(r.operation==="create")await h.mkdir(R.dirname(t),{recursive:!0}),await h.writeFile(t,r.content,{flag:"wx"});else{let n=await h.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`Refiner update target must be a regular file: ${r.target}`);await h.writeFile(t,r.content,{flag:"w"})}}}w(ae,"applyOverlayEdits");function oe(s,e){let r=R.resolve(s),t=R.resolve(r,...e.replaceAll("\\","/").split("/")),n=R.relative(r,t);if(!n||n.startsWith("..")||R.isAbsolute(n))throw new Error(`Refiner edit target escapes the Harness source: ${e}`);return t}w(oe,"containedPath");async function ne(s,e){let r=`${s}.${O()}.tmp`;await h.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
2
|
+
import{ca as Y,fa as D,ga as Z,ha as ee,la as I,ma as re}from"./chunk-FFTVDR3E.js";import{E as x}from"./chunk-PKBU37CH.js";import{kd as X}from"./chunk-JIG7KQOX.js";import{b as W}from"./chunk-L3KS6MOV.js";import{Ba as G,Ca as Q,i as B,l as K,o as J,q as $,r as P,s as U,v as L,x as q}from"./chunk-QUNRWDVO.js";import{k as N,l as _,m as A}from"./chunk-HZP5U2AA.js";import{b as S}from"./chunk-ES2ISFJC.js";import{a as w}from"./chunk-FTQLQJQV.js";import{randomUUID as Re}from"node:crypto";import{readFile as C}from"node:fs/promises";import E from"node:path";import{promises as le}from"node:fs";import y from"node:path";import{randomUUID as O}from"node:crypto";import{promises as h}from"node:fs";import{stripTypeScriptTypes as me}from"node:module";import R from"node:path";async function Oe(s){let e=$.parse(s.overlay),r=P.parse(s.proposal),t=s.validations.map(u=>U.parse(u));if((r.route==="agent"?r.edits.filter(u=>u.target!=="harness.json"&&u.operation!=="delete"):[]).length>0){let u=r.validationPlan.find(a=>a.kind==="component_activation"&&a.required);if(!u)throw new Error("Desktop Work Agent proposals require component-activation validation before review.");if(t.find(a=>a.validationId===u.id)?.status==="passed")throw new Error("Desktop Work cannot accept a passed Agent activation receipt until an Agent source executor exists.")}if(r.overlay.id!==e.id||r.overlay.revision!==e.revision||r.overlay.contentHash!==e.contentHash)throw new Error("Refiner proposal is not bound to the supplied run overlay.");if(e.status!=="frozen")throw new Error("Only a frozen run overlay can advance a Harness workspace.");let o=await s.store.getHarnessWorkspace(r.expectedWorkspace.workspaceId);if(!o)throw new Error(`Harness workspace ${r.expectedWorkspace.workspaceId} does not exist.`);if(o.location!==s.store.harnessStoragePlacement)throw new Error("Refiner workspace does not match the admitted storage placement.");let i=D(s.storeDir,o.id),l=await I({workspaceId:o.id,sourceDir:i.source});if(l.sourceRevision!==o.sourceRevision)throw new Error(`Harness source is ${l.sourceRevision}; workspace expects ${o.sourceRevision}. Record or revert the source change before refinement.`);let d=R.join(i.root,`.source-candidate-${O()}`);await h.cp(i.source,d,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{await ae(d,r);let u=await I({workspaceId:o.id,sourceDir:d}),f=(s.now??(()=>new Date().toISOString()))(),a=await re({storeDir:s.storeDir,workspaceId:o.id,compiled:u,createdAt:f});await s.store.saveHarnessReleaseRecord(a),await s.store.saveHarnessImprovementArtifact(o.id,"run_overlay",e),await s.store.saveHarnessImprovementArtifact(o.id,"proposal",r);for(let c of t)await s.store.saveHarnessImprovementArtifact(o.id,"targeted_validation",c);if(!X({workspace:o,proposal:r}).eligible&&!s.reviewAuthority)return s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});let m=R.join(i.root,`.source-backup-${O()}`),p=R.join(i.root,"source-swap.json");await ne(p,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:o.id,expectedWorkspaceRevision:o.revision,previousSourceRevision:o.sourceRevision,nextSourceRevision:a.sourceRevision,backupSource:m,candidateSource:d,createdAt:f}),await h.rename(i.source,m),await h.rename(d,i.source);try{let c=s.reviewAuthority?await s.store.advanceReviewedHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,reviewer:s.reviewAuthority.reviewer,now:f}):await s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});return c.receipt.decision!=="advanced"?await j(i.source,m):await h.rm(m,{recursive:!0,force:!0}),await h.rm(p,{force:!0}),c}catch(c){throw await j(i.source,m).catch(()=>{}),await h.rm(p,{force:!0}).catch(()=>{}),c}}finally{await h.rm(d,{recursive:!0,force:!0}).catch(()=>{})}}w(Oe,"applyLocalHarnessRefinerProposal");async function $e(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e||e.location!==s.store.harnessStoragePlacement)throw new Error(`Local Harness workspace ${s.workspaceId} does not exist.`);if(e.currentChannel.release?.id!==s.rollbackOf.id||e.currentChannel.release.contentHash!==s.rollbackOf.contentHash)throw new Error("Harness rollback source is no longer the current release.");let r=await s.store.getHarnessReleaseRecord(s.targetRelease.contentHash);if(!r||r.workspaceId!==e.id||r.harnessRelease.id!==s.targetRelease.id)throw new Error("Harness rollback target is unavailable in this workspace.");let t=D(s.storeDir,e.id);if((await I({workspaceId:e.id,sourceDir:t.source})).sourceRevision!==e.sourceRevision)throw new Error("Harness source changed before rollback.");let o=R.join(t.root,`.source-rollback-${O()}`);await h.cp(R.join(r.bundlePath,"source"),o,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{if((await I({workspaceId:e.id,sourceDir:o})).sourceRevision!==r.sourceRevision)throw new Error("Harness rollback bundle does not reproduce its registered source revision.");let l=(s.now??(()=>new Date().toISOString()))(),d=R.join(t.root,`.source-backup-${O()}`),u=R.join(t.root,"source-swap.json");await ne(u,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:e.id,expectedWorkspaceRevision:e.revision,previousSourceRevision:e.sourceRevision,nextSourceRevision:r.sourceRevision,backupSource:d,candidateSource:o,createdAt:l}),await h.rename(t.source,d),await h.rename(o,t.source);try{let f=await s.store.rollbackHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:e.id,expectedWorkspaceRevision:e.revision,expectedChannelRevision:e.currentChannel.revision,targetRelease:s.targetRelease,targetSourceRevision:r.sourceRevision,rollbackOf:s.rollbackOf,now:l});return f.receipt.decision!=="rolled_back"?await j(t.source,d):await h.rm(d,{recursive:!0,force:!0}),await h.rm(u,{force:!0}),f}catch(f){throw await j(t.source,d).catch(()=>{}),await h.rm(u,{force:!0}).catch(()=>{}),f}}finally{await h.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}w($e,"rollbackLocalHarnessWorkspaceRelease");async function We(s){let e=P.parse(s.proposal);if(e.expectedWorkspace.workspaceId!==s.workspace.id)throw new Error("Refiner proposal targets a different Harness workspace.");if(e.route==="memory")return we({proposal:e,now:s.now});let r=D(s.storeDir,s.workspace.id),t=await I({workspaceId:s.workspace.id,sourceDir:r.source});if(t.sourceRevision!==e.expectedWorkspace.sourceRevision)throw new Error("Refiner proposal source revision no longer matches the Local Harness workspace.");let n=R.join(r.root,`.validation-candidate-${O()}`);await h.cp(r.source,n,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});let o=(s.now??(()=>new Date().toISOString()))();try{await ae(n,e);let i=await I({workspaceId:s.workspace.id,sourceDir:n}),l=new Map(i.manifest.files.map(a=>[a.path,a])),d=new Map(e.edits.map(a=>[a.target,a])),u=se(t),f=se(i);return Promise.all(e.validationPlan.map(async a=>{let v="passed",m="The candidate Harness source compiles and preserves its manifest contract.";try{if(a.kind==="observed_recovery"){let p=e.evidence.filter(c=>c.kind==="recovery");if(p.length===0)throw new Error("Observed-recovery validation requires recorded recovery evidence.");m=`Validated ${p.length} immutable recovery evidence reference(s) before candidate advancement.`}else if(a.kind==="prompt"){let p=e.edits.filter(c=>c.route==="prompt"&&c.target!=="harness.json");if(p.length===0)throw new Error("Prompt validation requires an instruction-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted instruction ${c.target} remains declared.`)}else if(g?.kind!=="instruction")throw new Error(`Instruction ${c.target} is not declared in the candidate Harness.`);if(c.content!==null&&/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(c.content))throw new Error(`Instruction ${c.target} appears to contain credential material.`)}m=`Validated ${p.length} textual instruction edit(s) and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="skill"){let p=e.edits.filter(c=>c.route==="skill"&&c.target!=="harness.json");if(p.length===0)throw new Error("Skill validation requires a declared Skill-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted Skill ${c.target} remains declared.`);continue}if(g?.kind!=="skill")throw new Error(`Skill ${c.target} is not declared in the candidate Harness.`);let k=d.get(c.target)?.content;if(!k)throw new Error(`Skill edit ${c.target} has no content.`);let H=W(k);if(!H.name||!H.description||H.messages.length>0)throw new Error(`Skill ${c.target} is invalid: ${H.messages.join(" ")}`)}m=`Validated ${p.length} Skill edit(s), Skill frontmatter, and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="dependency"){let p=i.manifest.files.find(c=>c.kind==="dependency_lock");if(!p)throw new Error("Candidate Harness has no dependency lock.");JSON.parse(await h.readFile(oe(n,p.path),"utf8")),m=`Validated dependency lock ${p.path} and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="schema")P.parse(e),m=`Validated proposal, manifest, and candidate release schemas for ${i.harnessRelease.id}.`;else if(a.kind==="package"){let p=e.edits.filter(c=>c.route==="agent"&&c.operation!=="delete"&&c.target!=="harness.json");for(let c of p){if(!c.content)throw new Error(`Agent edit ${c.target} has no source.`);me(c.content,{mode:"transform",sourceUrl:c.target,sourceMap:!1})}m=p.length>0?`Syntax-checked ${p.length} Agent source edit(s) and compiled candidate ${i.harnessRelease.id}.`:`Compiled candidate package ${i.harnessRelease.id} and preserved the Harness source manifest contract.`}else if(a.kind==="component_activation"){let p=e.edits.filter(c=>c.target!=="harness.json");if(p.length===0)throw new Error("Component activation requires a concrete Harness component edit.");if(e.route==="agent"){if(p.filter(g=>g.operation!=="delete").length>0)throw new Error("Desktop Work does not compile or execute released Agent source; use an active instruction or standalone Skill, or add an Agent executor before release.");m=`Confirmed ${p.length} deleted Agent component(s) were inactive in Desktop Work.`}else{if(!["prompt","skill"].includes(e.route))throw new Error(`Desktop Work has no activation policy for ${e.route} proposals.`);let c=e.route==="prompt"?"instruction":"skill";for(let g of p){let k=f.components.find(H=>H.path===g.target&&H.kind===c);if(g.operation==="delete"?k:!k)throw new Error(`${c} ${g.target} is not reflected in the candidate Desktop Work runtime surface.`)}if(u.contentHash===f.contentHash)throw new Error("The candidate does not change the effective Desktop Work runtime surface.");m=`Activated ${p.length} ${c} edit(s) in the candidate Desktop Work runtime surface.`}}else a.kind==="business_formula"?(v="blocked",m="Business or financial logic is retained for review until an approved deterministic fixture supplies inputs and expected outputs."):a.kind==="targeted_evaluation"?(v="blocked",m="This sensitive change requires an explicit authority-preserving targeted Evaluation before release."):a.kind==="file_render"?(v="blocked",m="File-render validation requires an exact produced artifact reference; no artifact was attached to this Harness-source proposal."):(v="blocked",m=`Local targeted validation does not yet own ${a.kind}; it requires its dedicated validator.`)}catch(p){v="failed",m=p instanceof Error?p.message:String(p)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${a.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:a.id,kind:a.kind,status:v,summary:m,evidenceRefs:e.evidence,createdAt:o,metadata:{candidateHarnessRelease:{id:i.harnessRelease.id,contentHash:i.harnessRelease.contentHash},sourceRevision:i.sourceRevision,...a.kind==="component_activation"?{targetRuntime:"desktop_work",beforeEffectiveRuntimeHash:u.contentHash,afterEffectiveRuntimeHash:f.contentHash,activatedComponentRefs:f.components,inactiveAgentRefs:f.inactiveAgents}:{}}})}))}catch(i){let l=i instanceof Error?i.message:String(i);return e.validationPlan.map(d=>q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${d.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:d.id,kind:d.kind,status:"failed",summary:l,evidenceRefs:e.evidence,createdAt:o,metadata:{}}))}finally{await h.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}w(We,"validateLocalHarnessRefinerProposal");function se(s){let e=[...s.agentSnapshot.instructions.map(t=>({kind:"instruction",path:t.path,contentHash:t.contentHash})),...s.agentSnapshot.skills.map(t=>({kind:"skill",path:t.path,contentHash:t.contentHash}))].sort((t,n)=>t.path.localeCompare(n.path)),r=s.agentSnapshot.agents.map(t=>({path:t.path,contentHash:t.contentHash})).sort((t,n)=>t.path.localeCompare(n.path));return{contentHash:_({schemaVersion:"openpond.desktopWorkHarnessSurface.v1",components:e}),components:e,inactiveAgents:r}}w(se,"desktopWorkRuntimeSurface");function we(s){let e=(s.now??(()=>new Date().toISOString()))(),r=s.proposal.edits.find(t=>t.route==="memory");return s.proposal.validationPlan.map(t=>{let n="passed",o="Memory candidate is bounded, scoped, and contains no obvious credential material.";try{if(t.kind==="observed_recovery"){if(!s.proposal.evidence.some(i=>i.kind==="recovery"))throw new Error("Observed-recovery validation requires recorded recovery evidence.");o="Memory proposal is grounded in immutable recovery evidence."}else if(t.kind==="memory"){if(!r||!/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(r.target))throw new Error("Memory proposal requires one safe memory/<slug> target.");let i=s.proposal.metadata.expectedMemory;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Memory proposal requires an expected revision snapshot.");let l=i;if(l.key!==fe(r.target))throw new Error("Memory proposal expected revision targets a different key.");if(l.revision!==null&&(!Number.isInteger(l.revision)||Number(l.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(l.contentHash!==null&&typeof l.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(l.status!==null&&l.status!=="active"&&l.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");if(l.revision===null&&(l.contentHash!==null||l.status!==null))throw new Error("New memory snapshot must not claim existing content or status.");if(l.revision!==null&&(typeof l.contentHash!="string"||l.status===null))throw new Error("Existing memory snapshot requires its content hash and status.");if(r.operation==="delete"&&l.status!=="active")throw new Error("Memory deletion requires an active expected revision.");if(r.operation!=="delete"){if(!r.content?.trim()||r.content.length>24e3)throw new Error("Memory content must contain 1-24,000 characters.");if(/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(r.content))throw new Error("Memory content appears to contain credential material.")}}else n="blocked",o=`Memory validation cannot satisfy ${t.kind}.`}catch(i){n="failed",o=i instanceof Error?i.message:String(i)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${s.proposal.id}-${t.id}`,proposal:{id:s.proposal.id,contentHash:s.proposal.contentHash},validationId:t.id,kind:t.kind,status:n,summary:o,evidenceRefs:s.proposal.evidence,createdAt:e,metadata:{externalState:"harness_memory"}})})}w(we,"validateMemoryProposal");function fe(s){let e=s.replaceAll("\\","/"),r=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(e);if(!r)throw new Error(`Invalid Harness memory target: ${s}.`);return r[1]}w(fe,"memoryKeyFromTarget");async function te(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e)throw new Error(`Harness workspace ${s.workspaceId} does not exist.`);let r=D(s.storeDir,e.id),t=R.join(r.root,"source-swap.json"),n=await h.readFile(t,"utf8").then(JSON.parse).catch(l=>{if(l.code==="ENOENT")return null;throw l});if(!n)return"none";let o=await I({workspaceId:e.id,sourceDir:r.source});if(e.sourceRevision===n.nextSourceRevision&&o.sourceRevision===n.nextSourceRevision)return await h.rm(n.backupSource,{recursive:!0,force:!0}),await h.rm(t,{force:!0}),"completed";let i=await I({workspaceId:e.id,sourceDir:n.backupSource});if(e.sourceRevision===n.previousSourceRevision&&i.sourceRevision===n.previousSourceRevision)return await j(r.source,n.backupSource),await h.rm(t,{force:!0}),"restored";throw new Error("Harness source-swap recovery cannot reconcile filesystem and workspace revisions.")}w(te,"recoverLocalHarnessSourceSwap");async function ae(s,e){for(let r of e.edits){let t=oe(s,r.target);if(r.operation==="delete"){await h.rm(t,{force:!1});continue}if(r.content===null)throw new Error(`Refiner edit ${r.id} has no content.`);if(r.operation==="create")await h.mkdir(R.dirname(t),{recursive:!0}),await h.writeFile(t,r.content,{flag:"wx"});else{let n=await h.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`Refiner update target must be a regular file: ${r.target}`);await h.writeFile(t,r.content,{flag:"w"})}}}w(ae,"applyOverlayEdits");function oe(s,e){let r=R.resolve(s),t=R.resolve(r,...e.replaceAll("\\","/").split("/")),n=R.relative(r,t);if(!n||n.startsWith("..")||R.isAbsolute(n))throw new Error(`Refiner edit target escapes the Harness source: ${e}`);return t}w(oe,"containedPath");async function ne(s,e){let r=`${s}.${O()}.tmp`;await h.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
3
3
|
`,{flag:"wx"}),await h.rename(r,s)}w(ne,"writeSwapJournal");async function j(s,e){await h.rm(s,{recursive:!0,force:!0}),await h.rename(e,s)}w(j,"restoreSource");var b="desktop-personal",ie="personal-default";async function qe(s){let e=await s.store.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});if(e&&e.metadata.selectionEligible!==!1)return await te({store:s.store,storeDir:s.storeDir,workspaceId:e.id}),M(s.store,e.id,e.currentChannel.release?.contentHash??null);let r=(await s.store.listHarnessWorkspaces({ownerKind:"personal",ownerId:b})).find(o=>o.metadata.selectionEligible!==!1);if(r)return await s.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:b,workspaceId:r.id,updatedAt:(s.now??(()=>new Date().toISOString()))()}),M(s.store,r.id,r.currentChannel.release?.contentHash??null);let t=await s.loadProfileState(),n=t.mode==="local"&&t.sourcePath&&!t.error?await ee({store:s.store,storeDir:s.storeDir,id:ie,ownerId:b,name:t.activeProfile?.trim()||"Personal Harness",profile:t,now:s.now}):await Z({store:s.store,storeDir:s.storeDir,id:ie,ownerId:b,name:"Personal Harness",now:s.now});return await s.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:b,workspaceId:n.workspace.id,updatedAt:(s.now??(()=>new Date().toISOString()))()}),n.release}w(qe,"ensureSelectedLocalHarnessWorkspace");async function ce(s){let e=await s.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});return e?M(s,e.id,e.currentChannel.release?.contentHash??null):null}w(ce,"resolveSelectedLocalHarnessRelease");async function M(s,e,r){if(!r)throw new Error(`Selected Harness workspace ${e} has no current release.`);let t=await s.getHarnessReleaseRecord(r);if(!t||t.workspaceId!==e)throw new Error(`Selected Harness workspace ${e} points to a missing release ${r}.`);return A(t.agentSnapshot,"Selected Agent snapshot"),A(t.harnessRelease,"Selected Harness release"),t}w(M,"requireCurrentRelease");async function Ke(s,e){if(e){let n=await s.getHarnessReleaseRecord(e.contentHash);if(!n||n.harnessRelease.id!==e.id)throw new Error("The selected immutable Harness release is unavailable.");let o=await s.getHarnessWorkspace(n.workspaceId);if(!o||o.ownerScope.kind!=="personal"||o.ownerScope.id!==b)throw new Error("The selected Harness release is not available to this local owner.");return A(n.agentSnapshot,"Selected Agent snapshot"),A(n.harnessRelease,"Selected Harness release"),T({workspace:o,release:n})}let r=await ce(s);if(!r)return null;let t=await s.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});if(!t||t.id!==r.workspaceId)throw new Error("Selected Harness workspace changed while its release was being admitted.");return T({workspace:t,release:r})}w(Ke,"loadSelectedLocalHarnessRuntime");async function T(s){let{workspace:e,release:r}=s;if(r.workspaceId!==e.id)throw new Error("Harness release does not belong to the requested workspace.");let t=y.join(r.bundlePath,"source");await Promise.all(r.harnessRelease.files.map(a=>ve(t,a.path,a.contentHash)));let n=await Promise.all(r.agentSnapshot.instructions.map(async a=>({path:a.path,content:await z(t,a.path,a.contentHash)}))),o=[],i=new Map;for(let a of r.agentSnapshot.skills){let v=await z(t,a.path,a.contentHash),m=W(v);if(!m.name||!m.description||m.messages.length>0)throw new Error(`Released Harness Skill ${a.path} is invalid: ${m.messages.join(" ")||"missing name or description"}`);if(i.has(m.name))throw new Error(`Released Harness has duplicate Skill ${m.name}.`);let p=`${y.posix.dirname(a.path)}/`,c=r.harnessRelease.files.filter(k=>k.path.startsWith(p)&&k.path!==a.path).map(k=>k.path.slice(p.length)).sort(),g={name:m.name,description:m.description,path:a.path,scope:"profile",enabled:!0,sourcePath:t,charCount:v.length,sourceHash:a.contentHash,validationStatus:"valid",validationMessages:[],resourceFiles:c};o.push(g),i.set(g.name,async()=>{let k=await z(t,a.path,a.contentHash),H=W(k);if(!H.name||!H.description||H.messages.length>0)throw new Error(`Released Harness Skill ${a.path} failed validation while loading.`);return{name:H.name,description:H.description,body:H.body,path:a.path,sourceHash:a.contentHash,charCount:k.length,packagePath:y.join(t,...y.posix.dirname(a.path).split("/")),resourceFiles:c}})}o.sort((a,v)=>a.name.localeCompare(v.name));let l={profileSourcePath:t,skills:o,readSkill:i.size>0?async a=>{let v=i.get(a);if(!v)throw new Error(`Released Harness Skill not found: ${a}`);return v()}:null},d=n.sort((a,v)=>a.path.localeCompare(v.path)).map(({path:a,content:v})=>[`Active Harness instruction (${a}):`,v.trim()].join(`
|
|
4
4
|
`)).filter(a=>a.trim().length>0),f=[["Harness capability receipt:",JSON.stringify({harnessRelease:{id:r.harnessRelease.id,contentHash:r.harnessRelease.contentHash},agentSnapshot:{id:r.agentSnapshot.id,contentHash:r.agentSnapshot.contentHash},files:r.harnessRelease.files.map(a=>({path:a.path,contentHash:a.contentHash})),skills:r.agentSnapshot.skills.map(a=>a.path),agents:r.agentSnapshot.agents.map(a=>a.path),tools:r.agentSnapshot.toolDeclarations.map(a=>a.name),capabilityRequirements:r.agentSnapshot.capabilityRequirements})].join(`
|
|
5
5
|
`),d.length>0?["Active Harness preflight:","Apply the following released instructions when planning work and immediately before every tool call.","Preflight each call: (1) identify any active instruction that matches the planned operation, (2) inspect the exact tool arguments for a forbidden pattern, and (3) rewrite the call before sending it when a pattern matches. Compliance is required even when the prohibited call might still succeed.",...d].join(`
|