omics-os 0.0.0-stage → 1.3.0
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/LICENSE +664 -0
- package/README.md +385 -2
- package/package.json +38 -4
- package/packages/cli/dist/index.js +154 -0
- package/packages/cloud-client/dist/agents.d.ts +20 -0
- package/packages/cloud-client/dist/agents.js +69 -0
- package/packages/cloud-client/dist/apiClient.d.ts +44 -0
- package/packages/cloud-client/dist/apiClient.js +368 -0
- package/packages/cloud-client/dist/auth.d.ts +76 -0
- package/packages/cloud-client/dist/auth.js +462 -0
- package/packages/cloud-client/dist/biovault/approval.d.ts +40 -0
- package/packages/cloud-client/dist/biovault/approval.js +38 -0
- package/packages/cloud-client/dist/biovault/assurance.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/assurance.js +14 -0
- package/packages/cloud-client/dist/biovault/client.d.ts +76 -0
- package/packages/cloud-client/dist/biovault/client.js +212 -0
- package/packages/cloud-client/dist/biovault/compat.d.ts +29 -0
- package/packages/cloud-client/dist/biovault/compat.js +90 -0
- package/packages/cloud-client/dist/biovault/entries.d.ts +143 -0
- package/packages/cloud-client/dist/biovault/entries.js +359 -0
- package/packages/cloud-client/dist/biovault/errors.d.ts +18 -0
- package/packages/cloud-client/dist/biovault/errors.js +90 -0
- package/packages/cloud-client/dist/biovault/fields.d.ts +7 -0
- package/packages/cloud-client/dist/biovault/fields.js +42 -0
- package/packages/cloud-client/dist/biovault/identity.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/identity.js +43 -0
- package/packages/cloud-client/dist/biovault/index.d.ts +15 -0
- package/packages/cloud-client/dist/biovault/index.js +16 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.d.ts +32 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.js +118 -0
- package/packages/cloud-client/dist/biovault/pending.d.ts +41 -0
- package/packages/cloud-client/dist/biovault/pending.js +208 -0
- package/packages/cloud-client/dist/biovault/preCommit.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/preCommit.js +10 -0
- package/packages/cloud-client/dist/biovault/provenance.d.ts +45 -0
- package/packages/cloud-client/dist/biovault/provenance.js +55 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.d.ts +3981 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.js +3632 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.d.ts +2326 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.js +491 -0
- package/packages/cloud-client/dist/biovault/wireShape.d.ts +25 -0
- package/packages/cloud-client/dist/biovault/wireShape.js +88 -0
- package/packages/cloud-client/dist/bootstrap.d.ts +4 -0
- package/packages/cloud-client/dist/bootstrap.js +19 -0
- package/packages/cloud-client/dist/config.d.ts +44 -0
- package/packages/cloud-client/dist/config.js +309 -0
- package/packages/cloud-client/dist/credentials.d.ts +96 -0
- package/packages/cloud-client/dist/credentials.js +395 -0
- package/packages/cloud-client/dist/editor.d.ts +77 -0
- package/packages/cloud-client/dist/editor.js +278 -0
- package/packages/cloud-client/dist/errors.d.ts +27 -0
- package/packages/cloud-client/dist/errors.js +102 -0
- package/packages/cloud-client/dist/exports.d.ts +19 -0
- package/packages/cloud-client/dist/exports.js +85 -0
- package/packages/cloud-client/dist/featureFlags.d.ts +10 -0
- package/packages/cloud-client/dist/featureFlags.js +36 -0
- package/packages/cloud-client/dist/files.d.ts +35 -0
- package/packages/cloud-client/dist/files.js +109 -0
- package/packages/cloud-client/dist/index.d.ts +29 -0
- package/packages/cloud-client/dist/index.js +22 -0
- package/packages/cloud-client/dist/multipartUpload.d.ts +99 -0
- package/packages/cloud-client/dist/multipartUpload.js +624 -0
- package/packages/cloud-client/dist/projects.d.ts +42 -0
- package/packages/cloud-client/dist/projects.js +119 -0
- package/packages/cloud-client/dist/resources.d.ts +8 -0
- package/packages/cloud-client/dist/resources.js +26 -0
- package/packages/cloud-client/dist/sessions.d.ts +67 -0
- package/packages/cloud-client/dist/sessions.js +187 -0
- package/packages/cloud-client/dist/templates.d.ts +4 -0
- package/packages/cloud-client/dist/templates.js +12 -0
- package/packages/cloud-client/dist/types.d.ts +431 -0
- package/packages/cloud-client/dist/types.js +94 -0
- package/packages/cloud-client/dist/uploads.d.ts +93 -0
- package/packages/cloud-client/dist/uploads.js +61 -0
- package/packages/cloud-client/dist/vault.d.ts +20 -0
- package/packages/cloud-client/dist/vault.js +43 -0
- package/packages/cloud-client/dist/vectorSearch.d.ts +3 -0
- package/packages/cloud-client/dist/vectorSearch.js +12 -0
- package/packages/tui/dist/lobster.mjs +273 -0
- package/skills/omics-os-cloud/SKILL.md +24 -0
- package/skills/omics-os-lobster/SKILL.md +24 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "module";
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
var Cc=Object.create;var Mn=Object.defineProperty;var qc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Oc=Object.getPrototypeOf,$c=Object.prototype.hasOwnProperty;var Wt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var rt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fn=(t,e)=>{for(var r in e)Mn(t,r,{get:e[r],enumerable:!0})},Tc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ac(e))!$c.call(t,o)&&o!==r&&Mn(t,o,{get:()=>e[o],enumerable:!(n=qc(e,o))||n.enumerable});return t};var Rc=(t,e,r)=>(r=t!=null?Cc(Oc(t)):{},Tc(e||!t||!t.__esModule?Mn(r,"default",{value:t,enumerable:!0}):r,t));var Gt=rt(Bn=>{var $r=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Vn=class extends $r{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Bn.CommanderError=$r;Bn.InvalidArgumentError=Vn});var Tr=rt(Hn=>{var{InvalidArgumentError:jc}=Gt(),zn=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new jc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ic(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Hn.Argument=zn;Hn.humanReadableArgName=Ic});var Gn=rt(Wn=>{var{humanReadableArgName:Pc}=Tr(),Jn=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(o=>!o._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((o,i)=>o.name().localeCompare(i.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(o=>!o.hidden),n=e._getHelpOption();if(n&&!n.hidden){let o=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!o&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!o&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(i=>!i.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Pc(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(o)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(o)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(o)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(o)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth??80;function i(d,p){return r.formatItem(d,n,p,r)}let s=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(s=s.concat([r.boxWrap(r.styleCommandDescription(a),o),""]));let l=r.visibleArguments(e).map(d=>i(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));l.length>0&&(s=s.concat([r.styleTitle("Arguments:"),...l,""]));let u=r.visibleOptions(e).map(d=>i(r.styleOptionTerm(r.optionTerm(d)),r.styleOptionDescription(r.optionDescription(d))));if(u.length>0&&(s=s.concat([r.styleTitle("Options:"),...u,""])),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(p=>i(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));d.length>0&&(s=s.concat([r.styleTitle("Global Options:"),...d,""]))}let c=r.visibleCommands(e).map(d=>i(r.styleSubcommandTerm(r.subcommandTerm(d)),r.styleSubcommandDescription(r.subcommandDescription(d))));return c.length>0&&(s=s.concat([r.styleTitle("Commands:"),...c,""])),s.join(`
|
|
5
|
+
`)}displayWidth(e){return $s(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,r,n,o){let s=" ".repeat(2);if(!n)return s+e;let a=e.padEnd(r+e.length-o.displayWidth(e)),l=2,c=(this.helpWidth??80)-r-l-2,d;return c<this.minWidthToWrap||o.preformatted(n)?d=n:d=o.boxWrap(n,c).replace(/\n/g,`
|
|
6
|
+
`+" ".repeat(r+l)),s+a+" ".repeat(l)+d.replace(/\n/g,`
|
|
7
|
+
${s}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),o=/[\s]*[^\s]+/g,i=[];return n.forEach(s=>{let a=s.match(o);if(a===null){i.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let d=this.displayWidth(c);if(u+d<=r){l.push(c),u+=d;return}i.push(l.join(""));let p=c.trimStart();l=[p],u=this.displayWidth(p)}),i.push(l.join(""))}),i.join(`
|
|
8
|
+
`)}};function $s(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}Wn.Help=Jn;Wn.stripColor=$s});var Qn=rt(Xn=>{var{InvalidArgumentError:Nc}=Gt(),Kn=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Lc(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Nc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Ts(this.name().replace(/^no-/,"")):Ts(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Yn=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,i=o!==void 0?o:!1;return r.negate===(i===e)}};function Ts(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Lc(t){let e,r,n=/^-[^-]$/,o=/^--[^-]/,i=t.split(/[ |,]+/).concat("guard");if(n.test(i[0])&&(e=i.shift()),o.test(i[0])&&(r=i.shift()),!e&&n.test(i[0])&&(e=i.shift()),!e&&o.test(i[0])&&(e=r,r=i.shift()),i[0].startsWith("-")){let s=i[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
|
|
9
|
+
- a short flag is a single dash and a single character
|
|
10
|
+
- either use a single dash and a single character (for a short flag)
|
|
11
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
|
|
12
|
+
- too many short flags`):o.test(s)?new Error(`${a}
|
|
13
|
+
- too many long flags`):new Error(`${a}
|
|
14
|
+
- unrecognised flag format`)}if(e===void 0&&r===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:r}}Xn.Option=Kn;Xn.DualOptions=Yn});var js=rt(Rs=>{function Dc(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let i=1;t[o-1]===e[n-1]?i=0:i=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+i),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function Uc(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let n=[],o=3,i=.4;return e.forEach(s=>{if(s.length<=1)return;let a=Dc(t,s),l=Math.max(t.length,s.length);(l-a)/l>i&&(a<o?(o=a,n=[s]):a===o&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),r&&(n=n.map(s=>`--${s}`)),n.length>1?`
|
|
15
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
16
|
+
(Did you mean ${n[0]}?)`:""}Rs.suggestSimilar=Uc});var Ls=rt(no=>{var Mc=Wt("node:events").EventEmitter,Zn=Wt("node:child_process"),Pe=Wt("node:path"),Rr=Wt("node:fs"),B=Wt("node:process"),{Argument:Fc,humanReadableArgName:Vc}=Tr(),{CommanderError:eo}=Gt(),{Help:Bc,stripColor:zc}=Gn(),{Option:Is,DualOptions:Hc}=Qn(),{suggestSimilar:Ps}=js(),to=class t extends Mc{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:r=>B.stdout.write(r),writeErr:r=>B.stderr.write(r),outputError:(r,n)=>n(r),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>ro()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>ro()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:r=>zc(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,i=n;typeof o=="object"&&o!==null&&(i=o,o=null),i=i||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return o&&(l.description(o),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),o?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Bc,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
17
|
+
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Fc(e,r)}argument(e,r,n,o){let i=this.createArgument(e,r);return typeof n=="function"?i.default(o).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,o]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",s=this.createCommand(n);return s.helpOption(!1),o&&s.arguments(o),i&&s.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
18
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new eo(e,r,n)),B.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,i=n.slice(0,o);return this._storeOptionsAsProperties?i[o]=this:i[o]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Is(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(i){if(i.code==="commander.invalidArgument"){let s=`${o} ${i.message}`;this.error(s,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
19
|
+
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=o=>[o.name()].concat(o.aliases()),n=r(e).find(o=>this._findCommand(o));if(n){let o=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let o=(i,s,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,s):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let s=`error: option '${e.flags}' argument '${i}' is invalid.`;o(i,s,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let s=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;o(i,s,"env")}),this}_optionEx(e,r,n,o,i){if(typeof r=="object"&&r instanceof Is)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(r,n);if(s.makeOptionMandatory(!!e.mandatory),typeof o=="function")s.default(i).argParser(o);else if(o instanceof RegExp){let a=o;o=(l,u)=>{let c=a.exec(l);return c?c[0]:u},s.default(i).argParser(o)}else s.default(o);return this.addOption(s)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){B.versions?.electron&&(r.from="electron");let o=B.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(r.from="eval")}e===void 0&&(e=B.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":B.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
20
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,r,n){if(Rr.existsSync(e))return;let o=r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
|
|
21
|
+
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
22
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
23
|
+
- ${o}`;throw new Error(i)}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function i(c,d){let p=Pe.resolve(c,d);if(Rr.existsSync(p))return p;if(o.includes(Pe.extname(d)))return;let f=o.find(h=>Rr.existsSync(`${p}${h}`));if(f)return`${p}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=Rr.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=Pe.resolve(Pe.dirname(c),a)}if(a){let c=i(a,s);if(!c&&!e._executableFile&&this._scriptPath){let d=Pe.basename(this._scriptPath,Pe.extname(this._scriptPath));d!==this._name&&(c=i(a,`${d}-${e._name}`))}s=c||s}n=o.includes(Pe.extname(s));let l;B.platform!=="win32"?n?(r.unshift(s),r=Ns(B.execArgv).concat(r),l=Zn.spawn(B.argv[0],r,{stdio:"inherit"})):l=Zn.spawn(s,r,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,e._name),r.unshift(s),r=Ns(B.execArgv).concat(r),l=Zn.spawn(B.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{B.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new eo(c,"commander.executeSubCommandAsync","(close)")):B.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,e._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!u)B.exit(1);else{let d=new eo(1,"commander.executeSubCommandAsync","(error)");d.nestedError=c,u(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0}),o._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,o,"preSubcommand"),i=this._chainOrCall(i,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,i)=>{let s=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,o,i,a)}return s};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let i=n.defaultValue;n.variadic?o<this.args.length?(i=this.args.slice(o),n.parseArg&&(i=i.reduce((s,a)=>e(n,a,s),n.defaultValue))):i===void 0&&(i=[]):o<this.args.length&&(i=this.args[o],n.parseArg&&(i=e(n,i,n.defaultValue))),r[o]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(s=>{o.push({hookedCommand:i,callback:s})})}),r==="postAction"&&o.reverse(),o.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{o=this._chainOrCall(o,()=>i(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(i,e,r)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(i))o(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(i=>n.conflictsWith.includes(i.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,i=e.slice();function s(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){o===n&&o.push(l),o.push(...i);break}if(a&&!s(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let c=i.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;i.length>0&&!s(i[0])&&(c=i.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(s(l)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){o.push(l),i.length>0&&o.push(...i);break}o.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
24
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
25
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
26
|
+
`),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,i=n.code||"commander.error";this._exit(o,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in B.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,B.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Hc(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=s=>{let a=s.attributeName(),l=this.getOptionValue(a),u=this.options.find(d=>d.negate&&a===d.attributeName()),c=this.options.find(d=>!d.negate&&a===d.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||s},o=s=>{let a=n(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],i=this;do{let s=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);o=o.concat(s),i=i.parent}while(i&&!i._enablePositionalOptions);r=Ps(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(i=>{o.push(i.name()),i.alias()&&o.push(i.alias())}),r=Ps(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
27
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let o=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>Vc(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Pe.basename(e,Pe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp(),n=this._getOutputContext(e);r.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let o=r.formatHelp(this,r);return n.hasColors?o:this._outputConfiguration.stripColor(o)}_getOutputContext(e){e=e||{};let r=!!e.error,n,o,i;return r?(n=a=>this._outputConfiguration.writeErr(a),o=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),o=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(o||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:o,helpWidth:i}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getOutputContext(e),o={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",o)),this.emit("beforeHelp",o);let i=this.helpInformation({error:n.error});if(r&&(i=r(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",o),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",o))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=Number(B.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
28
|
+
Expecting one of '${n.join("', '")}'`);let o=`${e}Help`;return this.on(o,i=>{let s;typeof r=="function"?s=r({error:i.error,command:i.command}):s=r,s&&i.write(`${s}
|
|
29
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(o=>r.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ns(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?o=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],n=i[3],o=i[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}function ro(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0}no.Command=to;no.useColor=ro});var Fs=rt(we=>{var{Argument:Ds}=Tr(),{Command:oo}=Ls(),{CommanderError:Jc,InvalidArgumentError:Us}=Gt(),{Help:Wc}=Gn(),{Option:Ms}=Qn();we.program=new oo;we.createCommand=t=>new oo(t);we.createOption=(t,e)=>new Ms(t,e);we.createArgument=(t,e)=>new Ds(t,e);we.Command=oo;we.Option=Ms;we.Argument=Ds;we.Help=Wc;we.CommanderError=Jc;we.InvalidArgumentError=Us;we.InvalidOptionArgumentError=Us});var Vs=Rc(Fs(),1),{program:o_,createCommand:i_,createArgument:s_,createOption:a_,CommanderError:l_,InvalidArgumentError:u_,InvalidOptionArgumentError:c_,Command:Bs,Argument:d_,Option:io,Help:f_}=Vs.default;var zs=["handshake","text","markdown","code","table","form","confirm","select","progress","alert","spinner","status","clear","done","agent_transition","modality_loaded","tool_execution","suspend","resume","ready","heartbeat","set_lang","completion_response","component_render","component_set_data","run_state","input","form_response","confirm_response","select_response","cancel","quit","resize","slash_command","completion_request","component_response","decision_answer"],Gc=["running","needs_decision","completed","failed","cancelled"],Kc=["cancel","decision_abandoned","decision_unsupported"];var Yc="lobster.result/1",Xc=["replay"],Qc=["cancelled","failed"],Zc=["turn"],ed=["no_final_answer","qc_flagged_cells_kept","qc_thresholds_differ","qc_thresholds_not_recorded","usage_incomplete","modalities_not_restored","no_data_file_saved","no_qc_plots","plot_view_failed","notebook_not_exported","open_question","metrics_unavailable"],td=["human","model"],rd=["","interrupt","cancelled","error"];function re(){return t=>t}var m_={"envelope required":re()(["type","version"]),"envelope.type enum":zs,"envelope.version const":1,"run_state required":["payload"],"run_state.payload required":re()(["state","run_id"]),"run_state.payload.state enum":Gc,"run_state.payload[state=cancelled] required":["reason"],"run_state.payload[state=cancelled].reason enum":Kc,"run_state.payload[state=needs_decision] required":["decision"],"run_state.payload.decision required":re()(["decision_id","request_version","question","components"]),"run_state.payload.decision.components[] required":re()(["n","component","data","fallback_prompt"]),"run_state.payload.error required":re()(["code","message","retryable"]),"component_render required":["id","payload"],"decision_answer required":["payload"],"decision_answer.payload required":re()(["decision_id","request_version","answer","source"]),"decision_answer.payload.source enum":td,"component_render.payload required":re()(["component"]),"done.payload.summary enum":rd,"result required":re()(["schema_version","engine","session_id","run_id","response"]),"result.schema_version const":Yc,"result.engine required":re()(["name","version"]),"result.engine.name const":"lobster-ai","result.modality_details[] required":re()(["name"]),"result.request required":re()(["instruction","channel"]),"result.request.model_source enum":Xc,"result.request.unfinished_instructions[] required":re()(["instruction","outcome"]),"result.request.unfinished_instructions[].outcome enum":Qc,"result.decisions[] required":re()(["question","answer","source","channel"]),"result.metrics.tokens.scope enum":Zc,"result.steps[] required":re()(["seq","tool","parameters"]),"result.warnings[] required":re()(["code","message"]),"result.warnings[].code enum":ed,"result.files_written[] required":re()(["path","relative","category","size_bytes"]),"result.plan required":re()(["requested","asked"]),"result.loaded_files[] required":re()(["path","modality"])},nd=new Set(zs),Hs=t=>typeof t=="string"&&nd.has(t);var Kt=class{buffer="";line=0;lastSeq=0;push(e){this.buffer+=e;let r=this.buffer.split(`
|
|
30
|
+
`);return this.buffer=r.pop()??"",r.flatMap(n=>this.decode(n))}end(){let e=this.buffer;return this.buffer="",e?this.decode(e):[]}decode(e){if(this.line+=1,!e.trim())return[];let r;try{r=JSON.parse(e)}catch{throw Object.assign(new Error(`protocol: line ${this.line} is not JSON`),{text:e})}if(r?.version!==1)throw new Error(`protocol: line ${this.line} has version ${JSON.stringify(r?.version)}, expected ${1}`);if(typeof r.seq=="number"){if(r.seq<=this.lastSeq)throw new Error(`protocol: line ${this.line} seq ${r.seq} after ${this.lastSeq}`);this.lastSeq=r.seq}return Hs(r.type)?[r]:[]}};function so(t,e=process.platform){return e==="darwin"?["open",[t]]:e!=="win32"?["xdg-open",[t]]:/^https?:\/\//i.test(t)?["rundll32",["url.dll,FileProtocolHandler",t]]:["cmd",["/c","start","",t]]}import{spawn as od}from"node:child_process";function Js(t){let e=["agent","--stdio"];return t.sessionId&&e.push("--session",t.sessionId),t.workspace&&e.push("--workspace",t.workspace),t.provider&&e.push("--provider",t.provider),t.model&&e.push("--model",t.model),e}var jr=class{engineStdin;decoder=new Kt;queue=[];waiters=[];ended=!1;failure;constructor(e,r){this.engineStdin=r,e.setEncoding("utf8"),e.on("data",n=>this.accept(()=>this.decoder.push(n))),e.on("end",()=>{this.accept(()=>this.decoder.end()),this.ended=!0,this.wake()}),e.on("error",n=>this.fail(n)),r.on("error",n=>this.fail(n))}next(e){if(this.failure)return Promise.reject(this.failure);let r=this.queue.shift();return r||this.ended?Promise.resolve(r):e?.aborted?Promise.reject(e.reason):new Promise((n,o)=>{let i=()=>{let l=this.waiters.indexOf(a);l>=0&&this.waiters.splice(l,1),o(e.reason)},s=l=>u=>{e?.removeEventListener("abort",i),l(u)},a={resolve:s(n),reject:s(o)};this.waiters.push(a),e?.addEventListener("abort",i,{once:!0})})}send(e){this.engineStdin.write(e)}accept(e){try{this.queue.push(...e())}catch(r){this.fail(r);return}this.wake()}wake(){for(;this.waiters.length&&(this.queue.length||this.ended);)this.waiters.shift().resolve(this.queue.shift())}fail(e){this.failure=e;for(let r of this.waiters.splice(0))r.reject(e)}},Ws=["OMICSOS_API_KEY","LOBSTER_TOKEN","LOBSTER_CLOUD_TOKEN"],Gs="OMICS_OS_API_KEY";function ze(t,e={}){let r={...t};for(let n of Ws)delete r[n];return e.engine||delete r[Gs],r}function ao(t){let e=ze(t.env??process.env,{engine:!0}),r=od(t.command??"lobster",Js(t),{stdio:["pipe","pipe","ignore"],env:e});return r.on("error",n=>r.stdout?.destroy(n)),{session:new jr(r.stdout,r.stdin),child:r}}import{execFile as id}from"node:child_process";import{closeSync as sd,openSync as ad,readFileSync as ld,readSync as ud,realpathSync as lo,statSync as cd}from"node:fs";import dd from"node:os";import Yt from"node:path";var Xs="https://docs.omics-os.com/docs/cloud/cli",Ks="1.3";function fd(t,e){return new Promise(r=>id(t,["--version"],{env:e??process.env,timeout:3e3,encoding:"utf8"},(n,o)=>r(n?void 0:o)))}function pd(t){let e=a=>`needs Lobster AI ${Ks} or later (${a?`found ${a}`:"this one has no 'agent' command"})`;if(t===void 0)return e();let r=/(?:lobster|version)\D*?(\d+\.\d+(?:\.\d+)?\S*)/i.exec(t)?.[1]??/(\d+\.\d+(?:\.\d+)?\S*)/.exec(t)?.[1];if(!r)return"exited with code 2 before the handshake";let[n=0,o=0]=r.split(".").map(a=>Number.parseInt(a,10)),[i=0,s=0]=Ks.split(".").map(a=>Number.parseInt(a,10));return n<i||n===i&&o<s?e(r):"exited with code 2 before the handshake"}var Ir="omics-os shim",Ys=/node_modules[\\/](@omicsos[\\/]lobster|omics-os)[\\/]/;function Qs(t){let e;try{e=ad(t,"r");let r=Buffer.alloc(1024);return r.toString("utf8",0,ud(e,r,0,r.length,0))}catch{return""}finally{e!==void 0&&sd(e)}}function He(t){return Qs(t).includes(Ir)}function Pr(t){let e=t;try{e=lo(t)}catch{}return Ys.test(e)||Ys.test(Qs(t))||He(t)}var Zs=t=>{try{return cd(t).isFile()}catch{return!1}};function Xt(t,e,r){let n=r==="win32"?[".exe",".cmd",".bat",""].map(i=>t+i):[t];return e.split(r==="win32"?";":":").filter(i=>Yt.isAbsolute(i)).flatMap(i=>n.map(s=>Yt.join(i,s)).filter(Zs))}var md=/^(.*node_modules[\\/]@omicsos[\\/]lobster)[\\/]/;function ea(t=process.env,e=process.platform){let r=[];for(let n of Xt("lobster",t.PATH??"",e)){let o;try{o=lo(n)}catch{continue}let i=md.exec(o)?.[1];if(!i)continue;let s="unknown";try{s=String(JSON.parse(ld(Yt.join(i,"package.json"),"utf8")).version??"unknown")}catch{}r.push({path:n,version:s})}return r}function Nr(t=process.env,e=process.platform){let r=t.OMICS_OS_LOBSTER_BIN;if(r)return[Yt.resolve(r)];let n=t.HOME??t.USERPROFILE??dd.homedir(),o=Yt.join(n,".local","bin",e==="win32"?"lobster.exe":"lobster"),i=new Set;return[...Xt("lobster",t.PATH??"",e),o].filter(s=>{if(!Zs(s)||Pr(s))return!1;let a=lo(s);return!i.has(a)&&!!i.add(a)})}async function ta(t,e={}){if(Pr(t))return{ok:!1,path:t,reason:"is an Omics-OS command, not a Lobster AI engine"};let{session:r,child:n}=ao({...e,command:t}),o=new Promise(u=>n.once("exit",(c,d)=>u(c===null?`was stopped by ${d}`:`exited with code ${c}`))),i=u=>(n.kill(),{ok:!1,path:t,reason:u}),s;try{s=await r.next()}catch(u){let{message:c,code:d,text:p}=u;return i(typeof p=="string"?`did not speak Lobster protocol v1: its first line was ${hd(p)}`:c.startsWith("protocol:")?`did not speak Lobster protocol v1 (${c})`:`could not be started (${d??c})`)}if(!s){let u=new Promise(p=>setTimeout(()=>p("closed its output"),2e3).unref()),c=await Promise.race([o,u]),d=/^exited with code (\d+)$/.exec(c)?.[1];if(d!==void 0){let p=await fd(t,e.env),f=p===void 0?void 0:/^@omicsos\/lobster\s+(\S+)/m.exec(p)?.[1];if(f)return n.kill(),{ok:!1,path:t,reason:`is the old npm client @omicsos/lobster ${f}, not a Lobster AI engine`,oldNpmClient:f};if(d==="2")return i(pd(p))}return i(`${c} before the handshake`)}if(s.type!=="handshake")return i(`sent '${s.type}' first, not a handshake`);let a=s.payload?.protocol_version;if(a!==1)return i(`speaks protocol ${JSON.stringify(a)}, not ${1}`);let l=s.payload?.engine_version;return{ok:!0,path:t,engineVersion:typeof l=="string"?l:void 0,session:r,child:n}}function hd(t){let e=t.replace(/[\u0000-\u001f\u007f]/g,"").trim();return`"${e.length>80?`${e.slice(0,80)}\u2026`:e}"`}var gd="lobster.commands/1",_d=["cli","slash","stdio"],yd=["string","integer","number","boolean","path","choice"];function yt(t,e){throw new Error(`Command manifest: ${t} ${e}`)}function bt(t,e){return typeof t!="string"&&yt(e,"must be a string"),t}function Qt(t,e,r){if(t!==void 0)return e(t)||yt(r,"has the wrong type"),t}var uo=t=>typeof t=="string",ra=t=>typeof t=="boolean",na=t=>Array.isArray(t)&&t.every(uo);function oa(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function bd(t,e){let r=bt(t?.type,`${e}.type`);return yd.includes(r)||yt(`${e}.type`,`"${r}" is not a known type`),oa({name:bt(t.name,`${e}.name`),type:r,required:Qt(t.required,ra,`${e}.required`),choices:Qt(t.choices,na,`${e}.choices`),help:Qt(t.help,uo,`${e}.help`)})}function wd(t,e){let r=t?.surfaces;return(!na(r)||!r.every(n=>_d.includes(n)))&&yt(`${e}.surfaces`,"must list cli, slash or stdio"),Array.isArray(t.args)||yt(`${e}.args`,"must be a list"),oa({name:bt(t.name,`${e}.name`),handler:bt(t.handler,`${e}.handler`),help:Qt(t.help,uo,`${e}.help`),surfaces:r,scientist_facing:Qt(t.scientist_facing,ra,`${e}.scientist_facing`),args:t.args.map((n,o)=>bd(n,`${e}.args[${o}]`))})}function ia(t){let e=t,r=e?.schema_version;if(typeof r!="string"||!/^lobster\.commands\/1(\.\d+)*$/.test(r))throw new Error(`Unsupported command manifest ${String(r)} (this omics-os reads ${gd})`);return Array.isArray(e.commands)||yt("commands","must be a list"),{schema_version:r,engine_version:bt(e.engine_version,"engine_version"),agent_interface:bt(e.agent_interface,"agent_interface"),commands:e.commands.map((n,o)=>wd(n,`commands[${o}]`))}}var sa={schema_version:"lobster.commands/1",engine_version:"1.3.0",agent_interface:"lobster agent --stdio",commands:[{name:"/analysis-dash",handler:"slash:/analysis-dash",help:"Show analysis monitoring dashboard",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/clear",handler:"slash:/clear",help:"Clear screen",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config",handler:"slash:/config",help:"Show current configuration (provider, profile, config files)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config model",handler:"slash:/config model",help:"List available Ollama models",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config model <name>",handler:"slash:/config model <name>",help:"Switch to specified Ollama model (runtime only)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config model <name> --save",handler:"slash:/config model <name> --save",help:"Switch Ollama model and persist to workspace",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config provider",handler:"slash:/config provider",help:"List available LLM providers",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config provider <name>",handler:"slash:/config provider <name>",help:"Switch to specified provider (runtime only)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/config provider <name> --save",handler:"slash:/config provider <name> --save",help:"Switch provider and persist to workspace",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/dashboard",handler:"slash:/dashboard",help:"Switch to interactive dashboard (Textual UI)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/data",handler:"slash:/data",help:"Show current data summary",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/describe",handler:"slash:/describe",help:"Show detailed information about a specific modality",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/exit",handler:"slash:/exit",help:"Exit the chat",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/export",handler:"slash:/export",help:"Export to ZIP: data + saved figures with HTML views and every recorded PNG; no new PNG is rendered, --no-png only disables generation (--force to re-serialize all)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/files",handler:"slash:/files",help:"List workspace files",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/help",handler:"slash:/help",help:"Show this help message",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/input-features",handler:"slash:/input-features",help:"Show input capabilities and navigation features",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/lang",handler:"slash:/lang",help:"Set the UI language (en, zh) for this session and the next launch",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata",handler:"slash:/metadata",help:"Show smart metadata overview with stats & next steps",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata clear",handler:"slash:/metadata clear",help:"Clear metadata (memory + workspace/metadata/)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata clear all",handler:"slash:/metadata clear all",help:"Clear ALL metadata (memory + disk + exports)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata clear exports",handler:"slash:/metadata clear exports",help:"Clear export files (workspace/exports/)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata exports",handler:"slash:/metadata exports",help:"Export files with categories & usage hints",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata list",handler:"slash:/metadata list",help:"Legacy detailed list (use overview instead)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata publications",handler:"slash:/metadata publications",help:"Publication queue status breakdown",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata samples",handler:"slash:/metadata samples",help:"Aggregated sample statistics & disease coverage",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/metadata workspace",handler:"slash:/metadata workspace",help:"Categorized file inventory across all locations",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/modalities",handler:"slash:/modalities",help:"Show detailed modality information",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/open",handler:"slash:/open",help:"Open file or folder in system default application",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/plot",handler:"slash:/plot",help:"Open plots directory or specific plot",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/plots",handler:"slash:/plots",help:"List all generated plots",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/progress",handler:"slash:/progress",help:"Show multi-task progress monitor",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue",handler:"slash:/queue",help:"Show queue status",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue clear",handler:"slash:/queue clear",help:"Clear publication queue",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue clear all",handler:"slash:/queue clear all",help:"Clear all queues (publication + download)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue clear download",handler:"slash:/queue clear download",help:"Clear download queue",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue export",handler:"slash:/queue export",help:"Export queue to workspace for persistence",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue list",handler:"slash:/queue list",help:"List queued items",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/queue load",handler:"slash:/queue load",help:"Load file into queue (supports .ris, more coming)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/read",handler:"slash:/read",help:"View file contents (inspection only)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/reset",handler:"slash:/reset",help:"Reset conversation",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/restore",handler:"slash:/restore",help:"Restore previous session datasets",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/save",handler:"slash:/save",help:"Save current state to workspace (--force to re-save all)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/session",handler:"slash:/session",help:"Show current session status",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/status",handler:"slash:/status",help:"Show subscription tier, packages, and agents",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/status-panel",handler:"slash:/status-panel",help:"Show comprehensive system status panel",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/tokens",handler:"slash:/tokens",help:"Execute /tokens command",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/tree",handler:"slash:/tree",help:"Show directory tree view",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/vector-search",handler:"slash:/vector-search",help:"Search all ontology collections (semantic vector similarity)",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace",handler:"slash:/workspace",help:"Show workspace status and information",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace info",handler:"slash:/workspace info",help:"Show dataset information",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace list",handler:"slash:/workspace list",help:"List available datasets in workspace",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace load",handler:"slash:/workspace load",help:"Load dataset or file into workspace",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace remove",handler:"slash:/workspace remove",help:"Remove modality(ies) by index, pattern, or name",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace save",handler:"slash:/workspace save",help:"Save modality to workspace",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"/workspace-info",handler:"slash:/workspace-info",help:"Show detailed workspace overview",surfaces:["slash"],scientist_facing:!0,args:[]},{name:"agent",handler:"lobster.cli_internal.commands.light.agent_commands:agent_command",help:"Run Lobster as a machine interface for other programs (NDJSON on stdin and stdout).",surfaces:["cli"],scientist_facing:!1,args:[{name:"stdio",type:"boolean",required:!1,help:"Speak protocol v1 NDJSON on stdin and stdout."},{name:"workspace",type:"path",required:!1,help:"Workspace directory. Can also be set via LOBSTER_WORKSPACE env var. Default: ./.lobster_workspace"},{name:"session-id",type:"string",required:!1,help:"Session ID to continue (use 'latest' for most recent session in workspace)"},{name:"provider",type:"string",required:!1,help:"LLM provider to use (anthropic, bedrock, ollama, gemini, azure, openai, openrouter, nebius, ollama-cloud, omics-os). Overrides auto-detection."},{name:"model",type:"string",required:!1,help:"Model to use (e.g., claude-4-sonnet, llama3:70b-instruct, mixtral:8x7b). Overrides configuration."}]},{name:"agents info",handler:"lobster.cli_internal.commands.light.agent_commands:agents_info",help:"Show detailed agent information.",surfaces:["cli"],scientist_facing:!0,args:[{name:"agent_name",type:"string",required:!0,help:"Agent name to inspect"}]},{name:"agents install",handler:"lobster.cli_internal.commands.light.agent_commands:agents_install",help:"Install an agent package and auto-enable its agents.",surfaces:["cli"],scientist_facing:!1,args:[{name:"package_name",type:"string",required:!0,help:"Package name to install"},{name:"workspace",type:"path",required:!1,help:"Path to workspace directory"}]},{name:"agents list",handler:"lobster.cli_internal.commands.light.agent_commands:agents_list",help:"List installed agents with status.",surfaces:["cli"],scientist_facing:!0,args:[{name:"workspace",type:"path",required:!1,help:"Path to workspace directory"}]},{name:"agents uninstall",handler:"lobster.cli_internal.commands.light.agent_commands:agents_uninstall",help:"Uninstall an agent package and remove its agents from config.",surfaces:["cli"],scientist_facing:!1,args:[{name:"package_name",type:"string",required:!0,help:"Package name to uninstall"},{name:"workspace",type:"path",required:!1,help:"Path to workspace directory"}]},{name:"auth login",handler:"lobster.cli_internal.commands.light.auth_commands:login",help:"Login to an LLM provider via OAuth.",surfaces:["cli"],scientist_facing:!1,args:[{name:"provider",type:"string",required:!0,help:"Provider to authenticate with (e.g., 'anthropic')."},{name:"no-browser",type:"boolean",required:!1,help:"Don't auto-open browser; print URL instead."},{name:"timeout",type:"integer",required:!1,help:"Seconds to wait for browser callback."}]},{name:"auth logout",handler:"lobster.cli_internal.commands.light.auth_commands:logout",help:"Remove stored OAuth credentials for a provider.",surfaces:["cli"],scientist_facing:!1,args:[{name:"provider",type:"string",required:!0,help:"Provider to log out from (e.g., 'anthropic')."}]},{name:"auth status",handler:"lobster.cli_internal.commands.light.auth_commands:status",help:"Show authentication status for all providers.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"chat",handler:"lobster.cli:chat",help:"Start an interactive chat session with the multi-agent system.",surfaces:["cli"],scientist_facing:!0,args:[{name:"workspace",type:"path",required:!1,help:"Workspace directory. Can also be set via LOBSTER_WORKSPACE env var. Default: ./.lobster_workspace"},{name:"session-id",type:"string",required:!1,help:"Session ID to continue (use 'latest' for most recent session in workspace)"},{name:"reasoning",type:"boolean",required:!1,help:"Show agent reasoning and thinking process"},{name:"verbose",type:"boolean",required:!1,help:"Show detailed tool usage and agent activity"},{name:"debug",type:"boolean",required:!1,help:"Enable debug mode with enhanced error reporting"},{name:"profile-timings",type:"boolean",required:!1,help:"Enable timing diagnostics for data manager operations"},{name:"provider",type:"string",required:!1,help:"LLM provider to use (anthropic, bedrock, ollama, gemini, azure, openai, openrouter, nebius, ollama-cloud, omics-os). Overrides auto-detection."},{name:"model",type:"string",required:!1,help:"Model to use (e.g., claude-4-sonnet, llama3:70b-instruct, mixtral:8x7b). Overrides configuration."},{name:"no-intro",type:"boolean",required:!1,help:"Disable the Go TUI inline intro animation (useful for automation and PTY capture)."},{name:"stream",type:"boolean",required:!1,help:"Enable real-time text streaming (default: on)"},{name:"ui",type:"string",required:!1,help:"UI mode: auto (Go TUI, then classic), go (Go TUI), classic (Rich terminal)"},{name:"classic",type:"boolean",required:!1,help:"Shorthand for --ui classic (force Rich/Textual UI)"}]},{name:"cloud account",handler:"lobster.cli_internal.commands.light.cloud_commands:account",help:"Show your Omics-OS Cloud account summary.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"cloud chat",handler:"lobster.cli_internal.commands.light.cloud_commands:chat",help:"Start an interactive cloud chat session (lobster-cli, direct connection).",surfaces:["cli"],scientist_facing:!0,args:[{name:"session-id",type:"string",required:!1,help:"Resume an existing cloud session"},{name:"token",type:"string",required:!1,help:"Override stored auth token (prefer LOBSTER_CLOUD_TOKEN env var)"},{name:"endpoint",type:"string",required:!1,help:"Custom cloud API endpoint"},{name:"stream-endpoint",type:"string",required:!1,help:"Custom stream origin (e.g., https://stream.omics-os.com)"},{name:"project-id",type:"string",required:!1,help:"Associate session with a cloud project"}]},{name:"cloud login",handler:"lobster.cli_internal.commands.light.cloud_commands:login",help:"Authenticate the Python local gateway provider with --api-key <key>.",surfaces:["cli"],scientist_facing:!1,args:[{name:"api-key",type:"string",required:!1,help:"Omics-OS API key from app.omics-os.com/account"}]},{name:"cloud logout",handler:"lobster.cli_internal.commands.light.cloud_commands:logout",help:"Log out of Omics-OS Cloud.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"cloud projects",handler:"lobster.cli_internal.commands.light.cloud_commands:projects",help:"List your Omics-OS Cloud projects (also: omics-os lobster projects list).",surfaces:["cli"],scientist_facing:!1,args:[{name:"json",type:"boolean",required:!1,help:"Output JSON"}]},{name:"cloud query",handler:"lobster.cli_internal.commands.light.cloud_commands:query",help:"Send a single query to Omics-OS Cloud (agents run on ECS Fargate).",surfaces:["cli"],scientist_facing:!0,args:[{name:"question",type:"string",required:!0,help:"Question to ask"},{name:"session-id",type:"string",required:!1,help:"Session UUID to continue (or 'latest')"},{name:"token",type:"string",required:!1,help:"Override stored auth token (prefer OMICS_OS_API_KEY env var)"},{name:"endpoint",type:"string",required:!1,help:"Custom REST API origin (e.g., https://app.omics-os.com)"},{name:"stream-endpoint",type:"string",required:!1,help:"Custom stream origin (e.g., https://stream.omics-os.com)"},{name:"stream",type:"boolean",required:!1,help:"Stream text as it arrives"},{name:"json",type:"boolean",required:!1,help:"Output JSON only on stdout"},{name:"project-id",type:"string",required:!1,help:"Associate session with a cloud project (personal projects only)"}]},{name:"cloud status",handler:"lobster.cli_internal.commands.light.cloud_commands:status",help:"Show current Omics-OS Cloud connection and usage.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"command",handler:"lobster.cli:command_cmd",help:"Execute workspace commands without an LLM session.",surfaces:["cli"],scientist_facing:!1,args:[{name:"cmd",type:"string",required:!0,help:'Command to execute, e.g. "data", "workspace list", "files"'},{name:"workspace",type:"path",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"session-id",type:"string",required:!1,help:"Session ID to load. Use 'latest' for most recent. Defaults to last session if not specified."},{name:"json",type:"boolean",required:!1,help:"Output as JSON for programmatic consumption"}]},{name:"commands",handler:"lobster.cli_internal.commands.light.manifest_commands:commands_command",help:"List Lobster's commands; --json prints the machine-readable manifest.",surfaces:["cli"],scientist_facing:!1,args:[{name:"json",type:"boolean",required:!1,help:"Print the lobster.commands/1 manifest as JSON."}]},{name:"config create-custom",handler:"lobster.cli:create_custom",help:"Interactive creation of custom configuration.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"config generate-env",handler:"lobster.cli:generate_env",help:"Generate .env template with all available options.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"config list-models",handler:"lobster.cli:list_models",help:"List all available model presets.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"config list-profiles",handler:"lobster.cli:list_profiles",help:"List all available testing profiles.",surfaces:["cli"],scientist_facing:!1,args:[]},{name:"config models",handler:"lobster.cli:config_models",help:"Interactive per-agent model configuration.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"string",required:!1,help:"Workspace path (default: current directory)"}]},{name:"config show",handler:"lobster.cli:config_show_subcommand",help:"Display current configuration including agent composition.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"string",required:!1,help:"Workspace directory to use"}]},{name:"config show-config",handler:"lobster.cli:show_config",help:"Show current runtime configuration from ConfigResolver and ProviderRegistry.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"path",required:!1,help:"Workspace path (default: current directory)"},{name:"show-all",type:"boolean",required:!1,help:"Show all configured agents regardless of license tier"}]},{name:"config test",handler:"lobster.cli:test",help:"Test LLM provider connectivity and configuration.",surfaces:["cli"],scientist_facing:!1,args:[{name:"profile",type:"string",required:!1,help:"Profile to test (optional, auto-detects if not provided)"},{name:"agent",type:"string",required:!1,help:"Specific agent to test"}]},{name:"config-test",handler:"lobster.cli:config_test",help:"Test API connectivity and validate configuration.",surfaces:["cli"],scientist_facing:!1,args:[{name:"json",type:"boolean",required:!1,help:"Output results as JSON (machine-readable)"}]},{name:"dashboard",handler:"lobster.cli:dashboard_command",help:"Launch interactive dashboard (Textual UI).",surfaces:["cli"],scientist_facing:!0,args:[{name:"workspace",type:"path",required:!1,help:"Workspace directory. Can also be set via LOBSTER_WORKSPACE env var. Default: ./.lobster_workspace"}]},{name:"init",handler:"lobster.cli:init",help:"Initialize Lobster AI configuration.",surfaces:["cli"],scientist_facing:!0,args:[{name:"folder",type:"path",required:!1,help:"Folder to set up as a project (default: the current folder)"},{name:"global",type:"boolean",required:!1,help:"Save configuration globally (~/.config/lobster/) for all workspaces"},{name:"force",type:"boolean",required:!1,help:"Overwrite existing configuration"},{name:"non-interactive",type:"boolean",required:!1,help:"Non-interactive mode for CI/CD (requires API key flags)"},{name:"use-omics-os",type:"boolean",required:!1,help:"Use Omics-OS Cloud with OMICS_OS_API_KEY or saved credentials (non-interactive mode)"},{name:"omics-os-key",type:"string",required:!1,help:"Omics-OS Cloud gateway API key (non-interactive mode; saved, not checked)"},{name:"anthropic-key",type:"string",required:!1,help:"Claude API key (non-interactive mode)"},{name:"bedrock-access-key",type:"string",required:!1,help:"AWS Bedrock access key (non-interactive mode)"},{name:"bedrock-secret-key",type:"string",required:!1,help:"AWS Bedrock secret key (non-interactive mode)"},{name:"use-ollama",type:"boolean",required:!1,help:"Use Ollama (local LLM) provider (non-interactive mode)"},{name:"ollama-model",type:"string",required:!1,help:"Ollama model name (default: llama3:8b-instruct, non-interactive mode)"},{name:"model",type:"string",required:!1,help:"Default model ID for the selected provider. Saved to workspace config."},{name:"gemini-key",type:"string",required:!1,help:"Google API key (non-interactive mode)"},{name:"openai-key",type:"string",required:!1,help:"OpenAI API key (non-interactive mode)"},{name:"openrouter-key",type:"string",required:!1,help:"OpenRouter API key (non-interactive mode)"},{name:"nebius-key",type:"string",required:!1,help:"Nebius AI Studio API key (non-interactive mode)"},{name:"ollama-cloud-key",type:"string",required:!1,help:"Ollama Cloud API key (non-interactive mode)"},{name:"azure-endpoint",type:"string",required:!1,help:"Azure AI endpoint URL (non-interactive mode)"},{name:"azure-credential",type:"string",required:!1,help:"Azure AI API credential (non-interactive mode)"},{name:"profile",type:"string",required:!1,help:"Agent profile (development, production, performance, max). Only for Anthropic/Bedrock providers."},{name:"ncbi-key",type:"string",required:!1,help:"NCBI API key (optional, non-interactive mode)"},{name:"cloud-key",type:"string",required:!1,help:"Lobster Cloud API key (optional, enables premium tier)"},{name:"cloud-endpoint",type:"string",required:!1,help:"Custom cloud endpoint URL (optional)"},{name:"skip-ssl-test",type:"boolean",required:!1,help:"Skip SSL connectivity test during init"},{name:"ssl-verify",type:"boolean",required:!1,help:"Enable/disable SSL verification (non-interactive mode)"},{name:"ssl-cert-path",type:"string",required:!1,help:"Path to custom CA certificate bundle"},{name:"agents",type:"string",required:!1,help:"Comma-separated list of agents to enable (non-interactive mode)"},{name:"preset",type:"string",required:!1,help:"Agent preset name (scrna-basic, scrna-full, multiomics-full)"},{name:"auto-agents",type:"boolean",required:!1,help:"Use LLM to suggest agents based on description (requires --agents-description)"},{name:"agents-description",type:"string",required:!1,help:"Workflow description for LLM agent suggestion (with --auto-agents)"},{name:"skip-docling",type:"boolean",required:!1,help:"Skip docling installation prompt (non-interactive mode)"},{name:"install-docling",type:"boolean",required:!1,help:"Install docling for PDF intelligence (non-interactive mode)"},{name:"install-vector-search",type:"boolean",required:!1,help:"Install Smart Standardization dependencies (the lobster-vector package)"},{name:"skip-extras",type:"boolean",required:!1,help:"Skip optional package installation (provider, TUI, extended-data)"},{name:"ui",type:"string",required:!1,help:"UI mode for interactive init: auto (Go TUI if available, else questionary, else classic), go (require Go TUI), classic (Rich prompts only)"},{name:"name",type:"string",required:!1,help:"Project name (default: the folder name)"},{name:"provider",type:"string",required:!1,help:"Provider for a project made without a terminal (no key is read or saved)"},{name:"lamin",type:"boolean",required:!1,help:"Keep a LaminDB catalog (default: ask; No)"}]},{name:"lamin init",handler:"lobster.cli_internal.commands.light.lamin_commands:init_cmd",help:"Switch the catalog on for this workspace and create it now.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"}]},{name:"lamin ls",handler:"lobster.cli_internal.commands.light.lamin_commands:ls_cmd",help:"List the files or sessions in the workspace catalog.",surfaces:["cli"],scientist_facing:!1,args:[{name:"runs",type:"boolean",required:!1,help:"List sessions"},{name:"artifacts",type:"boolean",required:!1,help:"List files (default)"},{name:"limit",type:"integer",required:!1,help:"Maximum number of rows"},{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"json",type:"boolean",required:!1,help:"Output results as JSON (machine-readable)"}]},{name:"lamin prune",handler:"lobster.cli_internal.commands.light.lamin_commands:prune_cmd",help:"Remove the kept copies of earlier versions; the records stay.",surfaces:["cli"],scientist_facing:!1,args:[{name:"dry-run",type:"boolean",required:!1,help:"Show what would be removed; remove nothing"},{name:"yes",type:"boolean",required:!1,help:"Do not ask first"},{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"json",type:"boolean",required:!1,help:"Output results as JSON (machine-readable)"}]},{name:"lamin status",handler:"lobster.cli_internal.commands.light.lamin_commands:status_cmd",help:"Show whether this workspace is recorded, and where.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"json",type:"boolean",required:!1,help:"Output results as JSON (machine-readable)"}]},{name:"lamin use",handler:"lobster.cli_internal.commands.light.lamin_commands:use_cmd",help:"Record this workspace in a LaminDB instance of your own instead.",surfaces:["cli"],scientist_facing:!1,args:[{name:"target",type:"string",required:!1,help:"Instance as owner/name, or the storage folder of a local instance"},{name:"clear",type:"boolean",required:!1,help:"Go back to the workspace catalog"},{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"}]},{name:"mcp",handler:"lobster.cli_internal.commands.light.mcp_commands:mcp_command",help:"Run Lobster as an MCP server for desktop and agent hosts (JSON-RPC on stdin and stdout).",surfaces:["cli"],scientist_facing:!1,args:[{name:"stdio",type:"boolean",required:!1,help:"Speak MCP (JSON-RPC) on stdin and stdout."},{name:"workspace",type:"path",required:!1,help:"Folder the Lobster project is found from (default: the current folder)."}]},{name:"metadata",handler:"lobster.cli:metadata_command",help:"Display metadata overview and statistics.",surfaces:["cli"],scientist_facing:!1,args:[{name:"subcommand",type:"string",required:!1,help:"Subcommand: overview, publications, samples, workspace, exports, list, clear"},{name:"target",type:"string",required:!1,help:"For clear: exports or all"},{name:"workspace",type:"path",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"status",type:"string",required:!1,help:"Status filter for publications subcommand"}]},{name:"projects delete",handler:"lobster.cli_internal.commands.light.project_commands:projects_delete",help:"Delete a project's Lobster workspace; the folder and your other files stay.",surfaces:["cli"],scientist_facing:!0,args:[{name:"folder",type:"path",required:!1,help:"Project folder (default: the project in the current folder)"},{name:"yes",type:"boolean",required:!1,help:"Delete without asking (needed without a terminal)"},{name:"dry-run",type:"boolean",required:!1,help:"List what would be removed; change nothing"},{name:"json",type:"boolean",required:!1,help:"Print the result as lobster.project/1 JSON"}]},{name:"projects info",handler:"lobster.cli_internal.commands.light.project_commands:projects_info",help:"Show a project's identity, provider, model, experts and runs.",surfaces:["cli"],scientist_facing:!0,args:[{name:"folder",type:"path",required:!1,help:"Project folder (default: the project that contains the current folder)"},{name:"json",type:"boolean",required:!1,help:"Print the lobster.project/1 record as JSON"}]},{name:"projects list",handler:"lobster.cli_internal.commands.light.project_commands:projects_list",help:"List the projects this machine has set up.",surfaces:["cli"],scientist_facing:!0,args:[{name:"json",type:"boolean",required:!1,help:"Print the lobster.project/1 listing as JSON"}]},{name:"purge",handler:"lobster.cli:purge",help:"Remove all Lobster AI files from your system.",surfaces:["cli"],scientist_facing:!1,args:[{name:"scope",type:"string",required:!1,help:"What to purge: 'global' (~/.lobster, ~/.config/lobster), 'workspace' (current), or 'all'"},{name:"workspace",type:"path",required:!1,help:"Workspace directory to purge (default: current workspace)"},{name:"dry-run",type:"boolean",required:!1,help:"Show what would be deleted without actually deleting"},{name:"force",type:"boolean",required:!1,help:"Skip confirmation prompt"}]},{name:"query",handler:"lobster.cli:query",help:"Send a single query, or run a local slash command when QUESTION starts with '/'.",surfaces:["cli"],scientist_facing:!0,args:[{name:"question",type:"string",required:!0},{name:"workspace",type:"path",required:!1,help:"Workspace directory. Defaults to ./.lobster_workspace or LOBSTER_WORKSPACE."},{name:"session-id",type:"string",required:!1,help:"Continue a saved session. Use 'latest' for the most recent one."},{name:"reasoning",type:"boolean",required:!1,help:"Show agent reasoning."},{name:"verbose",type:"boolean",required:!1,help:"Show agent and tool trace details."},{name:"debug",type:"boolean",required:!1,help:"Enable debug logging."},{name:"output",type:"path",required:!1,help:"Write the final answer to a file."},{name:"profile-timings",type:"boolean",required:!1,help:"Show data-manager timing diagnostics."},{name:"provider",type:"string",required:!1,help:"Provider override. Uses the configured provider when omitted."},{name:"model",type:"string",required:!1,help:"Model override. Uses the configured model when omitted."},{name:"stream",type:"boolean",required:!1,help:"Stream text as it arrives. Disabled automatically in trace mode."},{name:"json",type:"boolean",required:!1,help:"Emit JSON only on stdout."}]},{name:"replay",handler:"lobster.cli_internal.commands.light.replay_commands:replay_command",help:"Re-run an exported notebook and compare its output with the saved file. Exit codes: 0 MATCH, 1 MISMATCH, 2 usage error, 3 NOT_COMPARED, 4 REFUSED, 5 the notebook failed to run, 6 MATCH_CUSTOM_POLICY, 130 interrupted. Compares what the notebook writes against what the session saved, and detects changes it can see; it does not prove how the outputs were computed.",surfaces:["cli"],scientist_facing:!1,args:[{name:"verify",type:"path",required:!0,help:"Exported notebook to re-run and check"},{name:"input",type:"path",required:!1,help:"Input data file of the notebook (.h5ad)"},{name:"policy",type:"path",required:!1,help:"Comparison policy (JSON). Default: exact values, without the session's own provenance and lineage records"},{name:"workspace",type:"string",required:!1,help:"Workspace directory. Default: ./.lobster_workspace"},{name:"json",type:"boolean",required:!1,help:"Output results as JSON (machine-readable)"},{name:"timeout",type:"integer",required:!1,help:"Time limit per cell, in seconds; a cell that runs longer stops the check (0: no limit)"}]},{name:"scaffold agent",handler:"lobster.cli_internal.commands.light.scaffold_commands:scaffold_agent_cmd",help:"Generate a complete agent plugin package.",surfaces:["cli"],scientist_facing:!1,args:[{name:"name",type:"string",required:!0,help:"Agent name in snake_case (e.g., epigenomics_expert)"},{name:"display-name",type:"string",required:!0,help:"Human-readable name (e.g., 'Epigenomics Expert')"},{name:"description",type:"string",required:!0,help:"Agent capabilities description"},{name:"children",type:"string",required:!1,help:"Comma-separated child agent names"},{name:"output-dir",type:"path",required:!1,help:"Output directory"},{name:"author-name",type:"string",required:!1,help:"Package author name"},{name:"author-email",type:"string",required:!1,help:"Package author email"}]},{name:"serve",handler:"lobster.cli:serve",help:"Start the agent system as an API server (for React UI).",surfaces:["cli"],scientist_facing:!1,args:[{name:"port",type:"integer",required:!1},{name:"host",type:"string",required:!1,help:"Bind address. Anything other than localhost requires a token."},{name:"token",type:"string",required:!1,help:"Bearer token. Prefer LOBSTER_SERVE_TOKEN: --token shows in ps."}]},{name:"sessions list",handler:"lobster.cli_internal.commands.light.session_commands:sessions_list",help:"List saved sessions in a workspace, newest first.",surfaces:["cli"],scientist_facing:!1,args:[{name:"workspace",type:"path",required:!1,help:"Workspace directory. Defaults to ./.lobster_workspace or LOBSTER_WORKSPACE."},{name:"json",type:"boolean",required:!1,help:"Print the lobster.sessions/1 listing as JSON."}]},{name:"skills install",handler:"lobster.cli_internal.commands.light.skills_commands:skills_install",help:"Copy the shipped skills into coding-agent skill folders (Claude Code, Codex, ...).",surfaces:["cli"],scientist_facing:!1,args:[{name:"harness",type:"string",required:!1,help:"Harness to install into (claude-code, codex, cursor, os, pi); repeatable. Default: every harness found in your home directory."},{name:"target",type:"path",required:!1,help:"Install into this skill folder instead."},{name:"dry-run",type:"boolean",required:!1,help:"Show what would be copied; write nothing."},{name:"json",type:"boolean",required:!1,help:"Print the lobster.skills-install/1 plan as JSON."}]},{name:"skills list",handler:"lobster.cli_internal.commands.light.skills_commands:skills_list",help:"List the agent skills shipped with Lobster.",surfaces:["cli"],scientist_facing:!1,args:[{name:"json",type:"boolean",required:!1,help:"Print the shipped skills as JSON."}]},{name:"status",handler:"lobster.cli:status",help:"Display subscription tier, installed packages, and available agents.",surfaces:["cli"],scientist_facing:!0,args:[]},{name:"upgrade",handler:"lobster.cli:upgrade",help:"Upgrade lobster-ai to the latest published version.",surfaces:["cli"],scientist_facing:!1,args:[{name:"dry-run",type:"boolean",required:!1,help:"Print the upgrade command without running it"}]},{name:"vector-search",handler:"lobster.cli:vector_search_cmd",help:"Search all ontology collections via semantic vector similarity.",surfaces:["cli"],scientist_facing:!1,args:[{name:"query_text",type:"string",required:!0,help:"Biomedical term to search"},{name:"top-k",type:"integer",required:!1,help:"Results per collection (default: 5)"},{name:"pretty",type:"boolean",required:!1,help:"Pretty-print or compact JSON"}]}]};var Je=ia(sa);var Sd="Analysis on your own machine runs in the Lobster AI engine (Python):",kd={"":{summary:"Omics-OS Cloud from your terminal",intro:["Sign in, chat with Lobster AI, run BioVault and the LaTeX editor on Omics-OS Cloud."],groups:[{title:"Get started",items:[{name:"login",summary:"Sign in (opens your browser; --device over SSH)"},{name:"lobster chat",summary:"Chat with Lobster AI on Omics-OS Cloud"},{name:"lobster query <q>",summary:"Ask one question and print the answer"},{name:"doctor",summary:"Check version, login, Lobster AI engines and shortcuts"}]},{title:"Omics-OS Cloud",items:[{name:"upload",summary:"Upload files or folders to a project (resumable, for large files)"},{name:"lobster",summary:"Lobster AI sessions: chat, query, session, files, export, agents"},{name:"biovault",summary:"BioVault drafts and runs: draft, run, runs, features"},{name:"editor",summary:"LaTeX editor: generate, compile, files, pull, push, download"},{name:"app",summary:"Print the Omics-OS Cloud workspace URL"},{name:"playground",summary:"Print the Agent Playground URL"}]},{title:"Account",items:[{name:"status",summary:"Who you are signed in as, plan and usage"},{name:"profiles",summary:"List or remove credential profiles (one per tenant)"},{name:"use <name>",summary:"Switch the active profile"},{name:"logout",summary:"Sign out of this computer"}]},{title:"This installation",items:[{name:"setup",summary:"Optional shortcuts: lobster, biovault, editor, app, playground"},{name:"skills",summary:"Add omics-os skills to Claude Code, Codex, Cursor, Pi and others"},{name:"upgrade",summary:"Update omics-os to the latest release"},{name:"uninstall",summary:"Remove omics-os, its sign-in and shortcuts from this computer"}]}],examples:[{command:"omics-os login"},{command:"omics-os lobster chat"},{command:'omics-os lobster query "Find GEO scRNA-seq datasets of human liver fibrosis"'},{command:"omics-os lobster session list --json",note:"for scripts and agents"}],footer:[{hint:Sd,command:"lobster --help"},{hint:"Docs:",link:Xs}]},login:{intro:["API key from the environment: OMICS_OS_API_KEY (the local Lobster AI engine reads the same name).","The older OMICSOS_API_KEY still works here, but it is never passed to the engine."],examples:[{command:"omics-os login",note:"browser sign-in"},{command:"omics-os login --device",note:"no browser on this machine"},{command:"omics-os login --tenant acme"}]},lobster:{groups:[{title:"Talk to Lobster AI",items:[{name:"chat",summary:"Interactive chat (--backend local: your own engine, experimental)"},{name:"query <question>",summary:"Ask one question, print the answer (--json, --stream)"}]},{title:"Sessions and results",items:[{name:"session",summary:"create, list, info, messages, provenance, share, archive, cancel, delete"},{name:"files",summary:"list, upload, download, load, delete session files"},{name:"export <id>",summary:"Export a session as report, pipeline or slide deck"},{name:"projects",summary:"create, list, info, download your Cloud projects"}]},{title:"Agents and ontologies",items:[{name:"agents",summary:"list, info, push, download agent packages"},{name:"vector search <q>",summary:"Search ontology terms (cell types, tissues, diseases)"}]}],examples:[{command:"omics-os lobster chat"},{command:'omics-os lobster query -s latest "Now cluster the cells"',note:"continue your last session"},{command:"omics-os lobster session list"},{command:"omics-os lobster files upload <session-id> counts.h5ad"}]},"lobster query":{examples:[{command:'omics-os lobster query "Find GEO scRNA-seq datasets of human liver fibrosis"'},{command:'omics-os lobster query -s latest "Plot the UMAP coloured by donor"'},{command:'omics-os lobster query --json "Summarise session QC" | jq -r .response'}]},"lobster projects download":{intro:["Files land in <folder>/sessions/<session-id>/. Nothing is tracked or synced back.","","By default only the light files come: notebooks, reports, result tables and plots. Data files come only with --data and are otherwise listed with their sizes: .h5ad, .h5, .h5mu, .loom, .mtx, .fastq/.fq, .bam, .sam, .cram, .vcf, .bcf, .parquet, .zarr, .rds, .rda, .npz, .npy, .pkl, .feather, .arrow, .tar, .tgz, .zip (also compressed with .gz, .bgz, .bz2, .xz or .zst), and any file over 50\xA0MiB. A file whose size Cloud does not list is downloaded unless its name marks it as a data file.","","--dry-run shows what a download would bring and writes nothing. With --dry-run, downloaded lists what would be downloaded; the exit code is the one the real run would have (1 when a file would fail). Session files are not listed by projects info: --dry-run is the preview of a download.","","A file already in the folder is skipped, never overwritten. A Lobster project folder itself (it holds .lobster_workspace/project.json) and anything inside a .lobster_workspace folder are refused; a subfolder of a project, such as its data/ folder, is fine. Dataset files are listed but cannot be downloaded from Omics-OS Cloud yet.","","Limits: a file whose name differs only in case from one already downloaded is skipped on a later run on a case-insensitive disk. Download into a folder only you can write to: links are refused, but the checks are not race-proof. omics-os is not tested on Windows yet. Use WSL."],examples:[{command:"omics-os lobster projects download <project-id>",note:"into ./<project name>"},{command:"omics-os lobster projects download <project-id> atlas --session <session-id>"},{command:"omics-os lobster projects download <project-id> atlas --dry-run",note:"see what would come"},{command:"omics-os lobster projects download <project-id> atlas --data",note:"data files too"},{command:"omics-os --json lobster projects download <project-id> atlas",note:"summary as JSON"}]},upload:{intro:["Sends each file straight into the project's data on Omics-OS Cloud, in parts, at its path: a folder keeps its own name and its subfolders (run1/pod5_pass/barcode01/a.pod5). A file appears in the project once it is complete.","","Stopped or cut off? Run the same command again: finished files are skipped and a partly sent file resumes from its last finished part, for 7 days from the start of its upload. A file is recognised by its path, its size and a fingerprint of its first and last 8 MiB. If its modification time changed, the parts already sent are read again and compared first, so a changed file starts over.","","A file can be up to 48.8 TiB, within your organisation's per-file limit. The 7 days count per file, so only one very large file on a slow line can run out of time. Largest file that fits in 7 days at about 75 % of the line speed: 20 Mbit/s ~1.1 TB, 100 Mbit/s ~5.7 TB, 500 Mbit/s ~28 TB, 1 Gbit/s and faster: 48.8 TiB. A larger file on a slower line: split it, or upload from a faster connection.","","Storage checks every part on arrival. Empty files and links are skipped and listed. A file already in the project with the same path, size and fingerprint is skipped. A different file at the same path is not overwritten: run again with --replace to overwrite it (the old version is kept for 30 days), or to cancel your own unfinished upload of an earlier version of the file. --json gives each file's path and version ID for scripts.","","To delete files from a project, use the web app.","","Windows: if PowerShell refuses to run omics-os because of its execution policy, run omics-os.cmd instead, with the same arguments."],examples:[{command:"omics-os upload ./run1 --project <project-id>",note:"a whole folder"},{command:'omics-os upload ./run1 --project <project-id> --include "*.pod5" --dry-run',note:"see what would go"},{command:"omics-os --json upload a.pod5 b.pod5 --project <project-id>",note:"paths and version IDs as JSON"}]},biovault:{groups:[{title:"Drafts and runs",items:[{name:"draft"},{name:"run"},{name:"runs"},{name:"features"}]},{title:"Legacy",items:[{name:"search"},{name:"evidence"},{name:"export"},{name:"ask"},{name:"jobs"},{name:"job-status"},{name:"cancel"}]}],examples:[{command:"omics-os biovault draft new --output draft.json"},{command:"omics-os biovault draft list"},{command:"omics-os biovault runs"}]},uninstall:{intro:["Signs out first (revokes a browser or device sign-in on the server), then removes","this client's sign-in, profiles, config and the shortcuts made by omics-os setup,","then removes the npm package.","","It never touches the Lobster AI engine (~/.lobster, ~/.config/lobster, workspaces).","To remove those too, run: lobster purge"],examples:[{command:"omics-os uninstall --dry-run",note:"see what would go"},{command:"omics-os uninstall"},{command:"omics-os uninstall --yes --keep-credentials",note:"reinstall later, stay signed in"}]}},aa=92,la=100;function ot(t,e){let r=(e.env.FORCE_COLOR??"").toLowerCase(),n=r!==""&&r!=="0"&&r!=="false";if(!((!!t.isTTY||n)&&!e.noColor&&!e.env.NO_COLOR&&e.env.TERM!=="dumb"))return{color:!1,boxes:!1,width:t.isTTY?Math.min(la,Math.max(40,t.columns||80)):la};let i=Math.max(40,t.columns||80),s=i>=aa+4;return{color:!0,boxes:s,width:s?aa:i}}var xd=/\x1b\[[0-9;]*m/g,ve=t=>[...t.replace(xd,"")].length,co=(t,e)=>t+" ".repeat(Math.max(0,e-ve(t))),nt=class{constructor(e){this.on=e}on;sgr(e,r){return this.on&&r?`\x1B[${e}m${r}\x1B[0m`:r}bold=e=>this.sgr("1",e);dim=e=>this.sgr("2",e);command=e=>this.sgr("1;36",e);flag=e=>this.sgr("1;32",e);meta=e=>this.sgr("1;33",e);label=e=>this.sgr("1;33",e);link=e=>this.sgr("4;36",e);red=e=>this.sgr("31",e);green=e=>this.sgr("32",e)};function Ed(t,e){let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=r[0];r[0]=n;for(let i=1;i<=e.length;i++){let s=r[i];r[i]=Math.min(r[i]+1,r[i-1]+1,o+(t[n-1]===e[i-1]?0:1)),o=s}}return r[e.length]}function ua(t,e){let r=t.length<=3?1:2,n;for(let o of e){let i=Ed(t.toLowerCase(),o.toLowerCase());i<=r&&(!n||i<n.d)&&(n={name:o,d:i})}return n?.name}function po(t){let e=!1;try{e=t?.optsWithGlobals()?.color===!1}catch{}return new nt(ot(process.stderr,{noColor:e,env:process.env}).color)}function Ne(t,e){let r=[];for(let n of t.split(`
|
|
31
|
+
`)){let o="";for(let i of n.split(" "))o&&ve(o)+1+ve(i)>e?(r.push(o),o=i):o=o?`${o} ${i}`:i;r.push(o)}return r}function Dr(t){let e=[];for(let r=t;r;r=r.parent)e.unshift(r.name());return e.join(" ")}var Cd=t=>!!t._hidden,fo=class{constructor(e){this.style=e;this.p=new nt(e.color)}style;p;name(e){return e.split(" ").map(r=>/^[<[]/.test(r)?this.p.meta(r):this.p.command(r)).join(" ")}optionTerm(e){let r=e.long??e.short??"",n=r?e.flags.slice(e.flags.indexOf(r)+r.length).trim():"";return`${e.long?`${e.short?`${this.p.flag(e.short)}, `:" "}${this.p.command(e.long)}`:this.p.flag(e.short??"")}${n?` ${this.p.meta(n)}`:""}`}panel(e,r,n=Math.min(Math.max(...r.map(([o])=>ve(o))),32)){let{p:o}=this;if(!this.style.boxes){let c=Math.max(20,this.style.width-2-n-2),d=[o.bold(e)];for(let[p,f]of r){let[h="",..._]=ve(p)>n?["",...Ne(f,c)]:Ne(f,c);d.push(` ${co(p,n)} ${h}`.trimEnd());for(let b of _)d.push(`${" ".repeat(n+4)}${b}`)}return d.push(""),d}let i=this.style.width,s=i-4,a=Math.max(20,s-n-2),l=[o.dim("\u256D\u2500 ")+o.bold(e)+" "+o.dim("\u2500".repeat(i-5-ve(e))+"\u256E")],u=c=>`${o.dim("\u2502")} ${co(c,s)} ${o.dim("\u2502")}`;for(let[c,d]of r){let[p="",...f]=ve(c)>n?["",...Ne(d,a)]:Ne(d,a);l.push(u(`${co(c,n)} ${p}`.trimEnd()));for(let h of f)l.push(u(`${" ".repeat(n+2)}${h}`))}return l.push(o.dim(`\u2570${"\u2500".repeat(i-2)}\u256F`)),l}heading(e){return this.style.boxes?["",this.p.bold(e)]:[this.p.bold(e)]}render(e,r){let{p:n}=this,o=Dr(e),i=o.replace(/^omics-os ?/,""),s=kd[i]??{},a=!e.parent,l="1.3.0",u=r.visibleCommands(e).filter(m=>!Cd(m)&&m.name()!=="help"),c=[],d=s.summary??e.description(),p=`${n.bold(o)}${a?` ${n.dim(l)}`:""}`,f=d&&ve(p)+2+ve(d)<=this.style.width;c.push(f?`${p} ${d}`:p),c.push("");let h=e.registeredArguments.map(m=>m.required?`<${m.name()}>`:`[${m.name()}]`).join(" "),_=[o,u.length?"<command>":"",h,"[options]"].filter(Boolean).join(" ");c.push(`${n.label("Usage:")} ${n.bold(_)}`),c.push("");let b=[];!f&&d&&b.push(d);let j="";for(let m of s.intro??[])m===""?(j&&b.push(j),j=""):j=j?`${j} ${m}`:m;j&&b.push(j);for(let m of b)c.push(...Ne(m,this.style.width),"");if(u.length){let m=new Set,x=[];for(let D of s.groups??[]){let v=[];for(let S of D.items){let I=S.name.split(" ")[0],L=u.find(te=>te.name()===I);L&&(m.add(I),v.push([this.name(S.name),S.summary??L.description()]))}v.length&&x.push([D.title,v])}let C=u.filter(D=>!m.has(D.name()));if(C.length){let D=C.map(v=>{let S=v.registeredArguments.map(I=>I.required?`<${I.name()}>`:`[${I.name()}]`).join(" ");return[this.name(S?`${v.name()} ${S}`:v.name()),v.description()]});x.push([s.groups?"Other commands":"Commands",D])}let A=Math.min(Math.max(...x.flatMap(([,D])=>D.map(([v])=>ve(v)))),32);for(let[D,v]of x)c.push(...this.panel(D,v,A))}if(e.registeredArguments.length){let m=e.registeredArguments.map(x=>[n.meta(x.required?`<${x.name()}>`:`[${x.name()}]`),`${x.description}${x.required?` ${n.red("[required]")}`:""}`.trim()]);c.push(...this.panel("Arguments",m))}let g=r.visibleOptions(e).filter(m=>!m.hidden).sort((m,x)=>(m.long??m.short??"").replace(/^-+/,"").localeCompare((x.long??x.short??"").replace(/^-+/,"")));if(g.length&&c.push(...this.panel("Options",g.map(m=>[this.optionTerm(m),r.optionDescription(m)]))),s.examples?.length){c.push(...this.heading("Examples"));for(let m of s.examples){let x=m.command.replace(/"[^"]*"/g,S=>n.green(S)),C=m.note?` ${n.dim(`# ${m.note}`)}`:"",A=ve(x)+ve(C)<=this.style.width-4,[D="",...v]=Ne(A?`${x}${C}`:x,this.style.width-4);c.push(` ${n.dim("$")} ${D}`,...v.map(S=>` ${S}`)),!A&&C&&c.push(...Ne(C.trim(),this.style.width-6).map(S=>` ${S}`))}c.push("")}if(s.footer?.length){for(let m of s.footer)c.push(...Ne(`${n.dim(m.hint)} ${m.command??""}${m.link?n.link(m.link):""}`.trimEnd(),this.style.width));c.push("")}for(;c.length&&c[c.length-1]==="";)c.pop();return`${c.join(`
|
|
32
|
+
`)}
|
|
33
|
+
`}};function ca(t,e){let r=new nt(e.color),n=[`${r.bold("omics-os")} ${r.dim(t.version)} Omics-OS Cloud from your terminal`,""];if(t.signedIn){let o=t.signedIn.fromEnv?`Signed in with ${t.signedIn.fromEnv} on ${t.signedIn.host}`:`Signed in as ${t.signedIn.email??"an account"} on ${t.signedIn.host}${t.signedIn.profile&&t.signedIn.profile!=="default"?` (profile ${t.signedIn.profile})`:""}`;n.push(` ${r.green("\u2713")} ${o}`,"",r.bold("Next"))}else n.push(` ${r.red("\u2717")} Not signed in. Start with: ${r.command("omics-os login")}`,"",r.bold("Then"));for(let[o,i]of[["omics-os lobster chat","chat with Lobster AI"],["omics-os lobster session list","your sessions"],["omics-os doctor","check this installation"]])n.push(` ${r.dim("$")} ${o} ${r.dim(`# ${i}`)}`);return n.push("",`${r.dim("All commands:")} omics-os --help`),`${n.join(`
|
|
34
|
+
`)}
|
|
35
|
+
`}var Lr=class t extends Bs{helpToStderr=!1;createCommand(e){return new t(e)}helpInformation(e){return this.helpToStderr=!!e?.error,super.helpInformation(e)}};function qd(t,e){let r=t.helpToStderr?process.stderr:process.stdout,n=!1;try{n=t.optsWithGlobals().color===!1}catch{}return new fo(ot(r,{noColor:n,env:process.env})).render(t,e)}function da(t,e){let r=t.helpToStderr?process.stderr:process.stdout,n=!1;try{n=t.optsWithGlobals().color===!1}catch{}let{width:o}=ot(r,{noColor:n,env:process.env});return e.split(`
|
|
36
|
+
`).flatMap(i=>i?Ne(i,o):[""]).join(`
|
|
37
|
+
`)}function mo(t){t.configureHelp({formatHelp:qd}),t.configureOutput({getOutHasColors:()=>!0,getErrHasColors:()=>!0,outputError:(r,n)=>n(`${po(t).red("\u2717")} ${r.replace(/^error: /,"")}`)}),t._helpOption===null||(t.parent?t.helpOption("-h, --help","Show this help"):t.helpOption("-h, --help","Help for any command, e.g. omics-os lobster --help"));for(let r of t.commands)mo(r)}var y={};Fn(y,{APPROVAL_GENERATION:()=>Ce,BIOVAULT_CONTRACT:()=>Ha,CONFIRMABLE_PATHS:()=>Sa,DISPLAY_SHAPES:()=>Jo,NATIVE_BUNDLE_VERSION:()=>tr,NATIVE_MANIFEST_VERSION:()=>vt,NATIVE_SCOPE:()=>_o,NEWER_SERVER_NOTICE:()=>Da,PRE_COMMIT_REFUSALS:()=>ba,PRE_COMMIT_TRY_AGAIN:()=>wa,PROMPT_VERSIONS:()=>Vr,RP1_BUNDLE_VERSION:()=>St,RP1_MANIFEST_VERSION:()=>it,RP1_SCOPE:()=>er,approvalNonconformity:()=>Jd,bindIdentity:()=>lp,cancelNonconformity:()=>Oo,cancelRun:()=>ap,canonicalJson:()=>ha,claim:()=>mp,classifyVaultError:()=>xt,configValue:()=>Vd,contextKey:()=>Xo,createDraft:()=>Qf,deliveryNonconformity:()=>Ge,deliveryV1:()=>go,digestsOf:()=>ga,discardDraft:()=>rp,displayJobNonconformity:()=>Ko,displayProfileNonconformity:()=>Wo,displayRunsNonconformity:()=>Go,draftNonconformity:()=>$e,entriesNonconformity:()=>Eo,entryNonconformity:()=>sr,entrySummaryNonconformity:()=>ir,executeReadiness:()=>Wd,executeRun:()=>sp,features:()=>Lf,featuresNonconformity:()=>xo,fieldsOfPreview:()=>Md,forget:()=>gp,getArchiveLink:()=>op,getDecisions:()=>Kf,getDraft:()=>Df,getEntry:()=>Mf,getFileLink:()=>np,getPackage:()=>Wf,getProblems:()=>Gf,getPrompt:()=>Hf,getRun:()=>Vf,getRunForDisplay:()=>zf,getSamples:()=>Jf,instructionHashesMatch:()=>wo,instructionsMatch:()=>bo,isPromptVersion:()=>kt,isRp1:()=>$d,jobNonconformity:()=>ar,jobPromptNonconformity:()=>Ao,judge:()=>Dd,legacyJobNonconformity:()=>Co,legacyJobsNonconformity:()=>qo,listEntries:()=>Uf,listRuns:()=>Ff,listRunsForDisplay:()=>Bf,manifestVersionOf:()=>Ur,modelSelectionNonconformity:()=>xa,newerThan:()=>Ld,nonconformity:()=>Le,observe:()=>en,originOf:()=>Fd,packageLinkMismatch:()=>ip,pendingContext:()=>dp,pendingLockPath:()=>Za,pendingPath:()=>jt,provesNothingCommitted:()=>vo,provesNothingStartedTryAgain:()=>So,read:()=>pp,release:()=>hp,removeLiterature:()=>tp,resavesCeiling:()=>Ud,runCompatibility:()=>Fa,runV1:()=>ho,sameTuple:()=>Fr,saveDraft:()=>Zf,sha256Hex:()=>rr,snapshotNonconformity:()=>Hd,supersededBy:()=>ya,uploadLiterature:()=>ep,validExecuteTuple:()=>Ya,withCompatibility:()=>Yr,withoutCompatibility:()=>Kr});var ho={};Fn(ho,{WIRE_SHAPES_RUN_V1:()=>wt});var wt={Artifact:{artifact_sha256:{t:"string",required:!0},version:{t:"string",required:!0},version_sha256:{t:"string",required:!0}},CeilingPolicySnapshot:{deployment_config_revision:{t:"string",required:!0},effective_org_id:{t:"string",required:!0},max_cost_usd:{t:"string",required:!0},max_storage_bytes:{t:"integer",required:!0},observed_at:{t:"string",required:!0},revision:{t:"string",required:!0},scope:{t:"enum",values:["platform_default","org_override"],required:!0}},Check:{code:{t:"string",required:!0},kind:{t:"enum",values:["blocking","warning","decided_in_run"],required:!0},message:{t:"string",required:!0},path:{t:"string",required:!0},problem_kind:{t:"string",required:!0,nullable:!0},severity:{t:"enum",values:["blocking","warning","info"],required:!0}},Cohorts:{control_fallback:{t:"enum",values:["label_adjacent_normal_as_adjacent_normal_never_as_healthy_report_shortfall"],required:!0},control_preference:{t:"enum",values:["lobster_decides_and_records","healthy_donors","adjacent_normal","no_controls"],required:!0},covariates:{t:"array",of:{t:"ref",name:"Covariate"},required:!0},intent:{t:"string",required:!0},min_samples_per_group:{t:"integer",required:!0},pairing_preference:{t:"enum",values:["no_preference","prefer_paired","require_paired"],required:!0},stratify_by:{t:"array",of:{t:"ref",name:"Stratifier"},required:!0}},Covariate:{name:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Credential:{binding_id:{t:"string",required:!0},version:{t:"string",required:!0}},DatasetRef:{accession:{t:"string",required:!0},reason:{t:"string",required:!0}},Datasets:{change_policy:{t:"enum",values:["replace_failed_within_scope_never_excluded"],required:!0},commercially_usable_only:{t:"boolean",required:!0},exclude:{t:"array",of:{t:"ref",name:"DatasetRef"},required:!0},include:{t:"array",of:{t:"ref",name:"DatasetRef"},required:!0},literature:{t:"array",of:{t:"ref",name:"Literature"},required:!0},literature_files:{t:"array",of:{t:"ref",name:"LiteratureFile"},required:!0},mode:{t:"enum",values:["discover_within_scope","listed_only","both"],required:!0}},DraftCandidateV1:{cohorts:{t:"ref",name:"Cohorts",required:!0},config_version:{t:"enum",values:["1"],required:!0},created_by:{t:"string",required:!0},datasets:{t:"ref",name:"Datasets",required:!0},eligibility:{t:"ref",name:"Eligibility",required:!0},execution_contract:{t:"ref",name:"ExecutionContract",required:!0,nullable:!0},handoff:{t:"ref",name:"Handoff",required:!0},harmonization:{t:"ref",name:"Harmonization",required:!0},interaction:{t:"ref",name:"Interaction",required:!0},limits:{t:"ref",name:"Limits",required:!0},llm:{t:"ref",name:"FrozenLlm",required:!0,nullable:!0},metadata:{t:"ref",name:"Metadata",required:!0},org_id:{t:"string",required:!0},output:{t:"ref",name:"Output",required:!0},processing:{t:"ref",name:"Processing",required:!0},provenance:{t:"ref",name:"Provenance",required:!0},request:{t:"ref",name:"Request",required:!0},run_id:{t:"string",required:!0},scope:{t:"ref",name:"Scope",required:!0},selection:{t:"ref",name:"Selection",required:!0},size:{t:"ref",name:"Size",required:!0},sources:{t:"ref",name:"Sources",required:!0}},DraftCohorts:{control_preference:{t:"enum",values:["lobster_decides_and_records","healthy_donors","adjacent_normal","no_controls"],nullable:!0},covariates:{t:"array",of:{t:"ref",name:"DraftCovariate"},nullable:!0},intent:{t:"string",nullable:!0},min_samples_per_group:{t:"integer",nullable:!0},pairing_preference:{t:"enum",values:["no_preference","prefer_paired","require_paired"],nullable:!0},stratify_by:{t:"array",of:{t:"ref",name:"DraftStratifier"},nullable:!0}},DraftCovariate:{name:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"]}},DraftDatasetRef:{accession:{t:"string",required:!0},reason:{t:"string"}},DraftDatasets:{commercially_usable_only:{t:"boolean",nullable:!0},exclude:{t:"array",of:{t:"ref",name:"DraftDatasetRef"},nullable:!0},include:{t:"array",of:{t:"ref",name:"DraftDatasetRef"},nullable:!0},literature_decisions:{t:"array",of:{t:"ref",name:"LiteratureDecision"},nullable:!0},mode:{t:"enum",values:["discover_within_scope","listed_only","both"],nullable:!0}},DraftEligibility:{donor_age_when_missing:{t:"enum",values:["exclude","flag","unknown"],nullable:!0},donors_under_18:{t:"enum",values:["lobster_decides_and_records","include","exclude"],nullable:!0},exclude:{t:"array",of:{t:"string"},nullable:!0},include:{t:"array",of:{t:"string"},nullable:!0},library:{t:"ref",name:"DraftLibrary",nullable:!0},preferences:{t:"array",of:{t:"string"},nullable:!0},sample_types:{t:"ref",name:"DraftSampleTypes",nullable:!0},sex:{t:"ref",name:"DraftSex",nullable:!0},treatment_status:{t:"ref",name:"DraftTreatment",nullable:!0}},DraftFieldsV1:{cohorts:{t:"ref",name:"DraftCohorts",nullable:!0},datasets:{t:"ref",name:"DraftDatasets",nullable:!0},eligibility:{t:"ref",name:"DraftEligibility",nullable:!0},interaction:{t:"ref",name:"DraftInteraction",nullable:!0},limits:{t:"ref",name:"DraftLimits",nullable:!0},llm:{t:"ref",name:"DraftLlm",nullable:!0},request:{t:"ref",name:"DraftRequest",nullable:!0},selection:{t:"ref",name:"DraftSelection",nullable:!0},size:{t:"ref",name:"DraftSize",nullable:!0},sources:{t:"ref",name:"DraftSources",nullable:!0}},DraftInteraction:{stop_on_blocking_problem:{t:"boolean",nullable:!0}},DraftLibrary:{type:{t:"enum",values:["any_rna_seq","poly_a","total_rna_ribo_depleted","tag_3_prime"],nullable:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],nullable:!0}},DraftLimits:{max_cost_usd:{t:"string",nullable:!0},max_storage_bytes:{t:"integer",nullable:!0}},DraftLlm:{selection:{t:"union",of:[{t:"ref",name:"Inherit"},{t:"ref",name:"Explicit"}],required:!0}},DraftNodeInput:{id:{t:"string",required:!0},label:{t:"string",required:!0},role:{t:"enum",values:["target","case","control","tissue","context","stratify","required","never"],required:!0,nullable:!0},type:{t:"enum",values:["gene","protein","disease","tissue","cell_type","compound","pathway","variant","accession","other","unresolved"],required:!0}},DraftRequest:{custom_prompt_addition:{t:"string",nullable:!0},question:{t:"string",nullable:!0}},DraftSampleTypes:{allow:{t:"array",of:{t:"enum",values:["primary_tissue","metastasis","cell_line","pdx_or_organoid"]},nullable:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],nullable:!0}},DraftSelection:{nodes:{t:"array",of:{t:"ref",name:"DraftNodeInput"},nullable:!0}},DraftSex:{use:{t:"enum",values:["any","report_only"],nullable:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],nullable:!0}},DraftSize:{preferred_bytes:{t:"integer",nullable:!0},preferred_studies:{t:"integer",nullable:!0},preferred_subjects:{t:"integer",nullable:!0}},DraftSources:{disallowed:{t:"array",of:{t:"string"},nullable:!0}},DraftStratifier:{node:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"]}},DraftTreatment:{policy:{t:"enum",values:["lobster_decides_and_records","treatment_naive_only","include_treated_record_regimen"],nullable:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],nullable:!0}},Edge:{from:{t:"string",required:!0},intent:{t:"string",required:!0},release:{t:"string",required:!0},source:{t:"string",required:!0},to:{t:"string",required:!0}},Editing:{omni:{t:"boolean",required:!0},turn_generation:{t:"integer",required:!0},turn_id:{t:"string",required:!0,nullable:!0}},Eligibility:{donor_age_when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0},donors_under_18:{t:"enum",values:["lobster_decides_and_records","include","exclude"],required:!0},exclude:{t:"array",of:{t:"string"},required:!0},include:{t:"array",of:{t:"string"},required:!0},library:{t:"ref",name:"Library",required:!0},preferences:{t:"array",of:{t:"string"},required:!0},sample_types:{t:"ref",name:"SampleTypes",required:!0},sex:{t:"ref",name:"Sex",required:!0},treatment_status:{t:"ref",name:"Treatment",required:!0}},ExecutionContract:{manifest:{t:"union",of:[{t:"ref",name:"Manifest"},{t:"ref",name:"RestrictedManifest"}],required:!0},manifest_sha256:{t:"string",required:!0}},Explicit:{mode:{t:"enum",values:["explicit"],required:!0},model:{t:"ref",name:"ModelRef",required:!0}},FixedContext:{clock_utc:{t:"string",required:!0},conversation:{t:"enum",values:["empty"],required:!0},encoding:{t:"enum",values:["utf-8"],required:!0},locale:{t:"enum",values:["en-US"],required:!0},timezone:{t:"enum",values:["UTC"],required:!0},workspace:{t:"enum",values:["new_run"],required:!0}},FrozenLlm:{approved_actor_user_id:{t:"string",required:!0},catalog_revision:{t:"string",required:!0},control_schema_version:{t:"enum",values:["omics.llm.control.v1"],required:!0},credential:{t:"ref",name:"Credential",required:!0,nullable:!0},effective_org_id:{t:"string",required:!0},engine_entitlement:{t:"enum",values:["free","premium","enterprise"],required:!0},interface:{t:"enum",values:["bedrock_converse"],required:!0},mode:{t:"enum",values:["managed"],required:!0},model:{t:"ref",name:"ModelRef",required:!0},parameters:{t:"ref",name:"Parameters",required:!0},payer:{t:"enum",values:["omics"],required:!0},policy_revision:{t:"enum",values:["biovault-local-1"],required:!0},price_revision:{t:"string",required:!0},run_limits:{t:"ref",name:"RunLimits",required:!0},selection:{t:"union",of:[{t:"ref",name:"Inherit"},{t:"ref",name:"Explicit"}],required:!0},workload:{t:"enum",values:["science.biovault_dataset"],required:!0}},Handoff:{destination:{t:"enum",values:["offer_open_in_omics_os_workspace"],required:!0},start_analysis:{t:"boolean",required:!0}},Harmonization:{preferences:{t:"enum",values:["lobster_decides_and_records"],required:!0}},Inherit:{mode:{t:"enum",values:["inherit"],required:!0}},InitialMessage:{component:{t:"string",required:!0},content:{t:"string",required:!0},role:{t:"enum",values:["system","user"],required:!0}},InstructionAsset:{id:{t:"string",required:!0},kind:{t:"enum",values:["system_prompt","helper_prompt","tool_schema"],required:!0},sha256:{t:"string",required:!0}},InstructionPolicy:{sha256:{t:"string",required:!0},version:{t:"string",required:!0}},InstructionPreview:{execution_manifest_sha256:{t:"string",required:!0},initial_messages:{t:"array",of:{t:"ref",name:"InitialMessage"},required:!0},instruction_bundle_json:{t:"string",required:!0},instruction_bundle_sha256:{t:"string",required:!0},verification_scope:{t:"enum",values:["local_release_assets_and_initial_request","Instructions recorded; not checked by the engine; tools restricted by Omics-OS"],required:!0}},Interaction:{interrupt_run_to_ask_user:{t:"boolean",required:!0},stop_on_blocking_problem:{t:"boolean",required:!0}},Library:{type:{t:"enum",values:["any_rna_seq","poly_a","total_rna_ribo_depleted","tag_3_prime"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Limits:{max_cost_usd:{t:"string",required:!0,nullable:!0},max_storage_bytes:{t:"integer",required:!0,nullable:!0}},Literature:{accessions:{t:"array",of:{t:"string"},required:!0},decision:{t:"enum",values:["include","exclude"],required:!0},doi:{t:"string",required:!0,nullable:!0},file:{t:"string",required:!0},pmid:{t:"string",required:!0,nullable:!0},source:{t:"enum",values:["ris"],required:!0},title:{t:"string",required:!0}},LiteratureDecision:{decision:{t:"enum",values:["include","exclude"],required:!0},file:{t:"string",required:!0},record_index:{t:"integer",required:!0}},LiteratureFile:{bytes:{t:"integer",required:!0},name:{t:"string",required:!0},sha256:{t:"string",required:!0}},Manifest:{assets:{t:"array",of:{t:"ref",name:"InstructionAsset"},required:!0},behavior_settings:{t:"record",of:{t:"boolean"},required:!0},engine:{t:"ref",name:"Artifact",required:!0},fixed_context:{t:"ref",name:"FixedContext",required:!0},manifest_version:{t:"enum",values:["biovault.instructions.v1"],required:!0},policies:{t:"ref",name:"Policies",required:!0},prompt_builder:{t:"ref",name:"Artifact",required:!0}},Metadata:{batch_fields:{t:"enum",values:["unused_v1"],required:!0}},ModelRef:{model_id:{t:"string",required:!0},provider:{t:"enum",values:["bedrock","anthropic"],required:!0}},Node:{id:{t:"string",required:!0},identity_status:{t:"enum",values:["verified","syntax_only","unresolved"],required:!0},label:{t:"string",required:!0},release:{t:"string",required:!0,nullable:!0},role:{t:"enum",values:["target","case","control","tissue","context","stratify","required","never"],required:!0,nullable:!0},snapshot_id:{t:"string",required:!0,nullable:!0},source:{t:"string",required:!0},type:{t:"enum",values:["gene","protein","disease","tissue","cell_type","compound","pathway","variant","accession","other","unresolved"],required:!0}},OmniEvent:{by:{t:"enum",values:["omni"],required:!0},model:{t:"ref",name:"ModelRef",required:!0},prompt_sha256:{t:"string",required:!0},revision:{t:"integer",required:!0}},OmniEvidence:{model:{t:"ref",name:"ModelRef",required:!0},prompt_sha256:{t:"string",required:!0}},Output:{agreement_version:{t:"enum",values:["1"],required:!0},config_key:{t:"enum",values:["biovault_config_json"],required:!0},filename:{t:"enum",values:["dataset.h5mu"],required:!0},format:{t:"enum",values:["h5mu"],required:!0},include_original_inputs:{t:"boolean",required:!0},record_source_and_licence:{t:"boolean",required:!0}},Parameters:{context_window:{t:"integer",required:!0},max_output_tokens:{t:"integer",required:!0},reasoning:{t:"any",required:!0,nullable:!0},temperature:{t:"any",required:!0,nullable:!0}},Policies:{checks:{t:"ref",name:"InstructionPolicy",required:!0},context:{t:"ref",name:"InstructionPolicy",required:!0},graph:{t:"ref",name:"InstructionPolicy",required:!0}},Processing:{batch_preference:{t:"enum",values:["unused_v1"],required:!0}},PromptSection:{end_byte:{t:"integer",required:!0},key:{t:"enum",values:["TASK","QUESTION","NODES","STUDIES","SAMPLES","LIMITS","MODEL","EXTRA","CONFIG"],required:!0},spans:{t:"array",of:{t:"ref",name:"PromptSpan"},required:!0},start_byte:{t:"integer",required:!0}},PromptSpan:{end_byte:{t:"integer",required:!0},kind:{t:"string",required:!0},path:{t:"string",required:!0,nullable:!0},start_byte:{t:"integer",required:!0}},Provenance:{field_history:{t:"record",of:{t:"array",of:{t:"union",of:[{t:"ref",name:"UserEvent"},{t:"ref",name:"OmniEvent"}]}},required:!0},field_origin:{t:"record",of:{t:"enum",values:["user","omni","default"]},required:!0},omni:{t:"ref",name:"OmniEvidence",required:!0,nullable:!0}},Request:{custom_prompt_addition:{t:"string",required:!0},question:{t:"string",required:!0}},RestrictedManifest:{assets:{t:"array",of:{t:"ref",name:"InstructionAsset"},required:!0},behavior_settings:{t:"record",of:{t:"boolean"},required:!0},engine:{t:"ref",name:"Artifact",required:!0},fixed_context:{t:"ref",name:"FixedContext",required:!0},manifest_version:{t:"enum",values:["biovault.instructions.rp1.v1"],required:!0},policies:{t:"ref",name:"Policies",required:!0},prompt_builder:{t:"ref",name:"Artifact",required:!0},restricted_profile:{t:"ref",name:"RestrictedProfile",required:!0}},RestrictedProfile:{profile_id:{t:"enum",values:["geo-counts-tools-v1","geo-counts-tools-v2"],required:!0},sha256:{t:"string",required:!0}},RunConfigV1:{cohorts:{t:"ref",name:"Cohorts",required:!0},config_version:{t:"enum",values:["1"],required:!0},created_by:{t:"string",required:!0},datasets:{t:"ref",name:"Datasets",required:!0},eligibility:{t:"ref",name:"Eligibility",required:!0},execution_contract:{t:"ref",name:"ExecutionContract",required:!0},handoff:{t:"ref",name:"Handoff",required:!0},harmonization:{t:"ref",name:"Harmonization",required:!0},interaction:{t:"ref",name:"Interaction",required:!0},limits:{t:"ref",name:"Limits",required:!0},llm:{t:"ref",name:"FrozenLlm",required:!0},metadata:{t:"ref",name:"Metadata",required:!0},org_id:{t:"string",required:!0},output:{t:"ref",name:"Output",required:!0},processing:{t:"ref",name:"Processing",required:!0},provenance:{t:"ref",name:"Provenance",required:!0},request:{t:"ref",name:"Request",required:!0},run_id:{t:"string",required:!0},scope:{t:"ref",name:"Scope",required:!0},selection:{t:"ref",name:"Selection",required:!0},size:{t:"ref",name:"Size",required:!0},sources:{t:"ref",name:"Sources",required:!0}},RunLimits:{basis:{t:"enum",values:["omics_inference_charge"],required:!0},max_charge_usd:{t:"string",required:!0}},SampleTypes:{allow:{t:"array",of:{t:"enum",values:["primary_tissue","metastasis","cell_line","pdx_or_organoid"]},required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Scope:{assay:{t:"enum",values:["bulk_rna_seq"],required:!0},gene_output:{t:"enum",values:["full_available_matrix"],required:!0},organism:{t:"enum",values:["NCBITaxon:9606"],required:!0}},Selection:{edges:{t:"array",of:{t:"ref",name:"Edge"},required:!0},nodes:{t:"array",of:{t:"ref",name:"Node"},required:!0},reference_release:{t:"string",required:!0,nullable:!0},reference_release_reason:{t:"string",required:!0,nullable:!0}},Sex:{use:{t:"enum",values:["any","report_only"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Size:{preferred_bytes:{t:"integer",required:!0,nullable:!0},preferred_studies:{t:"integer",required:!0,nullable:!0},preferred_subjects:{t:"integer",required:!0,nullable:!0}},Sources:{disallowed:{t:"array",of:{t:"string"},required:!0}},Stratifier:{node:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Treatment:{policy:{t:"enum",values:["lobster_decides_and_records","treatment_naive_only","include_treated_record_regimen"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},UserEvent:{by:{t:"enum",values:["user"],required:!0},revision:{t:"integer",required:!0}},DraftCommand:{config_version:{t:"enum",values:["1"],required:!0},confirm_defaults:{t:"array",of:{t:"string"}},draft:{t:"ref",name:"DraftFieldsV1",required:!0},expected_revision:{t:"integer",nullable:!0}},DraftPreview:{admission_policy:{t:"ref",name:"CeilingPolicySnapshot",required:!0,nullable:!0},approval_generation:{t:"enum",values:["biovault.approval.v1.1"],required:!0},can_execute:{t:"boolean",required:!0},checks:{t:"array",of:{t:"ref",name:"Check"},required:!0},config:{t:"union",of:[{t:"ref",name:"RunConfigV1"},{t:"ref",name:"DraftCandidateV1"}],required:!0},config_bytes:{t:"integer",required:!0},config_json:{t:"string",required:!0},config_sha256:{t:"string",required:!0},editing:{t:"ref",name:"Editing",required:!0},entry_id:{t:"string",required:!0},instructions:{t:"ref",name:"InstructionPreview",required:!0,nullable:!0},prompt:{t:"string",required:!0},prompt_bytes:{t:"integer",required:!0},prompt_sections:{t:"array",of:{t:"ref",name:"PromptSection"},required:!0},prompt_sha256:{t:"string",required:!0},prompt_version:{t:"enum",values:["5","6","7"],required:!0},revision:{t:"integer",required:!0},state:{t:"enum",values:["planning"],required:!0},success:{t:"boolean",required:!0}},ExecuteCommand:{config_sha256:{t:"string",required:!0},execution_manifest_sha256:{t:"string",required:!0},expected_revision:{t:"integer",required:!0},expected_turn_generation:{t:"integer",required:!0},instruction_bundle_sha256:{t:"string",required:!0},prompt_sha256:{t:"string",required:!0},prompt_version:{t:"enum",values:["5","6","7"],required:!0}}};var go={};Fn(go,{KNOWN_VALUES:()=>Od,SCHEMA_REVISION:()=>Ad,WIRE_SHAPES:()=>We});var Ad=5,Od={DatasetResultV1:{outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"],stop_reason:["cost_limit","storage_limit","blocking_problem"]},DecisionsPageV1:{folder_outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"]},Diagnostics:{outcome:["incomplete","failed"]},ErrorDetail:{code:["CONFIG_TOO_LARGE","INVALID_REQUEST","DRAFT_BLOCKED","LIMIT_REQUIRED","LIMIT_INVALID","STORAGE_LIMIT_TOO_SMALL","LIMIT_CEILING_EXCEEDED","CONFIG_CHANGED","DRAFT_EDIT_IN_PROGRESS","DRAFT_TURN_INVALID","DRAFT_TURN_CONFLICT","DRAFT_EXPIRED","ENTRY_NOT_PLANNING","CONFIG_VERSION_REAPPROVAL_REQUIRED","LITERATURE_FILE_INVALID","LITERATURE_FILE_CHANGED","SAMPLES_NOT_READY","INVALID_CURSOR","RECORD_CHANGED","RUN_COST_LIMIT","RUN_STORAGE_LIMIT","RUN_CONTEXT_CONFLICT","WORKER_CONTRACT_MISMATCH","RUN_SCIENCE_ALREADY_STARTED","RUN_CAPACITY_REACHED","RUN_CAPACITY_UNAVAILABLE","OMNI_TOOL_FORBIDDEN","NOT_FOUND","UNAUTHORIZED","ACCESS_DENIED","LEGACY_COMPUTE_CLOSED","CANCEL_CLEANUP_INCOMPLETE","POLICY_UNAVAILABLE","CEILING_POLICY_UNAVAILABLE","INSTRUCTION_MANIFEST_UNAVAILABLE","BUDGET_UNAVAILABLE","USAGE_RECORDING_UNAVAILABLE","SERVICE_UNAVAILABLE","INSTRUCTION_BOUNDARY_UNQUALIFIED","MODEL_POLICY_UNAVAILABLE","MODEL_UNKNOWN"]},JobDetail:{outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"],stop_reason:["cost_limit","storage_limit","blocking_problem"]},PackageResponseV1:{outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"],stop_reason:["cost_limit","storage_limit","blocking_problem"]},ProblemV1:{problem_kind:["no_healthy_donors","too_few_samples","too_few_controls","empty_case_group","empty_control_group","mixed_studies","target_gene_absent","treated_samples","treatment_unknown","under_18","metadata_missing","pairing_unmet","platform_mixed","non_rnaseq_study","organism_out_of_scope","units_unknown","incompatible_units","unlabelled_samples","duplicate_samples","mapping_ambiguity","reference_without_dataset","rights_unknown","assay_inferred_bulk","unit_inferred_not_proven","geo_column_rule_used","eligibility_violation","excluded_dataset_used","disallowed_source_used","cost_limit","storage_limit","draft_warning"]},ProblemsPageV1:{folder_outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"]},RunRowV1:{outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"],stop_reason:["cost_limit","storage_limit","blocking_problem"]},SamplesPage:{folder_outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"]},SummaryV1:{outcome:["complete","complete_with_problems","incomplete","failed","stopped_at_limit"],stop_reason:["cost_limit","storage_limit","blocking_problem"]}},We={AgentToolCalls:{agent:{t:"string",required:!0},calls:{t:"integer",required:!0},tool:{t:"string",required:!0}},ArchiveInfo:{available:{t:"boolean",required:!0},sha256:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},size_bytes:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},skipped_reason:{t:"maybe",of:{t:"enum",values:["too_large","too_many_files","build_failed","not_built"]},required:!0,nullable:!0}},Artifact:{artifact_sha256:{t:"string",required:!0},version:{t:"string",required:!0},version_sha256:{t:"string",required:!0}},Cohorts:{control_fallback:{t:"literal",value:"label_adjacent_normal_as_adjacent_normal_never_as_healthy_report_shortfall",required:!0},control_preference:{t:"enum",values:["lobster_decides_and_records","healthy_donors","adjacent_normal","no_controls"],required:!0},covariates:{t:"array",of:{t:"ref",name:"Covariate"},required:!0},intent:{t:"string",required:!0},min_samples_per_group:{t:"integer",required:!0},pairing_preference:{t:"enum",values:["no_preference","prefer_paired","require_paired"],required:!0},stratify_by:{t:"array",of:{t:"ref",name:"Stratifier"},required:!0}},Cost:{basis:{t:"enum",values:["omics_inference_charge","provider_cost_estimate"],required:!0},inflight_upper_bound_usd:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},limit_usd:{t:"string",required:!0},provisional_usd:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},reason:{t:"maybe",of:{t:"string"},nullable:!0},source:{t:"enum",values:["biovault_interim","llm_control_plane","gateway_run_ledger","unavailable"],required:!0},spent_usd:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},unresolved:{t:"maybe",of:{t:"boolean"},required:!0,nullable:!0}},Counters:{downloads_fetched:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},downloads_queued:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},step_started_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},tokens_at_least:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0}},Covariate:{name:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Credential:{binding_id:{t:"string",required:!0},version:{t:"string",required:!0}},DatasetLedgerRow:{accession:{t:"string",required:!0},assay:{t:"maybe",of:{t:"string"},nullable:!0},decided_by:{t:"enum",values:["user","omni","lobster","validator"],required:!0},literature_references:{t:"array",of:{t:"string"},required:!0},platform:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},reason:{t:"string",required:!0},repository:{t:"string",required:!0},sample_count:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},title:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},DatasetRef:{accession:{t:"string",required:!0},reason:{t:"string",required:!0}},DatasetResultV1:{archive:{t:"ref",name:"ArchiveInfo",required:!0},blocking_problems:{t:"integer",required:!0},config_sha256:{t:"string",required:!0},decisions:{t:"integer",required:!0},folder_state:{t:"enum",values:["complete","partial"],required:!0},manifest_sha256:{t:"string",required:!0},metadata_assistant_observed:{t:"boolean",required:!0},model_id:{t:"string",required:!0},outcome:{t:"string",required:!0},problems:{t:"integer",required:!0},prompt_sha256:{t:"string",required:!0},samples:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},stop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},studies:{t:"integer",required:!0}},Datasets:{change_policy:{t:"literal",value:"replace_failed_within_scope_never_excluded",required:!0},commercially_usable_only:{t:"boolean",required:!0},exclude:{t:"array",of:{t:"ref",name:"DatasetRef"},required:!0},include:{t:"array",of:{t:"ref",name:"DatasetRef"},required:!0},literature:{t:"array",of:{t:"ref",name:"Literature"},required:!0},literature_files:{t:"array",of:{t:"ref",name:"LiteratureFile"},required:!0},mode:{t:"enum",values:["discover_within_scope","listed_only","both"],required:!0}},DatasetsSummary:{excluded:{t:"array",of:{t:"ref",name:"DatasetLedgerRow"},required:!0},included:{t:"array",of:{t:"ref",name:"DatasetLedgerRow"},required:!0},not_reached:{t:"array",of:{t:"ref",name:"DatasetLedgerRow"},required:!0}},DecisionV1:{actor:{t:"string",required:!0},alternatives_considered:{t:"array",of:{t:"string"},required:!0},datasets_used:{t:"array",of:{t:"string"},required:!0},decision:{t:"string",required:!0},id:{t:"string",required:!0},links:{t:"array",of:{t:"string"},required:!0},reason:{t:"string",required:!0}},DecisionsPageV1:{config_sha256:{t:"string",required:!0},failure_reasons:{t:"array",of:{t:"string"},required:!0},folder_outcome:{t:"string",required:!0},folder_published:{t:"boolean",required:!0},items:{t:"array",of:{t:"ref",name:"DecisionV1"},required:!0},job_id:{t:"string",required:!0},limit:{t:"integer",required:!0},next_cursor:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},record_sha256:{t:"string",required:!0},success:{t:"literal",value:!0,required:!0},total:{t:"integer",required:!0}},Diagnostics:{outcome:{t:"string",required:!0},reasons:{t:"array",of:{t:"string"},required:!0}},DroppedCount:{count:{t:"integer",required:!0},stage:{t:"string",required:!0}},Edge:{from:{t:"string",required:!0},intent:{t:"string",required:!0},release:{t:"string",required:!0},source:{t:"string",required:!0},to:{t:"string",required:!0}},Eligibility:{donor_age_when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0},donors_under_18:{t:"enum",values:["lobster_decides_and_records","include","exclude"],required:!0},exclude:{t:"array",of:{t:"string"},required:!0},include:{t:"array",of:{t:"string"},required:!0},library:{t:"ref",name:"Library",required:!0},preferences:{t:"array",of:{t:"string"},required:!0},sample_types:{t:"ref",name:"SampleTypes",required:!0},sex:{t:"ref",name:"Sex",required:!0},treatment_status:{t:"ref",name:"Treatment",required:!0}},ErrorDetail:{code:{t:"string",required:!0},issues:{t:"maybe",of:{t:"array",of:{t:"any"}},nullable:!0},message:{t:"string",required:!0},request_id:{t:"maybe",of:{t:"string"},nullable:!0},retryable:{t:"boolean",required:!0},run_id:{t:"maybe",of:{t:"string"},nullable:!0},status:{t:"integer",required:!0}},ErrorEnvelope:{detail:{t:"ref",name:"ErrorDetail",required:!0}},ExcludedCount:{count:{t:"integer",required:!0},reason:{t:"string",required:!0}},ExecutionContract:{manifest:{t:"union",of:[{t:"ref",name:"Manifest"},{t:"ref",name:"RestrictedManifest"}],required:!0},manifest_sha256:{t:"string",required:!0}},Explicit:{mode:{t:"literal",value:"explicit",required:!0},model:{t:"ref",name:"api__models_vault_run_v1__ModelRef",required:!0}},FieldLabel:{evidence:{t:"string",required:!0},field:{t:"string",required:!0},source:{t:"literal",value:"field",required:!0}},FixedContext:{clock_utc:{t:"string",required:!0},conversation:{t:"literal",value:"empty",required:!0},encoding:{t:"literal",value:"utf-8",required:!0},locale:{t:"literal",value:"en-US",required:!0},timezone:{t:"literal",value:"UTC",required:!0},workspace:{t:"literal",value:"new_run",required:!0}},FrozenLlm:{approved_actor_user_id:{t:"string",required:!0},catalog_revision:{t:"string",required:!0},control_schema_version:{t:"literal",value:"omics.llm.control.v1",required:!0},credential:{t:"maybe",of:{t:"ref",name:"Credential"},required:!0,nullable:!0},effective_org_id:{t:"string",required:!0},engine_entitlement:{t:"enum",values:["free","premium","enterprise"],required:!0},interface:{t:"literal",value:"bedrock_converse",required:!0},mode:{t:"literal",value:"managed",required:!0},model:{t:"ref",name:"api__models_vault_run_v1__ModelRef",required:!0},parameters:{t:"ref",name:"Parameters",required:!0},payer:{t:"literal",value:"omics",required:!0},policy_revision:{t:"literal",value:"biovault-local-1",required:!0},price_revision:{t:"string",required:!0},run_limits:{t:"ref",name:"RunLimits",required:!0},selection:{t:"union",of:[{t:"ref",name:"Inherit"},{t:"ref",name:"Explicit"}],required:!0},workload:{t:"literal",value:"science.biovault_dataset",required:!0}},Funnel:{datasets:{t:"ref",name:"FunnelDatasets",required:!0},samples:{t:"ref",name:"FunnelSamples",required:!0},search:{t:"ref",name:"FunnelSearch",required:!0}},FunnelDatasets:{excluded:{t:"array",of:{t:"ref",name:"ExcludedCount"},required:!0},found:{t:"integer",required:!0},included:{t:"integer",required:!0},not_reached:{t:"integer",required:!0},screened:{t:"integer",required:!0}},FunnelSamples:{dropped:{t:"array",of:{t:"ref",name:"DroppedCount"},required:!0},in_included:{t:"integer",required:!0},kept:{t:"integer",required:!0}},FunnelSearch:{not_searched:{t:"array",of:{t:"string"},required:!0},sources:{t:"array",of:{t:"ref",name:"FunnelSearchSource"},required:!0},synonyms:{t:"array",of:{t:"string"},required:!0}},FunnelSearchSource:{deduplicated_hits:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},hits:{t:"integer",required:!0},name:{t:"string",required:!0},query:{t:"string",required:!0},raw_hits:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},retrieved_at:{t:"string",required:!0}},FunnelValidation:{issues:{t:"array",of:{t:"string"},required:!0},state:{t:"enum",values:["verified","inconsistent","not_recorded"],required:!0}},GeneJoin:{dropped_genes:{t:"integer",required:!0},kept_genes:{t:"integer",required:!0},key:{t:"string",required:!0},method:{t:"literal",value:"intersection",required:!0}},GroupCount:{condition:{t:"string",required:!0},control_type:{t:"string",required:!0},independent_subjects:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},samples:{t:"integer",required:!0},study:{t:"string",required:!0}},Handoff:{destination:{t:"literal",value:"offer_open_in_omics_os_workspace",required:!0},start_analysis:{t:"literal",value:!1,required:!0}},Harmonization:{preferences:{t:"literal",value:"lobster_decides_and_records",required:!0}},Inherit:{mode:{t:"literal",value:"inherit",required:!0}},InstructionAsset:{id:{t:"string",required:!0},kind:{t:"enum",values:["system_prompt","helper_prompt","tool_schema"],required:!0},sha256:{t:"string",required:!0}},InstructionPolicy:{sha256:{t:"string",required:!0},version:{t:"string",required:!0}},Interaction:{interrupt_run_to_ask_user:{t:"literal",value:!1,required:!0},stop_on_blocking_problem:{t:"boolean",required:!0}},InvokedModel:{count:{t:"integer",required:!0},model:{t:"ref",name:"api__models_vault_delivery_v1__ModelRef",required:!0}},JobDetail:{approval_generation:{t:"literal",value:"biovault.approval.v1.1",required:!0},cancel_cleanup_status:{t:"maybe",of:{t:"enum",values:["pending","complete"]},required:!0,nullable:!0},config_sha256:{t:"string",required:!0},cost:{t:"ref",name:"Cost",required:!0},counters:{t:"ref",name:"Counters",required:!0},created_at:{t:"string",required:!0},dataset_diagnostics:{t:"maybe",of:{t:"ref",name:"Diagnostics"},required:!0,nullable:!0},dataset_result:{t:"maybe",of:{t:"ref",name:"DatasetResultV1"},required:!0,nullable:!0},execution_manifest_sha256:{t:"string",required:!0},failure:{t:"maybe",of:{t:"ref",name:"RunFailure"},nullable:!0},finished_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},instruction_bundle_sha256:{t:"string",required:!0},job_id:{t:"string",required:!0},last_progress_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},outcome:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},progress_pct:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},progress_step:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},prompt_sha256:{t:"string",required:!0},question:{t:"string",required:!0},run_config:{t:"ref",name:"RunConfigReadV1",required:!0},run_id:{t:"string",required:!0},run_terminal:{t:"maybe",of:{t:"boolean"},required:!0,nullable:!0},selection:{t:"ref",name:"SelectionRead",required:!0},status:{t:"enum",values:["queued","discovering","acquiring","harmonizing","analyzing","packaging","completed","failed","cancelled"],required:!0},stop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},title:{t:"string",required:!0},updated_at:{t:"string",required:!0}},JobDetailResponse:{job:{t:"ref",name:"JobDetail",required:!0},message:{t:"string",required:!0},success:{t:"literal",value:!0,required:!0}},LabelsSummary:{adjacent_normal:{t:"integer",required:!0},case:{t:"integer",required:!0},control:{t:"integer",required:!0},control_type_unresolved:{t:"integer",required:!0},healthy_donor:{t:"integer",required:!0},resolved:{t:"integer",required:!0},samples:{t:"integer",required:!0},unresolved:{t:"integer",required:!0}},Library:{type:{t:"enum",values:["any_rna_seq","poly_a","total_rna_ribo_depleted","tag_3_prime"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Limits:{max_cost_usd:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},max_storage_bytes:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0}},Literature:{accessions:{t:"array",of:{t:"string"},required:!0},decision:{t:"enum",values:["include","exclude"],required:!0},doi:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},file:{t:"string",required:!0},pmid:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},source:{t:"literal",value:"ris",required:!0},title:{t:"string",required:!0}},LiteratureFile:{bytes:{t:"integer",required:!0},name:{t:"string",required:!0},sha256:{t:"string",required:!0}},Liveness:{interval_seconds:{t:"integer"},stale_after_seconds:{t:"integer"}},LlmLabel:{evidence:{t:"string",required:!0},model_id:{t:"string",required:!0},prompt_sha256:{t:"string",required:!0},provider:{t:"enum",values:["bedrock","anthropic"],required:!0},source:{t:"literal",value:"llm",required:!0}},Manifest:{assets:{t:"array",of:{t:"ref",name:"InstructionAsset"},required:!0},behavior_settings:{t:"record",of:{t:"boolean"},required:!0},engine:{t:"ref",name:"Artifact",required:!0},fixed_context:{t:"ref",name:"FixedContext",required:!0},manifest_version:{t:"literal",value:"biovault.instructions.v1",required:!0},policies:{t:"ref",name:"Policies",required:!0},prompt_builder:{t:"ref",name:"Artifact",required:!0}},ManifestEntry:{derived_from:{t:"array",of:{t:"string"},required:!0},licence:{t:"string",required:!0},path:{t:"string",required:!0},role:{t:"enum",values:["main","original","mapping","metadata","preparation","quality","doc","other"],required:!0},sha256:{t:"string",required:!0},size:{t:"integer",required:!0},source:{t:"string",required:!0}},Metadata:{batch_fields:{t:"literal",value:"unused_v1",required:!0}},OmniEvent:{by:{t:"literal",value:"omni",required:!0},model:{t:"ref",name:"api__models_vault_run_v1__ModelRef",required:!0},prompt_sha256:{t:"string",required:!0},revision:{t:"integer",required:!0}},OmniEvidence:{model:{t:"ref",name:"api__models_vault_run_v1__ModelRef",required:!0},prompt_sha256:{t:"string",required:!0}},Output:{agreement_version:{t:"literal",value:"1",required:!0},config_key:{t:"literal",value:"biovault_config_json",required:!0},filename:{t:"literal",value:"dataset.h5mu",required:!0},format:{t:"literal",value:"h5mu",required:!0},include_original_inputs:{t:"literal",value:!0,required:!0},record_source_and_licence:{t:"literal",value:!0,required:!0}},Override:{at:{t:"string",required:!0},by:{t:"string",required:!0},field:{t:"string",required:!0},from:{t:"string",required:!0},reason:{t:"string",required:!0},to:{t:"string",required:!0}},PackageDownloadV1:{expires_in_seconds:{t:"literal",value:300,required:!0},filename:{t:"string",required:!0},job_id:{t:"string",required:!0},path:{t:"string",required:!0},sha256:{t:"string",required:!0},size_bytes:{t:"integer",required:!0},success:{t:"literal",value:!0,required:!0},url:{t:"string",required:!0}},PackageResponseV1:{archive:{t:"ref",name:"ArchiveInfo",required:!0},config_sha256:{t:"string",required:!0},cost:{t:"ref",name:"Cost",required:!0},files:{t:"array",of:{t:"ref",name:"ManifestEntry"},required:!0},folder_state:{t:"enum",values:["complete","partial"],required:!0},job_id:{t:"string",required:!0},manifest_sha256:{t:"string",required:!0},outcome:{t:"string",required:!0},preparation:{t:"ref",name:"PreparationV1",required:!0},prompt_sha256:{t:"string",required:!0},record_sha256:{t:"string",required:!0},stop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},success:{t:"literal",value:!0,required:!0},summary:{t:"ref",name:"SummaryV1",required:!0},totals:{t:"ref",name:"PackageTotals",required:!0}},PackageTotals:{bytes:{t:"integer",required:!0},files:{t:"integer",required:!0}},Parameters:{context_window:{t:"integer",required:!0},max_output_tokens:{t:"integer",required:!0},reasoning:{t:"literal",value:null,required:!0,nullable:!0},temperature:{t:"literal",value:null,required:!0,nullable:!0}},Policies:{checks:{t:"ref",name:"InstructionPolicy",required:!0},context:{t:"ref",name:"InstructionPolicy",required:!0},graph:{t:"ref",name:"InstructionPolicy",required:!0}},PreparationV1:{agents_and_tools:{t:"array",of:{t:"ref",name:"AgentToolCalls"},required:!0},configured_model_id:{t:"string",required:!0},data_availability_text:{t:"string",required:!0},finished_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},invoked_model_id:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},invoked_models:{t:"array",of:{t:"ref",name:"InvokedModel"},required:!0},metadata_assistant_observed:{t:"boolean",required:!0},methods_text:{t:"string",required:!0},rejected_tool_calls:{t:"array",of:{t:"ref",name:"RejectedToolCall"}},started_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},ProblemV1:{actor:{t:"string",required:!0},affected:{t:"array",of:{t:"string"},required:!0},evidence:{t:"array",of:{t:"string"},required:!0},id:{t:"string",required:!0},impact:{t:"string",required:!0},lobster_decision:{t:"string",required:!0},problem_kind:{t:"string",required:!0},severity:{t:"enum",values:["blocking","warning","info"],required:!0},source_check_code:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},status:{t:"enum",values:["resolved","unresolved"],required:!0},what:{t:"string",required:!0},why:{t:"string",required:!0}},ProblemsPageV1:{blocking:{t:"integer",required:!0},config_sha256:{t:"string",required:!0},failure_reasons:{t:"array",of:{t:"string"},required:!0},folder_outcome:{t:"string",required:!0},folder_published:{t:"boolean",required:!0},items:{t:"array",of:{t:"ref",name:"ProblemV1"},required:!0},job_id:{t:"string",required:!0},limit:{t:"integer",required:!0},next_cursor:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},record_sha256:{t:"string",required:!0},success:{t:"literal",value:!0,required:!0},total:{t:"integer",required:!0},unresolved:{t:"integer",required:!0}},Processing:{batch_preference:{t:"literal",value:"unused_v1",required:!0}},Provenance:{field_history:{t:"record",of:{t:"array",of:{t:"union",of:[{t:"ref",name:"UserEvent"},{t:"ref",name:"OmniEvent"}]}},required:!0},field_origin:{t:"record",of:{t:"enum",values:["user","omni","default"]},required:!0},omni:{t:"maybe",of:{t:"ref",name:"OmniEvidence"},required:!0,nullable:!0}},Quantification:{gene_join:{t:"maybe",of:{t:"ref",name:"GeneJoin"},required:!0,nullable:!0},studies:{t:"array",of:{t:"ref",name:"StudyQuantification"},required:!0}},RejectedToolCall:{count:{t:"integer",required:!0},name:{t:"string",required:!0},status:{t:"literal",value:"not dispatched",required:!0}},Request:{custom_prompt_addition:{t:"string",required:!0},question:{t:"string",required:!0}},RestrictedManifest:{assets:{t:"array",of:{t:"ref",name:"InstructionAsset"},required:!0},behavior_settings:{t:"record",of:{t:"boolean"},required:!0},engine:{t:"ref",name:"Artifact",required:!0},fixed_context:{t:"ref",name:"FixedContext",required:!0},manifest_version:{t:"literal",value:"biovault.instructions.rp1.v1",required:!0},policies:{t:"ref",name:"Policies",required:!0},prompt_builder:{t:"ref",name:"Artifact",required:!0},restricted_profile:{t:"ref",name:"RestrictedProfile",required:!0}},RestrictedProfile:{profile_id:{t:"enum",values:["geo-counts-tools-v1","geo-counts-tools-v2"],required:!0},sha256:{t:"string",required:!0}},RuleLabel:{evidence:{t:"string",required:!0},rule:{t:"string",required:!0},source:{t:"literal",value:"rule",required:!0}},RunConfigReadV1:{cohorts:{t:"ref",name:"Cohorts",required:!0},config_version:{t:"literal",value:"1",required:!0},created_by:{t:"string",required:!0},datasets:{t:"ref",name:"Datasets",required:!0},eligibility:{t:"ref",name:"Eligibility",required:!0},execution_contract:{t:"ref",name:"ExecutionContract",required:!0},handoff:{t:"ref",name:"Handoff",required:!0},harmonization:{t:"ref",name:"Harmonization",required:!0},interaction:{t:"ref",name:"Interaction",required:!0},limits:{t:"ref",name:"Limits",required:!0},llm:{t:"ref",name:"FrozenLlm",required:!0},metadata:{t:"ref",name:"Metadata",required:!0},org_id:{t:"string",required:!0},output:{t:"ref",name:"Output",required:!0},processing:{t:"ref",name:"Processing",required:!0},provenance:{t:"ref",name:"Provenance",required:!0},request:{t:"ref",name:"Request",required:!0},run_id:{t:"string",required:!0},scope:{t:"ref",name:"Scope",required:!0},selection:{t:"ref",name:"SelectionRead",required:!0},size:{t:"ref",name:"Size",required:!0},sources:{t:"ref",name:"Sources",required:!0}},RunFailure:{detail:{t:"string",required:!0},message:{t:"string",required:!0},provider_stop_reason:{t:"maybe",of:{t:"string"},nullable:!0},reason:{t:"string",required:!0}},RunLimits:{basis:{t:"literal",value:"omics_inference_charge",required:!0},max_charge_usd:{t:"string",required:!0}},RunListV1:{jobs:{t:"array",of:{t:"ref",name:"RunRowV1"},required:!0},message:{t:"string",required:!0},next_cursor:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},success:{t:"literal",value:!0,required:!0},total:{t:"integer",required:!0}},RunRowV1:{approval_generation:{t:"literal",value:"biovault.approval.v1.1",required:!0},cancel_cleanup_status:{t:"maybe",of:{t:"enum",values:["pending","complete"]},required:!0,nullable:!0},config_sha256:{t:"string",required:!0},cost:{t:"ref",name:"Cost",required:!0},created_at:{t:"string",required:!0},execution_manifest_sha256:{t:"string",required:!0},failure:{t:"maybe",of:{t:"ref",name:"RunFailure"},nullable:!0},instruction_bundle_sha256:{t:"string",required:!0},job_id:{t:"string",required:!0},outcome:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},progress_pct:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},progress_step:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},prompt_sha256:{t:"string",required:!0},question:{t:"string",required:!0},run_config:{t:"ref",name:"RunConfigReadV1",required:!0},run_id:{t:"string",required:!0},run_terminal:{t:"maybe",of:{t:"boolean"},required:!0,nullable:!0},selection:{t:"ref",name:"SelectionRead",required:!0},status:{t:"enum",values:["queued","discovering","acquiring","harmonizing","analyzing","packaging","completed","failed","cancelled"],required:!0},stop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},title:{t:"string",required:!0},updated_at:{t:"string",required:!0}},RunStep:{id:{t:"enum",values:["queued","preparing","checking","complete"],required:!0},label:{t:"string",required:!0},statuses:{t:"array",of:{t:"enum",values:["queued","discovering","acquiring","harmonizing","analyzing","packaging","completed"]},required:!0}},SampleAssay:{basis:{t:"maybe",of:{t:"enum",values:["structured","geo_structured_rule"]},nullable:!0},conflict:{t:"boolean",required:!0},evidence_fields:{t:"array",of:{t:"string"},required:!0},proven:{t:"boolean",required:!0},value:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},SampleRow:{assay:{t:"maybe",of:{t:"ref",name:"SampleAssay"},nullable:!0},column:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},condition:{t:"enum",values:["case","control","other","unknown"],required:!0},control_type:{t:"enum",values:["healthy_donor","adjacent_normal","other","unknown","not_applicable"],required:!0},covariates:{t:"record",of:{t:"maybe",of:{t:"string"}},required:!0},drop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},drop_stage:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},duplicate_of:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},file:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},h5mu_row:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},id:{t:"string",required:!0},included:{t:"boolean",required:!0},label:{t:"union",of:[{t:"ref",name:"FieldLabel"},{t:"ref",name:"RuleLabel"},{t:"ref",name:"LlmLabel"},{t:"ref",name:"UnknownLabel"}],required:!0},label_provenance:{t:"record",of:{t:"union",of:[{t:"ref",name:"FieldLabel"},{t:"ref",name:"RuleLabel"},{t:"ref",name:"LlmLabel"},{t:"ref",name:"UnknownLabel"}]},required:!0},original:{t:"record",of:{t:"union",of:[{t:"string"},{t:"array",of:{t:"string"}}]},required:!0},overrides:{t:"array",of:{t:"ref",name:"Override"},required:!0},run:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},sample_type:{t:"string",required:!0},sex:{t:"enum",values:["female","male","other","unknown"],required:!0},strata:{t:"record",of:{t:"maybe",of:{t:"string"}},required:!0},study:{t:"string",required:!0},treatment:{t:"enum",values:["naive","treated","unknown"],required:!0},treatment_regimen:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},SampleTypes:{allow:{t:"array",of:{t:"enum",values:["primary_tissue","metastasis","cell_line","pdx_or_organoid"]},required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},SamplesPage:{config_sha256:{t:"string",required:!0},folder_outcome:{t:"string",required:!0},folder_published:{t:"boolean",required:!0},items:{t:"array",of:{t:"ref",name:"SampleRow"},required:!0},job_id:{t:"string",required:!0},limit:{t:"integer",required:!0},matched_total:{t:"integer",required:!0},next_cursor:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},record_sha256:{t:"string",required:!0},success:{t:"literal",value:!0,required:!0},total:{t:"integer",required:!0}},Scope:{assay:{t:"literal",value:"bulk_rna_seq",required:!0},gene_output:{t:"literal",value:"full_available_matrix",required:!0},organism:{t:"literal",value:"NCBITaxon:9606",required:!0}},SelectionNode:{id:{t:"string",required:!0},identity_status:{t:"enum",values:["verified","syntax_only","unresolved"],required:!0},label:{t:"string",required:!0},release:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},role:{t:"enum",values:["target","case","control","tissue","context","stratify","required","never"],required:!0},snapshot_id:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},source:{t:"string",required:!0},type:{t:"enum",values:["gene","protein","disease","tissue","cell_type","compound","pathway","variant","accession","other","unresolved"],required:!0}},SelectionRead:{edges:{t:"array",of:{t:"ref",name:"Edge"},required:!0},nodes:{t:"array",of:{t:"ref",name:"SelectionNode"},required:!0},reference_release:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},reference_release_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},Sex:{use:{t:"enum",values:["any","report_only"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},Size:{preferred_bytes:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},preferred_studies:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},preferred_subjects:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0}},Sources:{disallowed:{t:"array",of:{t:"string"},required:!0}},Stratifier:{node:{t:"string",required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},StudyQuantification:{accession:{t:"string",required:!0},annotation:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},genome_build:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},level:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},library:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},platform:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},quantifier:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},unit:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},StudyRights:{accession:{t:"string",required:!0},acknowledgement:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},commercial_use:{t:"enum",values:["allowed","not_allowed","unknown"],required:!0},policy_url:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},redistribution:{t:"enum",values:["allowed","not_allowed","unknown"],required:!0},retrieved_at:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},terms:{t:"maybe",of:{t:"string"},required:!0,nullable:!0}},SummaryV1:{blocking_problems:{t:"integer",required:!0},config_sha256:{t:"string",required:!0},datasets:{t:"ref",name:"DatasetsSummary",required:!0},decisions:{t:"integer",required:!0},funnel:{t:"maybe",of:{t:"ref",name:"Funnel"},required:!0,nullable:!0},funnel_validation:{t:"ref",name:"FunnelValidation",required:!0},groups:{t:"array",of:{t:"ref",name:"GroupCount"},required:!0},labels:{t:"maybe",of:{t:"ref",name:"LabelsSummary"},required:!0,nullable:!0},outcome:{t:"string",required:!0},problems:{t:"integer",required:!0},quantification:{t:"ref",name:"Quantification",required:!0},rights:{t:"array",of:{t:"ref",name:"StudyRights"},required:!0},run_id:{t:"string",required:!0},samples:{t:"maybe",of:{t:"integer"},required:!0,nullable:!0},stop_reason:{t:"maybe",of:{t:"string"},required:!0,nullable:!0},target_genes_present:{t:"record",of:{t:"maybe",of:{t:"boolean"}},required:!0},unresolved_problems:{t:"integer",required:!0}},Treatment:{policy:{t:"enum",values:["lobster_decides_and_records","treatment_naive_only","include_treated_record_regimen"],required:!0},when_missing:{t:"enum",values:["exclude","flag","unknown"],required:!0}},UnknownLabel:{evidence:{t:"string",required:!0},source:{t:"literal",value:"unknown",required:!0}},UserEvent:{by:{t:"literal",value:"user",required:!0},revision:{t:"integer",required:!0}},api__models_vault_delivery_v1__ModelRef:{model_id:{t:"string",required:!0},provider:{t:"enum",values:["bedrock","anthropic"],required:!0}},api__models_vault_run_v1__ModelRef:{model_id:{t:"string",required:!0},provider:{t:"enum",values:["bedrock","anthropic"],required:!0}},PackageDeliveryV1:{decisions:{t:"ref",name:"DecisionsPageV1",required:!0},download:{t:"ref",name:"PackageDownloadV1",required:!0},error:{t:"ref",name:"ErrorEnvelope",required:!0},job:{t:"ref",name:"JobDetailResponse",required:!0},jobs:{t:"ref",name:"RunListV1",required:!0},liveness:{t:"ref",name:"Liveness",required:!0},package:{t:"ref",name:"PackageResponseV1",required:!0},problems:{t:"ref",name:"ProblemsPageV1",required:!0},run_steps:{t:"array",of:{t:"ref",name:"RunStep"},required:!0},samples:{t:"ref",name:"SamplesPage",required:!0}}};var fa=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Zt(t,e,r,n){switch(e.t){case"literal":return r===e.value?null:`${n}: expected ${JSON.stringify(e.value)}`;case"union":return e.of.some(o=>Zt(t,o,r,n)===null)?null:`${n}: no union branch matched`;case"string":return typeof r=="string"?null:`${n}: expected a string`;case"any":return null;case"number":return typeof r=="number"&&Number.isFinite(r)?null:`${n}: expected a number`;case"maybe":return r===null?null:Zt(t,e.of,r,n);case"integer":return Number.isInteger(r)?null:`${n}: expected an integer`;case"boolean":return typeof r=="boolean"?null:`${n}: expected true or false`;case"enum":return typeof r=="string"&&e.values.includes(r)?null:`${n}: expected one of ${e.values.join(", ")}`;case"array":{if(!Array.isArray(r))return`${n}: expected a list`;for(let o=0;o<r.length;o++){let i=Zt(t,e.of,r[o],`${n}[${o}]`);if(i)return i}return null}case"record":{if(!fa(r))return`${n}: expected an object`;for(let[o,i]of Object.entries(r)){let s=Zt(t,e.of,i,`${n}.${o}`);if(s)return s}return null}case"ref":return pa(t,e.name,r,n)}}function pa(t,e,r,n){if(!fa(r))return`${n}: expected an object`;let o=t[e];if(!o)return`${n}: this page has no shape named ${e}`;for(let[i,s]of Object.entries(o)){let a=r[i];if(a===void 0){if(s.required)return`${n}.${i}: missing`;continue}if(a===null){if(s.nullable)continue;return`${n}.${i}: must not be null`}let l=Zt(t,s,a,`${n}.${i}`);if(l)return l}return null}function Le(t,e,r){return pa(r,t,e,t)}var er="Instructions recorded; not checked by the engine; tools restricted by Omics-OS",_o="local_release_assets_and_initial_request",it="biovault.instructions.rp1.v1",vt="biovault.instructions.v1",St="biovault.initial.instructions.rp1.v1",tr="biovault.initial.instructions.v1";function Ur(t){let r=(t&&typeof t=="object"?t.execution_contract:void 0)?.manifest?.manifest_version;return typeof r=="string"?r:null}var $d=t=>Ur(t)===it;var Td=(t,e)=>{let r=Array.from(t),n=Array.from(e);for(let o=0;o<Math.min(r.length,n.length);o++){let i=r[o].codePointAt(0)-n[o].codePointAt(0);if(i!==0)return i}return r.length-n.length};function ha(t){let e=r=>Array.isArray(r)?r.map(e):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort(Td).map(n=>[n,e(r[n])])):r;return JSON.stringify(e(t))}async function rr(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e),r=>r.toString(16).padStart(2,"0")).join("")}var Mr=(t,e)=>{if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null||Array.isArray(t)!==Array.isArray(e))return!1;let r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(o=>Object.prototype.hasOwnProperty.call(e,o)&&Mr(t[o],e[o]))},yo=t=>{let e=t.config.execution_contract;return e&&typeof e.manifest_sha256=="string"&&e.manifest&&typeof e.manifest=="object"?e:null},ma={"geo-counts-tools-v1":{bundle_version:St,assurance:er},"geo-counts-tools-v2":{bundle_version:St,assurance:er}},Rd=/^[0-9a-f]{64}$/,jd=(t,e)=>{let r=t.manifest,n={stage:"installed_inventory_only",manifest:t.manifest,initial_messages:[{component:"supervisor",role:"user",content:e}],pinned_sources:r.assets??null,native_request_verified:!1};if(r.manifest_version===vt)return"restricted_profile"in r?null:{bundle_version:tr,...n};if(r.manifest_version===it){let o=r.restricted_profile;if(!o||typeof o!="object"||Object.keys(o).sort().join()!=="profile_id,sha256"||typeof o.profile_id!="string"||typeof o.sha256!="string"||!Rd.test(o.sha256))return null;let i=Object.prototype.hasOwnProperty.call(ma,o.profile_id)?ma[o.profile_id]:null;return i?{...i,restricted_profile:o,...n}:null}return null},Id=t=>t.manifest.manifest_version===it?er:t.manifest.manifest_version===vt?_o:null;function bo(t){let e=t.instructions;if(!e)return!0;let r=yo(t);if(!r||e.execution_manifest_sha256!==r.manifest_sha256)return!1;try{if(!Mr(JSON.parse(t.config_json),t.config))return!1;let n=jd(r,t.prompt);return n===null||e.verification_scope!==Id(r)||!Mr(e.initial_messages,n.initial_messages)?!1:Mr(JSON.parse(e.instruction_bundle_json),n)}catch{return!1}}var Pd=t=>{let e=yo(t);return t.instructions&&e?{bundle:t.instructions.instruction_bundle_json,manifest:ha(e.manifest),config:t.config_json,prompt:t.prompt}:null};async function ga(t){let[e,r,n,o]=await Promise.all([rr(t.bundle),rr(t.manifest),rr(t.config),rr(t.prompt)]);return{bundle:e,manifest:r,config:n,prompt:o}}var Nd=(t,e)=>e.bundle===t.instructions.instruction_bundle_sha256&&e.manifest===yo(t).manifest_sha256&&e.config===t.config_sha256&&e.prompt===t.prompt_sha256;async function wo(t){let e=Pd(t);return e!==null&&Nd(t,await ga(e))}var Ce="biovault.approval.v1.1",_a=["config_sha256","prompt_sha256","execution_manifest_sha256","instruction_bundle_sha256","expected_revision","expected_turn_generation","prompt_version"],Fr=(t,e)=>_a.every(r=>t[r]===e[r]),ya=(t,e)=>e.revision>t.expected_revision||e.revision===t.expected_revision&&e.generation>t.expected_turn_generation,Ld=(t,e)=>ya(e,{revision:t.expected_revision,generation:t.expected_turn_generation});function Dd(t,e){let r=t.entry;if(!r)return{kind:"unknown"};let n=r.work_plan?.approval;if(n&&typeof n=="object"){let o=n,i=typeof o.job_id=="string"&&o.job_id!==""?o.job_id:null,s=o.approval_generation===Ce&&_a.every(a=>o[a]===e.tuple[a])&&(o.entry_id===void 0||o.entry_id===e.entry_id)&&r.entry_id===e.entry_id;return i?s?(r.job_ids??[]).includes(i)?{kind:"same",jobId:i}:{kind:"unknown"}:{kind:"different",jobId:i}:{kind:"unknown"}}return r.status==="planning"?{kind:"not-started"}:r.status==="cancelled"&&(r.job_ids??[]).length===0&&r.entry_id===e.entry_id?{kind:"cancelled"}:{kind:"unknown"}}var ba=["CEILING_POLICY_UNAVAILABLE","INSTRUCTION_MANIFEST_UNAVAILABLE","MODEL_POLICY_UNAVAILABLE"],vo=t=>!!t&&ba.includes(t),Ud=t=>t==="CEILING_POLICY_UNAVAILABLE",wa=["RUN_CAPACITY_REACHED","RUN_CAPACITY_UNAVAILABLE"],So=t=>!!t&&wa.includes(t);var Sa=["request.question","request.custom_prompt_addition","selection.nodes","cohorts.intent","cohorts.control_preference","cohorts.min_samples_per_group","cohorts.pairing_preference","cohorts.stratify_by","cohorts.covariates","eligibility.include","eligibility.exclude","eligibility.preferences","eligibility.treatment_status.policy","eligibility.treatment_status.when_missing","eligibility.sample_types.allow","eligibility.sample_types.when_missing","eligibility.sex.use","eligibility.sex.when_missing","eligibility.library.type","eligibility.library.when_missing","eligibility.donors_under_18","eligibility.donor_age_when_missing","datasets.mode","datasets.include","datasets.exclude","datasets.commercially_usable_only","size.preferred_subjects","size.preferred_studies","size.preferred_bytes","limits.max_cost_usd","limits.max_storage_bytes","interaction.stop_on_blocking_problem","sources.disallowed","llm.selection"],nr=(t,e)=>e.split(".").reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,t),va=(t,e,r)=>{let n=e.split("."),o=t;for(let i of n.slice(0,-1))o=o[i]??={};o[n[n.length-1]]=r};function Md(t){let e={};for(let r of Sa){if(r==="llm.selection"){let o=nr(t.config,"llm.selection");o?.mode==="explicit"&&va(e,r,structuredClone(o));continue}let n=structuredClone(nr(t.config,r));r==="selection.nodes"&&(n=(n??[]).map(({id:o,label:i,type:s,role:a})=>({id:o,label:i,type:s,role:a}))),n!==void 0&&va(e,r,n)}return e}var Fd=(t,e)=>nr(t.config,"provenance.field_origin")?nr(t.config,"provenance.field_origin")[e]:void 0,Vd=(t,e)=>nr(t.config,e);var Vr=wt.ExecuteCommand.prompt_version.values,kt=t=>typeof t=="string"&&Vr.includes(t),se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),st=t=>typeof t=="string"&&t.length>0,ka=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),ko=t=>t==null||typeof t=="string",Bd=/^[a-f0-9]{64}$/,zd=["config_sha256","prompt_sha256","execution_manifest_sha256","instruction_bundle_sha256"];function or(t,e){return se(t)?typeof t.success!="boolean"?`${e}.success: expected true or false`:typeof t.message!="string"?`${e}.message: expected a string`:null:`${e}: expected an object`}function xo(t){return se(t)&&typeof t.biovault_run_config=="boolean"?null:"Features.biovault_run_config: expected true or false"}function $e(t,e){let r=Le("DraftPreview",t,wt);if(r)return r;let n=t;return st(n.entry_id)?e!==void 0&&n.entry_id!==e?"DraftPreview.entry_id: requested entry does not match":null:"DraftPreview.entry_id: expected a non-empty string"}function ir(t){if(!se(t))return"Entry: expected an object";for(let e of["entry_id","title","status"])if(typeof t[e]!="string")return`Entry.${e}: expected a string`;if(!se(t.work_plan))return"Entry.work_plan: expected an object";if(!ka(t.job_ids))return"Entry.job_ids: expected a list of strings";for(let e of["created_at","updated_at","error_message"])if(!ko(t[e]))return`Entry.${e}: expected a string or null`;return null}function Eo(t){let e=or(t,"Entries");if(e)return e;let r=t;if(!Number.isInteger(r.total))return"Entries.total: expected an integer";if(!Array.isArray(r.entries))return"Entries.entries: expected a list";for(let n=0;n<r.entries.length;n++){let o=ir(r.entries[n]);if(o)return`Entries.entries[${n}]: ${o}`}return null}function sr(t,e){let r=or(t,"EntryResponse");if(r)return r;let n=t.entry,o=ir(n);if(o)return o;let i=n;if(i.entry_id!==e)return"Entry.entry_id: requested entry does not match";if(i.work_plan.preview!==void 0){let s=$e(i.work_plan.preview,e);if(s)return`Entry.work_plan.preview: ${s}`}return null}function Co(t){if(!se(t))return"LegacyJob: expected an object";if(t.approval_generation!==void 0&&t.approval_generation!==null)return"LegacyJob.approval_generation: unsupported generation";if(se(t.run_config)&&t.run_config.config_version==="1"||t.run_approval!==void 0&&t.run_approval!==null)return"LegacyJob: v1 markers without supported approval generation";if(!st(t.job_id))return"LegacyJob.job_id: expected a non-empty string";for(let e of["status","disease","control"])if(typeof t[e]!="string")return`LegacyJob.${e}: expected a string`;if(!ka(t.genes))return"LegacyJob.genes: expected a list of strings";for(let e of["created_at","evidence_id","error_message"])if(!ko(t[e]))return`LegacyJob.${e}: expected a string or null`;return null}function qo(t){let e=or(t,"LegacyJobs");if(e)return e;let r=t;if(!Number.isInteger(r.total))return"LegacyJobs.total: expected an integer";if(!Array.isArray(r.jobs))return"LegacyJobs.jobs: expected a list";for(let n=0;n<r.jobs.length;n++){let o=Co(r.jobs[n]);if(o)return`LegacyJobs.jobs[${n}]: ${o}`}return ko(r.next_cursor)?null:"LegacyJobs.next_cursor: expected a string or null"}function ar(t,e,r=We){let n=or(t,"JobResponse");if(n)return n;let o=t;if(!se(o.job))return"JobResponse.job: expected an object";let i=o.job.approval_generation===Ce?Le("JobDetailResponse",t,r):Co(o.job);return i||(o.job.job_id===e?null:"JobResponse.job.job_id: requested job does not match")}function Ge(t,e,r,n){let o=Le(t,e,We);if(o)return o;let i=e;return r!==void 0&&i.job_id!==r?`${t}.job_id: requested job does not match`:n!==void 0&&i.path!==n?`${t}.path: requested path does not match`:null}function Ao(t){if(!se(t))return"JobPrompt: expected an object";for(let e of["success","matches_approved"])if(typeof t[e]!="boolean")return`JobPrompt.${e}: expected true or false`;for(let e of["prompt","prompt_sha256","config_sha256"])if(typeof t[e]!="string")return`JobPrompt.${e}: expected a string`;if(t.approved_prompt_sha256!==null&&typeof t.approved_prompt_sha256!="string")return"JobPrompt.approved_prompt_sha256: expected a string or null";if(!kt(t.prompt_version))return"JobPrompt.prompt_version: unsupported version";if(t.approval_generation!==Ce)return"JobPrompt.approval_generation: unsupported generation";if(t.instructions!==null){let e=Le("InstructionPreview",t.instructions,wt);if(e)return e}if(!Array.isArray(t.prompt_sections))return"JobPrompt.prompt_sections: expected a list";for(let e of t.prompt_sections){let r=Le("PromptSection",e,wt);if(r)return r}return null}function Oo(t,e){let r=or(t,"CancelAck");if(r)return r;let n=t;return n.success!==!0?"CancelAck.success: expected true":se(n.job)?n.job.job_id!==e?"CancelAck.job.job_id: requested job does not match":n.job.status!=="cancelled"?"CancelAck.job.status: expected cancelled":n.job.run_terminal!==!0?"CancelAck.job.run_terminal: expected true":n.job.cancel_cleanup_status==="pending"||n.job.cancel_cleanup_status==="complete"?null:"CancelAck.job.cancel_cleanup_status: expected pending or complete":"CancelAck.job: expected an object"}function xa(t){return se(t)?t.mode==="inherit"?null:t.mode!=="explicit"?"model_selection.mode: expected inherit or explicit":se(t.model)?t.model.provider!=="bedrock"&&t.model.provider!=="anthropic"?"model_selection.model.provider: unsupported provider":typeof t.model.model_id=="string"?null:"model_selection.model.model_id: expected a string":"model_selection.model: expected an object":"model_selection: expected an object"}var Ea=(t,e)=>{if(t===e)return!0;if(!se(t)||!se(e))return!1;let r=Object.keys(t);return r.length===Object.keys(e).length&&r.every(n=>Object.hasOwn(e,n)&&Ea(t[n],e[n]))};function Hd(t,e){let r=$e(t);if(r)return`unreadable: ${r}`;let n=ir(e);if(n)return`unreadable: ${n}`;let o=t,i=e,s=i.work_plan.preview,a=$e(s);if(a)return`unreadable: Entry.work_plan.preview: ${a}`;let l=s,u=xa(i.work_plan.model_selection);if(u)return`unreadable: ${u}`;for(let c of["entry_id","revision","config_sha256","prompt_sha256"])if(o[c]!==l[c])return`mismatch: DraftPreview.${c} changed between R3 and R8`;if(i.entry_id!==o.entry_id)return"mismatch: Entry.entry_id changed between R3 and R8";if(o.editing.turn_generation!==l.editing.turn_generation)return"mismatch: DraftPreview.editing.turn_generation changed between R3 and R8";if(o.instructions===null!=(l.instructions===null))return"mismatch: DraftPreview.instructions changed between R3 and R8";if(o.instructions&&l.instructions){for(let c of["execution_manifest_sha256","instruction_bundle_sha256"])if(o.instructions[c]!==l.instructions[c])return`mismatch: DraftPreview.instructions.${c} changed between R3 and R8`}for(let c of[o,l])if(c.config.llm!==null&&!Ea(c.config.llm.selection,i.work_plan.model_selection))return"unreadable: model_selection does not match preview.config.llm.selection";return null}function Jd(t,e,r,n){let o=ir(t);if(o)return o;let i=t;if(i.entry_id!==e)return"Approval.entry_id: requested entry does not match";if(!se(r)||!st(r.user_id)||!st(r.org_id))return"Approval.identity: expected non-empty user_id and org_id";if(n!==void 0&&(!se(n)||n.user_id!==r.user_id||n.org_id!==r.org_id))return"Approval.pending: identity does not match";if(!Object.hasOwn(i.work_plan,"approval"))return null;let s=i.work_plan.approval;if(!se(s))return"Approval: expected an object";if(s.approval_generation!==Ce)return"Approval.approval_generation: unsupported generation";for(let a of zd)if(typeof s[a]!="string"||!Bd.test(s[a]))return`Approval.${a}: expected a lowercase SHA-256 digest`;return!Number.isInteger(s.expected_revision)||s.expected_revision<=0?"Approval.expected_revision: expected a positive integer":!Number.isInteger(s.expected_turn_generation)||s.expected_turn_generation<0?"Approval.expected_turn_generation: expected a non-negative integer":kt(s.prompt_version)?s.entry_id!==e?"Approval.entry_id: requested entry does not match":!st(s.job_id)||!i.job_ids.includes(s.job_id)?"Approval.job_id: expected a non-empty job in entry.job_ids":!st(s.actor_user_id)||s.actor_user_id!==r.user_id?"Approval.actor_user_id: identity does not match":!st(s.effective_org_id)||s.effective_org_id!==r.org_id?"Approval.effective_org_id: identity does not match":null:"Approval.prompt_version: unsupported version"}async function Wd(t){if(t.can_execute!==!0)return{ok:!1,reason:"not_executable"};if(t.checks.some(n=>n.kind==="blocking"))return{ok:!1,reason:"blocking"};if(t.editing.omni!==!1)return{ok:!1,reason:"omni_editing"};if(t.editing.turn_id!==null)return{ok:!1,reason:"turn_active"};if(!t.instructions)return{ok:!1,reason:"no_instructions"};let e=Ur(t.config);if(!kt(t.prompt_version)||t.approval_generation!==Ce||e!==vt&&e!==it)return{ok:!1,reason:"unknown_version"};let r;try{r=JSON.parse(t.instructions.instruction_bundle_json)}catch{return{ok:!1,reason:"instructions_mismatch"}}if(!se(r))return{ok:!1,reason:"instructions_mismatch"};if(r.bundle_version!==tr&&r.bundle_version!==St)return{ok:!1,reason:"unknown_version"};if(!bo(t))return{ok:!1,reason:"instructions_mismatch"};try{if(!await wo(t))return{ok:!1,reason:"hash_mismatch"}}catch{return{ok:!1,reason:"hash_mismatch"}}return{ok:!0,command:{config_sha256:t.config_sha256,prompt_sha256:t.prompt_sha256,execution_manifest_sha256:t.instructions.execution_manifest_sha256,instruction_bundle_sha256:t.instructions.instruction_bundle_sha256,expected_revision:t.revision,expected_turn_generation:t.editing.turn_generation,prompt_version:t.prompt_version}}}var w=class extends Error{path;status;statusText;detail;body;code;retryAfterMs;types;retryable;requestId;kind;publicMessage;exitCode;constructor(e,r,n,o,i,s,a,l={},u){let c=`API ${e}: ${r} ${n}`;super(o?`${c} \u2014 ${o}`:c),this.path=e,this.status=r,this.statusText=n,this.detail=o,this.body=i,this.code=s,this.retryAfterMs=a,this.types=l,this.name="ApiError",this.retryable=u?.retryable??null,this.requestId=u?.requestId??null}},qe="Not logged in. Run: omics-os login",M=class extends w{constructor(e,r,n){super(e,401,"Unauthorized",n?.detail,n?.body,n?.code,n?.retryAfterMs,n?.types,n),this.name="AuthError",this.message=r??qe}},at=class extends M{constructor(e,r){super(e,r),this.name="StoredCredentialOriginError"}},lr=class extends w{tenant;constructor(e,r,n){super(e,403,"Forbidden",n?.detail,n?.body,n?.code,n?.retryAfterMs,n?.types,n),this.tenant=r,this.name="TenantAccessDeniedError",this.message=`Access denied to tenant '${r}'. You may no longer be a member. Run 'omics-os profiles remove ${r}' to clean up.`}},pe=class extends w{constructor(e,r,n,o,i,s={},a){super(e,429,"Too Many Requests",n,o,i,r,s,a),this.name="RateLimitError"}},U=class extends w{constructor(e,r,n="",o){super(e,r,n),this.name="UnreadableResponseError",this.message="The server sent a response the CLI could not read.",this.cause=o}},ne=class extends w{constructor(e,r,n){super(e,r?.status??0,r?.statusText??"",r?.detail,r?.body,r?.code,r?.retryAfterMs,r?.types,r),this.name="UnknownOutcomeError",this.message="The request was sent but its outcome is unknown. Check before retrying.",this.cause=n}},H=class extends Error{path;constructor(e,r){super(`Network error on ${e}: ${r?.message??"connection failed"}`),this.path=e,this.name="NetworkError",this.cause=r}};var Gd=["R2","R4","R5","R6","R9","R10","R20"],Kd=["CONFIG_CHANGED","DRAFT_EDIT_IN_PROGRESS","DRAFT_TURN_INVALID","DRAFT_TURN_CONFLICT","RECORD_CHANGED","LITERATURE_FILE_CHANGED"],Yd=["ENTRY_NOT_PLANNING","DRAFT_EXPIRED","CONFIG_VERSION_REAPPROVAL_REQUIRED","PACKAGE_NOT_READY","SAMPLES_NOT_READY"],Xd=["DRAFT_BLOCKED","LIMIT_REQUIRED","LIMIT_INVALID","STORAGE_LIMIT_TOO_SMALL","LIMIT_CEILING_EXCEEDED","RUN_COST_LIMIT","RUN_STORAGE_LIMIT"],Qd=["INVALID_REQUEST","INVALID_CURSOR","CONFIG_TOO_LARGE","LITERATURE_FILE_INVALID"],Ca="The server could not complete the request. Try again later.",Zd="Cancellation recorded. No evidence will be published for this run.",qa=(t,e)=>typeof t=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:e;function xt(t,e,r){let n=e instanceof w?e:void 0,o=n?.status??0,i=n?.code,s=Gd.includes(t),a=qa(r,"<entry>"),l=qa(r,"<job>"),u=(c,d,p)=>{let f=n??new w("",0,"");return n||(f.cause=e),f.kind=c,f.exitCode=d,f.publicMessage=p,f};if(e instanceof at)return u("session",3,e.message);if(t==="R9")return vo(i)?u("precommit_refused",6,"Nothing was started by this attempt. The server could not apply its run policy; try again later."):So(i)?u("busy",7,"Nothing was started by this attempt. Run capacity is full; try again later."):u("unknown_outcome",8,`The start outcome is unknown. Run: omics-os biovault run recover ${a}`);if(t==="R20"&&i==="CANCEL_CLEANUP_INCOMPLETE")return u("cancel_cleanup_pending",7,`${Zd} Cleanup is still pending; run omics-os biovault run cancel ${l} again.`);if(t==="R20"&&o===409)return u("not_now",5,"This run has already ended.");if(s&&(e instanceof H||e instanceof ne||e instanceof U||o>=300&&o<400||o===408||o>=500||o>=200&&o<300)){let c=t==="R2"?"The draft may or may not have been created. Check with: omics-os biovault draft list":t==="R20"?`Cancellation could not be confirmed; check omics-os biovault run show ${l}.`:`The change may or may not have been saved. Check with: omics-os biovault draft show ${a}`;return u("unknown_outcome",8,c)}return o===401||i==="UNAUTHORIZED"?u("session",3,"Your session is not valid. Run: omics-os login"):o===403||i==="ACCESS_DENIED"?u("forbidden",3,"You do not have access to this."):i==="PACKAGE_UNAVAILABLE"||i==="ARCHIVE_UNAVAILABLE"?u("unavailable",4,i==="ARCHIVE_UNAVAILABLE"?"No zip was built for this folder; download the files instead.":"This run has no downloadable folder."):o===404||i==="NOT_FOUND"?u("not_found",4,"Not found."):i&&Kd.includes(i)?u("stale",5,"The draft changed since it was read. Export or show it again."):i&&Yd.includes(i)?u("not_now",5,"This is not possible in the record's current state."):i&&Xd.includes(i)?u("blocked",6,"The draft is not ready: fix its Blocking checks or limits."):[422,413,400].includes(o)||i&&Qd.includes(i)?u("invalid",2,"The server rejected the configuration or arguments."):i==="PACKAGE_INTEGRITY"?u("integrity",9,"Integrity check failed; the file was not saved."):o===429?u("rate_limited",7,"Too many requests. Try again shortly."):o>=400&&o<500?u("refused",6,"Request refused. Review the command and try again."):o>=500||o>=300&&o<400||i==="PACKAGE_STORAGE"||e instanceof H?u("server",1,Ca):e instanceof U?u("unreadable",1,"The server sent a response this CLI version could not read. Update the CLI (npm install -g omics-os@latest) and try again."):u("server",1,Ca)}function Aa(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function zr(t){let e=Aa(t)?t:void 0,r=e&&Aa(e.detail)?e.detail:e;return{code:Et(e).code??null,retryable:typeof r?.retryable=="boolean"?r.retryable:null,requestId:typeof r?.request_id=="string"?r.request_id:null}}function De(t){let e,r;if(t instanceof M)e="session",r=t.message;else if(t instanceof lr)e="forbidden",r=t.message;else if(t instanceof pe){e="rate_limited";let o=t.retryAfterMs?`${Math.ceil(t.retryAfterMs/1e3)}s`:"a few seconds";r=t.detail?`${t.detail} Retry after ${o}.`:`Rate limited. Retry after ${o}.`}else if(t instanceof ne)e="unknown_outcome",r=t.message;else if(t instanceof U)e="unreadable",r=t.message;else if(t instanceof H)e="network",r=`Network error: ${t.message}`;else if(t instanceof w){e=t.status===403?"forbidden":t.status===404?"not_found":"server";let o=["worker_not_started","session_busy"].includes(t.types.error??t.code??""),i=t.retryAfterMs&&!o?` Retry after ${Math.ceil(t.retryAfterMs/1e3)}s.`:"";r=`API error (${t.status}${t.code?`, ${t.code}`:""}): ${t.message}${i}`}else e="internal",r=String(t);let n=t instanceof w?t:void 0;return{payload:{error:n?.publicMessage??r,kind:n?.kind??e,status:n?.status?n.status:null,code:n?.code??null,retryable:n?.retryable??null,request_id:n?.requestId??null},exitCode:n?.exitCode??1}}var ef=["turns_per_minute","turns_per_hour","running_turns_user","running_turns_tenant","ip"],Br=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:void 0;function Hr(t){return Br(t.body?.retry_after)??(t.retryAfterMs?Br(Math.ceil(t.retryAfterMs/1e3)):void 0)??null}function $o(t){let e=t.body??{},r=t.types.error??t.code;if(t.status===429&&r==="session_busy")return"This session is still running a turn. Wait for it to finish, or cancel it, then try again.";if(t.status===429&&r==="rate_limited"){let n=typeof e.limit=="string"&&ef.includes(e.limit)?` (${e.limit})`:"",o=Hr(t);return`Too many requests${n}. ${o?`Try again in ${o} s.`:"Try again later."}`}if(t.status===413&&r==="prompt_too_large"){let n=Br(e.actual_bytes),o=Br(e.max_bytes);return`The message is too large${n&&o?` (${n} bytes; the limit is ${o})`:""}. Shorten it and send again.`}}import{chmodSync as Oa,closeSync as tf,constants as To,existsSync as $a,fsyncSync as rf,lstatSync as nf,mkdirSync as of,openSync as sf,readFileSync as af,renameSync as lf,unlinkSync as uf,writeFileSync as cf,writeSync as df}from"fs";import{randomBytes as ff}from"crypto";import{homedir as pf}from"os";import{dirname as mf,join as hf}from"path";var oe="https://app.omics-os.com",lt=`${oe}/api/v1`,Jr="https://stream.omics-os.com/api/v1",Io="http://localhost:8000",Ae=hf(pf(),".config","omics-os","credentials.json"),gf=new Set([oe,"https://stream.omics-os.com","http://localhost:8000","http://127.0.0.1:8000"]);function _f(t){if(gf.has(t))return!0;try{let e=new URL(t);if(e.protocol==="https:"&&e.hostname.endsWith(".omics-os.com"))return!0}catch{}return!1}function Ct(t){return new URL(t).origin}function Ue(t){if(t)try{let{hostname:e}=new URL(t);if(e==="localhost"||e==="127.0.0.1")return t.replace(/\/+$/,"")}catch{}return lt}function Oe(t){return`${t.replace(/\/+$/,"")}/api/v1`}function Te(t){try{let e=new URL(t).origin;return{safe:_f(e),origin:e}}catch{return{safe:!1,origin:t}}}function ur(t){let e=qt();Ye(e,t,e==="default"?"Platform":e)}function Ro(){if(!$a(Ae))return!1;let t=nf(Ae);return t.isSymbolicLink()||cf(Ae,Buffer.alloc(t.size,0),{mode:384}),uf(Ae),!0}function Po(t){if(!t||typeof t!="object")return;let e=t;if(e.auth_mode==="api_key")return typeof e.api_key!="string"||!e.api_key.startsWith("omk_")?void 0:{auth_mode:"api_key",api_key:e.api_key,endpoint:jo(e.endpoint,oe),user_id:Se(e.user_id),email:Se(e.email),org_id:Se(e.org_id),tier:Se(e.tier)};if(e.auth_mode==="oauth")return e.credential_type!=="omics_cli"||typeof e.credential_id!="string"||e.credential_id.length===0||typeof e.cli_token!="string"||!e.cli_token.startsWith("omc_")||typeof e.refresh_token!="string"||!e.refresh_token.startsWith("omr_")||typeof e.token_expiry!="string"||e.token_expiry.length===0||typeof e.refresh_expiry!="string"||e.refresh_expiry.length===0?void 0:{auth_mode:"oauth",credential_type:"omics_cli",credential_id:e.credential_id,cli_token:e.cli_token,refresh_token:e.refresh_token,token_expiry:e.token_expiry,refresh_expiry:e.refresh_expiry,endpoint:jo(e.endpoint,oe),user_id:Se(e.user_id),email:Se(e.email),org_id:Se(e.org_id),tier:Se(e.tier)}}function cr(t,e){let r=yf(t);if(!r||typeof r!="object")return;let n=r,o={auth_mode:"oauth",credential_type:"omics_cli",credential_id:String(n.credential_id??""),cli_token:String(n.cli_token??""),refresh_token:String(n.refresh_token??""),token_expiry:String(n.token_expiry??""),refresh_expiry:String(n.refresh_expiry??""),endpoint:jo(n.endpoint,e),user_id:Se(n.user_id),email:Se(n.email),org_id:Se(n.org_id),tier:Se(n.tier)};return Po(o)}function yf(t){if(!t||typeof t!="object")return t;let e=t;return e.credential??e.credentials??t}function ge(){try{if(!$a(Ae))return;let t=JSON.parse(af(Ae,"utf-8"));if(!t||typeof t!="object")return;let e=t;if(e.version===2&&typeof e.active_profile=="string"&&typeof e.profiles=="object")return t;let r=Po(t);if(!r)return;let o={version:2,active_profile:"default",profiles:{default:{endpoint:r.endpoint??oe,label:"Platform",auth_mode:r.auth_mode,...r.auth_mode==="oauth"?{credential_type:r.credential_type,credential_id:r.credential_id,cli_token:r.cli_token,refresh_token:r.refresh_token,token_expiry:r.token_expiry,refresh_expiry:r.refresh_expiry}:{api_key:r.api_key},user_id:r.user_id,email:r.email,org_id:r.org_id,tier:r.tier}}};return ut(o),o}catch{return}}function ut(t){let e=mf(Ae);of(e,{recursive:!0,mode:448}),Oa(e,448);let r=`${Ae}.tmp.${ff(4).toString("hex")}`,n=sf(r,To.O_CREAT|To.O_EXCL|To.O_WRONLY,384);try{let o=Buffer.from(JSON.stringify(t,null,2)+`
|
|
38
|
+
`,"utf-8");df(n,o),rf(n)}finally{tf(n)}lf(r,Ae),Oa(Ae,384)}function qt(){return ge()?.active_profile??"default"}var bf=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function wf(t){return t==="default"||bf.test(t)}function Ke(t){let e=ge();if(!e)throw new Error("No credentials file found. Run 'omics-os login' first.");if(!Object.hasOwn(e.profiles,t))throw new Error(`Profile '${t}' not found. Run 'omics-os profiles' to see available profiles.`);e.active_profile=t,ut(e)}function At(){let t=ge();return t?Object.entries(t.profiles).map(([e,r])=>({name:e,endpoint:r.endpoint,label:r.label,email:r.email,active:e===t.active_profile})):[]}function No(t){let e=ge();if(!e||!Object.hasOwn(e.profiles,t))return!1;if(t==="default")throw new Error("Cannot remove the 'default' profile.");if(delete e.profiles[t],e.active_profile===t){let r=Object.keys(e.profiles);e.active_profile=r.includes("default")?"default":r[0]??"default"}return ut(e),!0}function Lo(t){let e=ge();if(!e)return Ro();let r=t??e.active_profile;if(!Object.hasOwn(e.profiles,r))return!1;delete e.profiles[r];let n=Object.keys(e.profiles);return n.length===0?Ro():(e.active_profile===r&&(e.active_profile=n.includes("default")?"default":n[0]),ut(e),!0)}function Ye(t,e,r){if(!wf(t))throw new Error(`Invalid profile name '${t}'. Must be lowercase alphanumeric with optional hyphens.`);let n=ge();n||(n={version:2,active_profile:"default",profiles:{}});let o={endpoint:e.endpoint??oe,label:r,auth_mode:e.auth_mode,...e.auth_mode==="oauth"?{credential_type:e.credential_type,credential_id:e.credential_id,cli_token:e.cli_token,refresh_token:e.refresh_token,token_expiry:e.token_expiry,refresh_expiry:e.refresh_expiry}:{api_key:e.api_key},user_id:e.user_id,email:e.email,org_id:e.org_id,tier:e.tier};n.profiles[t]=o,ut(n)}function Do(t,e,r){if(!t)return;let n=ge();if(!n)return;let o=!1;for(let[i,s]of Object.entries(n.profiles))i!==r&&(s.auth_mode!=="oauth"||s.credential_id!==t||(s.cli_token=e.cli_token,s.refresh_token=e.refresh_token,s.token_expiry=e.token_expiry,s.refresh_expiry=e.refresh_expiry,o=!0));o&&ut(n)}function Y(t){let e=ge();if(!e)return;let r=t??e.active_profile;if(!Object.hasOwn(e.profiles,r))return;let n=e.profiles[r];if(n){if(n.auth_mode==="api_key"&&n.api_key)return{auth_mode:"api_key",api_key:n.api_key,endpoint:n.endpoint,user_id:n.user_id,email:n.email,org_id:n.org_id,tier:n.tier};if(n.auth_mode==="oauth"&&n.cli_token&&n.refresh_token)return{auth_mode:"oauth",credential_type:"omics_cli",credential_id:n.credential_id??"",cli_token:n.cli_token,refresh_token:n.refresh_token,token_expiry:n.token_expiry??"",refresh_expiry:n.refresh_expiry??"",endpoint:n.endpoint,user_id:n.user_id,email:n.email,org_id:n.org_id,tier:n.tier}}}function jo(t,e){return typeof t=="string"&&t.length>0?t:e}function Se(t){return typeof t=="string"&&t.length>0?t:void 0}function ja(t){let e=t.token_expiry;if(!e)return!0;try{return new Date(e).getTime()<Date.now()+6e4}catch{return!0}}async function vf(t,e){let r=t.refresh_token,n=t.credential_id;if(!r||!n||!r.startsWith("omr_"))return;let o=(t.endpoint??oe).replace(/\/+$/,""),i=`${Ue(Oe(o))}/gateway/oauth/cli/token`;try{let s=await fetch(i,{redirect:"error",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",credential_id:n,refresh_token:r}),signal:AbortSignal.timeout(15e3)});if(!s.ok)return;let a=await s.json(),l=cr(a,o);if(!l)return;let u=e??qt(),c=u==="default"?"Platform":u;return Ye(u,{...l,endpoint:o},c),Do(n,l,u),l.cli_token}catch{return}}var Uo=new Map;async function Sf(t,e){let r=t.credential_id,n=Uo.get(r);n||(n=vf(t,e).finally(()=>Uo.delete(r)),Uo.set(r,n));let o=await n;if(o)return o;let i=Y(e);return i?.auth_mode==="oauth"&&i.credential_id===r&&!ja(i)?i.cli_token:void 0}async function kf(t,e){if(t){if(t.auth_mode==="api_key"&&t.api_key.startsWith("omk_"))return{token:t.api_key,authType:"api-key"};if(t.auth_mode==="oauth"){if(ja(t)){let r=await Sf(t,e);return r?{token:r,authType:"bearer"}:void 0}return t.cli_token?{token:t.cli_token,authType:"bearer"}:void 0}}}function Ia(t){let e=Y(t);if(e){if(e.auth_mode==="api_key"&&e.api_key.startsWith("omk_"))return{token:e.api_key,authType:"api-key"};if(e.auth_mode==="oauth"&&e.cli_token.startsWith("omc_"))return{token:e.cli_token,authType:"bearer"}}}function Ta(t){return t.startsWith("omk_")?"api-key":"bearer"}function xf(t,e){return e||(t===lt?Jr:t)}function _e(t){let e=t.cloud??!1,n=(e&&!t.apiUrl?Y(t.profile):void 0)?.endpoint,o=t.apiUrl??(n?Oe(n):e?lt:Io),i=xf(o,t.streamApiUrl),s=t.isResume??!1,a=Me()?.value;if(a)return{apiUrl:o,streamApiUrl:i,sessionId:t.sessionId,projectId:t.projectId,token:a,authType:Ta(a),tokenSource:"env",isCloud:e,isResume:s,profile:t.profile};if(t.token)return{apiUrl:o,streamApiUrl:i,sessionId:t.sessionId,projectId:t.projectId,token:t.token,authType:Ta(t.token),tokenSource:"cli",isCloud:e,isResume:s,profile:t.profile};if(e){let l=Ia(t.profile);if(l)return{apiUrl:o,streamApiUrl:i,sessionId:t.sessionId,projectId:t.projectId,token:l.token,authType:l.authType,tokenSource:"stored",isCloud:e,isResume:s,profile:t.profile}}return{apiUrl:o,streamApiUrl:i,sessionId:t.sessionId,projectId:t.projectId,authType:"none",tokenSource:"none",isCloud:e,isResume:s,profile:t.profile}}var Pa=["OMICS_OS_API_KEY","OMICSOS_API_KEY","LOBSTER_TOKEN"],Ra=!1;function Me(t=process.env){let[e,r]=[t.OMICSOS_API_KEY,t.OMICS_OS_API_KEY];e&&r&&e!==r&&!Ra&&(Ra=!0,process.stderr.write(`OMICSOS_API_KEY and OMICS_OS_API_KEY are both set, with different values; using OMICS_OS_API_KEY.
|
|
39
|
+
`));let n=Pa.find(o=>t[o]);return n?{name:n,value:t[n]}:void 0}function dr(t){if(!t.token)return{};switch(t.authType){case"api-key":return{Authorization:`Bearer ${t.token}`,"X-API-Key":t.token};case"bearer":return{Authorization:`Bearer ${t.token}`};default:return{}}}async function X(t){if(t.tokenSource==="env"||t.tokenSource==="cli"||!t.isCloud)return dr(t);let{safe:e,origin:r}=Te(t.apiUrl);if(!e)throw t.token?new Error(`Refusing to send stored credentials to untrusted origin: ${r}. Use OMICS_OS_API_KEY env var with --endpoint, or remove --endpoint.`):new M(t.apiUrl);if(t.streamApiUrl){let i=Te(t.streamApiUrl);if(!i.safe)throw new Error(`Refusing to send stored credentials to untrusted stream origin: ${i.origin}. Remove --stream-endpoint or use an explicit API key.`)}let n=Y(t.profile);Af(t,n);let o=await kf(n,t.profile);if(o){let i={...t,token:o.token,authType:o.authType};return dr(i)}if(t.tokenSource==="stored")throw new M(t.apiUrl);return dr(t)}function Ef(t){let e=new URL(t||oe).origin,r=new URL(Ue(Oe(e))).origin;return[e,r,...r===oe?[new URL(Jr).origin]:[]]}var Cf=/^([a-z0-9-]+)\.omics-os\.com$/;function qf(t){let{host:e}=new URL(t),r=Cf.exec(e)?.[1],n=e===new URL(oe).host?"omics-os login":r&&r!=="stream"?`omics-os login --tenant ${r}`:`omics-os --endpoint ${t} login`;return`Not logged in for ${e}. Run: ${n}, or set OMICS_OS_API_KEY.`}function Af(t,e){if(!e){if(t.tokenSource==="stored")throw new M(t.apiUrl);return}let r=Ef(e.endpoint);for(let n of[t.apiUrl,t.streamApiUrl])if(n&&!r.includes(new URL(n).origin))throw new at(n,qf(n))}var Wr=2,Of=1e3,$f=3e4;function Tf(t){return t==="GET"}function Rf(t,e){return t>=500?!0:t===409&&e!==null}function Gr(t,e=Date.now(),r=$f){if(!t)return;let n=t.trim(),o;if(/^\d+$/.test(n))o=Number.parseInt(n,10)*1e3;else{let i=Date.parse(n);if(Number.isNaN(i))return;o=Math.max(0,i-e)}return Math.min(o,r)}async function Vo(t){try{return await t.json()}catch{return}}function Et(t){if(!t)return{};let e=a=>typeof a=="string"&&a.trim()?a.trim():void 0,r=t.detail;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,l=e(a.error),u=l?e(a.code):void 0,c=e(a.code)??l;return{detail:(e(a.message)??e(a.detail)??c)?.slice(0,200),code:c,error:l,subcode:u}}let n=e(r)?e(t.error):void 0,o=n?e(t.code):void 0,i=e(t.code)??n;return{detail:(e(r)??e(t.message)??e(t.error))?.slice(0,200),code:i,error:n,subcode:o}}function Na(t,e=t.apiUrl){if(t.token&&t.tokenSource==="stored"){let{safe:r,origin:n}=Te(e);if(!r)throw new M(e,`Refusing to send credentials to untrusted origin: ${n}. Use OMICS_OS_API_KEY env var or remove --endpoint to use the default.`)}}var Mo;function Bo(t){Mo=t}function fr(t,e,r,n){if(!Mo)return;let o;try{let i=new URL(e);o=i.pathname+(i.search?"?\u2026":"")}catch{o="(unreadable URL)"}try{Mo({method:t,path:o,status:r,requestId:n??null})}catch{}}async function E(t,e,r={}){Na(t);let n=`${t.apiUrl}${e}`,o=r.method??"GET",i=(r.retry??(Tf(o)?"safe":"none"))==="safe",s=r.body instanceof FormData,a=s?r.body:r.body===void 0?void 0:JSON.stringify(r.body),l={Accept:"application/json"};r.body!==void 0&&!s&&(l["Content-Type"]="application/json");let u={};for(let[f,h]of Object.entries(r.headers??{})){let _=f.toLowerCase();if(!(_==="authorization"||_==="x-api-key"||s&&_==="content-type")){for(let b of Object.keys(l))b.toLowerCase()===_&&delete l[b];u[f]=h}}new Headers({...l,...u});let c=!1,d,p=()=>{if(r.signal?.aborted)throw o!=="GET"&&c?new ne(e,d,r.signal.reason):r.signal.reason};for(let f=0;f<=Wr;f++){p();let h;try{h=await Fo(X(t),r.signal)}catch(A){throw p(),o!=="GET"&&c?new ne(e,d,A):A}p();let _=typeof r.timeoutMs=="number"?new AbortController:void 0,b=_?setTimeout(()=>_.abort(new Error(`timed out after ${r.timeoutMs}ms`)),r.timeoutMs):void 0,j=[r.signal,_?.signal].filter(A=>A!==void 0),g=j.length?AbortSignal.any(j):void 0,m,x=!1,C=Of*(f+1);try{if(p(),c=!0,m=await Fo(fetch(n,{method:o,headers:{...l,...h,...u},...a!==void 0?{body:a}:{},signal:g,redirect:"manual"}),g),d={status:m.status,statusText:m.statusText},m.ok&&(x=!0,fr(o,n,m.status,m.headers.get("x-request-id"))),m.status===204)return{};let A=await jf(m,g);if(m.ok)try{let k=JSON.parse(A);return g?.throwIfAborted(),k}catch(k){throw g?.aborted?g.reason:o!=="GET"?new ne(e,d,k):new U(e,m.status,m.statusText,k)}let D=await Vo(new Response(A));g?.throwIfAborted();let v=zr(D),{detail:S,error:I,subcode:L}=Et(D),te=v.code??void 0,ce=m.headers.get("retry-after"),N=Gr(ce,Date.now(),m.status===429?void 0:r.maxRetryAfterMs),z={error:I,subcode:L};if(x=!0,fr(o,n,m.status,v.requestId??m.headers.get("x-request-id")),d={status:m.status,statusText:m.statusText,detail:S,body:D,code:te,retryAfterMs:N,types:z,retryable:v.retryable,requestId:v.requestId},m.status>=300&&m.status<400)throw o!=="GET"?new ne(e,d):new w(e,m.status,m.statusText,void 0,D,void 0,void 0,{},v);if(m.status===401)throw new M(e,void 0,d);let Z=m.status===429||m.status>=500||o==="GET"&&Rf(m.status,ce);if(i&&f<Wr&&Z&&v.retryable!==!1)C=N??C;else throw m.status===429?new pe(e,N??C,S,D,te,z,v):o!=="GET"&&(m.status>=500||m.status===408)?new ne(e,d):new w(e,m.status,m.statusText,S,D,te,N,z,v)}catch(A){if(x||fr(o,n,m?m.status:null,m?.headers.get("x-request-id")),p(),A instanceof w)throw A;if(o!=="GET"&&(m||_?.signal.aborted||!i||f===Wr))throw new ne(e,d,A);if(!i||f===Wr)throw new H(e,A instanceof Error?A:void 0)}finally{b!==void 0&&clearTimeout(b)}try{await If(C,r.signal)}catch(A){throw p(),A}}throw new H(e)}function Fo(t,e){return e?new Promise((r,n)=>{let o=()=>{e.removeEventListener("abort",o),n(e.reason)};e.addEventListener("abort",o,{once:!0}),t.then(i=>{e.removeEventListener("abort",o),e.aborted?n(e.reason):r(i)},i=>{e.removeEventListener("abort",o),n(e.aborted?e.reason:i)}),e.aborted&&o()}):t}async function jf(t,e){if(!t.body)return"";let r=t.body.getReader(),n=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await Fo(r.read(),e);if(i)return o+n.decode();o+=n.decode(s,{stream:!0})}}catch(i){throw r.cancel(i).catch(()=>{}),i}finally{r.releaseLock()}}function La(t,e,r){let n;try{let c=JSON.parse(r);c&&typeof c=="object"&&!Array.isArray(c)&&(n=c)}catch{}let o=zr(n),{detail:i,error:s,subcode:a}=Et(n),l=o.code??void 0,u=Gr(e.headers.get("retry-after"),Date.now(),1/0);return e.status===429?new pe(t,u,i,n,l,{error:s,subcode:a},o):new w(t,e.status,e.statusText,i,n,l,u,{error:s,subcode:a},o)}async function zo(t,e,r={}){Na(t,t.streamApiUrl);let n=`${t.streamApiUrl}${e}`,o=await X(t),i=await fetch(n,{redirect:"error",method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json",...o,...r.headers},body:r.body!==void 0?JSON.stringify(r.body):void 0,signal:r.signal}).catch(s=>{throw fr("POST",n,null),s});if(fr("POST",n,i.status,i.headers.get("x-request-id")),i.status===401)throw new M(e);if(!i.ok)throw La(e,i,await i.text().catch(()=>""));if(!i.body)throw new H(e,new Error("Response has no body"));return i.body}function If(t,e){return new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}let o=()=>{clearTimeout(i),n(e?.reason)},i=setTimeout(()=>{e?.removeEventListener("abort",o),r()},t);e?.addEventListener("abort",o,{once:!0})})}var Da="Made by a newer server; this CLI can't verify or execute it. Update the CLI (npm install -g omics-os@latest).",Ua=We.RestrictedProfile.profile_id.values,Ho=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Pf=["4"],Jo={...We,RestrictedProfile:{...We.RestrictedProfile,profile_id:{t:"string",required:!0}}},ct=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ma(t){if(!ct(t)||!ct(t.run_config)||!ct(t.run_config.execution_contract))return null;let e=t.run_config.execution_contract.manifest;return ct(e)?e:null}function Nf(t){return!Vr.includes(t)&&!Pf.includes(t)}function Wo(t,e){let r=Ma(t)?.restricted_profile;return!ct(r)||typeof r.profile_id!="string"||Ua.includes(r.profile_id)||Ho.test(r.profile_id)?null:`${e}.run_config.execution_contract.manifest.restricted_profile.profile_id: unsupported value`}function Fa(t){let e=Ma(t);if(!e)return null;let r=[],n=e.restricted_profile;ct(n)&&typeof n.profile_id=="string"&&!Ua.includes(n.profile_id)&&r.push({field:"restricted_profile.profile_id",value:Ho.test(n.profile_id)?n.profile_id:"(not shown)"});let o=e.prompt_builder;return ct(o)&&typeof o.version=="string"&&Nf(o.version)&&r.push({field:"prompt_builder.version",value:Ho.test(o.version)?o.version:"(not shown)"}),r.length?{newer_server:!0,can_verify:!1,can_execute:!1,notice:Da,fields:r}:null}function Go(t){let e=Le("RunListV1",t,Jo);if(e)return e;let r=t.jobs;for(let n=0;n<r.length;n++){let o=Wo(r[n],`RunListV1.jobs[${n}]`);if(o)return o}return null}function Ko(t,e){let r=ar(t,e,Jo);if(r)return r;let n=t.job;return n.approval_generation===Ce?Wo(n,"JobResponse.job"):null}function Kr(t){if(!Object.hasOwn(t,"cli_compatibility"))return t;let{cli_compatibility:e,...r}=t;return r}function Yr(t){let e=Kr(t),r=Fa(e);return r?{...e,cli_compatibility:r}:e}import*as Xr from"node:fs/promises";import{basename as Yf,extname as Xf}from"node:path";function ae(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t)){let e=new w("",0,"");throw e.kind="usage",e.publicMessage="The ID must contain 1\u2013128 letters, numbers, underscores or hyphens.",e.exitCode=2,e}return t}function $t(t){let e=new URLSearchParams;for(let[r,n]of Object.entries(t))n!==void 0&&e.set(r,String(n));return e.size?`?${e}`:""}async function de(t,e,r,n){let o=await E(t,e,{signal:n.signal}),i=r(o);if(i)throw new U(e,200,"OK",i);return o}function Lf(t,e={}){return de(t,"/vault/features",xo,e)}function Df(t,e,r={}){let n=ae(e);return de(t,`/vault/runs/${n}`,o=>$e(o,n),r)}function Uf(t,e={}){return de(t,"/vault/entries?limit=100",Eo,e)}function Mf(t,e,r={}){let n=ae(e);return de(t,`/vault/entries/${n}`,o=>sr(o,n),r)}function Ff(t,e){if(e.view!=="v1"&&e.view!=="legacy")throw new TypeError('BioVault listRuns requires view "v1" or "legacy".');let r="/vault/jobs"+$t({view:e.view,status:e.status,outcome:e.outcome,limit:e.limit,cursor:e.cursor});return de(t,r,e.view==="v1"?n=>Ge("RunListV1",n):qo,e)}function Vf(t,e,r={}){let n=ae(e);return de(t,`/vault/jobs/${n}`,o=>ar(o,n),r)}async function Bf(t,e={}){let r="/vault/jobs"+$t({view:"v1",status:e.status,outcome:e.outcome,limit:e.limit,cursor:e.cursor}),n=await de(t,r,Go,e);return{...n,jobs:n.jobs.map(o=>Yr(o))}}async function zf(t,e,r={}){let n=ae(e),o=await de(t,`/vault/jobs/${n}`,i=>Ko(i,n),r);return{...o,job:o.job.approval_generation===Ce?Yr(o.job):Kr(o.job)}}function Hf(t,e,r={}){return de(t,`/vault/jobs/${ae(e)}/prompt`,Ao,r)}function Jf(t,e,r={}){let n=ae(e),o=`/vault/jobs/${n}/samples`+$t({limit:r.limit,cursor:r.cursor});return de(t,o,i=>Ge("SamplesPage",i,n),r)}function Wf(t,e,r={}){let n=ae(e);return de(t,`/vault/jobs/${n}/package`,o=>Ge("PackageResponseV1",o,n),r)}function Gf(t,e,r={}){let n=ae(e),o=`/vault/jobs/${n}/problems`+$t({status:r.status,severity:r.severity,limit:r.limit,cursor:r.cursor});return de(t,o,i=>Ge("ProblemsPageV1",i,n),r)}function Kf(t,e,r={}){let n=ae(e),o=`/vault/jobs/${n}/decisions`+$t({limit:r.limit,cursor:r.cursor});return de(t,o,i=>Ge("DecisionsPageV1",i,n),r)}function Ot(t){let e=new w("",0,"");return e.kind="usage",e.publicMessage=t,e.exitCode=2,e}function Va(t){if(!Number.isInteger(t)||t<=0)throw Ot("The expected revision must be a positive integer.")}async function pr(t,e,r,n,o,i,s){try{let a=await E(t,r,{method:n,...o===void 0?{}:{body:o}}),l=i(a);if(l)throw new U(r,200,"OK",l);return a}catch(a){throw xt(e,a,s)}}function Qf(t,e){return pr(t,"R2","/vault/runs","POST",e,r=>$e(r))}function Zf(t,e,r){let n=ae(e);return pr(t,"R4",`/vault/runs/${n}`,"PUT",r,o=>$e(o,n),n)}async function ep(t,e,r,n){let o=ae(e);if(Va(r),Xf(n)!==".ris")throw Ot("Literature must be a .ris file.");let i;try{let a=await Xr.stat(n);if(!a.isFile()||a.size<1||a.size>2*1024*1024)throw Ot("Literature must be a regular .ris file of 1 byte to 2 MiB.");i=await Xr.readFile(n)}catch(a){throw a instanceof w?a:Ot("The literature file could not be read.")}if(i.byteLength<1||i.byteLength>2*1024*1024)throw Ot("Literature must be a regular .ris file of 1 byte to 2 MiB.");let s=new FormData;return s.append("file",new Blob([new Uint8Array(i)]),Yf(n)),s.append("expected_revision",String(r)),pr(t,"R5",`/vault/runs/${o}/literature`,"POST",s,a=>$e(a,o),o)}function tp(t,e,r,n){let o=ae(e);if(Va(n),!r)throw Ot("A literature file ID is required.");return pr(t,"R6",`/vault/runs/${o}/literature/${encodeURIComponent(r)}?expected_revision=${n}`,"DELETE",void 0,i=>$e(i,o),o)}function rp(t,e){let r=ae(e);return pr(t,"R10",`/vault/entries/${r}/cancel`,"POST",void 0,n=>sr(n,r),r)}function Ba(t){let e=Ge("PackageDownloadV1",t);if(e)return e;try{if(new URL(t.url).protocol==="https:")return null}catch{}return"PackageDownloadV1.url: expected an HTTPS URL"}function np(t,e,r,n={}){let o=ae(e);return de(t,`/vault/jobs/${o}/package/file`+$t({path:r}),Ba,n)}function op(t,e,r={}){return de(t,`/vault/jobs/${ae(e)}/package/archive`,Ba,r)}function ip(t,e){for(let r of["job_id","path","sha256","size_bytes"])if(t[r]!==e[r])return`PackageDownloadV1.${r}: does not match the original folder manifest`;return null}async function za(t,e,r,n,o,i){let s=e==="R9"?`/vault/entries/${r}/confirm`:`/vault/jobs/${r}/cancel`;try{let a=await E(t,s,{method:"POST",...n===void 0?{}:{body:n},retry:"none",signal:i.signal}),l=o(a);if(l)throw new U(s,200,"OK",l);return a}catch(a){throw xt(e,a,r)}}function sp(t,e,r,n={}){let o=ae(e);return za(t,"R9",o,r,i=>sr(i,o),n)}function ap(t,e,r={}){let n=ae(e);return za(t,"R20",n,void 0,o=>Oo(o,n),r)}var Ha={repo:"the-omics-os/lobster-cloud",sha:"da3f40ab161bce91ba80d72ddd94015f4a2f448f",files:[{source:"biovault/src/types/runV1.generated.ts",source_sha256:"28247bec0b411a7c3ad9de0e2dd2a3a481fbf6ee02926d9094e28e63346cef3f",emitted:"vendor/runV1.generated.ts",emitted_sha256:"476f322d92a918818746ed13994b9602aef528f00bf48f32c3970048da035f53"},{source:"biovault/src/types/packageDeliveryV1.generated.ts",source_sha256:"a9be4e9c7bff519028346f9000f067f7f82bd4e98f5216c7c7e9a90208d5a9c2",emitted:"vendor/packageDeliveryV1.generated.ts",emitted_sha256:"1635f3ea5a489ee8d67bbf8e16aa348a67374040b6eb87d722abf6dca6c92632"},{source:"biovault/src/api/wireShape.ts",source_sha256:"1a65b086dbf5a8dc5f0c33d1a1870c845c1a3ad51cc0363d1871e31fa9f4d108",emitted:"wireShape.ts",emitted_sha256:"997a020cb18f7a80499e946612e328346b6b0e8b6e3c086a3b47340a8d9ba89a"},{source:"biovault/src/plan/instructionMatch.ts",source_sha256:"2e08e134a195aa825118c267058baaeb3b51ffbe51371d3d019008fcf8ac67fb",emitted:"instructionMatch.ts",emitted_sha256:"67eba90d6db12fe0c3c8090f7ba8729ccf089abf75b4b3619627bbe4c0bfe102"},{source:"biovault/src/plan/assurance.ts",source_sha256:"831c6a9edbee17045c60f8650e8a46ea6241ac2a375471d5641b72f57886310a",emitted:"assurance.ts",emitted_sha256:"11e5450859b587e32a1b81a6f7266c04443324078138caea3d9e7b63089f0948"},{source:"biovault/src/plan/approval.ts",source_sha256:"c952f166a3e34410df3bbeec52270a72ceb6863e65939bdb2710a9776cef045d",emitted:"approval.ts",emitted_sha256:"056355bb599b9790e51930296962a09089ff7bbd86b053d89dfa10b3452b3ae8"},{source:"biovault/src/plan/preCommit.ts",source_sha256:"0861a303484405bd16900e7f547092def27f1c0ee4b5425628093e018b7d760c",emitted:"preCommit.ts",emitted_sha256:"17f210e7a161ad5e4bf4b2a04815cb2adc5d233f25018b4f8f7dc09a8d5a7056"},{source:"biovault/src/plan/fields.ts",source_sha256:"9ed12aa918de93eff196ce62a1b684747204c9773f4449dfe134f950ebfe497e",emitted:"fields.ts",emitted_sha256:"253af9096a18ca059baf8eedba4c357d30edff54e462079235af771106a7c161"}]};async function lp(t,e={}){let r="/gateway/auth/verify";try{e.signal?.throwIfAborted();let n=await X(t);e.signal?.throwIfAborted();let o=n.Authorization;if(typeof o!="string"||!o.startsWith("Bearer ")||!o.slice(7))throw new M(r);let i={...t,token:o.slice(7),authType:n["X-API-Key"]?"api-key":"bearer",tokenSource:"cli"},s=await E(i,r,{signal:e.signal});if(s===null||typeof s!="object"||Array.isArray(s))throw new U(r,200);let a=s;if(a.authenticated!==!0||typeof a.user_id!="string"||!a.user_id||a.org_id!==null&&typeof a.org_id!="string"||typeof a.auth_mode!="string")throw new U(r,200);if(!a.org_id){let l=new w(r,0,"");throw l.kind="forbidden",l.exitCode=3,l.publicMessage="BioVault runs need an organisation account.",l}return{config:i,user_id:a.user_id,org_id:a.org_id,auth_mode:a.auth_mode}}catch(n){throw e.signal?.aborted?e.signal.reason:n instanceof w&&n.exitCode!==void 0?n:xt("R1",n)}}import*as fe from"node:fs/promises";import{constants as Ja}from"node:fs";import Ga from"node:os";import Yo from"node:path";import{createHash as up}from"node:crypto";var cp=["version","entry_id","attempt_id","tuple","api_url","user_id","org_id","created_at"],Wa=["config_sha256","prompt_sha256","execution_manifest_sha256","instruction_bundle_sha256","expected_revision","expected_turn_generation","prompt_version"],Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Rt=(t,e)=>Qr(t)&&t.code===e,Tt=t=>typeof t=="string"&&t.length>0;function Ka(t,e){return Object.keys(t).length===e.length&&e.every(r=>Object.hasOwn(t,r))}function Ya(t){return Qr(t)&&Ka(t,Wa)&&Wa.slice(0,4).every(e=>typeof t[e]=="string"&&/^[a-f0-9]{64}$/.test(t[e]))&&Number.isInteger(t.expected_revision)&&t.expected_revision>0&&Number.isInteger(t.expected_turn_generation)&&t.expected_turn_generation>=0&&kt(t.prompt_version)}function Xa(t,e){return Qr(t)&&Ka(t,cp)&&t.version===1&&t.entry_id===e&&typeof t.attempt_id=="string"&&/^[a-f0-9]{32}$/.test(t.attempt_id)&&Ya(t.tuple)&&Tt(t.api_url)&&Tt(t.user_id)&&Tt(t.org_id)&&typeof t.created_at=="string"&&Number.isFinite(Date.parse(t.created_at))}function Qa(t,e){return t.api_url===e.api_url&&t.user_id===e.user_id&&t.org_id===e.org_id}function Xo(t,e,r){return up("sha256").update([t,e,r].join(`
|
|
40
|
+
`),"utf8").digest("hex").slice(0,16)}function dp(t,e,r){return{key:Xo(t,e,r),api_url:t,user_id:e,org_id:r}}function Zr(t,e){if(!/^[A-Za-z0-9_-]{1,128}$/.test(e))throw new Error("Unsafe pending entry locator.");if(!t||!Tt(t.api_url)||!Tt(t.user_id)||!Tt(t.org_id)||t.key!==Xo(t.api_url,t.user_id,t.org_id))throw new Error("Invalid pending account context.")}function jt(t,e){return Zr(t,e),Yo.join(Ga.homedir(),".config","omics-os","biovault","pending",t.key,e+".json")}function Za(t,e){return jt(t,e)+".lock"}async function el(t,e){let r=Yo.join(Ga.homedir(),".config","omics-os");e&&await fe.mkdir(r,{recursive:!0,mode:448});for(let n of["biovault","biovault/pending",`biovault/pending/${t.key}`]){let o=Yo.join(r,n);if(e)try{await fe.mkdir(o,{mode:448})}catch(s){if(!Rt(s,"EEXIST"))throw s}let i;try{i=await fe.lstat(o)}catch(s){if(!e&&Rt(s,"ENOENT"))return!1;throw s}if(!i.isDirectory()||i.isSymbolicLink())throw new Error("The local start directory is not a real directory.")}return!0}async function fp(t,e){let r=jt(t,e);if(!await el(t,!1))return null;let n;try{n=await fe.lstat(r)}catch(s){if(Rt(s,"ENOENT"))return null;throw s}if(!n.isFile()||n.isSymbolicLink())return"nonregular";let o=16*1024;if(n.size>o)return"oversize";let i;try{i=await fe.open(r,Ja.O_RDONLY|Ja.O_NOFOLLOW)}catch(s){if(Rt(s,"ELOOP"))return"nonregular";throw s}try{let s=await i.stat();if(!s.isFile())return"nonregular";if(s.size>o)return"oversize";let a=Buffer.alloc(o+1),l=0;for(;l<a.length;){let{bytesRead:u}=await i.read(a,l,a.length-l,l);if(!u)break;l+=u}return l>o?"oversize":a.subarray(0,l)}finally{await i.close()}}async function en(t,e){let r=await fp(t,e);if(r===null)return{kind:"absent"};if(typeof r=="string")return{kind:"malformed",bytes:null,identityMismatch:!1,unsafeReason:r};let n;try{n=JSON.parse(r.toString("utf8"))}catch{return{kind:"malformed",bytes:r,identityMismatch:!1}}let o=Qr(n)&&["api_url","user_id","org_id"].some(i=>Object.hasOwn(n,i)&&typeof n[i]=="string"&&n[i]!==t[i]);return!Xa(n,e)||o?{kind:"malformed",bytes:r,identityMismatch:o}:{kind:"valid",record:n}}async function pp(t,e){let r=await en(t,e);return r.kind==="valid"?r.record:r.kind==="absent"?null:"malformed"}async function Qo(t,e,r){let n=Za(t,e);await el(t,!0);try{await fe.mkdir(n,{mode:448})}catch(o){if(Rt(o,"EEXIST"))return"locked";throw o}try{return await r()}finally{await fe.rmdir(n)}}async function mp(t,e){if(Zr(t,e.entry_id),!Xa(e,e.entry_id)||!Qa(e,t))throw new Error("Invalid local start record.");return Qo(t,e.entry_id,async()=>{let r=jt(t,e.entry_id),n;try{n=await fe.open(r,"wx",384)}catch(o){if(Rt(o,"EEXIST"))return"exists";throw o}try{await n.writeFile(JSON.stringify(e)+`
|
|
41
|
+
`),await n.sync()}finally{await n.close()}return"claimed"})}async function hp(t,e,r,n){return Zr(t,e),Qo(t,e,async()=>{let o=await en(t,e);return o.kind!=="valid"||o.record.entry_id!==e||o.record.attempt_id!==n||!Fr(o.record.tuple,r)?"kept":(await fe.unlink(jt(t,e)),"released")})}async function gp(t,e,r){return Zr(t,e),Qo(t,e,async()=>{let n=await en(t,e);return r.kind==="valid"&&n.kind==="valid"&&Qa(r.record,t)&&r.record.entry_id===n.record.entry_id&&r.record.attempt_id===n.record.attempt_id&&Fr(r.record.tuple,n.record.tuple)||r.kind==="malformed"&&n.kind==="malformed"&&!r.identityMismatch&&!n.identityMismatch&&r.bytes!==null&&n.bytes!==null&&r.bytes.equals(n.bytes)?(await fe.unlink(jt(t,e)),"forgotten"):"changed"})}import{createServer as _p}from"http";import{randomBytes as yp,timingSafeEqual as bp}from"crypto";var wp=12e4,tl=1e4,vp=16*1024,Sp=10*6e4;async function ei(t){let e=t.apiKey.trim();if(!e.startsWith("omk_"))throw new Error("API key must start with omk_.");let r=It(t.apiUrl),{safe:n,origin:o}=Te(r);if(!n)throw new M(r,`Refusing to send credentials to untrusted origin: ${o}. A key for this endpoint works without login: set OMICS_OS_API_KEY and pass --endpoint.`);let i=_e({cloud:!0,apiUrl:r,token:e}),s=await E(i,"/gateway/auth/verify",{timeoutMs:15e3}),a={auth_mode:"api_key",api_key:e,endpoint:Ct(i.apiUrl),user_id:Re(s.user_id),email:Re(s.email),org_id:Re(s.org_id),tier:Re(s.tier)};return ur(a),{credential:a,verify:s}}async function ti(t){let e=It(t.apiUrl),r=Ct(e),n=Ue(e),o=yp(32).toString("hex"),i=await il({state:o,timeoutMs:t.timeoutMs});try{let s=await ni(n,"/gateway/oauth/cli/start",{method:"POST",body:{mode:"local_callback",callback_url:i.callbackUrl,client_name:"omics-os",...t.tenant?{tenant:t.tenant}:{}},timeoutMs:15e3}),a=Re(s.transaction_id),l=Re(s.transaction_secret),u=Re(s.state)??o,c=Re(s.authorization_url)??Re(s.auth_url)??Re(s.browser_url);if(!a||!l||!c)throw new Error("CLI auth start response missing transaction metadata.");i.setExpectedState(u),t.onAuthUrl?.(c),await t.openBrowser(c);let d=await i.waitForCode();if(!al(u,d.state??""))throw new Error("Invalid CLI auth callback state.");let p=await ol({apiUrl:n,endpoint:r,transactionId:a,transactionSecret:l,code:d.code});return ur(p),p}finally{await i.close()}}async function ol(t){let e=It(t.apiUrl),r=t.endpoint??Ct(e),n=Ue(e),o=await ni(n,"/gateway/oauth/cli/token",{method:"POST",body:{grant_type:"authorization_code",transaction_id:t.transactionId,transaction_secret:t.transactionSecret,handoff_code:t.code},timeoutMs:15e3}),i=cr(o,r);if(!i)throw new Error("CLI token response did not contain a valid Omics CLI credential.");return i}async function tn(t){let e=It(t.apiUrl),r=Ct(e),n=Ue(e),o=t.wait??qp,i=t.maxWaitMs??Sp,s=await ni(n,"/gateway/oauth/cli/device/start",{method:"POST",body:{client_name:"omics-os",...t.tenant?{tenant:t.tenant}:{}},timeoutMs:15e3});if(!s.device_code||!s.user_code||!s.verification_uri)throw new Error("Device auth start response missing required fields.");await t.onVerification(s);let a=Math.max(Number(s.interval??5),1),l=Date.now();for(;Date.now()-l<i;){let u=await sl(n,"/gateway/oauth/cli/device/token",{method:"POST",body:{device_code:s.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"},timeoutMs:15e3});if(u.ok){let d=cr(u.body,r);if(!d)throw new Error("Device token response did not contain a valid Omics CLI credential.");return ur(d),d}let c=oi(u.body);if(c==="authorization_pending"){await o(a*1e3);continue}if(c==="slow_down"){a+=5,await o(a*1e3);continue}throw c==="expired_token"?new Error("Device login expired. Run omics-os login --device again."):c==="access_denied"?new Error("Device login was denied."):new Error(`Device login failed${c?`: ${c}`:""}.`)}throw new Error("Device login timed out.")}async function ri(t={}){let e=Y(t.profile);if(!e)throw new Error(qe);let r=It(t.apiUrl??Oe(e.endpoint)),n=_e({cloud:!0,apiUrl:r,profile:t.profile});return E(n,"/gateway/auth/verify",{timeoutMs:15e3})}async function mr(t={}){let e=Y(t.profile),r=!1;if(e?.auth_mode==="oauth"){let o=It(t.apiUrl??Oe(e.endpoint)),i=Ue(o);try{let s=_e({cloud:!0,apiUrl:i,profile:t.profile});await E(s,"/gateway/oauth/cli/revoke",{method:"POST",body:{credential_id:e.credential_id},timeoutMs:1e4}),r=!0}catch{r=!1}}return{removed:Lo(t.profile),revoked:r}}async function il(t){let e=t.state,r=!1,n,o,i,s=new Promise((u,c)=>{n=d=>{r||(r=!0,i&&clearTimeout(i),u(d))},o=d=>{r||(r=!0,i&&clearTimeout(i),c(d))}}),a=_p((u,c)=>{kp(u,c,e,n)});a.requestTimeout=tl,a.headersTimeout=tl,await new Promise((u,c)=>{a.once("error",c),a.listen(0,"127.0.0.1",()=>{a.off("error",c),u()})}),i=setTimeout(()=>{o(new Error("Login timed out waiting for browser callback.")),Zo(a)},t.timeoutMs??wp);let l=a.address();if(!l?.port)throw await Zo(a),new Error("Failed to bind local CLI auth callback server.");return{callbackUrl:`http://127.0.0.1:${l.port}/callback`,setExpectedState:u=>{e=u},waitForCode:()=>s,close:async()=>{i&&clearTimeout(i),await Zo(a)}}}async function kp(t,e,r,n){let o=new URL(t.url??"/","http://127.0.0.1");if(o.pathname!=="/callback"){e.writeHead(404),e.end("Not found");return}if(t.method==="GET"){let i=o.searchParams.get("state")??"",s=o.searchParams.get("code")??o.searchParams.get("handoff_code")??"";if(!rl(r,i,e)||!nl(s,e))return;n({code:s,state:i}),e.writeHead(200,{"Content-Type":"text/html"}),e.end("<html><body><h2>Omics-OS CLI login complete.</h2><p>You can close this tab.</p></body></html>");return}if(t.method==="POST"){let i=await xp(t,e);if(!i)return;if(Ep(i)){e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Durable credentials are not accepted on the local callback.");return}let s=typeof i.state=="string"?i.state:"",a=typeof i.code=="string"?i.code:typeof i.handoff_code=="string"?i.handoff_code:"";if(!rl(r,s,e)||!nl(a,e))return;n({code:a,state:s}),e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({success:!0}));return}e.writeHead(405,{Allow:"GET, POST"}),e.end("Method not allowed")}async function ni(t,e,r){let n=await sl(t,e,r);if(!n.ok){let o=oi(n.body)??`HTTP ${n.status}`,i=Cp(n.body);throw new Error(`Auth request failed: ${o}${i&&i!==o?` \u2014 ${i}`:""}`)}return n.body}async function sl(t,e,r){let{safe:n,origin:o}=Te(t);if(!n)throw new Error(`Refusing to send auth request to untrusted origin: ${o}.`);let i=typeof r.timeoutMs=="number"?new AbortController:void 0,s=i?setTimeout(()=>i.abort(),r.timeoutMs):void 0;try{let a=await fetch(`${t}${e}`,{redirect:"error",method:r.method,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{}},...r.body!==void 0?{body:JSON.stringify(r.body)}:{},...i?{signal:i.signal}:{}}),l;try{l=await a.json()}catch{l=void 0}return{ok:a.ok,status:a.status,body:l}}finally{s&&clearTimeout(s)}}async function xp(t,e){let r="",n=0;for await(let o of t){let i=Buffer.isBuffer(o)?o:Buffer.from(o);if(n+=i.length,n>vp){e.writeHead(413,{"Content-Type":"text/plain"}),e.end("Payload too large");return}r+=i.toString("utf-8")}try{let o=JSON.parse(r);if(!o||typeof o!="object")throw new Error("not object");return o}catch{e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Invalid JSON");return}}function rl(t,e,r){return al(t,e)?!0:(r.writeHead(403,{"Content-Type":"text/plain"}),r.end("Invalid state parameter"),!1)}function nl(t,e){return t?!0:(e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Missing one-time code"),!1)}function Ep(t){return typeof t.access_token=="string"||typeof t.refresh_token=="string"||typeof t.id_token=="string"||typeof t.cli_token=="string"||typeof t.api_key=="string"}function It(t){if(!t)return lt;if(t.endsWith("/api/v1"))return t.replace(/\/+$/,"");let e=new URL(t);return e.pathname==="/"||e.pathname===""?Oe(e.origin):t.replace(/\/+$/,"")}function al(t,e){if(t.length!==e.length)return!1;try{return bp(Buffer.from(t),Buffer.from(e))}catch{return!1}}function Zo(t){return new Promise(e=>{if(!t.listening){e();return}t.close(()=>e())})}function oi(t){if(!t||typeof t!="object")return;let e=t,r=e.error??e.code??e.detail??e.message;if(typeof r=="string")return r;if(r&&typeof r=="object")return oi(r)}function Cp(t){if(!t||typeof t!="object")return;let e=t,r=e.detail;if(r&&typeof r=="object"){let n=r.message;if(typeof n=="string"&&n.length>0)return n}return typeof e.message=="string"&&e.message.length>0?e.message:void 0}function Re(t){return typeof t=="string"&&t.length>0?t:void 0}function qp(t){return new Promise(e=>setTimeout(e,t))}async function ii(t,e,r){let n=`/org/projects/${encodeURIComponent(e)}/data/${r.split("/").map(encodeURIComponent).join("/")}`,o=await X(t),i=await fetch(`${t.apiUrl}${n}`,{redirect:"error",headers:{...o}});if(i.status===401)throw new M(n);if(!i.ok)throw new w(n,i.status,i.statusText);if(!i.body)throw new H(n,new Error("No response body"));return i.body}var si=500*1024*1024;async function ai(t,e,r){let n=`/org/projects/${encodeURIComponent(e)}/data-link/${r.split("/").map(encodeURIComponent).join("/")}`,o=await E(t,n),i;try{typeof o.url=="string"&&(i=new URL(o.url))}catch{i=void 0}if(i?.protocol!=="https:")throw Object.assign(new U(n,200),{publicMessage:"The server returned no usable HTTPS download link; nothing was downloaded."});let s=await fetch(i,{redirect:"error",credentials:"omit"});if(!s.ok)throw new w(n,s.status,s.statusText,"storage refused the download link");if(!s.body)throw new H(n,new Error("No response body"));return s.body}function ll(t){return`This login cannot open project ${t}. Either it is an organisation project you are not assigned to (ask an organisation admin), or it belongs to an organisation this login does not reach (log in to it: omics-os login --tenant <organisation>).`}async function hr(t,e){let r=`/projects/${encodeURIComponent(e)}`,n;try{n=await E(t,r)}catch(o){throw o instanceof w&&o.status===403?new Error(ll(e)):o instanceof w&&o.status===404?new Error(`Project ${e} was not found.`):o}if(typeof n?.project?.project_id!="string")throw new U(r,200);return n.project}async function li(t,e){let r=await E(t,"/projects",{method:"POST",body:e});if(typeof r?.project?.project_id!="string")throw new U("/projects",201);return r.project}function ui(t,e){if(t instanceof w)return t.status===404&&t.code==="project_not_found"?`Project ${e} was not found in this login's organisation, or it is a personal project. Uploads go to organisation projects: check the ID, or log in to the project's organisation (omics-os login --tenant <organisation>).`:t.status===403&&!t.code?ll(e):void 0}var Ap=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gr(t){return Ap.test(t)}var ci=6e4,rn=class extends Error{constructor(){super(`Omics-OS Cloud did not answer within ${ci/1e3} s`),this.name="SessionOpenTimeoutError"}};async function ul(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ci);try{return await t(e.signal)}catch(n){throw e.signal.aborted?new rn:n}finally{clearTimeout(r)}}function _r(t){let e=t.filter(o=>o.reason!=="listing_failed").length,r=e===0?"":e===1?"1 project file was not copied into this session; the agent cannot read it here":`${e.toLocaleString("en-US")} project files were not copied into this session; the agent cannot read them here`;if(e===t.length)return r;let n="The project's file list could not be read, so this session may lack some or all of the project's files; start a new session to try again";return r?`${r}. ${n}`:n}function Op(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return[];let{relative_path:r,size_bytes:n,reason:o}=e;return typeof r!="string"||typeof o!="string"?[]:[{relative_path:r,size_bytes:typeof n=="number"?n:null,reason:o}]}):[]}async function nn(t,e,r={}){let n=`${t.apiUrl}/sessions`,o={name:r.name??"CLI Session",client_source:"cli",...await cl(t,r.project)},i=await X(t);return ul(s=>$p(t,n,i,s,o,e))}async function cl(t,e){return e?e.org_id?{org_project_id:e.project_id}:{project_id:e.project_id}:t.projectId?t.isCloud?cl(t,await hr(t,t.projectId)):{project_id:t.projectId}:{}}async function $p(t,e,r,n,o,i){let s=await fetch(e,{signal:n,redirect:"error",method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(o)});if(!s.ok){let c="";try{let p=await s.json();c=String(p.detail??p.message??p.error??"").slice(0,200)}catch{}let d=`Failed to create session: ${s.status} ${s.statusText}`;throw new Error(c?`${d} \u2014 ${c}`:d)}let a=await s.json(),l=a.session?.session_id??a.session_id??a.id;if(!l)throw new Error("Backend returned no session_id");if(t.isCloud&&!gr(l))throw new Error(`Backend returned invalid session ID: ${l.slice(0,40)}`);let u=Op(a.seed_warnings);return u.length&&i?.(u),l}async function on(t){let e=await E(t,"/sessions");return Array.isArray(e)?e:e.sessions??[]}async function di(t,e){if(t.sessionId){if(t.sessionId.toLowerCase()==="latest"){let r=await ul(o=>Promise.race([on(t),new Promise((i,s)=>o.addEventListener("abort",()=>s(o.reason)))]));if(r.length===0)throw new Error("No existing sessions found. Start a new one first.");return r.sort((o,i)=>new Date(i.last_activity??i.created_at).getTime()-new Date(o.last_activity??o.created_at).getTime())[0].session_id}if(t.isCloud&&!gr(t.sessionId))throw new Error(`Invalid session ID format: "${t.sessionId}". Expected a UUID.`);return t.sessionId}try{return await nn(t,e)}catch(r){if(t.isCloud)throw r;return`local_${crypto.randomUUID().slice(0,12)}`}}async function fi(t,e){await E(t,`/sessions/${e}/archive`,{method:"POST"})}async function pi(t,e){await E(t,`/sessions/${e}`,{method:"DELETE"})}async function mi(t,e){return E(t,`/sessions/${e}/share`,{method:"POST"})}async function hi(t,e){return E(t,`/sessions/${e}`)}async function Pt(t,e){return await E(t,`/sessions/${e}/chat/cancel`,{method:"POST"})}var Tp="The agent store is not available.";function Rp(t,e,r){let n=new w(t.path,t.status,t.statusText,t.detail,t.body,t.code,void 0,t.types,{retryable:!1,requestId:t.requestId});return n.kind=e,n.publicMessage=r,n.message=r,n.exitCode=1,n.cause=t,n}async function gi(t,e){if(!t.token)throw new M("/agents/store");try{return await e()}catch(r){throw r instanceof w&&r.status===404&&r.detail==="Agent store is not enabled"?Rp(r,"unavailable",Tp):r}}async function _i(t,e={}){let r=new URLSearchParams;e.limit!==void 0&&r.set("limit",String(e.limit)),e.nextToken!==void 0&&r.set("next_token",e.nextToken),e.category!==void 0&&r.set("category",e.category);let n=r.size?`?${r}`:"";return gi(t,()=>E(t,`/agents/store${n}`))}async function sn(t,e,r){let n=r===void 0||r==="latest"?void 0:r;try{return await gi(t,()=>n===void 0?E(t,`/agents/store/${encodeURIComponent(e)}`):E(t,`/agents/store/${encodeURIComponent(e)}/${encodeURIComponent(n)}`))}catch(o){if(o instanceof w&&o.status===404&&o.kind!=="unavailable")return null;throw o}}async function yi(t,e,r){let n=r===void 0||r==="latest"?await jp(t,e):r;return gi(t,()=>E(t,`/agents/store/${encodeURIComponent(e)}/${encodeURIComponent(n)}/download`))}async function jp(t,e){let r=await sn(t,e);if(!r)throw new w(`/agents/store/${encodeURIComponent(e)}`,404,"Not Found","Package not found");return r.version}async function yr(t,e,r){let n=r?`?directory=${encodeURIComponent(r)}`:"";return(await E(t,`/sessions/${e}/files${n}`)).files??[]}async function bi(t,e,r,n,o){let i=`${t.apiUrl}/sessions/${e}/files/upload`,s=await X(t),a=new FormData,l=r instanceof Blob?r:new Blob([r]);a.append("file",l,n),o?.description&&a.append("description",o.description);let u=await fetch(i,{redirect:"error",method:"POST",headers:{...s},body:a,signal:o?.signal});if(u.status===401)throw new M(`/sessions/${e}/files/upload`);if(!u.ok){let c=`/sessions/${e}/files/upload`,d=await Vo(u),{detail:p,code:f,error:h,subcode:_}=Et(d),b=Gr(u.headers.get("retry-after"));throw u.status===429?new pe(c,b,p,d,f,{error:h,subcode:_}):new w(c,u.status,u.statusText,p,d,f,b,{error:h,subcode:_})}return await u.json()}async function wi(t,e,r,n){let o=`${t.apiUrl}/sessions/${e}/files/${encodeURIComponent(r)}/download${n?.inline?"?inline=true":""}`,i=await X(t),s=await fetch(o,{redirect:"error",headers:{...i},signal:n?.signal});if(s.status===401)throw new M(`/sessions/${e}/files/${r}/download`);if(!s.ok)throw new w(`/sessions/${e}/files/${r}/download`,s.status,s.statusText);if(!s.body)throw new H(`/sessions/${e}/files/${r}/download`,new Error("No response body"));return s.body}async function vi(t,e,r){await E(t,`/sessions/${e}/files/${encodeURIComponent(r)}`,{method:"DELETE"})}async function Si(t,e,r){return E(t,`/sessions/${e}/data/load`,{method:"POST",body:{file_path:r}})}async function ki(t,e,r,n){let o=`/sessions/${e}/files/${encodeURIComponent(r)}/download`,i=t.streamApiUrl&&t.streamApiUrl!==t.apiUrl?[t.streamApiUrl,t.apiUrl]:[t.apiUrl];for(let[s,a]of i.entries()){let l=await X(t),u=await fetch(`${a}${o}`,{redirect:"error",headers:{...l},signal:n?.signal});if(u.status===403&&s<i.length-1){await u.body?.cancel().catch(()=>{});continue}if(u.status===401)throw new M(o);if(!u.ok)throw new w(o,u.status,u.statusText);if(!u.body)throw new H(o,new Error("No response body"));let c=Number(u.headers.get("content-length"));return{body:u.body,size:Number.isSafeInteger(c)&&u.headers.has("content-length")?c:null}}throw new H(o)}var br=100,an=t=>`/uploads/${encodeURIComponent(t)}`;function xi(t,e,r){return E(t,"/uploads",{method:"POST",body:e,retry:"safe",signal:r})}async function Ei(t,e,r,n){if(r.length>br)throw new RangeError(`at most ${br} parts per sign call`);return(await E(t,`${an(e)}/parts/sign`,{method:"POST",body:{parts:r},retry:"safe",signal:n})).parts??[]}function ln(t,e,r){return E(t,an(e),{signal:r})}function Ci(t,e,r,n){return E(t,`${an(e)}/complete`,{method:"POST",body:n?{resume_trust:n}:{},signal:r,maxRetryAfterMs:6e4})}async function un(t,e,r){await E(t,an(e),{method:"DELETE",signal:r})}var Ip=new Set(["uploads_disabled","policy","upload_too_large","upload_not_found","upload_expired","part_out_of_range","checksum_mismatch","size_mismatch","parts_missing","upload_completed","file_exists","upload_in_progress","quota_exceeded","not_current","complete_conflict","complete_in_progress"]);function Xe(t){if(!(!(t instanceof w)||!t.code))return Ip.has(t.code)?t.code:void 0}function qi(t){if(!(t instanceof w))return!1;let e=Xe(t);return e==="uploads_disabled"||e==="policy"?!0:t.status===404&&!t.code&&t.path==="/uploads"}import{createHash as fl}from"node:crypto";import{open as Pp,stat as dl}from"node:fs/promises";import pl from"node:http";import ml from"node:https";var hl=1024*1024,Ai=8*hl,Np=hl,vr=4,dt=16,Lp=6e4,Dp=3e3,Up=16*1024,Mp=new Set(["authorization","x-api-key","cookie","proxy-authorization","host","content-length"]),J=class extends Error{reason;versionId;constructor(e,r,n){super(r,n),this.reason=e,this.name="UploadFailure",n?.versionId&&(this.versionId=n.versionId)}},Fp=new Set(["file_exists","upload_in_progress","quota_exceeded","upload_too_large","not_current","complete_conflict"]);function Vp(t){if(!(t instanceof w))return t;let e=Xe(t),r=e&&Fp.has(e)?e:t.status===400&&t.path==="/uploads"?"invalid_path":void 0;if(!r)return t;let n=typeof t.body?.version_id=="string"?t.body.version_id:void 0;return new J(r,t.detail||t.message,{cause:t,...n?{versionId:n}:{}})}var Nt=class extends Error{status;s3Code;constructor(e,r,n){super(n),this.status=e,this.s3Code=r,this.name="PartPutError"}};function dn(t){let e=0,r=[];return{async run(n){e>=t&&await new Promise(o=>r.push(o)),e++;try{return await n()}finally{e--,r.shift()?.()}}}}function wr(t,e){let r=(e-1)*t.partSize,n=Math.min(t.size,e*t.partSize);return{start:r,end:n-1,length:n-r}}async function gl(t,e,r,n,o){let i=await Pp(t,"r");try{let s=Buffer.allocUnsafe(Math.min(Np,r-e+1));for(let a=e;a<=r;){o?.throwIfAborted();let{bytesRead:l}=await i.read(s,0,Math.min(s.length,r-a+1),a);if(l===0)throw new J("file_changed","the file got shorter while it was being read");await n(s.subarray(0,l)),a+=l}}finally{await i.close().catch(()=>{})}}function cn(t,e,r,n,o,i){return gl(e,r,n,s=>{t.update(s),i?.(s.length)},o)}async function _l(t,e,r){let n=fl("sha256");return e<=2*Ai?e>0&&await cn(n,t,0,e-1,r):(await cn(n,t,0,Ai-1,r),await cn(n,t,e-Ai,e-1,r)),n.update(String(e)),n.digest("hex")}async function Oi(t,e,r,n,o){let i=fl("sha256");return await cn(i,t,e,r,n,o),i.digest("base64")}function Bp(t){let e;try{e=new URL(t)}catch{throw new J("server","The server returned an unreadable upload link.")}let r=e.hostname==="127.0.0.1"||e.hostname==="localhost"||e.hostname==="[::1]";if(e.protocol==="https:"||e.protocol==="http:"&&r)return e;throw new J("server","The server returned an upload link that is not HTTPS; nothing was sent.")}function zp(t,e){let r={};for(let[n,o]of Object.entries(t.headers??{}))Mp.has(n.toLowerCase())||(r[n]=o);return r["Content-Length"]=String(e),r.Expect="100-continue",r}function Hp(t){return/<Code>([^<]{1,64})<\/Code>/.exec(t)?.[1]}function Jp(t,e,r,n,o,i,s){let a=Bp(t.url),l=a.protocol==="https:"?ml:pl;return new Promise((u,c)=>{let d=!1,p=(g,m)=>{d||(d=!0,clearTimeout(_),g?(f.destroy(),c(g)):u(m))},f=l.request(a,{method:"PUT",headers:zp(t,r.length),agent:n,signal:o}),h=!1,_,b=g=>new Promise((m,x)=>{if(d){x(new Error("part transfer ended"));return}let C=()=>x(new Error("connection closed"));f.once("close",C),f.write(g,A=>{f.off("close",C),A?x(A):(s(g.length),m())})}),j=()=>{h||d||(h=!0,clearTimeout(_),gl(e,r.start,r.end,b).then(()=>{d||f.end()}).catch(g=>setTimeout(()=>p(g),100)))};f.setTimeout(i,()=>p(new Error(`no progress for ${Math.round(i/1e3)} s`))),f.on("continue",j),f.on("error",g=>setTimeout(()=>p(g),100)),f.on("response",g=>{let m=g.statusCode??0;if(m===200){g.resume(),g.on("end",()=>{let A=g.headers.etag;typeof A=="string"&&A?p(void 0,A):p(new Nt(m,void 0,"storage accepted a part without an ETag"))}),g.on("error",A=>p(A));return}let x="";g.setEncoding("utf8"),g.on("data",A=>{x.length<Up&&(x+=A)});let C=()=>{let A=Hp(x);p(new Nt(m,A,`storage answered ${m}${A?` ${A}`:""}`))};g.on("end",C),g.on("error",C)}),f.flushHeaders(),_=setTimeout(j,Dp)})}var Wp=new Set(["RequestTimeout","SlowDown","InternalError","ServiceUnavailable"]),Gp=new Set(["BadDigest","InvalidDigest","XAmzContentSHA256Mismatch","XAmzContentChecksumMismatch"]);function $i(t,e,r){let n=Math.min(6e4,e*2**t)*(.75+Math.random()*.5);return new Promise((o,i)=>{if(r.aborted){i(r.reason);return}let s=()=>{clearTimeout(a),i(r.reason)},a=setTimeout(()=>{r.removeEventListener("abort",s),o()},n);r.addEventListener("abort",s,{once:!0})})}var Kp=24,Yp=960;async function Ti(t,e,r){let n=0,o;for(;;)try{return await t()}catch(i){if(Xe(i)==="complete_in_progress"){if(o??=Date.now()+Yp*e,Date.now()>=o)throw i}else if(!(i instanceof pe)||n++>=Kp)throw i;await $i(0,Math.max(i.retryAfterMs??0,5*e),r)}}async function yl(t,e,r){let n=new Array(t.length),o=0,i=async()=>{for(;o<t.length;){let s=o++;n[s]=await r(t[s])}};return await Promise.all(Array.from({length:Math.min(e,t.length)},i)),n}function Ri(t,e){return Xp(t,e).catch(r=>{throw Vp(r)})}async function Xp(t,e){let r=e.concurrency??vr;if(!Number.isInteger(r)||r<1||r>dt)throw new RangeError(`concurrency must be 1\u2013${dt}`);let n=e.signal??new AbortController().signal;n.throwIfAborted();let o=await dl(e.path);if(!o.isFile())throw new J("not_regular","not a regular file");if(o.size===0)throw new J("empty","empty file");let i=o.size,s=Math.floor(o.mtimeMs),a=await _l(e.path,i,n),l=!1,u=p=>{let f=Xe(p);return e.replace===!0&&!l&&(f==="file_exists"||f==="upload_in_progress")},c=!1,d;for(let p=0;p<4;p++){let f;try{f=await Ti(()=>xi(t,{project_id:e.projectId,relative_path:e.relativePath,size_bytes:i,fingerprint:a,client_sha256:null,mtime_ms:s,...l?{replace:!0}:{}},n),e.retryBaseMs??1e3,n)}catch(x){if(!u(x))throw x;l=!0;continue}if(f.state==="completed"){if(c)throw new J("server","the server kept answering 'already uploaded' after a replace; stopped");return{outcome:"skipped",relativePath:f.relative_path??e.relativePath,sizeBytes:i,partsSent:0,partsReused:0,...f.version_id?{versionId:f.version_id}:{},...f.match?{match:f.match}:{}}}if(l&&(c=!0),!f.upload_id)throw new J("server","the server started an upload without an id");let h={size:i,partSize:f.part_size_bytes,partCount:f.part_count};if(!(h.partSize>0)||h.partCount!==Math.ceil(i/h.partSize))throw new J("server","the server's part layout does not fit the file size");let _=f.upload_id,b=[],j="none",g,m;try{if(f.state==="open"||f.state==="completing"){let A=typeof f.mtime_ms=="number"&&f.mtime_ms!==s,D=f.state==="completing"?"completing":await Qp(t,_,e,h,A,n);if(D==="restart"){try{await un(t,_,n)}catch(v){if(Xe(v)!=="upload_completed")throw v;if(c)throw new J("file_changed","the file differs from its completed upload and a replace did not take; stopped",{cause:v});l=!0}continue}b=D==="completing"?Array.from({length:h.partCount},(v,S)=>S+1):D,b.length&&(j=A?"rehash":typeof f.mtime_ms=="number"?"fingerprint+mtime":"fingerprint")}let x=new Set(b);m=[];for(let A=1;A<=h.partCount;A++)x.has(A)||m.push(A);await Zp(t,_,e,h,m,b,r,n);let C=await dl(e.path);if(C.size!==o.size||C.mtimeMs!==o.mtimeMs)throw await un(t,_,n).catch(()=>{}),new J("file_changed","the file changed while it was being uploaded; run the command again");g=await em(t,_,n,e.retryBaseMs??1e3,j)}catch(x){let C=Xe(x),A=C==="complete_conflict"?"complete_conflict":C==="upload_expired"||C==="upload_not_found"||x instanceof J&&x.reason==="expired"?"expired":void 0;if(A&&!d){d=A;continue}if(u(x)){l=!0;continue}throw x}return{outcome:b.length?"resumed":"sent",relativePath:g.relative_path??e.relativePath,sizeBytes:g.size_bytes,partsSent:m.length,partsReused:b.length,...g.version_id?{versionId:g.version_id}:{},...d?{restarted:d}:{},...g.resume_trust?{resumeTrust:g.resume_trust}:{}}}throw new J("server","the upload had to restart too often; stopped")}async function Qp(t,e,r,n,o,i){let s=await ln(t,e,i);if(s.status==="completing")return"completing";if(s.status!=="open"||s.part_size_bytes!==n.partSize||s.part_count!==n.partCount)return"restart";let a=s.parts??[],l=f=>Number.isInteger(f.part_number)&&f.part_number>=1&&f.part_number<=n.partCount&&f.size_bytes===wr(n,f.part_number).length;if(!o)return a.every(l)?a.map(f=>f.part_number):"restart";let u=0,c=a.reduce((f,h)=>f+(h.size_bytes>0?h.size_bytes:0),0),d=f=>{u+=f,r.onProgress?.({phase:"verify",bytes:u,total:c})};return(await yl(a,4,async f=>{if(!l(f)||!f.checksum_sha256)return!1;let h=wr(n,f.part_number);return await Oi(r.path,h.start,h.end,i,d)===f.checksum_sha256})).includes(!1)?"restart":a.map(f=>f.part_number)}async function Zp(t,e,r,n,o,i,s,a){let l=new AbortController,u=AbortSignal.any([a,l.signal]),c=r.limiter??dn(s),d=new ml.Agent({keepAlive:!0,maxSockets:s}),p=new pl.Agent({keepAlive:!0,maxSockets:s}),f=r.retryBaseMs??1e3,h=r.maxAttempts??8,_=r.idleTimeoutMs??12e4,b=Math.min(br,Math.max(8,s*4)),j=i.reduce((N,z)=>N+wr(n,z).length,0),g=0,m=()=>r.onProgress?.({phase:"send",bytes:j+g,total:n.size});m();let x=async N=>{let z=await Ti(()=>Ei(t,e,N.map(k=>({part_number:k.part,checksum_sha256:k.checksum})),u),f,u),Z=new Map(z.map(k=>[k.part_number,k]));return N.map(k=>{let T=Z.get(k.part);if(!T)throw new J("server",`the server did not sign part ${k.part}`);return{part:k.part,checksum:k.checksum,signed:T}})},C=N=>{let z=wr(n,N);return Oi(r.path,z.start,z.end,u)},A=[...o],D=[],v=null,S,I=()=>{if(!v&&A.length&&S===void 0){let N=A.splice(0,b);v=yl(N,Math.min(s,4),async z=>({part:z,checksum:await C(z)})).then(x).then(z=>{D.push(...z)}).catch(z=>{S??=z}).finally(()=>{v=null})}return v??Promise.resolve()},L=async()=>{for(;;){if(S!==void 0)throw S;let N=D.shift();if(N)return D.length<b/2&&I(),N;if(!A.length&&!v)return;await I()}},te=async N=>{let z=wr(n,N.part),Z=0,k=!1;for(let T=0;;T++){u.throwIfAborted(),Date.parse(N.signed.expires_at)-Date.now()<Lp&&(N=(await x([{part:N.part,checksum:N.checksum}]))[0]);let xe=0;try{let V=N.signed.url.startsWith("https:")?d:p;await c.run(()=>Jp(N.signed,r.path,z,V,u,_,Ee=>{xe+=Ee,g+=Ee,m()})),g-=xe,j+=z.length,m();return}catch(V){if(g-=xe,m(),u.throwIfAborted(),V instanceof J)throw V;if(V instanceof Nt){if(V.status===403&&Z<2){Z++,N=(await x([{part:N.part,checksum:N.checksum}]))[0];continue}if(V.s3Code==="NoSuchUpload")throw new J("expired","the unfinished upload expired on the server",{cause:V});if(V.s3Code&&Gp.has(V.s3Code)){if(k)throw new J("file_changed","the file changed while it was being uploaded; run the command again",{cause:V});k=!0,N=(await x([{part:N.part,checksum:await C(N.part)}]))[0];continue}if(!(V.status>=500||V.status===408||V.status===429||V.status===200||V.s3Code!==void 0&&Wp.has(V.s3Code))||T+1>=h)throw new J("part_failed",`part ${N.part} failed: ${V.message}`,{cause:V})}else if(T+1>=h)throw new J("part_failed",`part ${N.part} failed after ${h} attempts: ${V instanceof Error?V.message:String(V)}`,{cause:V});await $i(T,f,u)}}},ce=async()=>{for(let N=await L();N;N=await L())await te(N)};try{let N=await Promise.allSettled(Array.from({length:s},async()=>{try{await ce()}catch(Z){throw S??=Z,l.abort(Z),Z}}));a.throwIfAborted();let z=N.find(Z=>Z.status==="rejected");if(z)throw S??z.reason}finally{d.destroy(),p.destroy()}}async function em(t,e,r,n,o){for(let i=0;;i++)try{return await Ti(()=>Ci(t,e,r,o),n,r)}catch(s){if(r.throwIfAborted(),!(s instanceof ne)||i>=2)throw s;if(await $i(i,n,r),(await ln(t,e,r)).status==="aborted")throw new J("expired","the upload was aborted on the server before it completed")}}async function ji(t,e,r){let n={};return r?.exportType&&(n.export_type=r.exportType),r?.format&&(n.format=r.format),E(t,`/sessions/${e}/export`,{method:"POST",body:n})}async function bl(t,e,r){return E(t,`/sessions/${e}/export/${r}`)}async function Ii(t,e,r,n){let o=`${t.apiUrl}/sessions/${e}/files/${encodeURIComponent(r)}/download`,i=await X(t),s=await fetch(o,{redirect:"error",headers:{...i},signal:n?.signal});if(s.status===401)throw new M(`/sessions/${e}/files/${r}/download`);if(!s.ok)throw new w(`/sessions/${e}/files/${r}/download`,s.status,s.statusText);if(!s.body)throw new H(`/sessions/${e}/files/${r}/download`,new Error("No response body"));return s.body}function tm(t){return t instanceof M?!1:t instanceof H?!0:t instanceof w?t.status===409?(t.types.error??t.code)==="worker_hydrating":t.status===429||t.status>=500:!1}async function Pi(t,e,r,n){let o=n?.pollIntervalMs??2e3,i=n?.timeoutMs??3e5,s=Date.now()+i,a=n?.maxConsecutiveFailures??3,l=0;for(;Date.now()<s;){let u;try{u=await bl(t,e,r),l=0}catch(c){if(c instanceof w&&c.retryable===!1||!tm(c)||++l>=a)throw c;let d=c instanceof w?c.retryAfterMs:void 0,p=Math.min(Math.max(o,d??0),Math.max(0,s-Date.now()));await new Promise(f=>setTimeout(f,p));continue}if(u.status==="complete"||u.status==="failed")return u;await new Promise(c=>setTimeout(c,o))}return{job_id:r,status:"failed",error:"Export timed out"}}async function Ni(t,e){let r=new URLSearchParams({genes:e.genes.join(","),disease:e.disease,control:e.control});return E(t,`/vault/cache/search?${r.toString()}`)}async function Li(t,e){return E(t,`/vault/evidence/${e}`)}async function Di(t,e){return E(t,"/vault/export",{method:"POST",body:e})}async function Ui(t,e,r){let n=r?.force?"?force=true":"";return E(t,`/editor/${e}/generate${n}`,{method:"POST"})}async function Mi(t,e,r){return E(t,`/editor/${e}/generate/${r}`)}async function Fi(t,e){return E(t,`/editor/${e}/meta`)}async function Vi(t,e){return(await E(t,`/editor/${e}/files`)).files??[]}async function Bi(t,e,r,n){let o=`${t.apiUrl}/editor/${e}/files/${encodeURIComponent(r)}`,i=await X(t),s=await fetch(o,{redirect:"error",headers:{...i},signal:n?.signal});if(s.status===401)throw new M(`/editor/${e}/files/${r}`);if(!s.ok)throw new w(`/editor/${e}/files/${r}`,s.status,s.statusText);return s.arrayBuffer()}async function zi(t,e,r,n){let o=`${t.apiUrl}/editor/${e}/files/${encodeURIComponent(r)}`,i=await X(t),s=typeof n=="string"?new TextEncoder().encode(n):n,a=await fetch(o,{redirect:"error",method:"PUT",headers:{"Content-Type":"application/octet-stream",...i},body:s});if(a.status===401)throw new M(`/editor/${e}/files/${r}`);if(!a.ok){let l;try{let u=await a.json();l=String(u.detail??"").slice(0,200)||void 0}catch{}throw new w(`/editor/${e}/files/${r}`,a.status,a.statusText,l)}return await a.json()}async function Hi(t,e,r){let n=`${t.apiUrl}/editor/${e}/download-zip`,o=await X(t),i=await fetch(n,{redirect:"error",method:"POST",headers:{...o},signal:r?.signal});if(i.status===401)throw new M(`/editor/${e}/download-zip`);if(!i.ok){let s;try{let a=await i.json();s=String(a.detail??"").slice(0,200)||void 0}catch{}throw new w(`/editor/${e}/download-zip`,i.status,i.statusText,s)}return i.arrayBuffer()}async function vl(t,e,r){return E(t,`/editor/${e}/compile`,{method:"POST",signal:r?.signal})}async function Sl(t,e,r,n){return E(t,`/editor/${e}/compile/${encodeURIComponent(r)}`,{signal:n?.signal})}function Lt(t,e,r,n){let o=new w(t,0,"",void 0,void 0,n);return o.kind=e,o.publicMessage=r,o}function wl(t,e){return e?new Promise((r,n)=>{let o=()=>n(e.reason);if(t.then(i=>{e.removeEventListener("abort",o),r(i)},i=>{e.removeEventListener("abort",o),n(i)}),e.aborted){o();return}e.addEventListener("abort",o,{once:!0})}):t}async function kl(t,e){let r="compiled PDF",n=null;try{n=new URL(t)}catch{}if(!n||n.protocol!=="https:"||n.username!==""||n.password!==""||!n.hostname.toLowerCase().endsWith(".amazonaws.com"))throw Lt(r,"unreadable","The server's PDF link is not an https S3 link; nothing was written.");let o=e?.signal,i,s;try{i=await wl(fetch(n,{redirect:"error",method:"GET",headers:{Accept:"application/pdf"},signal:o}),o);let u=i;s=await wl(u.arrayBuffer(),o).catch(c=>{throw u.body?.cancel().catch(()=>{}),c})}catch{throw o?.aborted?o.reason:Lt(r,"network","The compiled PDF could not be downloaded; nothing was written.")}let a=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),l=new TextDecoder().decode(new Uint8Array(s,0,Math.min(5,s.byteLength)));if(i.status!==200||a!=="application/pdf"||l!=="%PDF-")throw Lt(r,"unreadable",`The PDF link did not return a PDF (HTTP ${i.status}, ${a||"no content type"}); nothing was written.`);return s}var rm=(t,e)=>new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}let o=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t),i=()=>{clearTimeout(o),n(e?.reason)};e?.addEventListener("abort",i,{once:!0})});async function Ji(t,e,r){let n=`/editor/${e}/compile`,o=r?.intervalMs??2e3,i=r?.timeoutMs??33e4,s=r?.sleep??rm,a=new AbortController,l=setTimeout(()=>a.abort(new Error("compile wait budget used up")),i),u=r?.signal?AbortSignal.any([r.signal,a.signal]):a.signal,c=f=>Lt(n,"timeout",`The compile ${f?"is still running":"request got no answer"} after ${Math.round(i/1e3)} s${f?"":" (it may have started)"}; nothing was written. Open it in the Omics-OS Editor: https://editor.omics-os.com`),d=!1;try{return await p()}catch(f){throw a.signal.aborted&&!r?.signal?.aborted?c(d):f}finally{clearTimeout(l)}async function p(){let f=Date.now()+i,h;try{h=await vl(t,e,{signal:u})}catch(_){throw _ instanceof ne&&a.signal.aborted?c(!1):_}if(d=!0,typeof h?.job_id!="string"||!h.job_id)throw new U(n,202,"Accepted");for(;;){let _=await Sl(t,e,h.job_id,{signal:u});if(_?.status==="complete"){if(typeof _.pdf_url!="string")throw Lt(n,"unreadable","The compile finished without a PDF link; nothing was written.");return{pdf:await kl(_.pdf_url,{signal:u}),jobId:h.job_id}}if(_?.status==="failed"){let b=typeof _.error=="string"&&_.error.trim()?_.error.trim().slice(0,300):"Compilation failed";throw Lt(n,"compile_failed",`The compile failed: ${b}. Nothing was written.`,typeof _.error_code=="string"?_.error_code:void 0)}if(Date.now()>=f)throw c(!0);r?.onStatus?.(String(_?.status??"pending")),await s(o,u)}}}async function Wi(t,e){return E(t,"/vector-search",{method:"POST",body:{query:e.query,top_k:e.top_k??5,collections:e.collections??["mondo","uberon","cell_ontology"]}})}import qs from"node:path";import{spawnSync as As}from"node:child_process";function O(t){let{json:e,endpoint:r,profile:n}=t.optsWithGlobals();return{json:e,endpoint:r,profile:n}}function R(t){return _e({cloud:!0,apiUrl:t.endpoint,profile:t.profile})}async function q(t,e=!1){try{return await t()}catch(r){let{payload:n,exitCode:o}=De(r);if(e)console.log(JSON.stringify(n));else{let i=r instanceof w&&r.kind&&n.code?` (code ${n.code})`:"";console.error(`${n.error}${i}`)}process.exit(o)}}var sm="87dc78cf-bb6c-4be8-b627-3ea74c3dc784";function Gi(t){return gr(t)?null:`Invalid session ID "${t.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").slice(0,40)}": expected a UUID like ${sm}.`}function Sr(t,e){e?console.log(JSON.stringify({error:t,kind:"usage",status:null,code:null,retryable:null,request_id:null})):console.error(t),process.exit(2)}function W(t,e){let r=Gi(t);r&&Sr(r,e)}function Q(t,e){let r=t.map((s,a)=>{let l=s.length;for(let u of e){let c=u[a]??"";c.length>l&&(l=c.length)}return l}),n=t.map((s,a)=>s.padEnd(r[a])).join(" "),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u2500"),i=e.map(s=>s.map((a,l)=>a.padEnd(r[l])).join(" "));return[n,o,...i].join(`
|
|
42
|
+
`)}function ie(t){let e=Math.max(...t.map(([r])=>r.length));return t.map(([r,n])=>`${r.padEnd(e)} ${n}`).join(`
|
|
43
|
+
`)}function $(t){console.log(JSON.stringify(t,null,2))}import{randomBytes as Em}from"crypto";import{createWriteStream as Cm,unlinkSync as qm}from"fs";import{readFile as Am,rename as Om,stat as Ml,unlink as $m}from"fs/promises";import{basename as Zi,dirname as Tm,join as Rm,resolve as Fl}from"path";import{Readable as jm}from"stream";import{pipeline as Im}from"stream/promises";import jl from"node:fs";import Ve from"node:fs/promises";import{basename as am,isAbsolute as lm,join as Ut,parse as um,resolve as Il,sep as cm}from"node:path";import{createHash as dm,randomBytes as fm}from"node:crypto";import{Readable as pm,Transform as mm}from"node:stream";import{pipeline as hm}from"node:stream/promises";var xl=15*6e4;function Dt(t){return t.approval_generation===y.APPROVAL_GENERATION}function El(t){return t.status==="completed"||t.status==="failed"&&(!Object.hasOwn(t,"run_terminal")||t.run_terminal===!0)||t.status==="cancelled"&&(!Object.hasOwn(t,"cancel_cleanup_status")||t.cancel_cleanup_status==="complete")}function Ki(t){if(t.unresolved||t.source==="unavailable")return"cost unavailable";let e=[];return t.spent_usd!==null&&e.push(`spent $${t.spent_usd}`),t.provisional_usd!==null&&e.push(`provisional $${t.provisional_usd}`),t.inflight_upper_bound_usd!==null&&e.push(`up to $${t.inflight_upper_bound_usd}`),e.length?e.join("; "):"cost unavailable"}function Yi(t){return["blocking","warning","info"].map(e=>{let r=e==="info"?"Info (decided by the run)":e==="warning"?"Warnings":"Blocking",n=t.filter(o=>o.kind===(e==="info"?"decided_in_run":e));return`${r}:
|
|
44
|
+
${n.length?Q(["CODE","SEVERITY","MESSAGE"],n.map(o=>[o.code,o.severity,o.message])):" None"}`}).join(`
|
|
45
|
+
`)}function kr(t){return t==="unknown_version"?"unknown_version; Update the CLI and review the draft again":t}function fn(t,e,r){let n=t.config,o=e.mode==="explicit"?`${e.model.provider}: ${e.model.model_id}`:"inherit";return ie([["Entry",t.entry_id],["Revision",String(t.revision)],["State",t.state],["Question",n.request.question],["Nodes",n.selection.nodes.map(i=>`${i.id} / ${i.label} / ${i.type} / ${i.role??"(no role)"}`).join(`
|
|
46
|
+
`)||"None"],["Cost limit",n.limits.max_cost_usd===null?"not set":`$${n.limits.max_cost_usd}`],["Storage limit",n.limits.max_storage_bytes===null?"not set":`${n.limits.max_storage_bytes} bytes`],["Model",o],["can_execute",String(t.can_execute)]])+`
|
|
47
|
+
|
|
48
|
+
`+Yi(t.checks)+`
|
|
49
|
+
|
|
50
|
+
`+(r.ok?"Ready to start":`Not ready to start: ${kr(r.reason)}`)}function Cl(t){return t.entries.length?Q(["ENTRY","STATUS","TITLE","JOBS"],t.entries.map(e=>[e.entry_id,e.status,e.title,e.job_ids.join(", ")])):"No BioVault drafts found."}function pn(t){return`${t.fields.map(e=>`${e.field} ${e.value}`).join(", ")}. ${t.notice}`}function ql(t){if(!t.jobs.length)return"No BioVault runs found.";let e=t.jobs.filter(r=>r.cli_compatibility);return Q(["JOB ID","STATUS","QUESTION","COST"],t.jobs.map(r=>[r.cli_compatibility?`${r.job_id} *`:r.job_id,r.status,r.question,Ki(r.cost)]))+e.map(r=>`
|
|
51
|
+
* ${r.job_id}: ${pn(r.cli_compatibility)}`).join("")+hn(t.next_cursor)}function Al(t){return t.jobs.length?Q(["JOB ID","STATUS","GENES","DISEASE","CREATED"],t.jobs.map(e=>[e.job_id,e.status,e.genes.join(", ").slice(0,30),e.disease,e.created_at??"-"])):"No vault jobs found."}function mn(t){if(!Dt(t))return ie([["Job ID",t.job_id],["Status",t.status],["Genes",t.genes.join(", ")],["Disease",t.disease],["Control",t.control],["Evidence ID",t.evidence_id??"-"],["Error",t.error_message??"-"],["Created",t.created_at??"-"]]);let e=t.status==="failed"?`
|
|
52
|
+
Run failed${t.failure?.message?`: ${t.failure.message}`:""}`:"";return ie([["Job ID",t.job_id],["Run ID",t.run_id],["Status",t.status],["Question",t.question],["Progress",t.progress_step??"-"],["Cost",Ki(t.cost)],["Outcome",t.outcome??"-"],["Created",t.created_at],...t.cli_compatibility?[["Compatibility",pn(t.cli_compatibility)]]:[]])+e}function Ol(t){return ie([["Job ID",t.job_id],["Folder",t.folder_state],["Outcome",t.outcome],["Stop reason",t.stop_reason??"-"],["Cost",Ki(t.cost)],["Archive",t.archive.available?"available":"unavailable"]])+`
|
|
53
|
+
|
|
54
|
+
`+Q(["PATH","BYTES","SHA256","ROLE"],t.files.map(e=>[e.path,String(e.size),e.sha256,e.role]))}function $l(t){return Q(["ID","STUDY","INCLUDED","CONDITION","TYPE"],t.items.map(e=>[e.id,e.study,String(e.included),e.condition,e.sample_type]))+hn(t.next_cursor)}function Tl(t){return Q(["ID","STATUS","SEVERITY","WHAT","DECISION"],t.items.map(e=>[e.id,e.status,e.severity,e.what,e.lobster_decision??"-"]))+hn(t.next_cursor)}function Rl(t){return Q(["ID","ACTOR","DECISION","REASON"],t.items.map(e=>[e.id,e.actor,e.decision,e.reason]))+hn(t.next_cursor)}function hn(t){return t===null?"":`
|
|
55
|
+
Next cursor: ${t}`}var Mt="The destination must be a directory you own that other users cannot write to.",gm="The server could not complete the request. Try again later.";function me(t,e,r){let n=new w("",0,"");return n.kind=t,n.exitCode=e,n.publicMessage=r,n}var le=t=>me("usage",2,t),je=()=>me("server",1,gm),xr=()=>me("integrity",9,"Integrity check failed; the file was not saved."),_m=()=>me("interrupted",130,"Interrupted.");function Pl(){return _m()}function Nl(t,e){return{job_id:t,dest:Il(e),completed:[],failed:null,not_attempted:[]}}function ye(t){t.signal.throwIfAborted()}function _n(t){return t?.code}async function Fe(t){try{return await Ve.lstat(t)}catch(e){if(_n(e)==="ENOENT")return null;throw e}}function Xi(t,e){return t.dev===e.dev&&t.ino===e.ino}function yn(t,e,r){return!!t?.isDirectory()&&!t.isSymbolicLink()&&(r?t.uid===e&&(t.mode&18)===0:(t.uid===0||t.uid===e)&&((t.mode&18)===0||(t.mode&512)!==0))}async function ym(t,e){let r=Il(t),n=um(r).root,o=n;for(let i of["",...r.slice(n.length).split(cm).filter(Boolean)])if(i&&(o=Ut(o,i)),!yn(await Fe(o),e,o===r))throw le(Mt);if(await Ve.realpath(r)!==r)throw le(Mt)}async function bm(t){for(let[e,r]of t.temps){let n=await Fe(e);if(!n){t.temps.delete(e);continue}if(!n.isFile()||n.isSymbolicLink()||!Xi(r,n))throw je();await Ve.unlink(e),t.temps.delete(e)}await Ve.rmdir(t.staging)}function wm(t){if(!t||lm(t)||/[\\\u0000-\u001f\u007f-\u009f]/.test(t)||t.split("/").some(e=>!e||e==="."||e===".."||/^[A-Za-z]:/.test(e)))throw le("The folder contains an unsafe file path.")}async function gn(t,e,r,n,o){let i=e.split("/"),s=t;if(!yn(await Fe(t),o.uid,!0))throw le(Mt);for(let l of i.slice(0,-1)){s=Ut(s,l);let u=await Fe(s);if(!u&&n){try{await Ve.mkdir(s,{mode:448})}catch(c){if(_n(c)!=="EEXIST")throw c}u=await Fe(s)}if(u&&!yn(u,o.uid,!0))throw le(Mt)}let a=await Fe(Ut(t,e));if(a&&(!a.isFile()||a.isSymbolicLink()))throw le("The download target must be a regular file or absent.");if(a&&!r)throw le("A download target already exists; use --force to replace a regular file.")}function Ll(t){let e,r=()=>{e!==void 0&&clearTimeout(e),e=void 0},n=()=>{r(),e=setTimeout(()=>t.abort(je()),6e4)};return n(),{reset:n,stop:r}}async function Qi(t,e,r,n){ye(t);let o=Ll(t);try{let i=await n();return ye(t),i}catch(i){throw ye(t),i instanceof w&&i.kind==="usage"?i:y.classifyVaultError(e,i,r)}finally{o.stop()}}function vm(t,e,r){if(y.packageLinkMismatch(t,{job_id:r,path:e.path,sha256:e.sha256,size_bytes:e.size})!==null)throw xr();try{if(new URL(t.url).protocol!=="https:")throw new Error}catch{throw me("unreadable",1,"The server sent a response the CLI could not read.")}}async function Dl(t){if(t&&!t.locked)try{await t.cancel()}catch{}}async function Sm(t,e){ye(e);let r=e.signal;return new Promise((n,o)=>{let i=()=>o(r.reason);r.addEventListener("abort",i,{once:!0}),fetch(t,{redirect:"error",credentials:"omit",headers:{},signal:r}).then(s=>{r.removeEventListener("abort",i),r.aborted?(Dl(s.body),o(r.reason)):n(s)},()=>{r.removeEventListener("abort",i),o(r.aborted?r.reason:je())})})}async function km(t,e,r,n,o,i,s){let{controller:a}=n,l=n.archive?"R19":"R18";for(let u=0;u<2;u++){ye(a);let c=await Qi(a,l,e,()=>n.archive?y.getArchiveLink(t,e,{signal:a.signal}):y.getFileLink(t,e,r.path,{signal:a.signal}));vm(c,r,e);let d=Ut(o,r.path),p=Ut(i.staging,`.${am(d)}.part-${fm(4).toString("hex")}`),f=null,h,_,b,j,g=Ll(a);try{let m=await Sm(c.url,a);if(f=m.body,ye(a),m.status===403&&u===0)continue;if(m.status!==200||!f)throw je();let x=0,C=dm("sha256");h=pm.fromWeb(f);let A=new mm({transform(I,L,te){if(g.reset(),x+=I.byteLength,x>r.size){let ce=xr();a.abort(ce),te(ce);return}C.update(I),te(null,I)}});ye(a),_=jl.createWriteStream(p,{flags:"wx",mode:384});let D=_;b=await new Promise((I,L)=>{D.on("error",L),D.once("open",te=>{try{I(jl.fstatSync(te))}catch(ce){L(ce)}})}),i.temps.set(p,{dev:b.dev,ino:b.ino}),await hm(h,A,_,{signal:a.signal}),ye(a),g.stop();let v=C.digest("hex");if(x!==r.size||v!==r.sha256)throw xr();await gn(o,r.path,!0,!1,i),ye(a);let S=await Fe(p);if(!S?.isFile()||S.isSymbolicLink()||!Xi(b,S)||S.size!==x)throw xr();if(ye(a),n.force)await Ve.rename(p,d);else try{await Ve.link(p,d)}catch(I){throw _n(I)==="EEXIST"?le("The target appeared during download; it was not replaced."):je()}s({path:r.path,bytes:x,sha256:v});return}catch(m){throw j=m,m instanceof w&&m.kind==="integrity"?m:a.signal.aborted?a.signal.reason:m instanceof w&&m.kind?m:je()}finally{if(g.stop(),h?.destroy(),_?.destroy(),_&&!_.closed&&await new Promise(m=>_.once("close",m)),await Dl(f),b){let m=await Fe(p);if(!m)i.temps.delete(p);else if(m.isFile()&&!m.isSymbolicLink()&&Xi(b,m))try{await Ve.unlink(p),i.temps.delete(p)}catch(x){if(_n(x)==="ENOENT")i.temps.delete(p);else if(!j)throw je()}}}}throw je()}async function Ul(t,e,r,n){let{controller:o}=r;if(r.archive&&r.paths?.length)throw le("--archive and --path are mutually exclusive.");if(!/^[A-Za-z0-9_-]{1,128}$/.test(e))throw le("The ID must contain 1\u2013128 letters, numbers, underscores or hyphens.");if(typeof process.getuid!="function")throw le("run download is supported on macOS and Linux. On Windows, use WSL.");let i={uid:process.getuid(),staging:"",temps:new Map};try{await ym(n.dest,i.uid)}catch(a){throw a instanceof w?a:le(Mt)}let s;i.staging=await Ve.mkdtemp(Ut(n.dest,".lobster-download-")).catch(()=>{throw je()});try{let a=await Fe(i.staging);if(!yn(a,i.uid,!0))throw le(Mt);ye(o),await xm(t,e,r,n,i)}catch(a){throw s=a,a}finally{try{await bm(i)}catch{if(console.error(`Download temporary files could not be removed safely. Inspect ${i.staging} for manual cleanup.`),!s)throw je()}}}async function xm(t,e,r,n,o){let{controller:i}=r,s=await Qi(i,"R12",e,()=>y.getRun(t,e,{signal:i.signal}));if(!Dt(s.job))throw le("This is not a BioVault dataset run.");if(y.runCompatibility(s.job))throw y.classifyVaultError("R12",new U(`/vault/jobs/${e}`,200,"OK","run made by a newer server"),e);if(s.job.status==="failed"||s.job.status==="cancelled")throw me("not_now",5,`This run did not publish downloadable files. Inspect: omics-os biovault run problems ${e} and omics-os biovault run decisions ${e}`);if(s.job.status!=="completed")throw me("not_now",5,"This is not possible in the record's current state.");let a=await Qi(i,"R15",e,()=>y.getPackage(t,e,{signal:i.signal})),l;if(r.archive){if(!a.archive.available)throw me("unavailable",4,"No zip was built for this folder; download the files instead.");if(a.archive.size_bytes===null||a.archive.sha256===null)throw xr();l=[Object.freeze({path:"package.zip",size:a.archive.size_bytes,sha256:a.archive.sha256})]}else{let c=r.paths?.length?r.paths:a.files.map(p=>p.path),d=c.filter(p=>!a.files.some(f=>f.path===p));if(d.length)throw le(`Unknown folder paths: ${d.map(p=>JSON.stringify(p)).join(", ")}`);l=c.map(p=>{let f=a.files.find(h=>h.path===p);return Object.freeze({path:f.path,size:f.size,sha256:f.sha256})})}n.not_attempted=l.map(c=>c.path);let u=new Set;for(let c of l){wm(c.path);let d=c.path.toLowerCase();if(u.has(d))throw le("The folder selection contains duplicate paths after case-folding.");u.add(d)}try{for(let c of l)await gn(n.dest,c.path,!!r.force,!1,o);for(let c of l)await gn(n.dest,c.path,!!r.force,!0,o);for(let c of l)await gn(n.dest,c.path,!!r.force,!1,o)}catch(c){throw c instanceof w?c:le("A download target could not be prepared safely.")}for(let c=0;c<l.length;c++){let d=l[c];n.failed=d.path,n.not_attempted=l.slice(c+1).map(p=>p.path),ye(i),r.progress?.(d.path),await km(t,e,d,r,n.dest,o,p=>n.completed.push(p)),n.failed=null,ye(i)}}var Pm=2*1024*1024*1024-1;function G(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KiB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MiB`:`${(t/(1024*1024*1024)).toFixed(1)} GiB`}function Vl(t){let e=t.command("files").description("Manage session files");e.command("list").description("List files in a session").argument("<session-id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>yr(o,r),n.json);if(n.json){$(i);return}if(i.length===0){console.log("No files in this session.");return}let s=i.map(a=>[a.name,G(a.size_bytes),a.created_at]);console.log(Q(["NAME","SIZE","UPLOADED"],s))}),e.command("upload").description("Upload a file to a session").argument("<session-id>","Session ID").argument("<path>","Local file path").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o),s=Fl(n),a=Zi(s),l=await Ml(s).catch(()=>{});l&&l.size>Pm&&await q(()=>Promise.reject(me("usage",2,`${a} is ${G(l.size)}; session uploads take files up to 2 GiB. Send large files to a project instead: omics-os upload <path> --project <project-id>`)),o.json),o.json||process.stdout.write(`Uploading ${a}...`);let u=await Am(s),c=await q(()=>bi(i,r,u,a),o.json);o.json?$(c):(process.stdout.write(` done (${G(c.file_size)})
|
|
56
|
+
`),console.log(`Path: ${c.file_path}`))}),e.command("download").description("Download a file from a session").argument("<session-id>","Session ID").argument("<key>","File path/key").argument("[dest]","Destination path").action(async(r,n,o)=>{let i=O(t);W(r,i.json);let s=R(i),a=o??Zi(n);i.json||process.stdout.write(`Downloading ${n}...`);let{body:l,size:u}=await q(()=>ki(s,r,n),i.json),c=Fl(a),d=Rm(Tm(c),`.${Zi(c)}.${Em(4).toString("hex")}.part`),p=()=>{try{qm(d)}catch{}process.exit(130)};process.on("SIGINT",p);let f;try{if(await Im(jm.fromWeb(l),Cm(d)),f=(await Ml(d)).size,u!==null&&f!==u)throw new Error(`received ${f} bytes, expected ${u}; not saved`);await Om(d,c)}catch(h){await $m(d).catch(()=>{}),i.json||process.stdout.write(` failed
|
|
57
|
+
`),await q(()=>Promise.reject(h),i.json);return}finally{process.off("SIGINT",p)}i.json?$({success:!0,path:c,size:f}):(process.stdout.write(` done (${G(f)})
|
|
58
|
+
`),console.log(`Saved: ${c}`))}),e.command("delete").description("Delete a file from a session").argument("<session-id>","Session ID").argument("<key>","File path/key").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o);await q(()=>vi(i,r,n),o.json),o.json?$({success:!0,key:n}):console.log(`Deleted: ${n}`)}),e.command("load").description("Load a file into session context").argument("<session-id>","Session ID").argument("<path>","File path in session workspace").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o),s=await q(()=>Si(i,r,n),o.json);o.json?$(s):console.log(s.message||"File loaded into session.")})}function Bl(t){if(t===null||typeof t!="object")return{};let e=t.session;return e!==null&&typeof e=="object"?e:t}function ke(t){return t.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").trim()}var ft=t=>t!==null&&typeof t=="object"?t:{};function Nm(t){let e=t.content??t.content_blocks;return typeof e=="string"?ke(e):Array.isArray(e)?ke(e.map(r=>typeof ft(r).text=="string"?ft(r).text:"").join(" ")):""}var zl=t=>typeof t=="boolean"?t?"yes":"no":"-",Hl={raw_type:{kind:"raw sequencing ",count:"not copied",file:"raw sequencing file"},too_large:{count:"larger than a session copy allows",file:"too large to copy"},session_limit:{count:"past the session's storage limit",file:"past the session's storage limit"},copy_failed:{count:"whose copy failed",file:"copy failed"}},es=10;function Lm(t){let e=t.filter(o=>o.reason!=="listing_failed"),r=new Map;for(let o of e)(r.get(o.reason)??r.set(o.reason,[]).get(o.reason)).push(o);let n=[...r].map(([o,i])=>{let s=Hl[o],a=`${i.length.toLocaleString("en-US")} ${s?.kind??""}${i.length===1?"file":"files"}`;if(!s)return` ${a}: ${ke(o)}`;let l=o==="raw_type"?new Set(i.map(u=>/(\.[^./]+(\.gz)?)$/i.exec(u.relative_path)?.[1]?.toLowerCase()).filter(Boolean)):new Set;return` ${a} ${s.count}${l.size?` (${[...l].join(", ")})`:""}`});return[_r(t),...n,...e.slice(0,es).map(o=>` ${ke(o.relative_path)} ${o.size_bytes===null?"size unknown":G(o.size_bytes)} ${Hl[o.reason]?.file??ke(o.reason)}`),...e.length>es?[` \u2026 and ${(e.length-es).toLocaleString("en-US")} more (see --json)`]:[]]}function Jl(t){let e=t.command("session").description("Manage cloud sessions");e.command("list").description("List sessions").action(async()=>{let r=O(t),n=R(r),o=await q(()=>on(n),r.json);if(r.json){$(o);return}if(o.length===0){console.log("No sessions found.");return}let i=o.map(s=>[s.session_id.slice(0,8),s.name??"(untitled)",s.status??"active",s.last_activity??s.created_at]);console.log(Q(["ID","TITLE","STATUS","LAST ACTIVITY"],i))}),e.command("info").description("Show session details").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>hi(o,r),n.json);if(n.json){$(i);return}let s=Bl(i),a=(l,u="-")=>l==null||l===""?u:String(l);console.log(ie([["Session ID",a(s.session_id,r)],["Name",a(s.name,"(untitled)")],["Status",a(s.status)],["Created",a(s.created_at)],["Last Activity",a(s.last_activity)],["Messages",a(s.message_count)],["Source",a(s.client_source)]]))}),e.command("archive").description("Archive a session").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n);await q(()=>fi(o,r),n.json),n.json?$({success:!0,session_id:r}):console.log(`Session ${r.slice(0,8)} archived.`)}),e.command("delete").description("Delete a session permanently").argument("<id>","Session ID").option("--force","Skip confirmation").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o);if(!n.force&&!o.json){let a=(await import("readline")).createInterface({input:process.stdin,output:process.stdout}),l=await new Promise(u=>{a.question(`Delete session ${r.slice(0,8)}? This cannot be undone. [y/N] `,u)});if(a.close(),l.toLowerCase()!=="y"){console.log("Cancelled.");return}}await q(()=>pi(i,r),o.json),o.json?$({success:!0,session_id:r}):console.log(`Session ${r.slice(0,8)} deleted.`)}),e.command("create").description("Start a new session; with --project, an organisation project's files are copied into it").option("--project <id>","Project to open the session in").option("--name <name>","Session name").action(async r=>{let n=O(t),o=R(n),i=[],{project:s,id:a}=await q(async()=>{let u=r.project===void 0?void 0:await hr(o,r.project),c=await nn(o,d=>{i=d},{name:r.name,project:u});return{project:u,id:c}},n.json);if(n.json){$({session_id:a,...s?{project_id:s.project_id}:{},...i.length?{seed_warnings:i}:{}});return}let l=s?` in project ${ke(s.name)} (${s.org_id?"organisation":"personal"} project)`:"";if(console.log(`Session ${a} created${l}.`),i.length)for(let u of Lm(i))console.log(u);s&&console.log("Files uploaded to the project after this are not in this session; start a new session after uploading."),console.log(`Ask: omics-os lobster query -s ${a} "<question>"`)}),e.command("share").description("Share a session").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>mi(o,r),n.json);n.json?$(i):console.log(`Share URL: ${i.share_url}`)}),e.command("cancel").description("Cancel a running session").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>Pt(o,r),n.json),s=i!==null&&typeof i=="object"?i:{},a=s.success===!0,l=typeof s.message=="string"?ke(s.message):"";n.json?$(i):a?console.log(`Session ${r.slice(0,8)}: ${l||"cancellation accepted"}`):console.error(`Session ${r.slice(0,8)} was not cancelled: ${l||"the server did not confirm the cancellation"}`),a||process.exit(1)}),e.command("messages").description("Show the conversation of a session (Cloud only)").argument("<id>","Session ID").option("--limit <n>","Show only the last n messages (applied by the CLI; the server has no limit)").action(async(r,n)=>{let o=O(t);W(r,o.json);let i;n.limit!==void 0&&(i=/^[1-9]\d*$/.test(n.limit)?Number(n.limit):void 0,i===void 0&&Sr(`Invalid --limit "${ke(n.limit).slice(0,40)}": expected a positive integer.`,o.json));let s=R(o),a=await q(()=>E(s,`/sessions/${encodeURIComponent(r)}/messages`),o.json),l=ft(a),u=Array.isArray(l.messages)?l.messages:[],c=i===void 0?u:u.slice(-i);if(o.json){$(i===void 0?a:{...l,messages:c});return}if(c.length===0){console.log("No messages.");return}c.length<u.length&&console.log(`Showing the last ${c.length} of ${u.length} messages.
|
|
59
|
+
`),console.log(c.map(d=>`${ke(String(ft(d).role??"unknown"))}: ${Nm(ft(d))}`).join(`
|
|
60
|
+
|
|
61
|
+
`))}),e.command("provenance").description("Show the provenance summary of a session (Cloud only)").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>E(o,`/sessions/${encodeURIComponent(r)}/provenance/summary`),n.json);if(n.json){$(i);return}let s=ft(i);if(s.summary===null||typeof s.summary!="object"){console.log(typeof s.message=="string"?ke(s.message):"No provenance summary available.");return}let a=ft(s.summary),l=u=>Array.isArray(u)&&u.length>0?u.map(c=>ke(String(c))).join(", "):"-";console.log(ie([["Activities",typeof a.activity_count=="number"?String(a.activity_count):"-"],["Tools used",l(a.tools_used)],["Agents used",l(a.agents_used)],["Has IR",zl(a.has_ir)],["Can export notebook",zl(a.can_export_notebook)]]))}),e.command("unarchive").description("Return an archived session to the active list (Cloud only)").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>E(o,`/sessions/${encodeURIComponent(r)}/unarchive`,{method:"POST"}),n.json);n.json?$(i):console.log(`Session ${r.slice(0,8)} unarchived.`)}),e.command("extend").description("Reset the inactivity timeout of a session (Cloud only)").argument("<id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>E(o,`/sessions/${encodeURIComponent(r)}/extend`,{method:"POST"}),n.json);if(n.json)$(i);else{let s=Bl(i).last_activity;console.log(`Session ${r.slice(0,8)} extended${typeof s=="string"?` (last activity ${ke(s)})`:""}.`)}})}import{randomBytes as Mm}from"node:crypto";import{constants as Fm,unlinkSync as Vm}from"node:fs";import{copyFile as Bm,link as zm,lstat as Qe,mkdir as ou,open as Hm,realpath as Jm,unlink as iu}from"node:fs/promises";import{basename as Wm,dirname as Gm,isAbsolute as Km,join as Cr,resolve as Xl,sep as Ym}from"node:path";import{Readable as Xm}from"node:stream";import{pipeline as Qm}from"node:stream/promises";var Dm=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Um=new Set(["omics-os","omicsos","omics-os.com","app","default","platform","cloud"]);function Wl(t){return t.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"").replace(/\.omics-os\.com$/,"").replace(/_/g,"-")}function bn(t){return Um.has(Wl(t))}function ts(t){let e=Wl(t);if(!Dm.test(e))throw new Error(`Invalid tenant slug '${e}'. Must be a lowercase DNS label (a-z, 0-9, hyphens, no leading/trailing hyphen).`);return e}function Gl(t){return(t instanceof Error?t.message:String(t)).includes("invalid_tenant")}function Kl(t){return[`Tenant '${t}' does not exist, or is not active.`,"","The main Omics-OS platform is not a tenant \u2014 log in with no --tenant:"," omics-os login","","Tenants you already hold credentials for:"," omics-os profiles list"].join(`
|
|
62
|
+
`)}function Yl(t){try{let{protocol:e,hostname:r}=new URL(t),n=/^([a-z0-9-]+)\.omics-os\.com$/.exec(r)?.[1];return e==="https:"&&n&&n!=="stream"&&!bn(n)?n:void 0}catch{return}}var rs=20,pt=50;function Ie(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function mt(t){return Array.isArray(t)?t.map(Ie):[]}var su=/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g;function F(t,e="-"){return t==null||t===""?e:String(t).replace(su,"").replace(/[\u0000-\u001f\u007f-\u009f]/g," ").trim()||e}var wn=t=>typeof t=="number"?G(t):"size unknown",vn=(t,e)=>`${t} ${t===1?e:`${e}s`}`;function ns(t){let e=t.filter(n=>typeof n=="number");if(t.length&&!e.length)return"size unknown";let r=G(e.reduce((n,o)=>n+o,0));return e.length<t.length?`at least ${r}`:r}var Zm=/\.(h5ad|h5|h5mu|loom|mtx|fastq|fq|bam|sam|cram|vcf|bcf|parquet|zarr|rds|rda|rdata|npz|npy|pkl|feather|arrow|tar|tgz|zip)$/i,eh=/\.(gz|bgz|bz2|xz|zst)$/i,th=50*1024*1024;function au(t,e){let r=t.split("/");return Zm.test(r[r.length-1].replace(eh,""))||r.slice(0,-1).some(n=>/\.zarr$/i.test(n))||typeof e=="number"&&e>th}var os=(t,e)=>au(String(t??""),e)?"data":"light";function Be(t,e){return Object.fromEntries(e.filter(r=>r in t).map(r=>[r,t[r]]))}var Ql=["project_id","name","description","metadata","status","org_id","created_at","updated_at"],rh=["session_id","name","title","status","created_at","updated_at","last_activity","project_id","org_project_id","message_count"],nh=["dataset_id","project_id","name","description","status","created_at","updated_at"],oh=["name","size","type","created_at"],ih=["filename","size_bytes","last_modified"];async function Zl(t,e){let r=`/projects/${encodeURIComponent(e)}`,n=Ie(await E(t,r)),o=Ie(n.project),i=typeof o.project_id=="string"?o.project_id:e,s=mt(Ie(await E(t,`${r}/datasets`)).datasets).map(u=>({...Be(u,nh),files:mt(u.files).map(c=>({...Be(c,oh),kind:os(c.name,c.size)}))})),a=mt(Ie(await E(t,"/sessions?status=all")).sessions).filter(u=>u.project_id===i||u.org_project_id===i).map(u=>Be(u,rh)),l=o.org_id?(await sh(t,i)).map(u=>({...Be(u,ih),kind:os(u.filename,u.size_bytes)})):void 0;return{reply:n,project:o,projectId:i,datasets:s,sessions:a,data:l}}async function sh(t,e){let r=`/org/projects/${encodeURIComponent(e)}/data`,n=[],o=new Set;for(let i;;){let s=Ie(await E(t,i===void 0?r:`${r}?cursor=${encodeURIComponent(i)}`));n.push(...mt(s.files));let a=s.next_cursor;if(a==null)return n;if(typeof a!="string"||!a||o.has(a))throw Object.assign(new U(r,200),{publicMessage:"The project file list repeated a page; stopped. Try again later."});o.add(a),i=a}}function lu(t){return t.datasets.flatMap(e=>mt(e.files).map(r=>({dataset:String(e.name??""),name:String(r.name??""),size_bytes:typeof r.size=="number"?r.size:null})))}var uu=t=>`${t} dataset file${t===1?" is":"s are"} listed but cannot be downloaded from Omics-OS Cloud yet.`;function ah(t){let e=[],r=0,n=0,o=(s,a,l)=>{if(r>=pt){n++;return}r++,e.push(`${l}${F(s)} ${wn(a)} ${os(s,a)}`)},i=lu(t);if(t.datasets.length){e.push("",`Datasets: ${t.datasets.length} (${vn(i.length,"file")}, ${ns(i.map(s=>s.size_bytes))})`);for(let s of t.datasets){let a=mt(s.files);e.push(` ${F(s.name,"(untitled)")} ${a.length} file${a.length===1?"":"s"}`);for(let l of a)o(l.name,l.size," ")}i.length&&e.push(` ${uu(i.length)}`)}else e.push("","Datasets: none");if(t.data){e.push("",`Project files: ${t.data.length}`);for(let s of t.data)o(s.filename,s.size_bytes," ")}if(n&&e.push(` \u2026 and ${n} more files`),t.sessions.length){let s=[...t.sessions].sort((a,l)=>String(l.last_activity??"").localeCompare(String(a.last_activity??"")));e.push("",`Sessions: ${s.length}`),e.push(Q(["ID","NAME","STATUS","MESSAGES","LAST ACTIVITY"],s.slice(0,rs).map(a=>[F(a.session_id),F(a.name,"(untitled)"),F(a.status),F(a.message_count,"0"),F(a.last_activity??a.created_at)]))),s.length>rs&&e.push(`\u2026 and ${s.length-rs} more sessions`)}else e.push("","Sessions: none");return e.push("",`Download: omics-os lobster projects download ${t.projectId} [folder]`),e}function Ft(t,e,r,n){return q(()=>Promise.reject(me(e,r,n)),t)}var is=".lobster_workspace";async function lh(t){let e=t,r=[];for(;;){try{e=await Jm(e);break}catch{}let n=Gm(e);if(n===e)break;r.unshift(Wm(e)),e=n}return[...e.split(Ym),...r].includes(is)}async function eu(t,e){if(await lh(t))return Ft(e,"usage",2,`${t} is inside a ${is} folder, which holds Lobster's own files. Download into another folder.`);let r;try{r=await Qe(t)}catch{return}if(r.isSymbolicLink())return Ft(e,"usage",2,`${t} is a symbolic link. Download into a plain folder.`);if(!r.isDirectory())return Ft(e,"usage",2,`${t} exists and is not a folder.`);if(await Qe(Cr(t,".lobster_workspace","project.json")).then(()=>!0,()=>!1))return Ft(e,"usage",2,`${t} is a Lobster project (it has .lobster_workspace/project.json). Download into another folder.`)}function uh(t,e=process.platform){return t==="ENAMETOOLONG"||t==="EINVAL"||t==="ENOENT"&&e==="win32"}function ch(t,e){let r="";for(let n of t){if(Buffer.byteLength(r+n)>e)break;r+=n}return r}function dh(t,e){let r=o=>o.replace(/^[.\s-]+|[.\s-]+$/g,""),n=o=>r(ch(r(o.replace(su,"").replace(/[/\\:*?"<>|\u0000-\u001f\u007f-\u009f]+/g,"-")),200));return n(String(t??""))||`unnamed-${n(e).slice(0,8)||"project"}`}function Er(t){if(!t||Km(t)||/[\\\u0000-\u001f\u007f-\u009f]/.test(t))return;let e=t.split("/");return e.some(r=>!r||r==="."||r===".."||r===is||/^[A-Za-z]:/.test(r))?void 0:e}var Vt=class extends Error{constructor(r,n){super(n);this.reason=r}reason},cu=(t,e)=>t.ino!==0?`${t.dev}:${t.ino}`:`path:${e.toLowerCase()}`,fh=new Set(["ENOTSUP","EPERM","EXDEV","ENOSYS","EINVAL"]);async function ph(t,e){try{return await zm(t,e),!0}catch(r){let n=r.code??"";if(n==="EEXIST")return!1;if(!fh.has(n))throw r}try{return await Bm(t,e,Fm.COPYFILE_EXCL),!0}catch(r){if(r.code==="EEXIST")return!1;throw await iu(e).catch(()=>{}),r}}async function tu(t,e,r,n){let o=await Qe(t),i=n.written.get(cu(o,e));if(i===void 0)return{skipped:typeof r=="number"&&o.size!==r?"size_differs":"exists"};throw new Vt("name_collision",i===e?"listed twice; the second copy was not downloaded":`same name as ${i} on this disk (names differ only in case); not downloaded`)}async function ru(t,e,r){let n=await Qe(Cr(t,...e)).catch(()=>{});if(n)return typeof r=="number"&&n.size!==r?"size_differs":"exists"}async function mh(t,e,r,n,o,i){let s=e.join("/"),a=t;for(let d of e.slice(0,-1)){a=Cr(a,d),await ou(a).catch(f=>{if(f.code!=="EEXIST")throw f});let p=await Qe(a);if(!p.isDirectory()||p.isSymbolicLink())throw new Vt("unsafe_path","a folder on the way is not a plain folder; not followed")}let l=Cr(a,e[e.length-1]);if(await Qe(l).then(()=>!0,()=>!1))return tu(l,s,r,o);let u=Cr(a,`.omics-os-partial-${Mm(8).toString("hex")}`);i();let c=await Hm(u,"wx");o.temp=u;try{await Qm(Xm.fromWeb(await n()),c.createWriteStream());let d=(await Qe(u)).size;if(typeof r=="number"&&d!==r)throw new Vt("size_mismatch",`received ${d} bytes, the listing says ${r}; not saved; the session may still be running; run the download again later`);return await ph(u,l)?(o.written.set(cu(await Qe(l),s),s),d):tu(l,s,r,o)}finally{o.temp=void 0,await c.close().catch(()=>{}),await iu(u).catch(()=>{})}}var hh=t=>t instanceof Error&&!("kind"in t)?t.message:De(t).payload.error,nu=(t,e,r)=>({path:t,reason:e instanceof Vt?e.reason:r,error:hh(e)});function du(t,e={}){let r=t.command("projects").description("Browse your projects and download their files");e.list!==void 0&&r.command("list").description(e.list).action(async()=>{let n=O(t),o=R(n),i=await q(()=>E(o,"/projects"),n.json);if(n.json){let l=Ie(i);$({...Be(l,["success","message"]),projects:mt(l.projects).map(u=>Be(u,Ql)),...Be(l,["total"])});return}let s=Ie(i).projects;if(!Array.isArray(s)||s.length===0){console.log("No projects found.");return}let a=s.map(l=>{let u=Ie(l);return[F(u.project_id),F(u.name,"(untitled)"),F(u.status),F(u.updated_at??u.created_at)]});console.log(Q(["ID","NAME","STATUS","UPDATED"],a))}),e.info!==void 0&&r.command("info").description(e.info).argument("<project-id>","Project ID").action(async n=>{let o=O(t),i=R(o),s=await q(()=>Zl(i,n),o.json);if(o.json){$({...Be(s.reply,["success","message"]),project:Be(s.project,Ql),datasets:s.datasets,sessions:s.sessions,...s.data?{data:s.data}:{}});return}let a=s.project,l=Ie(a.metadata);console.log(ie([["Project ID",F(a.project_id,n)],["Name",F(a.name,"(untitled)")],["Description",F(a.description)],["Status",F(a.status)],["Domain",F(l.domain)],["Organism",F(l.organism)],["Tags",Array.isArray(l.tags)&&l.tags.length?l.tags.map(u=>F(u)).join(", "):"-"],["Created",F(a.created_at)],["Updated",F(a.updated_at)]])),console.log(ah(s).join(`
|
|
63
|
+
`))}),r.command("create").description("Create a project: in your organisation when logged in with --tenant, otherwise a personal project").argument("<name>","Project name").option("--description <text>","Project description").action(async(n,o)=>{let i=O(t),s=R(i),a=await q(()=>li(s,{name:n,...o.description===void 0?{}:{description:o.description}}),i.json);if(i.json){$({project_id:a.project_id,name:a.name,org_id:a.org_id??null});return}let l=a.org_id?`in organisation ${F(Yl(s.apiUrl)??a.org_id)}`:"as a personal project";if(console.log(`Project ${F(a.name)} (${F(a.project_id)}) created ${l}.`),a.org_id){console.log(`Upload into it: omics-os upload <paths> --project ${F(a.project_id)}`);return}console.log("Uploads go to organisation projects; omics-os upload cannot send files to a personal project."),Y(i.profile)?.org_id&&console.log("To create projects in your organisation, log in with: omics-os login --tenant <organisation>")}),r.command("download").description("Download a project's session files (one-way copy; files already there are skipped)").argument("<project-id>","Project ID").argument("[folder]","Folder to download into (default: ./<project name>)").option("--session <session-id>","Only this session of the project").option("--data","Also download data files (the formats above, and any file over 50 MiB)").option("--dry-run","Show what would be downloaded, held and skipped; write nothing").action(async(n,o,i)=>{let s=O(t),a=R(s);o&&await eu(Xl(o),s.json);let l=await q(()=>Zl(a,n),s.json),{projectId:u}=l,c=Xl(o??dh(l.project.name,u));o||await eu(c,s.json);let d=l.sessions;i.session&&(d=d.filter(v=>v.session_id===i.session),d.length||await Ft(s.json,"not_found",1,`Session ${F(i.session)} is not one of your sessions in this project.`));let p=[],f=[];for(let v of d){let S=String(v.session_id??""),I=`sessions/${S}/`;if(!Er(S)||S.includes("/")){f.push({path:F(I),reason:"unsafe_path",error:"unsafe path from the server; skipped"});continue}try{for(let L of await yr(a,S))p.push({path:I+L.path,parts:Er(L.path)&&["sessions",S,...Er(L.path)],bytes:L.size_bytes,body:()=>wi(a,S,L.path)})}catch(L){f.push(nu(I,L,"list_failed"))}}if(!i.session)for(let v of l.data??[]){let S=String(v.filename??""),I=typeof v.size_bytes=="number"&&v.size_bytes>si?ai:ii;p.push({path:`data/${S}`,parts:Er(S)&&["data",...Er(S)],bytes:v.size_bytes,body:()=>I(a,u,S)})}let h=i.session?[]:lu(l),_=[],b=[],j=[];for(let v of p){if(!v.parts){f.push({path:F(v.path),reason:"unsafe_path",error:"unsafe path from the server; skipped"});continue}let S=v.parts.join("/");if(i.data||!au(S,v.bytes)){j.push({...v,parts:v.parts});continue}let I=await ru(c,v.parts,v.bytes);I?_.push({path:S,reason:I}):b.push({path:S,reason:"data_file",size:typeof v.bytes=="number"?v.bytes:null})}let g=(v=!1)=>{let S=[];_.length&&!v&&S.push(`${_.length} skipped: already in the folder (never overwritten)`);let I=_.filter(L=>L.reason==="size_differs");return I.length&&S.push(`${vn(I.length,"skipped file")} ${I.length===1?"differs":"differ"} in size from the Cloud copy (not overwritten): ${I.map(L=>F(L.path)).join(", ")}`),f.length&&S.push(`Failed (${f.length}):`,...f.map(L=>` ${L.path}: ${F(L.error)}`)),b.length&&S.push(`${vn(b.length,"data file")} not downloaded (${ns(b.map(L=>L.size))}); add --data to get them`,...b.slice(0,pt).map(L=>` ${F(L.path)} ${wn(L.size)}`),...b.length>pt?[` \u2026 and ${b.length-pt} more`]:[]),h.length&&S.push(uu(h.length)),S};if(i.dryRun){let v=[];for(let S of j){let I=S.parts.join("/"),L=await ru(c,S.parts,S.bytes);L?_.push({path:I,reason:L}):v.push({path:I,size_bytes:typeof S.bytes=="number"?S.bytes:null})}s.json?$({project_id:u,folder:c,dry_run:!0,downloaded:v,skipped:_,failed:f,held:b,not_downloadable:h}):console.log(["Dry run: nothing was written.",`Would download ${vn(v.length,"file")} (${ns(v.map(S=>S.size_bytes))}) to ${c}`,...v.slice(0,pt).map(S=>` ${F(S.path)} ${wn(S.size_bytes)}`),...v.length>pt?[` \u2026 and ${v.length-pt} more`]:[],...g()].join(`
|
|
64
|
+
`)),f.length&&process.exit(1);return}if(!j.length){if(s.json)$({project_id:u,folder:null,downloaded:[],skipped:_,failed:f,held:b,not_downloadable:h});else{let v=b.length?"Nothing to download without --data.":_.length?"Nothing new to download.":f.length?"Nothing downloaded.":"Nothing to download: no session files in this project.";console.log([v,...g()].join(`
|
|
65
|
+
`))}f.length&&process.exit(1);return}try{await ou(c,{recursive:!0})}catch(v){let S=v.code;throw uh(S)&&await Ft(s.json,"usage",2,`${c}: the folder name is too long or not allowed on this disk.`),v}let m=[],x={written:new Map},C=v=>{if(x.temp)try{Vm(x.temp)}catch{}process.exit(v)},A=()=>C(130),D=()=>C(143);process.on("SIGINT",A),process.on("SIGTERM",D);try{for(let[v,S]of j.entries()){let I=N=>process.stderr.write(`[${v+1}/${j.length}] ${F(S.path)} ${N}
|
|
66
|
+
`),L=!1,te=()=>{L=!0,I(typeof S.bytes=="number"?wn(S.bytes):"size unknown")},ce=S.parts.join("/");try{let N=await mh(c,S.parts,S.bytes,S.body,x,te);typeof N=="number"?m.push({path:ce,size_bytes:N}):(_.push({path:ce,reason:N.skipped}),I(N.skipped==="size_differs"?"skipped: already there, size differs from the Cloud copy":"skipped: already there"))}catch(N){f.push(nu(ce,N,"download_failed")),L||I("failed")}}}finally{process.off("SIGINT",A),process.off("SIGTERM",D)}if(s.json)$({project_id:u,folder:c,downloaded:m,skipped:_,failed:f,held:b,not_downloadable:h});else{let v=m.reduce((I,L)=>I+L.size_bytes,0),S=[`${m.length} downloaded${m.length?` (${G(v)})`:""}`,..._.length?[`${_.length} skipped (already there)`]:[],...f.length?[`${f.length} failed`]:[],...b.length?[`${b.length} held (data files)`]:[]];console.log([`${S.join(", ")} in ${c}`,...g(!0)].join(`
|
|
67
|
+
`))}f.length&&process.exit(1)})}import{writeFile as gh}from"fs/promises";import{resolve as _h,basename as yh}from"path";var fu=["report","pipeline","slidedeck"];function pu(t){t.command("export").description("Export a session (report, pipeline, slidedeck)").argument("<session-id>","Session ID").requiredOption("--type <type>","Export type: report, pipeline, slidedeck").action(async(e,r)=>{let n=O(t);W(e,n.json);let o=fu.find(d=>d===r.type);o||Sr(`Unknown export type "${r.type.slice(0,40)}". Allowed: ${fu.join(", ")}.`,n.json);let i=R(n),s=await q(()=>ji(i,e,{exportType:o}),n.json);n.json||process.stdout.write(`Exporting (${o})...`);let a=await q(()=>Pi(i,e,s.job_id,{pollIntervalMs:2e3}),n.json);a.status==="failed"&&(n.json?$({error:a.error??"Export failed",job_id:s.job_id}):console.error(`
|
|
68
|
+
Export failed: ${a.error??"unknown error"}`),process.exit(1));let l=a.result?.files??{},u=Object.values(l).filter(Boolean);if(u.length===0){n.json?$({success:!0,job_id:s.job_id,files:[]}):(process.stdout.write(` done
|
|
69
|
+
`),console.log("Export complete (no downloadable files)."));return}let c=[];for(let d of u){let p=await q(()=>Ii(i,e,d),n.json),f=[],h=p.getReader();for(;;){let{done:b,value:j}=await h.read();if(b)break;f.push(j)}let _=_h(yh(d));await gh(_,Buffer.concat(f)),c.push(_)}if(n.json)$({success:!0,job_id:s.job_id,files:c});else{process.stdout.write(` done
|
|
70
|
+
`);for(let d of c)console.log(`Saved: ${d}`)}})}function mu(t,e={}){let r=t.command("agents").description("Browse and manage agents");e.list!==void 0&&r.command("list").description(e.list).action(async()=>{let n=O(t),o=R(n),i=await q(()=>_i(o,{limit:100}),n.json);if(n.json){$(i);return}let s=i.packages??[];if(s.length===0){console.log("No agents found.");return}let a=s.map(l=>[l.package_name,l.version,(l.categories??[]).join(", ")||"-",l.description?.slice(0,40)||"-"]);console.log(Q(["NAME","VERSION","CATEGORY","DESCRIPTION"],a)),typeof i.total=="number"&&i.total>s.length&&console.log(`
|
|
71
|
+
Showing ${s.length} of ${i.total} agents.`)}),e.info!==void 0&&r.command("info").description(e.info).argument("<name>","Agent name").option("--version <version>","Agent version","latest").action(async(n,o)=>{let i=O(t),s=R(i),a=await q(()=>sn(s,n,o.version),i.json);if(a||(i.json?$({error:"Agent not found",name:n}):console.error(`Agent "${n}" not found.`),process.exit(1)),i.json){$(a);return}console.log(ie([["Name",a.package_name],["Title",a.display_name||"-"],["Version",a.version],["Categories",(a.categories??[]).join(", ")||"-"],["Author",a.author||"-"],["Description",a.description||"-"],["Agents",(a.agent_names??[]).join(", ")||"-"],["Tools",(a.tools??[]).join(", ")||"-"],["Created",a.created_at??"-"]]))}),r.command("push").description("Not available: agent packages are curated in Omics-OS Cloud").argument("<path>","Path to agent bundle").action(async()=>{let n=O(t),o="Publishing agents from the CLI is not available. Agent packages are curated in Omics-OS Cloud.";n.json?$({error:o,kind:"unsupported",status:null,code:null,retryable:null,request_id:null}):console.error(o),process.exit(1)}),r.command("download").description("Download an agent bundle").argument("<name>","Agent name").option("--version <version>","Agent version","latest").action(async(n,o)=>{let i=O(t),s=R(i),a=await q(()=>yi(s,n,o.version),i.json);i.json?$(a):console.log(`Download URL: ${a.download_url}`)})}var gu="BioVault runs are not enabled for your account or organisation.";function P(t,e,r){let n=new w("",0,"");return n.kind=t,n.publicMessage=e,n.exitCode=r,n}function K(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t))throw P("usage","The ID must contain 1\u2013128 letters, numbers, underscores or hyphens.",2)}async function ue(t,e,r){try{return await e()}catch(n){if((t==="R7"||t==="R8")&&n instanceof w&&n.status===403){let o=y.classifyVaultError(t,n,r);throw o.publicMessage=gu,o.exitCode=6,o}throw y.classifyVaultError(t,n,r)}}function Sn(t){if(t.limit!==void 0&&(!/^\d+$/.test(t.limit)||Number(t.limit)<1||Number(t.limit)>100))throw P("usage","--limit must be an integer from 1 to 100.",2);return{...t.limit!==void 0?{limit:Number(t.limit)}:{},...t.cursor!==void 0?{cursor:t.cursor}:{}}}function kn(t){return t.option("--limit <n>","Page size (integer 1\u2013100)").option("--cursor <cursor>","Opaque pagination cursor")}function _u({cloud:t,vault:e,draft:r,run:n}){let o=async(i,s,a=!1)=>{let l=O(t),u=await q(()=>i(R(l)),l.json);l.json||a?$(u):console.log(s(u))};e.command("features").description("Check BioVault run availability").action(async()=>{await o(async i=>{let s=await ue("R1",()=>y.features(i));if(!s.biovault_run_config)throw P("blocked",gu,6);return s},()=>"BioVault runs are enabled.")}),r.command("list").description("List your BioVault drafts").action(async()=>{await o(i=>ue("R7",()=>y.listEntries(i)),Cl)}),r.command("show").description("Review a checked draft snapshot").argument("<entry>","Entry ID").option("--config","Show configuration").option("--prompt","Show raw prompt").option("--checks","Show checks").option("--execute-command","Print a ready 7-field ExecuteCommand JSON").action(async(i,s)=>{let a=O(t),l=await q(async()=>{if(K(i),[s.config,s.prompt,s.checks,s.executeCommand].filter(Boolean).length>1)throw P("usage","Choose only one of --config, --prompt, --checks or --execute-command.",2);let u=R(a),c=await ue("R3",()=>y.getDraft(u,i),i),d=await ue("R8",()=>y.getEntry(u,i),i),p=y.snapshotNonconformity(c,d.entry);if(p?.startsWith("mismatch:"))throw P("stale","The draft changed while it was being read. Try again.",5);if(p)throw y.classifyVaultError("R8",new U(`/vault/entries/${i}`,200,"OK",p),i);let f=await y.executeReadiness(c);if(s.executeCommand&&!f.ok)throw P("blocked",`The draft is not ready to start: ${kr(f.reason)}.`,6);return{preview:c,selection:d.entry.work_plan.model_selection,readiness:f}},a.json);s.executeCommand&&l.readiness.ok?$(l.readiness.command):a.json?$(l.preview):s.config?$(l.preview.config):s.prompt?console.log(l.preview.prompt):s.checks?console.log(Yi(l.preview.checks)):console.log(fn(l.preview,l.selection,l.readiness))}),kn(e.command("runs").description("List supported v1 BioVault runs").option("--status <status>","Run status").option("--outcome <outcome>","Folder outcome")).action(async i=>{await o(async s=>{let a=Sn(i);return ue("R11",()=>y.listRunsForDisplay(s,{status:i.status,outcome:i.outcome,...a}))},ql)}),n.command("show").description("Show a run; watch only reads, never cancels").argument("<job>","Job ID").option("--watch","Poll until settled (Ctrl-C stops watching only)").action(async(i,s)=>{let a=O(t),l=await q(async()=>{K(i);let u=R(a);return s.watch?bh(u,i):{interrupted:!1,job:(await ue("R12",()=>y.getRunForDisplay(u,i),i)).job}},a.json);l.interrupted&&(a.json?$(l):console.error("Interrupted. Watching stopped; the run was not cancelled."),process.exit(130)),a.json?$(l.job):s.watch||console.log(mn(l.job))}),n.command("package").description("Show validated package metadata (no download)").argument("<job>","Job ID").action(async i=>{await o(async s=>(K(i),ue("R15",()=>y.getPackage(s,i),i)),Ol)}),n.command("prompt").description("Show the approved run prompt").argument("<job>","Job ID").action(async i=>{await o(async s=>(K(i),ue("R13",()=>y.getPrompt(s,i),i)),s=>s.prompt)}),kn(n.command("samples").description("Show run samples").argument("<job>","Job ID")).action(async(i,s)=>{await o(async a=>{K(i);let l=Sn(s);return ue("R14",()=>y.getSamples(a,i,l),i)},$l)}),kn(n.command("problems").description("Show run problems").argument("<job>","Job ID").option("--status <status>","resolved or unresolved").option("--severity <severity>","info, warning or blocking")).action(async(i,s)=>{await o(async a=>{K(i);let l=Sn(s);if(s.status!==void 0&&s.status!=="resolved"&&s.status!=="unresolved")throw P("usage","--status must be resolved or unresolved.",2);if(s.severity!==void 0&&s.severity!=="info"&&s.severity!=="warning"&&s.severity!=="blocking")throw P("usage","--severity must be info, warning or blocking.",2);return ue("R16",()=>y.getProblems(a,i,{...l,status:s.status,severity:s.severity}),i)},Tl)}),kn(n.command("decisions").description("Show run decisions").argument("<job>","Job ID")).action(async(i,s)=>{await o(async a=>{K(i);let l=Sn(s);return ue("R17",()=>y.getDecisions(a,i,l),i)},Rl)})}async function bh(t,e){let r=new AbortController,n=()=>r.abort(new Error("Interrupted."));process.on("SIGINT",n),process.on("SIGTERM",n);let o=null,i=1e4,s,a,l=null,u=!1,c=!1,d=Date.now();try{for(;!r.signal.aborted;){try{let p=await y.getRunForDisplay(t,e,{signal:r.signal});if(r.signal.aborted)break;o=p.job,i=1e4,!c&&p.job.cli_compatibility&&(console.error(pn(p.job.cli_compatibility)),c=!0),o.status!==s&&(console.error(`Job ${o.job_id} Status: ${o.status}`),o.status==="failed"&&console.error(`Run failed${Dt(o)&&o.failure?.message?`: ${o.failure.message}`:""}`),s=o.status);let f=Dt(o)?o.last_progress_at:null;f!==l&&(u=!1,a=void 0,l=f);let h=f===null?NaN:Date.parse(f),_=Math.max(0,Date.now()-(Number.isFinite(h)?h:d)),b=Math.floor(_/6e4);if(b!==a&&(console.error(Number.isFinite(h)?`last progress ${b} min ago`:`last progress unavailable; watching for ${b} min`),a=b),El(o))return{interrupted:!1,job:o};!u&&_>=xl&&(console.error("No progress reported for 15 min or more; still watching."),u=!0)}catch(p){if(r.signal.aborted)break;if(!(p instanceof H||p instanceof w&&p.retryable!==!1&&(p.status===429||p.status>=500)))throw y.classifyVaultError("R12",p,e);console.error(`Read temporarily unavailable; retrying in ${i/1e3}s.`),await hu(i,r.signal),i=Math.min(i*2,6e4);continue}await hu(5e3,r.signal)}}catch(p){if(!r.signal.aborted)throw p}finally{process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n)}return{interrupted:!0,job:o}}function hu(t,e){return new Promise((r,n)=>{if(e.aborted){n(e.reason);return}let o=()=>{clearTimeout(i),e.removeEventListener("abort",o),n(e.reason)},i=setTimeout(()=>{e.removeEventListener("abort",o),r()},t);e.addEventListener("abort",o,{once:!0})})}import{randomBytes as vh}from"node:crypto";import*as En from"node:fs/promises";import{createInterface as wh}from"node:readline/promises";var xn=t=>P("stale",`The plan changed since it was reviewed. Review it again: omics-os biovault draft show ${t} --execute-command`,5);async function yu(t,e,r){try{let n=await En.stat(t);if(!n.isFile()||n.size>4096)throw xn(r);let o=await En.readFile(t);if(o.length>4096)throw xn(r);let i=JSON.parse(o.toString("utf8"));if(!y.validExecuteTuple(i)||!y.sameTuple(i,e))throw xn(r)}catch{throw xn(r)}}function Ze(){return P("interrupted","Interrupted.",130)}async function Cn(t,e){if(e.aborted)throw Ze();let r=wh({input:process.stdin,output:process.stderr}),n=()=>{},o=()=>{},i=new Promise((a,l)=>{n=()=>l(Ze()),e.addEventListener("abort",n,{once:!0})}),s=new Promise((a,l)=>{o=()=>l(P("usage","No request was sent.",2)),r.once("close",o)});try{let a=await Promise.race([r.question(t,{signal:e}),i,s]);if(e.aborted)throw Ze();if(!/^(y|yes)$/i.test(a.trim()))throw P("usage","No request was sent.",2)}catch(a){throw e.aborted?Ze():a instanceof Error&&"exitCode"in a?a:P("usage","No request was sent.",2)}finally{e.removeEventListener("abort",n),r.removeListener("close",o),r.close()}}var Sh=t=>`The start outcome is unknown. Run: omics-os biovault run recover ${t}`,bu=t=>`An earlier start of this draft has an unknown outcome. Run: omics-os biovault run recover ${t}`,kh="Cancellation recorded. No evidence will be published for this run.";function vu(t,e,r){return t.kind!=="malformed"?null:t.identityMismatch?`This start record belongs to another login. Log in as that user, then run: omics-os biovault run recover ${r}`:t.unsafeReason?`The local start record cannot be inspected safely. Inspect ${y.pendingPath(e,r)} for manual removal.`:null}function Su(t,e,r=!1){return`The local start record is busy or locked after an interrupted command. ${r?"No record was forgotten.":"No request was sent."} Inspect ${y.pendingLockPath(t,e)} before retrying.`}async function ht(t,e){let r=!1;try{r=await y.release(t,e.entry_id,e.tuple,e.attempt_id)==="released"}catch{}r||console.error(`The local start record was kept. Clear it with: omics-os biovault run recover ${e.entry_id}`)}async function ss(t,e){let r=O(t),n=new AbortController,o=()=>n.abort(Ze());process.on("SIGINT",o),process.on("SIGTERM",o);try{let i=await q(()=>e(n.signal),r.json);r.json?$(i.error?{...i.payload,...De(i.error).payload}:i.payload):i.exit?console.error(i.message):console.log(i.message),r.json&&i.exit&&!i.error&&console.error(i.message),i.exit&&process.exit(i.exit)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}async function xh(t,e,r,n){if(K(e),!!r.yes!=!!r.review)throw P("usage","Starting a run from a script needs --yes --review FILE",2);if((!process.stdin.isTTY||!process.stdout.isTTY)&&!r.yes)throw P("usage","Starting a run from a script needs --yes --review FILE",2);let o=!1,i=!1;try{n.throwIfAborted();let s=await y.bindIdentity(R(O(t)),{signal:n}),a=y.pendingContext(s.config.apiUrl,s.user_id,s.org_id),l=await y.observe(a,e),u=vu(l,a,e);if(u)throw console.error(`Local start record: ${y.pendingPath(a,e)}`),P("unknown_outcome",u,8);if(l.kind!=="absent")throw P("unknown_outcome",bu(e),8);n.throwIfAborted();let c=await wu("R3",()=>y.getDraft(s.config,e,{signal:n}),e),d=await wu("R8",()=>y.getEntry(s.config,e,{signal:n}),e),p=y.snapshotNonconformity(c,d.entry);if(p?.startsWith("mismatch:"))throw P("stale","The draft changed while it was being read. Try again.",5);if(p)throw y.classifyVaultError("R8",new U(`/vault/entries/${e}`,200,"OK",p),e);if(c.config.created_by!==s.user_id||c.config.org_id!==s.org_id)throw P("forbidden","You do not have access to this.",3);let f=await y.executeReadiness(c);if(!f.ok)throw P("blocked",`The draft is not ready to start: ${kr(f.reason)}.`,6);if(n.throwIfAborted(),r.yes)await yu(r.review,f.command,e);else{let m=d.entry.work_plan.model_selection,x=m.mode==="inherit"?"inherit":`${m.model.provider}/${m.model.model_id}`;console.error(`Model (requested): ${x}
|
|
72
|
+
Cost limit: $${c.config.limits.max_cost_usd}
|
|
73
|
+
Storage limit: ${c.config.limits.max_storage_bytes} bytes
|
|
74
|
+
Revision: ${c.revision}
|
|
75
|
+
Warnings: ${c.checks.filter(C=>C.kind==="warning").length}
|
|
76
|
+
config_sha256: ${c.config_sha256}
|
|
77
|
+
This starts a billable run.`),await Cn("Start this run? [y/N]",n)}n.throwIfAborted();let h={version:1,entry_id:e,attempt_id:vh(16).toString("hex"),tuple:f.command,api_url:s.config.apiUrl,user_id:s.user_id,org_id:s.org_id,created_at:new Date().toISOString()},_=await y.claim(a,h);if(_==="exists")throw P("unknown_outcome",bu(e),8);if(_==="locked")throw P("unknown_outcome",Su(a,e),8);o=!0;try{n.throwIfAborted();let m=await y.getEntry(s.config,e,{signal:n});n.throwIfAborted();let x=y.entryNonconformity(m,e);if(x||!m.entry)throw new U(`/vault/entries/${e}`,200,"OK",x??"Missing entry");if(m.entry.status!=="planning"||m.entry.job_ids.length)throw P("not_now","This draft was already started. See: omics-os biovault runs",5);if(!m.entry.work_plan.preview)throw new U(`/vault/entries/${e}`,200,"OK","Missing preview");let C=y.snapshotNonconformity(m.entry.work_plan.preview,m.entry);if(C)throw new U(`/vault/entries/${e}`,200,"OK",C);let A=await y.executeReadiness(m.entry.work_plan.preview);if(n.throwIfAborted(),!A.ok||!y.sameTuple(A.command,h.tuple))throw P("stale",`The draft changed since you reviewed it. Review it again with: omics-os biovault draft show ${e}`,5)}catch(m){i=!0;let x=m instanceof w&&(m.kind==="not_now"||m.kind==="stale"),C=n.aborted?P("interrupted","Interrupted. No request was sent.",130):x?m:y.classifyVaultError("R8",m,e);throw!n.aborted&&!x&&(C.publicMessage+=" No request was sent."),await ht(a,h),C}let b;try{b=await y.executeRun(s.config,e,h.tuple,{signal:n})}catch(m){let x=y.classifyVaultError("R9",m,e);throw(x.kind==="precommit_refused"||x.kind==="busy")&&(i=!0,await ht(a,h)),x}n.throwIfAborted();let g=y.approvalNonconformity(b.entry,e,s,h)?{kind:"unknown"}:y.judge(b,h);if(g.kind!=="same")throw y.classifyVaultError("R9",new U(`/vault/entries/${e}/confirm`,200),e);return i=!0,await ht(a,h),{payload:{entry_id:e,job_id:g.jobId,state:"accepted"},message:`Approval accepted. Job ${g.jobId}. Check progress: omics-os biovault run show ${g.jobId}`,exit:0}}catch(s){throw n.aborted&&!i?P("interrupted",o?Sh(e):"Interrupted.",130):s instanceof w?s:P("server","The local start record could not be read or saved. No request was sent.",1)}}async function wu(t,e,r){try{return await e()}catch(n){throw y.classifyVaultError(t,n,r)}}function he(t,e,r,n,o=null,i){let s={payload:{entry_id:t,state:e,job_id:o},exit:r,message:n};if(r){let a=i instanceof w?i:P(e==="unknown"||e==="pending"?"unknown_outcome":"stale",n,r);a.publicMessage=n,a.exitCode=r,(e==="unknown"||e==="pending")&&(a.kind="unknown_outcome"),s.error=a}return s}async function Eh(t,e,r,n){if(K(e),r.yes&&!r.forget)throw P("usage","--yes requires --forget for recovery.",2);let o=!1;try{let i=await y.bindIdentity(R(O(t)),{signal:n}),s=y.pendingContext(i.config.apiUrl,i.user_id,i.org_id),a=await y.observe(s,e);if(a.kind==="absent")return he(e,"nothing",0,"Nothing to recover.");let l=vu(a,s,e);if(l)return console.error(`Local start record: ${y.pendingPath(s,e)}`),he(e,"unknown",8,l);let u;if(a.kind==="malformed")console.error(`Local start record: ${y.pendingPath(s,e)}`),u=he(e,"unknown",8,"The local start record is malformed. Use run recover --forget to forget only the local record; the run may still exist.");else{let d=a.record,p;try{p=await y.getEntry(i.config,e,{signal:n})}catch(f){u=he(e,"unknown",8,"Could not check the draft now; try again.",null,f)}if(p){let h=y.approvalNonconformity(p.entry,e,i,d)?{kind:"unknown"}:y.judge(p,d);switch(h.kind){case"same":{let _,b;try{let g=(await y.getRun(i.config,h.jobId,{signal:n})).job;g.approval_generation===y.APPROVAL_GENERATION&&"run_config"in g&&g.run_config&&g.run_config.created_by===d.user_id&&g.run_config.org_id===d.org_id&&g.config_sha256===d.tuple.config_sha256&&g.prompt_sha256===d.tuple.prompt_sha256&&g.execution_manifest_sha256===d.tuple.execution_manifest_sha256&&g.instruction_bundle_sha256===d.tuple.instruction_bundle_sha256&&(_=g)}catch(j){b=j}_?(n.throwIfAborted(),o=!0,await ht(s,d),u=he(e,"accepted",0,`Job ${_.job_id}. Status: ${_.status}.`,_.job_id)):u=he(e,"unknown",8,"Approval recorded; the run could not be confirmed yet. Try again.",h.jobId,b??new U(`/vault/jobs/${h.jobId}`,200));break}case"different":o=!0,await ht(s,d),u=he(e,"different",5,`This draft was started with a different plan (job ${h.jobId}). Your reviewed version was not started.`,h.jobId);break;case"cancelled":o=!0,await ht(s,d),u=he(e,"cancelled",5,"The draft was discarded before starting. Nothing ran.");break;case"not-started":{try{let _=await y.getDraft(i.config,e,{signal:n});_.state==="planning"&&y.supersededBy(d.tuple,{revision:_.revision,generation:_.editing.turn_generation})?(o=!0,await ht(s,d),u=he(e,"superseded",5,"Not started; the plan has changed since.")):u=he(e,"pending",8,"Not started as of now; the request may still land. Run recover again in a minute.")}catch(_){u=he(e,"unknown",8,"Could not check the draft now; try again.",null,_)}break}default:u=he(e,"unknown",8,"The outcome cannot be determined yet.")}}}o||n.throwIfAborted();let c=u.payload;if(r.forget&&(c.state==="unknown"||c.state==="pending")){if(!r.yes){if(!process.stdin.isTTY||!process.stdout.isTTY)throw P("usage","Use --forget --yes to forget a local record without a TTY. The run may still exist.",2);await Cn("Forget the local record? The run may still exist. [y/N]",n)}n.throwIfAborted();let d=await y.forget(s,e,a);return d==="forgotten"?he(e,"forgotten",0,"The local record was forgotten. The run may still exist."):he(e,"unknown",8,d==="locked"?Su(s,e,!0):"The local record changed; run recover again.")}return u}catch(i){throw n.aborted&&!o?Ze():i instanceof w?i:P("server","The local start record could not be read or changed.",1)}}async function as({cloud:t,jobId:e,yes:r}){await ss(t,async n=>{K(e);try{if(!r){if(!process.stdin.isTTY||!process.stdout.isTTY)throw P("usage","Use --yes to cancel this run without a TTY.",2);await Cn("Cancel this run? [y/N]",n)}n.throwIfAborted();let o;try{o=await y.cancelRun(R(O(t)),e,{signal:n})}catch(s){if(n.aborted)throw P("interrupted",`Cancellation could not be confirmed; check omics-os biovault run show ${e}.`,130);let a=y.classifyVaultError("R20",s,e);throw a.kind!=="cancel_cleanup_pending"&&!(a.status===409&&a.kind==="not_now")&&(a.kind="unknown_outcome",a.exitCode=8,a.publicMessage=`Cancellation could not be confirmed; check omics-os biovault run show ${e}.`),a}let i=o.job.cancel_cleanup_status==="pending";return{payload:o,exit:i?7:0,message:kh+(i?` Cleanup is still pending; run omics-os biovault run cancel ${e} again.`:"")}}catch(o){throw n.aborted&&!(o instanceof w&&o.exitCode===130)?Ze():o}})}function ku({cloud:t,run:e}){e.command("start").description("Starts a billable run. Works with CLI logins and API keys.").argument("<entry>","Entry ID").option("--yes","Approve the freshly reviewed billable plan (requires --review)").option("--review <file>","Exact seven-field draft show --execute-command JSON").action(async(r,n)=>{await ss(t,o=>xh(t,r,n,o))}),e.command("recover").description("Read the outcome of an earlier start; never resend it").argument("<entry>","Entry ID").option("--forget","Forget only an unresolved local record; the run may still exist").option("--yes","Confirm local forgetting without a prompt").action(async(r,n)=>{await ss(t,o=>Eh(t,r,n,o))}),e.command("cancel").description("Record a cancellation fence; cleanup may still be pending").argument("<job>","Job ID").option("--yes","Confirm cancellation without a prompt").action(async(r,n)=>{await as({cloud:t,jobId:r,yes:n.yes})})}var qn="--show-urls",ls=t=>t.endsWith("_url"),xu="Print the time-limited download links (hidden by default)";function Eu({cloud:t,vault:e}){e.command("search").description("Search legacy evidence; may not work with a CLI login").requiredOption("--genes <genes>","Comma-separated gene list").requiredOption("--disease <disease>","Disease term").requiredOption("--control <control>","Control term").action(async r=>{let n=O(t),o=R(n),i=r.genes.split(",").map(a=>a.trim()),s=await q(()=>Ni(o,{genes:i,disease:r.disease,control:r.control}),n.json);if(n.json){$(s);return}s.hit?(console.log(`Hit: ${s.evidence_id}`),console.log(s.message)):(console.log("No cached result found."),console.log(s.message))}),e.command("evidence").description("Get legacy evidence; may not work with a CLI login").argument("<id>","Evidence ID").option(qn,xu).action(async(r,n)=>{let o=O(t),i=await q(async()=>(K(r),Li(R(o),r)),o.json);if(o.json){let a=!n.showUrls&&i.plot_urls.length>0;$(a?{...i,plot_urls:i.plot_urls.map(()=>null),urls_hidden:!0}:i);return}let s=i.evidence;if(console.log(ie([["Evidence ID",s.evidence_id],["Genes",s.genes.join(", ")],["Disease",s.disease],["Control",s.control],["Created",s.created_at??"-"]])),s.methods_paragraph&&console.log(`
|
|
78
|
+
Methods:
|
|
79
|
+
${s.methods_paragraph}`),i.plot_urls.length>0&&!n.showUrls)console.log(`
|
|
80
|
+
Plots: ${i.plot_urls.length} (time-limited links hidden; add ${qn} to print them)`);else if(i.plot_urls.length>0){console.log(`
|
|
81
|
+
Plots (${i.plot_urls.length}):`);for(let a of i.plot_urls)console.log(` ${a}`)}}),e.command("ask").description("Closed legacy compute; use draft new instead").argument("[args...]").allowUnknownOption().helpOption(!1).action(async(r,n,o)=>{o.args.some(s=>s==="--help"||s==="-h")&&(o.outputHelp(),process.exit(0));let i=O(t);await q(async()=>{throw P("usage","BioVault questions are now runs. Start with: omics-os biovault draft new",2)},i.json)}),e.command("jobs").description("List legacy vault jobs").action(async()=>{let r=O(t),n=R(r),o=await q(()=>ue("R11",()=>y.listRuns(n,{view:"legacy"})),r.json);if(r.json){$(o);return}console.log(Al(o)),console.log(`
|
|
82
|
+
BioVault runs are listed by: omics-os biovault runs`)}),e.command("job-status").description("Get vault job status (v1 or legacy)").argument("<job-id>","Job ID").action(async r=>{let n=O(t),o=await q(async()=>(K(r),ue("R12",()=>y.getRun(R(n),r),r)),n.json);n.json?$(o):console.log(mn(o.job))}),e.command("cancel").description("Alias of run cancel; cleanup may still be pending").argument("<job-id>","Job ID").option("--yes","Confirm cancellation without a prompt").action(async(r,n)=>{await as({cloud:t,jobId:r,yes:n.yes})}),e.command("export").description("Export legacy evidence; may not work with a CLI login").argument("<evidence-id>","Evidence ID").requiredOption("--formats <formats>","Comma-separated formats (e.g. pdf,csv)").option(qn,xu).action(async(r,n)=>{let o=O(t),i=n.formats.split(",").map(a=>a.trim()),s=await q(async()=>(K(r),Di(R(o),{evidence_id:r,formats:i})),o.json);if(o.json){let a=!n.showUrls&&Object.entries(s.exports).some(([l,u])=>ls(l)&&u!==null);$(a?{...s,exports:Object.fromEntries(Object.entries(s.exports).map(([l,u])=>[l,ls(l)?null:u])),urls_hidden:!0}:s);return}console.log(`Export for ${r}:`);for(let[a,l]of Object.entries(s.exports)){let u=l===null?"(not available)":n.showUrls||!ls(a)?l:`available (link hidden; add ${qn} to print it)`;console.log(` ${a}: ${u}`)}})}import*as ee from"node:fs/promises";import Ar from"node:path";import Ch from"node:os";import{randomBytes as qh}from"node:crypto";import{spawnSync as Ah}from"node:child_process";import{createInterface as Oh}from"node:readline/promises";import*as On from"node:fs/promises";var Bt=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Cu=256*1024;async function $n(t){let e;try{let n=await On.stat(t);if(!n.isFile())throw P("usage","The configuration must be a regular JSON file.",2);if(n.size>Cu)throw P("usage","The configuration file must be at most 256 KiB.",2);e=await On.readFile(t)}catch(n){throw n instanceof Error&&"kind"in n?n:P("usage","The configuration file could not be read.",2)}if(e.byteLength>Cu)throw P("usage","The configuration file must be at most 256 KiB.",2);let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw P("usage","The configuration file is not valid JSON.",2)}if(!Bt(r))throw P("usage","The configuration must be a JSON object.",2);if(r.config_version!=="1")throw P("usage",'config_version must be "1".',2);if(!Bt(r.draft))throw P("usage","draft must be a JSON object.",2);return r}function qr(t,e){let{llm:r,...n}=y.fieldsOfPreview(t),o=e.work_plan.model_selection,i=new Map,s=t.config.datasets.literature.map(a=>{let l=i.get(a.file)??0;return i.set(a.file,l+1),{file:a.file,record_index:l,decision:a.decision}});return{config_version:"1",expected_revision:t.revision,confirm_defaults:[],draft:{...n,datasets:{...n.datasets,literature_decisions:s},...o.mode==="explicit"?{llm:{selection:structuredClone(o)}}:{}}}}function An(t,e){let r=t;for(let n of e.split(".")){if(!Bt(r))return{present:!0,malformed:!0,value:r};if(!Object.hasOwn(r,n))return{present:!1,malformed:!1};r=r[n]}return{present:!0,malformed:!1,value:r}}function us(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every((n,o)=>us(n,e[o]));if(!Bt(t)||!Bt(e))return!1;let r=Object.keys(t);return r.length===Object.keys(e).length&&r.every(n=>Object.hasOwn(e,n)&&us(t[n],e[n]))}var qu=t=>Bt(t)&&typeof t.file=="string"&&Number.isInteger(t.record_index)&&t.record_index>=0&&(t.decision==="include"||t.decision==="exclude");function cs(t,e,r){let n=[],o=[];for(let a of y.CONFIRMABLE_PATHS){let l=An(r.draft,a),u=An(e.draft,a);l.present?(l.malformed||!us(l.value,u.value))&&n.push(a):y.originOf(t,a)!=="default"&&o.push(a)}let i="datasets.literature_decisions",s=An(r.draft,i);if(s.present){let a=s.value;if(s.malformed||!Array.isArray(a)||!a.every(qu))n.push(i);else if(a.length){let l=An(e.draft,i).value,u=Array.isArray(l)?l.filter(qu):[];a.some(c=>u.find(d=>d.file===c.file&&d.record_index===c.record_index)?.decision!==c.decision)&&n.push(i)}}return{changed:n,omitted:o}}function Au(){return{config_version:"1",draft:{request:{question:""},selection:{nodes:[]},cohorts:{intent:""}}}}var Tn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Nu=t=>JSON.stringify(t,null,2)+`
|
|
83
|
+
`,Ou=(t,e)=>[...e,t],be=t=>P("usage",t,2);async function ds(t,e){let r=await ue("R3",()=>y.getDraft(t,e),e),n=await ue("R8",()=>y.getEntry(t,e),e),o=y.snapshotNonconformity(r,n.entry);if(o?.startsWith("mismatch:"))throw P("stale","The draft changed while it was being read. Try again.",5);if(o)throw y.classifyVaultError("R8",new U(`/vault/entries/${e}`,200,"OK",o),e);return{preview:r,entry:n.entry}}function $u(t,e){if(!e.length)return t;let r=t.confirm_defaults;if(r!==void 0&&(!Array.isArray(r)||!r.every(n=>typeof n=="string")))throw be("confirm_defaults must be absent or an array of strings when --confirm-default is used.");return{...t,confirm_defaults:[...new Set([...r??[],...e])]}}function Tu(t){if(!Number.isInteger(t.expected_revision)||t.expected_revision<=0)throw be("expected_revision must be a positive integer for apply.")}function Ru(t){let e=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(e)||e<=0)throw be("--expect-revision must be a positive integer.");return e}async function fs(t){let e=Oh({input:process.stdin,output:process.stderr});try{let r=await e.question(t);if(!/^y$/i.test(r.trim()))throw be("No change was sent.")}catch(r){throw r instanceof w?r:be("No change was sent.")}finally{e.close()}}function ju(t){console.error(`Changed fields (advisory): ${t.changed.length?t.changed.join(", "):"None"}`),t.omitted.length&&console.error(`These fields are not in your file; the server will apply its defaults to them (values may already match): ${t.omitted.join(", ")}`)}async function zt(t,e=!1){try{return await t()}catch(r){throw r instanceof w&&(e&&r.status===409&&r.kind!=="unknown_outcome"?(r.publicMessage="This draft was already started; cancel its run instead. Find it with: omics-os biovault runs",r.exitCode=5):r.kind==="stale"&&(r.publicMessage="The draft changed since your file was made. Export it again.")),r}}function $h(t,e,r){let n=t.draft.llm,o=n===void 0?{mode:"inherit"}:Tn(n)?n.selection:void 0,i=y.modelSelectionNonconformity(o);if(i)throw y.classifyVaultError(e,new U("/vault/runs",200,"OK",i),r.entry_id);return o}async function ps(t,e,r){let n=$h(e,r,t),o=await y.executeReadiness(t),i=n.mode==="explicit"?`${n.model.provider}/${n.model.model_id}`:"inherit";return fn(t,n,o).replace(/^Model\s+[^\n]*$/m,`Model (requested): ${i}`)}async function Iu(t){try{if(!(await ee.lstat(t)).isFile())throw be("The output target must be a regular file, not a directory or symlink.")}catch(e){if(Tn(e)&&e.code==="ENOENT")return;throw e}}async function Pu(t,e,r){let n=Ar.join(Ar.dirname(t),`.${Ar.basename(t)}.tmp-${qh(12).toString("hex")}`),o=!1;try{r&&await Iu(t);let i=await ee.open(n,"wx",420);o=!0;try{await i.writeFile(Nu(e))}finally{await i.close()}r?(await Iu(t),await ee.rename(n,t)):await ee.link(n,t)}catch(i){throw i instanceof w?i:Tn(i)&&i.code==="EEXIST"?be("The output file already exists. Use --force to replace a regular file."):P("server","The output file could not be saved.",1)}finally{o&&await ee.unlink(n).catch(i=>{if(!Tn(i)||i.code!=="ENOENT")throw i})}}function Lu({cloud:t,draft:e,literature:r}){let n=async(o,i,s=!1)=>{let a=O(t),l=await q(async()=>{let u=await o(()=>R(a),a.json===!0),c=a.json||s?void 0:await i(u);return{value:u,text:c}},a.json);a.json||s?$(l.value):console.log(l.text)};e.command("new").description("Write a starter DraftCommand; this never starts a run").option("--output <file>","Output JSON file").option("--force","Replace a regular output file").action(async o=>{await n(async()=>{if(o.force&&!o.output)throw be("--force requires --output.");let i=Au();return o.output?(await Pu(o.output,i,o.force===!0),{output:o.output,command:i}):i},()=>o.output?`Saved ${o.output}`:"",!o.output)}),e.command("create").description("Create a draft from a DraftCommand file (not run approval)").requiredOption("--file <file>","DraftCommand JSON file").option("--confirm-default <path>","Acknowledge a default, not run approval",Ou,[]).action(async o=>{let i;await n(async s=>{if(i=$u(await $n(o.file),o.confirmDefault),i.expected_revision!==void 0&&i.expected_revision!==null)throw be("remove expected_revision for create");return zt(()=>y.createDraft(s(),i))},s=>ps(s,i,"R2"))}),e.command("export").description("Export a checked editable draft with its revision").argument("<entry>","Entry ID").requiredOption("--output <file>","Output JSON file").option("--force","Replace a regular output file").action(async(o,i)=>{await n(async s=>{K(o);let a=await ds(s(),o),l=qr(a.preview,a.entry);return await Pu(i.output,l,i.force===!0),{output:i.output,command:l}},s=>`Saved ${s.output}`)}),e.command("apply").description("Apply a whole draft replacement; --yes acknowledges omissions only, not billable start").argument("<entry>","Entry ID").requiredOption("--file <file>","DraftCommand JSON file").option("--confirm-default <path>","Acknowledge a default, not run approval",Ou,[]).option("--yes","Acknowledge omitted fields without a prompt (not run approval)").action(async(o,i)=>{let s;await n(async a=>{K(o),s=$u(await $n(i.file),i.confirmDefault),Tu(s);let l=a(),u=await ds(l,o),c=cs(u.preview,qr(u.preview,u.entry),s);if(ju(c),c.omitted.length&&!i.yes){if(!process.stdin.isTTY)throw be("Use --yes to acknowledge omitted fields (not run approval).");await fs("Apply? [y/N]")}return zt(()=>y.saveDraft(l,o,s))},a=>ps(a,s,"R4"))}),e.command("edit").description("Edit a checked draft in a local editor (TTY only)").argument("<entry>","Entry ID").action(async o=>{let i,s=!1;await n(async(a,l)=>{if(K(o),!process.stdin.isTTY)throw be("Use draft export + draft apply when no TTY is available.");let u=a(),c=await ds(u,o);i=qr(c.preview,c.entry);let d=await ee.mkdtemp(Ar.join(Ch.tmpdir(),"lobster-vault-"));try{await ee.chmod(d,448);let p=Ar.join(d,"run.json"),f=Buffer.from(Nu(i)),h=await ee.open(p,"wx",384);try{await h.writeFile(f)}finally{await h.close()}let _=(process.env.VISUAL?.trim()||process.env.EDITOR?.trim()||"vi").split(/\s+/),b=Ah(_[0],[..._.slice(1),p],{stdio:"inherit",shell:!1});if(b.error||b.status!==0)throw be("The editor did not finish successfully; no change was sent.");return(await ee.readFile(p)).equals(f)?(s=!0,l&&console.error("No changes."),c.preview):(i=await $n(p),Tu(i),ju(cs(c.preview,qr(c.preview,c.entry),i)),await fs("Apply? [y/N]"),await zt(()=>y.saveDraft(u,o,i)))}finally{await ee.rm(d,{recursive:!0,force:!0})}},a=>s?"No changes.":ps(a,i,"R4"))}),r.command("add").description("Register a .ris file; no run is started").argument("<entry>","Entry ID").argument("<file.ris>","RIS file").requiredOption("--expect-revision <n>","Positive draft revision").action(async(o,i,s)=>{await n(async a=>{K(o);let l=Ru(s.expectRevision);return zt(()=>y.uploadLiterature(a(),o,l,i))},a=>{let l=new Map;for(let u of a.config.datasets.literature)l.set(u.file,(l.get(u.file)??0)+1);return`Revision: ${a.revision}
|
|
84
|
+
`+a.config.datasets.literature_files.map(u=>`${u.name}: ${l.get(u.name)??0} parsed records`).join(`
|
|
85
|
+
`)})}),r.command("remove").description("Remove registered literature from a draft").argument("<entry>","Entry ID").argument("<file_id>","Registered literature basename").requiredOption("--expect-revision <n>","Positive draft revision").action(async(o,i,s)=>{await n(async a=>{K(o);let l=Ru(s.expectRevision);return zt(()=>y.removeLiterature(a(),o,i,l))},a=>`Revision: ${a.revision}`)}),e.command("discard").description("Discard a planning draft; this never stops a run").argument("<entry>","Entry ID").option("--yes","Confirm discard without a prompt").action(async(o,i)=>{await n(async s=>{if(K(o),!i.yes){if(!process.stdin.isTTY)throw be("Use --yes to discard this draft without a TTY.");await fs("Discard this draft? [y/N]")}return zt(()=>y.discardDraft(s(),o),!0)},s=>`Draft ${s.entry.entry_id} discarded.`)})}function Du({cloud:t,run:e}){e.command("download").description("Each file is checked against the folder's SHA-256 manifest.").argument("<job>","Full BioVault dataset job ID").requiredOption("--dest <dir>","Existing directory you own, not writable by other users; no symlink ancestors (macOS/Linux; Windows: use WSL)").option("--path <path>","Exact manifest path (repeatable)",(r,n)=>[...n,r],[]).option("--archive","Download the optional package.zip instead of individual files").option("--force","Atomically replace existing regular files").action(async(r,n)=>{let o=O(t),i=new AbortController,s=Nl(r,n.dest),a,l=()=>i.abort(Pl());process.on("SIGINT",l),process.on("SIGTERM",l);try{await Ul(R(o),r,{dest:n.dest,paths:n.path,archive:n.archive,force:n.force,controller:i,progress:u=>console.error(`Downloading ${JSON.stringify(u)}\u2026`)},s),i.signal.throwIfAborted()}catch(u){let c=i.signal.aborted?i.signal.reason:u instanceof w&&u.kind?u:y.classifyVaultError("R12",u,r);a=De(c)}finally{if(process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l),o.json)console.log(JSON.stringify({...s,...a?.payload??{}}));else if(console.log(s.completed.length?["PATH BYTES CHECK",...s.completed.map(u=>`${u.path} ${u.bytes} sha256 ok`)].join(`
|
|
86
|
+
`):"No files were saved."),a){let u=a.payload.code?` (code ${a.payload.code})`:"",c=s.completed.length?`
|
|
87
|
+
Kept files: ${s.completed.map(p=>JSON.stringify(p.path)).join(", ")}`:"",d=s.not_attempted.length?`
|
|
88
|
+
Not attempted: ${s.not_attempted.map(p=>JSON.stringify(p)).join(", ")}`:"";console.error(`${a.payload.error}${u}${s.failed?`
|
|
89
|
+
Failed file: ${JSON.stringify(s.failed)}`:""}${c}${d}`)}process.exitCode=a?.exitCode??0}})}function Rn(t,e="vault"){let r=t.command(e).description("BioVault drafts, runs and legacy evidence"),n=r.command("draft").description("Review and configure BioVault drafts"),o=n.command("literature").description("Manage draft literature"),i=r.command("run").description("Inspect and manage BioVault runs");Lu({cloud:t,vault:r,draft:n,literature:o}),_u({cloud:t,vault:r,draft:n,run:i}),Du({cloud:t,run:i}),ku({cloud:t,run:i}),Eu({cloud:t,vault:r})}import{randomBytes as Th}from"crypto";import{rename as Rh,rm as jh,writeFile as ms}from"fs/promises";import{basename as Ih,dirname as Ph,join as Nh,resolve as jn}from"path";function hs(t){let e=t.command("editor").description("LaTeX editor operations");e.command("meta").description("Get editor project metadata").argument("<session-id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>Fi(o,r),n.json);if(n.json){$(i);return}if(!i.exists){console.log("No editor project for this session.");return}console.log(ie([["Exists","yes"],["Generated At",i.generated_at??"-"],["File Count",String(i.file_count??0)],["Generation Version",String(i.generation_version??"-")],["New Messages",String(i.new_messages??0)],["New Plots",String(i.new_plots??0)]]))}),e.command("generate").description("Start LaTeX generation for a session").argument("<session-id>","Session ID").option("--force","Force regeneration").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o),s=await q(()=>Ui(i,r,{force:n.force}),o.json);o.json||process.stdout.write(`Generating LaTeX (job: ${s.job_id})...`);let a=2e3,u=Date.now()+3e5,c=s;for(;Date.now()<u;){await new Promise(p=>setTimeout(p,a));let d=await q(()=>Mi(i,r,s.job_id),o.json);if(d.status==="complete"||d.status==="failed"){o.json?$(d):d.status==="failed"?(console.error(`
|
|
90
|
+
Generation failed: ${d.error??"unknown error"}`),process.exit(1)):(process.stdout.write(` done
|
|
91
|
+
`),d.result&&(console.log(`TeX: ${d.result.tex_path}`),console.log(`Figures: ${d.result.figures.length}`)));return}o.json||process.stdout.write(".")}o.json?$({error:"Generation timed out",job_id:s.job_id}):console.error(`
|
|
92
|
+
Generation timed out.`),process.exit(1)}),e.command("files").description("List files in editor project").argument("<session-id>","Session ID").action(async r=>{let n=O(t);W(r,n.json);let o=R(n),i=await q(()=>Vi(o,r),n.json);if(n.json){$(i);return}if(i.length===0){console.log("No editor files.");return}let s=i.map(a=>[a.name,G(a.size),a.zone,a.writable?"yes":"no"]);console.log(Q(["NAME","SIZE","ZONE","WRITABLE"],s))}),e.command("pull").description("Download an editor file").argument("<session-id>","Session ID").argument("<path>","File path in editor project").argument("[dest]","Local destination").action(async(r,n,o)=>{let i=O(t);W(r,i.json);let s=R(i),a=await q(()=>Bi(s,r,n),i.json),l=jn(o??n.split("/").pop());await ms(l,Buffer.from(a)),i.json?$({success:!0,path:l,size:a.byteLength}):console.log(`Saved: ${l} (${G(a.byteLength)})`)}),e.command("push").description("Upload a file to editor project").argument("<session-id>","Session ID").argument("<path>","File path in editor project").argument("<local>","Local file to upload").action(async(r,n,o)=>{let i=O(t);W(r,i.json);let s=R(i),{readFile:a}=await import("fs/promises"),l=await a(jn(o)),u=await q(()=>zi(s,r,n,l),i.json);i.json?$(u):console.log(`Pushed: ${u.path} (${G(u.size)})`)}),e.command("compile").description("Compile the editor project and save the PDF").argument("<session-id>","Session ID").option("--output <path>","Output PDF path","output.pdf").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o);o.json||process.stderr.write(`Compiling...
|
|
93
|
+
`);let s=jn(n.output),a=await q(async()=>{let l=await Ji(i,r),u=Nh(Ph(s),`.${Ih(s)}.${Th(6).toString("hex")}.part`);try{await ms(u,Buffer.from(l.pdf),{flag:"wx"}),await Rh(u,s)}catch(c){await jh(u,{force:!0}).catch(()=>{});let d=c?.code??"write failed",p=new w("output",0,"");throw p.kind="filesystem",p.publicMessage=`Could not write ${s} (${d}); the PDF was not saved and any existing file is unchanged.`,p}return l},o.json);o.json?$({success:!0,path:s,size:a.pdf.byteLength,job_id:a.jobId}):console.log(`Saved: ${s} (${G(a.pdf.byteLength)})`)}),e.command("download").description("Download entire editor project as zip").argument("<session-id>","Session ID").option("--output <path>","Output zip path","editor-project.zip").action(async(r,n)=>{let o=O(t);W(r,o.json);let i=R(o);o.json||process.stdout.write("Downloading project...");let s=await q(()=>Hi(i,r),o.json),a=jn(n.output);await ms(a,Buffer.from(s)),o.json?$({success:!0,path:a,size:s.byteLength}):(process.stdout.write(` done
|
|
94
|
+
`),console.log(`Zip: ${a} (${G(s.byteLength)})`))})}import{spawn as Lh}from"node:child_process";import{createInterface as Mu}from"node:readline";function Dh(t){let[e,r]=so(t),n=Lh(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}function Uu(t){console.log("Open this URL in your browser:"),console.log(t.verification_uri_complete??t.verification_uri),t.verification_uri_complete||console.log(`Enter code: ${t.user_code}`),console.log("Waiting for authorization...")}async function Uh(t,e){let r=Mu({input:process.stdin,output:process.stdout});return console.log(t),e.forEach((n,o)=>console.log(` ${o+1}) ${n}`)),new Promise(n=>{r.question("Enter number: ",o=>{r.close();let i=Number.parseInt(o.trim(),10);n(Number.isInteger(i)&&i>=1&&i<=e.length?i-1:-1)})})}async function Mh(t){let e=Mu({input:process.stdin,output:process.stdout});return new Promise(r=>{e.question(`${t} `,n=>{e.close(),r(n.trim())})})}function Fh(t,e){let r={...t,endpoint:oe};if(Ye("default",r,"Platform"),e){let n={...t,endpoint:`https://${e}.omics-os.com`};Ye(e,n,e),Ke(e)}else Ke("default")}function gs(t){t.command("login").description("Authenticate with Omics-OS Cloud").option("--api-key <key>","Login with API key (prefer OMICS_OS_API_KEY env var for security)").option("--device","Use device-code login instead of the local browser callback").option("--tenant <slug>","Login to a tenant subdomain (e.g. acme); omit for the platform").action(async e=>{let r=t.optsWithGlobals(),n=_e({cloud:!0,apiUrl:r.endpoint}),o=!r.json&&!!process.stdin.isTTY,i=f=>{r.json?console.log(JSON.stringify({error:f})):console.error(f),process.exit(1)},s,a=!1;if(e.tenant)if(bn(e.tenant))a=!0,r.json||console.log(`'${e.tenant}' is the platform itself (${oe}), not a tenant subdomain \u2014 logging into the "default" profile.`);else try{s=ts(e.tenant)}catch(f){i(f instanceof Error?f.message:String(f))}let l=Me(),u=(l?.name==="LOBSTER_TOKEN"?void 0:l?.value)??e.apiKey;u&&s&&i("--tenant is not supported with API key login. Use OAuth: omics-os login --tenant <slug>");try{Ke("default")}catch{}if(u){e.apiKey&&u===e.apiKey&&!r.json&&console.error("Warning: API key visible in shell history. Prefer: OMICS_OS_API_KEY=<key> omics-os login");let f=await q(()=>ei({apiKey:u,apiUrl:n.apiUrl}),r.json),h=f.credential.endpoint;Ye("default",f.credential,h===oe?"Platform":new URL(h).host),Ke("default"),r.json?console.log(JSON.stringify({success:!0,auth_mode:f.credential.auth_mode,email:f.credential.email,org_id:f.credential.org_id,tier:f.credential.tier,profile:"default"})):console.log(`API key validated. Logged in${f.credential.email?` as ${f.credential.email}`:""}.`);return}if(!s&&!a&&o){let f=At();if(f.length>0){let h=f.filter(g=>g.name!=="default"),_=[{label:"Platform \u2014 app.omics-os.com"},...h.map(g=>({label:`${g.label} \u2014 ${g.endpoint}`,slug:g.name})),{label:"Log into a different tenant\u2026",other:!0}],b=await Uh("Which would you like to log into?",_.map(g=>g.label));b<0&&i("Invalid selection. Aborted.");let j=_[b];if(j.other){let g=await Mh("Enter tenant slug (e.g. acme):");if(bn(g))console.log(`'${g}' is the platform itself (${oe}) \u2014 logging into the "default" profile.`);else try{s=ts(g)}catch(m){i(m instanceof Error?m.message:String(m))}}else s=j.slug}}let c=async f=>{try{return await f()}catch(h){throw s&&Gl(h)&&i(r.json?`Tenant '${s}' does not exist or is not active. Log in without --tenant for the platform.`:Kl(s)),h}},d;try{if(e.device)d=await q(()=>c(()=>tn({apiUrl:n.apiUrl,tenant:s,onVerification:f=>{r.json||Uu(f)}})),r.json);else{let f;try{d=await q(()=>c(()=>ti({apiUrl:n.apiUrl,openBrowser:Dh,tenant:s,onAuthUrl:h=>{f=h,r.json||(console.log("Opening browser for authentication..."),console.log(`If browser does not open, visit: ${h}`))}})),r.json)}catch(h){if(r.json)throw h;let _=h instanceof Error?h.message:String(h);console.error(`Browser login failed: ${_}`),f&&console.error(`Last auth URL: ${f}`),console.error("Falling back to device login."),d=await q(()=>c(()=>tn({apiUrl:n.apiUrl,tenant:s,onVerification:Uu})),r.json)}}}catch(f){i(`Login failed: ${f instanceof Error?f.message:String(f)}`)}if(Fh(d,s),r.json){console.log(JSON.stringify({success:!0,auth_mode:d.auth_mode,credential_id:d.auth_mode==="oauth"?d.credential_id:void 0,email:d.email,org_id:d.org_id,tier:d.tier,profile:s??"default",...s?{endpoint:`https://${s}.omics-os.com`}:{}}));return}let p=d.email||(d.user_id?`user ${d.user_id}`:"");console.log(`Logged in${p?` as ${p}`:""}.`),s&&(console.log(`Profile "${s}" is now active (https://${s}.omics-os.com).`),console.log("Tip: `omics-os use default` switches back to the platform."))}),t.command("logout").description("Remove stored credentials").action(async()=>{let e=O(t),r=Y(e.profile),n=await mr({apiUrl:e.endpoint,profile:e.profile});if(e.json){console.log(JSON.stringify({success:!0,removed:n.removed,revoked:n.revoked,auth_mode:r?.auth_mode}));return}if(!r&&!n.removed){console.log("Not logged in; nothing to remove.");return}if(r?.auth_mode==="oauth"){console.log(n.revoked?"Logged out. CLI credential revoked.":"Logged out locally. Backend revoke was not confirmed.");return}if(r?.auth_mode==="api_key"){console.log("Logged out locally. Your API key stays valid until you revoke it in Account \u2192 API Keys.");return}console.log("Logged out.")})}function _s(t){t.command("status").description("Show account status and usage").action(async()=>{let e=O(t),r=Y(e.profile),n=Me(),o=!!n;!r&&!o&&(e.json?console.log(JSON.stringify({error:"Not logged in",code:"AUTH_REQUIRED"})):console.error(qe),process.exit(1));let i=await q(()=>{if(!o)return ri({apiUrl:e.endpoint,profile:e.profile});let c=e.endpoint??(r?Oe(r.endpoint):void 0),d=_e({cloud:!0,apiUrl:c,profile:e.profile});return E(d,"/gateway/auth/verify",{timeoutMs:15e3})},e.json),s=o?void 0:r,a=(n?.value??"").startsWith("omk_")?"api_key":"token";if(e.json){$({...i,auth_mode:s?s.auth_mode:a,credential_source:s?"stored":"env",credential_id:s?.auth_mode==="oauth"?s.credential_id:void 0});return}let l=n?.name??"LOBSTER_TOKEN",u=s?s.auth_mode==="api_key"?"API key":"Omics CLI credential":`${a==="api_key"?"API key":"Token"} (${l})`;console.log(ie([["Auth Mode",u],["Email",i.email??s?.email??"-"],["User ID",i.user_id??s?.user_id??"-"],["Org ID",i.org_id??s?.org_id??"-"],["Tier",i.tier??s?.tier??"free"],["Valid",i.valid===!1?"no":"yes"]]))})}var Vh={disease:"mondo",tissue:"uberon",cell_type:"cell_ontology"},Bh={mondo:"disease",uberon:"tissue",cell_ontology:"cell_type"};function zh(t){if(t)return t.split(",").map(e=>{let r=e.trim().toLowerCase();return Vh[r]??r})}function Hh(t){return Bh[t]??t}function Jh(t,e){switch(t){case"VECTOR_SEARCH_UNAVAILABLE":return"Vector search service unavailable. Try again shortly.";case"VECTOR_ARTIFACT_EMBEDDER_MISMATCH":return"Vector search: query embedder does not match artifact metadata. Service needs rebuild.";case"VECTOR_COLLECTION_UNAVAILABLE":return"Vector search: requested collection is not available.";case"VECTOR_SEARCH_QUERY_FAILED":return"Vector search: query failed. Try again or simplify your query.";default:return e===502?"Vector search: embedding service temporarily unavailable. Try again shortly.":e===503?"Vector search: service is initializing. Try again in a few seconds.":`Vector search failed (${e}).`}}function Fu(t){t.command("vector").description("Semantic ontology search").command("search").description("Search ontology databases for matching terms").argument("<query>",'Search query (e.g. "triple-negative breast cancer")').option("-k, --top-k <n>","Number of results per collection","5").option("-c, --collections <list>","Collections: mondo,uberon,cell_ontology (aliases: disease,tissue,cell_type)").action(async(r,n)=>{let o=O(t),i=R(o),s;try{s=await Wi(i,{query:r,top_k:parseInt(n.topK,10),collections:zh(n.collections)})}catch(l){if(l instanceof w&&(l.status===502||l.status===503)){let u=l.body?.code,c=Jh(u,l.status);o.json?console.log(JSON.stringify({error:c,code:"ServiceUnavailable",status:l.status,backend_code:u??null,vector_status:l.body?.vector_status??null,collections:l.body?.collections??null})):console.error(c),process.exit(1)}throw o.json&&(l instanceof w?console.log(JSON.stringify({error:l.message,code:l.name,status:l.status,backend_code:l.body?.code??null,vector_status:null,collections:null})):console.log(JSON.stringify({error:String(l),code:"UnknownError",status:null,backend_code:null,vector_status:null,collections:null})),process.exit(1)),l instanceof M&&(console.error(l.message),process.exit(1)),l instanceof pe&&(console.error(`Rate limited. Retry after ${l.retryAfterMs?Math.ceil(l.retryAfterMs/1e3):"a few"}s`),process.exit(1)),l instanceof H&&(console.error(`Network error: ${l.message}`),process.exit(1)),l instanceof w&&(console.error(`API error (${l.status}): ${l.message}`),process.exit(1)),l}if(o.json){$(s);return}let a=Object.keys(s.results);if(a.length===0){console.log("No results.");return}for(let l of a){let u=s.results[l];if(!(!u||u.length===0)){console.log(`
|
|
95
|
+
${Hh(l)}:`);for(let c of u){let d=(c.score*100).toFixed(1);console.log(` ${d}% ${c.ontology_id} ${c.term}`)}}}})}function ys(t){let e=t.command("profiles").description("Manage credential profiles for multi-tenant access");e.command("list",{isDefault:!0}).description("List all credential profiles").action(()=>{let r=t.optsWithGlobals(),n=At();if(n.length===0){r.json?console.log(JSON.stringify({profiles:[]})):console.log("No profiles. Run `omics-os login` to create one.");return}if(r.json){console.log(JSON.stringify({profiles:n}));return}let o=Math.max(7,...n.map(s=>s.name.length)),i=Math.max(5,...n.map(s=>s.label.length));console.log(`${"NAME".padEnd(o)} ${"LABEL".padEnd(i)} ${"ENDPOINT".padEnd(35)} EMAIL`);for(let s of n){let a=s.active?" *":"";console.log(`${(s.name+a).padEnd(o+2)} ${s.label.padEnd(i)} ${s.endpoint.padEnd(35)} ${s.email??""}`)}}),e.command("remove <name>").description("Remove a credential profile").action(r=>{let n=t.optsWithGlobals();try{if(!No(r)){let i=`Profile '${r}' not found.`;n.json?console.log(JSON.stringify({error:i})):console.error(i),process.exit(1)}if(n.json)console.log(JSON.stringify({success:!0,removed:r}));else{console.log(`Removed profile '${r}'.`);let i=qt();console.log(`Active profile: ${i}`)}}catch(o){let i=o instanceof Error?o.message:String(o);n.json?console.log(JSON.stringify({error:i})):console.error(i),process.exit(1)}}),t.command("use [name]").description("Switch active credential profile").action(r=>{let n=t.optsWithGlobals(),o=At();if(o.length===0){let i="No profiles. Run `omics-os login` first.";n.json?console.log(JSON.stringify({error:i})):console.error(i),process.exit(1)}if(!r){process.stdin.isTTY||(console.error("Profile name required in non-interactive mode."),process.exit(1)),console.log("Available profiles:");for(let i of o){let s=i.active?" (active)":"";console.log(` ${i.name}${s} \u2014 ${i.label} (${i.endpoint})`)}console.log(`
|
|
96
|
+
Usage: omics-os use <name>`);return}try{if(Ke(r),n.json)console.log(JSON.stringify({success:!0,active_profile:r}));else{let i=o.find(s=>s.name===r);console.log(`Switched to profile '${r}' (${i?.endpoint??r}).`)}}catch(i){let s=i instanceof Error?i.message:String(i);n.json?console.log(JSON.stringify({error:s})):console.error(s),process.exit(1)}})}var Wh=10*1024*1024;function zu(t){let e=t instanceof H?t.cause:t;return e instanceof TypeError&&e.message==="fetch failed"?"Cannot reach backend. Is the server running?":t instanceof Error?t.message:String(t)}function Vu(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,r=e.status_reason??null;return typeof e.status!="string"||typeof e.has_artifacts!="boolean"||r!==null&&typeof r!="string"?null:{status:e.status,status_reason:r,has_artifacts:e.has_artifacts}}function Gh(){return{textChunks:[],reasoningChunks:[],activeAgent:null,agentStatus:null,tokenUsage:null,sessionTitle:null,errorDetail:null,workerStatus:null,finishReason:null,toolCalls:[],sawValidLine:!1,textSize:0,turnOutcome:null,refusal:null}}function Bu(t,e,r,n){if(t.startsWith("aui-state:")){let a=t.slice(10),l;try{l=JSON.parse(a)}catch{return}if(!Array.isArray(l))return;e.sawValidLine=!0;for(let u of l){if(typeof u!="object"||u===null)continue;let c=u,d=c.path,p=c.value;if(Array.isArray(d)&&d.length===0&&typeof p=="object"&&p!==null){let h=Vu(p.turn_outcome);h&&(e.turnOutcome=h);continue}if(!Array.isArray(d)||d.length===0)continue;let f=d[0];if(f==="active_agent"&&(p===null||typeof p=="string"))e.activeAgent=p;else if(f==="agent_status"&&(p===null||typeof p=="string"))e.agentStatus=p;else if(f==="token_usage"&&typeof p=="object"&&p!==null)e.tokenUsage=p;else if(f==="session_title"&&typeof p=="string")e.sessionTitle=p;else if(f==="error_detail"&&typeof p=="string")e.errorDetail===null&&(e.errorDetail=p);else if(f==="turn_outcome"&&d.length===1){let h=Vu(p);h&&(e.turnOutcome=h)}else f==="worker_status"&&(p===null||typeof p=="object"&&p!==null)&&(e.workerStatus=p,n&&n(e.workerStatus))}return}let o=t.indexOf(":");if(o===-1)return;let i=t.slice(0,o),s=t.slice(o+1);if(i==="0")try{let a=JSON.parse(s);typeof a=="string"&&(e.sawValidLine=!0,e.textSize+a.length<=Wh&&(e.textChunks.push(a),e.textSize+=a.length),r&&r(a))}catch{}else if(i==="g")try{let a=JSON.parse(s);typeof a=="string"&&(e.sawValidLine=!0,e.reasoningChunks.push(a))}catch{}else if(i==="3"){e.sawValidLine=!0;let a;try{let l=JSON.parse(s);typeof l=="object"&&l!==null?a=String(l.message??l.error??JSON.stringify(l)):typeof l=="string"?a=l:a=String(l)}catch{a=s.slice(0,200)||"Unknown stream error"}e.errorDetail===null&&(e.errorDetail=`Stream error: ${a.slice(0,200)}`)}else if(i==="b")try{let a=JSON.parse(s);typeof a=="object"&&a!==null&&(e.sawValidLine=!0,e.toolCalls.push({id:a.toolCallId,name:a.toolName,status:"started"}))}catch{}else if(i==="a")try{let a=JSON.parse(s);if(typeof a=="object"&&a!==null){e.sawValidLine=!0;let l=a.toolCallId;for(let u of e.toolCalls)if(u.id===l){u.status="complete",u.resultPreview=String(a.result??"").slice(0,200);break}}}catch{}else if(i==="2")try{let a=JSON.parse(s);if(e.sawValidLine=!0,typeof a=="object"&&a!==null&&!Array.isArray(a)){let l=a;("total_cost_usd"in l||"input_tokens"in l)&&(e.tokenUsage=l)}}catch{}else if(i==="d")try{let a=JSON.parse(s);if(typeof a=="object"&&a!==null){e.sawValidLine=!0,e.finishReason=a.finishReason??null;let l=a.usage;typeof l=="object"&&l!==null&&!e.tokenUsage&&(e.tokenUsage=l)}}catch{}}async function Kh(t,e,r,n,o,i){let s=Gh(),a;try{a=await zo(t,`/sessions/${e}/chat/stream`,{body:{messages:[{role:"user",content:r}]},signal:i})}catch(d){let p=zu(d);return d instanceof w&&(s.refusal=d),s.errorDetail=(d instanceof w?$o(d):void 0)??p,s}let l=a.getReader(),u=new TextDecoder,c="";try{for(;;){let{done:p,value:f}=await l.read();if(p)break;c+=u.decode(f,{stream:!0});let h;for(;(h=c.indexOf(`
|
|
97
|
+
`))!==-1;){let _=c.slice(0,h).trim();c=c.slice(h+1),_&&Bu(_,s,n,o)}}let d=c.trim();d&&Bu(d,s,n,o)}catch(d){if(i?.aborted)s.errorDetail="Cancelled by user";else{let p=d instanceof Error?d.message:String(d);s.errorDetail=`Stream error: ${p}`}}return!s.sawValidLine&&s.errorDetail===null&&(s.errorDetail="Empty response from cloud (no valid DataStream parts received)."),s}function Hu(t){t.command("query").description("Send a single query to Omics-OS Cloud").argument("<question>","Question to ask").option("-s, --session-id <id>",'Session UUID to continue (or "latest")').addOption(new io("--token <token>","Override stored auth token").hideHelp()).option("--endpoint <url>","API base URL including /api/v1 (default https://app.omics-os.com/api/v1)").addOption(new io("--stream-endpoint <url>","Custom stream origin").hideHelp()).option("--stream","Stream text as it arrives",!1).option("-j, --json","Output JSON only on stdout",!1).option("-p, --project-id <id>","Associate session with a cloud project").action(async(e,r,n)=>{let o=n.optsWithGlobals(),i=!!(r.json||o.json),s=[],a=()=>s.length?{seed_warnings:s}:{};function l(C,A,D){let v=D?{code:D.types.error??D.code??null,retryable:D.retryable,retry_after:Hr(D)}:{};console.log(JSON.stringify({success:!1,error:C,session_id:A??null,...v,...a()}))}e.trim()||(i?l("Question cannot be empty."):process.stderr.write(`Error: Question cannot be empty.
|
|
98
|
+
`),process.exit(1));let u=r.sessionId&&r.sessionId.toLowerCase()!=="latest"?Gi(r.sessionId):null;u&&(i?l(u):process.stderr.write(`${u}
|
|
99
|
+
`),process.exit(2));let c=_e({apiUrl:r.endpoint??o.endpoint,streamApiUrl:r.streamEndpoint,sessionId:r.sessionId,projectId:r.projectId,token:r.token,cloud:!0,profile:o.profile});c.token||(i?l(qe):process.stderr.write(`${qe}
|
|
100
|
+
`),process.exit(1));let d;try{d=await di(c,C=>{s=C})}catch(C){let A=zu(C);i?l(A):process.stderr.write(`Error: ${A}
|
|
101
|
+
`),process.exit(1)}i||(process.stderr.write(`session: ${d}
|
|
102
|
+
`),s.length&&process.stderr.write(`${_r(s)}
|
|
103
|
+
`));let p=!1,f=null,h=r.stream&&!i?C=>{p=!0,process.stdout.write(C)}:void 0,_=r.stream&&!i?C=>{if(p||!C)return;let A=String(C.phase??C.status??"starting"),D=String(C.message??"Starting analysis worker"),I=`${C.transport==="ecs"?"cloud worker":"worker"}: ${A.replace(/_/g," ")} - ${D}`;I!==f&&(f=I,process.stderr.write(`${I}
|
|
104
|
+
`))}:void 0,b=new AbortController,j=()=>b.abort();process.on("SIGINT",j),process.on("SIGTERM",j);let g;try{g=await Kh(c,d,e,h,_,b.signal)}catch{i||process.stderr.write(`
|
|
105
|
+
Cancelled.
|
|
106
|
+
`);try{await Pt(c,d)}catch{}i&&l("Cancelled by user",d),process.exit(130)}finally{process.off("SIGINT",j),process.off("SIGTERM",j)}if(b.signal.aborted){i||process.stderr.write(`
|
|
107
|
+
Cancelled.
|
|
108
|
+
`);try{await Pt(c,d)}catch{}i&&l("Cancelled by user",d),process.exit(130)}if(r.stream&&!i&&process.stdout.write(`
|
|
109
|
+
`),g.turnOutcome?.status==="cancelled"){let C=g.textChunks.join("").trim();i?console.log(JSON.stringify({success:!1,cancelled:!0,error:"Cancelled",response:C,session_id:d,turn_outcome:g.turnOutcome,active_agent:g.activeAgent,token_usage:g.tokenUsage,finish_reason:g.finishReason,...a()})):(!r.stream&&C&&process.stdout.write(C+`
|
|
110
|
+
`),process.stderr.write(`Cancelled.
|
|
111
|
+
`)),process.exit(130)}g.errorDetail&&(i?l(g.errorDetail,d,g.refusal):process.stderr.write(`Error: ${g.errorDetail}
|
|
112
|
+
`),process.exit(1));let m=g.textChunks.join("").trim();if(i){console.log(JSON.stringify({success:g.agentStatus!=="error"&&g.errorDetail===null,response:m,session_id:d,active_agent:g.activeAgent,token_usage:g.tokenUsage,session_title:g.sessionTitle,finish_reason:g.finishReason,worker_status:g.workerStatus,turn_outcome:g.turnOutcome,...a()}));return}if(!r.stream){let C=(g.activeAgent??"Supervisor").replace(/_/g," ");process.stdout.write(`
|
|
113
|
+
\u2500\u2500 Lobster \xB7 ${C} \u2500\u2500
|
|
114
|
+
|
|
115
|
+
`),process.stdout.write(m+`
|
|
116
|
+
`)}let x=[`session=${d}`];if(g.tokenUsage){let C=g.tokenUsage.total_cost_usd;typeof C=="number"&&isFinite(C)&&x.push(`cost $${C.toFixed(4)}`)}x.push("continue with --session-id latest"),process.stderr.write(`
|
|
117
|
+
${x.join(" \xB7 ")}
|
|
118
|
+
`)})}import{existsSync as Wu,realpathSync as Yh,rmSync as Gu,writeFileSync as Xh}from"node:fs";import In from"node:path";var et=["lobster","editor","app","playground","biovault"],Ht=(t,e,r)=>In.join(t,r==="win32"?`${e}.cmd`:e);function Qh(t,e,r){return Xt(t,e,r).find(n=>!He(n))}var Zh=t=>`'${t.replace(/'/g,"'\\''")}'`,eg=t=>`"${t.replace(/%/g,"%%")}"`;function tg(t,e){let r=In.resolve(t);return In.basename(r)==="omics-os"?[r]:[e,r]}function rg(t,e,r,n,o=tg(process.argv[1]??"omics-os",process.execPath)){let i=[],s=[];for(let a of t){if(!et.includes(a))throw new Error(`'${a}' is not a shim; choose from ${et.join(", ")}`);let l=Qh(a,r,n);if(l){s.push({name:a,existing:l});continue}let u=n==="win32"?`@echo off\r
|
|
119
|
+
rem ${Ir}\r
|
|
120
|
+
${o.map(eg).join(" ")} ${a} %*\r
|
|
121
|
+
`:`#!/bin/sh
|
|
122
|
+
# ${Ir}
|
|
123
|
+
exec ${o.map(Zh).join(" ")} ${a} "$@"
|
|
124
|
+
`;Xh(Ht(e,a,n),u,{mode:493}),i.push(a)}return{written:i,skipped:s}}function ng(t,e){let r=[];for(let n of et){let o=Ht(t,n,e);Wu(o)&&He(o)&&(Gu(o),r.push(n))}return r}function og(t,e,r){let n=Ht(t,"lobster",r);if(!Wu(n)||!He(n))return;let o=Xt("lobster",e,r).find(i=>!Pr(i));return o&&Gu(n),o}var Ju=()=>In.dirname(process.argv[1]??".");function Ku(t){t.command("setup").description(`Optional shortcuts: ${et.join(", ")} (each runs omics-os <surface>)`).option("--shims <names>",'Comma-separated names, or "all"').option("--remove-shims","Remove the shortcuts this command wrote").option("--bin-dir <dir>","Directory for the shortcuts (default: where omics-os is installed)").action(e=>{let r=e.binDir??Ju(),n=process.env.PATH??"";if(e.removeShims){let a=ng(r,process.platform);console.log(a.length?`Removed: ${a.join(", ")}`:"No omics-os shortcuts found.");return}if(!e.shims){console.log("Optional shortcuts let you type '<surface> <verb>' instead of 'omics-os <surface> <verb>'."),console.log("Install: omics-os setup --shims all (or a list, e.g. --shims biovault,editor)"),console.log("Existing commands are never replaced; 'lobster' is skipped when the Python engine is installed.");return}let o=e.shims==="all"?[...et]:e.shims.split(",").map(a=>a.trim()).filter(Boolean),{written:i,skipped:s}=rg(o,r,n,process.platform);i.length&&console.log(`Installed in ${r}: ${i.join(", ")}`);for(let{name:a,existing:l}of s)console.log(`Skipped ${a}: already provided by ${l}`)}),t.command("doctor").description("Check this installation: version, login, Lobster engines, shortcuts").option("--bin-dir <dir>","Directory of the shortcuts (default: where omics-os is installed)").action(async e=>{let r=e.binDir??Ju(),n=process.env.PATH??"",o=O(t).profile,i=og(r,n,process.platform),s=await Promise.all(Nr().map(h=>ta(h,{env:process.env}))),a=et.filter(h=>He(Ht(r,h,process.platform))),l=Y(o),u=h=>{try{return Yh(h)}catch{return h}},c=(h,_="")=>{let b=_;for(let j of h.split(" "))b.trim()&&b.length+1+j.length>100?(console.log(b),b=` ${j}`):b=b.trim()?`${b} ${j}`:`${b}${j}`;console.log(b)},d=(h,_)=>{c(`old npm client @omicsos/lobster ${_}: not a Lobster AI engine`),console.log(` at ${u(h)}`),c("Remove it: npm uninstall -g @omicsos/lobster"," ")};console.log(`omics-os 1.3.0 (node ${process.version})`),console.log(`cloud: ${l?.endpoint??"https://app.omics-os.com"}`),console.log(`login: ${l?`yes (profile ${o??"default"})`:"no \u2014 run: omics-os login"}`);for(let h of ea())d(h.path,h.version);let p=!1,f=0;for(let h of s){if(!h.ok&&h.oldNpmClient){d(h.path,h.oldNpmClient);continue}f++,h.ok?(h.child.kill(),c(`python engine (lobster): engine_version ${h.engineVersion??"unknown"}${p?"":" \u2014 used by chat"}`),p=!0):c(`python engine (lobster): not usable: ${h.reason}`),console.log(` at ${u(h.path)}`)}f||console.log("python engine (lobster): not on PATH"),console.log(`shortcuts in ${r}: ${a.length?a.join(", "):"none"}`),i&&console.log(`Removed the lobster shortcut: the Python engine at ${i} owns 'lobster'.`)})}import{cpSync as cg,existsSync as ec,readdirSync as tc,rmSync as dg}from"node:fs";import fg from"node:os";import Jt from"node:path";import{spawn as ig,spawnSync as sg}from"node:child_process";var Yu="lobster",ag=6e4,Xu=()=>ze(process.env,{engine:!0}),lg=2e3;function ug(t,e){return new Promise(r=>{let n=ig(t,["skills","list","--json"],{env:Xu(),stdio:["ignore","pipe","ignore"]}),o="";n.stdout.setEncoding("utf8").on("data",l=>{o+=l});let i=setTimeout(()=>{e.shown||process.stderr.write(`starting the Lobster AI engine\u2026
|
|
125
|
+
`),e.shown=!0},lg),s=setTimeout(()=>n.kill("SIGKILL"),ag),a=l=>{clearTimeout(i),clearTimeout(s),r(l)};n.once("error",()=>a(null)),n.once("close",l=>{if(l!==0)return a(null);try{let u=JSON.parse(o);a(u?.schema_version==="lobster.skills/1"&&Array.isArray(u.skills)?u:null)}catch{a(null)}})})}async function bs(){let t={shown:!1};for(let e of Nr()){let r=await ug(e,t);if(r)return Yu=e,r}return null}function Qu(t){return sg(Yu,t,{env:Xu(),stdio:"inherit"}).status??1}var pg=[".claude",".agents",".codex",".cursor",".os/agent"];function ws(t){return pg.filter(e=>ec(Jt.join(t,e))).map(e=>Jt.join(t,e,"skills"))}function mg(t,e,r){let n=tc(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name).sort(),o=[];for(let i of e)for(let s of n){let a=Jt.join(i,s);r||(dg(a,{recursive:!0,force:!0}),cg(Jt.join(t,s),a,{recursive:!0})),o.push(a)}return o}var Zu="These skills cover Omics-OS Cloud. The Lobster AI engine skills (lobster-use, lobster-dev): curl -fsSL https://skills.lobsterbio.com | bash";function Pn(){return["../../../skills","../../../../skills"].map(t=>Jt.join(import.meta.dirname,t)).find(ec)??Jt.join(import.meta.dirname,"../../../skills")}function rc(t){let e=t.command("skills").description("Agent skills for omics-os (Claude Code, Codex, Cursor, Pi and others)");e.command("list").description("List the omics-os skills and, when a Lobster AI engine is installed, its skills").option("--json","Print JSON").action(async(r,n)=>{let o=n.optsWithGlobals().json,i=tc(Pn(),{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name).sort(),s=await bs();if(o){console.log(JSON.stringify({schema_version:"omics-os.skills/1",skills:i,engine:s},null,2));return}console.log("omics-os skills:");for(let a of i)console.log(` ${a}`);if(!s)return void console.log(Zu);console.log("Lobster AI engine skills:");for(let a of s.skills)console.log(` ${a.name}`)}),e.command("install").description("Copy the omics-os skills into every detected agent harness").option("--target <dir>","Install into this skills directory only").option("--dry-run","Show what would be written").action(async r=>{let n=r.target?[r.target]:ws(fg.homedir());n.length||(console.error("No agent harness found in your home directory. Use --target <skills dir>."),process.exit(1));for(let i of mg(Pn(),n,!!r.dryRun))console.log(`${r.dryRun?"would write":"wrote"} ${i}`);if(!await bs())return void console.log(Zu);let o=Qu(["skills","install",...r.target?["--target",r.target]:[],...r.dryRun?["--dry-run"]:[]]);o!==0&&process.exit(o)})}import{realpathSync as hg}from"node:fs";import Or from"node:path";import{spawnSync as gg}from"node:child_process";var nc=["npm","install","-g","omics-os@latest"];function vs(t,e){let r=`${Or.sep}node_modules${Or.sep}omics-os${Or.sep}`,n=t.indexOf(r);if(n<0)return;let o=t.slice(0,n),i=Or.resolve(e);if(!(i===o||i.startsWith(o+Or.sep)))return nc}function _g(t,e,r){let n=vs(e,r);if(n||(process.stderr.write(`\u26A0 Could not tell how omics-os was installed, so nothing was changed.
|
|
126
|
+
`),process.stderr.write(` Update manually with: ${nc.join(" ")}
|
|
127
|
+
`),process.exit(1)),t.dryRun){console.log(n.join(" "));return}console.log(`Running: ${n.join(" ")}`);let o=process.platform==="win32",s=gg(o?"npm.cmd":"npm",n.slice(1),{stdio:"inherit",shell:o}).status??1;s!==0&&(process.stderr.write(`\u26A0 npm install failed (exit ${s}); nothing was changed.
|
|
128
|
+
`),process.stderr.write(` Your current omics-os keeps working. Check: npm view omics-os version
|
|
129
|
+
`)),process.exit(s)}function oc(t){t.command("upgrade").description("Upgrade omics-os to the latest release").option("--dry-run","Print the command without running it").action(e=>{let r=process.argv[1]??"";try{r=hg(r)}catch{}_g(e,r,process.cwd())})}import{existsSync as Nn,lstatSync as Ln,readdirSync as xs,readFileSync as yg,realpathSync as bg,rmdirSync as wg,rmSync as vg,unlinkSync as Sg}from"node:fs";import kg from"node:os";import gt from"node:path";import{spawnSync as xg}from"node:child_process";import{createInterface as Eg}from"node:readline/promises";var Cg=["npm","uninstall","-g","omics-os"];function ic(t){let e=t.indexOf("_");return`${e>0?t.slice(0,e+1):""}\u2026${t.slice(-4)}`}var sc=t=>{try{return new URL(t).host}catch{return t}},Ss={"credentials.json":"sign-in and profiles",biovault:"BioVault run start records",history:"chat input history"};function qg(t,e){try{let r=yg(gt.join(t,"SKILL.md"),"utf8");return/^name:\s*(\S+)\s*$/m.exec(r)?.[1]===e}catch{return!1}}function Ag(t,e){let r=gt.join(t.home,".config","omics-os"),n=[],o=[],i=[];if(!e.keepCredentials){let u=ge();for(let[c,d]of Object.entries(u?.profiles??{}))d.auth_mode==="oauth"&&d.credential_id?n.push({kind:"revoke",profile:c,host:sc(d.endpoint),id:ic(d.credential_id)}):d.auth_mode==="api_key"&&d.api_key&&n.push({kind:"api_key",profile:c,host:sc(d.endpoint),id:ic(d.api_key)})}let s;try{s=Ln(r)}catch{s=void 0}if(s?.isSymbolicLink())i.push({path:r,note:"a link to somewhere else; the files behind it stay"});else if(s&&!s.isDirectory())i.push({path:r,note:"not a directory"});else if(s){for(let u of Object.keys(Ss)){if(e.keepCredentials&&u==="credentials.json")continue;let c=gt.join(r,u),d;try{d=Ln(c)}catch{continue}let p=u==="credentials.json"&&n.length?`sign-in and ${n.length} profile${n.length===1?"":"s"}`:Ss[u];o.push({path:c,note:d.isSymbolicLink()?`${p} (a link; only the link goes)`:p,link:d.isSymbolicLink()})}for(let u of xs(r))Object.hasOwn(Ss,u)||i.push({path:gt.join(r,u),note:"not written by this version of omics-os"})}for(let u of[...et].sort()){let c=Ht(t.binDir,u,t.platform);Nn(c)&&He(c)&&o.push({path:c,note:"shortcut from omics-os setup"})}let a=Nn(t.skillsSource)?xs(t.skillsSource,{withFileTypes:!0}).filter(u=>u.isDirectory()).map(u=>u.name).sort():[];for(let u of ws(t.home))for(let c of a){let d=gt.join(u,c);Nn(d)&&qg(d,c)&&o.push({path:d,note:"skill copied by omics-os skills install"})}let l={signOut:n,configDir:r,files:o,leftovers:i};return vs(t.script,t.cwd)?l.packageCommand=Cg:l.packageNote=`omics-os runs from ${t.script}, not from a global npm install. Remove it the way it was installed (npm unlink -g omics-os for a linked checkout).`,l}var ks=(t,e)=>t.startsWith(e+gt.sep)?`~${t.slice(e.length)}`:t;function Og(t,e,r){let{paint:n}=r,o=[`${n.bold("omics-os uninstall")}${r.dryRun?` ${n.meta("(dry run: nothing is changed)")}`:""}`,""],i=1;if(t.signOut.length){o.push(n.bold(`${i++} Sign out`));for(let s of t.signOut)s.kind==="revoke"?o.push(` revoke CLI sign-in ${n.dim(s.id)} on ${s.host} ${n.dim(`(profile ${s.profile})`)}`):o.push(` ${n.meta("\u26A0")} API key ${n.dim(s.id)} on ${s.host} cannot be revoked from here: Account \u2192 API Keys ${n.dim(`(profile ${s.profile})`)}`);o.push("")}if(t.files.length){o.push(n.bold(`${i++} Remove files`));let s=Math.max(...t.files.map(a=>ks(a.path,e.home).length));for(let a of t.files)o.push(` ${ks(a.path,e.home).padEnd(s)} ${n.dim(a.note)}`);o.push("")}return t.leftovers.length&&o.push(n.bold("Left in place"),...t.leftovers.map(s=>` ${ks(s.path,e.home)} ${n.dim(s.note)}`),""),o.push(n.bold(`${i++} Remove the package`)),o.push(t.packageCommand?` ${t.packageCommand.join(" ")}`:` ${n.meta("\u26A0")} ${t.packageNote}`),o.push(""),o.push(n.bold("Kept"),` ~/.lobster, ~/.config/lobster, workspaces ${n.dim("Lobster AI engine: lobster purge")}`),o.push("","Close any running omics-os lobster chat first: an open chat writes its history file back."),r.dryRun&&o.push("","Run without --dry-run to do this."),o.join(`
|
|
130
|
+
`)}function $g(t){let e=Ln(t);e.isSymbolicLink()||!e.isDirectory()?Sg(t):vg(t,{recursive:!0,force:!0})}async function Tg(t,e){let r=[];for(let n of t.signOut){if(n.kind!=="revoke")continue;let o=!1;try{o=(await mr({profile:n.profile})).revoked}catch{o=!1}o||r.push(`Sign-in ${n.id} on ${n.host} is still valid on the server (revoke failed). Revoke it in your account settings on ${n.host}.`)}for(let n of t.files)try{$g(n.path)}catch(o){r.push(`${n.path}: ${o.message}`)}try{let n=Nn(t.configDir)?Ln(t.configDir):void 0;n&&!n.isSymbolicLink()&&n.isDirectory()&&xs(t.configDir).length===0&&wg(t.configDir)}catch(n){r.push(`${t.configDir}: ${n.message}`)}if(t.packageCommand){let n=e.platform==="win32",o=xg(n?"npm.cmd":"npm",t.packageCommand.slice(1),{stdio:"inherit",shell:n});(o.status??1)!==0&&r.push(`${t.packageCommand.join(" ")} exited with ${o.status??"a signal"}; the package is still installed.`)}return r}function Rg(){let t=process.argv[1]??"";try{t=bg(t)}catch{}return{home:kg.homedir(),binDir:gt.dirname(process.argv[1]??"."),platform:process.platform,script:t,cwd:process.cwd(),skillsSource:Pn()}}function ac(t,e=Rg){t.command("uninstall").description("Remove omics-os, its sign-in and shortcuts from this computer").option("-n, --dry-run","List every path and command; change nothing").option("-y, --yes","Do not ask for confirmation (needed when not on a terminal)").option("--keep-credentials","Keep your sign-in and profiles; remove the rest").option("--bin-dir <dir>","Directory of the shortcuts (default: where omics-os is installed)").action(async r=>{let n={...e(),...r.binDir?{binDir:r.binDir}:{}},o=t.opts().color===!1,i=new nt(ot(process.stdout,{noColor:o,env:process.env}).color),s=Ag(n,{keepCredentials:!!r.keepCredentials});if(console.log(Og(s,n,{dryRun:!!r.dryRun,paint:i})),r.dryRun)return;if(!r.yes){(!process.stdin.isTTY||!process.stdout.isTTY)&&(process.stderr.write(`Not a terminal: add --yes to confirm. Nothing was changed.
|
|
131
|
+
`),process.exit(2));let l=Eg({input:process.stdin,output:process.stdout}),u=await l.question(`
|
|
132
|
+
Remove all of this? [y/N] `);l.close(),/^y(es)?$/i.test(u.trim())||(console.log("Nothing changed."),process.exit(1))}console.log("");let a=await Tg(s,{keepCredentials:!!r.keepCredentials,platform:n.platform});for(let l of a)process.stderr.write(`${i.red("\u2717")} ${l}
|
|
133
|
+
`);console.log(a.length?`omics-os uninstall finished with ${a.length} problem${a.length===1?"":"s"} (above).`:`omics-os removed.${r.keepCredentials?" Your sign-in was kept.":""} The Lobster AI engine, if installed, is untouched: lobster purge removes it.`),process.exit(a.length?1:0)})}import{lstat as jg,readdir as Ig}from"node:fs/promises";import Pg from"node:path";function Ng(t,e=process.platform){let r="";for(let n=0;n<t.length;n++){let o=t[n];o==="*"&&t[n+1]==="*"?(n++,t[n+1]==="/"?(n++,r+="(?:.*/)?"):r+=".*"):o==="*"?r+="[^/]*":o==="?"?r+="[^/]":r+=o.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${r}$`,e==="win32"?"i":"")}function lc(t,e,r=process.platform){if(!e.length)return!0;let n=t.slice(t.lastIndexOf("/")+1);return e.some(o=>{let i=r==="win32"?o.replaceAll("\\","/"):o;return Ng(i,r).test(i.includes("/")?t:n)})}var Lg={path:Pg,platform:process.platform,lstat:jg,readdir:t=>Ig(t,{withFileTypes:!0})};async function Dg(t,e,r=Lg){let{path:n,platform:o}=r,i=[],s=[],a=async(l,u)=>{let c=await r.lstat(l);if(c.isSymbolicLink()){lc(u,e,o)&&s.push({relativePath:u,reason:"link"});return}if(c.isDirectory()){let d=await r.readdir(l);d.sort((p,f)=>p.name<f.name?-1:p.name>f.name?1:0);for(let p of d)await a(n.join(l,p.name),`${u}/${p.name}`);return}lc(u,e,o)&&(c.isFile()?c.size===0?s.push({relativePath:u,reason:"empty"}):i.push({path:l,relativePath:u,size:c.size}):s.push({relativePath:u,reason:"not_regular"}))};for(let l of t){let u=n.resolve(l);await a(u,n.basename(u).split(n.sep).join("/")||"upload")}return{files:i,skipped:s}}function Es(t=process.argv.slice(2)){let e=r=>/^[\w./:=@%+,-]+$/.test(r)?r:`"${r.replace(/"/g,'\\"')}"`;return["omics-os",...t.map(e)].join(" ")}var uc={empty:"skipped: empty file",link:"skipped: link (not followed)",not_regular:"skipped: not a regular file"},Ug={file_exists:"exists in the project with different content; run again with --replace to overwrite it (the old version is kept for 30 days)",upload_in_progress:"another upload to this path is unfinished on Omics-OS Cloud; if it is an earlier run of yours and the file has changed since, run again with --replace to cancel it and start over"},Mg=new Set(["file_exists","upload_in_progress","invalid_path","upload_too_large"]),Fg={expired:"sent again from the start (the unfinished upload had expired on Omics-OS Cloud)",complete_conflict:"sent again from the start (another write to this path interfered as it completed)"};function tt(t,e,r,n){return q(()=>Promise.reject(me(e,r,n)),t)}function cc(t){t.command("upload").description("Upload files or folders to a project on Omics-OS Cloud (resumable)").argument("<paths...>","Files or folders to upload").requiredOption("--project <id>","Project to upload into").option("--include <pattern>",'Only files matching this pattern, e.g. "*.pod5" (repeatable)',(e,r=[])=>[...r,e]).option("--dry-run","List the files and the total size; send nothing").option("--concurrency <n>",`Parts sent at once (1-${dt}, default ${vr})`).option("--replace","Overwrite a different file already in the project at the same path (the old version is kept for 30 days)").action(async(e,r)=>{let n=O(t),o=n.json,i=r.include??[],s=r.concurrency===void 0?vr:Number(r.concurrency);(!Number.isInteger(s)||s<1||s>dt)&&await tt(o,"usage",2,`--concurrency must be a whole number from 1 to ${dt}.`),r.project.trim()||await tt(o,"usage",2,"--project needs a project ID.");let a;try{a=await Dg(e,i)}catch(k){let T=k;if(T.code==="ENOENT")return tt(o,"usage",2,`No such file or folder: ${T.path??""}`);if(T.code==="EACCES"||T.code==="EPERM")return tt(o,"usage",2,`Cannot read ${T.path??"a file"}: permission denied.`);throw k}let{files:l,skipped:u}=a,c=new Map;for(let k of l){let T=c.get(k.relativePath);T&&await tt(o,"usage",2,`Two files would upload as ${k.relativePath}: ${T} and ${k.path}. Upload them separately.`),c.set(k.relativePath,k.path)}!l.length&&!u.length&&await tt(o,"usage",2,i.length?"No files match --include.":"No files to upload.");let d=l.reduce((k,T)=>k+T.size,0);if(r.dryRun){o?$({project_id:r.project,dry_run:!0,files:l.map(k=>({path:k.relativePath,size_bytes:k.size})),skipped:u.map(k=>({path:k.relativePath,reason:k.reason})),totals:{files:l.length,bytes:d}}):console.log(["Dry run: nothing was sent.",`Would upload ${l.length} ${l.length===1?"file":"files"} (${G(d)}) to project ${r.project}`,...l.map(k=>` ${k.relativePath} ${G(k.size)}`),...u.map(k=>` ${k.relativePath} ${uc[k.reason]}`)].join(`
|
|
134
|
+
`));return}let p=R(n);p.token||await q(()=>Promise.reject(new M("/uploads")),o);let f=new AbortController,h=!1,_=()=>{h&&process.exit(130),h=!0,f.abort(new Error("interrupted"))};process.on("SIGINT",_),process.on("SIGTERM",_);let b=u.map(k=>({path:k.relativePath,size_bytes:null,outcome:"skipped",reason:k.reason}));if(!o)for(let k of u)console.log(`${k.relativePath} ${uc[k.reason]}`);let j=!!process.stderr.isTTY&&!o,g=new Map,m=0,x=(k=!1)=>{if(!j)return;let T=Date.now();if(!k&&T-m<250)return;m=T;let xe=[...g.values()].reduce((Ee,Un)=>Ee+Un,0),V=d?Math.floor(xe/d*100):100;process.stderr.write(`\r\x1B[2KUploading: ${G(xe)} of ${G(d)} (${V}%)`)},C=()=>{j&&process.stderr.write("\r\x1B[2K")},A=k=>{o||(C(),console.log(k),x(!0))},D=dn(s),v,S,I,L=!1,te=[...l],ce=async k=>{try{let T=await Ri(p,{projectId:r.project,path:k.path,relativePath:k.relativePath,concurrency:s,limiter:D,replace:r.replace===!0,signal:f.signal,onProgress:Ee=>{Ee.phase==="send"&&(g.set(k.relativePath,Ee.bytes),x())}});g.set(k.relativePath,k.size);let xe={path:k.relativePath,size_bytes:T.sizeBytes,outcome:T.outcome,relative_path:T.relativePath,version_id:T.versionId??null,parts_sent:T.partsSent,parts_reused:T.partsReused,...T.outcome==="skipped"?{reason:"already_in_project"}:{},...T.match?{match:T.match}:{},...T.restarted?{restarted:T.restarted}:{},...T.resumeTrust?{resume_trust:T.resumeTrust}:{}};b.push(xe);let V=T.outcome==="skipped"?"skipped: already in the project (same path, size and fingerprint)":T.outcome==="resumed"?`resumed (${T.partsReused} parts already there, ${T.partsSent} sent)`:T.restarted?Fg[T.restarted]:"sent";A(`${k.relativePath} ${G(k.size)} ${V}`)}catch(T){if(f.signal.aborted&&(h||v||S||I)){b.push({path:k.relativePath,size_bytes:k.size,outcome:"failed",reason:"interrupted"});return}if(qi(T)){v??=T,f.abort(T);return}if(T instanceof M){S??=T,f.abort(T);return}let xe=ui(T,r.project);if(xe){I??=xe,f.abort(T);return}let V=T instanceof J?T.reason:"server";V==="quota_exceeded"&&(L=!0);let Ee=!r.replace&&Ug[V]||(T instanceof Error?T.message:String(T)),Un=T instanceof J&&T.versionId?{version_id:T.versionId}:{};b.push({path:k.relativePath,size_bytes:k.size,outcome:"failed",reason:V,error:Ee,...Un}),A(`${k.relativePath} ${G(k.size)} failed: ${Ee}`)}},N=Array.from({length:Math.min(s,l.length)},async()=>{for(let k=te.shift();k&&!f.signal.aborted;k=L?void 0:te.shift())await ce(k)});try{await Promise.all(N)}finally{process.off("SIGINT",_),process.off("SIGTERM",_),C()}if(S)return q(()=>Promise.reject(S),o);if(v)return tt(o,"unavailable",1,"Uploads are not enabled for this organisation on Omics-OS Cloud yet. Contact support@omics-os.com.");if(I)return tt(o,"project",1,I);for(let k of te)b.push({path:k.relativePath,size_bytes:k.size,outcome:"failed",reason:L?"quota_exceeded":"interrupted"}),L&&!o&&console.log(`${k.relativePath} ${G(k.size)} not started: over the organisation's storage quota (see above)`);let z=k=>b.filter(T=>T.outcome===k).length,Z={files:b.length,sent:z("sent"),resumed:z("resumed"),skipped:z("skipped"),failed:z("failed"),bytes:d};if(o)$({project_id:r.project,files:b,totals:Z,...h?{interrupted:!0,resume:Es()}:{}});else if(h)console.error(["Stopped. Parts already sent are kept for 7 days from the start of each file's upload. To resume, run the same command again:",` ${Es()}`].join(`
|
|
135
|
+
`));else{let k=[`${Z.sent} sent`,`${Z.resumed} resumed`,`${Z.skipped} skipped`,`${Z.failed} failed`];console.log(`${k.join(", ")} (${G(d)}) to project ${r.project}`),b.some(T=>T.outcome==="failed"&&!Mg.has(T.reason??""))&&console.log(`Run the same command again to retry; finished files are skipped:
|
|
136
|
+
${Es()}`)}h&&process.exit(130),Z.failed&&process.exit(1)})}var dc=["query","chat","agents list","agents info","projects list","projects info"],Vg=["cloud chat","cloud query"],Bg=["session","files","export","vector","projects download","projects create","agents push","agents download"],zg={query:"Send a single query to Omics-OS Cloud",chat:"Start interactive chat: Omics-OS Cloud by default, --backend local for a local engine (experimental)","agents list":"List agents available on Omics-OS Cloud","agents info":"Show an agent from the Omics-OS Cloud catalogue","projects list":"List your Omics-OS Cloud projects","projects info":"Show an Omics-OS Cloud project with its datasets and sessions"},fc={query:{same:["question","stream"],differentMeaning:[{arg:"session-id",engine:"a saved session in the local workspace (or latest)",cloud:"an Omics-OS Cloud session UUID (or latest)"},{arg:"json",engine:"prints lobster.result/1",cloud:"prints the Cloud query reply as JSON (not checked against lobster.result/1)"}],engineOnly:["workspace","reasoning","verbose","debug","output","profile-timings","provider","model"]},chat:{same:["workspace","provider","model"],differentMeaning:[{arg:"session-id",engine:"a saved local session (also with --backend local)",cloud:"an Omics-OS Cloud session (default backend)"}],engineOnly:["reasoning","verbose","debug","profile-timings","no-intro","stream","ui","classic"]},"agents list":{same:[],differentMeaning:[],engineOnly:["workspace"]},"agents info":{same:[],differentMeaning:[{arg:"agent_name",engine:"an agent installed in the local engine",cloud:"an agent in the Omics-OS Cloud catalogue"}],engineOnly:[],cloudName:{agent_name:"name"}},"projects list":{same:[],differentMeaning:[{arg:"json",engine:"prints the lobster.project/1 listing (projects, total)",cloud:"prints the Cloud project list (success, message, projects with the info project fields, total)"}],engineOnly:[]},"projects info":{same:[],differentMeaning:[{arg:"folder",engine:"a project folder (default: the project around the current folder)",cloud:"an Omics-OS Cloud project id"},{arg:"json",engine:"prints lobster.project/1 (project, local)",cloud:"prints the Cloud project block (lobster.project/1 project fields) with its datasets and sessions"}],engineOnly:[],cloudName:{folder:"project-id"}}};function pc(t){return t.commands.filter(e=>e.surfaces.includes("cli")&&e.scientist_facing)}function mc(t=Je){return pc(t).filter(e=>dc.includes(e.name))}function hc(t=Je){return[...new Set(t.commands.filter(e=>e.surfaces.includes("cli")).map(e=>e.name.split(" ")[0]))]}function Cs(t=Je){return pc(t).map(e=>e.name).filter(e=>!dc.includes(e)&&!Vg.includes(e))}function gc(t){return zg[t.name]??t.help??""}function _c(t=Je){let e=Cs(t).map(r=>`lobster ${r}`).join(", ");return["",`Cloud only: ${Bg.join(", ")}`,...e?[`On your machine (Lobster AI engine): ${e}`]:[]].join(`
|
|
137
|
+
`)}function yc(t){return t.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").slice(0,128)}function bc(t){let e=t.status===null?"no response":String(t.status),r=t.requestId?` (request ${yc(t.requestId)})`:"";return`${t.method} ${yc(t.path)} \u2192 ${e}${r}`}function Os(t){return t.error?1:t.status!==null?t.status:t.signal==="SIGINT"?130:t.signal==="SIGTERM"?143:1}function vc(t,e){let r=[],n;for(let o=0;o<t.length;o++){let i=t[o];if(i==="--token"){n=t[++o];continue}if(i.startsWith("--token=")){n=i.slice(8);continue}r.push(i)}return{args:r,token:n??e.LOBSTER_CLOUD_TOKEN}}function Hg(t){return{...ze(process.env),LOBSTER_TOKEN:t}}var Jg=t=>t.some(e=>e==="--api-url"||e.startsWith("--api-url="));function Sc(t,e){(!process.stdin.isTTY||!process.stdout.isTTY)&&(process.stderr.write(`Error: omics-os lobster chat requires an interactive terminal.
|
|
138
|
+
`),process.exit(1));let{args:r,token:n}=vc(t.filter(l=>l!=="--cloud"),process.env),o=n??Me()?.value;!o&&!Y(e.profile)&&(process.stderr.write(`${qe}
|
|
139
|
+
`),process.exit(1));let i=e.endpoint&&!Jg(r)?["--api-url",e.endpoint]:[],s=qs.join(import.meta.dirname,"../../tui/dist/lobster.mjs"),a=As(process.execPath,[s,"--cloud",...e.profile?["--profile",e.profile]:[],...i,...r],{stdio:"inherit",env:o?Hg(o):ze(process.env)});process.exit(Os(a))}function Wg(t){let e=new Set(fc.chat.engineOnly.map(r=>`--${r}`));return t.map(r=>r.split("=")[0]).find(r=>e.has(r))}function Gg(t){let e="cloud",r=[];for(let n=0;n<t.length;n++){let o=t[n];o==="--backend"?e=t[++n]??"":o.startsWith("--backend=")?e=o.slice(10):r.push(o)}return{backend:e,args:r}}function Kg(t,e){(!process.stdin.isTTY||!process.stdout.isTTY)&&(process.stderr.write(`Error: omics-os lobster chat requires an interactive terminal.
|
|
140
|
+
`),process.exit(1));let{args:r,token:n}=vc(t,{});n!==void 0&&process.stderr.write(`Note: --token is ignored with --backend local; the local engine needs no Omics-OS token.
|
|
141
|
+
`),e!==void 0&&process.stderr.write(`Note: --endpoint is ignored with --backend local; the local engine does not use Omics-OS Cloud.
|
|
142
|
+
`);let o=ze(process.env,{engine:!0}),i=qs.join(import.meta.dirname,"../../tui/dist/lobster.mjs"),s=As(process.execPath,[i,"--backend","local",...r],{stdio:"inherit",env:o});process.exit(Os(s))}function wc(t,e){let r=new Map(mc(e).map(n=>[n.name,gc(n)]));Jl(t),du(t,{list:r.get("projects list"),info:r.get("projects info")}),Vl(t),pu(t),mu(t,{list:r.get("agents list"),info:r.get("agents info")}),Fu(t),r.has("query")&&(Hu(t),t.commands.find(n=>n.name()==="query").description(r.get("query"))),t.addHelpText("after",()=>da(t,_c(e))),r.has("chat")&&t.command("chat").description(r.get("chat")).allowUnknownOption().allowExcessArguments().helpOption(!1).action((n,o)=>{if(o.args.some(u=>u==="--help"||u==="-h")){let u=qs.join(import.meta.dirname,"../../tui/dist/lobster.mjs");process.exit(Os(As(process.execPath,[u,"--help"],{stdio:"inherit"})))}let i=Wg(o.args);i&&(process.stderr.write(`omics-os lobster chat does not take ${i}: it is a Lobster AI engine option (lobster chat ${i}).
|
|
143
|
+
`),process.exit(2));let{backend:s,args:a}=Gg(o.args),l=o.optsWithGlobals();s==="local"&&Kg(a,l.endpoint),s!=="cloud"&&(process.stderr.write(`Unknown backend "${s}". Use --backend local|cloud.
|
|
144
|
+
`),process.exit(2)),Sc(a,l)})}function Dn(t,e,r){let n=e[0]??"",o=Dr(t),i=po(t).red("\u2717"),[,s,...a]=o.split(" "),l=[...a,n].join(" ");if(["lobster","cloud"].includes(s??"")&&Cs(r).includes(l))process.stderr.write(`${i} ${l} runs on your machine with the Lobster AI engine: lobster ${l}
|
|
145
|
+
`);else{process.stderr.write(`${i} Unknown command: ${o} ${e.join(" ")}
|
|
146
|
+
`);let u=t.commands.filter(d=>!d._hidden).flatMap(d=>[d.name(),...d.aliases()]),c=ua(n,u);c&&process.stderr.write(`Did you mean '${c}'?
|
|
147
|
+
`),process.stderr.write(`Run: ${o} --help
|
|
148
|
+
`),!t.parent&&hc(r).includes(n)&&process.stderr.write(`Local Lobster AI commands run in the Python engine: lobster ${e.join(" ")}
|
|
149
|
+
`)}process.exit(2)}function kc(t,e){t.commands.length&&t.on("command:*",r=>Dn(t,r,e)),t.hook("preSubcommand",(r,n)=>{let o=r.args[0];o&&!o.startsWith("-")&&o!==n.name()&&!n.aliases().includes(o)&&Dn(r,r.args,e)});for(let r of t.commands)kc(r,e)}function xc(t){t.exitOverride(e=>{e.exitCode===0&&process.exit(0),e.code!=="commander.help"&&process.stderr.write(`Run: ${Dr(t)} --help
|
|
150
|
+
`),process.exit(2)});for(let e of t.commands)xc(e)}function Ec(t=Je){let e=new Lr;e.name("omics-os").description("Omics-OS Cloud command line").option("-V, --version","Print the version").on("option:version",()=>{console.log("omics-os 1.3.0 (Omics-OS Cloud client)"),process.exit(0)}),e.option("--json","Machine-readable output on stdout"),e.option("--endpoint <url>","API base URL including /api/v1 (default https://app.omics-os.com/api/v1)"),e.option("--no-color","Plain output (also NO_COLOR=1, or when piped)"),e.option("--verbose","Print each API request to stderr (not cloud chat or file transfers)"),e.hook("preAction",()=>{e.opts().verbose&&Bo(o=>{process.stderr.write(`${bc(o)}
|
|
151
|
+
`)})}),e.option("--profile <name>","Use this credential profile"),gs(e),_s(e),ys(e),Ku(e),rc(e),oc(e),ac(e);let r=e.command("lobster").description("Lobster AI sessions on Omics-OS Cloud");wc(r,t),cc(e),Rn(e,"biovault"),hs(e);for(let[o,i,s]of[["app","Omics-OS Cloud workspace","https://app.omics-os.com"],["playground","Agent Playground","https://playground.omics-os.com"]])e.command(o).description(`${i} (prints ${s})`).allowExcessArguments().action((a,l)=>{l.args.length&&Dn(l,l.args,t),console.log(s)});let n=e.command("cloud",{hidden:!0});return wc(n,t),Rn(n),hs(n),gs(n),_s(n),ys(n),e.command("chat",{hidden:!0}).allowUnknownOption().allowExcessArguments().helpOption(!1).action((o,i)=>{i.args.includes("--cloud")||(process.stderr.write(`Local chat runs in the Python engine: lobster chat
|
|
152
|
+
`),process.stderr.write(`Cloud chat: omics-os lobster chat
|
|
153
|
+
`),process.exit(2)),Sc(i.args,i.optsWithGlobals())}),e.command("capabilities",{hidden:!0}).action(()=>console.log(JSON.stringify({"token-env":!0}))),e.allowExcessArguments().action((o,i)=>{i.args.length&&Dn(i,i.args,t);let s=i.optsWithGlobals(),a="1.3.0",l=Me(),u=Y(s.profile),c=p=>{try{return new URL(p).host}catch{return p}},d=l?{host:c(u?.endpoint??"https://app.omics-os.com"),fromEnv:l.name}:u?{email:u.email,host:c(u.endpoint),profile:s.profile??ge()?.active_profile}:void 0;if(s.json){console.log(JSON.stringify({version:a,signed_in:!!d,...d?{email:d.email,host:d.host,profile:d.profile,env:d.fromEnv}:{},help:"omics-os --help"}));return}process.stdout.write(ca({version:a,signedIn:d},ot(process.stdout,{noColor:s.color===!1,env:process.env})))}),kc(e,t),xc(e),mo(e),e}Ec().parseAsync().catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
|
|
154
|
+
`),process.exit(1)});
|