openpond 0.2.73 → 0.2.74
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/chunks/{acp-35QBGOMJ.js → acp-TBDNUDTR.js} +1 -1
- package/dist/chunks/{app-layer-42ZKHTPN.js → app-layer-4YIA53WX.js} +1 -1
- package/dist/chunks/{apps-EGFRTFAJ.js → apps-APEPLFYU.js} +1 -1
- package/dist/chunks/{chunk-OFC5N6R3.js → chunk-5SVBY7NP.js} +6 -6
- package/dist/chunks/{chunk-P7RLDDPN.js → chunk-KOC74O7R.js} +1 -1
- package/dist/chunks/{configuration-command-XMXTU2FQ.js → configuration-command-SAGJMI3I.js} +1 -1
- package/dist/chunks/{connected-evidence-NFQPO5E3.js → connected-evidence-EVZTMVHV.js} +1 -1
- package/dist/chunks/{connected-starting-assets-M54PSOEP.js → connected-starting-assets-F2DBUHV5.js} +1 -1
- package/dist/chunks/{core-commands-SY4I5FHE.js → core-commands-Z27A5ZPQ.js} +1 -1
- package/dist/chunks/{datasets-2OQDMF7E.js → datasets-RZBRILIN.js} +1 -1
- package/dist/chunks/{desktop-test-VNMR5H4I.js → desktop-test-UXOA4EON.js} +1 -1
- package/dist/chunks/{evaluation-coordination-GULGPATI.js → evaluation-coordination-43DTVJFD.js} +1 -1
- package/dist/chunks/{experiment-improvements-XNXTU6ZA.js → experiment-improvements-JBYCVRYR.js} +1 -1
- package/dist/chunks/{experiments-DZX6ZU6F.js → experiments-5QAMBNB6.js} +1 -1
- package/dist/chunks/{experiments-signal-QDVPO3M5.js → experiments-signal-OIDQ5SNH.js} +1 -1
- package/dist/chunks/{help-UCN67FN7.js → help-ESZC6NHQ.js} +1 -1
- package/dist/chunks/{human-review-DNVIVJRK.js → human-review-HTHWLUNA.js} +1 -1
- package/dist/chunks/{import-QT5AKEA3.js → import-IWDEDLM3.js} +1 -1
- package/dist/chunks/{opchat-7PWUXQSY.js → opchat-RJINPBFB.js} +1 -1
- package/dist/chunks/{opchat-bounded-chat-B3GOCGWY.js → opchat-bounded-chat-WRXN7S52.js} +1 -1
- package/dist/chunks/{organizations-TWBMN7KF.js → organizations-AWMQ46PJ.js} +1 -1
- package/dist/chunks/{profile-RVARQYG4.js → profile-VJDML6I7.js} +1 -1
- package/dist/chunks/{project-agent-ZC33YRZE.js → project-agent-NI4EGNDI.js} +1 -1
- package/dist/chunks/{sandbox-command-HWIAH6JA.js → sandbox-command-763SZPJ4.js} +1 -1
- package/dist/chunks/{sandbox-template-MNZ6OXQQ.js → sandbox-template-AVTZNKFZ.js} +1 -1
- package/dist/chunks/{teams-bot-7U6JOV6T.js → teams-bot-PX7HUAQQ.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/skills/manifest.json +1 -1
- package/docs/command-reference.md +1 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as Z,b as v,d as re}from"./chunk-GMA365GI.js";import"./chunk-HYUTDZ3N.js";import{c as Q}from"./chunk-RFQD6B44.js";import{a as A,d as k}from"./chunk-6IKIGVJF.js";import{Ol as V,Pl as B,sm as K}from"./chunk-5AV2EWFX.js";import"./chunk-2EAZB2MW.js";import"./chunk-ZMRP2A7K.js";import"./chunk-P7RLDDPN.js";import"./chunk-OFC5N6R3.js";import"./chunk-XRKFTPHD.js";import{Bd as ee,df as te,gf as ae}from"./chunk-2IECLXB2.js";import"./chunk-W45RKGM6.js";import"./chunk-73COPJ32.js";import"./chunk-UGDBMRCT.js";import"./chunk-2PVW2XFF.js";import"./chunk-64EDQ7UV.js";import{J as G}from"./chunk-DLOJG7LP.js";import"./chunk-ULTV6INR.js";import"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import"./chunk-GR4MJJCE.js";import{q as N}from"./chunk-GG6PM7TB.js";import"./chunk-2GEZ3ZY7.js";import"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import"./chunk-HIQPGYVH.js";import"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-KHDCMVEJ.js";import{n as X,o as Y}from"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import{d as W}from"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import{m as z,q as J}from"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import{Fb as M}from"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{a as H}from"./chunk-JF7WWLNW.js";import"./chunk-RRWL5BHZ.js";import{c as F,f as $}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as n,f as T}from"./chunk-3M53YXEI.js";import{b as U}from"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{h as _,n as D}from"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-NXN7GJOH.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as g}from"./chunk-FTQLQJQV.js";import{readFile as O,stat as j}from"node:fs/promises";var y=e.string().trim().min(1).max(500),ne=e.string().regex(/^[a-f0-9]{64}$/),me=e.object({schemaVersion:e.literal("openpond.experimentCaseInspection.v1"),teamId:y,executionId:y,manifestHash:ne,receiptId:y,taskId:y,seed:e.string().min(1),input:e.record(e.string(),e.unknown()).nullable(),output:e.unknown().nullable(),error:e.string().nullable(),events:e.array(e.record(e.string(),e.unknown())).max(25),nextEventCursor:y.nullable(),eventCount:e.number().int().nonnegative()}).strict(),pe=me.extend({contentHash:ne}).strict(),L=class{constructor(s){this.options=s;let a=new URL(s.baseUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash||!s.apiKey.trim()||!s.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=a.toString().replace(/\/+$/,"")}options;static{g(this,"OpenPondExperimentInspectionClient")}baseUrl;async case(s,a,t={}){let l=new URLSearchParams(t.afterId?{afterId:y.parse(t.afterId)}:{}),p=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/experiments/${encodeURIComponent(y.parse(s))}/cases/${encodeURIComponent(y.parse(a))}?${l}`,{signal:t.signal,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,Accept:"application/json"}}),w=await p.json();if(!p.ok)throw new Error(e.object({message:e.string()}).parse(w).message);let d=pe.parse(w),{contentHash:o,...i}=d;if(D(i)!==o||d.teamId!==this.options.teamId||d.executionId!==s||d.receiptId!==a||t.manifestHash&&d.manifestHash!==t.manifestHash||d.events.length>d.eventCount)throw new Error("Case inspection differs from its requested workspace, execution or retained content.");return d}};import{readFile as ye,stat as de}from"node:fs/promises";var R=e.string().trim().min(1).max(240),fe=e.object({location:e.literal("local").default("local"),jobId:R,modelRunId:R,modelId:R,modelVersionId:R.nullable(),adapterArtifactLineageId:R.nullable(),owner:e.object({teamId:R,actorId:R}).strict(),taskset:_,state:e.enum(["prepared","running","succeeded","failed","cancelled"]),executionState:e.enum(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),updatedAt:e.iso.datetime()}).strict(),he=e.object({location:e.literal("cloud"),jobId:R,owner:e.object({teamId:R,actorId:R}).strict(),apiOrigin:e.url(),job:G,updatedAt:e.iso.datetime()}).strict().refine(r=>r.jobId===r.job.id&&r.owner.teamId===r.job.teamId&&r.updatedAt===r.job.updatedAt,"Hosted training attachment must match its canonical job."),ie=e.union([fe,he]);var u=e.string().trim().min(1).max(240),I=e.string().regex(/^[a-f0-9]{64}$/),ge=e.object({kind:e.enum(["structure","graders"]),revision:e.number().int().positive(),workspaceHash:I,status:e.enum(["passed","failed","unavailable"]),checkedAt:e.iso.datetime(),checked:e.number().int().nonnegative(),total:e.number().int().nonnegative(),issues:e.array(e.object({code:e.string(),message:e.string(),taskId:u.optional(),graderId:u.optional()})).max(1e4),scopes:e.array(e.object({graderId:u,checked:e.number().int().nonnegative(),total:e.number().int().nonnegative(),status:e.enum(["passed","failed","unavailable"])}).strict()).max(1e3).optional()}).strict(),we=e.object({apiOrigin:e.url(),actorId:u,teamId:u,datasetId:u,remoteRevision:e.number().int().nonnegative(),acknowledgedHash:I.nullable(),remoteHash:I.nullable(),pendingLocalHash:I.nullable(),paused:e.boolean(),status:e.enum(["pending","syncing","synced","retry","conflict","paused"]),error:e.string().nullable(),operationId:u.nullable(),pendingWorkspace:N.nullable(),beginVersionOperationId:u.nullable().optional(),publicationIntent:e.object({operationId:u,expectedRevision:e.number().int().positive(),workspaceHash:I,packageHash:I,localHash:I}).strict().nullable().optional()}).strict(),Je=e.object({schemaVersion:e.literal("openpond.localDataset.v1"),ownerId:u,projectId:u.nullable(),workspace:N,checks:e.array(ge).max(2),packageHash:I.nullable(),sync:we.nullable()}).strict(),E=e.object({kind:e.enum(["dataset","grader","experiment"]),id:u,revision:e.number().int().positive(),name:e.string().max(500),state:e.string().max(100),datasetId:u.optional(),datasetRevision:e.number().int().positive().optional(),taskCount:e.number().int().nonnegative().optional(),graderCount:e.number().int().nonnegative().optional(),checkState:e.string().optional(),syncState:e.string().optional(),model:e.string().optional(),evaluationHash:I.optional(),graderId:u.optional(),graderType:e.string().optional(),description:e.string().optional(),location:e.enum(["local","cloud"]).optional(),scoreLabel:e.string().optional(),owner:e.object({teamId:u,actorId:u}).strict().optional(),contentHash:I.optional(),profileRef:Z.optional(),score:e.number().nullable().optional(),costUsd:e.number().nonnegative().nullable().optional(),evaluatedCount:e.number().int().nonnegative().optional(),failedCount:e.number().int().nonnegative().optional(),qualityFailureCount:e.number().int().nonnegative().optional(),executionFailureCount:e.number().int().nonnegative().optional(),ungradedCount:e.number().int().nonnegative().optional(),rows:e.array(e.object({id:u,label:e.string(),detail:e.string(),score:e.number().nullable().optional()})).max(10)}).strict(),oe=e.object({id:u,ordinal:e.number().int().positive(),name:e.string().trim().min(1).max(500),draft:te.optional(),storedDraft:ae.optional(),draftRevision:e.number().int().positive().optional(),creationHash:I.optional(),dataset:E.nullable(),evaluationModel:e.string().min(1).max(500).optional(),executionLocation:e.enum(["local","cloud"]).optional(),graders:e.array(E),selectedGraderId:u.nullable(),runs:e.array(E),selectedRunId:u.nullable(),training:e.array(ie).optional(),selectedTrainingKey:e.string().max(4e3).nullable().optional(),selectedTrainingJobId:u.nullable().optional(),results:e.array(ee).max(16).optional(),turnIds:e.array(u),operationId:u,createdAt:e.iso.datetime(),updatedAt:e.iso.datetime()}).strict(),be=oe.extend({ordinal:e.null()}),Ve=e.object({datasetFocus:be.optional(),scopes:e.array(oe),activeScopeId:u.nullable(),selectionVersion:e.number().int().nonnegative(),selectedAt:e.iso.datetime().nullable(),selectionOperations:e.record(e.string(),e.object({hash:I,version:e.number().int().nonnegative(),visualPublicationId:e.string().optional(),resource:E.optional()}).strict()).default({})}).strict();var Be=e.object({action:e.enum(["schema","list","read","create","save","file","validate","check_graders","check_sources","package","import","inspect_source","import_source","upload","sync","pause_sync","disconnect_sync","related_chats","list_graders","read_grader","save_grader","test_grader","publish"]),id:u.optional(),operationId:u.optional(),expectedRevision:e.number().int().nonnegative().optional(),payload:e.record(e.string(),e.unknown()).default({})}).strict(),Ke=e.object({contentHash:I,scope:e.string(),graders:e.unknown(),cases:e.array(e.object({id:u,taskId:u,seed:e.string(),status:e.string(),output:e.string().nullable(),error:e.string().nullable(),score:e.number().nullable()}).strict()).max(1e4)}).strict();function se(r){let s=r&&typeof r=="object"?r:{},a=[s.summary,...Array.isArray(s.summaries)?s.summaries:[]].flatMap(t=>{let l=E.safeParse(t);return l.success?[l.data]:[]});if(a.length){for(let t of a)console.log(`${t.name} \xB7 ${t.state}`),console.log(`${t.id} \xB7 ${t.location??"local"} \xB7 Dataset ${t.datasetId} version ${t.datasetRevision} \xB7 ${t.model}`),console.log(`${t.scoreLabel??"Mean task score"}: ${t.score==null?"Unavailable":(t.score*100).toFixed(1)+"%"} \xB7 Graded: ${t.evaluatedCount??0}/${t.taskCount??0} \xB7 Cost: ${t.costUsd==null?"Unavailable":"$"+t.costUsd.toFixed(4)}`),console.log(`Quality failures: ${t.qualityFailureCount??0} \xB7 Execution failures: ${t.executionFailureCount??0} \xB7 Ungraded: ${t.ungradedCount??t.taskCount??0}`),t.rows.length&&console.table(t.rows.map(l=>({Task:l.label,Outcome:l.detail,Score:l.score==null?"Unavailable":(l.score*100).toFixed(1)+"%"}))),console.log(`Results: openpond experiments result ${t.id} --local`);Array.isArray(s.items)&&console.table(s.items.flatMap(t=>{let l=v.safeParse(t);return l.success?[{ID:l.data.id,Name:l.data.configuration.request.name,Model:l.data.model.modelId,Status:l.data.status}]:[]}));for(let t of Array.isArray(s.errors)?s.errors:[])console.log(`Admission failed: ${t.modelId} \xB7 ${t.message}`);return}if(Array.isArray(s.models)){console.table(s.models);return}if(Array.isArray(s.items)){console.table(s.items.flatMap(t=>{let l=v.safeParse(t);return l.success?[{ID:l.data.id,Name:l.data.configuration.request.name,Model:l.data.model.modelId,Status:l.data.status}]:[]}));return}console.log(JSON.stringify(r,null,2))}g(se,"printLocalExperimentResult");import{readFile as xe,stat as Ie}from"node:fs/promises";var q={"profile-catalog":"/v1/profile/evaluations","prepare-profile":"/v1/profile/evaluations/prepare","run-profile":"/v1/profile/evaluations/run","inspect-profile":"/v1/profile/evaluations/discover"};async function ce(r,s){let a=s[0];if(!a||!Object.hasOwn(q,a))return!1;if(s.length!==1||r.team||r.revision||r.contentHash)throw new Error("Profile experiments accept one action and exact selection in --input-file; ownership is resolved by the running installation.");let t=new URL(n(r,"serverUrl")||process.env.OPENPOND_LOCAL_API_URL||A);if(t.protocol!=="http:"||!["localhost","127.0.0.1"].includes(t.hostname)||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new Error("Local Profile experiments require an HTTP loopback server origin.");let l=n(r,"inputFile"),p;if(l){let c=await Ie(l);if(!c.isFile()||c.size>1048576)throw new Error("Profile selection input must be a file within one MiB.");let b=JSON.parse(await xe(l,"utf8"));if(!b||typeof b!="object"||Array.isArray(b))throw new Error("Profile selection input must be an object.");p=b}else if(a!=="profile-catalog")throw new Error(`${a} requires --input-file with the exact Profile or run selection.`);let w=a==="profile-catalog"&&p?q["inspect-profile"]:q[a],o=await(await k(t.origin,{maximumResponseBytes:32*1024*1024,timeoutMs:a==="run-profile"||a==="prepare-profile"?12e5:6e4}))(new URL(w,t),{method:p?"POST":"GET",...p?{headers:{"content-type":"application/json"},body:JSON.stringify({...p,...["prepare-profile","run-profile","inspect-profile"].includes(a)&&process.env.OPENPOND_CHAT_INVOCATION?{invocationToken:process.env.OPENPOND_CHAT_INVOCATION}:{}})}:{}}),i=await o.json();if(!o.ok){let c=i&&typeof i=="object"&&"error"in i?i.error:void 0;throw new Error(typeof c=="string"?c:`Local Profile experiment request failed (${o.status}).`)}return console.log(JSON.stringify(i,null,2)),!0}g(ce,"runLocalProfileExperimentCommand");import{readFile as Se,stat as Re}from"node:fs/promises";async function le(r,s,a,t,l){let[p,w]=s;if(!["record-modification","modification","modifications"].includes(p??""))return!1;if(!l)throw new Error("Local observation operations require --team <workspace-id>.");let d=K({baseUrl:a,fetch:t}),o;if(p==="record-modification"&&s.length===1){let i=n(r,"inputFile"),c=i?await Re(i):null;if(!i||!c?.isFile()||c.size>V)throw new Error("Provide --input-file <command.json> containing a recording request of at most 8 MiB.");let b=B.parse(JSON.parse(await Se(i,"utf8")));if(b.teamId!==l)throw new Error("The recording request belongs to another workspace.");o=await d.recordModificationObservation(b)}else if(p==="modification"&&w&&s.length===2)o=await d.modificationRecording(w,{teamId:l});else if(p==="modifications"&&s.length===1){let i=n(r,"project"),c=n(r,"search"),b=n(r,"cursor"),m=n(r,"limit");o=await d.modificationRecordings({teamId:l,...i?{projectId:i}:{},...c?{search:c}:{},...b?{cursor:b}:{},...m?{limit:Number(m)}:{}})}else throw new Error("Use experiments record-modification --input-file <command.json>, modification <id>, or modifications, with --local --team <id>.");return console.log(JSON.stringify(o,null,2)),!0}g(le,"runLocalModificationRecordingCommand");async function ue(r,s){if(await ce(r,s))return;let[a,t,l]=s,p=n(r,"team"),w=n(r,"receiptId");if(a==="case"&&(!t||s.length!==2||!w))throw new Error("Usage: experiments case <run-id> --local --receipt-id <retained-receipt-id> [--after-sequence <n>] [--limit <1..500>] --json. A task id is not a receipt id; find receiptId in experiments result <run-id> --local --json (independent runs: evidence.cases[].receiptId).");if(r.revision!==void 0)throw new Error("A local Experiment is one immutable run; read it by id rather than a saved configuration revision.");if(a!=="read"&&r.contentHash!==void 0)throw new Error("An exact configuration hash requires the local read action.");if(!a||s.length>(a==="compare"?3:2))throw new Error("Local Experiments require an action; use --server-url for an existing local server.");let d=n(r,"serverUrl")||process.env.OPENPOND_LOCAL_API_URL||A,o=new URL(d);if(o.protocol!=="http:"||!["localhost","127.0.0.1"].includes(o.hostname)||o.username||o.password||o.search||o.hash||o.pathname!=="/")throw new Error("Local Experiments require an HTTP loopback server origin.");let i=await k(o.origin,{timeoutMs:["prepare-harness","run"].includes(a)?12e5:6e4});if(await le(r,s,o.origin,i,p))return;async function c(h,x){let f=await i(new URL(p?"/v1/local-experiments":"/v1/chat-experiments",o),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...p?{teamId:p}:{},...process.env.OPENPOND_CHAT_INVOCATION?{invocationToken:process.env.OPENPOND_CHAT_INVOCATION}:{},action:h,payload:x})}),S=await f.json();if(!f.ok)throw new Error(typeof S.error=="string"?S.error:`Local Experiment request failed (${f.status}).`);return S}g(c,"command");async function b(){let h=n(r,"inputFile");if(!h||!(await de(h)).isFile()||(await de(h)).size>67108864)throw new Error("Provide a bounded --input-file with exact local configuration and retained package bytes.");return JSON.parse(await ye(h,"utf8"))}g(b,"input");let m;if(!p){if(a==="models")m=await c("models",{});else if(a==="run"||a==="run-cloud")m=await c(a.replaceAll("-","_"),await b());else if(a==="list"){let h=n(r,"afterId"),x=n(r,"limit");m=await c("list",{...h?{afterId:h}:{},...x?{limit:Number(x)}:{}})}else if(a==="compare"&&t&&l)m=await c("compare",{baselineId:t,candidateId:l});else if(a==="case"&&t&&w){let h=n(r,"afterSequence"),x=n(r,"limit");m=await c("case",{id:t,receiptId:w,...h?{afterSequence:Number(h)}:{},...x?{limit:Number(x)}:{}})}else if(t&&["read","status","cancel","result"].includes(a))m=await c(a,{id:t});else throw new Error("Independent local Experiments support models/run/list/read/status/cancel/result/compare/case. Workspace operations require --team.");T(r.json)?console.log(JSON.stringify(m,null,2)):se(m);return}if(a==="prepare-harness"){if(t)throw new Error("Local Profile preparation accepts --input-file rather than an id.");m=await c("prepareHarness",await b())}else if(a==="run"){if(t)throw new Error("Local Run accepts reviewed configuration through --input-file rather than an id.");let h=await b();m=await c(h.package?"run":"runFromRelease",h)}else if(a==="list"){if(t)throw new Error("Local List does not accept an id.");let h=n(r,"status"),x=n(r,"limit"),f=n(r,"project"),S=n(r,"afterId"),C=n(r,"datasetHash"),P=n(r,"search");m=await c("list",{...h?{status:h}:{},...f?{projectId:f}:{},...C?{datasetHash:C}:{},...P?{search:P}:{},...S?{afterId:S}:{},...x?{limit:Number(x)}:{}})}else{if(!t)throw new Error(`${a} requires a local Experiment or scoring pass id.`);let h=n(r,"afterId"),x=n(r,"limit");if(a==="duplicate"){let f=n(r,"operationId");if(!f)throw new Error("Duplicate requires --operation-id for safe replay.");let S=v.parse(await c("read",{id:t})),C=J.parse({...S.configuration,operationId:f,request:{...S.configuration.request,operationId:f},sourceExperimentId:S.id});m=await c("runFromRelease",{configuration:C,expectedPackageHash:S.packageHash})}else if(a==="passes")m=await c("passes",{executionId:t,...h?{afterId:h}:{},...x?{limit:Number(x)}:{}});else if(a==="case"){let f=n(r,"afterSequence");m=await c("case",{id:t,receiptId:w,...f?{afterSequence:Number(f)}:{},...x?{limit:Number(x)}:{}})}else if(a==="score"){let f=await b();if(f.execution?.id!==t)throw new Error("Local scoring input belongs to a different retained execution.");m=await c("score",f)}else if(a==="compare"){if(!l)throw new Error("Local Compare requires baseline and candidate execution ids.");let f=re.parse(await c("compare",{baselineId:t,candidateId:l}));m={...f,comparison:M(f.baseline,f.candidate)}}else if(a==="read"){let f=n(r,"contentHash");m=await c("read",{id:t,...f?{configurationHash:f}:{}})}else if(["status","cancel","result","pass"].includes(a))m=await c(a,{id:t});else if(a==="cancel-pass")m=await c("cancel",{id:t});else if(a==="pass-result")m=await c("result",{id:t});else throw new Error(`Local Experiment action is unavailable: ${a}`)}console.log(JSON.stringify(m,null,2))}g(ue,"runLocalExperimentsCommand");async function At(r,s){if(s[0]==="signal-plan"||s[0]==="signal-report")return(await import("./experiments-signal-QDVPO3M5.js")).runExperimentsSignalCommand(r,s);if(r.local===!0||r.local==="true")return ue(r,s);if(r.revision!==void 0||r.contentHash!==void 0)throw new Error("Experiments retain their immutable configuration on the run; definition revisions are not selectable.");let[a,t]=s,l=n(r,"team");if(!l||!a||s.length>(a==="compare"?3:2))throw new Error("usage: experiments <defaults|create-comparison|comparison-budget|prepare-harness|run|read|list|status|diagnostics|cancel|duplicate|score|passes|pass|cancel-pass|pass-result|result|compare|case> [id] [candidate-id] --team <id> [--input-file <path>] [--operation-id <id>]");let p=await W(),w={teamId:l,fetch:H,apiKey:await Q(p,$(p)),baseUrl:F(r)??p.apiBaseUrl??U},d=new Y(w),o;if(a==="defaults"){if(t)throw new Error("Defaults does not accept an id.");o=await d.defaults()}else if(a==="create-comparison"){let i=n(r,"inputFile");if(!i||t||(await j(i)).size>1048576)throw new Error("Create comparison requires a bounded input file with an id, fresh operationIds and optional maximumSpendUsd.");o=await d.createComparisonBudget(JSON.parse(await O(i,"utf8")))}else if(a==="comparison-budget"){if(!t)throw new Error("Comparison budget requires an id.");o=await d.comparisonBudget(t)}else if(a==="prepare-harness"){let i=n(r,"inputFile");if(!i||t||(await j(i)).size>1048576)throw new Error("Harness preparation requires a bounded --input-file with its released target, model and optional ceiling.");o=await d.prepareHarness(JSON.parse(await O(i,"utf8")))}else if(a==="run"){let i=n(r,"inputFile");if(!i||t)throw new Error("Run requires --input-file with the reviewed configuration and stable operationId.");if((await j(i)).size>1048576)throw new Error("Experiment input exceeds one MiB.");o=await d.run(JSON.parse(await O(i,"utf8")))}else if(a==="list"){if(t)throw new Error("List does not accept an Experiment id.");let i=n(r,"limit");o=await d.list(z.parse({projectId:n(r,"project")||void 0,datasetHash:n(r,"datasetHash")||void 0,search:n(r,"search")||void 0,status:n(r,"status")||void 0,afterId:n(r,"afterId")||void 0,...i?{limit:Number(i)}:{}}))}else{if(!t)throw new Error(`${a} requires an id.`);if(a==="read")o=await d.get(t);else if(a==="status")o=await d.get(t);else if(a==="diagnostics"){let i=await d.get(t),c=n(r,"afterSequence");o=await d.diagnostics(t,{manifestHash:i.manifest.contentHash,...c?{afterSequence:Number(c)}:{},afterCallId:n(r,"afterCallId")||void 0})}else if(a==="cancel")o=await d.cancel(t);else if(a==="duplicate"){let i=n(r,"operationId");if(!i)throw new Error("Duplicate requires a stable --operation-id for the new Experiment.");o=await d.duplicate(t,i)}else if(a==="score"){let i=n(r,"inputFile");if(!i||(await j(i)).size>1048576)throw new Error("Score requires --input-file containing an exact execution reference, grader releases and explicit ceiling, within one MiB.");let c=X.parse(JSON.parse(await O(i,"utf8")));if(c.execution.id!==t)throw new Error("Scoring input belongs to a different execution.");o=await d.score(c)}else if(a==="passes")o=await d.scoringPasses(t,{afterId:n(r,"afterId")||void 0});else if(a==="pass")o=await d.scoringPass(t);else if(a==="cancel-pass")o=await d.cancelScoringPass(t);else if(a==="pass-result")o=await d.scoringResult(t);else if(a==="result")o=await d.result(t);else if(a==="case"){let i=n(r,"receiptId");if(!i)throw new Error("Case inspection requires --receipt-id from the retained Experiment.");let c=await d.get(t);o=await new L(w).case(t,i,{manifestHash:c.manifest.contentHash,afterId:n(r,"afterId")||void 0})}else if(a==="compare"){if(!s[2])throw new Error("Compare requires a baseline and candidate execution id.");o=await d.compare(t,s[2])}else throw new Error(`Unknown Experiment action: ${a}`)}console.log(JSON.stringify(o,null,2))}g(At,"runExperimentsCommand");export{At as runExperimentsCommand};
|
|
2
|
+
import{a as Z,b as v,d as re}from"./chunk-GMA365GI.js";import"./chunk-HYUTDZ3N.js";import{c as Q}from"./chunk-RFQD6B44.js";import{a as A,d as k}from"./chunk-6IKIGVJF.js";import{Ol as V,Pl as B,sm as K}from"./chunk-5AV2EWFX.js";import"./chunk-2EAZB2MW.js";import"./chunk-ZMRP2A7K.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import{Bd as ee,df as te,gf as ae}from"./chunk-2IECLXB2.js";import"./chunk-W45RKGM6.js";import"./chunk-73COPJ32.js";import"./chunk-UGDBMRCT.js";import"./chunk-2PVW2XFF.js";import"./chunk-64EDQ7UV.js";import{J as G}from"./chunk-DLOJG7LP.js";import"./chunk-ULTV6INR.js";import"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import"./chunk-GR4MJJCE.js";import{q as N}from"./chunk-GG6PM7TB.js";import"./chunk-2GEZ3ZY7.js";import"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import"./chunk-HIQPGYVH.js";import"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-KHDCMVEJ.js";import{n as X,o as Y}from"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import{d as W}from"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import{m as z,q as J}from"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import{Fb as M}from"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{a as H}from"./chunk-JF7WWLNW.js";import"./chunk-RRWL5BHZ.js";import{c as F,f as $}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as n,f as T}from"./chunk-3M53YXEI.js";import{b as U}from"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{h as _,n as D}from"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-NXN7GJOH.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as g}from"./chunk-FTQLQJQV.js";import{readFile as O,stat as j}from"node:fs/promises";var y=e.string().trim().min(1).max(500),ne=e.string().regex(/^[a-f0-9]{64}$/),me=e.object({schemaVersion:e.literal("openpond.experimentCaseInspection.v1"),teamId:y,executionId:y,manifestHash:ne,receiptId:y,taskId:y,seed:e.string().min(1),input:e.record(e.string(),e.unknown()).nullable(),output:e.unknown().nullable(),error:e.string().nullable(),events:e.array(e.record(e.string(),e.unknown())).max(25),nextEventCursor:y.nullable(),eventCount:e.number().int().nonnegative()}).strict(),pe=me.extend({contentHash:ne}).strict(),L=class{constructor(s){this.options=s;let a=new URL(s.baseUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash||!s.apiKey.trim()||!s.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=a.toString().replace(/\/+$/,"")}options;static{g(this,"OpenPondExperimentInspectionClient")}baseUrl;async case(s,a,t={}){let l=new URLSearchParams(t.afterId?{afterId:y.parse(t.afterId)}:{}),p=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/experiments/${encodeURIComponent(y.parse(s))}/cases/${encodeURIComponent(y.parse(a))}?${l}`,{signal:t.signal,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,Accept:"application/json"}}),w=await p.json();if(!p.ok)throw new Error(e.object({message:e.string()}).parse(w).message);let d=pe.parse(w),{contentHash:o,...i}=d;if(D(i)!==o||d.teamId!==this.options.teamId||d.executionId!==s||d.receiptId!==a||t.manifestHash&&d.manifestHash!==t.manifestHash||d.events.length>d.eventCount)throw new Error("Case inspection differs from its requested workspace, execution or retained content.");return d}};import{readFile as ye,stat as de}from"node:fs/promises";var R=e.string().trim().min(1).max(240),fe=e.object({location:e.literal("local").default("local"),jobId:R,modelRunId:R,modelId:R,modelVersionId:R.nullable(),adapterArtifactLineageId:R.nullable(),owner:e.object({teamId:R,actorId:R}).strict(),taskset:_,state:e.enum(["prepared","running","succeeded","failed","cancelled"]),executionState:e.enum(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),updatedAt:e.iso.datetime()}).strict(),he=e.object({location:e.literal("cloud"),jobId:R,owner:e.object({teamId:R,actorId:R}).strict(),apiOrigin:e.url(),job:G,updatedAt:e.iso.datetime()}).strict().refine(r=>r.jobId===r.job.id&&r.owner.teamId===r.job.teamId&&r.updatedAt===r.job.updatedAt,"Hosted training attachment must match its canonical job."),ie=e.union([fe,he]);var u=e.string().trim().min(1).max(240),I=e.string().regex(/^[a-f0-9]{64}$/),ge=e.object({kind:e.enum(["structure","graders"]),revision:e.number().int().positive(),workspaceHash:I,status:e.enum(["passed","failed","unavailable"]),checkedAt:e.iso.datetime(),checked:e.number().int().nonnegative(),total:e.number().int().nonnegative(),issues:e.array(e.object({code:e.string(),message:e.string(),taskId:u.optional(),graderId:u.optional()})).max(1e4),scopes:e.array(e.object({graderId:u,checked:e.number().int().nonnegative(),total:e.number().int().nonnegative(),status:e.enum(["passed","failed","unavailable"])}).strict()).max(1e3).optional()}).strict(),we=e.object({apiOrigin:e.url(),actorId:u,teamId:u,datasetId:u,remoteRevision:e.number().int().nonnegative(),acknowledgedHash:I.nullable(),remoteHash:I.nullable(),pendingLocalHash:I.nullable(),paused:e.boolean(),status:e.enum(["pending","syncing","synced","retry","conflict","paused"]),error:e.string().nullable(),operationId:u.nullable(),pendingWorkspace:N.nullable(),beginVersionOperationId:u.nullable().optional(),publicationIntent:e.object({operationId:u,expectedRevision:e.number().int().positive(),workspaceHash:I,packageHash:I,localHash:I}).strict().nullable().optional()}).strict(),Je=e.object({schemaVersion:e.literal("openpond.localDataset.v1"),ownerId:u,projectId:u.nullable(),workspace:N,checks:e.array(ge).max(2),packageHash:I.nullable(),sync:we.nullable()}).strict(),E=e.object({kind:e.enum(["dataset","grader","experiment"]),id:u,revision:e.number().int().positive(),name:e.string().max(500),state:e.string().max(100),datasetId:u.optional(),datasetRevision:e.number().int().positive().optional(),taskCount:e.number().int().nonnegative().optional(),graderCount:e.number().int().nonnegative().optional(),checkState:e.string().optional(),syncState:e.string().optional(),model:e.string().optional(),evaluationHash:I.optional(),graderId:u.optional(),graderType:e.string().optional(),description:e.string().optional(),location:e.enum(["local","cloud"]).optional(),scoreLabel:e.string().optional(),owner:e.object({teamId:u,actorId:u}).strict().optional(),contentHash:I.optional(),profileRef:Z.optional(),score:e.number().nullable().optional(),costUsd:e.number().nonnegative().nullable().optional(),evaluatedCount:e.number().int().nonnegative().optional(),failedCount:e.number().int().nonnegative().optional(),qualityFailureCount:e.number().int().nonnegative().optional(),executionFailureCount:e.number().int().nonnegative().optional(),ungradedCount:e.number().int().nonnegative().optional(),rows:e.array(e.object({id:u,label:e.string(),detail:e.string(),score:e.number().nullable().optional()})).max(10)}).strict(),oe=e.object({id:u,ordinal:e.number().int().positive(),name:e.string().trim().min(1).max(500),draft:te.optional(),storedDraft:ae.optional(),draftRevision:e.number().int().positive().optional(),creationHash:I.optional(),dataset:E.nullable(),evaluationModel:e.string().min(1).max(500).optional(),executionLocation:e.enum(["local","cloud"]).optional(),graders:e.array(E),selectedGraderId:u.nullable(),runs:e.array(E),selectedRunId:u.nullable(),training:e.array(ie).optional(),selectedTrainingKey:e.string().max(4e3).nullable().optional(),selectedTrainingJobId:u.nullable().optional(),results:e.array(ee).max(16).optional(),turnIds:e.array(u),operationId:u,createdAt:e.iso.datetime(),updatedAt:e.iso.datetime()}).strict(),be=oe.extend({ordinal:e.null()}),Ve=e.object({datasetFocus:be.optional(),scopes:e.array(oe),activeScopeId:u.nullable(),selectionVersion:e.number().int().nonnegative(),selectedAt:e.iso.datetime().nullable(),selectionOperations:e.record(e.string(),e.object({hash:I,version:e.number().int().nonnegative(),visualPublicationId:e.string().optional(),resource:E.optional()}).strict()).default({})}).strict();var Be=e.object({action:e.enum(["schema","list","read","create","save","file","validate","check_graders","check_sources","package","import","inspect_source","import_source","upload","sync","pause_sync","disconnect_sync","related_chats","list_graders","read_grader","save_grader","test_grader","publish"]),id:u.optional(),operationId:u.optional(),expectedRevision:e.number().int().nonnegative().optional(),payload:e.record(e.string(),e.unknown()).default({})}).strict(),Ke=e.object({contentHash:I,scope:e.string(),graders:e.unknown(),cases:e.array(e.object({id:u,taskId:u,seed:e.string(),status:e.string(),output:e.string().nullable(),error:e.string().nullable(),score:e.number().nullable()}).strict()).max(1e4)}).strict();function se(r){let s=r&&typeof r=="object"?r:{},a=[s.summary,...Array.isArray(s.summaries)?s.summaries:[]].flatMap(t=>{let l=E.safeParse(t);return l.success?[l.data]:[]});if(a.length){for(let t of a)console.log(`${t.name} \xB7 ${t.state}`),console.log(`${t.id} \xB7 ${t.location??"local"} \xB7 Dataset ${t.datasetId} version ${t.datasetRevision} \xB7 ${t.model}`),console.log(`${t.scoreLabel??"Mean task score"}: ${t.score==null?"Unavailable":(t.score*100).toFixed(1)+"%"} \xB7 Graded: ${t.evaluatedCount??0}/${t.taskCount??0} \xB7 Cost: ${t.costUsd==null?"Unavailable":"$"+t.costUsd.toFixed(4)}`),console.log(`Quality failures: ${t.qualityFailureCount??0} \xB7 Execution failures: ${t.executionFailureCount??0} \xB7 Ungraded: ${t.ungradedCount??t.taskCount??0}`),t.rows.length&&console.table(t.rows.map(l=>({Task:l.label,Outcome:l.detail,Score:l.score==null?"Unavailable":(l.score*100).toFixed(1)+"%"}))),console.log(`Results: openpond experiments result ${t.id} --local`);Array.isArray(s.items)&&console.table(s.items.flatMap(t=>{let l=v.safeParse(t);return l.success?[{ID:l.data.id,Name:l.data.configuration.request.name,Model:l.data.model.modelId,Status:l.data.status}]:[]}));for(let t of Array.isArray(s.errors)?s.errors:[])console.log(`Admission failed: ${t.modelId} \xB7 ${t.message}`);return}if(Array.isArray(s.models)){console.table(s.models);return}if(Array.isArray(s.items)){console.table(s.items.flatMap(t=>{let l=v.safeParse(t);return l.success?[{ID:l.data.id,Name:l.data.configuration.request.name,Model:l.data.model.modelId,Status:l.data.status}]:[]}));return}console.log(JSON.stringify(r,null,2))}g(se,"printLocalExperimentResult");import{readFile as xe,stat as Ie}from"node:fs/promises";var q={"profile-catalog":"/v1/profile/evaluations","prepare-profile":"/v1/profile/evaluations/prepare","run-profile":"/v1/profile/evaluations/run","inspect-profile":"/v1/profile/evaluations/discover"};async function ce(r,s){let a=s[0];if(!a||!Object.hasOwn(q,a))return!1;if(s.length!==1||r.team||r.revision||r.contentHash)throw new Error("Profile experiments accept one action and exact selection in --input-file; ownership is resolved by the running installation.");let t=new URL(n(r,"serverUrl")||process.env.OPENPOND_LOCAL_API_URL||A);if(t.protocol!=="http:"||!["localhost","127.0.0.1"].includes(t.hostname)||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new Error("Local Profile experiments require an HTTP loopback server origin.");let l=n(r,"inputFile"),p;if(l){let c=await Ie(l);if(!c.isFile()||c.size>1048576)throw new Error("Profile selection input must be a file within one MiB.");let b=JSON.parse(await xe(l,"utf8"));if(!b||typeof b!="object"||Array.isArray(b))throw new Error("Profile selection input must be an object.");p=b}else if(a!=="profile-catalog")throw new Error(`${a} requires --input-file with the exact Profile or run selection.`);let w=a==="profile-catalog"&&p?q["inspect-profile"]:q[a],o=await(await k(t.origin,{maximumResponseBytes:32*1024*1024,timeoutMs:a==="run-profile"||a==="prepare-profile"?12e5:6e4}))(new URL(w,t),{method:p?"POST":"GET",...p?{headers:{"content-type":"application/json"},body:JSON.stringify({...p,...["prepare-profile","run-profile","inspect-profile"].includes(a)&&process.env.OPENPOND_CHAT_INVOCATION?{invocationToken:process.env.OPENPOND_CHAT_INVOCATION}:{}})}:{}}),i=await o.json();if(!o.ok){let c=i&&typeof i=="object"&&"error"in i?i.error:void 0;throw new Error(typeof c=="string"?c:`Local Profile experiment request failed (${o.status}).`)}return console.log(JSON.stringify(i,null,2)),!0}g(ce,"runLocalProfileExperimentCommand");import{readFile as Se,stat as Re}from"node:fs/promises";async function le(r,s,a,t,l){let[p,w]=s;if(!["record-modification","modification","modifications"].includes(p??""))return!1;if(!l)throw new Error("Local observation operations require --team <workspace-id>.");let d=K({baseUrl:a,fetch:t}),o;if(p==="record-modification"&&s.length===1){let i=n(r,"inputFile"),c=i?await Re(i):null;if(!i||!c?.isFile()||c.size>V)throw new Error("Provide --input-file <command.json> containing a recording request of at most 8 MiB.");let b=B.parse(JSON.parse(await Se(i,"utf8")));if(b.teamId!==l)throw new Error("The recording request belongs to another workspace.");o=await d.recordModificationObservation(b)}else if(p==="modification"&&w&&s.length===2)o=await d.modificationRecording(w,{teamId:l});else if(p==="modifications"&&s.length===1){let i=n(r,"project"),c=n(r,"search"),b=n(r,"cursor"),m=n(r,"limit");o=await d.modificationRecordings({teamId:l,...i?{projectId:i}:{},...c?{search:c}:{},...b?{cursor:b}:{},...m?{limit:Number(m)}:{}})}else throw new Error("Use experiments record-modification --input-file <command.json>, modification <id>, or modifications, with --local --team <id>.");return console.log(JSON.stringify(o,null,2)),!0}g(le,"runLocalModificationRecordingCommand");async function ue(r,s){if(await ce(r,s))return;let[a,t,l]=s,p=n(r,"team"),w=n(r,"receiptId");if(a==="case"&&(!t||s.length!==2||!w))throw new Error("Usage: experiments case <run-id> --local --receipt-id <retained-receipt-id> [--after-sequence <n>] [--limit <1..500>] --json. A task id is not a receipt id; find receiptId in experiments result <run-id> --local --json (independent runs: evidence.cases[].receiptId).");if(r.revision!==void 0)throw new Error("A local Experiment is one immutable run; read it by id rather than a saved configuration revision.");if(a!=="read"&&r.contentHash!==void 0)throw new Error("An exact configuration hash requires the local read action.");if(!a||s.length>(a==="compare"?3:2))throw new Error("Local Experiments require an action; use --server-url for an existing local server.");let d=n(r,"serverUrl")||process.env.OPENPOND_LOCAL_API_URL||A,o=new URL(d);if(o.protocol!=="http:"||!["localhost","127.0.0.1"].includes(o.hostname)||o.username||o.password||o.search||o.hash||o.pathname!=="/")throw new Error("Local Experiments require an HTTP loopback server origin.");let i=await k(o.origin,{timeoutMs:["prepare-harness","run"].includes(a)?12e5:6e4});if(await le(r,s,o.origin,i,p))return;async function c(h,x){let f=await i(new URL(p?"/v1/local-experiments":"/v1/chat-experiments",o),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...p?{teamId:p}:{},...process.env.OPENPOND_CHAT_INVOCATION?{invocationToken:process.env.OPENPOND_CHAT_INVOCATION}:{},action:h,payload:x})}),S=await f.json();if(!f.ok)throw new Error(typeof S.error=="string"?S.error:`Local Experiment request failed (${f.status}).`);return S}g(c,"command");async function b(){let h=n(r,"inputFile");if(!h||!(await de(h)).isFile()||(await de(h)).size>67108864)throw new Error("Provide a bounded --input-file with exact local configuration and retained package bytes.");return JSON.parse(await ye(h,"utf8"))}g(b,"input");let m;if(!p){if(a==="models")m=await c("models",{});else if(a==="run"||a==="run-cloud")m=await c(a.replaceAll("-","_"),await b());else if(a==="list"){let h=n(r,"afterId"),x=n(r,"limit");m=await c("list",{...h?{afterId:h}:{},...x?{limit:Number(x)}:{}})}else if(a==="compare"&&t&&l)m=await c("compare",{baselineId:t,candidateId:l});else if(a==="case"&&t&&w){let h=n(r,"afterSequence"),x=n(r,"limit");m=await c("case",{id:t,receiptId:w,...h?{afterSequence:Number(h)}:{},...x?{limit:Number(x)}:{}})}else if(t&&["read","status","cancel","result"].includes(a))m=await c(a,{id:t});else throw new Error("Independent local Experiments support models/run/list/read/status/cancel/result/compare/case. Workspace operations require --team.");T(r.json)?console.log(JSON.stringify(m,null,2)):se(m);return}if(a==="prepare-harness"){if(t)throw new Error("Local Profile preparation accepts --input-file rather than an id.");m=await c("prepareHarness",await b())}else if(a==="run"){if(t)throw new Error("Local Run accepts reviewed configuration through --input-file rather than an id.");let h=await b();m=await c(h.package?"run":"runFromRelease",h)}else if(a==="list"){if(t)throw new Error("Local List does not accept an id.");let h=n(r,"status"),x=n(r,"limit"),f=n(r,"project"),S=n(r,"afterId"),C=n(r,"datasetHash"),P=n(r,"search");m=await c("list",{...h?{status:h}:{},...f?{projectId:f}:{},...C?{datasetHash:C}:{},...P?{search:P}:{},...S?{afterId:S}:{},...x?{limit:Number(x)}:{}})}else{if(!t)throw new Error(`${a} requires a local Experiment or scoring pass id.`);let h=n(r,"afterId"),x=n(r,"limit");if(a==="duplicate"){let f=n(r,"operationId");if(!f)throw new Error("Duplicate requires --operation-id for safe replay.");let S=v.parse(await c("read",{id:t})),C=J.parse({...S.configuration,operationId:f,request:{...S.configuration.request,operationId:f},sourceExperimentId:S.id});m=await c("runFromRelease",{configuration:C,expectedPackageHash:S.packageHash})}else if(a==="passes")m=await c("passes",{executionId:t,...h?{afterId:h}:{},...x?{limit:Number(x)}:{}});else if(a==="case"){let f=n(r,"afterSequence");m=await c("case",{id:t,receiptId:w,...f?{afterSequence:Number(f)}:{},...x?{limit:Number(x)}:{}})}else if(a==="score"){let f=await b();if(f.execution?.id!==t)throw new Error("Local scoring input belongs to a different retained execution.");m=await c("score",f)}else if(a==="compare"){if(!l)throw new Error("Local Compare requires baseline and candidate execution ids.");let f=re.parse(await c("compare",{baselineId:t,candidateId:l}));m={...f,comparison:M(f.baseline,f.candidate)}}else if(a==="read"){let f=n(r,"contentHash");m=await c("read",{id:t,...f?{configurationHash:f}:{}})}else if(["status","cancel","result","pass"].includes(a))m=await c(a,{id:t});else if(a==="cancel-pass")m=await c("cancel",{id:t});else if(a==="pass-result")m=await c("result",{id:t});else throw new Error(`Local Experiment action is unavailable: ${a}`)}console.log(JSON.stringify(m,null,2))}g(ue,"runLocalExperimentsCommand");async function At(r,s){if(s[0]==="signal-plan"||s[0]==="signal-report")return(await import("./experiments-signal-OIDQ5SNH.js")).runExperimentsSignalCommand(r,s);if(r.local===!0||r.local==="true")return ue(r,s);if(r.revision!==void 0||r.contentHash!==void 0)throw new Error("Experiments retain their immutable configuration on the run; definition revisions are not selectable.");let[a,t]=s,l=n(r,"team");if(!l||!a||s.length>(a==="compare"?3:2))throw new Error("usage: experiments <defaults|create-comparison|comparison-budget|prepare-harness|run|read|list|status|diagnostics|cancel|duplicate|score|passes|pass|cancel-pass|pass-result|result|compare|case> [id] [candidate-id] --team <id> [--input-file <path>] [--operation-id <id>]");let p=await W(),w={teamId:l,fetch:H,apiKey:await Q(p,$(p)),baseUrl:F(r)??p.apiBaseUrl??U},d=new Y(w),o;if(a==="defaults"){if(t)throw new Error("Defaults does not accept an id.");o=await d.defaults()}else if(a==="create-comparison"){let i=n(r,"inputFile");if(!i||t||(await j(i)).size>1048576)throw new Error("Create comparison requires a bounded input file with an id, fresh operationIds and optional maximumSpendUsd.");o=await d.createComparisonBudget(JSON.parse(await O(i,"utf8")))}else if(a==="comparison-budget"){if(!t)throw new Error("Comparison budget requires an id.");o=await d.comparisonBudget(t)}else if(a==="prepare-harness"){let i=n(r,"inputFile");if(!i||t||(await j(i)).size>1048576)throw new Error("Harness preparation requires a bounded --input-file with its released target, model and optional ceiling.");o=await d.prepareHarness(JSON.parse(await O(i,"utf8")))}else if(a==="run"){let i=n(r,"inputFile");if(!i||t)throw new Error("Run requires --input-file with the reviewed configuration and stable operationId.");if((await j(i)).size>1048576)throw new Error("Experiment input exceeds one MiB.");o=await d.run(JSON.parse(await O(i,"utf8")))}else if(a==="list"){if(t)throw new Error("List does not accept an Experiment id.");let i=n(r,"limit");o=await d.list(z.parse({projectId:n(r,"project")||void 0,datasetHash:n(r,"datasetHash")||void 0,search:n(r,"search")||void 0,status:n(r,"status")||void 0,afterId:n(r,"afterId")||void 0,...i?{limit:Number(i)}:{}}))}else{if(!t)throw new Error(`${a} requires an id.`);if(a==="read")o=await d.get(t);else if(a==="status")o=await d.get(t);else if(a==="diagnostics"){let i=await d.get(t),c=n(r,"afterSequence");o=await d.diagnostics(t,{manifestHash:i.manifest.contentHash,...c?{afterSequence:Number(c)}:{},afterCallId:n(r,"afterCallId")||void 0})}else if(a==="cancel")o=await d.cancel(t);else if(a==="duplicate"){let i=n(r,"operationId");if(!i)throw new Error("Duplicate requires a stable --operation-id for the new Experiment.");o=await d.duplicate(t,i)}else if(a==="score"){let i=n(r,"inputFile");if(!i||(await j(i)).size>1048576)throw new Error("Score requires --input-file containing an exact execution reference, grader releases and explicit ceiling, within one MiB.");let c=X.parse(JSON.parse(await O(i,"utf8")));if(c.execution.id!==t)throw new Error("Scoring input belongs to a different execution.");o=await d.score(c)}else if(a==="passes")o=await d.scoringPasses(t,{afterId:n(r,"afterId")||void 0});else if(a==="pass")o=await d.scoringPass(t);else if(a==="cancel-pass")o=await d.cancelScoringPass(t);else if(a==="pass-result")o=await d.scoringResult(t);else if(a==="result")o=await d.result(t);else if(a==="case"){let i=n(r,"receiptId");if(!i)throw new Error("Case inspection requires --receipt-id from the retained Experiment.");let c=await d.get(t);o=await new L(w).case(t,i,{manifestHash:c.manifest.contentHash,afterId:n(r,"afterId")||void 0})}else if(a==="compare"){if(!s[2])throw new Error("Compare requires a baseline and candidate execution id.");o=await d.compare(t,s[2])}else throw new Error(`Unknown Experiment action: ${a}`)}console.log(JSON.stringify(o,null,2))}g(At,"runExperimentsCommand");export{At as runExperimentsCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{b as N,c as A}from"./chunk-GMA365GI.js";import"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import"./chunk-FVMTQSVW.js";import"./chunk-ZMRP2A7K.js";import"./chunk-P7RLDDPN.js";import"./chunk-OFC5N6R3.js";import"./chunk-XRKFTPHD.js";import"./chunk-W45RKGM6.js";import"./chunk-73COPJ32.js";import"./chunk-UGDBMRCT.js";import"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import"./chunk-GR4MJJCE.js";import"./chunk-GG6PM7TB.js";import"./chunk-2GEZ3ZY7.js";import"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import"./chunk-HIQPGYVH.js";import"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import{O}from"./chunk-6LAGMWJE.js";import{p as F}from"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import{Ja as z,da as M}from"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as C}from"./chunk-3M53YXEI.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{n as i,o as _}from"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as c}from"./chunk-X2J2P5ZT.js";import{a as x}from"./chunk-FTQLQJQV.js";import{readFile as $,stat as G}from"node:fs/promises";import{dirname as L,resolve as b}from"node:path";var H=c.string().regex(/^[a-f0-9]{64}$/),P=c.object({groupSize:c.number().int().min(2).max(100),minimumFamilies:c.number().int().min(2).max(1e3),minimumInformativeFamilies:c.number().int().min(2).max(1e3),minimumSpread:c.number().positive().max(1),minimumScoredFraction:c.number().positive().max(1)}).strict().refine(s=>s.minimumInformativeFamilies<=s.minimumFamilies,"Informative family requirement cannot exceed the minimum family population."),D=c.object({schemaVersion:c.literal("openpond.experimentSignalPlan.v1"),createdAt:c.iso.datetime(),preparation:F,packageHash:H,graders:c.array(M).min(1).max(100),tasks:c.array(c.object({id:c.string(),family:c.string(),taskHash:H,inputHash:H,contextHash:H}).strict()).min(1).max(1e4),thresholds:P}).strict(),j=D.extend({contentHash:H}).strict();function R(s){let n=j.parse(s),{contentHash:a,...p}=n;if(i(p)!==a)throw new Error("Signal plan content changed.");let{request:t,manifest:r,graders:m}=n.preparation;_(r,"Signal preparation manifest");let o=t.policy;if(o.kind!=="hosted_harness"||r.execution.kind!=="harness"||r.policy.kind!=="model"||r.runtimeTarget.placement!=="local"||r.gradingRole!=="evaluation"||i(r.profileEvaluation??null)!==i(o.source)||i(r.execution.harnessRelease)!==i(o.source.harnessRelease)||r.packageHash!==o.packageHash||r.policy.configurationHash!==o.modelConfigurationHash||r.policy.model.provider!=="openpond"||r.policy.model.model!==o.modelId||r.policy.model.revision!==null||r.policy.model.artifactHash!==(o.candidate?.contentHash??null)||r.policy.model.tokenizerRevision!==null||r.policy.model.chatTemplateHash!==null||r.tasksetRelease.id!==t.taskset.id||r.tasksetRelease.contentHash!==t.taskset.contentHash||i(r.population)!==i(t.population)||r.limits.maximumSpendUsd!==n.preparation.maximumCostUsd||r.metadata.profileRepositoryId!==void 0&&r.metadata.profileRepositoryId!==o.profileRepositoryId)throw new Error("Signal preparation differs from its native local source, package, model, budget or population.");for(let d of r.population){let g=o.source.externalDatasetBinding?[r.id,d.taskId,d.seed,d.fixtureId]:[r.id,d.taskId,d.seed];if(d.receiptId!==`evaluation-${i(g).slice(0,32)}`)throw new Error("Signal preparation receipt identity changed.")}if(t.policy.kind!=="hosted_harness"||t.policy.localRuntime||t.policy.packageHash!==n.packageHash)throw new Error("Signal plan requires the exact hosted-chat Harness package.");if(new Set(n.tasks.map(d=>d.id)).size!==n.tasks.length||new Set(m.map(d=>d.id)).size!==m.length||n.graders.length!==m.length)throw new Error("Signal plan contains duplicate or missing tasks/graders.");for(let[d,g]of n.graders.entries()){let f=m[d];if(f.id!==g.id||f.version!==g.version||f.contentHash!==i(g)||g.hardGate||!g.rewardEligible||g.weight<=0||g.taskIds||f.mappings?.length)throw new Error("Signal requires exact positive-weight reward graders, no hard gates, field mappings or task-specific grader subsets.")}let S=new Map;for(let d of t.population)S.set(d.taskId,(S.get(d.taskId)??0)+1);if(S.size!==n.tasks.length||n.tasks.some(d=>S.get(d.id)!==n.thresholds.groupSize))throw new Error("Every planned prompt must have exactly groupSize distinct seeded attempts.");if(new Set(n.tasks.map(d=>d.family)).size<n.thresholds.minimumFamilies)throw new Error("Signal population has too few independent source families.");return n}x(R,"verifySignalPlan");function T(s){let n=O(s.package),a=F.parse(s.preparation),p=new Set(a.request.population.map(o=>o.taskId)),t=n.taskset.tasks.filter(o=>p.has(o.id));if(t.length!==p.size||t.some(o=>o.split!=="train"))throw new Error("Signal probes require existing training tasks; validation/test/frozen holdouts cannot be reused.");if(a.request.taskset.id!==n.taskset.id||a.request.taskset.contentHash!==n.taskset.contentHash)throw new Error("Prepared taskset differs from the supplied package.");let r=a.graders.map(o=>{let S=n.taskset.graders.find(d=>d.id===o.id&&i(d)===o.contentHash);if(!S)throw new Error(`Selected grader is absent from the exact package: ${o.id}`);return S}),m=D.parse({schemaVersion:"openpond.experimentSignalPlan.v1",createdAt:s.createdAt??new Date().toISOString(),preparation:a,packageHash:n.contentHash,graders:r,tasks:t.map(o=>({id:o.id,family:o.clusterKey,taskHash:i(o),inputHash:i(o.input),contextHash:i(o.policyVisibleContext)})),thresholds:s.thresholds});return R({...m,contentHash:i(m)})}x(T,"createSignalPlan");function U(s){if(!s.length)return{count:0,min:null,max:null,mean:null,standardDeviation:null,spread:null};let n=s.reduce((a,p)=>a+p,0)/s.length;return{count:s.length,min:Math.min(...s),max:Math.max(...s),mean:n,standardDeviation:Math.sqrt(s.reduce((a,p)=>a+(p-n)**2,0)/s.length),spread:Math.max(...s)-Math.min(...s)}}x(U,"scoreDistribution");function V(s,n){let a=R(s),p=A.parse(n),t=N.parse(p.execution);if(i({execution:p.execution,cases:p.cases})!==p.contentHash)throw new Error("Signal result content changed.");if(t.packageHash!==a.packageHash||i(t.configuration.request)!==i(a.preparation.request)||i(t.graders)!==i(a.preparation.graders)||t.maximumCostUsd!==a.preparation.maximumCostUsd)throw new Error("Signal result differs from the frozen request, package, graders or budget.");if(Date.parse(t.createdAt)<Date.parse(a.createdAt))throw new Error("Signal plan must precede the execution.");let r=a.preparation.request.policy;if(r.kind!=="hosted_harness"||t.model.providerId!=="openpond"||t.model.modelId!==r.modelId||t.model.maxOutputTokens!==(r.maxOutputTokens??4096)||t.model.temperature!==(r.temperature??0)||t.model.topP!==(r.topP??1))throw new Error("Signal execution model or sampling differs from the frozen policy.");for(let e of["pending","running","completed","failed","cancelled","unknown"])if(t.counts[e]!==p.cases.filter(w=>w.status===e).length)throw new Error("Signal execution counts differ from its cases.");let m=new Map(a.preparation.request.population.map(e=>[e.receiptId,e]));if(p.cases.length!==m.size||new Set(p.cases.map(e=>e.receiptId)).size!==m.size)throw new Error("Signal result omits or duplicates planned attempts.");let o=new Map(a.tasks.map(e=>[e.id,e])),S=i(a.preparation.graders);for(let e of p.cases){let w=m.get(e.receiptId),k=o.get(e.taskId);if(!w||!k||w.taskId!==e.taskId||w.seed!==e.seed||i(e.input)!==k.inputHash||i(e.policyVisibleContext)!==k.contextHash)throw new Error("Signal case differs from its frozen prompt, context or seed.");if(e.status==="completed"&&(!e.profileNative||e.output===null||e.profileNative.modelConfigurationHash!==t.model.configurationHash||i(e.profileNative.source)!==i(r.source)||e.profileNative.outputHash!==i(e.output)))throw new Error("Signal case lacks matching native source, model or output evidence.");if(!e.grade)continue;if(e.grade.selectionHash!==S)throw new Error("Signal grade uses different selected graders.");if(e.grade.grades.some(u=>u.taskHash!==k.taskHash)||new Set(e.grade.grades.map(u=>u.evidenceHash)).size!==1)throw new Error("Signal criterion belongs to another prompt or inconsistent attempt evidence.");let y=e.grade.grades.flatMap(u=>u.components),E=z({graders:a.graders,components:y});for(let u of["score","passed","rewardEligible","gradingStatus","failureClass"])if(e.grade[u]!==E[u])throw new Error("Signal score differs from retained components and frozen weights.");for(let u of e.grade.grades){let l=a.graders.find(h=>h.id===u.components[0]?.graderId);if(u.graderSetHash!==i([l]))throw new Error("Signal criterion specification changed.");let I=z({graders:[l],components:u.components});for(let h of["score","passed","rewardEligible","gradingStatus","failureClass"])if(u[h]!==I[h])throw new Error("Signal criterion summary differs from its evidence.")}}let d=a.tasks.map(e=>{let w=p.cases.filter(l=>l.taskId===e.id),k=w.filter(l=>l.status==="completed"&&l.grade?.gradingStatus==="scored"&&l.grade.rewardEligible&&l.grade.score!==null),y=U(k.map(l=>l.grade.score)),E=k.length/w.length,u=a.graders.map(l=>({id:l.id,weight:l.weight,distribution:U(k.flatMap(I=>I.grade.grades.flatMap(h=>h.components).filter(h=>h.graderId===l.id&&h.rewardEligible&&h.score!==null).map(h=>h.score)))}));return{taskId:e.id,family:e.family,attempts:w.length,eligible:k.length,scoredFraction:E,combined:y,components:u,constant:y.spread!==null&&y.spread<=Number.EPSILON,uniqueOutputs:new Set(w.filter(l=>l.output!==null).map(l=>i(l.output))).size,informative:E>=a.thresholds.minimumScoredFraction&&(y.spread??0)>=a.thresholds.minimumSpread,outcomes:w.map(l=>({receiptId:l.receiptId,seed:l.seed,status:l.status,gradingStatus:l.grade?.gradingStatus??null,failureClass:l.grade?.failureClass??null,rewardEligible:l.grade?.rewardEligible??!1,score:l.grade?.score??null}))}}),g=[...new Set(d.filter(e=>e.informative).map(e=>e.family))],f=[];(t.status!=="completed"||!t.cleanupComplete)&&f.push("execution_or_local_cleanup_incomplete"),(t.usage.uncertainRequests||t.usage.costUsd===null||t.usage.heldUsd)&&f.push("cost_or_reservations_unsettled"),d.some(e=>e.scoredFraction<a.thresholds.minimumScoredFraction)&&f.push("insufficient_scored_coverage"),g.length<a.thresholds.minimumInformativeFamilies&&f.push("insufficient_within_prompt_signal");let q={schemaVersion:"openpond.experimentSignalReport.v1",planHash:a.contentHash,resultHash:p.contentHash,executionId:t.id,model:t.model,thresholds:a.thresholds,groups:d,informativeFamilies:g,usage:t.usage,cleanupComplete:t.cleanupComplete,blockers:f,signalObserved:f.length===0,trainingAuthorized:!1,runtimeParityVerified:!1,limitations:["Offline hashes bind supplied evidence; they do not authenticate it or prove source-family independence. Full grade evidence hashes require the retained trace/artifacts to independently reconstruct.","Local signal does not prove learner identity, GPU runtime/tokenizer parity, no-update behavior or provider deletion.","Review rates, private gold, fixture calibration, family exposure and the unchanged-parent noise control before training."]};return{...q,contentHash:i(q)}}x(V,"createSignalReport");async function v(s,n=64*1024*1024){if((await G(s)).size>n)throw new Error(`Signal input exceeds ${n} bytes: ${s}`);return JSON.parse(await $(s,"utf8"))}x(v,"readJson");async function pe(s,n){let a=C(s,"inputFile");if(!a||n.length!==1)throw new Error("usage: experiments <signal-plan|signal-report> --input-file <path>");let p=await v(a,1048576),t=L(b(a)),r;if(n[0]==="signal-plan"){let m=c.object({packageFile:c.string().min(1),preparationFile:c.string().min(1),thresholds:P}).strict().parse(p);r=T({package:await v(b(t,m.packageFile)),preparation:await v(b(t,m.preparationFile)),thresholds:m.thresholds})}else{let m=c.object({planFile:c.string().min(1),resultFile:c.string().min(1)}).strict().parse(p);r=V(await v(b(t,m.planFile)),await v(b(t,m.resultFile)))}console.log(JSON.stringify(r,null,2))}x(pe,"runExperimentsSignalCommand");export{pe as runExperimentsSignalCommand};
|
|
2
|
+
import{b as N,c as A}from"./chunk-GMA365GI.js";import"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import"./chunk-FVMTQSVW.js";import"./chunk-ZMRP2A7K.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import"./chunk-W45RKGM6.js";import"./chunk-73COPJ32.js";import"./chunk-UGDBMRCT.js";import"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import"./chunk-GR4MJJCE.js";import"./chunk-GG6PM7TB.js";import"./chunk-2GEZ3ZY7.js";import"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import"./chunk-HIQPGYVH.js";import"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import{O}from"./chunk-6LAGMWJE.js";import{p as F}from"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import{Ja as z,da as M}from"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as C}from"./chunk-3M53YXEI.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{n as i,o as _}from"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as c}from"./chunk-X2J2P5ZT.js";import{a as x}from"./chunk-FTQLQJQV.js";import{readFile as $,stat as G}from"node:fs/promises";import{dirname as L,resolve as b}from"node:path";var H=c.string().regex(/^[a-f0-9]{64}$/),P=c.object({groupSize:c.number().int().min(2).max(100),minimumFamilies:c.number().int().min(2).max(1e3),minimumInformativeFamilies:c.number().int().min(2).max(1e3),minimumSpread:c.number().positive().max(1),minimumScoredFraction:c.number().positive().max(1)}).strict().refine(s=>s.minimumInformativeFamilies<=s.minimumFamilies,"Informative family requirement cannot exceed the minimum family population."),D=c.object({schemaVersion:c.literal("openpond.experimentSignalPlan.v1"),createdAt:c.iso.datetime(),preparation:F,packageHash:H,graders:c.array(M).min(1).max(100),tasks:c.array(c.object({id:c.string(),family:c.string(),taskHash:H,inputHash:H,contextHash:H}).strict()).min(1).max(1e4),thresholds:P}).strict(),j=D.extend({contentHash:H}).strict();function R(s){let n=j.parse(s),{contentHash:a,...p}=n;if(i(p)!==a)throw new Error("Signal plan content changed.");let{request:t,manifest:r,graders:m}=n.preparation;_(r,"Signal preparation manifest");let o=t.policy;if(o.kind!=="hosted_harness"||r.execution.kind!=="harness"||r.policy.kind!=="model"||r.runtimeTarget.placement!=="local"||r.gradingRole!=="evaluation"||i(r.profileEvaluation??null)!==i(o.source)||i(r.execution.harnessRelease)!==i(o.source.harnessRelease)||r.packageHash!==o.packageHash||r.policy.configurationHash!==o.modelConfigurationHash||r.policy.model.provider!=="openpond"||r.policy.model.model!==o.modelId||r.policy.model.revision!==null||r.policy.model.artifactHash!==(o.candidate?.contentHash??null)||r.policy.model.tokenizerRevision!==null||r.policy.model.chatTemplateHash!==null||r.tasksetRelease.id!==t.taskset.id||r.tasksetRelease.contentHash!==t.taskset.contentHash||i(r.population)!==i(t.population)||r.limits.maximumSpendUsd!==n.preparation.maximumCostUsd||r.metadata.profileRepositoryId!==void 0&&r.metadata.profileRepositoryId!==o.profileRepositoryId)throw new Error("Signal preparation differs from its native local source, package, model, budget or population.");for(let d of r.population){let g=o.source.externalDatasetBinding?[r.id,d.taskId,d.seed,d.fixtureId]:[r.id,d.taskId,d.seed];if(d.receiptId!==`evaluation-${i(g).slice(0,32)}`)throw new Error("Signal preparation receipt identity changed.")}if(t.policy.kind!=="hosted_harness"||t.policy.localRuntime||t.policy.packageHash!==n.packageHash)throw new Error("Signal plan requires the exact hosted-chat Harness package.");if(new Set(n.tasks.map(d=>d.id)).size!==n.tasks.length||new Set(m.map(d=>d.id)).size!==m.length||n.graders.length!==m.length)throw new Error("Signal plan contains duplicate or missing tasks/graders.");for(let[d,g]of n.graders.entries()){let f=m[d];if(f.id!==g.id||f.version!==g.version||f.contentHash!==i(g)||g.hardGate||!g.rewardEligible||g.weight<=0||g.taskIds||f.mappings?.length)throw new Error("Signal requires exact positive-weight reward graders, no hard gates, field mappings or task-specific grader subsets.")}let S=new Map;for(let d of t.population)S.set(d.taskId,(S.get(d.taskId)??0)+1);if(S.size!==n.tasks.length||n.tasks.some(d=>S.get(d.id)!==n.thresholds.groupSize))throw new Error("Every planned prompt must have exactly groupSize distinct seeded attempts.");if(new Set(n.tasks.map(d=>d.family)).size<n.thresholds.minimumFamilies)throw new Error("Signal population has too few independent source families.");return n}x(R,"verifySignalPlan");function T(s){let n=O(s.package),a=F.parse(s.preparation),p=new Set(a.request.population.map(o=>o.taskId)),t=n.taskset.tasks.filter(o=>p.has(o.id));if(t.length!==p.size||t.some(o=>o.split!=="train"))throw new Error("Signal probes require existing training tasks; validation/test/frozen holdouts cannot be reused.");if(a.request.taskset.id!==n.taskset.id||a.request.taskset.contentHash!==n.taskset.contentHash)throw new Error("Prepared taskset differs from the supplied package.");let r=a.graders.map(o=>{let S=n.taskset.graders.find(d=>d.id===o.id&&i(d)===o.contentHash);if(!S)throw new Error(`Selected grader is absent from the exact package: ${o.id}`);return S}),m=D.parse({schemaVersion:"openpond.experimentSignalPlan.v1",createdAt:s.createdAt??new Date().toISOString(),preparation:a,packageHash:n.contentHash,graders:r,tasks:t.map(o=>({id:o.id,family:o.clusterKey,taskHash:i(o),inputHash:i(o.input),contextHash:i(o.policyVisibleContext)})),thresholds:s.thresholds});return R({...m,contentHash:i(m)})}x(T,"createSignalPlan");function U(s){if(!s.length)return{count:0,min:null,max:null,mean:null,standardDeviation:null,spread:null};let n=s.reduce((a,p)=>a+p,0)/s.length;return{count:s.length,min:Math.min(...s),max:Math.max(...s),mean:n,standardDeviation:Math.sqrt(s.reduce((a,p)=>a+(p-n)**2,0)/s.length),spread:Math.max(...s)-Math.min(...s)}}x(U,"scoreDistribution");function V(s,n){let a=R(s),p=A.parse(n),t=N.parse(p.execution);if(i({execution:p.execution,cases:p.cases})!==p.contentHash)throw new Error("Signal result content changed.");if(t.packageHash!==a.packageHash||i(t.configuration.request)!==i(a.preparation.request)||i(t.graders)!==i(a.preparation.graders)||t.maximumCostUsd!==a.preparation.maximumCostUsd)throw new Error("Signal result differs from the frozen request, package, graders or budget.");if(Date.parse(t.createdAt)<Date.parse(a.createdAt))throw new Error("Signal plan must precede the execution.");let r=a.preparation.request.policy;if(r.kind!=="hosted_harness"||t.model.providerId!=="openpond"||t.model.modelId!==r.modelId||t.model.maxOutputTokens!==(r.maxOutputTokens??4096)||t.model.temperature!==(r.temperature??0)||t.model.topP!==(r.topP??1))throw new Error("Signal execution model or sampling differs from the frozen policy.");for(let e of["pending","running","completed","failed","cancelled","unknown"])if(t.counts[e]!==p.cases.filter(w=>w.status===e).length)throw new Error("Signal execution counts differ from its cases.");let m=new Map(a.preparation.request.population.map(e=>[e.receiptId,e]));if(p.cases.length!==m.size||new Set(p.cases.map(e=>e.receiptId)).size!==m.size)throw new Error("Signal result omits or duplicates planned attempts.");let o=new Map(a.tasks.map(e=>[e.id,e])),S=i(a.preparation.graders);for(let e of p.cases){let w=m.get(e.receiptId),k=o.get(e.taskId);if(!w||!k||w.taskId!==e.taskId||w.seed!==e.seed||i(e.input)!==k.inputHash||i(e.policyVisibleContext)!==k.contextHash)throw new Error("Signal case differs from its frozen prompt, context or seed.");if(e.status==="completed"&&(!e.profileNative||e.output===null||e.profileNative.modelConfigurationHash!==t.model.configurationHash||i(e.profileNative.source)!==i(r.source)||e.profileNative.outputHash!==i(e.output)))throw new Error("Signal case lacks matching native source, model or output evidence.");if(!e.grade)continue;if(e.grade.selectionHash!==S)throw new Error("Signal grade uses different selected graders.");if(e.grade.grades.some(u=>u.taskHash!==k.taskHash)||new Set(e.grade.grades.map(u=>u.evidenceHash)).size!==1)throw new Error("Signal criterion belongs to another prompt or inconsistent attempt evidence.");let y=e.grade.grades.flatMap(u=>u.components),E=z({graders:a.graders,components:y});for(let u of["score","passed","rewardEligible","gradingStatus","failureClass"])if(e.grade[u]!==E[u])throw new Error("Signal score differs from retained components and frozen weights.");for(let u of e.grade.grades){let l=a.graders.find(h=>h.id===u.components[0]?.graderId);if(u.graderSetHash!==i([l]))throw new Error("Signal criterion specification changed.");let I=z({graders:[l],components:u.components});for(let h of["score","passed","rewardEligible","gradingStatus","failureClass"])if(u[h]!==I[h])throw new Error("Signal criterion summary differs from its evidence.")}}let d=a.tasks.map(e=>{let w=p.cases.filter(l=>l.taskId===e.id),k=w.filter(l=>l.status==="completed"&&l.grade?.gradingStatus==="scored"&&l.grade.rewardEligible&&l.grade.score!==null),y=U(k.map(l=>l.grade.score)),E=k.length/w.length,u=a.graders.map(l=>({id:l.id,weight:l.weight,distribution:U(k.flatMap(I=>I.grade.grades.flatMap(h=>h.components).filter(h=>h.graderId===l.id&&h.rewardEligible&&h.score!==null).map(h=>h.score)))}));return{taskId:e.id,family:e.family,attempts:w.length,eligible:k.length,scoredFraction:E,combined:y,components:u,constant:y.spread!==null&&y.spread<=Number.EPSILON,uniqueOutputs:new Set(w.filter(l=>l.output!==null).map(l=>i(l.output))).size,informative:E>=a.thresholds.minimumScoredFraction&&(y.spread??0)>=a.thresholds.minimumSpread,outcomes:w.map(l=>({receiptId:l.receiptId,seed:l.seed,status:l.status,gradingStatus:l.grade?.gradingStatus??null,failureClass:l.grade?.failureClass??null,rewardEligible:l.grade?.rewardEligible??!1,score:l.grade?.score??null}))}}),g=[...new Set(d.filter(e=>e.informative).map(e=>e.family))],f=[];(t.status!=="completed"||!t.cleanupComplete)&&f.push("execution_or_local_cleanup_incomplete"),(t.usage.uncertainRequests||t.usage.costUsd===null||t.usage.heldUsd)&&f.push("cost_or_reservations_unsettled"),d.some(e=>e.scoredFraction<a.thresholds.minimumScoredFraction)&&f.push("insufficient_scored_coverage"),g.length<a.thresholds.minimumInformativeFamilies&&f.push("insufficient_within_prompt_signal");let q={schemaVersion:"openpond.experimentSignalReport.v1",planHash:a.contentHash,resultHash:p.contentHash,executionId:t.id,model:t.model,thresholds:a.thresholds,groups:d,informativeFamilies:g,usage:t.usage,cleanupComplete:t.cleanupComplete,blockers:f,signalObserved:f.length===0,trainingAuthorized:!1,runtimeParityVerified:!1,limitations:["Offline hashes bind supplied evidence; they do not authenticate it or prove source-family independence. Full grade evidence hashes require the retained trace/artifacts to independently reconstruct.","Local signal does not prove learner identity, GPU runtime/tokenizer parity, no-update behavior or provider deletion.","Review rates, private gold, fixture calibration, family exposure and the unchanged-parent noise control before training."]};return{...q,contentHash:i(q)}}x(V,"createSignalReport");async function v(s,n=64*1024*1024){if((await G(s)).size>n)throw new Error(`Signal input exceeds ${n} bytes: ${s}`);return JSON.parse(await $(s,"utf8"))}x(v,"readJson");async function pe(s,n){let a=C(s,"inputFile");if(!a||n.length!==1)throw new Error("usage: experiments <signal-plan|signal-report> --input-file <path>");let p=await v(a,1048576),t=L(b(a)),r;if(n[0]==="signal-plan"){let m=c.object({packageFile:c.string().min(1),preparationFile:c.string().min(1),thresholds:P}).strict().parse(p);r=T({package:await v(b(t,m.packageFile)),preparation:await v(b(t,m.preparationFile)),thresholds:m.thresholds})}else{let m=c.object({planFile:c.string().min(1),resultFile:c.string().min(1)}).strict().parse(p);r=V(await v(b(t,m.planFile)),await v(b(t,m.resultFile)))}console.log(JSON.stringify(r,null,2))}x(pe,"runExperimentsSignalCommand");export{pe as runExperimentsSignalCommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as r,c as i,h as p}from"./chunk-
|
|
2
|
+
import{a as r,c as i,h as p}from"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import"./chunk-3M53YXEI.js";import{a as t}from"./chunk-FTQLQJQV.js";function d(){console.log(m())}t(d,"printHelp");function m(){let n=["OpenPond CLI","","Usage:"," openpond [--no-open] [--hostname HOST] [--port PORT]"," openpond <command> [options] [-- passthrough...]"," openpond --version","","Commands:"];for(let o of i()){let s=o.aliases?.length?` (aliases: ${o.aliases.join(", ")})`:"";n.push(` ${o.usage}${s}`);for(let e of o.usages??[])n.push(` ${e}`)}n.push("","Global options:");for(let[o,s]of Object.entries(r).sort(([e],[a])=>e.localeCompare(a))){let e=o.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);n.push(s==="boolean"?` --${e}`:` --${e} <${s}>`)}return n.push("","Run `openpond <command> --help` for the selected command schema.","Arguments after `--` are passed through without option parsing."),n.join(`
|
|
3
3
|
`)}t(m,"formatCliHelp");function l(){return["# OpenPond CLI command reference","","<!-- Generated by `pnpm --dir apps/cli docs:commands`; do not edit by hand. -->","","Parsing, aliases, command help, and this reference use the same authoritative registry.","",...i().map(o=>`## ${o.name}
|
|
4
4
|
|
|
5
5
|
\`\`\`text
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import"./chunk-HYUTDZ3N.js";import{c as S}from"./chunk-RFQD6B44.js";import{a as x,d as y}from"./chunk-6IKIGVJF.js";import"./chunk-
|
|
2
|
+
import"./chunk-HYUTDZ3N.js";import{c as S}from"./chunk-RFQD6B44.js";import{a as x,d as y}from"./chunk-6IKIGVJF.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import"./chunk-KHDCMVEJ.js";import{p as q}from"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import{d as E}from"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import{a as R}from"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import{K as g,L as b,U as p,V as I}from"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{a as f}from"./chunk-JF7WWLNW.js";import{c as h,f as v}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as n}from"./chunk-3M53YXEI.js";import{b as w}from"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{n as u}from"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import"./chunk-X2J2P5ZT.js";import{a as m}from"./chunk-FTQLQJQV.js";import{readFile as L,stat as U}from"node:fs/promises";async function J(r,l){let[i,a]=l,o=n(r,"team"),H=r.local===!0||r.local==="true";if(!o||!i||l.length>2)throw new Error("usage: human-review <read|inbox|inspect|results|request> [id] --team <id> [--input-file <path>] [--local --server-url <loopback-origin>]");let t;if(i==="request"){let e=n(r,"inputFile");if(a||!e||(await U(e)).size>1048576)throw new Error("Request requires a bounded --input-file with exact scoped pins, revision and stable operationId for mutations.");if(t=p.parse(JSON.parse(await L(e,"utf8"))),t.scope!==o)throw new Error("Input belongs to another workspace.")}else if(i==="inbox"){if(a)throw new Error("Inbox does not accept an assignment id.");t=p.parse({endpoint:"inbox",scope:o,view:n(r,"view")||"mine",status:n(r,"status")||"active",limit:Number(n(r,"limit")||100),...n(r,"project")?{projectId:n(r,"project")}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}})}else{if(!a)throw new Error(`${i} requires an exact assignment or execution id.`);t=p.parse(i==="read"?{endpoint:"get",scope:o,id:a,...n(r,"revision")?{revision:Number(n(r,"revision"))}:{}}:i==="inspect"?{endpoint:"inspect",scope:o,id:a,...n(r,"slot")?{slot:Number(n(r,"slot"))}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}}:i==="results"?{endpoint:"results",scope:o,executionId:a}:{endpoint:i,scope:o,id:a})}let s;if(H){let e=new URL(n(r,"serverUrl")||x);if(e.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw new Error("Local Human review requires an HTTP loopback server origin.");let c=await y(e.origin),d=await c(new URL("/v1/human-review?location=local",e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),redirect:"error",signal:AbortSignal.timeout(3e4)}),A=await N(d);if(s=JSON.parse(A),!d.ok)throw new Error(typeof s.error=="string"?s.error:`Local Human request failed (${d.status}).`)}else{let e=await E();s=await new q({scope:o,fetch:f,apiKey:await S(e,v(e)),baseUrl:h(r)??e.apiBaseUrl??w}).request(t,AbortSignal.timeout(3e4))}if(t.endpoint==="get"||t.endpoint==="command"){let e=g.parse(s),c=t.endpoint==="get"?t.id:t.command.id;if(e.id!==c||e.scope!==o)throw new Error("Review response differs from the requested identity.")}if(t.endpoint==="inbox"&&b.parse(s).items.some(c=>c.scope!==o||t.projectId&&c.projectId!==t.projectId))throw new Error("Inbox response differs from the requested scope.");if(t.endpoint==="inspect"&&I.parse(s).some(e=>e.reviewId!==t.id))throw new Error("Inspection response differs from the selected assignment.");if(t.endpoint==="results"){let e=R.parse(s),{contentHash:c,...d}=e;if(e.executionId!==t.executionId||u(d)!==c||t.selection!==void 0&&u(e.selection)!==u(t.selection))throw new Error("Result response differs from the selected execution or retained review revisions.")}console.log(JSON.stringify(s,null,2))}m(J,"runHumanReviewCommand");async function N(r){let l=r.body?.getReader();if(!l)throw new Error("Review response is unavailable.");let i=[],a=0;try{for(;;){let o=await l.read();if(o.done)break;if(a+=o.value.byteLength,a>8388608)throw new Error("Review response exceeds its bounded transport.");i.push(o.value)}}finally{await l.cancel(),l.releaseLock()}return Buffer.concat(i).toString("utf8")}m(N,"boundedResponse");export{J as runHumanReviewCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{A as z,a as ue,b as $,c as pe,d as fe,g as me,h as he,i as L,j as we,k as ge,l as ye,m as ve,n as be,o as H,p as N,q as Ie,r as Se,s as Ce,t as V,u as O,v as Q,w as Ee,x as M,y as xe,z as Re}from"./chunk-OTXGAKFH.js";import{k as Y}from"./chunk-HYUTDZ3N.js";import{a as Ne}from"./chunk-RFQD6B44.js";import"./chunk-
|
|
2
|
+
import{A as z,a as ue,b as $,c as pe,d as fe,g as me,h as he,i as L,j as we,k as ge,l as ye,m as ve,n as be,o as H,p as N,q as Ie,r as Se,s as Ce,t as V,u as O,v as Q,w as Ee,x as M,y as xe,z as Re}from"./chunk-OTXGAKFH.js";import{k as Y}from"./chunk-HYUTDZ3N.js";import{a as Ne}from"./chunk-RFQD6B44.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import"./chunk-JFXINDOQ.js";import"./chunk-KHDCMVEJ.js";import{k as Ue,l as Ae,m as J}from"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import{d as F,g as $e}from"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{c as le,f as de}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as u,f as y}from"./chunk-3M53YXEI.js";import{b as ce}from"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import{m as ae,n as x}from"./chunk-RCT3O3HQ.js";import{a as _,f as ie}from"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as g}from"./chunk-X2J2P5ZT.js";import{a as d}from"./chunk-FTQLQJQV.js";import{createInterface as Le}from"node:readline/promises";import{join as so,resolve as Me}from"node:path";import{homedir as io}from"node:os";import{createHash as Te,generateKeyPairSync as Fe,createPublicKey as Ye,diffieHellman as Ge,createDecipheriv as We}from"node:crypto";import{spawn as Ve}from"node:child_process";var Oe=d(e=>Te("sha256").update(e).digest("hex"),"hash"),Qe=g.object({publicKey:g.string().max(200),iv:g.string().max(100),tag:g.string().max(100),ciphertext:g.string().max(1e4)}).strict();async function X(e,t,o){let r=await fetch(`${e}${t}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),n=await r.text();if(n.length>16384)throw new Error("Authorization response exceeded its limit.");if(!r.ok)throw Object.assign(new Error(`Browser sign-in failed (${r.status}).`),{status:r.status});return JSON.parse(n)}d(X,"post");function Xe(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"rundll32":"xdg-open",o=process.platform==="win32"?["url.dll,FileProtocolHandler",e]:[e],r=Ve(t,o,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}d(Xe,"openBrowser");async function ke(e,t){let o=await F(),r=le(t)||o.apiBaseUrl||ce,n=u(t,"baseUrl")||de(o),i=new URL(n),c=new URL(r);for(let h of[i,c])if(h.protocol!=="https:"&&!(h.protocol==="http:"&&["localhost","127.0.0.1"].includes(h.hostname))||h.username||h.password||h.search||h.hash)throw new Error("Sign-in requires a clean HTTPS origin or local development origin.");let s=`import-${Oe([i.origin,e.machineId,e.instanceId].join(":")).slice(0,24)}`,a=Fe("x25519"),f=a.publicKey.export({format:"der",type:"spki"}).toString("base64"),l=g.object({deviceCode:g.string(),userCode:g.string(),expiresAt:g.string().datetime(),intervalSeconds:g.number().min(2).max(10)}).strict().parse(await X(i.origin,"/api/cli/import/device",{publicKey:f,machineId:e.machineId,sourceInstanceId:e.instanceId,sourceLabel:$[e.source],sourceRoot:e.root,...u(t,"team")?{requestedTeamId:u(t,"team")}:{}})),w=`${i.origin}/console/connections/authorize?code=${encodeURIComponent(l.userCode)}`;for(console.log(`OpenPond sign-in code: ${l.userCode}
|
|
3
3
|
${w}`),Xe(w);Date.now()<Date.parse(l.expiresAt);){await new Promise(R=>setTimeout(R,l.intervalSeconds*1e3));let h;try{h=await X(i.origin,"/api/cli/import/token",{deviceCode:l.deviceCode})}catch(R){if(Number(R.status)===429)continue;throw R}let b=g.object({state:g.enum(["pending","approved","denied","consumed"]),envelope:Qe.nullable().optional()}).strict().parse(h);if(b.state==="denied"||b.state==="consumed")throw new Error("Browser sign-in was declined or already consumed. Start the connection again.");if(b.state!=="approved"||!b.envelope)continue;let m=b.envelope,p=Ye({key:Buffer.from(m.publicKey,"base64"),format:"der",type:"spki"});if(p.asymmetricKeyType!=="x25519")throw new Error("Invalid sign-in encryption key.");let C=Te("sha256").update(Ge({privateKey:a.privateKey,publicKey:p})).digest(),v=We("aes-256-gcm",C,Buffer.from(m.iv,"base64"));v.setAAD(Buffer.from(Oe(l.deviceCode))),v.setAuthTag(Buffer.from(m.tag,"base64"));let S=g.object({apiKey:g.string().min(1),teamId:g.string().min(1),expiresAt:g.string().datetime()}).strict().parse(JSON.parse(Buffer.concat([v.update(Buffer.from(m.ciphertext,"base64")),v.final()]).toString("utf8")));if(u(t,"team")&&S.teamId!==u(t,"team"))throw new Error("Browser approved a different workspace.");return await $e({handle:s,apiKey:S.apiKey,baseUrl:i.origin,apiBaseUrl:c.origin,setActive:!1}),await X(i.origin,"/api/cli/import/token",{deviceCode:l.deviceCode,acknowledge:!0}),{apiKey:S.apiKey,teamId:S.teamId,baseUrl:c.origin,account:s,accountBaseUrl:i.origin}}throw new Error("Browser sign-in expired. Start the connection again.")}d(ke,"authorizeImporter");import{homedir as Ze}from"node:os";import{join as eo}from"node:path";import{zstdCompressSync as oo}from"node:zlib";function je(e,t,o){if(t.connectionId!==e.id||!t.boundaryIds.length||new Set(t.boundaryIds).size!==t.boundaryIds.length)throw Object.assign(new Error("Retained source selection differs from its connection."),{status:400});if(o.issues.length)throw Object.assign(new Error("Retained source normalization failed."),{status:400});let r=o.sessions.find(n=>JSON.stringify([e.source.instanceId,n.sessionId,n.branchId])===t.sessionKey);if(!r||t.boundaryIds.some(n=>{let i=r.boundaries.find(s=>s.id===n),c=i?r.events[i.start]?.occurredAt:null;return!i||i.projection!=="turn"||i.terminal==="unknown"||!c||!Number.isFinite(Date.parse(c))||e.since!==null&&Date.parse(c)<Date.parse(e.since)}))throw Object.assign(new Error("Retained source boundaries changed; inspect the connection before resuming."),{status:400});return{...t,contentHash:r.contentHash,operationId:r.contentHash===t.contentHash?t.operationId:`sync-${x([t.operationId,"source-normalization",r.contentHash]).slice(0,48)}`}}d(je,"refreshRetainedAdmission");async function k(e){let t=await _(e.credentialHome??eo(Ze(),".openpond"),()=>F({account:e.account,baseUrl:e.accountBaseUrl})),o=e.account?t.apiKey:Ne(t);if(!o)throw Object.assign(new Error("This source is disconnected. Reconnect it with OpenPond Importer to authorize collection."),{status:401});let r={apiKey:o,baseUrl:e.apiBaseUrl,teamId:e.teamId};return{evidence:new Ae(r),sync:new J(r)}}d(k,"collectorClients");var Z=null;async function ee(e,t,o){let r=AbortSignal.any([AbortSignal.timeout(6e4),...t?[t]:[]]);try{return await o(r)}catch(n){let i=n&&typeof n=="object"&&"status"in n?n.status:void 0;throw Object.assign(new Error(`Conversation import ${e} failed: ${n instanceof Error?n.message:String(n)}`,{cause:n}),typeof i=="number"?{status:i}:{})}}d(ee,"admissionStep");var Be={async publishCoverage(e,t,o){let{sync:r}=await k(e);await r.publishCoverage({id:e.id,expectedRevision:e.revision,manifest:t},AbortSignal.any([AbortSignal.timeout(6e4),...o?[o]:[]]))},async heartbeat(e,t,o){let{sync:r}=await k(e),n=await r.heartbeat({id:e.id,expectedRevision:e.revision,...t},AbortSignal.any([AbortSignal.timeout(6e4),...o?[o]:[]]));return{revision:n.revision,state:n.state,destinations:ge(e,n),requestedSyncRevision:n.requestedSyncRevision,completedSyncRevision:n.completedSyncRevision}},async admit(e,t,o){let{evidence:r,sync:n}=await k(e),i=x([e.id,e.revision,e.apiBaseUrl,e.teamId,e.account,e.credentialHome,e.projectId,e.source.instanceId,t.branchLeafId,t.files]);if(Z?.key!==i){let m=Buffer.from(JSON.stringify(t.files.map(C=>({path:C.path,encoding:"zstd",base64:oo(Buffer.from(C.text)).toString("base64")})))),p=ue({source:e.source.source,files:t.files,acquisition:{machineId:e.source.machineId,sourceInstanceId:e.source.instanceId},...t.branchLeafId?{branchLeafId:t.branchLeafId}:{}});Z={key:i,bytes:m,upload:{hash:ae(m),parts:Math.ceil(m.length/2e5)},nextPart:0,normalized:p}}let c=Z,s=je(e,t,c.normalized),a=c.upload;for(;c.nextPart<a.parts;){let m=c.nextPart,p=Math.min(4,a.parts-m),C=await Promise.allSettled(Array.from({length:p},(R,j)=>{let B=m+j;return ee(`upload part ${B+1}/${a.parts}`,o,K=>r.uploadPart({...a,index:B,base64:c.bytes.subarray(B*2e5,(B+1)*2e5).toString("base64")},K))})),v=C.findIndex(R=>R.status==="rejected");c.nextPart+=v<0?p:v;let S=C[v];if(S?.status==="rejected")throw S.reason}let f={upload:a,source:e.source.source,...t.branchLeafId?{branchLeafId:t.branchLeafId}:{},destination:{kind:"existing",projectId:e.projectId},acquisition:{machineId:e.source.machineId,sourceInstanceId:e.source.instanceId}},l=c.preview??=await ee("preview",o,m=>r.preview(f,m));if(l.issues.length)throw Object.assign(new Error("Source schema was rejected; inspect the connection before resuming."),{status:400});let w=l.sessions.find(m=>m.sessionHash===s.contentHash);if(!w||t.boundaryIds.some(m=>!w.boundaries.some(p=>p.id===m&&p.projection==="turn"&&p.terminal!=="unknown")))throw Object.assign(new Error("Server preview differs from the retained source boundaries."),{status:400});let h={...f,operationId:s.operationId,previewHash:l.previewHash,selection:[{sessionHash:w.sessionHash,boundaryIds:t.boundaryIds}]},b=Ue.parse(await ee("commit",o,m=>n.commit({connectionId:e.id,expectedRevision:e.revision,request:h},m)));if(b.state!=="completed"||b.operationId!==s.operationId||b.requestHash!==x(h)||b.projectId!==e.projectId)throw new Error("Admission did not acknowledge this retained operation.")}};function G(e){if(e.everyMinute!==void 0)throw new Error("Every-minute imports are no longer supported. Use --continual --hourly or a slower schedule.");let t=y(e.continual),o=["daily","weekly","hourly"].filter(a=>y(e[a]));e.cron!==void 0&&o.push("cron");let r=e.at!==void 0||e.on!==void 0;if(!t&&(o.length||r))throw new Error("Add --continual to enable recurring imports. Without it, imports run once.");if(!t)return null;if(o.length>1)throw new Error("Choose one cadence: --daily, --weekly, --hourly, or --cron.");if(e.off!==void 0)throw new Error("Choose --continual or --off, not both.");let n=o[0]??"daily";if(["cron","hourly"].includes(n)){if(r)throw new Error("--at and --on are for daily/weekly imports; use a cron expression for other times.");return n==="cron"?be({frequency:"cron",expression:u(e,"cron")}):{frequency:"hourly"}}if(n!=="weekly"&&e.on!==void 0)throw new Error("--on selects a weekday and requires --weekly.");let i=ve(e.at===void 0?"00:00":u(e,"at"));if(n==="daily")return{frequency:"daily",time:i};let c=e.on===void 0?"mon":u(e,"on").toLowerCase(),s=ye.findIndex(a=>a===c);if(s<0)throw new Error("Use --on sun|mon|tue|wed|thu|fri|sat (default: mon).");return{frequency:"weekly",time:i,day:s}}d(G,"importSchedule");import{setTimeout as to}from"node:timers/promises";async function Pe(e){console.log("Importing saved conversations. Ctrl+C cancels this run; queued work is retained.");let t=0;try{for(;!e.signal.aborted;){let n=(await O(e.directory)).connections.filter(s=>!e.connectionId||s.id===e.connectionId).find(s=>s.run?.state==="running"),i=n?.run,c=n&&i?`${n.source}: ${i.phase} \xB7 ${i.processed}/${i.discovered} conversations checked \xB7 ${i.uploaded} turns uploaded \xB7 ${n.queued} queued`:"Starting import\u2026";process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${["|","/","-","\\"][t++%4]} ${c}`);try{await to(500,void 0,{signal:e.signal})}catch{if(!e.signal.aborted)throw new Error("Import progress interrupted.")}}}finally{process.stdout.clearLine(0),process.stdout.cursorTo(0)}}d(Pe,"monitorImport");async function P(e){let t=new AbortController,o=d(()=>t.abort(new Error("Import cancelled.")),"stop");process.once("SIGINT",o),process.once("SIGTERM",o);let r=new AbortController,n=!!process.stdin.isTTY&&!!process.stdout.isTTY&&!e.json,i;try{let s=Ce({directory:e.directory,signal:t.signal,until:e.until,...e.connectionId?{connectionIds:[e.connectionId]}:{},...e.retainedStart?{}:{trigger:e.scheduled?"scheduled":"manual"},transport:Be}).finally(()=>r.abort());await Promise.all([s,n?Pe({directory:e.directory,connectionId:e.connectionId,signal:r.signal}):Promise.resolve()]),i=await O(e.directory)}finally{r.abort(),process.off("SIGINT",o),process.off("SIGTERM",o)}let c=i.connections.filter(s=>!e.connectionId||s.id===e.connectionId);if(e.json)console.log(JSON.stringify(i,null,2));else for(let s of c){let a=s.run;a&&console.log(`${s.source}: ${a.state}. ${a.processed} conversations checked, ${a.uploaded} turns uploaded, ${s.queued} queued.${a.error?` ${a.error}`:""}`),console.log(s.schedule?`Continual imports: ${H(s.schedule)} (${i.timezone}). Next: ${s.nextRunAt??"source paused"}.`:"Automatic sync is off. Run openpond import sync to import again.")}return t.signal.aborted?process.exitCode=130:c.some(s=>s.run?.state==="failed")&&(process.exitCode=1),i}d(P,"runImportJob");import{readFile as no}from"node:fs/promises";async function oe(e){let t=await no(e);if(t.byteLength>1024*1024)throw new Error("Conversation selection exceeds 1 MiB.");return me.parse(JSON.parse(t.toString("utf8")))}d(oe,"readUploadSelection");async function qe(e,t){let o=await L(e.source,await oe(t));return{...e,since:null,selectedSessionKeys:[...o.sessionKeys].sort()}}d(qe,"applyUploadSelection");function W(e){return{directory:e,executable:process.execPath,args:[...process.execArgv,process.argv[1]],environment:{...process.env.OPENPOND_HOME?{OPENPOND_HOME:process.env.OPENPOND_HOME}:{},...process.env.ELECTRON_RUN_AS_NODE==="1"?{ELECTRON_RUN_AS_NODE:"1"}:{}}}}d(W,"collectorSetup");async function He(e,t,o,r){let n=d(c=>console.log(JSON.stringify(c,null,2)),"print"),i=y(r.json);if(t==="status")return n(await O(e)),!0;if(t==="conversations"){if(!o)throw new Error("Use openpond import conversations <connection-id> [--query <text>] [--range day|week|all] [--offset <number>].");let c=await N.open(e);try{let s=c.connections().find(a=>a.id===o);if(!s)throw new Error("Select a retained connection from import status.");n({sourceInstanceId:s.source.instanceId,...we(s,await he(s.source),{query:u(r,"query"),range:u(r,"range")||"all",offset:Number(u(r,"offset")||"0")})})}finally{c.close()}return!0}if(t==="coverage"){if(!o)throw new Error("Use openpond import coverage <connection-id>.");let c=await N.open(e);try{if(!c.connections().some(a=>a.id===o))throw new Error("Select a retained connection from import status.");let s=c.coverage.manifest(o);if(!s)throw new Error("This connection has no retained source coverage. Run import sync first.");n({manifest:s,summary:c.coverage.summary(o)})}finally{c.close()}return!0}if(t==="cancel")return n(await Q(e,"stop")),!0;if(t==="schedule"){if(!o)throw new Error("Use openpond import schedule <connection-id> --continual [--daily|--weekly|--hourly|--cron <expression>] or --off.");let c=G(r),s=y(r.off);if(!c&&!s)throw new Error("Choose --continual [--daily|--weekly|--hourly|--cron <expression>] or --off.");return n(await M(W(e),o,c)),!0}if(t==="sync"){let c=await O(e);if(o&&!c.connections.some(a=>a.id===o&&a.state==="active"))throw new Error("Select an active connection from import status; resume or reconnect it first.");if(!c.connections.some(a=>a.state==="active"))throw new Error("No active sources. Connect or resume a source first.");let s=u(r,"selectionFile");if(s){if(!o)throw new Error("Select a connection ID when uploading chosen conversations.");if(c.running)throw new Error("Wait for the running import or cancel it before selecting more conversations.");let a=await N.open(e);try{let f=a.connections().find(w=>w.id===o);if(!f)throw new Error("The selected connection is unavailable.");let l=await qe(f,s);if(f.since!==null){let{sync:w}=await k(f),h=await w.register({id:f.id,source:f.source.source,machineId:f.source.machineId,sourceInstanceId:f.source.instanceId,sourceLabel:$[f.source.source],sourceRoot:f.source.root,destination:{kind:"existing",projectId:f.projectId},since:null,keepSyncing:f.keepSyncing,expectedRevision:f.revision});l={...l,revision:h.revision,state:h.state,requestedSyncRevision:h.requestedSyncRevision,completedSyncRevision:h.completedSyncRevision}}a.put(l)}finally{a.close()}}else if(!c.connections.some(a=>a.state==="active"&&(!o||a.id===o)&&a.selectedConversations!==0))throw new Error("Choose conversations first with --selection-file <path>.");return await P({directory:e,connectionId:o,json:i,until:u(r,"until")||void 0}),!0}if(t!=="service")return!1;if(o==="status")n(await O(e));else if(o==="stop")n(await Q(e,"stop"));else if(o==="uninstall")n(await xe(e));else if(o==="install")n(await Ee(W(e)));else if(o==="start")await P({directory:e,json:i});else if(o==="run")await P({directory:e,json:i,scheduled:y(r.scheduled),retainedStart:!y(r.scheduled)});else throw new Error("usage: openpond import service <install|start|stop|status|run|uninstall>");return!0}d(He,"runImporterControl");async function te(e,t){let o=await N.open(e),r;try{r=o.connections().find(n=>n.id===t)}finally{o.close()}if(!r)throw new Error("Select a retained connection from openpond import status.");if(r.source.machineId!==await z(e))throw new Error("This connection belongs to another machine. Use explicit Connect setup.");if(!r.accountBaseUrl)throw new Error("The original sign-in destination is unavailable. Use explicit Connect setup.");return r}d(te,"retainedReconnect");function Ke(e,t){if(!t?.available||!t.capabilities.history||t.source!==e.source.source||t.machineId!==e.source.machineId||t.instanceId!==e.source.instanceId||t.root!==e.source.root)throw new Error("The retained source is unavailable or its identity changed. Restore its original location or use explicit Connect setup.")}d(Ke,"assertReconnectSource");async function De(e,t){let o=await te(e,t.id),r=d(n=>({...n,destinations:void 0,requestedSyncRevision:n.requestedSyncRevision??0,completedSyncRevision:n.completedSyncRevision??0}),"scope");if(x(r(o))!==x(r(t)))throw new Error("The connection changed during sign-in. Reconnect again after reviewing its current scope.")}d(De,"assertReconnectUnchanged");import{createInterface as ro}from"node:readline/promises";async function _e(e,t,o,r){let n=u(r,"session");if(!o||!n)throw new Error("Use openpond import branches <connection-id> --session <native-session-id>.");let i=await Ie(e,o,n);if(t==="branches"){console.log(JSON.stringify(i,null,2));return}let c=process.stdin.isTTY&&process.stdout.isTTY&&!y(r.json),s=u(r,"leaf"),a=u(r,"revision");if(!s&&c){i.branches.forEach((w,h)=>console.log(`${h+1}. ${w.title||w.leafId} (${w.messages} messages; ${w.updatedAt||"date unavailable"})`));let l=ro({input:process.stdin,output:process.stdout});try{s=i.branches[Number(await l.question("Choose the branch to sync: "))-1]?.leafId??"",a=i.revision}finally{l.close()}}if(!s||!a)throw new Error("Supply --leaf and --revision from import branches, or choose interactively. No branch was selected.");if(!i.branches.some(l=>l.leafId===s)||a!==i.revision)throw new Error("Branch selection is stale or invalid. Run import branches again.");if(!y(r.yes)&&(!c||!await Y("Sync only this branch and its unambiguous future continuation for this conversation? Other branches stay excluded.",!1)))throw new Error("Branch selection was not approved.");let f=await Se(e,o,n,{leafId:s,revision:a});console.log(JSON.stringify({...f,next:`openpond import resume ${o}`},null,2))}d(_e,"runImporterBranchCommand");async function $t(e,t){let[o="connect",r]=t,n=Me(u(e,"collectorDir")||Re()),i=y(e.json),c=d(I=>console.log(JSON.stringify(I,null,2)),"print"),s=G(e),a=y(e.upload),f=u(e,"selectionFile");if(a&&!["connect","reconnect"].includes(o))throw new Error("Use --upload with import connect or reconnect; import sync is already an explicit upload.");if(f&&!["connect","reconnect","sync"].includes(o))throw new Error("Use --selection-file with connect, reconnect, or sync.");if(f&&o!=="sync"&&!a)throw new Error("Use --upload to confirm the selected initial upload.");if(s&&!a&&o==="connect")throw new Error("Select an initial upload with --upload before enabling continual imports.");if(e.until&&o!=="sync")throw new Error("Use --until with import sync to select a fixed event-time cutoff.");if(s&&!["connect","reconnect","schedule"].includes(o))throw new Error("Use --continual with import connect, reconnect, or schedule.");if(y(e.off)&&o!=="schedule")throw new Error("Use import schedule <connection-id> --off to disable recurring imports.");if(o==="branches"||o==="branch"){await _e(n,o,r,e);return}if(await He(n,o,r,e))return;if(["pause","resume","disconnect"].includes(o)){let I=await N.open(n),U;try{U=I.connections().find(Je=>Je.id===r)}finally{I.close()}if(!U)throw new Error("Select a connection id from openpond import status.");let{sync:A}=await k(U),q=await A.control({id:U.id,expectedRevision:U.revision,action:o});await V(n,{...U,revision:q.revision,state:q.state}),c(q);return}let l=o==="reconnect"?await te(n,r):null;l&&(e={...e,source:l.source.source,sourcePath:l.source.root,project:l.projectId,connection:l.id,team:l.teamId,apiBaseUrl:l.apiBaseUrl,baseUrl:l.accountBaseUrl});let w=u(e,"source");if(w&&!(w in $))throw new Error("Choose a supported native source name.");let h=await z(n),b=await pe({machineId:h,...w&&u(e,"sourcePath")?{locations:{[w]:Me(u(e,"sourcePath"))}}:{}});if(o==="discover"){c(b);return}if(o!=="connect"&&o!=="reconnect")throw new Error("usage: openpond import <connect|reconnect|discover|status|conversations|coverage|sync|schedule|cancel|pause|resume|disconnect|branches|branch|service>");let m=b.filter(I=>I.source===w),p=m.length===1?m[0]:void 0,C=process.stdin.isTTY&&process.stdout.isTTY&&!i;if(l&&Ke(l,p),!p&&C){let I=m.length>1?m:b.filter(A=>A.available);I.forEach((A,q)=>console.log(`${q+1}. ${$[A.source]} ${A.root}${A.capabilities.history?"":` (${A.reason})`}`));let U=Le({input:process.stdin,output:process.stdout});try{p=I[Number(await U.question("Choose a source: "))-1]}finally{U.close()}}if(!p?.capabilities.history)throw new Error(p?.reason??(m.length>1?"Multiple source instances found. Select the exact --source-path or use interactive setup.":"Select --source and optionally --source-path."));let v=u(e,"range")||"week";if(a&&!l&&C&&!e.range){let I=Le({input:process.stdin,output:process.stdout});try{v=(await I.question("Initial history: day, week, or all [default: week]: ")).trim()||"week"}finally{I.close()}}if(!["day","week","all"].includes(v))throw new Error("--range must be day, week or all.");let S=f?null:l?l.since:v==="all"?null:new Date(Date.now()-(v==="day"?1:7)*864e5).toISOString(),R=l?S?`since ${S}`:"all":v==="week"?`last week${e.range?"":" (default)"}`:v==="day"?"last day":"all",j=f?await L(p,await oe(f)):null,B=j?j.sessionKeys:l?l.selectedSessionKeys:a?void 0:[],K=await fe(p,{since:S??void 0,limit:100});i||console.log(`Found ${K.items.length}${K.nextCursor?"+":""} sessions in ${p.root}. Initial history: ${R}.`),i||console.log(a?s?`Continual imports: ${H(s)} local time. Continual learning is unchanged.`:"One-time import. Continual imports default to off; existing schedules are unchanged.":"Connect only. No conversations will be uploaded. Choose conversations with import sync --selection-file when ready.");let D=u(e,"project");if(!y(e.yes)&&(!C||!await Y(`Connect this source to ${D||"your personal Imported conversations Project"}${a?` and upload ${j?`${j.sessionKeys.length} selected conversations`:"the selected history window"}`:" without uploading history"}${s?` and enable continual imports ${H(s)} local time`:""}?`,!0)))throw new Error("Connection was not approved. No history was uploaded.");let ne=l?l.credentialHome??so(io(),".openpond"):ie(),T=await _(ne,()=>ke(p,e)),re=new J(T),se=u(e,"connection")||`sync-${x([T.baseUrl,T.teamId,p.instanceId,D||"default"]).slice(0,40)}`;l&&await De(n,l);let ze=(await re.list()).items.find(I=>I.id===se),E=await re.register({id:se,source:p.source,machineId:h,sourceInstanceId:p.instanceId,sourceLabel:$[p.source],sourceRoot:p.root,destination:D?{kind:"existing",projectId:D}:{kind:"new",name:"Imported conversations"},since:S,keepSyncing:!1,expectedRevision:ze?.revision??0});await V(n,{id:E.id,teamId:T.teamId,apiBaseUrl:T.baseUrl,account:T.account,accountBaseUrl:T.accountBaseUrl,credentialHome:ne,source:p,projectId:E.projectId,revision:E.revision,requestedSyncRevision:E.requestedSyncRevision,completedSyncRevision:E.completedSyncRevision,since:S,selectedSessionKeys:B,keepSyncing:!1,state:E.state}),s&&await M(W(n),E.id,s),a?await P({directory:n,connectionId:E.id,json:i}):i?c({connectionId:E.id,uploaded:!1}):console.log(`Connected ${E.id}. Choose conversations to upload when ready.`)}d($t,"runImportCommand");export{$t as runImportCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import"./chunk-T4QXKU5Y.js";import"./chunk-HYUTDZ3N.js";import{c as h}from"./chunk-RFQD6B44.js";import"./chunk-
|
|
2
|
+
import"./chunk-T4QXKU5Y.js";import"./chunk-HYUTDZ3N.js";import{c as h}from"./chunk-RFQD6B44.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import{a as k}from"./chunk-Q34IF4PW.js";import{a as d,c as w,d as B}from"./chunk-6XSSM4WT.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import{d as f}from"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{c as u,d as m,f as g}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{f as p}from"./chunk-3M53YXEI.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import"./chunk-X2J2P5ZT.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as U}from"node:crypto";async function T(t,r){let e=r[0]||"smoke";if(e==="chat"){if(r.length!==1)throw new Error("opchat chat accepts options, not positional arguments.");await(await import("./opchat-bounded-chat-WRXN7S52.js")).runBoundedOpChat(t);return}let o=await f(),s=await h(o,g(o)),l=C(o,t);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let n=await y({apiBaseUrl:l,token:s});console.log(JSON.stringify(n,null,2));return}if(e==="models"||e==="model-list"){let n=await w({apiBaseUrl:l,token:s});console.log(JSON.stringify(n,null,2));return}if(e==="model"||e==="model-get"){let n=r[1]||a(t,"model");if(!n)throw new Error("usage: opchat model <model>");let c=await B({apiBaseUrl:l,token:s,model:n});console.log(JSON.stringify(c,null,2));return}if(e==="smoke"){let n=await k({apiBaseUrl:l,token:s,defaultModel:a(t,"model")||void 0,compatibilityModel:a(t,"compatibilityModel")||a(t,"compatModel")||void 0,skipStream:p(t.skipStream),skipTool:p(t.skipTool),log:i(c=>console.log(c),"log")});p(t.json)&&console.log(JSON.stringify(n,null,2));return}throw new Error(`usage: opchat <provider-catalog|models|model|smoke> [--opchat-api-base-url <url>]
|
|
3
3
|
opchat chat --model <id> --message <text> --team-id <id> --max-output-tokens <n> --request-id <id> --timeout-sec <1..600> --max-spend <usd> [--stream] (one bounded request; JSON receipt after completion)`)}i(T,"runOpChatCommand");async function y(t){let r=t.apiBaseUrl.trim().replace(/\/+$/,"");if(!r)throw new Error("OpChat API base URL is required.");let e=t.token.trim();if(!e)throw new Error("OpenPond API key is required.");let o=await fetch(`${r}/provider-catalog`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json","x-openpond-client":"openpond-cli","x-openpond-request-id":U()}});if(!o.ok)throw new Error(`Hosted provider catalog failed: ${o.status} ${await A(o)}`);return o.json()}i(y,"getOpChatProviderCatalog");async function A(t){let r=await t.text().catch(()=>"");if(!r)return t.statusText||`HTTP ${t.status}`;try{let e=JSON.parse(r);if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){let o=e.error;return[o.code,o.message].filter(Boolean).join(": ")||r}return r}catch{return r}}i(A,"readResponseError");function C(t,r){let e=a(r,"opchatApiBaseUrl")||a(r,"opchatApiBaseurl")||a(r,"opChatApiBaseUrl")||a(r,"opChatApiBaseurl")||a(r,"opchatApiUrl")||a(r,"opChatApiUrl");return e?d({opChatApiBaseUrl:e}):d({apiBaseUrl:u(r)||t.apiBaseUrl,chatApiBaseUrl:m(r)||t.chatApiBaseUrl})}i(C,"resolveOpChatCliBaseUrl");function a(t,r){let e=t[r];return typeof e=="string"?e.trim():""}i(a,"optionString");export{T as runOpChatCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import"./chunk-T4QXKU5Y.js";import"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import{a as Z}from"./chunk-AZ7BL5FL.js";import"./chunk-
|
|
2
|
+
import"./chunk-T4QXKU5Y.js";import"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import{a as Z}from"./chunk-AZ7BL5FL.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import{a as D,d as X,i as J,j as Y}from"./chunk-6XSSM4WT.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{a as j}from"./chunk-REGKOCDO.js";import{c as $,d as z}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{c as A,f as H}from"./chunk-3M53YXEI.js";import"./chunk-EJOV6Z6F.js";import"./chunk-GY7YSD6J.js";import"./chunk-KUE46HTH.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-6FA3GG5B.js";import"./chunk-SV7ZBEK2.js";import{M as L}from"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import{A as s}from"./chunk-X2J2P5ZT.js";import{a as p}from"./chunk-FTQLQJQV.js";import{createHash as ne}from"node:crypto";var ee=new Set(["Error","TypeError","SyntaxError","AbortError","TimeoutError","SocketError","HeadersTimeoutError","BodyTimeoutError","ConnectTimeoutError"]),te=new Set(["UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_ABORTED","UND_ERR_DESTROYED","UND_ERR_CLOSED","UND_ERR_RESPONSE_STATUS_CODE","ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","ABORT_ERR"]);function K(n){let o=[],e=new Set,a=n;for(;a&&typeof a=="object"&&o.length<3&&!e.has(a);){e.add(a);let d=a;o.push({name:typeof d.name=="string"&&ee.has(d.name)?d.name:"unrecognized",code:d.code===void 0?null:typeof d.code=="string"&&te.has(d.code)?d.code:"unrecognized"}),a=d.cause}return o}p(K,"boundedTransportError");function V(){let n=null,o=null,e=null,a=null,d=null,M=null,l=0,y=0,m=0,S=0,c=0,i=0,E=null;return{observe:p(t=>{t.type==="request"&&(n=performance.now()-t.elapsedMs),t.type==="headers"&&(o=t),t.type==="bytes"&&(l=Math.max(l,t.elapsedMs-(a??o?.elapsedMs??0)),e??=t.elapsedMs,a=t.elapsedMs,y=Math.min(Number.MAX_SAFE_INTEGER,y+t.byteLength),m=Math.min(Number.MAX_SAFE_INTEGER,m+1)),t.type==="data"&&(S=Math.min(Number.MAX_SAFE_INTEGER,S+1),d=t.elapsedMs,t.errorFrame&&(i=Math.min(Number.MAX_SAFE_INTEGER,i+1))),t.type==="comment"&&(c=Math.min(Number.MAX_SAFE_INTEGER,c+1),M=t.elapsedMs),t.type==="done"&&(E=t.elapsedMs)},"observe"),snapshot:p(()=>{let t=n===null?null:Math.round(performance.now()-n);return{phase:n===null?"not_started":o?E!==null?"done":i>0?"error_frame":"response_body":"before_headers",elapsedMs:t,response:o===null?null:{status:o.status,headersAtMs:o.elapsedMs,eventStream:o.eventStream,noCache:o.noCache,noTransform:o.noTransform,bufferingDisabled:o.bufferingDisabled},bytes:y,readChunks:m,dataFrames:S,commentFrames:c,errorFrames:i,firstByteAtMs:e,lastByteAtMs:a,lastDataAtMs:d,lastCommentAtMs:M,doneAtMs:E,maxByteGapMs:l,silentForMs:t===null||o===null?null:Math.max(0,t-(a??o.elapsedMs))}},"snapshot")}}p(V,"createStreamDiagnostics");var O=s.coerce.number().int().positive().safe(),oe=s.object({model:s.string().trim().min(1).max(512),message:s.string().trim().min(1).max(131072),teamId:s.string().regex(/^[A-Za-z0-9_-]{3,191}$/),requestId:s.string().regex(/^[A-Za-z0-9._:-]{1,200}$/),maxOutputTokens:O,timeoutSec:O.max(600),maxSpend:s.coerce.number().finite().positive()}),q=s.number().finite().nonnegative(),re=s.object({id:s.string(),context_window:O,output_limit:O,metadata:s.object({billing:s.object({pricing:s.object({version:s.string().trim().min(1),source:s.string().trim().min(1),effectiveAt:s.string().refine(n=>Number.isFinite(Date.parse(n))),inputUsdPerMillionTokens:q,cachedInputUsdPerMillionTokens:q,outputUsdPerMillionTokens:q}).passthrough()})})});async function ge(n,o={}){let e=oe.parse({...n,message:A(n,"message")||A(n,"prompt")}),a=H(n.stream),d=n.effort===void 0?void 0:L.parse(n.effort),M=o.emit??(u=>console.log(JSON.stringify(u,null,2))),l=new AbortController,y=new Date().toISOString(),m=!1,S=null,c=null,i=null,E="",_=null,C=null,t=V(),x=null,B=p(u=>l.abort(new Error(`OpChat cancelled by ${u}.`)),"abort"),P=p(()=>B("SIGINT"),"interrupt"),v=p(()=>B("SIGTERM"),"terminate"),W=setTimeout(()=>l.abort(new DOMException("OpChat deadline reached.","TimeoutError")),e.timeoutSec*1e3);process.once("SIGINT",P),process.once("SIGTERM",v);let F=p((u,r)=>{let b=u==="completed"&&i&&i.estimated!==!0&&[i.prompt_tokens??i.input_tokens,i.completion_tokens??i.output_tokens].every(w=>typeof w=="number"&&Number.isSafeInteger(w)&&w>=0);return{schemaVersion:"openpond.boundedOpChatReceipt.v1",status:u,requestId:e.requestId,model:e.model,teamId:e.teamId,automaticRetry:!1,transport:a?"sse":"json",...a?{streamDiagnostics:t.snapshot()}:{},...x?{errorCauses:x}:{},startedAt:y,completedAt:new Date().toISOString(),apiOrigin:C,maxOutputTokens:e.maxOutputTokens,timeoutSec:e.timeoutSec,maximumSpendUsd:e.maxSpend,quote:S,dispatchAttempted:m,completion:c,usage:i,text:E,finishReason:_,accounting:{state:m?b?"usage_recorded":"unknown":"not_dispatched",chargedUsd:m?null:0,requiresLedgerReconciliation:m,cleanupConfirmed:!m},...r?{error:r}:{}}},"receipt");try{let u=await(o.account??j)(A(n,"account"));if(!u.token)throw new Error("Sign in to an OpenPond account before using OpChat.");let r=new URL(D({opChatApiBaseUrl:u.chatApiBaseUrl,env:{}})),b=[A(n,"opchatApiBaseUrl"),A(n,"opchatApiUrl"),z(n),$(n)].filter(g=>!!g);for(let g of b){let f=new URL(g);if(f.origin!==r.origin||f.username||f.password||f.search||f.hash)throw new Error("The OpChat API URL must match the signed-in account's chat origin.")}if(r.username||r.password||r.search||r.hash)throw new Error("The signed-in account has an invalid OpChat URL.");let w=D({opChatApiBaseUrl:b[0]??r.href,env:{}});C=r.origin,l.signal.throwIfAborted();let U=await X({apiBaseUrl:w,token:u.token,teamId:e.teamId,model:e.model,signal:AbortSignal.any([l.signal,AbortSignal.timeout(3e4)])}),Q=new Date().toISOString(),R=re.parse(U);if(R.id!==e.model)throw new Error("The catalog returned a different model identity.");if(e.maxOutputTokens>R.output_limit)throw new Error("The requested output limit exceeds the model's current limit.");let I=R.metadata.billing.pricing,N=Math.ceil(R.context_window*Math.max(I.inputUsdPerMillionTokens,I.cachedInputUsdPerMillionTokens)+e.maxOutputTokens*I.outputUsdPerMillionTokens);if(!Number.isSafeInteger(N)||N<=0)throw new Error("The model does not publish an enforceable positive request ceiling.");let k=N/1e6;if(S={kind:"worst_case_request_reservation",observedAt:Q,contextWindow:R.context_window,outputLimit:R.output_limit,pricing:I,maximumRequestCostUsd:k,predictedSpend:!1,catalog:U,catalogSha256:ne("sha256").update(JSON.stringify(U)).digest("hex")},k>e.maxSpend)throw new Error(`The current worst-case request reservation $${k} exceeds --max-spend $${e.maxSpend}.`);l.signal.throwIfAborted();let G={apiBaseUrl:w,token:u.token,teamId:e.teamId,model:e.model,requestId:e.requestId,reasoningEffort:d,maxTokens:e.maxOutputTokens,signal:l.signal,messages:[{role:"user",content:e.message}],...a?{onStreamDiagnostic:t.observe}:{}};if(m=!0,a){let g=null,f;for await(let h of Y(G)){l.signal.throwIfAborted();let T=h.raw&&typeof h.raw=="object"?h.raw:{};if(typeof T.id!="string"||!T.id||T.model!==e.model||T.request_id!==e.requestId||g!==null&&T.id!==g)throw new Error("The stream does not match the admitted completion, model and request identity.");if(g=T.id,typeof T.created=="number"&&(f=T.created),h.type==="text_delta"&&(E+=h.text),h.type==="usage"&&(i=h.usage),h.type==="finish"&&(_=h.finishReason),h.type==="tool_call_delta")throw new Error("The bounded OpChat request did not admit tool calls.")}if(!g||!_)throw new Error("The stream ended without a terminal completion receipt.");c={id:g,model:e.model,request_id:e.requestId,object:"chat.completion",assembledFromStream:!0,...f===void 0?{}:{created:f},choices:[{index:0,message:{role:"assistant",content:E},finish_reason:_}],...i===null?{}:{usage:i}}}else c=await J(G),i=c.usage??null,E=c.choices?.[0]?.message?.content??"",_=c.choices?.[0]?.finish_reason??null;if(!c.id||c.model!==e.model||c.request_id!==e.requestId)throw new Error("The completion does not match the admitted model and request identity.");if(l.signal.throwIfAborted(),!_)throw new Error("The response ended without a terminal completion receipt.");M(F("completed"))}catch(u){let r=l.signal.aborted?l.signal.reason:u;x=K(r);let b=r instanceof Error?r.message:String(r),w=l.signal.aborted?r instanceof Error&&r.name==="TimeoutError"?"timed_out":"cancelled":m?"failed":"rejected";throw M(F(w,b)),new Z(b)}finally{clearTimeout(W),process.removeListener("SIGINT",P),process.removeListener("SIGTERM",v)}}p(ge,"runBoundedOpChat");export{ge as runBoundedOpChat};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{m as M}from"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import"./chunk-P7RLDDPN.js";import"./chunk-OFC5N6R3.js";import"./chunk-XRKFTPHD.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{b as x}from"./chunk-REGKOCDO.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{a as _,f as O,h as k,i as S}from"./chunk-3M53YXEI.js";import"./chunk-EJOV6Z6F.js";import"./chunk-GY7YSD6J.js";import"./chunk-KUE46HTH.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-6FA3GG5B.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import"./chunk-X2J2P5ZT.js";import{a as i}from"./chunk-FTQLQJQV.js";import{createHash as j,randomBytes as L}from"node:crypto";import{createServer as B}from"node:http";function D(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}i(D,"formatOrganizationLine");function H(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}i(H,"formatOrganizationMemberLine");function W(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}i(W,"formatOrganizationMcpServerLine");var F=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function b(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}i(b,"normalizeMcpResourceUrl");function R(e,t){let r=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(r)return b(r);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return b(e.resourceUrl)}i(R,"resolveMcpProbeResourceUrl");function v(e,t){let r=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return r?b(r):new URL(e).origin}i(v,"resolveMcpProbeOrigin");function U(e=32){return L(e).toString("base64url")}i(U,"randomOauthToken");function G(e){return j("sha256").update(e).digest("base64url")}i(G,"buildMcpOauthPkceChallenge");function V(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...F];let r=t.split(/[,\s]+/g).map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("scope must include at least one OAuth scope");return r}i(V,"parseMcpOAuthScopes");function q(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}i(q,"resolveMcpOAuthClientId");function Y(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}i(Y,"resolveMcpOAuthTimeoutMs");function Z(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}i(Z,"resolveMcpOAuthCallbackPort");function E(e){return new Promise((t,r)=>{e.close(o=>{o?r(o):t()})})}i(E,"closeServer");async function K(e){let t=!1,r=null,o=null,s=null,n=new Promise((u,l)=>{o=u,s=l}),a=i((u,l,g,m,p)=>{if(t){u.writeHead(204).end();return}t=!0,u.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),u.end(g),r&&clearTimeout(r),m?o?.(m):s?.(p??new Error("oauth_callback_failed"))},"settle"),c=B((u,l)=>{let g=u.headers.host??"127.0.0.1",m=new URL(u.url??"/",`http://${g}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let p=m.searchParams.get("state")??"",f=m.searchParams.get("error")??"",w=m.searchParams.get("code")??"";if(p!==e.expectedState){a(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(f){a(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${f}`));return}if(!w){a(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}a(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:w,state:p})});await new Promise((u,l)=>{let g=i(p=>{c.off("listening",m),l(p)},"onError"),m=i(()=>{c.off("error",g),u()},"onListening");c.once("error",g),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let d=c.address();if(!d||typeof d.port!="number")throw await E(c),new Error("oauth_callback_listener_failed");return r=setTimeout(()=>{t||(t=!0,s?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:i(async()=>{r&&clearTimeout(r),await E(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${d.port}/callback`,waitForCallback:i(()=>n,"waitForCallback")}}i(K,"startMcpOAuthCallbackListener");function Q(e){x(e)}i(Q,"openUrlWithSystemBrowser");function X(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}i(X,"buildMcpOAuthAuthorizeUrl");async function ee(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let r=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),o=await N(r);if(!r.ok)throw new Error(`oauth_token_exchange_failed:${r.status}:${JSON.stringify(o)}`);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("oauth_token_exchange_invalid_response");let s=o;if(typeof s.access_token!="string"||!s.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:s.access_token,...typeof s.expires_in=="number"?{expires_in:s.expires_in}:{},...typeof s.refresh_token=="string"?{refresh_token:s.refresh_token}:{},...typeof s.scope=="string"?{scope:s.scope}:{},...typeof s.token_type=="string"?{token_type:s.token_type}:{}}}i(ee,"exchangeMcpOAuthAuthorizationCode");async function N(e){let t=await e.text().catch(()=>"");if(!t)return null;let r=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return t}return t}i(N,"readMcpProbeBody");async function P(e,t={}){let r=await fetch(e,t);return{url:e,status:r.status,ok:r.ok,headers:{contentType:r.headers.get("content-type"),location:r.headers.get("location"),wwwAuthenticate:r.headers.get("www-authenticate")},body:await N(r)}}i(P,"fetchMcpProbe");function te(e,t,r){return r?{jsonrpc:"2.0",id:e,method:t,params:r}:{jsonrpc:"2.0",id:e,method:t}}i(te,"buildMcpJsonRpcRequest");function T(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let r=_(t,"arguments");if(!r||typeof r!="object"||Array.isArray(r))throw new Error("arguments must be a JSON object");return r}i(T,"parseMcpToolArguments");async function z(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),P(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(te(e.id,e.method,e.params))})}i(z,"postMcpJsonRpcProbe");async function A(e){let t=b(e.resourceUrl),r=b(e.origin),o=`${t}/.well-known/oauth-protected-resource`,s=`${r}/.well-known/oauth-authorization-server`,[n,a,c,d,u,l,g]=await Promise.all([P(o),P(s),P(t),z({resourceUrl:t,id:1,method:"initialize"}),z({resourceUrl:t,id:2,method:"tools/list"}),z({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?z({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:r,protectedResource:n,authorizationServer:a,directGetChallenge:c,initialize:d,toolsList:u,unauthenticatedToolCall:l,...g?{authenticatedToolCall:g}:{}}}i(A,"probeOrganizationMcp");function re(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}i(re,"parseOrganizationRole");function ne(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}i(ne,"buildOrganizationCreateInput");function oe(e){let t={},r=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(r&&(t.displayName=r),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let o=e.status.trim();if(o!=="active"&&o!=="disabled"&&o!=="archived")throw new Error("status must be active, disabled, or archived");t.status=o}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}i(oe,"buildOrganizationUpdateInput");function ie(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:re(e.role)}}i(ie,"buildOrganizationMemberInput");function ae(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:S(e.toolset)}:{}}}i(ae,"buildOrganizationMcpGenerateInput");async function ge(e,t){let r=t[0]||"list",o=await M(e),s=O(e.json);if(r==="list"){let n=await o.listOrganizations();if(s){console.log(JSON.stringify({organizations:n},null,2));return}if(n.length===0){console.log("no organizations found");return}for(let a of n)console.log(D(a));return}if(r==="create"){let n=await o.createOrganization(ne(e));console.log(JSON.stringify({organization:n},null,2));return}if(r==="get"){let n=t[1];if(!n)throw new Error("usage: organizations get <slug>");let a=await o.getOrganization(n);console.log(JSON.stringify({organization:a},null,2));return}if(r==="update"){let n=t[1];if(!n)throw new Error("usage: organizations update <slug> [--name <name>]");let a=await o.updateOrganization(n,oe(e));console.log(JSON.stringify({organization:a},null,2));return}if(r==="members"||r==="member-list"){let n=t[1];if(!n)throw new Error("usage: organizations members <slug>");let a=await o.listOrganizationMembers(n);if(s){console.log(JSON.stringify({members:a},null,2));return}if(a.length===0){console.log("no organization members found");return}for(let c of a)console.log(H(c));return}if(r==="member-upsert"||r==="member-add"){let n=t[1];if(!n)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let a=await o.upsertOrganizationMember(n,ie(e));console.log(JSON.stringify({member:a},null,2));return}if(r==="mcp-get"||r==="mcp-server"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-get <slug>");let a=await o.getOrganizationMcpServer(n);if(s){console.log(JSON.stringify({mcpServer:a},null,2));return}console.log(W(a));return}if(r==="mcp-generate"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let a=await o.generateOrganizationMcpServer(n,ae(e));console.log(JSON.stringify({mcpServer:a},null,2));return}if(r==="mcp-probe"||r==="mcp-inspect"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let a=await o.getOrganizationMcpServer(n),c=R(a,e),d=v(c,e),u=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=T(e),g=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await A({resourceUrl:c,origin:d,toolName:u,toolArguments:l,...g?{accessToken:g}:{}});console.log(JSON.stringify({mcpServer:a,probe:m},null,2));return}if(r==="mcp-authorize"||r==="mcp-oauth"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let a=await o.getOrganizationMcpServer(n),c=R(a,e),d=v(c,e),u=q(e),l=V(e),g=U(18),m=U(48),p=G(m),f=await K({expectedState:g,port:Z(e),timeoutMs:Y(e)}),w=X({authorizationEndpoint:`${d}/oauth/authorize`,clientId:u,codeChallenge:p,redirectUri:f.redirectUri,resourceUrl:c,scopes:l,state:g});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(w),console.error(`Waiting for OAuth callback on ${f.redirectUri}`),O(e.open))try{Q(w)}catch(y){console.error(`Unable to open a browser automatically: ${y instanceof Error?y.message:String(y)}`)}try{let y=await f.waitForCallback(),h=await ee({clientId:u,code:y.code,codeVerifier:m,origin:d,redirectUri:f.redirectUri}),C=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",I=T(e),$=await A({accessToken:h.access_token,origin:d,resourceUrl:c,toolArguments:I,toolName:C}),J=O(e.printToken);console.log(JSON.stringify({mcpServer:a,oauth:{accessTokenReceived:!0,clientId:u,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...J?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:$},null,2))}finally{await f.close()}return}if(r==="mcp-rotate"||r==="mcp-disable"||r==="mcp-enable"){let n=t[1];if(!n)throw new Error(`usage: organizations ${r} <slug>`);let a=r==="mcp-rotate"?await o.rotateOrganizationMcpServer(n):r==="mcp-disable"?await o.disableOrganizationMcpServer(n):await o.enableOrganizationMcpServer(n);console.log(JSON.stringify({mcpServer:a},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}i(ge,"runOrganizationsCommand");export{F as DEFAULT_MCP_AUTHORIZE_SCOPES,te as buildMcpJsonRpcRequest,X as buildMcpOAuthAuthorizeUrl,G as buildMcpOauthPkceChallenge,ne as buildOrganizationCreateInput,ae as buildOrganizationMcpGenerateInput,ie as buildOrganizationMemberInput,oe as buildOrganizationUpdateInput,E as closeServer,ee as exchangeMcpOAuthAuthorizationCode,P as fetchMcpProbe,D as formatOrganizationLine,W as formatOrganizationMcpServerLine,H as formatOrganizationMemberLine,b as normalizeMcpResourceUrl,Q as openUrlWithSystemBrowser,V as parseMcpOAuthScopes,T as parseMcpToolArguments,re as parseOrganizationRole,z as postMcpJsonRpcProbe,A as probeOrganizationMcp,U as randomOauthToken,N as readMcpProbeBody,Z as resolveMcpOAuthCallbackPort,q as resolveMcpOAuthClientId,Y as resolveMcpOAuthTimeoutMs,v as resolveMcpProbeOrigin,R as resolveMcpProbeResourceUrl,ge as runOrganizationsCommand,K as startMcpOAuthCallbackListener};
|
|
2
|
+
import{m as M}from"./chunk-HYUTDZ3N.js";import"./chunk-RFQD6B44.js";import"./chunk-KOC74O7R.js";import"./chunk-5SVBY7NP.js";import"./chunk-XRKFTPHD.js";import"./chunk-KHDCMVEJ.js";import"./chunk-K3WM4NEC.js";import"./chunk-BLNEHU62.js";import"./chunk-BT5YNE5U.js";import"./chunk-RPM4FDRX.js";import"./chunk-DFZTRMTL.js";import"./chunk-2QHB5P2K.js";import"./chunk-BZS2PA4O.js";import"./chunk-VSQPWLAG.js";import"./chunk-6LAGMWJE.js";import"./chunk-IV2HEX3I.js";import"./chunk-C7NQPICU.js";import"./chunk-J256AEEE.js";import"./chunk-J7X72QUY.js";import"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import"./chunk-LK77GI6M.js";import"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import"./chunk-OKKNDQJF.js";import"./chunk-ZEOYNUHL.js";import"./chunk-ZY32SZ2P.js";import"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{b as x}from"./chunk-REGKOCDO.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import{a as _,f as O,h as k,i as S}from"./chunk-3M53YXEI.js";import"./chunk-EJOV6Z6F.js";import"./chunk-GY7YSD6J.js";import"./chunk-KUE46HTH.js";import"./chunk-GLUWATL5.js";import"./chunk-MZKCW6CB.js";import"./chunk-6FA3GG5B.js";import"./chunk-SV7ZBEK2.js";import"./chunk-2MEOUS24.js";import"./chunk-HNQPEOJD.js";import"./chunk-RCT3O3HQ.js";import"./chunk-UGOK7VTC.js";import"./chunk-TBODQT4W.js";import"./chunk-5HPZGLOL.js";import"./chunk-ZFJWA4JK.js";import"./chunk-X2J2P5ZT.js";import{a as i}from"./chunk-FTQLQJQV.js";import{createHash as j,randomBytes as L}from"node:crypto";import{createServer as B}from"node:http";function D(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}i(D,"formatOrganizationLine");function H(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}i(H,"formatOrganizationMemberLine");function W(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}i(W,"formatOrganizationMcpServerLine");var F=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function b(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}i(b,"normalizeMcpResourceUrl");function R(e,t){let r=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(r)return b(r);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return b(e.resourceUrl)}i(R,"resolveMcpProbeResourceUrl");function v(e,t){let r=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return r?b(r):new URL(e).origin}i(v,"resolveMcpProbeOrigin");function U(e=32){return L(e).toString("base64url")}i(U,"randomOauthToken");function G(e){return j("sha256").update(e).digest("base64url")}i(G,"buildMcpOauthPkceChallenge");function V(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...F];let r=t.split(/[,\s]+/g).map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("scope must include at least one OAuth scope");return r}i(V,"parseMcpOAuthScopes");function q(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}i(q,"resolveMcpOAuthClientId");function Y(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}i(Y,"resolveMcpOAuthTimeoutMs");function Z(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}i(Z,"resolveMcpOAuthCallbackPort");function E(e){return new Promise((t,r)=>{e.close(o=>{o?r(o):t()})})}i(E,"closeServer");async function K(e){let t=!1,r=null,o=null,s=null,n=new Promise((u,l)=>{o=u,s=l}),a=i((u,l,g,m,p)=>{if(t){u.writeHead(204).end();return}t=!0,u.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),u.end(g),r&&clearTimeout(r),m?o?.(m):s?.(p??new Error("oauth_callback_failed"))},"settle"),c=B((u,l)=>{let g=u.headers.host??"127.0.0.1",m=new URL(u.url??"/",`http://${g}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let p=m.searchParams.get("state")??"",f=m.searchParams.get("error")??"",w=m.searchParams.get("code")??"";if(p!==e.expectedState){a(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(f){a(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${f}`));return}if(!w){a(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}a(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:w,state:p})});await new Promise((u,l)=>{let g=i(p=>{c.off("listening",m),l(p)},"onError"),m=i(()=>{c.off("error",g),u()},"onListening");c.once("error",g),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let d=c.address();if(!d||typeof d.port!="number")throw await E(c),new Error("oauth_callback_listener_failed");return r=setTimeout(()=>{t||(t=!0,s?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:i(async()=>{r&&clearTimeout(r),await E(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${d.port}/callback`,waitForCallback:i(()=>n,"waitForCallback")}}i(K,"startMcpOAuthCallbackListener");function Q(e){x(e)}i(Q,"openUrlWithSystemBrowser");function X(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}i(X,"buildMcpOAuthAuthorizeUrl");async function ee(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let r=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),o=await N(r);if(!r.ok)throw new Error(`oauth_token_exchange_failed:${r.status}:${JSON.stringify(o)}`);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("oauth_token_exchange_invalid_response");let s=o;if(typeof s.access_token!="string"||!s.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:s.access_token,...typeof s.expires_in=="number"?{expires_in:s.expires_in}:{},...typeof s.refresh_token=="string"?{refresh_token:s.refresh_token}:{},...typeof s.scope=="string"?{scope:s.scope}:{},...typeof s.token_type=="string"?{token_type:s.token_type}:{}}}i(ee,"exchangeMcpOAuthAuthorizationCode");async function N(e){let t=await e.text().catch(()=>"");if(!t)return null;let r=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return t}return t}i(N,"readMcpProbeBody");async function P(e,t={}){let r=await fetch(e,t);return{url:e,status:r.status,ok:r.ok,headers:{contentType:r.headers.get("content-type"),location:r.headers.get("location"),wwwAuthenticate:r.headers.get("www-authenticate")},body:await N(r)}}i(P,"fetchMcpProbe");function te(e,t,r){return r?{jsonrpc:"2.0",id:e,method:t,params:r}:{jsonrpc:"2.0",id:e,method:t}}i(te,"buildMcpJsonRpcRequest");function T(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let r=_(t,"arguments");if(!r||typeof r!="object"||Array.isArray(r))throw new Error("arguments must be a JSON object");return r}i(T,"parseMcpToolArguments");async function z(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),P(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(te(e.id,e.method,e.params))})}i(z,"postMcpJsonRpcProbe");async function A(e){let t=b(e.resourceUrl),r=b(e.origin),o=`${t}/.well-known/oauth-protected-resource`,s=`${r}/.well-known/oauth-authorization-server`,[n,a,c,d,u,l,g]=await Promise.all([P(o),P(s),P(t),z({resourceUrl:t,id:1,method:"initialize"}),z({resourceUrl:t,id:2,method:"tools/list"}),z({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?z({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:r,protectedResource:n,authorizationServer:a,directGetChallenge:c,initialize:d,toolsList:u,unauthenticatedToolCall:l,...g?{authenticatedToolCall:g}:{}}}i(A,"probeOrganizationMcp");function re(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}i(re,"parseOrganizationRole");function ne(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}i(ne,"buildOrganizationCreateInput");function oe(e){let t={},r=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(r&&(t.displayName=r),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let o=e.status.trim();if(o!=="active"&&o!=="disabled"&&o!=="archived")throw new Error("status must be active, disabled, or archived");t.status=o}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}i(oe,"buildOrganizationUpdateInput");function ie(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:re(e.role)}}i(ie,"buildOrganizationMemberInput");function ae(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:S(e.toolset)}:{}}}i(ae,"buildOrganizationMcpGenerateInput");async function ge(e,t){let r=t[0]||"list",o=await M(e),s=O(e.json);if(r==="list"){let n=await o.listOrganizations();if(s){console.log(JSON.stringify({organizations:n},null,2));return}if(n.length===0){console.log("no organizations found");return}for(let a of n)console.log(D(a));return}if(r==="create"){let n=await o.createOrganization(ne(e));console.log(JSON.stringify({organization:n},null,2));return}if(r==="get"){let n=t[1];if(!n)throw new Error("usage: organizations get <slug>");let a=await o.getOrganization(n);console.log(JSON.stringify({organization:a},null,2));return}if(r==="update"){let n=t[1];if(!n)throw new Error("usage: organizations update <slug> [--name <name>]");let a=await o.updateOrganization(n,oe(e));console.log(JSON.stringify({organization:a},null,2));return}if(r==="members"||r==="member-list"){let n=t[1];if(!n)throw new Error("usage: organizations members <slug>");let a=await o.listOrganizationMembers(n);if(s){console.log(JSON.stringify({members:a},null,2));return}if(a.length===0){console.log("no organization members found");return}for(let c of a)console.log(H(c));return}if(r==="member-upsert"||r==="member-add"){let n=t[1];if(!n)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let a=await o.upsertOrganizationMember(n,ie(e));console.log(JSON.stringify({member:a},null,2));return}if(r==="mcp-get"||r==="mcp-server"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-get <slug>");let a=await o.getOrganizationMcpServer(n);if(s){console.log(JSON.stringify({mcpServer:a},null,2));return}console.log(W(a));return}if(r==="mcp-generate"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let a=await o.generateOrganizationMcpServer(n,ae(e));console.log(JSON.stringify({mcpServer:a},null,2));return}if(r==="mcp-probe"||r==="mcp-inspect"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let a=await o.getOrganizationMcpServer(n),c=R(a,e),d=v(c,e),u=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=T(e),g=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await A({resourceUrl:c,origin:d,toolName:u,toolArguments:l,...g?{accessToken:g}:{}});console.log(JSON.stringify({mcpServer:a,probe:m},null,2));return}if(r==="mcp-authorize"||r==="mcp-oauth"){let n=t[1];if(!n)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let a=await o.getOrganizationMcpServer(n),c=R(a,e),d=v(c,e),u=q(e),l=V(e),g=U(18),m=U(48),p=G(m),f=await K({expectedState:g,port:Z(e),timeoutMs:Y(e)}),w=X({authorizationEndpoint:`${d}/oauth/authorize`,clientId:u,codeChallenge:p,redirectUri:f.redirectUri,resourceUrl:c,scopes:l,state:g});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(w),console.error(`Waiting for OAuth callback on ${f.redirectUri}`),O(e.open))try{Q(w)}catch(y){console.error(`Unable to open a browser automatically: ${y instanceof Error?y.message:String(y)}`)}try{let y=await f.waitForCallback(),h=await ee({clientId:u,code:y.code,codeVerifier:m,origin:d,redirectUri:f.redirectUri}),C=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",I=T(e),$=await A({accessToken:h.access_token,origin:d,resourceUrl:c,toolArguments:I,toolName:C}),J=O(e.printToken);console.log(JSON.stringify({mcpServer:a,oauth:{accessTokenReceived:!0,clientId:u,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...J?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:$},null,2))}finally{await f.close()}return}if(r==="mcp-rotate"||r==="mcp-disable"||r==="mcp-enable"){let n=t[1];if(!n)throw new Error(`usage: organizations ${r} <slug>`);let a=r==="mcp-rotate"?await o.rotateOrganizationMcpServer(n):r==="mcp-disable"?await o.disableOrganizationMcpServer(n):await o.enableOrganizationMcpServer(n);console.log(JSON.stringify({mcpServer:a},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}i(ge,"runOrganizationsCommand");export{F as DEFAULT_MCP_AUTHORIZE_SCOPES,te as buildMcpJsonRpcRequest,X as buildMcpOAuthAuthorizeUrl,G as buildMcpOauthPkceChallenge,ne as buildOrganizationCreateInput,ae as buildOrganizationMcpGenerateInput,ie as buildOrganizationMemberInput,oe as buildOrganizationUpdateInput,E as closeServer,ee as exchangeMcpOAuthAuthorizationCode,P as fetchMcpProbe,D as formatOrganizationLine,W as formatOrganizationMcpServerLine,H as formatOrganizationMemberLine,b as normalizeMcpResourceUrl,Q as openUrlWithSystemBrowser,V as parseMcpOAuthScopes,T as parseMcpToolArguments,re as parseOrganizationRole,z as postMcpJsonRpcProbe,A as probeOrganizationMcp,U as randomOauthToken,N as readMcpProbeBody,Z as resolveMcpOAuthCallbackPort,q as resolveMcpOAuthClientId,Y as resolveMcpOAuthTimeoutMs,v as resolveMcpProbeOrigin,R as resolveMcpProbeResourceUrl,ge as runOrganizationsCommand,K as startMcpOAuthCallbackListener};
|