@zenon-red/probe 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import{defineCommand as t,runMain as n}from"citty";import{Buffer as r}from"node:buffer";import{arch as i,homedir as a,platform as o}from"node:os";import{dirname as s,join as c,resolve as l}from"node:path";import{loadConfig as u}from"c12";import{access as d,mkdir as f,readFile as p,readdir as m,unlink as ee,writeFile as h}from"node:fs/promises";import{confirm as te,log as ne,password as re,spinner as ie,text as ae}from"@clack/prompts";import{AsyncLocalStorage as oe}from"node:async_hooks";import{blue as se,bold as ce,cyan as le,dim as ue,gray as de,green as fe,white as pe}from"kolorist";import{KeyFile as me,KeyStore as he}from"znn-typescript-sdk";import{DbConnectionBuilder as ge,DbConnectionImpl as _e,SubscriptionBuilderImpl as ve,convertToAccessorMap as ye,makeQueryBuilder as be,procedureSchema as xe,procedures as Se,reducerSchema as g,reducers as Ce,schema as we,t as _,table as v}from"spacetimedb";import{encode as Te}from"@toon-format/toon";import{createWriteStream as Ee,existsSync as De,readFileSync as Oe,renameSync as ke,unlinkSync as Ae}from"node:fs";import{createConsola as je}from"consola";import{execSync as Me}from"node:child_process";import{createHash as Ne}from"node:crypto";import{Readable as Pe}from"node:stream";import{finished as Fe}from"node:stream/promises";const Ie={issuer:`https://api.zenon.red`,walletDir:`~/.probe/wallets`,passwordMinLength:8,tokenCacheDir:`~/.probe/tokens`,requestTimeout:3e4,spacetime:{host:`wss://db.zenon.red`,module:`nexus`}},Le=c(a(),`.probe`,`config.json`),Re=c(a(),`.probe`);async function y(){try{await d(Le);let e=await p(Le,`utf-8`);return JSON.parse(e)}catch{return{}}}async function ze(e){await f(Re,{recursive:!0}),await h(Le,JSON.stringify(e,null,2),{mode:384})}let b=null;async function x(){if(b)return b;let[e,t]=await Promise.all([u({name:`probe`,defaults:Ie,envName:`PROBE`}),y()]);return b={...Ie,...e.config,...t},b.walletDir=Ve(b.walletDir),b.tokenCacheDir=Ve(b.tokenCacheDir),b}function Be(){b=null}function Ve(e){return e.startsWith(`~/`)?c(a(),e.slice(2)):e}async function He(){return(await x()).walletDir}async function Ue(){return(await x()).tokenCacheDir}const We=new oe,Ge=(e,t)=>typeof t==`bigint`?t.toString():t,Ke=(e,t=!1)=>{let n=JSON.stringify(e,Ge,2);if(t){console.error(n);return}console.log(n)};function S(e){We.enterWith({jsonMode:e})}function C(){return We.getStore()?.jsonMode===!0}function w(e){C()&&Ke({success:!0,data:e})}function T(e,t,n,r=1){C()?(Ke({success:!1,error:{code:e,message:t,...n&&{suggestion:n}}},!0),process.exit(r)):(ne.error(t),n&&console.error(`${ue(`hint:`)} ${n}`),process.exit(r))}function E(e){C()||ne.info(e)}function D(e){C()||ne.success(e)}function qe(e){C()||ne.warn(e)}function Je(e){if(C())return{start:()=>{},stop:()=>{},succeed:()=>{},fail:()=>{}};let t=ie();return{start:()=>{t.start(e)},stop:()=>{t.stop()},succeed:n=>{t.stop(n||e)},fail:n=>{t.stop(n||e)}}}const Ye=async(e,t)=>{try{return(await p(e,`utf-8`)).trim()}catch{T(`FILE_READ_ERROR`,`Failed to read ${t} file: ${e}`)}},Xe=async e=>{if(e.passwordFile)return Ye(e.passwordFile,`password`);let t=e.envVar||`PROBE_WALLET_PASSWORD`,n=process.env[t];if(n)return n;(C()||!process.stdin.isTTY||!process.stdout.isTTY)&&T(`PASSWORD_REQUIRED`,e.jsonModeError);let r=await re({message:e.promptMessage,validate:t=>{if(t&&e.minLength&&t.length<e.minLength)return`Password must be at least ${e.minLength} characters`}});return typeof r!=`string`&&process.exit(130),e.confirmPromptMessage&&typeof await re({message:e.confirmPromptMessage,validate:e=>e===r?void 0:`Passwords do not match`})!=`string`&&process.exit(130),r},Ze=async e=>{if(e.mnemonic)return e.mnemonic;if(e.mnemonicFile)return Ye(e.mnemonicFile,`mnemonic`);let t=e.envVar||`PROBE_WALLET_MNEMONIC`,n=process.env[t];if(n)return n;(C()||!process.stdin.isTTY||!process.stdout.isTTY)&&T(`MNEMONIC_REQUIRED`,e.jsonModeError);let r=await ae({message:`Enter mnemonic phrase:`,validate:e=>e&&e.trim().split(/\s+/).length===24?void 0:`Mnemonic must be 24 words`});return typeof r!=`string`&&process.exit(130),r},Qe=new Set([`agent`,`task`,`message`,`idea`,`discover`,`project`,`config`]),$e=new Set([`wallet`,`auth`,`sign`,`token`,`nexus`,`query`,`doctor`,`upgrade`]),et=new Set([`create`,`import`,`list`,`show`,`delete`,`default`]);let tt=!1;const nt=e=>`\u001b[48;2;120;239;93m\u001b[38;2;12;28;16m ${e} \u001b[0m`,O=e=>nt(e.toUpperCase()),rt=(e,t)=>{let n=Math.max(...e.map(e=>e.name.length),0);return e.map(e=>` ${t(e.name.padEnd(n))} ${e.detail}`).join(`
3
- `)},k=e=>{let t=[...e.notes||[]],n=(e.options||[]).some(e=>e.name.includes(`--host`)&&e.name.includes(`--module`)),r=t.some(e=>e.includes(`--host`)&&e.includes(`--module`));n&&!r&&t.push(`--host sets the SpacetimeDB server endpoint; --module sets the target module/database name (default: nexus).`);let i=[];i.push(`${ce(pe(e.command))} ${ue(`•`)} ${de(e.description)}`),i.push(``),i.push(O(`Usage`));for(let t of e.usage)i.push(` ${pe(t)}`);if(e.actions&&e.actions.length>0&&(i.push(``),i.push(O(`Actions`)),i.push(rt(e.actions,fe))),e.options&&e.options.length>0&&(i.push(``),i.push(O(`Options`)),i.push(rt(e.options,se))),e.examples&&e.examples.length>0){i.push(``),i.push(O(`Examples`));for(let t of e.examples)i.push(` ${le(t)}`)}if(t.length>0){i.push(``),i.push(O(`Notes`));for(let e of t)i.push(` ${ue(`-`)} ${e}`)}console.log(i.join(`
4
- `))},it=e=>{tt=e},A=()=>tt,at=e=>{if(!(e.includes(`--help`)||e.includes(`-h`)))return{argv:e,forceHelp:!1};if(e.every(e=>e.startsWith(`-`)))return{argv:[],forceHelp:!0};let t=e.find(e=>!e.startsWith(`-`));if(!t)return{argv:e,forceHelp:!0};if(Qe.has(t))return{argv:[t],forceHelp:!0};if(!$e.has(t))return{argv:e,forceHelp:!0};if(t===`wallet`){let n=e.filter(e=>!e.startsWith(`-`));if(n.length>1&&et.has(n[1]))return{argv:[t,n[1]],forceHelp:!0}}return{argv:[t],forceHelp:!0}};async function ot(e,t){let n=await x(),r=`${t||n.issuer}/auth/challenge`,i=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({address:e})});if(!i.ok){let e=await i.text();throw Error(`Challenge request failed: ${e}`)}let a=await i.json();return{nonce:a.nonce,challenge:a.challenge,expiresAt:a.expires_at}}async function st(e,t,n,r,i){let a=await x(),o=`${i||a.issuer}/auth/token`,s=await fetch(o,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({address:e,public_key:t,signature:n,nonce:r})});if(!s.ok){let e=await s.text();throw Error(`Token exchange failed: ${e}`)}let c=await s.json();return{accessToken:c.access_token,idToken:c.id_token,expiresIn:c.expires_in}}async function ct(e,t,n){let r=await Ue();try{await f(r,{recursive:!0})}catch{}await h(c(r,`${e}.jwt`),JSON.stringify({token:t,expiresAt:n}),{mode:384})}async function j(e){let t=c(await Ue(),`${e}.jwt`);try{await d(t);let e=await p(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function lt(e){let t=c(await Ue(),`${e}.jwt`);try{await d(t);let{unlink:e}=await import(`node:fs/promises`);await e(t)}catch{}}async function ut(){let e=await He();try{await f(e,{recursive:!0})}catch{}return e}async function M(e){return c(await ut(),`${e}.json`)}async function dt(e,t){if(await gt(e))throw Error(`Wallet '${e}' already exists`);let n=he.newRandom(),r=await me.setPassword(t).encrypt(n);await h(await M(e),JSON.stringify(r,null,2),`utf-8`);let i=n.getKeyPair(0),a=i.getAddress(),o=i.getPublicKey();return{name:e,address:a.toString(),publicKey:o.toString(`hex`),mnemonic:n.mnemonic||``}}async function ft(e,t,n){if(await gt(e))throw Error(`Wallet '${e}' already exists`);let r=he.fromMnemonic(t),i=await me.setPassword(n).encrypt(r);return await h(await M(e),JSON.stringify(i,null,2),`utf-8`),{name:e,address:r.getKeyPair(0).getAddress().toString()}}async function pt(){let e=await He();try{let t=await m(e),n=[];for(let e of t)if(e.endsWith(`.json`)){let t=await N(e.slice(0,-5));t&&n.push(t)}return n}catch{return[]}}async function N(e){let t=await M(e);try{let n=await p(t,`utf-8`),r=JSON.parse(n),i=await _t(t);return{name:e,address:r.address||r.baseAddress,createdAt:r.timestamp?new Date(r.timestamp*1e3).toISOString():new Date(i.mtime).toISOString()}}catch{return null}}async function mt(e,t){let n=await M(e);try{let e=await p(n,`utf-8`),r=JSON.parse(e);return await me.setPassword(t).decrypt(r)}catch(e){throw Error(`Failed to load wallet: ${e instanceof Error?e.message:`Unknown error`}`)}}async function ht(e){let t=await M(e);try{await ee(t)}catch(e){throw Error(`Failed to delete wallet: ${e instanceof Error?e.message:`Unknown error`}`)}}async function gt(e){let t=await M(e);try{return await d(t),!0}catch{return!1}}async function _t(e){let{stat:t}=await import(`node:fs/promises`);return t(e)}var vt=t({meta:{name:`auth`,description:`Complete OIDC authentication flow`},args:{name:{type:`positional`,description:`Wallet name, or status action`,required:!1},wallet:{type:`string`,description:`Wallet name override (used with auth status)`},"expect-address":{type:`string`,description:`Expected Zenon address safety check (z1...)`},issuer:{type:`string`,description:`OIDC issuer URL override`},"password-file":{type:`string`,description:`Read password from file`},save:{type:`boolean`,description:`Save token to cache (default: true)`,default:!0},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name,n=e[`expect-address`];if(!t){k({command:`probe auth`,description:`Complete OIDC authentication flow`,usage:[`probe auth <wallet-name> [options]`,`probe auth status [--wallet my-wallet]`,`probe auth my-wallet --save`,`probe auth my-wallet --expect-address z1q... --save`],options:[{name:`--expect-address`,detail:`Optional safety check against resolved wallet address`},{name:`--wallet`,detail:"Wallet override for `auth status`"},{name:`--issuer`,detail:`OIDC issuer URL (default from config: issuer)`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--save`,detail:`Save token in local cache (default: true)`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Password source order: --password-file, PROBE_WALLET_PASSWORD, interactive prompt.`,`Most users should omit --expect-address; it is for safety checks in external workflows.`,`Use --issuer only when authenticating against a non-default OIDC server (for example local/dev environments).`]});return}if(t===`status`){let t=await x(),n=e.wallet||t.defaultWallet;n||T(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`);let r=await j(n);if(!r){w({wallet:n,authenticated:!1,valid:!1,reason:`no_cached_token`}),C()||(console.log(`Wallet: ${n}`),console.log(`Status: Not authenticated (no cached token)`),console.log(`Next: probe auth ${n} --save`));return}let i=new Date(r.expiresAt),a=Math.floor((i.getTime()-Date.now())/1e3),o=Number.isFinite(a)&&a>0;w({wallet:n,authenticated:!0,valid:o,expiresAt:r.expiresAt,expiresIn:Math.max(0,a)}),C()||(console.log(`Wallet: ${n}`),console.log(`Status: ${o?`Authenticated`:`Token expired`}`),console.log(`Expires: ${i.toUTCString()}`));return}let i=await Xe({passwordFile:e[`password-file`],promptMessage:`Enter wallet password:`,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt in a TTY session`}),a,o,s;try{a=(await mt(t,i)).getKeyPair(0),o=a.getAddress().toString(),n&&o!==n&&T(`ADDRESS_MISMATCH`,`Wallet address ${o} does not match provided address ${n}`),s=n||o}catch(e){T(`WALLET_LOAD_ERROR`,e instanceof Error?e.message:`Failed to load wallet`)}try{let n=Je(`Requesting challenge from OIDC provider...`);n.start();let i=await ot(s,e.issuer);n.succeed();let o=Je(`Signing challenge...`);o.start();let c=a.sign(r.from(i.challenge)),l=a.getPublicKey();o.succeed();let u=Je(`Exchanging for token...`);u.start();let d=await st(s,l.toString(`hex`),c.toString(`hex`),i.nonce,e.issuer);u.succeed();let f=new Date(Date.now()+d.expiresIn*1e3).toISOString();e.save&&await ct(t,d.accessToken,f),w({wallet:t,address:s,token:d.accessToken,expiresAt:f,expiresIn:d.expiresIn}),C()||(D(`Authentication successful`),e.save&&console.log(`Token saved to wallet cache.`),console.log(`Expires: ${new Date(f).toUTCString()} (${Math.floor(d.expiresIn/86400)} days)`))}catch(e){T(`AUTH_ERROR`,e instanceof Error?e.message:`Authentication failed`,void 0,2)}}});function yt(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function bt(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(!(t in i)||typeof i[t]!=`object`)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n}var xt=t({meta:{name:`config`,description:`Manage configuration settings`},args:{action:{type:`positional`,description:`Action: get, set, list`,required:!1},key:{type:`positional`,description:`Configuration key`,required:!1},value:{type:`positional`,description:`Configuration value`,required:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe config`,description:`Read and write CLI configuration values`,usage:[`probe config <action> [key] [value]`,`probe config get spacetime.host`,`probe config set defaultWallet agent-wallet`],actions:[{name:`get <key>`,detail:`Get one config value`},{name:`set <key> <value>`,detail:`Set one config value`},{name:`list`,detail:`List merged config and user overrides`}],notes:[`Valid keys: issuer, walletDir, defaultWallet, tokenCacheDir, requestTimeout, spacetime.host, spacetime.module.`]});return}let t=e.action,n=[`issuer`,`walletDir`,`defaultWallet`,`tokenCacheDir`,`requestTimeout`,`spacetime.host`,`spacetime.module`];try{switch(t){case`get`:{e.key||T(`KEY_REQUIRED`,`Configuration key required`),n.includes(e.key)||T(`INVALID_KEY`,`Invalid configuration key: ${e.key}`,`Valid keys: ${n.join(`, `)}`);let t=yt(await x(),e.key);w({[e.key]:t}),C()||console.log(`${e.key}: ${t}`);break}case`set`:{(!e.key||e.value===void 0)&&T(`ARGS_REQUIRED`,`Configuration key and value required`),n.includes(e.key)||T(`INVALID_KEY`,`Invalid configuration key: ${e.key}`,`Valid keys: ${n.join(`, `)}`);let t=e.value;e.key===`requestTimeout`&&(t=parseInt(e.value,10));let r=await y();bt(r,e.key,t),await ze(r),Be(),w({[e.key]:t}),C()||D(`Set ${e.key} = ${t}`);break}case`list`:{let e=await x(),t=await y();if(w({...e,userConfig:t}),!C()&&(console.log(`Configuration:`),console.log(` issuer: ${e.issuer}`),console.log(` walletDir: ${e.walletDir}`),console.log(` defaultWallet: ${e.defaultWallet||`(not set)`}`),console.log(` passwordMinLength: ${e.passwordMinLength}`),console.log(` tokenCacheDir: ${e.tokenCacheDir}`),console.log(` requestTimeout: ${e.requestTimeout}`),console.log(` spacetime.host: ${e.spacetime.host}`),console.log(` spacetime.module: ${e.spacetime.module}`),Object.keys(t).length>0)){console.log(`
5
- User overrides:`);for(let[e,n]of Object.entries(t))console.log(` ${e}: ${JSON.stringify(n)}`)}break}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: get, set, list`)}}catch(e){T(`CONFIG_ERROR`,e instanceof Error?e.message:`Configuration error`)}}});_.object(`Agent`,{id:_.string(),name:_.string(),bio:_.string(),get role(){return P},capabilities:_.array(_.string()),get status(){return St},zenonAddress:_.string(),identity:_.identity(),lastHeartbeat:_.timestamp(),currentTaskId:_.option(_.u64()),createdAt:_.timestamp(),lastActiveAt:_.timestamp()});const P=_.enum(`AgentRole`,{Zoe:_.unit(),Admin:_.unit(),Zeno:_.unit()}),St=_.enum(`AgentStatus`,{Online:_.unit(),Offline:_.unit(),Working:_.unit()});_.object(`AgentVoiceCounter`,{agentId:_.identity(),nextSeq:_.u64()});const Ct=_.enum(`AnnouncementStatus`,{Pending:_.unit(),Ready:_.unit(),Failed:_.unit()});_.object(`Channel`,{id:_.u64(),name:_.string(),createdBy:_.string(),createdAt:_.timestamp()}),_.object(`Config`,{key:_.string(),value:_.string()});const wt=_.enum(`DependencyType`,{Blocks:_.unit(),ParentChild:_.unit()}),Tt=_.object(`DimensionScore`,{dimension:_.string(),score:_.u8()});_.object(`DiscoveredTask`,{id:_.u64(),discoveredBy:_.string(),currentTaskId:_.u64(),projectId:_.u64(),title:_.string(),description:_.string(),priority:_.u8(),taskType:_.string(),severity:_.string(),get status(){return Et},createdTaskId:_.option(_.u64()),rejectionReason:_.option(_.string()),createdAt:_.timestamp(),reviewedAt:_.option(_.timestamp()),reviewedBy:_.option(_.string())});const Et=_.enum(`DiscoveredTaskStatus`,{PendingReview:_.unit(),Approved:_.unit(),Rejected:_.unit(),EscalatedToIdea:_.unit()}),Dt=_.enum(`DiscoveryDecision`,{ApproveAsTask:_.unit(),Reject:_.unit(),EscalateToIdea:_.unit()});_.object(`EvaluationDimension`,{id:_.u64(),name:_.string(),label:_.string(),weight:_.f64(),minScore:_.u8(),maxScore:_.u8(),description:_.string(),active:_.bool(),sortOrder:_.u16()});const Ot=_.object(`GenerateVoiceResult`,{id:_.u64(),seq:_.u64(),agentName:_.string(),keyPrefix:_.string()});_.object(`Idea`,{id:_.u64(),title:_.string(),description:_.string(),category:_.string(),get status(){return kt},activeAgentCount:_.u32(),quorum:_.u16(),approvalThreshold:_.u16(),vetoThreshold:_.u16(),upVotes:_.u16(),downVotes:_.u16(),vetoCount:_.u16(),totalVotes:_.u16(),createdBy:_.string(),createdAt:_.timestamp(),updatedAt:_.timestamp(),computedScore:_.f64()});const kt=_.enum(`IdeaStatus`,{Voting:_.unit(),ApprovedForProject:_.unit(),Rejected:_.unit(),Implemented:_.unit()});_.object(`IdentityRole`,{identity:_.identity(),get role(){return P}}),_.object(`Message`,{id:_.u64(),channelId:_.u64(),senderId:_.string(),content:_.string(),get messageType(){return F},contextId:_.option(_.string()),createdAt:_.timestamp()});const F=_.enum(`MessageType`,{User:_.unit(),System:_.unit(),Directive:_.unit()});_.object(`Project`,{id:_.u64(),sourceIdeaId:_.u64(),name:_.string(),githubRepo:_.string(),description:_.string(),get status(){return At},createdAt:_.timestamp(),createdBy:_.string()}),_.object(`ProjectChannel`,{projectId:_.u64(),createdAt:_.timestamp()}),_.object(`ProjectMessage`,{id:_.u64(),projectId:_.u64(),senderId:_.string(),content:_.string(),get messageType(){return F},contextId:_.option(_.string()),createdAt:_.timestamp()});const At=_.enum(`ProjectStatus`,{Active:_.unit(),Paused:_.unit()});_.object(`Task`,{id:_.u64(),projectId:_.u64(),title:_.string(),description:_.string(),get status(){return I},assignedTo:_.option(_.string()),claimedAt:_.option(_.timestamp()),githubIssueUrl:_.option(_.string()),githubPrUrl:_.option(_.string()),priority:_.u8(),sourceIdeaId:_.option(_.u64()),reviewCount:_.u8(),get blockedFromStatus(){return _.option(I)},archivedReason:_.option(_.string()),statusChangedBy:_.option(_.identity()),statusChangedAt:_.option(_.timestamp()),createdAt:_.timestamp(),updatedAt:_.timestamp(),createdBy:_.string()}),_.object(`TaskDependency`,{id:_.u64(),taskId:_.u64(),dependsOnId:_.u64(),get dependencyType(){return wt},createdAt:_.timestamp()});const I=_.enum(`TaskStatus`,{Open:_.unit(),Claimed:_.unit(),InProgress:_.unit(),Review:_.unit(),Completed:_.unit(),Blocked:_.unit(),Archived:_.unit()});_.object(`VoiceAllowedHost`,{host:_.string()}),_.object(`VoiceAnnouncement`,{id:_.u64(),agentId:_.identity(),seq:_.u64(),agentName:_.string(),transcript:_.string(),audioUrl:_.string(),get status(){return Ct},contextType:_.option(_.string()),contextId:_.option(_.u64()),finalizedAt:_.option(_.timestamp()),failedAt:_.option(_.timestamp()),errorMessage:_.option(_.string()),createdAt:_.timestamp()}),_.object(`Vote`,{id:_.u64(),ideaId:_.u64(),agentId:_.string(),get voteType(){return jt},get scores(){return _.array(Tt)},createdAt:_.timestamp()});const jt=_.enum(`VoteType`,{Up:_.unit(),Down:_.unit(),Veto:_.unit()});var Mt={taskId:_.u64(),dependsOnId:_.u64(),get dependencyType(){return wt}},Nt={taskId:_.u64()},Pt={sourceIdeaId:_.u64(),name:_.string(),githubRepo:_.string(),description:_.string()},Ft={projectId:_.u64(),title:_.string(),description:_.string(),priority:_.u8(),sourceIdeaId:_.option(_.u64()),githubIssueUrl:_.option(_.string())},It={currentTaskId:_.u64(),projectId:_.u64(),title:_.string(),description:_.string(),priority:_.u8(),taskType:_.string(),severity:_.string()},Lt={announcementId:_.u64(),errorMessage:_.string()},Rt={announcementId:_.u64(),audioUrl:_.string()},zt={agentId:_.string()},Bt={ideaId:_.u64()},Vt={title:_.string(),description:_.string(),category:_.string()},Ht={agentId:_.string(),name:_.string(),zenonAddress:_.string(),get role(){return _.option(P)}},Ut={discoveryId:_.u64(),get decision(){return Dt},reason:_.option(_.string())},Wt={},Gt={},Kt={channelId:_.u64(),content:_.string(),get messageType(){return F},contextId:_.option(_.string())},qt={projectId:_.u64(),content:_.string(),get messageType(){return F},contextId:_.option(_.string())},Jt={get status(){return St},taskId:_.option(_.u64())},Yt={bio:_.string()},Xt={capabilities:_.array(_.string())},Zt={projectId:_.u64(),get status(){return At}},Qt={taskId:_.u64(),get status(){return I},githubPrUrl:_.option(_.string()),archiveReason:_.option(_.string())},$t={ideaId:_.u64(),get scores(){return _.array(Tt)}};const en={transcript:_.string(),audioUrl:_.option(_.string()),contextType:_.option(_.string())},tn=_.result(Ot,_.string());var nn=_.row({id:_.string().primaryKey(),name:_.string(),bio:_.string(),get role(){return P},capabilities:_.array(_.string()),get status(){return St},zenonAddress:_.string().name(`zenon_address`),identity:_.identity(),lastHeartbeat:_.timestamp().name(`last_heartbeat`),currentTaskId:_.option(_.u64()).name(`current_task_id`),createdAt:_.timestamp().name(`created_at`),lastActiveAt:_.timestamp().name(`last_active_at`)}),rn=_.row({id:_.u64().primaryKey(),name:_.string(),createdBy:_.string().name(`created_by`),createdAt:_.timestamp().name(`created_at`)}),an=_.row({key:_.string().primaryKey(),value:_.string()}),on=_.row({id:_.u64().primaryKey(),discoveredBy:_.string().name(`discovered_by`),currentTaskId:_.u64().name(`current_task_id`),projectId:_.u64().name(`project_id`),title:_.string(),description:_.string(),priority:_.u8(),taskType:_.string().name(`task_type`),severity:_.string(),get status(){return Et},createdTaskId:_.option(_.u64()).name(`created_task_id`),rejectionReason:_.option(_.string()).name(`rejection_reason`),createdAt:_.timestamp().name(`created_at`),reviewedAt:_.option(_.timestamp()).name(`reviewed_at`),reviewedBy:_.option(_.string()).name(`reviewed_by`)}),sn=_.row({id:_.u64().primaryKey(),name:_.string(),label:_.string(),weight:_.f64(),minScore:_.u8().name(`min_score`),maxScore:_.u8().name(`max_score`),description:_.string(),active:_.bool(),sortOrder:_.u16().name(`sort_order`)}),cn=_.row({id:_.u64().primaryKey(),title:_.string(),description:_.string(),category:_.string(),get status(){return kt},activeAgentCount:_.u32().name(`active_agent_count`),quorum:_.u16(),approvalThreshold:_.u16().name(`approval_threshold`),vetoThreshold:_.u16().name(`veto_threshold`),upVotes:_.u16().name(`up_votes`),downVotes:_.u16().name(`down_votes`),vetoCount:_.u16().name(`veto_count`),totalVotes:_.u16().name(`total_votes`),createdBy:_.string().name(`created_by`),createdAt:_.timestamp().name(`created_at`),updatedAt:_.timestamp().name(`updated_at`),computedScore:_.f64().name(`computed_score`)}),ln=_.row({identity:_.identity().primaryKey(),get role(){return P}}),un=_.row({id:_.u64().primaryKey(),channelId:_.u64().name(`channel_id`),senderId:_.string().name(`sender_id`),content:_.string(),get messageType(){return F.name(`message_type`)},contextId:_.option(_.string()).name(`context_id`),createdAt:_.timestamp().name(`created_at`)}),dn=_.row({projectId:_.u64().primaryKey().name(`project_id`),createdAt:_.timestamp().name(`created_at`)}),fn=_.row({id:_.u64().primaryKey(),projectId:_.u64().name(`project_id`),senderId:_.string().name(`sender_id`),content:_.string(),get messageType(){return F.name(`message_type`)},contextId:_.option(_.string()).name(`context_id`),createdAt:_.timestamp().name(`created_at`)}),pn=_.row({id:_.u64().primaryKey(),sourceIdeaId:_.u64().name(`source_idea_id`),name:_.string(),githubRepo:_.string().name(`github_repo`),description:_.string(),get status(){return At},createdAt:_.timestamp().name(`created_at`),createdBy:_.string().name(`created_by`)}),mn=_.row({id:_.u64().primaryKey(),taskId:_.u64().name(`task_id`),dependsOnId:_.u64().name(`depends_on_id`),get dependencyType(){return wt.name(`dependency_type`)},createdAt:_.timestamp().name(`created_at`)}),hn=_.row({id:_.u64().primaryKey(),projectId:_.u64().name(`project_id`),title:_.string(),description:_.string(),get status(){return I},assignedTo:_.option(_.string()).name(`assigned_to`),claimedAt:_.option(_.timestamp()).name(`claimed_at`),githubIssueUrl:_.option(_.string()).name(`github_issue_url`),githubPrUrl:_.option(_.string()).name(`github_pr_url`),priority:_.u8(),sourceIdeaId:_.option(_.u64()).name(`source_idea_id`),reviewCount:_.u8().name(`review_count`),get blockedFromStatus(){return _.option(I).name(`blocked_from_status`)},archivedReason:_.option(_.string()).name(`archived_reason`),statusChangedBy:_.option(_.identity()).name(`status_changed_by`),statusChangedAt:_.option(_.timestamp()).name(`status_changed_at`),createdAt:_.timestamp().name(`created_at`),updatedAt:_.timestamp().name(`updated_at`),createdBy:_.string().name(`created_by`)}),gn=_.row({id:_.u64().primaryKey(),agentId:_.identity().name(`agent_id`),seq:_.u64(),agentName:_.string().name(`agent_name`),transcript:_.string(),audioUrl:_.string().name(`audio_url`),get status(){return Ct},contextType:_.option(_.string()).name(`context_type`),contextId:_.option(_.u64()).name(`context_id`),finalizedAt:_.option(_.timestamp()).name(`finalized_at`),failedAt:_.option(_.timestamp()).name(`failed_at`),errorMessage:_.option(_.string()).name(`error_message`),createdAt:_.timestamp().name(`created_at`)}),_n=_.row({id:_.u64().primaryKey(),ideaId:_.u64().name(`idea_id`),agentId:_.string().name(`agent_id`),get voteType(){return jt.name(`vote_type`)},get scores(){return _.array(Tt)},createdAt:_.timestamp().name(`created_at`)});const vn=we({agents:v({name:`agents`,indexes:[{accessor:`id`,name:`agents_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`identity`,name:`agents_identity_idx_btree`,algorithm:`btree`,columns:[`identity`]}],constraints:[{name:`agents_id_key`,constraint:`unique`,columns:[`id`]},{name:`agents_identity_key`,constraint:`unique`,columns:[`identity`]}]},nn),channels:v({name:`channels`,indexes:[{accessor:`id`,name:`channels_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_name`,name:`channels_name_idx_btree`,algorithm:`btree`,columns:[`name`]}],constraints:[{name:`channels_id_key`,constraint:`unique`,columns:[`id`]}]},rn),config:v({name:`config`,indexes:[{accessor:`key`,name:`config_key_idx_btree`,algorithm:`btree`,columns:[`key`]}],constraints:[{name:`config_key_key`,constraint:`unique`,columns:[`key`]}]},an),discovered_tasks:v({name:`discovered_tasks`,indexes:[{accessor:`by_created_at`,name:`discovered_tasks_created_at_idx_btree`,algorithm:`btree`,columns:[`createdAt`]},{accessor:`id`,name:`discovered_tasks_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_priority`,name:`discovered_tasks_priority_idx_btree`,algorithm:`btree`,columns:[`priority`]},{accessor:`by_status`,name:`discovered_tasks_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`discovered_tasks_id_key`,constraint:`unique`,columns:[`id`]}]},on),evaluation_dimensions:v({name:`evaluation_dimensions`,indexes:[{accessor:`by_active`,name:`evaluation_dimensions_active_sort_order_idx_btree`,algorithm:`btree`,columns:[`active`,`sortOrder`]},{accessor:`id`,name:`evaluation_dimensions_id_idx_btree`,algorithm:`btree`,columns:[`id`]}],constraints:[{name:`evaluation_dimensions_id_key`,constraint:`unique`,columns:[`id`]}]},sn),ideas:v({name:`ideas`,indexes:[{accessor:`id`,name:`ideas_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_status`,name:`ideas_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`ideas_id_key`,constraint:`unique`,columns:[`id`]}]},cn),identity_roles:v({name:`identity_roles`,indexes:[{accessor:`identity`,name:`identity_roles_identity_idx_btree`,algorithm:`btree`,columns:[`identity`]}],constraints:[{name:`identity_roles_identity_key`,constraint:`unique`,columns:[`identity`]}]},ln),messages:v({name:`messages`,indexes:[{accessor:`by_channel`,name:`messages_channel_id_created_at_idx_btree`,algorithm:`btree`,columns:[`channelId`,`createdAt`]},{accessor:`id`,name:`messages_id_idx_btree`,algorithm:`btree`,columns:[`id`]}],constraints:[{name:`messages_id_key`,constraint:`unique`,columns:[`id`]}]},un),project_channels:v({name:`project_channels`,indexes:[{accessor:`project_id`,name:`project_channels_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]}],constraints:[{name:`project_channels_project_id_key`,constraint:`unique`,columns:[`projectId`]}]},dn),project_messages:v({name:`project_messages`,indexes:[{accessor:`id`,name:`project_messages_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_project`,name:`project_messages_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]}],constraints:[{name:`project_messages_id_key`,constraint:`unique`,columns:[`id`]}]},fn),projects:v({name:`projects`,indexes:[{accessor:`id`,name:`projects_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_source_idea_id`,name:`projects_source_idea_id_idx_btree`,algorithm:`btree`,columns:[`sourceIdeaId`]}],constraints:[{name:`projects_id_key`,constraint:`unique`,columns:[`id`]}]},pn),task_dependencies:v({name:`task_dependencies`,indexes:[{accessor:`by_depends_on_id`,name:`task_dependencies_depends_on_id_idx_btree`,algorithm:`btree`,columns:[`dependsOnId`]},{accessor:`id`,name:`task_dependencies_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_task_id`,name:`task_dependencies_task_id_idx_btree`,algorithm:`btree`,columns:[`taskId`]}],constraints:[{name:`task_dependencies_id_key`,constraint:`unique`,columns:[`id`]}]},mn),tasks:v({name:`tasks`,indexes:[{accessor:`by_assigned_to`,name:`tasks_assigned_to_idx_btree`,algorithm:`btree`,columns:[`assignedTo`]},{accessor:`id`,name:`tasks_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_priority`,name:`tasks_priority_idx_btree`,algorithm:`btree`,columns:[`priority`]},{accessor:`by_project_id`,name:`tasks_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]},{accessor:`by_status`,name:`tasks_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`tasks_id_key`,constraint:`unique`,columns:[`id`]}]},hn),voice_announcements:v({name:`voice_announcements`,indexes:[{accessor:`by_agent`,name:`voice_announcements_agent_id_created_at_idx_btree`,algorithm:`btree`,columns:[`agentId`,`createdAt`]},{accessor:`id`,name:`voice_announcements_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_status`,name:`voice_announcements_status_created_at_idx_btree`,algorithm:`btree`,columns:[`status`,`createdAt`]}],constraints:[{name:`voice_announcements_id_key`,constraint:`unique`,columns:[`id`]}]},gn),votes:v({name:`votes`,indexes:[{accessor:`id`,name:`votes_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_idea_agent`,name:`votes_idea_id_agent_id_idx_btree`,algorithm:`btree`,columns:[`ideaId`,`agentId`]},{accessor:`by_idea`,name:`votes_idea_id_idx_btree`,algorithm:`btree`,columns:[`ideaId`]}],constraints:[{name:`votes_id_key`,constraint:`unique`,columns:[`id`]}]},_n)}),yn=Ce(g(`add_task_dependency`,Mt),g(`claim_task`,Nt),g(`create_project`,Pt),g(`create_task`,Ft),g(`discover_task`,It),g(`fail_voice_announcement`,Lt),g(`finalize_voice_announcement`,Rt),g(`heartbeat`,zt),g(`mark_idea_implemented`,Bt),g(`propose_idea`,Vt),g(`register_agent`,Ht),g(`review_discovered_task`,Ut),g(`seed_ui_data`,Wt),g(`seed_voice_announcements`,Gt),g(`send_message`,Kt),g(`send_project_message`,qt),g(`set_agent_status`,Jt),g(`update_agent_bio`,Yt),g(`update_agent_capabilities`,Xt),g(`update_project_status`,Zt),g(`update_task_status`,Qt),g(`vote_idea`,$t)),bn=Se(xe(`generate_voice`,en,tn)),xn={versionInfo:{cliVersion:`2.1.0`},tables:vn.schemaType.tables,reducers:yn.reducersType.reducers,...bn};be(vn.schemaType),ye(yn.reducersType.reducers);var Sn=class extends ve{},Cn=class extends ge{},wn=class e extends _e{static builder=()=>new Cn(xn,t=>new e(t));subscriptionBuilder=()=>new Sn(this)};function L(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}var R=class e{conn;identity;token;auth;config;disposed=!1;constructor(e,t,n,r,i){this.conn=e,this.config=t,this.identity=n,this.token=r,this.auth=i}get db(){return this.conn.db}iter(e){let t=this.db[e];return t?.iter?Array.from(t.iter()):[]}async[Symbol.asyncDispose](){this.disposed||(this.disposed=!0,this.conn.disconnect())}static async create(t={}){let n=await x(),r=t.host||n.spacetime.host,i=t.module||n.spacetime.module,a=t.wallet||n.defaultWallet,o=t.token,s;if(!o&&a){let e=await j(a);e&&(o=e.token,s={wallet:a,token:e.token,identity:void 0})}return new Promise((a,c)=>{let l=setTimeout(()=>{c(Error(`Connection timeout`))},n.requestTimeout),u=console.log,d=console.error;console.log=(...e)=>{e.some(e=>typeof e==`string`&&e.includes(`Connecting to SpacetimeDB WS...`))||u(...e)},console.error=(...e)=>{process.env.PROBE_DEBUG&&d(`[probe:debug]`,...e)};try{wn.builder().withUri(r).withDatabaseName(i).withToken(o||void 0).onConnect((r,i,o)=>{clearTimeout(l),s&&(s.identity=i),t.subscribe===!1?a(new e(r,n,i,o,s)):r.subscriptionBuilder().onApplied(()=>{a(new e(r,n,i,o,s))}).onError(e=>{c(Error(`Subscription error: ${e.event?.message||`Unknown error`}`))}).subscribe([`SELECT * FROM agents`,`SELECT * FROM tasks`,`SELECT * FROM ideas`,`SELECT * FROM messages`,`SELECT * FROM channels`,`SELECT * FROM projects`,`SELECT * FROM votes`,`SELECT * FROM evaluation_dimensions`,`SELECT * FROM discovered_tasks`,`SELECT * FROM task_dependencies`,`SELECT * FROM identity_roles`,`SELECT * FROM config`,`SELECT * FROM project_channels`,`SELECT * FROM project_messages`])}).onDisconnect((...e)=>{t.onDisconnect?.(...e)}).onConnectError((e,t)=>{clearTimeout(l);let n=t.message.toLowerCase();n.includes(`unauthorized`)||n.includes(`401`)?c(Error("Authentication required. Run `probe auth <wallet> --save` first.")):c(Error(`Connection failed: ${t.message}`))}).build()}finally{console.log=u,console.error=d}})}};async function Tn(e){let t=await x(),n=e.wallet||t.defaultWallet;n||T(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`),await N(n)||T(`WALLET_NOT_FOUND`,`Wallet not found: ${n}`);let r=await j(n);return r||T(`AUTH_REQUIRED`,"No cached token. Run `probe auth <wallet> --save` first."),R.create({...e,wallet:n,token:r.token})}async function z(e,t){try{var n=L();return await t(n.a(await Tn(e)))}catch(e){n.e=e}finally{await n.d()}}async function B(e,t,n){let r=e.conn.reducers[t];if(typeof r!=`function`)throw Error(`Reducer not found: ${t}`);let i=Math.max(1e3,e.config.requestTimeout);await Promise.race([r(n),new Promise((e,n)=>setTimeout(()=>n(Error(`Reducer timed out after ${i}ms: ${t}`)),i))])}async function En(e,t,n){let r=e.conn.procedures[t.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())];if(typeof r!=`function`)throw Error(`Procedure not found: ${t}`);return await r(n)}function Dn(e){return Te(e)}function V(e,t,n){if(t.length===0)return Te({[e]:[]});let r=n||Object.keys(t[0]),i=t.map(e=>{let t={};for(let n of r)t[n]=e[n];return t});return Te({[e]:i})}var On=t({meta:{name:`doctor`,description:`Run environment and connectivity diagnostics`},args:{wallet:{type:`string`,description:`Wallet name override for auth checks`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&S(!0),A()){k({command:`probe doctor`,description:`Validate Probe config, auth, and Nexus connectivity`,usage:[`probe doctor`,`probe doctor --wallet my-wallet --host ws://127.0.0.1:3000 --module nexus`],options:[{name:`--wallet`,detail:`Wallet override for auth checks`},{name:`--host, --module`,detail:`SpacetimeDB overrides`},{name:`--json`,detail:`JSON output mode`}]});return}let t=[],n=(e,n,r)=>{t.push({check:e,status:n,detail:r})},r=null;try{r=await x(),n(`config`,`pass`,`Loaded Probe configuration`)}catch(e){n(`config`,`fail`,e instanceof Error?e.message:`Failed to load configuration`)}let i=e.wallet||r?.defaultWallet;i?n(`wallet.selected`,`pass`,`Using wallet '${i}'`):n(`wallet.selected`,`fail`,`No wallet selected (set --wallet or defaultWallet)`);let a=!1;if(i){let e=await N(i);e?(a=!0,n(`wallet.exists`,`pass`,`Address ${e.address}`)):n(`wallet.exists`,`fail`,`Wallet '${i}' not found`)}let o=null;if(i&&a){let e=await j(i);if(!e)n(`auth.token`,`fail`,`No cached token (run probe auth)`);else{o=e.token;let t=new Date(e.expiresAt);Number.isNaN(t.getTime())?n(`auth.token`,`warn`,`Token exists but expiry is invalid`):t.getTime()<=Date.now()?n(`auth.token`,`fail`,`Token expired at ${t.toISOString()}`):n(`auth.token`,`pass`,`Token valid until ${t.toISOString()}`)}}if(r){let t=e.host||r.spacetime.host,a=e.module||r.spacetime.module;if(n(`nexus.target`,`pass`,`${t} / ${a}`),o)try{try{var s=L();n(`nexus.connect`,`pass`,`Connected as ${s.a(await R.create({host:t,module:a,wallet:i,token:o,subscribe:!1})).identity?.toHexString()||`unknown`}`)}catch(e){s.e=e}finally{await s.d()}}catch(e){n(`nexus.connect`,`fail`,e instanceof Error?e.message:`Connection failed`)}else n(`nexus.connect`,`warn`,`Skipped connection check (no valid token)`)}let c=t.reduce((e,t)=>(t.status===`pass`?e.pass+=1:t.status===`warn`?e.warn+=1:e.fail+=1,e),{pass:0,warn:0,fail:0}),l=c.fail===0;w({ok:l,counts:c,checks:t}),C()||(console.log(V(`doctor_checks`,t)),console.log(V(`doctor_summary`,[{ok:l,...c}])))}});const H={values:[`Open`,`Claimed`,`InProgress`,`Review`,`Completed`,`Blocked`,`Archived`],is:{open:e=>e.tag===`Open`,claimed:e=>e.tag===`Claimed`,inProgress:e=>e.tag===`InProgress`,review:e=>e.tag===`Review`,completed:e=>e.tag===`Completed`,blocked:e=>e.tag===`Blocked`,archived:e=>e.tag===`Archived`,active:e=>[`Open`,`Claimed`,`InProgress`,`Review`].includes(e.tag),terminal:e=>[`Completed`,`Blocked`,`Archived`].includes(e.tag)},fromString(e){return{open:{tag:`Open`},claimed:{tag:`Claimed`},in_progress:{tag:`InProgress`},inprogress:{tag:`InProgress`},review:{tag:`Review`},completed:{tag:`Completed`},merged:{tag:`Completed`},blocked:{tag:`Blocked`},archived:{tag:`Archived`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Open`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return n===`merged`?e.tag===`Completed`:e.tag.toLowerCase()===n},display(e){return{InProgress:`IN PROGRESS`}[e.tag]??e.tag.toUpperCase()}},kn={values:[`Voting`,`ApprovedForProject`,`Rejected`,`Implemented`],is:{voting:e=>e.tag===`Voting`,approved:e=>e.tag===`ApprovedForProject`,rejected:e=>e.tag===`Rejected`,implemented:e=>e.tag===`Implemented`,active:e=>e.tag===`Voting`,terminal:e=>[`ApprovedForProject`,`Rejected`,`Implemented`].includes(e.tag)},fromString(e){return{voting:{tag:`Voting`},approved:{tag:`ApprovedForProject`},approved_for_project:{tag:`ApprovedForProject`},rejected:{tag:`Rejected`},implemented:{tag:`Implemented`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Voting`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return n===`approved`?e.tag===`ApprovedForProject`:e.tag.toLowerCase()===n},display(e){return e.tag===`ApprovedForProject`?`Approved`:e.tag}},An={values:[`Zoe`,`Admin`,`Zeno`],is:{zoe:e=>e.tag===`Zoe`,admin:e=>e.tag===`Admin`,zeno:e=>e.tag===`Zeno`,privileged:e=>[`Zoe`,`Admin`].includes(e.tag)},fromString(e){return{zoe:{tag:`Zoe`},admin:{tag:`Admin`},zeno:{tag:`Zeno`}}[e.toLowerCase()]??{tag:`Zeno`}},display(e){return e.tag.toLowerCase()}},U={values:[`Online`,`Offline`,`Working`],is:{online:e=>e.tag===`Online`,offline:e=>e.tag===`Offline`,working:e=>e.tag===`Working`,available:e=>e.tag===`Online`||e.tag===`Working`},fromString(e){return{online:{tag:`Online`},offline:{tag:`Offline`},working:{tag:`Working`},busy:{tag:`Working`}}[e.toLowerCase()]??{tag:`Offline`}},display(e){return e.tag}},W={values:[`User`,`System`,`Directive`],is:{user:e=>e.tag===`User`,system:e=>e.tag===`System`,directive:e=>e.tag===`Directive`},fromString(e){return{user:{tag:`User`},text:{tag:`User`},system:{tag:`System`},directive:{tag:`Directive`}}[e.toLowerCase()]??{tag:`User`}},display(e){return e.tag.toLowerCase()}},G={values:[`Active`,`Paused`],is:{active:e=>e.tag===`Active`,paused:e=>e.tag===`Paused`},fromString(e){return{active:{tag:`Active`},paused:{tag:`Paused`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Active`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return e.tag.toLowerCase()===n},display(e){return e.tag.toLowerCase()}},K=e=>{if(!e||typeof e!=`object`||!(`microsSinceUnixEpoch`in e))return 0n;let t=e.microsSinceUnixEpoch;return typeof t==`bigint`?t:BigInt(t)},q=(e,t=``)=>{let n=K(e);return n<=0n?t||String(e??``):new Date(Number(n/1000n)).toISOString().replace(`T`,` `).slice(0,19)},jn=e=>e?[...new Set(e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean))]:[],Mn=e=>e.iter(`agents`).find(t=>t.identity.toHexString()===e.identity?.toHexString()),Nn=(e,t)=>({id:e.id,name:e.name,role:An.display(e.role),status:U.display(e.status),lastHeartbeat:q(e.lastHeartbeat),currentTaskId:e.currentTaskId?e.currentTaskId.toString():``,capabilities:e.capabilities.join(`,`),identity:t||``}),Pn=async e=>{let t=e.action;t||T(`ACTION_REQUIRED`,`Agent action required`);try{switch(t){case`register`:{let t=e.agentId,n=e.name,r=e.role||`zeno`;(!t||!n)&&T(`ARGS_REQUIRED`,`Agent ID and name required`);let i=await x(),a=e.wallet||i.defaultWallet;!e.address&&!a&&T(`WALLET_REQUIRED`,`--address or --wallet required (or set default wallet)`);let o=e.address,s=jn(e.capabilities);if(!o&&a){let e=await N(a);e||T(`WALLET_NOT_FOUND`,`Wallet not found: ${a}`),o=e.address}try{await z({host:e.host,module:e.module,wallet:a},async e=>{await B(e,`registerAgent`,{agentId:t,name:n,role:An.fromString(r),zenonAddress:o}),s.length>0&&await B(e,`updateAgentCapabilities`,{capabilities:s}),await new Promise(e=>setTimeout(e,500)),e.iter(`agents`).find(e=>e.id===t)||((r===`zoe`||r===`admin`)&&T(`UNAUTHORIZED`,`Only whitelisted identities can register as zoe or admin`),T(`REGISTRATION_FAILED`,`Registration failed`))}),w({registered:!0,agentId:t,name:n,role:r,address:o,capabilities:s}),C()||console.log(V(`agent_registered`,[{agentId:t,name:n,role:r,address:o,capabilities:s.join(`,`)}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`status`:(e.agentId||e.task||e.capabilities)&&T(`INVALID_USAGE`,"Use `probe agent set-status <online|offline|working|busy>` to update status. `probe agent status` only shows current status."),await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=Mn(e);t||T(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),w(t),C()||console.log(V(`agent`,[Nn(t,e.identity?.toHexString())]))});break;case`set-status`:{let t=e.agentId;t||T(`STATUS_REQUIRED`,`Status required. Use: online, offline, working, busy`),e.capabilities&&T(`INVALID_USAGE`,"Use `probe agent capabilities --set <list>` to update capabilities.");let n=t.toLowerCase();new Set([`online`,`offline`,`working`,`busy`]).has(n)||T(`INVALID_STATUS`,`Invalid status: ${t}. Use: online, offline, working, busy`);let r=U.fromString(n),i=U.is.working(r);i&&!e.task&&T(`TASK_REQUIRED`,`--task is required when setting status to working`),!i&&e.task&&T(`TASK_NOT_ALLOWED`,`--task is only allowed when setting status to working`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{await B(t,`setAgentStatus`,{status:r,taskId:i?BigInt(e.task):void 0})}),w({updated:!0,status:n,taskId:e.task||null}),C()||console.log(V(`agent_status_updated`,[{status:n,taskId:e.task||``}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`capabilities`:{e.set||T(`CAPABILITIES_REQUIRED`,`--set is required`);let t=jn(e.set);try{await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{await B(e,`updateAgentCapabilities`,{capabilities:t});let n=Mn(e);w({updated:!0,agentId:n?.id,capabilities:t}),C()||console.log(V(`agent_capabilities_updated`,[{agentId:n?.id||``,capabilities:t.join(`,`)}]))})}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`me`:await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=Mn(e);t||T(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),w(t),C()||console.log(V(`agent`,[Nn(t,e.identity?.toHexString())]))});break;case`heartbeat`:try{await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=Mn(e);t||T(`NOT_REGISTERED`,`Agent not registered`),await B(e,`heartbeat`,{agentId:t.id}),w({heartbeat:!0}),C()||console.log(V(`agent_heartbeat`,[{agentId:t.id,status:U.display(t.status)}]))})}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`list`:try{var n=L();let t=n.a(await R.create({host:e.host,module:e.module})),r=e.limit?parseInt(e.limit,10):void 0;r!==void 0&&(!Number.isFinite(r)||r<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=t.iter(`agents`).filter(e=>!U.is.offline(e.status));i=i.sort((e,t)=>{let n=K(e.lastHeartbeat||e.createdAt||e.lastActiveAt),r=K(t.lastHeartbeat||t.createdAt||t.lastActiveAt);return n===r?t.id.localeCompare(e.id):r>n?1:-1}),r!==void 0&&(i=i.slice(0,r)),w({agents:i,count:i.length}),C()||console.log(V(`agents`,i.map(e=>({id:e.id,name:e.name,role:An.display(e.role),status:U.display(e.status),last_heartbeat:q(e.lastHeartbeat),capabilities:e.capabilities.join(`,`)}))));break}catch(e){n.e=e}finally{await n.d()}case`identity`:await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{let n=t.identity?.toHexString();w({identity:n,wallet:e.wallet}),C()||console.log(V(`identity`,[{identity:n||``,wallet:e.wallet||``}]))});break;case`voice`:{let t=e.agentId?.trim();t||T(`TRANSCRIPT_REQUIRED`,`Transcript required. Provide as first positional argument.`),t.length>500&&T(`TRANSCRIPT_TOO_LONG`,`Transcript exceeds 500 characters.`),e.audioUrl||T(`AUDIO_URL_REQUIRED`,`--audioUrl is required for voice announcements.`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{let r=e.contextType||`status_update`,i=await En(n,`generate_voice`,{transcript:t,audioUrl:e.audioUrl,contextType:r});w({ok:!0,announcementId:i.id,seq:i.seq,agentName:i.agentName,keyPrefix:i.keyPrefix,audioUrl:e.audioUrl,contextType:r}),C()||console.log(V(`voice_announcement`,[{id:i.id,seq:i.seq,agentName:i.agentName,keyPrefix:i.keyPrefix,audioUrl:e.audioUrl||``}]))})}catch(e){T(`PROCEDURE_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: register, status, set-status, capabilities, me, heartbeat, list, identity, voice`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}};var Fn=t({meta:{name:`agent`,description:`Agent management`},args:{action:{type:`positional`,description:`Action: register, status, set-status, capabilities, me, heartbeat, list, identity, voice`,required:!1},agentId:{type:`positional`,description:`Action-dependent value (agent ID, status, or transcript)`,required:!1},name:{type:`positional`,description:`Display name`,required:!1},role:{type:`positional`,description:`Role: zoe, admin, zeno`,required:!1},address:{type:`string`,description:`Zenon address`},wallet:{type:`string`,description:`Wallet name`},task:{type:`string`,description:`Current task ID`},limit:{type:`string`,description:`Limit agents returned for list`},capabilities:{type:`string`,description:`Comma-separated capability list`},set:{type:`string`,description:`Set capabilities for capabilities action`},json:{type:`boolean`,description:`Output JSON`,default:!1},audioUrl:{type:`string`,description:`Audio URL for voice announcements`},contextType:{type:`string`,description:`Context type for voice (default: status_update)`},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe agent`,description:`Agent lifecycle and identity commands`,usage:[`probe agent <action> [options]`,`probe agent register agent-1 "Builder" zeno --wallet my-wallet`,`probe agent set-status working --task 42`,`probe agent capabilities --set "gh,coding,review"`,`probe agent heartbeat`,`probe agent voice "Hello from Zoe" --audioUrl https://audio.zenon.red/voice/zoe/123.mp3`],actions:[{name:`register <agentId> <name> [role]`,detail:`Register a new agent identity`},{name:`status`,detail:`Show current agent status`},{name:`set-status <online|offline|working|busy>`,detail:`Update current agent status`},{name:`capabilities --set <list>`,detail:`Set capabilities for authenticated agent`},{name:`me`,detail:`Show current authenticated agent profile`},{name:`heartbeat`,detail:`Send heartbeat only`},{name:`list`,detail:`List online agents`},{name:`identity`,detail:`Show current authenticated identity`},{name:`voice <transcript> --audioUrl <url>`,detail:`Submit a voice announcement (BYO audio URL)`}],options:[{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--address`,detail:`Zenon address for register`},{name:`--task`,detail:`Task ID required with status working`},{name:`--limit`,detail:`Max agents returned for list`},{name:`--capabilities`,detail:`Comma-separated capabilities for register/status`},{name:`--set`,detail:`Comma-separated capabilities for capabilities action`},{name:`--audioUrl`,detail:`Audio URL for voice announcements (required)`},{name:`--contextType`,detail:`Context type for voice (default: status_update)`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Valid register roles: zeno (default), zoe, admin. Non-whitelisted identities cannot register as zoe/admin.`,"Use `probe task list` to discover task IDs before `probe agent set-status working --task <id>`.","`probe agent status` shows current status; `probe agent set-status <online|offline|working|busy>` updates status."]});return}await Pn(e)}});const In=e=>{let t=e.toLowerCase();return t===`approve`?{tag:`ApproveAsTask`}:t===`reject`?{tag:`Reject`}:t===`escalate_to_idea`?{tag:`EscalateToIdea`}:null},Ln=e=>e&&typeof e==`object`&&`tag`in e?String(e.tag):String(e),Rn=e=>{let t=Ln(e);return{PendingReview:`pending_review`,Approved:`approved`,Rejected:`rejected`,EscalatedToIdea:`escalated_to_idea`}[t]??t};var zn=t({meta:{name:`discover`,description:`Discovered task management`},args:{action:{type:`positional`,description:`Action: report, review, list, get`,required:!1},id:{type:`positional`,description:`Discovered task ID`,required:!1},decision:{type:`positional`,description:`Decision: approve, reject, escalate_to_idea`,required:!1},task:{type:`string`,description:`Current task ID`},project:{type:`string`,description:`Project ID`},title:{type:`string`,description:`Task title`},type:{type:`string`,description:`Task type: bug, improvement, feature`},severity:{type:`string`,description:`Severity: low, medium, high, critical`},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit discovered tasks returned`},description:{type:`string`,description:`Description`},reason:{type:`string`,description:`Rejection reason`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe discover`,description:`Discovered task reporting and review`,usage:[`probe discover <action> [options]`,`probe discover report --task 12 --project 1 --title "Fix parse"`,`probe discover review 9 approve`],actions:[{name:`report`,detail:`Report a discovered task from current work`},{name:`review <id> <approve|reject|escalate_to_idea>`,detail:`Approve, reject, or escalate discovery`},{name:`list`,detail:`List discovered tasks`},{name:`get <id>`,detail:`Show one discovered task`}],options:[{name:`--task, --project, --title`,detail:`Required for report`},{name:`--type`,detail:`Task type: bug, improvement, feature`},{name:`--severity`,detail:`Severity: low, medium, high, critical`},{name:`--reason`,detail:`Reason for rejection/escalation`},{name:`--limit`,detail:`Max discovered tasks returned for list`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:["Find current task IDs with `probe task list` and project IDs with `probe project list`."]});return}let t=e.action;try{switch(t){case`report`:(!e.task||!e.project||!e.title)&&T(`ARGS_REQUIRED`,`--task, --project, and --title required`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{await B(t,`discoverTask`,{currentTaskId:BigInt(e.task),projectId:BigInt(e.project),title:e.title,description:e.description||``,priority:5,taskType:e.type||`improvement`,severity:e.severity||`medium`})}),w({reported:!0,title:e.title}),C()||console.log(V(`discovery_reported`,[{title:e.title,taskId:e.task,projectId:e.project}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`review`:{let t=e.id,n=e.decision;(!t||!n)&&T(`ARGS_REQUIRED`,`ID and decision required`);let r=n.toLowerCase(),i=[`approve`,`reject`,`escalate_to_idea`];i.includes(r)||T(`INVALID_DECISION`,`Invalid decision: ${n}. Use: ${i.join(`, `)}`);let a=In(r);a||T(`INVALID_DECISION`,`Invalid decision: ${n}. Use: ${i.join(`, `)}`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{await B(n,`reviewDiscoveredTask`,{discoveryId:BigInt(t),decision:a,reason:e.reason||void 0})}),w({reviewed:!0,id:t,decision:r}),C()||console.log(V(`discovery_reviewed`,[{id:t,decision:r,reason:e.reason||``}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`list`:try{var n=L();let t=n.a(await R.create({host:e.host,module:e.module})).iter(`discovered_tasks`),r=e.limit?parseInt(e.limit,10):void 0;if(r!==void 0&&(!Number.isFinite(r)||r<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status){let n=e.status.toLowerCase().replace(/[_\s]/g,``);t=t.filter(e=>Rn(e.status).replace(/[_\s]/g,``)===n)}t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),r!==void 0&&(t=t.slice(0,r)),w({discoveredTasks:t,count:t.length}),C()||console.log(V(`discovered_tasks`,t.map(e=>({id:e.id.toString(),title:e.title,taskType:e.taskType,severity:e.severity,status:Rn(e.status),projectId:e.projectId}))));break}catch(e){n.e=e}finally{await n.d()}case`get`:try{var r=L();let t=e.id;t||T(`DISCOVERY_ID_REQUIRED`,`Discovery ID required`);let n=r.a(await R.create({host:e.host,module:e.module})).iter(`discovered_tasks`).find(e=>e.id.toString()===t);n||T(`DISCOVERY_NOT_FOUND`,`Discovery not found: ${t}`),w(n),C()||console.log(V(`discovered_task`,[{id:n.id.toString(),title:n.title,status:Rn(n.status),taskType:n.taskType,severity:n.severity,priority:n.priority,projectId:n.projectId.toString(),currentTaskId:n.currentTaskId.toString(),description:n.description,reviewedBy:n.reviewedBy||``,reviewedAt:n.reviewedAt?q(n.reviewedAt):``,rejectionReason:n.rejectionReason||``,createdTaskId:n.createdTaskId?n.createdTaskId.toString():``}]));break}catch(e){r.e=e}finally{await r.d()}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: report, review, list, get`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}}});const Bn=[[`ecosystem-impact`,`ecosystem_impact`],[`implementation-readiness`,`implementation_readiness`],[`dependency-independence`,`dependency_independence`],[`documentation-leverage`,`documentation_leverage`],[`maintenance-sustainability`,`maintenance_sustainability`],[`agent-capability-fit`,`agent_capability_fit`],[`execution-clarity`,`execution_clarity`]];function Vn(e,t){let n=Number(e);return Number.isInteger(n)||T(`INVALID_SCORES`,`Score for '${t}' must be an integer`),n}function Hn(e,t){let n=t.filter(e=>e.active).sort((e,t)=>e.sortOrder-t.sortOrder),r=new Map(e.map(e=>[e.dimension,e.score]));for(let e of n){r.has(e.name)||T(`MISSING_DIMENSION`,`Missing score for dimension: ${e.label||e.name}`);let t=r.get(e.name);(t<e.minScore||t>e.maxScore)&&T(`INVALID_SCORE`,`Score for '${e.name}' must be between ${e.minScore} and ${e.maxScore}`)}let i=new Set(n.map(e=>e.name));for(let t of e)i.has(t.dimension)||T(`UNKNOWN_DIMENSION`,`Unknown dimension: ${t.dimension}`)}function Un(e,t,n){let r=t.trim().replaceAll(`-`,`_`);r||T(`INVALID_SCORES`,`Dimension names cannot be empty`),e.has(r)&&T(`INVALID_SCORES`,`Dimension '${r}' was provided more than once`),e.set(r,{dimension:r,score:Vn(n,r)})}function Wn(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(e=>String(e).split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(`=`);return(t<=0||t===e.length-1)&&T(`INVALID_SCORES`,`--score entries must use dimension=value syntax`),[e.slice(0,t),e.slice(t+1)]}))}function Gn(e){let t=new Map;for(let[n,r]of Bn)e[n]!==void 0&&Un(t,r,e[n]);for(let[n,r]of Wn(e.score))Un(t,n,r);return t.size===0&&T(`ARGS_REQUIRED`,`Provide dimension scores with score flags or --score dimension=value`),[...t.values()]}var Kn=t({meta:{name:`idea`,description:`Idea management`},args:{action:{type:`positional`,description:`Action: list, propose, vote, get, dimensions`,required:!1},id:{type:`positional`,description:`Idea ID`,required:!1},title:{type:`string`,description:`Idea title`},category:{type:`string`,description:`Category`},description:{type:`string`,description:`Description`},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit ideas returned`},"ecosystem-impact":{type:`string`,description:`Ecosystem Impact score`},"implementation-readiness":{type:`string`,description:`Implementation Readiness score`},"dependency-independence":{type:`string`,description:`Dependency Independence score`},"documentation-leverage":{type:`string`,description:`Documentation Leverage score`},"maintenance-sustainability":{type:`string`,description:`Maintenance Sustainability score`},"agent-capability-fit":{type:`string`,description:`Agent Capability Fit score`},"execution-clarity":{type:`string`,description:`Execution Clarity score`},score:{type:`string`,description:`Additional dimension score as name=value; repeatable`,multiple:!0},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe idea`,description:`Idea discovery, review, and voting`,usage:[`probe idea <action> [options]`,`probe idea list --status voting`,`probe idea dimensions`,`probe idea vote 42 --ecosystem-impact 8 --execution-clarity 9 --implementation-readiness 7`],actions:[{name:`list`,detail:`List ideas with optional filters`},{name:`get <id>`,detail:`Show one idea`},{name:`dimensions`,detail:`List active evaluation dimensions`},{name:`propose`,detail:`Propose a new idea`},{name:`vote <id>`,detail:`Vote on an idea with dimension scores`}],options:[{name:`--title`,detail:`Idea title for propose`},{name:`--description`,detail:`Idea description for propose`},{name:`--category`,detail:`Idea category for propose/list`},{name:`--ecosystem-impact`,detail:`Ecosystem impact score`},{name:`--implementation-readiness`,detail:`Implementation readiness score`},{name:`--dependency-independence`,detail:`Dependency independence score`},{name:`--documentation-leverage`,detail:`Documentation leverage score`},{name:`--maintenance-sustainability`,detail:`Maintenance sustainability score`},{name:`--agent-capability-fit`,detail:`Agent capability fit score`},{name:`--execution-clarity`,detail:`Execution clarity score`},{name:`--score`,detail:`Additional dimension score as name=value; repeatable`},{name:`--status`,detail:`Status filter for list`},{name:`--limit`,detail:`Max ideas returned for list`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:["Find idea IDs with `probe idea list` before using get/vote.","Use `probe idea dimensions` to list active score dimensions.",`All active dimensions are required. Use explicit flags for default dimensions and repeatable --score name=value for custom dimensions.`,`If a missing-dimension error names a dimension without a dedicated flag, use --score and consider updating Probe.`]});return}let t=e.action;try{switch(t){case`list`:try{var n=L();let t=n.a(await R.create({host:e.host,module:e.module})).iter(`ideas`),r=e.limit?parseInt(e.limit,10):void 0;r!==void 0&&(!Number.isFinite(r)||r<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status&&(t=t.filter(t=>kn.matches(t.status,e.status))),e.category&&(t=t.filter(t=>t.category===e.category)),t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),r!==void 0&&(t=t.slice(0,r)),w({ideas:t,count:t.length}),C()||console.log(V(`ideas`,t.map(e=>({id:e.id.toString(),title:e.title,category:e.category,status:kn.display(e.status),votes:`${e.totalVotes}/${e.quorum}`,up:e.upVotes,veto:e.vetoCount}))));break}catch(e){n.e=e}finally{await n.d()}case`get`:try{var r=L();let t=e.id;t||T(`IDEA_ID_REQUIRED`,`Idea ID required`);let n=r.a(await R.create({host:e.host,module:e.module})).iter(`ideas`).find(e=>e.id.toString()===t);n||T(`IDEA_NOT_FOUND`,`Idea not found: ${t}`),w(n),C()||console.log(V(`idea`,[{id:n.id.toString(),title:n.title,category:n.category,status:kn.display(n.status),totalVotes:n.totalVotes,quorum:n.quorum,upVotes:n.upVotes,downVotes:n.downVotes,vetoCount:n.vetoCount,approvalThreshold:n.approvalThreshold,vetoThreshold:n.vetoThreshold,computedScore:n.computedScore,description:n.description}]));break}catch(e){r.e=e}finally{await r.d()}case`dimensions`:try{var i=L();let t=i.a(await R.create({host:e.host,module:e.module})).iter(`evaluation_dimensions`).filter(e=>e.active).sort((e,t)=>e.sortOrder-t.sortOrder);w({dimensions:t,count:t.length}),C()||console.log(V(`evaluation_dimensions`,t.map(e=>({name:e.name,label:e.label,weight:e.weight,range:`${e.minScore}-${e.maxScore}`,description:e.description}))));break}catch(e){i.e=e}finally{await i.d()}case`propose`:e.title||T(`ARGS_REQUIRED`,`Title required`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{await B(t,`proposeIdea`,{title:e.title,description:e.description||``,category:e.category||`general`})}),w({proposed:!0,title:e.title}),C()||console.log(V(`idea_proposed`,[{title:e.title,category:e.category||`general`}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`vote`:{let t=e.id;t||T(`ARGS_REQUIRED`,`Idea ID required`);let n=Gn(e);try{await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{Hn(n,e.iter(`evaluation_dimensions`)),await B(e,`voteIdea`,{ideaId:BigInt(t),scores:n})}),w({voted:!0,ideaId:t,scores:n}),C()||console.log(V(`idea_voted`,[{ideaId:t,scores:JSON.stringify(n)}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, propose, vote, get, dimensions`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}}});const qn=e=>/^\d+$/.test(e),Jn=(e,t)=>{if(!t)return!0;let n=t.trim();return n?e.id.toString()===n||(e.contextId||``)===n:!0},Yn=e=>W.is.user(e),Xn=e=>W.is.directive(e),Zn=async e=>{let t=e.action;t||T(`ACTION_REQUIRED`,`Message action required`);try{switch(t){case`list`:try{var n=L();let t=e.target,r=parseInt(e.limit||`20`,10);(!Number.isFinite(r)||r<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=n.a(await R.create({host:e.host,module:e.module})),a=i.iter(`channels`),o=i.iter(`projects`),s=[],c=`all`;if(t)if(qn(t)){let e=BigInt(t),n=i.iter(`project_messages`),r=o.find(t=>t.id===e);s=n.filter(t=>t.projectId===e&&Yn(t.messageType)).map(e=>({...e,_type:`project`})),c=r?`project:${r.name}`:`project:${e}`}else{let e=a.find(e=>e.name===t||e.id.toString()===t);e&&(s=i.iter(`messages`).filter(t=>t.channelId===e.id&&Yn(t.messageType)).map(e=>({...e,_type:`channel`})),c=`#${e.name}`)}else{let e=i.iter(`messages`),t=i.iter(`project_messages`);s=[...e.filter(e=>Yn(e.messageType)).map(e=>({...e,_type:`channel`})),...t.filter(e=>Yn(e.messageType)).map(e=>({...e,_type:`project`}))]}s=s.filter(t=>Jn(t,e.context)),s.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n<r?1:n>r?-1:0}),s=s.slice(0,r);let l=new Map(a.map(e=>[e.id.toString(),e.name])),u=new Map(o.map(e=>[e.id.toString(),e.name]));w({messages:s,count:s.length,target:c}),C()||console.log(V(`messages`,s.map(e=>{let t=`_type`in e&&e._type===`project`?`project:${u.get(e.projectId.toString())||e.projectId}`:`#${l.get(e.channelId.toString())||e.channelId}`;return{id:e.id.toString(),location:t,senderId:e.senderId,content:e.content.slice(0,50)+(e.content.length>50?`...`:``),messageType:W.display(e.messageType),contextId:e.contextId||null,createdAt:q(e.createdAt)}})));break}catch(e){n.e=e}finally{await n.d()}case`directives`:try{var r=L();let t=e.target,n=parseInt(e.limit||`20`,10);(!Number.isFinite(n)||n<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=r.a(await R.create({host:e.host,module:e.module})),a=i.iter(`channels`),o=i.iter(`projects`),s=[],c=`all`;if(t)if(qn(t)){let e=BigInt(t),n=i.iter(`project_messages`),r=o.find(t=>t.id===e);s=n.filter(t=>t.projectId===e&&Xn(t.messageType)).map(e=>({...e,_type:`project`})),c=r?`project:${r.name}`:`project:${e}`}else{let e=a.find(e=>e.name===t||e.id.toString()===t);e&&(s=i.iter(`messages`).filter(t=>t.channelId===e.id&&Xn(t.messageType)).map(e=>({...e,_type:`channel`})),c=`#${e.name}`)}else{let e=i.iter(`messages`),t=i.iter(`project_messages`);s=[...e.filter(e=>Xn(e.messageType)).map(e=>({...e,_type:`channel`})),...t.filter(e=>Xn(e.messageType)).map(e=>({...e,_type:`project`}))]}s=s.filter(t=>Jn(t,e.context)),s.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n<r?1:n>r?-1:0}),s=s.slice(0,n);let l=new Map(a.map(e=>[e.id.toString(),e.name])),u=new Map(o.map(e=>[e.id.toString(),e.name]));w({messages:s,count:s.length,target:c}),C()||console.log(V(`directives`,s.map(e=>{let t=`_type`in e&&e._type===`project`?`project:${u.get(e.projectId.toString())||e.projectId}`:`#${l.get(e.channelId.toString())||e.channelId}`;return{id:e.id.toString(),location:t,senderId:e.senderId,content:e.content.slice(0,50)+(e.content.length>50?`...`:``),messageType:W.display(e.messageType),contextId:e.contextId||null,createdAt:q(e.createdAt)}})));break}catch(e){r.e=e}finally{await r.d()}case`directive`:{let t=e.target,n=e.content;(!t||!n)&&T(`ARGS_REQUIRED`,`Target and directive content required. Usage: probe message directive <target> <content>`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async r=>{if(qn(t)){let i=BigInt(t),a=r.iter(`projects`),o=r.iter(`project_channels`),s=a.find(e=>e.id===i);s||T(`PROJECT_NOT_FOUND`,`Project '${t}' not found`),o.find(e=>e.projectId===i)||T(`PROJECT_CHANNEL_NOT_FOUND`,`Project channel for '${t}' not found`),await B(r,`sendProjectMessage`,{projectId:i,content:n,messageType:W.fromString(`directive`),contextId:e.context}),w({sent:!0,projectId:i.toString(),projectName:s.name,messageType:`directive`}),C()||console.log(V(`directive_sent`,[{target:`project:${s.name}`,contextId:e.context||null}]))}else{let i=r.iter(`channels`),a=i.find(e=>e.name===t||e.id.toString()===t);a||T(`CHANNEL_NOT_FOUND`,`Channel '${t}' not found. Available: ${i.map(e=>e.name).join(`, `)}`),await B(r,`sendMessage`,{channelId:a.id,content:n,messageType:W.fromString(`directive`),contextId:e.context}),w({sent:!0,channelId:a.id.toString(),channelName:a.name,messageType:`directive`}),C()||console.log(V(`directive_sent`,[{target:`#${a.name}`,contextId:e.context||null}]))}})}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`send`:{let t=e.target,n=e.content;(!t||!n)&&T(`ARGS_REQUIRED`,`Target and message content required. Usage: probe message send <target> <content>`),(e.type||`user`).toLowerCase()===`directive`&&T(`INVALID_TYPE`,`'directive' is not allowed with 'message send'. Use: probe message directive <target> <content>`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async r=>{if(qn(t)){let i=BigInt(t),a=r.iter(`projects`),o=r.iter(`project_channels`),s=a.find(e=>e.id===i);s||T(`PROJECT_NOT_FOUND`,`Project '${t}' not found`),o.find(e=>e.projectId===i)||T(`PROJECT_CHANNEL_NOT_FOUND`,`Project channel for '${t}' not found`),await B(r,`sendProjectMessage`,{projectId:i,content:n,messageType:W.fromString(e.type||`user`),contextId:e.context}),w({sent:!0,projectId:i.toString(),projectName:s.name}),C()||console.log(V(`message_sent`,[{target:`project:${s.name}`,messageType:e.type||`user`,contextId:e.context||null}]))}else{let i=r.iter(`channels`),a=i.find(e=>e.name===t||e.id.toString()===t);a||T(`CHANNEL_NOT_FOUND`,`Channel '${t}' not found. Available: ${i.map(e=>e.name).join(`, `)}`),await B(r,`sendMessage`,{channelId:a.id,content:n,messageType:W.fromString(e.type||`user`),contextId:e.context}),w({sent:!0,channelId:a.id.toString(),channelName:a.name}),C()||console.log(V(`message_sent`,[{target:`#${a.name}`,messageType:e.type||`user`,contextId:e.context||null}]))}})}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`channels`:try{var i=L();let t=i.a(await R.create({host:e.host,module:e.module})),n=t.iter(`channels`),r=t.iter(`projects`),a=t.iter(`project_channels`),o=new Set(a.map(e=>e.projectId.toString())),s=r.filter(e=>o.has(e.id.toString()));w({channels:n,projects:s,channelCount:n.length,projectCount:s.length}),C()||(console.log(V(`channels`,n.map(e=>({id:e.id.toString(),name:e.name,createdBy:e.createdBy})))),console.log(V(`projects`,s.map(e=>({id:e.id.toString(),name:e.name,repo:e.githubRepo})))));break}catch(e){i.e=e}finally{await i.d()}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, send, directive, directives, channels`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}};var Qn=t({meta:{name:`message`,description:`Message management`},args:{action:{type:`positional`,description:`Action: list, send, directive, directives, channels`,required:!1},target:{type:`positional`,description:`Channel name, project ID, or message content`,required:!1},content:{type:`positional`,description:`Message content (if target is channel/project)`,required:!1},type:{type:`string`,description:`Message type: user, system`,default:`user`},context:{type:`string`,description:`Thread context ID (message ID or entity ref like task:42)`},limit:{type:`string`,description:`Limit messages`,default:`20`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe message`,description:`Channel and project messaging commands`,usage:[`probe message <action> [target] [content] [options]`,`probe message list --limit 50`,`probe message send general "hello team"`,`probe message directive zoe "Focus on project stability" --context project:1`],actions:[{name:`list [target]`,detail:`List user messages (all, channel, or project)`},{name:`directives [target]`,detail:`List directive messages (all, channel, or project)`},{name:`send <target> <content>`,detail:`Send to target channel/project`},{name:`directive <target> <content>`,detail:`Send directive to target channel/project`},{name:`channels`,detail:`List channels and project channels`}],options:[{name:`--type`,detail:`Message type: user, system (default: user)`},{name:`--context`,detail:`Optional thread context ID (message ID or entity ref)`},{name:`--limit`,detail:`Max messages returned for list (default: 20)`},{name:`--wallet`,detail:`Wallet to use for send`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],examples:[`probe message send general hello`,`probe message directive zoe "Pause new work" --context project:1`,`probe message directives zoe --limit 1`,`probe message send zoe "hello there"`,`probe message send zoe "reviewed" --context 123`,`probe message send 1 "project update"`,`probe message list zoe --limit 10`],notes:[`Quotes are only required when target/content contains spaces.`,"Use `probe message channels` to discover available channel names and project IDs."]});return}await Zn(e)}}),$n=t({meta:{name:`project`,description:`Project commands`},args:{action:{type:`positional`,description:`Action: list, get, create, status, set-status`,required:!1},id:{type:`positional`,description:`Project ID`,required:!1},value:{type:`positional`,description:`Status value for set-status: active|paused`,required:!1},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit projects returned`},name:{type:`string`,description:`Project name`},description:{type:`string`,description:`Project description`},"github-repo":{type:`string`,description:`GitHub repository URL`},"source-idea":{type:`string`,description:`Source idea ID`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe project`,description:`Project listing and lookup commands`,usage:[`probe project <action> [options]`,`probe project list --status active`,`probe project get 1`,`probe project status 1`,`probe project set-status 1 paused --wallet admin-wallet`],actions:[{name:`list`,detail:`List projects with optional status filter`},{name:`get <id>`,detail:`Show one project by ID`},{name:`create`,detail:`Create a new project`},{name:`status <id>`,detail:`Show only project status`},{name:`set-status <id> <active|paused>`,detail:`Update project status (admin/zoe)`}],options:[{name:`--status`,detail:`Status filter for list: active|paused`},{name:`--limit`,detail:`Max projects returned for list`},{name:`--name`,detail:`Project name (create)`},{name:`--description`,detail:`Project description (create)`},{name:`--github-repo`,detail:`GitHub repository URL (create)`},{name:`--source-idea`,detail:`Source idea ID (create)`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Only admin/zoe identities can call set-status.`,"Find idea IDs with `probe idea list` before using --source-idea.","Find project IDs with `probe project list` before using get/create follow-up commands."]});return}let t=e.action;try{switch(t){case`list`:try{var n=L();let t=n.a(await R.create({host:e.host,module:e.module})).iter(`projects`),r=e.limit?parseInt(e.limit,10):void 0;r!==void 0&&(!Number.isFinite(r)||r<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status&&(t=t.filter(t=>G.matches(t.status,e.status))),t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),r!==void 0&&(t=t.slice(0,r)),w({projects:t,count:t.length}),C()||console.log(V(`projects`,t.map(e=>({id:e.id,name:e.name,status:G.display(e.status),githubRepo:e.githubRepo}))));break}catch(e){n.e=e}finally{await n.d()}case`get`:try{var r=L();let t=e.id;t||T(`PROJECT_ID_REQUIRED`,`Project ID required`);let n=r.a(await R.create({host:e.host,module:e.module})).iter(`projects`).find(e=>e.id.toString()===t);n||T(`PROJECT_NOT_FOUND`,`Project not found: ${t}`),w(n),C()||console.log(V(`project`,[{id:n.id.toString(),name:n.name,status:G.display(n.status),githubRepo:n.githubRepo,description:n.description}]));break}catch(e){r.e=e}finally{await r.d()}case`status`:try{var i=L();let t=e.id;t||T(`PROJECT_ID_REQUIRED`,`Project ID required`);let n=i.a(await R.create({host:e.host,module:e.module})).iter(`projects`).find(e=>e.id.toString()===t);n||T(`PROJECT_NOT_FOUND`,`Project not found: ${t}`);let r=G.display(n.status);w({projectId:t,status:r}),C()||console.log(V(`project_status`,[{id:n.id.toString(),name:n.name,status:r}]));break}catch(e){i.e=e}finally{await i.d()}case`create`:(!e.name||!e[`github-repo`]||!e[`source-idea`])&&T(`ARGS_REQUIRED`,`--name, --github-repo, and --source-idea required`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{await B(t,`createProject`,{sourceIdeaId:BigInt(e[`source-idea`]),name:e.name,githubRepo:e[`github-repo`],description:e.description||``})}),w({created:!0,name:e.name,githubRepo:e[`github-repo`],sourceIdeaId:e[`source-idea`]}),C()||console.log(V(`project_created`,[{name:e.name,githubRepo:e[`github-repo`],sourceIdeaId:e[`source-idea`]}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`set-status`:{let t=e.id,n=e.value;(!t||!n)&&T(`ARGS_REQUIRED`,`Project ID and status required. Use: probe project set-status <id> <active|paused>`);let r=n.toLowerCase().replace(/[_\s]/g,``);[`active`,`paused`].includes(r)||T(`INVALID_STATUS`,`Invalid status: ${n}. Use: active, paused`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{await B(e,`updateProjectStatus`,{projectId:BigInt(t),status:G.fromString(n)})}),w({updated:!0,projectId:t,status:r}),C()||console.log(V(`project_status_updated`,[{projectId:t,status:r}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, get, create, status, set-status`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}}});const er=e=>{let t=e.trim().replace(/\.git$/i,``);if(!t)return;if(/^[\w.-]+\/[\w.-]+$/.test(t))return`https://github.com/${t}`;let n=t.match(/^git@github\.com:([\w.-]+\/[\w.-]+)$/i);if(n)return`https://github.com/${n[1]}`;if(t.startsWith(`http://`)||t.startsWith(`https://`))try{let e=new URL(t);if(e.hostname!==`github.com`)return;let n=e.pathname.split(`/`).filter(Boolean);return n.length<2?void 0:`https://github.com/${n[0]}/${n[1]}`}catch{return}},tr=async e=>{let t=e.action;t||T(`ACTION_REQUIRED`,`Task action required`);try{switch(t){case`list`:try{var n=L();let t=n.a(await R.create({host:e.host,module:e.module})).iter(`tasks`),r=e.status,i=e.limit?parseInt(e.limit,10):void 0;i!==void 0&&(!Number.isFinite(i)||i<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`),r&&(t=t.filter(e=>H.matches(e.status,r))),e.project&&(t=t.filter(t=>t.projectId.toString()===e.project)),e.assigned&&(t=t.filter(e=>e.assignedTo)),t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),i!==void 0&&(t=t.slice(0,i)),w({tasks:t,count:t.length}),C()||console.log(V(`tasks`,t.map(e=>({id:e.id.toString(),title:e.title,status:H.display(e.status),priority:e.priority,assignedTo:e.assignedTo||``,projectId:e.projectId}))));break}catch(e){n.e=e}finally{await n.d()}case`ready`:try{var r=L();let t=r.a(await R.create({host:e.host,module:e.module})),n=t.iter(`tasks`),i=t.iter(`task_dependencies`),a=new Map(n.map(e=>[e.id.toString(),e])),o=e.limit?parseInt(e.limit,10):void 0;o!==void 0&&(!Number.isFinite(o)||o<=0)&&T(`INVALID_LIMIT`,`--limit must be a positive integer`);let s=n.filter(e=>H.is.open(e.status)).filter(e=>!i.filter(t=>t.taskId===e.id).some(e=>{let t=typeof e.dependencyType==`string`?e.dependencyType:e.dependencyType.tag;if(t!==`Blocks`&&t!==`ParentChild`&&t!==`blocks`&&t!==`parent-child`)return!1;let n=a.get(e.dependsOnId.toString());return n?!H.is.completed(n.status):!1})).filter(t=>!e.project||t.projectId.toString()===e.project).filter(t=>!e.assigned||!!t.assignedTo).sort((e,t)=>{if(e.priority!==t.priority)return e.priority-t.priority;let n=K(e.createdAt),r=K(t.createdAt);return n<r?-1:+(n>r)}),c=(o===void 0?s:s.slice(0,o)).map(e=>({id:e.id.toString(),title:e.title,status:e.status.tag.toLowerCase(),priority:e.priority,assignedTo:e.assignedTo||``,projectId:e.projectId.toString(),blockedBy:[]}));w({tasks:c,count:c.length}),C()||console.log(V(`tasks`,c.map(e=>({id:e.id,title:e.title,status:e.status,priority:e.priority,assignedTo:e.assignedTo,projectId:e.projectId}))));break}catch(e){r.e=e}finally{await r.d()}case`get`:try{var i=L();let t=e.id;t||T(`TASK_ID_REQUIRED`,`Task ID required`);let n=i.a(await R.create({host:e.host,module:e.module})).iter(`tasks`).find(e=>e.id.toString()===t);n||T(`TASK_NOT_FOUND`,`Task not found: ${t}`),w(n),C()||console.log(V(`task`,[{id:n.id.toString(),title:n.title,status:H.display(n.status),priority:n.priority,assignedTo:n.assignedTo||``,projectId:n.projectId.toString(),githubIssueUrl:n.githubIssueUrl||``,githubPrUrl:n.githubPrUrl||``,description:n.description}]));break}catch(e){i.e=e}finally{await i.d()}case`create`:{(!e.project||!e.title)&&T(`ARGS_REQUIRED`,`--project and --title required`);let t=parseInt(e.priority||`5`,10);(t<1||t>10)&&T(`INVALID_PRIORITY`,`Priority must be 1-10`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{await B(n,`createTask`,{projectId:BigInt(e.project),title:e.title,description:e.description||``,priority:t,sourceIdeaId:void 0,githubIssueUrl:e[`github-issue-url`]})}),w({created:!0,projectId:e.project,title:e.title,issue:e[`github-issue-url`]}),C()||console.log(V(`task_created`,[{projectId:e.project,title:e.title,githubIssueUrl:e[`github-issue-url`]||``}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`claim`:{let t=e.id;t||T(`TASK_ID_REQUIRED`,`Task ID required`);try{let n,r;await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{await B(e,`claimTask`,{taskId:BigInt(t)});let i=e.iter(`tasks`).find(e=>e.id.toString()===t),a=i?e.iter(`projects`).find(e=>e.id===i.projectId):void 0;a?.githubRepo&&(n=er(a.githubRepo),n&&(r=`${n}/blob/main/CONTRIBUTING.md`))}),w({claimed:!0,taskId:t,repositoryUrl:n,contributingUrl:r,nextSteps:[n?`Fork the target repository: ${n}`:`Fork the target repository to your GitHub account using gh cli`,r?`Read CONTRIBUTING.md before starting: ${r}`:`Read CONTRIBUTING.md in the target repository before starting`,`Verify behavior independently by tracing relevant code flow and runtime path before implementing changes.`]}),C()||(console.log(V(`task_claimed`,[{taskId:t,repositoryUrl:n||``,contributingUrl:r||``}])),console.log(``),console.log(`Next steps:`),console.log(n?`1. Fork the target repository: ${n}`:`1. Fork the target repository to your GitHub account`),console.log(r?`2. Read CONTRIBUTING.md before starting: ${r}`:`2. Read CONTRIBUTING.md in the target repository before starting`),console.log(`3. Verify behavior independently by tracing relevant code flow and runtime path before implementing changes.`))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`update`:{let t=e.id;t||T(`TASK_ID_REQUIRED`,`Task ID required`),!e.status&&!e[`github-pr-url`]&&T(`UPDATE_REQUIRED`,`--status or --github-pr-url required`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{await B(n,`updateTaskStatus`,{taskId:BigInt(t),status:e.status?H.fromString(e.status):void 0,githubPrUrl:e[`github-pr-url`],archiveReason:void 0})}),w({updated:!0,taskId:t,status:e.status,pr:e[`github-pr-url`]}),C()||console.log(V(`task_updated`,[{taskId:t,status:e.status||``,githubPrUrl:e[`github-pr-url`]||``}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`review`:{let t=e.id;t||T(`TASK_ID_REQUIRED`,`Task ID required`);try{await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{await B(n,`updateTaskStatus`,{taskId:BigInt(t),status:{tag:`Review`},githubPrUrl:e[`github-pr-url`],archiveReason:void 0})}),w({reviewed:!0,taskId:t,status:`review`,pr:e[`github-pr-url`]}),C()||console.log(V(`task_review`,[{taskId:t,status:`review`,githubPrUrl:e[`github-pr-url`]||``}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`deps`:{let t=e.id;t||T(`TASK_ID_REQUIRED`,`Task ID required`);let n=BigInt(t);if(e[`add-dep`])try{await z({host:e.host,module:e.module,wallet:e.wallet},async t=>{await B(t,`addTaskDependency`,{taskId:n,dependsOnId:BigInt(e[`add-dep`]),dependencyType:{tag:`Blocks`}})}),w({added:!0,taskId:t,dependsOn:e[`add-dep`]}),C()||console.log(V(`dependency_added`,[{taskId:t,dependsOnId:e[`add-dep`],dependencyType:`blocks`}]))}catch(e){T(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}else if(e.list)try{var a=L();let t=a.a(await R.create({host:e.host,module:e.module})).iter(`task_dependencies`).filter(e=>e.taskId===n||e.dependsOnId===n);w({dependencies:t}),C()||console.log(V(`task_dependencies`,t.map(e=>({id:e.id.toString(),taskId:e.taskId.toString(),dependsOnId:e.dependsOnId.toString(),dependencyType:e.dependencyType}))))}catch(e){a.e=e}finally{await a.d()}else T(`DEPS_ACTION_REQUIRED`,`Use --add-dep <taskId> to add a dependency or --list to view dependencies`,`Examples: probe task deps 42 --list | probe task deps 42 --add-dep 17`);break}case`watch`:{let t=Math.min(parseInt(e.timeout||`60`,10),300);await z({host:e.host,module:e.module,wallet:e.wallet},async n=>{C()||console.log(V(`task_watch`,[{timeoutSeconds:t,statusFilter:e.status||``}]));let r=new Promise(e=>{let n=setTimeout(()=>{process.off(`SIGINT`,r),process.off(`SIGTERM`,r),e()},t*1e3),r=()=>{clearTimeout(n),process.off(`SIGINT`,r),process.off(`SIGTERM`,r),e()};process.on(`SIGINT`,r),process.on(`SIGTERM`,r)});n.db.tasks.onInsert((t,n)=>{(!e.status||H.matches(n.status,e.status))&&console.log(V(`tasks`,[{id:n.id.toString(),title:n.title,change_type:`created`}]))}),n.db.tasks.onUpdate((t,n,r)=>{(!e.status||H.matches(r.status,e.status))&&console.log(V(`tasks`,[{id:r.id.toString(),title:r.title,change_type:`updated`}]))}),await r});break}default:T(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, ready, get, create, claim, update, review, deps, watch`)}}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}};var nr=t({meta:{name:`task`,description:`Task management`},args:{action:{type:`positional`,description:`Action: list, ready, get, create, claim, update, review, deps, watch`,required:!1},id:{type:`positional`,description:`Task ID`,required:!1},status:{type:`string`,description:`Status filter or new status`},project:{type:`string`,description:`Project ID`},title:{type:`string`,description:`Task title`},description:{type:`string`,description:`Task description`},priority:{type:`string`,description:`Priority 1-10`},assigned:{type:`boolean`,description:`Show only assigned tasks`,default:!1},wallet:{type:`string`,description:`Wallet name`},"github-pr-url":{type:`string`,description:`GitHub PR URL`},"github-issue-url":{type:`string`,description:`GitHub issue URL`},"add-dep":{type:`string`,description:`Add dependency task ID`},list:{type:`boolean`,description:`List dependencies`,default:!1},timeout:{type:`string`,description:`Watch timeout (seconds)`},limit:{type:`string`,description:`Limit rows for list/ready`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&S(!0),!e.action){k({command:`probe task`,description:`Task management commands`,usage:[`probe task <action> [options]`,`probe task list --project 1 --status open`,`probe task create --project 1 --title "Fix bug" --priority 5`],actions:[{name:`list`,detail:`List tasks with optional filters`},{name:`ready`,detail:`List immediately claimable open tasks`},{name:`get <id>`,detail:`Show one task`},{name:`create`,detail:`Create a new task`},{name:`claim <id>`,detail:`Claim a task for your identity`},{name:`update <id>`,detail:`Update status and optional PR URL`},{name:`review <id>`,detail:`Mark a task as ready for review`},{name:`deps <id>`,detail:`List or add task dependencies`},{name:`watch`,detail:`Watch task changes in real time`}],options:[{name:`--project`,detail:`Project ID`},{name:`--title`,detail:`Task title (create)`},{name:`--description`,detail:`Task description`},{name:`--priority`,detail:`Priority from 1 to 10 (default: 5)`},{name:`--status`,detail:`Filter or new status`},{name:`--limit`,detail:`Limit rows for list/ready`},{name:`--github-pr-url`,detail:`GitHub PR URL for update/review`},{name:`--github-issue-url`,detail:`GitHub issue URL for create`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Use full long-form flags only; short aliases are intentionally disabled.`,"Find project IDs with `probe project list`; find task IDs with `probe task list`."]});return}await tr(e)}});const rr=5e3,ir=[{key:`agents`,name:`agents`},{key:`tasks`,name:`tasks`},{key:`ideas`,name:`ideas`},{key:`messages`,name:`messages`},{key:`channels`,name:`channels`},{key:`projects`,name:`projects`},{key:`votes`,name:`votes`},{key:`discovered_tasks`,name:`discovered_tasks`},{key:`task_dependencies`,name:`task_dependencies`},{key:`identity_roles`,name:`identity_roles`},{key:`config`,name:`config`},{key:`project_channels`,name:`project_channels`},{key:`project_messages`,name:`project_messages`}],ar=new Set([`connected`,`ready`,`disconnected`,`reconnecting`,`reconnected`,`subscription_applied`,`subscription_error`,`auth_failed`,`heartbeat_failed`,`heartbeat_recovered`,`shutdown`]),or=(e,t)=>typeof t==`bigint`?t.toString():t,sr=()=>new Date().toISOString(),cr=e=>new Promise(t=>setTimeout(t,e)),lr=e=>{let t=Math.floor(Math.random()*(rr*2+1)-rr);return Math.max(1e3,e+t)},ur=e=>lr(Math.min(3e4,1e3*2**Math.max(0,e-1))),dr=e=>e instanceof Error?e.message:String(e),J=e=>{if(e instanceof Error)return{name:e.name,message:e.message};if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===null)return e;if(typeof e==`bigint`)return e.toString();try{return JSON.parse(JSON.stringify(e,or))}catch{return String(e)}},fr=e=>e===`critical`||e===`info`||e===`debug`?e:`critical`,pr=(e,t)=>!!(t===`debug`||ar.has(e)||t===`info`&&e.startsWith(`heartbeat_`)),mr=async e=>{if(!e)return null;let t=l(e);return await f(s(t),{recursive:!0}),Ee(t,{flags:`a`})},hr=e=>{let t=e.toLowerCase();return t.includes(`authentication required`)||t.includes(`unauthorized`)||t.includes(`401`)},gr={wallet:{type:`string`,description:`Wallet name for authenticated connection`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},sender:{type:`string`,description:`Optional sender filter (debug table events only)`},"log-file":{type:`string`,description:`Optional path to append JSONL daemon events`},"log-level":{type:`string`,description:`critical, info, or debug`,default:`critical`},pretty:{type:`boolean`,description:`Human-readable lifecycle logs to stderr`,default:!1},json:{type:`boolean`,description:`Reserved for CLI consistency`,default:!1}};async function _r(e){let t=fr(e[`log-level`]),n=e.pretty?je({stdout:process.stderr,stderr:process.stderr}):null,r=null;try{r=await mr(e[`log-file`])}catch(e){let t=dr(e),n=JSON.stringify({source:`nexus`,at:sr(),type:`log_file_error`,message:t});console.log(n);return}let i=e=>{let t=JSON.stringify(e,or);console.log(t),r&&r.write(`${t}\n`)},a=e=>{if(!pr(e.type,t)||(i({source:`nexus`,at:sr(),...e}),!n))return;let r=String(e.type);r===`connected`?n.info(`Connected to Nexus`):r===`reconnected`?n.success(`Reconnected to Nexus`):r===`disconnected`?n.warn(`Disconnected from Nexus`):r===`reconnecting`?n.info(`Reconnecting to Nexus`):r===`auth_failed`?n.error(`Authentication failed`):r===`heartbeat_failed`?n.warn(`Heartbeat failed repeatedly`):r===`shutdown`&&n.info(`Nexus daemon shutting down`)},o=!1,s=null,c=new Promise(e=>{process.on(`SIGINT`,()=>{o||(o=!0,s=`SIGINT`,e())}),process.on(`SIGTERM`,()=>{o||(o=!0,s=`SIGTERM`,e())})}),l=0,u=null,d=!1;for(;!o;){let n=null;try{await z({host:e.host,module:e.module,wallet:e.wallet,onDisconnect:(...e)=>{n||={reason:`disconnected`,details:e.map(J)}}},async r=>{let i=r.auth?.wallet||e.wallet||null,s=r.iter(`agents`).find(e=>e.identity.toHexString()===r.identity?.toHexString());if(a(d?{type:`reconnected`,attempts:l,downtime_ms:u?Date.now()-u:null,identity:r.identity?.toHexString()}:{type:`connected`,identity:r.identity?.toHexString(),wallet:i,host:e.host||r.config.spacetime.host,module:e.module||r.config.spacetime.module}),d=!0,l=0,u=null,a({type:`subscription_applied`}),a({type:`ready`,identity:r.identity?.toHexString(),wallet:i,log_file:e[`log-file`]||null,log_level:t,auto_heartbeat:!!s}),t===`debug`)for(let t of ir){let n=r.db[t.key];n.onInsert?.((n,r)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&r.senderId!==e.sender||a({type:`table_insert`,table:t.name,row:J(r)})}),n.onUpdate?.((n,r,i)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&i.senderId!==e.sender||a({type:`table_update`,table:t.name,old_row:J(r),new_row:J(i)})}),n.onDelete?.((n,r)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&r.senderId!==e.sender||a({type:`table_delete`,table:t.name,row:J(r)})})}let f=null,p=!1,m=0,ee=()=>{o||!s||(f=setTimeout(async()=>{if(!s||p||o){ee();return}p=!0;try{await B(r,`heartbeat`,{agentId:s.id}),m>0&&a({type:`heartbeat_recovered`,failed_count_before_recovery:m}),m=0}catch(e){m+=1,m>=3&&!n&&(n={reason:`heartbeat_failed`,details:{consecutive_failures:m,message:dr(e)}},a({type:`heartbeat_failed`,consecutive_failures:m,message:dr(e)}))}finally{p=!1,ee()}},lr(6e4)))};for(s&&ee();!o&&!n;)await Promise.race([c,cr(200)]);f&&clearTimeout(f)})}catch(e){let t=dr(e);if(hr(t)){a({type:`auth_failed`,message:t});break}a({type:`subscription_error`,message:t}),n={reason:`disconnected`,details:{message:t}}}if(o)break;a({type:`disconnected`,reason:n?.reason||`disconnected`,details:J(n?.details||null)}),u===null&&(u=Date.now()),l+=1;let r=ur(l);a({type:`reconnecting`,attempt:l,backoff_ms:r}),await Promise.race([c,cr(r)])}a({type:`shutdown`,signal:s||`unknown`}),r&&r.end()}var vr=t({meta:{name:`nexus`,description:`Persistent Nexus daemon (keepalive + critical telemetry)`},args:gr,async run({args:e}){if(A()){k({command:`probe nexus`,description:`Run persistent Nexus keepalive + critical event logger`,usage:[`probe nexus [options]`,`probe nexus --wallet agent-wallet`,`probe nexus --wallet agent-wallet --log-file ./logs/nexus-events.jsonl`,`probe nexus --log-level debug --sender zoe-1`,`probe nexus --pretty`],options:[{name:`--wallet`,detail:`Wallet for authenticated persistent connection`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`},{name:`--log-level`,detail:`critical (default), info, or debug`},{name:`--sender`,detail:`Sender filter for debug message events only`},{name:`--log-file`,detail:`Optional JSONL file path for daemon events`},{name:`--pretty`,detail:`Human-readable lifecycle logs to stderr`}],notes:[`stdout is always structured JSONL for machine parsing.`,`Default mode logs critical connection lifecycle and heartbeat health events only.`,`Use --log-level debug to emit full table insert/update/delete payloads.`]});return}await _r(e)}});const Y={AgentRole:e=>Array.isArray(e)?[`Zoe`,`Admin`,`Zeno`][e[0]]??`variant_${e[0]}`:e,AgentStatus:e=>Array.isArray(e)?[`Online`,`Offline`,`Working`][e[0]]??`variant_${e[0]}`:e,AnnouncementStatus:e=>Array.isArray(e)?[`Pending`,`Ready`,`Failed`][e[0]]??`variant_${e[0]}`:e,DependencyType:e=>Array.isArray(e)?[`Blocks`,`ParentChild`][e[0]]??`variant_${e[0]}`:e,DiscoveredTaskStatus:e=>Array.isArray(e)?[`PendingReview`,`Approved`,`Rejected`,`EscalatedToIdea`][e[0]]??`variant_${e[0]}`:e,DiscoveryDecision:e=>Array.isArray(e)?[`ApproveAsTask`,`Reject`,`EscalateToIdea`][e[0]]??`variant_${e[0]}`:e,IdeaStatus:e=>Array.isArray(e)?[`Voting`,`ApprovedForProject`,`Rejected`,`Implemented`][e[0]]??`variant_${e[0]}`:e,MessageType:e=>Array.isArray(e)?[`User`,`System`,`Directive`][e[0]]??`variant_${e[0]}`:e,ProjectStatus:e=>Array.isArray(e)?[`Active`,`Paused`][e[0]]??`variant_${e[0]}`:e,TaskStatus:e=>Array.isArray(e)?[`Open`,`Claimed`,`InProgress`,`Review`,`Completed`,`Blocked`,`Archived`][e[0]]??`variant_${e[0]}`:e,VoteType:e=>Array.isArray(e)?[`Up`,`Down`,`Veto`][e[0]]??`variant_${e[0]}`:e},X=e=>{if(!Array.isArray(e))return e;let t=e[0];return typeof t!=`number`&&typeof t!=`bigint`?e:new Date(Number(t)/1e3).toISOString()},Z=e=>t=>{if(!Array.isArray(t))return t;let[n,r]=t;return n===1?null:e?e(r):Array.isArray(r)&&r.length===1?r[0]:r},yr={agents:{last_heartbeat:X,current_task_id:Z(),created_at:X,last_active_at:X,role:Y.AgentRole,status:Y.AgentStatus},channels:{created_at:X},discovered_tasks:{created_task_id:Z(),rejection_reason:Z(),created_at:X,reviewed_at:Z(X),reviewed_by:Z(),status:Y.DiscoveredTaskStatus},ideas:{created_at:X,updated_at:X,status:Y.IdeaStatus},identity_roles:{role:Y.AgentRole},messages:{context_id:Z(),created_at:X},project_channels:{created_at:X},project_messages:{context_id:Z(),created_at:X},projects:{created_at:X,status:Y.ProjectStatus},task_dependencies:{created_at:X},tasks:{assigned_to:Z(),claimed_at:Z(X),github_issue_url:Z(),github_pr_url:Z(),source_idea_id:Z(),archived_reason:Z(),status_changed_by:Z(),status_changed_at:Z(X),created_at:X,updated_at:X,status:Y.TaskStatus,blocked_from_status:Z(Y.TaskStatus)},voice_announcements:{context_type:Z(),context_id:Z(),finalized_at:Z(X),failed_at:Z(X),error_message:Z(),created_at:X,status:Y.AnnouncementStatus},votes:{created_at:X}};function br(e){return e.match(/FROM\s+(\w+)/i)?.[1]?.toLowerCase()}const xr=e=>{if(typeof e.name==`string`)return e.name;if(e.name&&typeof e.name==`object`&&`some`in e.name)return e.name.some};var Sr=class extends Error{status;responseBody;constructor(e,t,n){super(n||`SQL request failed with status ${e}`),this.name=`SqlRequestError`,this.status=e,this.responseBody=t}};const Cr=e=>{let t=new URL(e);if(t.protocol===`ws:`)t.protocol=`http:`;else if(t.protocol===`wss:`)t.protocol=`https:`;else if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Unsupported host protocol: ${t.protocol}`);return t.toString()},wr=(e,t)=>{let n=Cr(e),r=new URL(n);return r.pathname=`${r.pathname.replace(/\/$/,``)}/v1/database/${encodeURIComponent(t)}/sql`,r.toString()},Tr=e=>{if(!Array.isArray(e))throw Error(`Invalid SQL response: expected array of statement results`);return e.map(e=>{let t=e,n=Array.isArray(t.rows)?t.rows:[];return{schema:t.schema,rows:n}})},Er=async e=>{let t=wr(e.host,e.moduleName),n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs),i=Date.now();try{let r=await fetch(t,{method:`POST`,headers:{Authorization:`Bearer ${e.token}`,"Content-Type":`text/plain`,Accept:`application/json`},body:e.sql,signal:n.signal}),a=await r.text();if(!r.ok)throw new Sr(r.status,a);let o;try{o=a?JSON.parse(a):[]}catch{throw Error(`Invalid SQL response: expected JSON payload`)}return{results:Tr(o),durationMs:Date.now()-i}}finally{clearTimeout(r)}},Dr=e=>{let t=e.schema;return t&&`elements`in t&&Array.isArray(t.elements)?t.elements.map(xr).filter(e=>e!==void 0):t&&`columns`in t&&Array.isArray(t.columns)?t.columns.map(e=>e.name):[]},Or=e=>{let t;try{t=JSON.parse(e).error||e}catch{t=e}return t.includes(`ORDER BY`)?{message:t,suggestion:`SpacetimeDB SQL does not support ORDER BY. Remove it or filter/sort results locally.`}:t.includes(`IS NULL`)||t.includes(`IS NOT NULL`)?{message:t,suggestion:`Use "column = NULL" or "column != NULL" instead of IS NULL / IS NOT NULL.`}:t.includes(`JOIN`)?{message:t,suggestion:`SpacetimeDB has limited JOIN support. Try querying single tables or use multiple queries.`}:t.includes(`no such table`)?{message:t,suggestion:`Check the table name. Common tables: tasks, projects, agents, ideas, messages.`}:t.includes(`no such column`)?{message:t,suggestion:`Check the column name. Use SELECT * to see all available columns.`}:{message:t}},kr=Object.keys(yr),Ar=(e,t)=>{if(e instanceof Sr){e.status===401&&T(`AUTH_REQUIRED`,"Authentication required. Run `probe auth <wallet> --save` first.");let{message:t,suggestion:n}=Or(e.responseBody);e.status===400&&T(`SQL_INVALID`,t,n),T(`SQL_FAILED`,t,n)}e instanceof Error&&e.name===`AbortError`&&T(`SQL_UNAVAILABLE`,`SQL request timed out after ${t}ms`),T(`SQL_UNAVAILABLE`,e instanceof Error?e.message:`SQL request failed`)},jr=3e4,Mr=(e,t)=>({duration_ms:t,query_count:e.length,row_count_total:e.reduce((e,t)=>e+t.rows.length,0)}),Nr=(e,t,n)=>{let r={};for(let i=0;i<e.length;i+=1){let a=e[i],o=Dr(a),s=t&&n?yr[n]:void 0,c=a.rows.map(e=>{let t={};for(let n=0;n<o.length;n++){let r=o[n],i=e[n],a=s?.[r];t[r]=a?a(i):i}return t});r[`query_${i+1}`]={columns:o,rows:c}}return e.length===0&&(r.query_1={columns:[],rows:[]}),r},Pr=(e,t,n,r,i)=>{let a={},o=r&&i?yr[i]:void 0;for(let t=0;t<e.length;t+=1){let n=e[t],r=Dr(n),i=n.rows.map(e=>{let t={};for(let n=0;n<r.length;n++){let i=r[n],a=e[n],s=o?.[i];t[i]=s?s(a):a}return t});a[`query_${t+1}`]=i}return e.length===0&&(a.query_1=[]),t&&(a.meta=[Mr(e,n)]),Dn(a)};var Fr=t({meta:{name:`query`,description:`Run SQL read queries against Nexus`},args:{sql:{type:`positional`,description:`SQL query string`,required:!1},file:{type:`string`,description:`Read SQL from file path`},wallet:{type:`string`,description:`Wallet name override`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},timeout:{type:`string`,description:`Request timeout in milliseconds`},meta:{type:`boolean`,description:`Include metadata in output`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1},tables:{type:`boolean`,description:`List all available tables`,default:!1},decode:{type:`boolean`,description:`Decode algebraic types to human-readable values`,default:!0},raw:{type:`boolean`,description:`Output raw algebraic type arrays (no decoding)`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.sql||e.file;if(e.tables){C()?w({tables:kr}):console.log(Dn({tables:kr}));return}if(!t){k({command:`probe query`,description:`Execute SQL against the configured Nexus SpacetimeDB module`,usage:[`probe query "SELECT * FROM tasks LIMIT 5"`,`probe query --file ./query.sql --meta`,`probe query --tables`],options:[{name:`--file`,detail:`Read SQL from file`},{name:`--wallet`,detail:`Wallet override (defaults to config defaultWallet)`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`},{name:`--timeout`,detail:`Request timeout in ms (default: ${jr})`},{name:`--meta`,detail:`Include metadata in output`},{name:`--json`,detail:`JSON output mode with keyed objects`},{name:`--tables`,detail:`List all available tables`},{name:`--decode`,detail:`Decode algebraic types (default: true)`},{name:`--raw`,detail:`Output raw algebraic arrays (no decoding)`}],notes:[`This command is read-only and intended for SQL queries against Nexus tables.`,`JSON mode returns keyed objects: {"query_1": {"columns": [...], "rows": [{"id": 1, ...}]}}`,`Use --raw to see raw SpacetimeDB algebraic type arrays.`]});return}let n=e.timeout?Number.parseInt(e.timeout,10):jr;(!Number.isFinite(n)||n<=0)&&T(`INVALID_TIMEOUT`,`Invalid timeout: ${e.timeout}`);let r=await x(),i=e.wallet||r.defaultWallet;i||T(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`),await N(i)||T(`WALLET_NOT_FOUND`,`Wallet not found: ${i}`);let a=await j(i);a||T(`AUTH_REQUIRED`,"No cached token. Run `probe auth <wallet> --save` first.");let o=e.host||r.spacetime.host,s=e.module||r.spacetime.module,c=e.file?await p(e.file,`utf-8`):e.sql??``;c.trim()||T(`SQL_REQUIRED`,`SQL query is empty`);let l=e.raw?!1:e.decode??!0,u=br(c);try{let{results:t,durationMs:r}=await Er({host:o,moduleName:s,token:a.token,sql:c,timeoutMs:n});if(C()){let n=Nr(t,l,u);e.meta?w({...n,meta:Mr(t,r)}):w(n);return}console.log(Pr(t,!!e.meta,r,l,u))}catch(e){Ar(e,n)}}}),Ir=t({meta:{name:`sign`,description:`Sign a message using wallet private key`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},message:{type:`positional`,description:`Message to sign`,required:!1},"message-file":{type:`string`,description:`Read message from file`},"password-file":{type:`string`,description:`Read password from file`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(!t){k({command:`probe sign`,description:`Sign arbitrary text using wallet private key`,usage:[`probe sign <wallet-name> <message> [options]`,`probe sign <wallet-name> --message-file ./payload.txt [options]`],options:[{name:`--message-file`,detail:`Read message content from file`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--json`,detail:`JSON output for agents`}]});return}let n;if(e[`message-file`])try{n=await p(e[`message-file`],`utf-8`)}catch{T(`FILE_READ_ERROR`,`Failed to read message file: ${e[`message-file`]}`)}else e.message?n=e.message:T(`MESSAGE_REQUIRED`,`Message or message-file required`);let i=await Xe({passwordFile:e[`password-file`],promptMessage:`Enter wallet password:`,jsonModeError:`Password file required in JSON mode or provide PROBE_WALLET_PASSWORD`});try{let e=(await mt(t,i)).getKeyPair(0),a=e.sign(r.from(n)),o=e.getPublicKey(),s=e.getAddress();w({wallet:t,message:n,signature:a.toString(`hex`),publicKey:o.toString(`hex`),address:s.toString()}),C()||(D(`Message signed successfully`),console.log(`Signature: ${a.toString(`hex`)}`))}catch(e){T(`SIGN_ERROR`,e instanceof Error?e.message:`Failed to sign message`)}}}),Lr=t({meta:{name:`token`,description:`Show cached JWT token for wallet`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},clear:{type:`boolean`,description:`Clear cached token now (next auth call gets a new token)`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(!t){k({command:`probe token`,description:`Inspect or clear cached authentication token`,usage:[`probe token <wallet-name> [options]`,`probe token <wallet-name> --clear`],options:[{name:`--clear`,detail:`Clear cached token now (recommended)`},{name:`--json`,detail:`JSON output for agents`}]});return}if(e.clear){await lt(t),w({cleared:t}),C()||E(`Token cache cleared for "${t}". Run 'probe auth' to get a new token.`);return}try{let e=await j(t);e||T(`TOKEN_NOT_FOUND`,`No cached token for wallet '${t}'`,`Run 'probe auth ${t} --save' to authenticate`);let n=new Date(e.expiresAt),r=new Date,i=Math.floor((n.getTime()-r.getTime())/1e3),a=i>0;w({wallet:t,token:e.token,expiresAt:e.expiresAt,expiresIn:Math.max(0,i),valid:a}),C()||(console.log(`Wallet: ${t}`),console.log(`Token: ${e.token.slice(0,50)}...`),console.log(`Expires: ${n.toUTCString()}`),console.log(`Status: ${a?`Valid`:`Expired`}`),a||E(`Token has expired. Run with --clear to remove it and re-authenticate.`))}catch(e){T(`TOKEN_ERROR`,e instanceof Error?e.message:`Failed to read token`)}}});const Q=`@zenon-red/probe`,Rr=3e4,zr=e(import.meta.url);function $(e){let t=e.trim();return t.startsWith(`${Q}@`)?t.slice(`${Q}@`.length):t.startsWith(`refs/tags/`)?$(t.slice(10)):t.replace(/^v/,``)}function Br(){let e=[`../../package.json`,`../package.json`,`../../../package.json`];try{for(let t of e)try{let e=zr(t).version;if(e)return e}catch{}if(process.env.npm_package_version)return process.env.npm_package_version}catch{}return`0.0.0`}function Vr(e){if(e&&e!==`auto`)return e;let t=process.execPath,n=process.argv[1]||``,r=``;try{r=Me(`command -v probe`,{timeout:5e3,encoding:`utf8`}).trim()}catch{}if(t.includes(`.probe`)||t.includes(`probe-linux`)||t.includes(`probe-darwin`)||t.includes(`probe-windows`)||n.includes(`.probe`)||r.includes(`.probe`)||r.includes(`probe-linux`)||r.includes(`probe-darwin`)||r.includes(`probe-windows`))return`binary`;if(n.includes(`node_modules`)||r.includes(`node_modules`))return`npm`;try{if(Me(`npm list -g @zenon-red/probe --depth=0 2>/dev/null`,{timeout:1e4,encoding:`utf8`}).includes(`@zenon-red/probe`))return`npm`}catch{}return`unknown`}async function Hr(){let e=`https://registry.npmjs.org/${Q}/latest`,t=await fetch(e,{signal:AbortSignal.timeout(Rr)});if(!t.ok)throw Error(`npm registry returned ${t.status}`);let n=await t.json();if(!n.version)throw Error(`No version field in npm response`);return $(n.version)}async function Ur(e){let t=`https://api.github.com/repos/zenon-red/probe/releases/${e}`,n=await fetch(t,{headers:{Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(Rr)});if(!n.ok)throw Error(`GitHub API returned ${n.status}`);return await n.json()}async function Wr(){let e=await Ur(`latest`);return{version:$(e.tag_name),release:e}}async function Gr(e){let t=$(e);try{return await Ur(`tags/v${t}`)}catch(e){if(!(e instanceof Error?e.message:``).includes(`404`))throw e;return await Ur(`tags/${encodeURIComponent(`${Q}@${t}`)}`)}}function Kr(){let e=o(),t=i(),n={linux:`linux`,darwin:`darwin`,windows:`windows`},r={x64:`x64`,arm64:`arm64`},a=n[e],s=r[t];if(!a||!s)throw Error(`Unsupported platform: ${e}/${s}`);return`probe-${a}-${s}${o()===`windows`?`.exe`:``}`}function qr(){return s(process.execPath)}async function Jr(e,t){let n=await fetch(e,{signal:AbortSignal.timeout(Rr*2),redirect:`follow`});if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);if(!n.body)throw Error(`Empty response body`);let r=Pe.fromWeb(n.body),i=Ee(t,{mode:493});await Fe(r.pipe(i))}function Yr(e,t){let n=e.split(`/`).pop()||e.split(`\\`).pop()||``,r=t.split(`
6
- `),i=``;for(let e of r){let[t,r]=e.trim().split(/\s+/);if(r===n){i=t;break}}if(!i)return!1;let a=Oe(e);return Ne(`sha256`).update(a).digest(`hex`)===i}async function Xr(e){Me(`npm install -g ${Q}@${$(e)}`,{stdio:`inherit`,timeout:12e4})}async function Zr(e,t){let n=Kr(),r=e.assets.find(e=>e.name===n);if(!r)throw Error(`Asset not found for ${n}`);let i=e.assets.find(e=>e.name===`SHA256SUMS.txt`);if(!i)throw Error(`SHA256SUMS.txt not found in release`);let a=l(qr(),o()===`windows`?`probe.exe`:`probe`),s=`${a}.tmp`,c=`${a}.bak`;await Jr(r.browser_download_url,s);let u=await fetch(i.browser_download_url,{signal:AbortSignal.timeout(Rr)});if(!u.ok)throw Error(`Failed to download SHA256SUMS.txt`);if(!Yr(s,await u.text()))throw Ae(s),Error(`CHECKSUM_MISMATCH`);try{if(De(a)&&ke(a,c),ke(s,a),Me(`"${a}" --version`,{timeout:1e4,encoding:`utf8`}),De(c))try{Ae(c)}catch{}}catch(e){if(De(c))try{ke(c,a)}catch{throw Error(`ROLLBACK_FAILED: Upgrade failed and rollback also failed. Backup at: ${c}`)}if(De(s))try{Ae(s)}catch{}throw e}}const Qr=new Set([`auto`,`npm`,`binary`]),$r=e=>{w(e),!C()&&console.log(V(`upgrade_result`,[{method:e.method,currentVersion:e.currentVersion,targetVersion:e.targetVersion,latestVersion:e.latestVersion,updated:e.updated,checkOnly:e.checkOnly}]))};var ei=t({meta:{name:`upgrade`,description:`Upgrade Probe to the latest or a specific version`},args:{target:{type:`positional`,description:`Version to upgrade to (e.g. 1.2.0 or v1.2.0)`,required:!1},check:{type:`boolean`,description:`Check for updates without upgrading`,default:!1},method:{type:`string`,description:`Installation method: auto, npm, binary`},yes:{type:`boolean`,description:`Skip confirmation prompts`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&S(!0),e.target===`--help`||e.target===`-h`){k({command:`probe upgrade`,description:`Upgrade Probe to the latest or a specific version`,usage:[`probe upgrade`,`probe upgrade --check`,`probe upgrade 1.2.0`,`probe upgrade --method npm`,`probe upgrade --method binary --yes`,`probe upgrade --json --check`],options:[{name:`--check`,detail:`Check for updates without upgrading`},{name:`--method`,detail:`Force install method: auto, npm, binary`},{name:`--yes`,detail:`Skip confirmation prompts`},{name:`--json`,detail:`JSON output`}]});return}let t=e.method;t&&!Qr.has(t)&&T(`INVALID_METHOD`,`Invalid --method value: ${e.method}`,`Use: --method auto | npm | binary`);let n=Br(),r=Vr(t),i,a,o;try{if(e.target)i=$(e.target),r===`binary`&&(o=await Gr(i));else if(r===`npm`)a=await Hr(),i=a;else{let e=await Wr();a=e.version,i=e.version,o=e.release}}catch(t){let n=t instanceof Error?t.message:`Failed to check latest version`;!e.target&&r===`binary`&&n.includes(`GitHub API returned 404`)&&T(`NO_RELEASES_PUBLISHED`,`No GitHub releases are published yet for binary upgrades.`,`Use: npm install -g @zenon-red/probe (or your package manager) until the first release is published.`),T(`VERSION_LOOKUP_FAILED`,n)}i||T(`VERSION_LOOKUP_FAILED`,`Could not determine target version.`);let s=i!==n;if(e.check){$r({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:s,updated:!1,checkOnly:!0});return}if(r===`unknown`&&T(`METHOD_UNKNOWN`,`Could not detect installation method for in-place upgrade.`,"Use --method npm|binary explicitly, or run your package manager upgrade command (e.g. `bun add -g @zenon-red/probe`)."),!s){$r({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:!1,updated:!1,checkOnly:!1});return}!C()&&!e.yes&&(await te({message:`Upgrade Probe from ${n} to ${i}?`})||(E(`Upgrade cancelled`),process.exit(0)));try{r===`npm`?await Xr(i):await Zr(o||await Gr(i),i)}catch(e){let t=e instanceof Error?e.message:`Upgrade failed`;T(t.includes(`CHECKSUM_MISMATCH`)?`CHECKSUM_MISMATCH`:t.includes(`ROLLBACK_FAILED`)?`ROLLBACK_FAILED`:t.includes(`PERMISSION`)||t.includes(`EACCES`)?`PERMISSION_DENIED`:`UPGRADE_FAILED`,t)}$r({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:!0,updated:!0,checkOnly:!1})}}),ti=t({meta:{name:`create`,description:`Create a new wallet with randomly generated mnemonic`},args:{name:{type:`positional`,description:`Wallet identifier`,required:!1},"password-file":{type:`string`,description:`Read password from file`},"set-default":{type:`boolean`,description:`Set this wallet as the default`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(A()||!t){k({command:`probe wallet create`,description:`Create a new encrypted wallet`,usage:[`probe wallet create <name> [options]`,`probe wallet create agent-wallet --set-default`],options:[{name:`--password-file`,detail:`Read wallet password from file`},{name:`--set-default`,detail:`Set created wallet as default`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Password source order: --password-file, PROBE_WALLET_PASSWORD, interactive prompt.`]});return}/^[a-zA-Z0-9_-]+$/.test(t)||T(`INVALID_NAME`,`Wallet name must be alphanumeric with hyphens or underscores only`);let n=await x(),r=await Xe({passwordFile:e[`password-file`],promptMessage:`Enter password to encrypt wallet:`,confirmPromptMessage:`Confirm password:`,minLength:n.passwordMinLength,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt`});try{let n=await dt(t,r),i=e[`set-default`];if(i||(await pt()).length===1&&(i=!0),i){let e=await y();e.defaultWallet=n.name,await ze(e)}w({name:n.name,address:n.address,publicKey:n.publicKey,mnemonic:n.mnemonic,default:i}),C()||(D(`Wallet "${n.name}" created successfully`),console.log(`Address: ${n.address}`),console.log(`\nMnemonic: ${n.mnemonic}`),qe(`Save this mnemonic securely - it cannot be recovered!`),i&&console.log(`
7
- Set as default wallet`))}catch(e){T(`WALLET_CREATE_ERROR`,e instanceof Error?e.message:`Failed to create wallet`)}}}),ni=t({meta:{name:`default`,description:`Set the default wallet`},args:{name:{type:`positional`,description:`Wallet name to set as default`,required:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(A()||!t){k({command:`probe wallet default`,description:`Set the default wallet used by commands`,usage:[`probe wallet default <name> [options]`,`probe wallet default agent-wallet`],options:[{name:`--json`,detail:`JSON output for agents`}]});return}await gt(t)||T(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`);let n=await y();n.defaultWallet=t,await ze(n),w({defaultWallet:t}),C()||D(`Default wallet set to '${t}'`)}}),ri=t({meta:{name:`delete`,description:`Delete a wallet`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},yes:{type:`boolean`,description:`Skip confirmation prompt`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(A()||!t){k({command:`probe wallet delete`,description:`Delete a wallet from local storage`,usage:[`probe wallet delete <name> [options]`,`probe wallet delete old-wallet --yes`],options:[{name:`--yes`,detail:`Skip interactive confirmation prompt`},{name:`--json`,detail:`JSON output for agents`}]});return}await gt(t)||T(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`,`Run 'probe wallet list' to see available wallets`),!C()&&!e.yes&&(await te({message:`Are you sure you want to delete wallet "${t}"? This cannot be undone.`})||(E(`Deletion cancelled`),process.exit(0)));try{await ht(t),w({deleted:t}),C()||D(`Wallet "${t}" deleted successfully`)}catch(e){T(`WALLET_DELETE_ERROR`,e instanceof Error?e.message:`Failed to delete wallet`)}}}),ii=t({meta:{name:`import`,description:`Import wallet from mnemonic phrase`},args:{name:{type:`positional`,description:`Wallet identifier`,required:!1},mnemonic:{type:`string`,description:`Mnemonic phrase (space-separated)`},"mnemonic-file":{type:`string`,description:`Read mnemonic from file`},"password-file":{type:`string`,description:`Read password from file`},"set-default":{type:`boolean`,description:`Set this wallet as the default`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(A()||!t){k({command:`probe wallet import`,description:`Import an encrypted wallet from mnemonic`,usage:[`probe wallet import <name> [options]`,`probe wallet import agent-wallet --mnemonic-file ./mnemonic.txt`],options:[{name:`--mnemonic`,detail:`24-word mnemonic phrase`},{name:`--mnemonic-file`,detail:`Read mnemonic from file`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--set-default`,detail:`Set imported wallet as default`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Mnemonic source order: --mnemonic, --mnemonic-file, PROBE_WALLET_MNEMONIC, interactive prompt.`]});return}/^[a-zA-Z0-9_-]+$/.test(t)||T(`INVALID_NAME`,`Wallet name must be alphanumeric with hyphens or underscores only`);let n=await Ze({mnemonic:e.mnemonic,mnemonicFile:e[`mnemonic-file`],jsonModeError:`Mnemonic required via --mnemonic, --mnemonic-file, or PROBE_WALLET_MNEMONIC env`}),r=await Xe({passwordFile:e[`password-file`],promptMessage:`Enter password to encrypt wallet:`,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt`});try{let i=await ft(t,n,r),a=e[`set-default`];if(a||(await pt()).length===1&&(a=!0),a){let e=await y();e.defaultWallet=i.name,await ze(e)}w({name:i.name,address:i.address,default:a}),C()||(D(`Wallet "${i.name}" imported successfully`),console.log(`Address: ${i.address}`),a&&console.log(`
8
- Set as default wallet`))}catch(e){T(`WALLET_IMPORT_ERROR`,e instanceof Error?e.message:`Failed to import wallet`)}}}),ai=t({meta:{name:`list`,description:`List all stored wallets`},args:{json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(A()){k({command:`probe wallet list`,description:`List all locally stored wallets`,usage:[`probe wallet list [options]`,`probe wallet list --json`],options:[{name:`--json`,detail:`JSON output for agents`}]});return}e.json&&S(!0);try{let e=await pt(),t=await x(),n=e.map(e=>({...e,default:e.name===t.defaultWallet}));if(w(n),!C())if(e.length===0)E(`No wallets found`);else{console.log(`Wallets:`);for(let e of n){let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`unknown`,n=e.default?`*`:` `;console.log(`${n} ${e.name.padEnd(12)} ${e.address.slice(0,10)}... created ${t}`)}t.defaultWallet&&console.log(`
9
- * = default wallet`)}}catch(e){T(`WALLET_LIST_ERROR`,e instanceof Error?e.message:`Failed to list wallets`)}}}),oi=t({meta:{name:`show`,description:`Show wallet address and public key`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},"public-key":{type:`boolean`,description:`Include public key in output`,default:!1},"password-file":{type:`string`,description:`Read password from file`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&S(!0);let t=e.name;if(A()||!t){k({command:`probe wallet show`,description:`Show wallet address and optional public key`,usage:[`probe wallet show <name> [options]`,`probe wallet show my-wallet --public-key --password-file ./pass.txt`],options:[{name:`--public-key`,detail:`Include public key in output`},{name:`--password-file`,detail:`Read password for public key extraction`},{name:`--json`,detail:`JSON output for agents`}]});return}let n=await N(t);n||T(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`,`Run 'probe wallet list' to see available wallets`);let r;if(e[`password-file`])try{r=await p(e[`password-file`],`utf-8`),r=r.trim()}catch{T(`FILE_READ_ERROR`,`Failed to read password file: ${e[`password-file`]}`)}try{let i;r&&(i=(await mt(t,r)).getKeyPair(0).getPublicKey().toString(`hex`));let a={name:n.name,address:n.address,createdAt:n.createdAt};(e[`public-key`]||i)&&(a.publicKey=i),w(a),C()||(console.log(`Name: ${n.name}`),console.log(`Address: ${n.address}`),n.createdAt&&console.log(`Created: ${new Date(n.createdAt).toLocaleString()}`),i&&console.log(`Public Key: ${i}`))}catch(e){T(`WALLET_LOAD_ERROR`,e instanceof Error?e.message:`Failed to load wallet`)}}});const si=new Set([`create`,`import`,`list`,`show`,`delete`,`default`]);var ci=t({meta:{name:`wallet`,description:`Manage Zenon Network wallets`},run(){let e=process.argv.slice(2).filter(e=>!e.startsWith(`-`));e.length>1&&si.has(e[1])||k({command:`probe wallet`,description:`Create, import, inspect, and manage wallets`,usage:[`probe wallet <subcommand> [positionals] [options]`,`probe wallet create my-wallet --set-default`,`probe wallet import my-wallet --mnemonic-file ./mnemonic.txt`],actions:[{name:`create <name>`,detail:`Create a new encrypted wallet`},{name:`import <name>`,detail:`Import wallet from mnemonic phrase`},{name:`list`,detail:`List stored wallets`},{name:`show <name>`,detail:`Show wallet address and optional public key`},{name:`delete <name>`,detail:`Delete a wallet`},{name:`default <name>`,detail:`Set default wallet`}],notes:[`Use long-form flags only for predictable agent automation.`]})},subCommands:{create:ti,import:ii,list:ai,show:oi,delete:ri,default:ni}}),li=t({meta:{name:`whoami`,description:`Show current authenticated agent profile`},args:{wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){e.json&&S(!0);try{await z({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=e.iter(`agents`).find(t=>t.identity.toHexString()===e.identity?.toHexString());t||T(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),w(t),C()||console.log(V(`agent`,[{id:t.id,name:t.name,role:An.display(t.role),status:U.display(t.status),lastHeartbeat:q(t.lastHeartbeat),currentTaskId:t.currentTaskId?t.currentTaskId.toString():``,capabilities:t.capabilities.join(`,`),identity:e.identity?.toHexString()||``}]))})}catch(e){T(`CONNECTION_ERROR`,e instanceof Error?e.message:String(e))}}});const ui=new Set([`wallet`,`auth`,`sign`,`token`,`config`,`nexus`,`agent`,`task`,`message`,`idea`,`discover`,`project`,`query`,`doctor`,`whoami`,`upgrade`]),di=()=>{let e=at(process.argv.slice(2));it(e.forceHelp),process.argv=[...process.argv.slice(0,2),...e.argv]},{version:fi,description:pi}=e(import.meta.url)(`../package.json`),mi=t({meta:{name:`probe`,version:fi,description:pi},args:{json:{type:`boolean`,description:`Output JSON only`,default:!1}},run(){let e=process.argv.slice(2).find(e=>!e.startsWith(`-`));e&&ui.has(e)||k({command:`probe`,description:pi,usage:[`probe <command> [positionals] [options]`,`probe idea propose --title "Better task scoring" --category planning`,`probe task claim 42 --wallet agent-wallet`],actions:[{name:`wallet`,detail:`Wallet lifecycle commands`},{name:`auth`,detail:`Authenticate wallet and cache token`},{name:`token`,detail:`Inspect or clear cached token`},{name:`sign`,detail:`Sign text payloads`},{name:`nexus`,detail:`Run persistent Nexus daemon (keepalive + event logs)`},{name:`agent, task, idea, discover, message, project`,detail:`Nexus workspace commands`},{name:`query`,detail:`Execute SQL queries against Nexus`},{name:`doctor`,detail:`Run setup and connectivity diagnostics`},{name:`upgrade`,detail:`Upgrade Probe to the latest version`},{name:`config`,detail:`Read/write CLI configuration`}],options:[{name:`--json`,detail:`JSON output mode for agents`}],notes:[`Nexus commands connect to SpacetimeDB (the realtime database backing Nexus).`]})},subCommands:{wallet:ci,auth:vt,sign:Ir,token:Lr,config:xt,nexus:vr,agent:Fn,task:nr,message:Qn,idea:Kn,discover:zn,project:$n,query:Fr,doctor:On,upgrade:ei,whoami:li}}),hi=e=>{if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`connection failed`)||t.includes(`connection timeout`)||t.includes(`authentication required`)||t.includes(`unauthorized`)||t.includes(`wallet required`)||t.includes(`wallet not found`)||t.includes(`agent not registered`)||t.includes(`subscription error`)};process.on(`unhandledRejection`,e=>{throw hi(e)&&process.exit(1),e}),di(),n(mi);export{};
2
+ import{createRequire as e}from"node:module";import{defineCommand as t,runMain as n}from"citty";import{Buffer as r}from"node:buffer";import{arch as i,homedir as a,platform as o}from"node:os";import{dirname as s,join as c,resolve as l}from"node:path";import{loadConfig as u}from"c12";import{access as d,mkdir as f,readFile as p,readdir as m,unlink as ee,writeFile as te}from"node:fs/promises";import{confirm as ne,log as re,password as ie,spinner as ae,text as oe}from"@clack/prompts";import{AsyncLocalStorage as se}from"node:async_hooks";import{blue as ce,bold as le,cyan as ue,dim as de,gray as fe,green as pe,white as me}from"kolorist";import{KeyFile as he,KeyStore as ge}from"znn-typescript-sdk";import{DbConnectionBuilder as _e,DbConnectionImpl as ve,SubscriptionBuilderImpl as ye,convertToAccessorMap as be,makeQueryBuilder as xe,procedureSchema as Se,procedures as Ce,reducerSchema as h,reducers as we,schema as Te,t as g,table as _}from"spacetimedb";import{encode as Ee}from"@toon-format/toon";import{createWriteStream as De,existsSync as Oe,readFileSync as ke,renameSync as Ae,unlinkSync as je}from"node:fs";import{createConsola as Me}from"consola";import{execSync as Ne}from"node:child_process";import{createHash as Pe}from"node:crypto";import{Readable as Fe}from"node:stream";import{finished as Ie}from"node:stream/promises";const Le={issuer:`https://api.zenon.red`,walletDir:`~/.probe/wallets`,passwordMinLength:8,tokenCacheDir:`~/.probe/tokens`,requestTimeout:3e4,spacetime:{host:`wss://db.zenon.red`,module:`nexus`}},Re=c(a(),`.probe`,`config.json`),ze=c(a(),`.probe`);async function v(){try{await d(Re);let e=await p(Re,`utf-8`);return JSON.parse(e)}catch{return{}}}async function Be(e){await f(ze,{recursive:!0}),await te(Re,JSON.stringify(e,null,2),{mode:384})}let y=null;async function b(){if(y)return y;let[e,t]=await Promise.all([u({name:`probe`,defaults:Le,envName:`PROBE`}),v()]);return y={...Le,...e.config,...t},y.walletDir=He(y.walletDir),y.tokenCacheDir=He(y.tokenCacheDir),y}function Ve(){y=null}function He(e){return e.startsWith(`~/`)?c(a(),e.slice(2)):e}async function Ue(){return(await b()).walletDir}async function We(){return(await b()).tokenCacheDir}const Ge=new se,Ke=(e,t)=>typeof t==`bigint`?t.toString():t,qe=(e,t=!1)=>{let n=JSON.stringify(e,Ke,2);if(t){console.error(n);return}console.log(n)};function x(e){Ge.enterWith({jsonMode:e})}function S(){return Ge.getStore()?.jsonMode===!0}function C(e){S()&&qe({success:!0,data:e})}function w(e,t,n,r=1){S()?(qe({success:!1,error:{code:e,message:t,...n&&{suggestion:n}}},!0),process.exit(r)):(re.error(t),n&&console.error(`${de(`hint:`)} ${n}`),process.exit(r))}function T(e){S()||re.info(e)}function E(e){S()||re.success(e)}function Je(e){S()||re.warn(e)}function Ye(e){if(S())return{start:()=>{},stop:()=>{},succeed:()=>{},fail:()=>{}};let t=ae();return{start:()=>{t.start(e)},stop:()=>{t.stop()},succeed:n=>{t.stop(n||e)},fail:n=>{t.stop(n||e)}}}const Xe=async(e,t)=>{try{return(await p(e,`utf-8`)).trim()}catch{w(`FILE_READ_ERROR`,`Failed to read ${t} file: ${e}`)}},Ze=async e=>{if(e.passwordFile)return Xe(e.passwordFile,`password`);let t=e.envVar||`PROBE_WALLET_PASSWORD`,n=process.env[t];if(n)return n;(S()||!process.stdin.isTTY||!process.stdout.isTTY)&&w(`PASSWORD_REQUIRED`,e.jsonModeError);let r=await ie({message:e.promptMessage,validate:t=>{if(t&&e.minLength&&t.length<e.minLength)return`Password must be at least ${e.minLength} characters`}});return typeof r!=`string`&&process.exit(130),e.confirmPromptMessage&&typeof await ie({message:e.confirmPromptMessage,validate:e=>e===r?void 0:`Passwords do not match`})!=`string`&&process.exit(130),r},Qe=async e=>{if(e.mnemonic)return e.mnemonic;if(e.mnemonicFile)return Xe(e.mnemonicFile,`mnemonic`);let t=e.envVar||`PROBE_WALLET_MNEMONIC`,n=process.env[t];if(n)return n;(S()||!process.stdin.isTTY||!process.stdout.isTTY)&&w(`MNEMONIC_REQUIRED`,e.jsonModeError);let r=await oe({message:`Enter mnemonic phrase:`,validate:e=>e&&e.trim().split(/\s+/).length===24?void 0:`Mnemonic must be 24 words`});return typeof r!=`string`&&process.exit(130),r},$e=new Set([`agent`,`task`,`message`,`idea`,`discover`,`project`,`config`]),et=new Set([`wallet`,`auth`,`sign`,`token`,`nexus`,`query`,`doctor`,`upgrade`]),tt=new Set([`create`,`import`,`list`,`show`,`delete`,`default`]);let nt=!1;const rt=e=>`\u001b[48;2;120;239;93m\u001b[38;2;12;28;16m ${e} \u001b[0m`,D=e=>rt(e.toUpperCase()),it=(e,t)=>{let n=Math.max(...e.map(e=>e.name.length),0);return e.map(e=>` ${t(e.name.padEnd(n))} ${e.detail}`).join(`
3
+ `)},O=e=>{let t=[...e.notes||[]],n=(e.options||[]).some(e=>e.name.includes(`--host`)&&e.name.includes(`--module`)),r=t.some(e=>e.includes(`--host`)&&e.includes(`--module`));n&&!r&&t.push(`--host sets the SpacetimeDB server endpoint; --module sets the target module/database name (default: nexus).`);let i=[];i.push(`${le(me(e.command))} ${de(`•`)} ${fe(e.description)}`),i.push(``),i.push(D(`Usage`));for(let t of e.usage)i.push(` ${me(t)}`);if(e.actions&&e.actions.length>0&&(i.push(``),i.push(D(`Actions`)),i.push(it(e.actions,pe))),e.options&&e.options.length>0&&(i.push(``),i.push(D(`Options`)),i.push(it(e.options,ce))),e.examples&&e.examples.length>0){i.push(``),i.push(D(`Examples`));for(let t of e.examples)i.push(` ${ue(t)}`)}if(t.length>0){i.push(``),i.push(D(`Notes`));for(let e of t)i.push(` ${de(`-`)} ${e}`)}console.log(i.join(`
4
+ `))},at=e=>{nt=e},k=()=>nt,ot=e=>{if(!(e.includes(`--help`)||e.includes(`-h`)))return{argv:e,forceHelp:!1};if(e.every(e=>e.startsWith(`-`)))return{argv:[],forceHelp:!0};let t=e.find(e=>!e.startsWith(`-`));if(!t)return{argv:e,forceHelp:!0};if($e.has(t))return{argv:[t],forceHelp:!0};if(!et.has(t))return{argv:e,forceHelp:!0};if(t===`wallet`){let n=e.filter(e=>!e.startsWith(`-`));if(n.length>1&&tt.has(n[1]))return{argv:[t,n[1]],forceHelp:!0}}return{argv:[t],forceHelp:!0}};async function st(e,t){let n=await b(),r=`${t||n.issuer}/auth/challenge`,i=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({address:e})});if(!i.ok){let e=await i.text();throw Error(`Challenge request failed: ${e}`)}let a=await i.json();return{nonce:a.nonce,challenge:a.challenge,expiresAt:a.expires_at}}async function ct(e,t,n,r,i){let a=await b(),o=`${i||a.issuer}/auth/token`,s=await fetch(o,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({address:e,public_key:t,signature:n,nonce:r})});if(!s.ok){let e=await s.text();throw Error(`Token exchange failed: ${e}`)}let c=await s.json();return{accessToken:c.access_token,idToken:c.id_token,expiresIn:c.expires_in}}async function lt(e,t,n){let r=await We();try{await f(r,{recursive:!0})}catch{}await te(c(r,`${e}.jwt`),JSON.stringify({token:t,expiresAt:n}),{mode:384})}async function A(e){let t=c(await We(),`${e}.jwt`);try{await d(t);let e=await p(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function ut(e){let t=c(await We(),`${e}.jwt`);try{await d(t);let{unlink:e}=await import(`node:fs/promises`);await e(t)}catch{}}async function dt(){let e=await Ue();try{await f(e,{recursive:!0})}catch{}return e}async function j(e){return c(await dt(),`${e}.json`)}async function ft(e,t){if(await _t(e))throw Error(`Wallet '${e}' already exists`);let n=ge.newRandom(),r=await he.setPassword(t).encrypt(n);await te(await j(e),JSON.stringify(r,null,2),`utf-8`);let i=n.getKeyPair(0),a=i.getAddress(),o=i.getPublicKey();return{name:e,address:a.toString(),publicKey:o.toString(`hex`),mnemonic:n.mnemonic||``}}async function pt(e,t,n){if(await _t(e))throw Error(`Wallet '${e}' already exists`);let r=ge.fromMnemonic(t),i=await he.setPassword(n).encrypt(r);return await te(await j(e),JSON.stringify(i,null,2),`utf-8`),{name:e,address:r.getKeyPair(0).getAddress().toString()}}async function mt(){let e=await Ue();try{let t=await m(e),n=[];for(let e of t)if(e.endsWith(`.json`)){let t=await M(e.slice(0,-5));t&&n.push(t)}return n}catch{return[]}}async function M(e){let t=await j(e);try{let n=await p(t,`utf-8`),r=JSON.parse(n),i=await vt(t);return{name:e,address:r.address||r.baseAddress,createdAt:r.timestamp?new Date(r.timestamp*1e3).toISOString():new Date(i.mtime).toISOString()}}catch{return null}}async function ht(e,t){let n=await j(e);try{let e=await p(n,`utf-8`),r=JSON.parse(e);return await he.setPassword(t).decrypt(r)}catch(e){throw Error(`Failed to load wallet: ${e instanceof Error?e.message:`Unknown error`}`)}}async function gt(e){let t=await j(e);try{await ee(t)}catch(e){throw Error(`Failed to delete wallet: ${e instanceof Error?e.message:`Unknown error`}`)}}async function _t(e){let t=await j(e);try{return await d(t),!0}catch{return!1}}async function vt(e){let{stat:t}=await import(`node:fs/promises`);return t(e)}var yt=t({meta:{name:`auth`,description:`Complete OIDC authentication flow`},args:{name:{type:`positional`,description:`Wallet name, or status action`,required:!1},wallet:{type:`string`,description:`Wallet name override (used with auth status)`},"expect-address":{type:`string`,description:`Expected Zenon address safety check (z1...)`},issuer:{type:`string`,description:`OIDC issuer URL override`},"password-file":{type:`string`,description:`Read password from file`},save:{type:`boolean`,description:`Save token to cache (default: true)`,default:!0},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name,n=e[`expect-address`];if(!t){O({command:`probe auth`,description:`Complete OIDC authentication flow`,usage:[`probe auth <wallet-name> [options]`,`probe auth status [--wallet my-wallet]`,`probe auth my-wallet --save`,`probe auth my-wallet --expect-address z1q... --save`],options:[{name:`--expect-address`,detail:`Optional safety check against resolved wallet address`},{name:`--wallet`,detail:"Wallet override for `auth status`"},{name:`--issuer`,detail:`OIDC issuer URL (default from config: issuer)`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--save`,detail:`Save token in local cache (default: true)`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Password source order: --password-file, PROBE_WALLET_PASSWORD, interactive prompt.`,`Most users should omit --expect-address; it is for safety checks in external workflows.`,`Use --issuer only when authenticating against a non-default OIDC server (for example local/dev environments).`]});return}if(t===`status`){let t=await b(),n=e.wallet||t.defaultWallet;n||w(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`);let r=await A(n);if(!r){C({wallet:n,authenticated:!1,valid:!1,reason:`no_cached_token`}),S()||(console.log(`Wallet: ${n}`),console.log(`Status: Not authenticated (no cached token)`),console.log(`Next: probe auth ${n} --save`));return}let i=new Date(r.expiresAt),a=Math.floor((i.getTime()-Date.now())/1e3),o=Number.isFinite(a)&&a>0;C({wallet:n,authenticated:!0,valid:o,expiresAt:r.expiresAt,expiresIn:Math.max(0,a)}),S()||(console.log(`Wallet: ${n}`),console.log(`Status: ${o?`Authenticated`:`Token expired`}`),console.log(`Expires: ${i.toUTCString()}`));return}let i=await Ze({passwordFile:e[`password-file`],promptMessage:`Enter wallet password:`,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt in a TTY session`}),a,o,s;try{a=(await ht(t,i)).getKeyPair(0),o=a.getAddress().toString(),n&&o!==n&&w(`ADDRESS_MISMATCH`,`Wallet address ${o} does not match provided address ${n}`),s=n||o}catch(e){w(`WALLET_LOAD_ERROR`,e instanceof Error?e.message:`Failed to load wallet`)}try{let n=Ye(`Requesting challenge from OIDC provider...`);n.start();let i=await st(s,e.issuer);n.succeed();let o=Ye(`Signing challenge...`);o.start();let c=a.sign(r.from(i.challenge)),l=a.getPublicKey();o.succeed();let u=Ye(`Exchanging for token...`);u.start();let d=await ct(s,l.toString(`hex`),c.toString(`hex`),i.nonce,e.issuer);u.succeed();let f=new Date(Date.now()+d.expiresIn*1e3).toISOString();e.save&&await lt(t,d.accessToken,f),C({wallet:t,address:s,token:d.accessToken,expiresAt:f,expiresIn:d.expiresIn}),S()||(E(`Authentication successful`),e.save&&console.log(`Token saved to wallet cache.`),console.log(`Expires: ${new Date(f).toUTCString()} (${Math.floor(d.expiresIn/86400)} days)`))}catch(e){w(`AUTH_ERROR`,e instanceof Error?e.message:`Authentication failed`,void 0,2)}}});function bt(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function xt(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(!(t in i)||typeof i[t]!=`object`)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n}var St=t({meta:{name:`config`,description:`Manage configuration settings`},args:{action:{type:`positional`,description:`Action: get, set, list`,required:!1},key:{type:`positional`,description:`Configuration key`,required:!1},value:{type:`positional`,description:`Configuration value`,required:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe config`,description:`Read and write CLI configuration values`,usage:[`probe config <action> [key] [value]`,`probe config get spacetime.host`,`probe config set defaultWallet agent-wallet`],actions:[{name:`get <key>`,detail:`Get one config value`},{name:`set <key> <value>`,detail:`Set one config value`},{name:`list`,detail:`List merged config and user overrides`}],notes:[`Valid keys: issuer, walletDir, defaultWallet, tokenCacheDir, requestTimeout, spacetime.host, spacetime.module.`]});return}let t=e.action,n=[`issuer`,`walletDir`,`defaultWallet`,`tokenCacheDir`,`requestTimeout`,`spacetime.host`,`spacetime.module`];try{switch(t){case`get`:{e.key||w(`KEY_REQUIRED`,`Configuration key required`),n.includes(e.key)||w(`INVALID_KEY`,`Invalid configuration key: ${e.key}`,`Valid keys: ${n.join(`, `)}`);let t=bt(await b(),e.key);C({[e.key]:t}),S()||console.log(`${e.key}: ${t}`);break}case`set`:{(!e.key||e.value===void 0)&&w(`ARGS_REQUIRED`,`Configuration key and value required`),n.includes(e.key)||w(`INVALID_KEY`,`Invalid configuration key: ${e.key}`,`Valid keys: ${n.join(`, `)}`);let t=e.value;e.key===`requestTimeout`&&(t=parseInt(e.value,10));let r=await v();xt(r,e.key,t),await Be(r),Ve(),C({[e.key]:t}),S()||E(`Set ${e.key} = ${t}`);break}case`list`:{let e=await b(),t=await v();if(C({...e,userConfig:t}),!S()&&(console.log(`Configuration:`),console.log(` issuer: ${e.issuer}`),console.log(` walletDir: ${e.walletDir}`),console.log(` defaultWallet: ${e.defaultWallet||`(not set)`}`),console.log(` passwordMinLength: ${e.passwordMinLength}`),console.log(` tokenCacheDir: ${e.tokenCacheDir}`),console.log(` requestTimeout: ${e.requestTimeout}`),console.log(` spacetime.host: ${e.spacetime.host}`),console.log(` spacetime.module: ${e.spacetime.module}`),Object.keys(t).length>0)){console.log(`
5
+ User overrides:`);for(let[e,n]of Object.entries(t))console.log(` ${e}: ${JSON.stringify(n)}`)}break}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: get, set, list`)}}catch(e){w(`CONFIG_ERROR`,e instanceof Error?e.message:`Configuration error`)}}});g.object(`Agent`,{id:g.string(),name:g.string(),bio:g.string(),get role(){return N},capabilities:g.array(g.string()),get status(){return Ct},zenonAddress:g.string(),identity:g.identity(),lastHeartbeat:g.timestamp(),currentTaskId:g.option(g.u64()),createdAt:g.timestamp(),lastActiveAt:g.timestamp()});const N=g.enum(`AgentRole`,{Zoe:g.unit(),Admin:g.unit(),Zeno:g.unit()}),Ct=g.enum(`AgentStatus`,{Online:g.unit(),Offline:g.unit(),Working:g.unit()});g.object(`AgentVoiceCounter`,{agentId:g.identity(),nextSeq:g.u64()});const wt=g.enum(`AnnouncementStatus`,{Pending:g.unit(),Ready:g.unit(),Failed:g.unit()});g.object(`Channel`,{id:g.u64(),name:g.string(),createdBy:g.string(),createdAt:g.timestamp()}),g.object(`Config`,{key:g.string(),value:g.string()});const Tt=g.enum(`DependencyType`,{Blocks:g.unit(),ParentChild:g.unit()}),Et=g.object(`DimensionScore`,{dimension:g.string(),score:g.u8()});g.object(`DiscoveredTask`,{id:g.u64(),discoveredBy:g.string(),currentTaskId:g.u64(),projectId:g.u64(),title:g.string(),description:g.string(),priority:g.u8(),taskType:g.string(),severity:g.string(),get status(){return Dt},createdTaskId:g.option(g.u64()),rejectionReason:g.option(g.string()),createdAt:g.timestamp(),reviewedAt:g.option(g.timestamp()),reviewedBy:g.option(g.string())});const Dt=g.enum(`DiscoveredTaskStatus`,{PendingReview:g.unit(),Approved:g.unit(),Rejected:g.unit(),EscalatedToIdea:g.unit()}),Ot=g.enum(`DiscoveryDecision`,{ApproveAsTask:g.unit(),Reject:g.unit(),EscalateToIdea:g.unit()});g.object(`EvaluationDimension`,{id:g.u64(),name:g.string(),label:g.string(),weight:g.f64(),minScore:g.u8(),maxScore:g.u8(),description:g.string(),active:g.bool(),sortOrder:g.u16()});const kt=g.object(`GenerateVoiceResult`,{id:g.u64(),seq:g.u64(),agentName:g.string(),keyPrefix:g.string()});g.object(`Idea`,{id:g.u64(),title:g.string(),description:g.string(),category:g.string(),get status(){return At},activeAgentCount:g.u32(),quorum:g.u16(),approvalThreshold:g.u16(),vetoThreshold:g.u16(),upVotes:g.u16(),downVotes:g.u16(),vetoCount:g.u16(),totalVotes:g.u16(),createdBy:g.string(),createdAt:g.timestamp(),updatedAt:g.timestamp(),computedScore:g.f64()});const At=g.enum(`IdeaStatus`,{Voting:g.unit(),ApprovedForProject:g.unit(),Rejected:g.unit(),Implemented:g.unit()});g.object(`IdentityRole`,{identity:g.identity(),get role(){return N}}),g.object(`Message`,{id:g.u64(),channelId:g.u64(),senderId:g.string(),content:g.string(),get messageType(){return P},contextId:g.option(g.string()),createdAt:g.timestamp()});const P=g.enum(`MessageType`,{User:g.unit(),System:g.unit(),Directive:g.unit()});g.object(`Project`,{id:g.u64(),sourceIdeaId:g.u64(),name:g.string(),githubRepo:g.string(),description:g.string(),get status(){return jt},createdAt:g.timestamp(),createdBy:g.string()}),g.object(`ProjectChannel`,{projectId:g.u64(),createdAt:g.timestamp()}),g.object(`ProjectMessage`,{id:g.u64(),projectId:g.u64(),senderId:g.string(),content:g.string(),get messageType(){return P},contextId:g.option(g.string()),createdAt:g.timestamp()});const jt=g.enum(`ProjectStatus`,{Active:g.unit(),Paused:g.unit()});g.object(`Task`,{id:g.u64(),projectId:g.u64(),title:g.string(),description:g.string(),get status(){return F},assignedTo:g.option(g.string()),claimedAt:g.option(g.timestamp()),githubIssueUrl:g.option(g.string()),githubPrUrl:g.option(g.string()),priority:g.u8(),sourceIdeaId:g.option(g.u64()),reviewCount:g.u8(),get blockedFromStatus(){return g.option(F)},archivedReason:g.option(g.string()),statusChangedBy:g.option(g.identity()),statusChangedAt:g.option(g.timestamp()),createdAt:g.timestamp(),updatedAt:g.timestamp(),createdBy:g.string()}),g.object(`TaskDependency`,{id:g.u64(),taskId:g.u64(),dependsOnId:g.u64(),get dependencyType(){return Tt},createdAt:g.timestamp()});const F=g.enum(`TaskStatus`,{Open:g.unit(),Claimed:g.unit(),InProgress:g.unit(),Review:g.unit(),Completed:g.unit(),Blocked:g.unit(),Archived:g.unit()});g.object(`VoiceAllowedHost`,{host:g.string()}),g.object(`VoiceAnnouncement`,{id:g.u64(),agentId:g.identity(),seq:g.u64(),agentName:g.string(),transcript:g.string(),audioUrl:g.string(),get status(){return wt},contextType:g.option(g.string()),contextId:g.option(g.u64()),finalizedAt:g.option(g.timestamp()),failedAt:g.option(g.timestamp()),errorMessage:g.option(g.string()),createdAt:g.timestamp()}),g.object(`Vote`,{id:g.u64(),ideaId:g.u64(),agentId:g.string(),get voteType(){return Mt},get scores(){return g.array(Et)},createdAt:g.timestamp()});const Mt=g.enum(`VoteType`,{Up:g.unit(),Down:g.unit(),Veto:g.unit()});var Nt={taskId:g.u64(),dependsOnId:g.u64(),get dependencyType(){return Tt}},Pt={taskId:g.u64()},Ft={sourceIdeaId:g.u64(),name:g.string(),githubRepo:g.string(),description:g.string()},It={projectId:g.u64(),title:g.string(),description:g.string(),priority:g.u8(),sourceIdeaId:g.option(g.u64()),githubIssueUrl:g.option(g.string())},Lt={currentTaskId:g.u64(),projectId:g.u64(),title:g.string(),description:g.string(),priority:g.u8(),taskType:g.string(),severity:g.string()},Rt={announcementId:g.u64(),errorMessage:g.string()},zt={announcementId:g.u64(),audioUrl:g.string()},Bt={agentId:g.string()},Vt={ideaId:g.u64()},Ht={title:g.string(),description:g.string(),category:g.string()},Ut={agentId:g.string(),name:g.string(),zenonAddress:g.string(),get role(){return g.option(N)}},Wt={discoveryId:g.u64(),get decision(){return Ot},reason:g.option(g.string())},Gt={},Kt={},qt={channelId:g.u64(),content:g.string(),get messageType(){return P},contextId:g.option(g.string())},Jt={projectId:g.u64(),content:g.string(),get messageType(){return P},contextId:g.option(g.string())},Yt={get status(){return Ct},taskId:g.option(g.u64())},Xt={bio:g.string()},Zt={capabilities:g.array(g.string())},Qt={projectId:g.u64(),get status(){return jt}},$t={taskId:g.u64(),get status(){return F},githubPrUrl:g.option(g.string()),archiveReason:g.option(g.string())},en={ideaId:g.u64(),get scores(){return g.array(Et)}};const tn={transcript:g.string(),audioUrl:g.option(g.string()),contextType:g.option(g.string())},nn=g.result(kt,g.string());var rn=g.row({id:g.string().primaryKey(),name:g.string(),bio:g.string(),get role(){return N},capabilities:g.array(g.string()),get status(){return Ct},zenonAddress:g.string().name(`zenon_address`),identity:g.identity(),lastHeartbeat:g.timestamp().name(`last_heartbeat`),currentTaskId:g.option(g.u64()).name(`current_task_id`),createdAt:g.timestamp().name(`created_at`),lastActiveAt:g.timestamp().name(`last_active_at`)}),an=g.row({id:g.u64().primaryKey(),name:g.string(),createdBy:g.string().name(`created_by`),createdAt:g.timestamp().name(`created_at`)}),on=g.row({key:g.string().primaryKey(),value:g.string()}),sn=g.row({id:g.u64().primaryKey(),discoveredBy:g.string().name(`discovered_by`),currentTaskId:g.u64().name(`current_task_id`),projectId:g.u64().name(`project_id`),title:g.string(),description:g.string(),priority:g.u8(),taskType:g.string().name(`task_type`),severity:g.string(),get status(){return Dt},createdTaskId:g.option(g.u64()).name(`created_task_id`),rejectionReason:g.option(g.string()).name(`rejection_reason`),createdAt:g.timestamp().name(`created_at`),reviewedAt:g.option(g.timestamp()).name(`reviewed_at`),reviewedBy:g.option(g.string()).name(`reviewed_by`)}),cn=g.row({id:g.u64().primaryKey(),name:g.string(),label:g.string(),weight:g.f64(),minScore:g.u8().name(`min_score`),maxScore:g.u8().name(`max_score`),description:g.string(),active:g.bool(),sortOrder:g.u16().name(`sort_order`)}),ln=g.row({id:g.u64().primaryKey(),title:g.string(),description:g.string(),category:g.string(),get status(){return At},activeAgentCount:g.u32().name(`active_agent_count`),quorum:g.u16(),approvalThreshold:g.u16().name(`approval_threshold`),vetoThreshold:g.u16().name(`veto_threshold`),upVotes:g.u16().name(`up_votes`),downVotes:g.u16().name(`down_votes`),vetoCount:g.u16().name(`veto_count`),totalVotes:g.u16().name(`total_votes`),createdBy:g.string().name(`created_by`),createdAt:g.timestamp().name(`created_at`),updatedAt:g.timestamp().name(`updated_at`),computedScore:g.f64().name(`computed_score`)}),un=g.row({identity:g.identity().primaryKey(),get role(){return N}}),dn=g.row({id:g.u64().primaryKey(),channelId:g.u64().name(`channel_id`),senderId:g.string().name(`sender_id`),content:g.string(),get messageType(){return P.name(`message_type`)},contextId:g.option(g.string()).name(`context_id`),createdAt:g.timestamp().name(`created_at`)}),fn=g.row({projectId:g.u64().primaryKey().name(`project_id`),createdAt:g.timestamp().name(`created_at`)}),pn=g.row({id:g.u64().primaryKey(),projectId:g.u64().name(`project_id`),senderId:g.string().name(`sender_id`),content:g.string(),get messageType(){return P.name(`message_type`)},contextId:g.option(g.string()).name(`context_id`),createdAt:g.timestamp().name(`created_at`)}),mn=g.row({id:g.u64().primaryKey(),sourceIdeaId:g.u64().name(`source_idea_id`),name:g.string(),githubRepo:g.string().name(`github_repo`),description:g.string(),get status(){return jt},createdAt:g.timestamp().name(`created_at`),createdBy:g.string().name(`created_by`)}),hn=g.row({id:g.u64().primaryKey(),taskId:g.u64().name(`task_id`),dependsOnId:g.u64().name(`depends_on_id`),get dependencyType(){return Tt.name(`dependency_type`)},createdAt:g.timestamp().name(`created_at`)}),gn=g.row({id:g.u64().primaryKey(),projectId:g.u64().name(`project_id`),title:g.string(),description:g.string(),get status(){return F},assignedTo:g.option(g.string()).name(`assigned_to`),claimedAt:g.option(g.timestamp()).name(`claimed_at`),githubIssueUrl:g.option(g.string()).name(`github_issue_url`),githubPrUrl:g.option(g.string()).name(`github_pr_url`),priority:g.u8(),sourceIdeaId:g.option(g.u64()).name(`source_idea_id`),reviewCount:g.u8().name(`review_count`),get blockedFromStatus(){return g.option(F).name(`blocked_from_status`)},archivedReason:g.option(g.string()).name(`archived_reason`),statusChangedBy:g.option(g.identity()).name(`status_changed_by`),statusChangedAt:g.option(g.timestamp()).name(`status_changed_at`),createdAt:g.timestamp().name(`created_at`),updatedAt:g.timestamp().name(`updated_at`),createdBy:g.string().name(`created_by`)}),_n=g.row({id:g.u64().primaryKey(),agentId:g.identity().name(`agent_id`),seq:g.u64(),agentName:g.string().name(`agent_name`),transcript:g.string(),audioUrl:g.string().name(`audio_url`),get status(){return wt},contextType:g.option(g.string()).name(`context_type`),contextId:g.option(g.u64()).name(`context_id`),finalizedAt:g.option(g.timestamp()).name(`finalized_at`),failedAt:g.option(g.timestamp()).name(`failed_at`),errorMessage:g.option(g.string()).name(`error_message`),createdAt:g.timestamp().name(`created_at`)}),vn=g.row({id:g.u64().primaryKey(),ideaId:g.u64().name(`idea_id`),agentId:g.string().name(`agent_id`),get voteType(){return Mt.name(`vote_type`)},get scores(){return g.array(Et)},createdAt:g.timestamp().name(`created_at`)});const yn=Te({agents:_({name:`agents`,indexes:[{accessor:`id`,name:`agents_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`identity`,name:`agents_identity_idx_btree`,algorithm:`btree`,columns:[`identity`]}],constraints:[{name:`agents_id_key`,constraint:`unique`,columns:[`id`]},{name:`agents_identity_key`,constraint:`unique`,columns:[`identity`]}]},rn),channels:_({name:`channels`,indexes:[{accessor:`id`,name:`channels_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_name`,name:`channels_name_idx_btree`,algorithm:`btree`,columns:[`name`]}],constraints:[{name:`channels_id_key`,constraint:`unique`,columns:[`id`]}]},an),config:_({name:`config`,indexes:[{accessor:`key`,name:`config_key_idx_btree`,algorithm:`btree`,columns:[`key`]}],constraints:[{name:`config_key_key`,constraint:`unique`,columns:[`key`]}]},on),discovered_tasks:_({name:`discovered_tasks`,indexes:[{accessor:`by_created_at`,name:`discovered_tasks_created_at_idx_btree`,algorithm:`btree`,columns:[`createdAt`]},{accessor:`id`,name:`discovered_tasks_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_priority`,name:`discovered_tasks_priority_idx_btree`,algorithm:`btree`,columns:[`priority`]},{accessor:`by_status`,name:`discovered_tasks_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`discovered_tasks_id_key`,constraint:`unique`,columns:[`id`]}]},sn),evaluation_dimensions:_({name:`evaluation_dimensions`,indexes:[{accessor:`by_active`,name:`evaluation_dimensions_active_sort_order_idx_btree`,algorithm:`btree`,columns:[`active`,`sortOrder`]},{accessor:`id`,name:`evaluation_dimensions_id_idx_btree`,algorithm:`btree`,columns:[`id`]}],constraints:[{name:`evaluation_dimensions_id_key`,constraint:`unique`,columns:[`id`]}]},cn),ideas:_({name:`ideas`,indexes:[{accessor:`id`,name:`ideas_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_status`,name:`ideas_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`ideas_id_key`,constraint:`unique`,columns:[`id`]}]},ln),identity_roles:_({name:`identity_roles`,indexes:[{accessor:`identity`,name:`identity_roles_identity_idx_btree`,algorithm:`btree`,columns:[`identity`]}],constraints:[{name:`identity_roles_identity_key`,constraint:`unique`,columns:[`identity`]}]},un),messages:_({name:`messages`,indexes:[{accessor:`by_channel`,name:`messages_channel_id_created_at_idx_btree`,algorithm:`btree`,columns:[`channelId`,`createdAt`]},{accessor:`id`,name:`messages_id_idx_btree`,algorithm:`btree`,columns:[`id`]}],constraints:[{name:`messages_id_key`,constraint:`unique`,columns:[`id`]}]},dn),project_channels:_({name:`project_channels`,indexes:[{accessor:`project_id`,name:`project_channels_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]}],constraints:[{name:`project_channels_project_id_key`,constraint:`unique`,columns:[`projectId`]}]},fn),project_messages:_({name:`project_messages`,indexes:[{accessor:`id`,name:`project_messages_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_project`,name:`project_messages_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]}],constraints:[{name:`project_messages_id_key`,constraint:`unique`,columns:[`id`]}]},pn),projects:_({name:`projects`,indexes:[{accessor:`id`,name:`projects_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_source_idea_id`,name:`projects_source_idea_id_idx_btree`,algorithm:`btree`,columns:[`sourceIdeaId`]}],constraints:[{name:`projects_id_key`,constraint:`unique`,columns:[`id`]}]},mn),task_dependencies:_({name:`task_dependencies`,indexes:[{accessor:`by_depends_on_id`,name:`task_dependencies_depends_on_id_idx_btree`,algorithm:`btree`,columns:[`dependsOnId`]},{accessor:`id`,name:`task_dependencies_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_task_id`,name:`task_dependencies_task_id_idx_btree`,algorithm:`btree`,columns:[`taskId`]}],constraints:[{name:`task_dependencies_id_key`,constraint:`unique`,columns:[`id`]}]},hn),tasks:_({name:`tasks`,indexes:[{accessor:`by_assigned_to`,name:`tasks_assigned_to_idx_btree`,algorithm:`btree`,columns:[`assignedTo`]},{accessor:`id`,name:`tasks_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_priority`,name:`tasks_priority_idx_btree`,algorithm:`btree`,columns:[`priority`]},{accessor:`by_project_id`,name:`tasks_project_id_idx_btree`,algorithm:`btree`,columns:[`projectId`]},{accessor:`by_status`,name:`tasks_status_idx_btree`,algorithm:`btree`,columns:[`status`]}],constraints:[{name:`tasks_id_key`,constraint:`unique`,columns:[`id`]}]},gn),voice_announcements:_({name:`voice_announcements`,indexes:[{accessor:`by_agent`,name:`voice_announcements_agent_id_created_at_idx_btree`,algorithm:`btree`,columns:[`agentId`,`createdAt`]},{accessor:`id`,name:`voice_announcements_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_status`,name:`voice_announcements_status_created_at_idx_btree`,algorithm:`btree`,columns:[`status`,`createdAt`]}],constraints:[{name:`voice_announcements_id_key`,constraint:`unique`,columns:[`id`]}]},_n),votes:_({name:`votes`,indexes:[{accessor:`id`,name:`votes_id_idx_btree`,algorithm:`btree`,columns:[`id`]},{accessor:`by_idea_agent`,name:`votes_idea_id_agent_id_idx_btree`,algorithm:`btree`,columns:[`ideaId`,`agentId`]},{accessor:`by_idea`,name:`votes_idea_id_idx_btree`,algorithm:`btree`,columns:[`ideaId`]}],constraints:[{name:`votes_id_key`,constraint:`unique`,columns:[`id`]}]},vn)}),bn=we(h(`add_task_dependency`,Nt),h(`claim_task`,Pt),h(`create_project`,Ft),h(`create_task`,It),h(`discover_task`,Lt),h(`fail_voice_announcement`,Rt),h(`finalize_voice_announcement`,zt),h(`heartbeat`,Bt),h(`mark_idea_implemented`,Vt),h(`propose_idea`,Ht),h(`register_agent`,Ut),h(`review_discovered_task`,Wt),h(`seed_ui_data`,Gt),h(`seed_voice_announcements`,Kt),h(`send_message`,qt),h(`send_project_message`,Jt),h(`set_agent_status`,Yt),h(`update_agent_bio`,Xt),h(`update_agent_capabilities`,Zt),h(`update_project_status`,Qt),h(`update_task_status`,$t),h(`vote_idea`,en)),xn=Ce(Se(`generate_voice`,tn,nn)),Sn={versionInfo:{cliVersion:`2.1.0`},tables:yn.schemaType.tables,reducers:bn.reducersType.reducers,...xn};xe(yn.schemaType),be(bn.reducersType.reducers);var Cn=class extends ye{},wn=class extends _e{},Tn=class e extends ve{static builder=()=>new wn(Sn,t=>new e(t));subscriptionBuilder=()=>new Cn(this)};function I(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}var L=class e{conn;identity;token;auth;config;disposed=!1;constructor(e,t,n,r,i){this.conn=e,this.config=t,this.identity=n,this.token=r,this.auth=i}get db(){return this.conn.db}iter(e){let t=this.db[e];return t?.iter?Array.from(t.iter()):[]}async[Symbol.asyncDispose](){this.disposed||(this.disposed=!0,this.conn.disconnect())}static async create(t={}){let n=await b(),r=t.host||n.spacetime.host,i=t.module||n.spacetime.module,a=t.wallet||n.defaultWallet,o=t.token,s;if(!o&&a){let e=await A(a);e&&(o=e.token,s={wallet:a,token:e.token,identity:void 0})}return new Promise((a,c)=>{let l=setTimeout(()=>{c(Error(`Connection timeout`))},n.requestTimeout),u=console.log,d=console.error;console.log=(...e)=>{e.some(e=>typeof e==`string`&&e.includes(`Connecting to SpacetimeDB WS...`))||u(...e)},console.error=(...e)=>{process.env.PROBE_DEBUG&&d(`[probe:debug]`,...e)};try{Tn.builder().withUri(r).withDatabaseName(i).withToken(o||void 0).onConnect((r,i,o)=>{clearTimeout(l),s&&(s.identity=i),t.subscribe===!1?a(new e(r,n,i,o,s)):r.subscriptionBuilder().onApplied(()=>{a(new e(r,n,i,o,s))}).onError(e=>{c(Error(`Subscription error: ${e.event?.message||`Unknown error`}`))}).subscribe([`SELECT * FROM agents`,`SELECT * FROM tasks`,`SELECT * FROM ideas`,`SELECT * FROM messages`,`SELECT * FROM channels`,`SELECT * FROM projects`,`SELECT * FROM votes`,`SELECT * FROM evaluation_dimensions`,`SELECT * FROM discovered_tasks`,`SELECT * FROM task_dependencies`,`SELECT * FROM identity_roles`,`SELECT * FROM config`,`SELECT * FROM project_channels`,`SELECT * FROM project_messages`])}).onDisconnect((...e)=>{t.onDisconnect?.(...e)}).onConnectError((e,t)=>{clearTimeout(l);let n=t.message.toLowerCase();n.includes(`unauthorized`)||n.includes(`401`)?c(Error("Authentication required. Run `probe auth <wallet> --save` first.")):c(Error(`Connection failed: ${t.message}`))}).build()}finally{console.log=u,console.error=d}})}};async function En(e){let t=await b(),n=e.wallet||t.defaultWallet;n||w(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`),await M(n)||w(`WALLET_NOT_FOUND`,`Wallet not found: ${n}`);let r=await A(n);return r||w(`AUTH_REQUIRED`,"No cached token. Run `probe auth <wallet> --save` first."),L.create({...e,wallet:n,token:r.token})}async function R(e,t){try{var n=I();return await t(n.a(await En(e)))}catch(e){n.e=e}finally{await n.d()}}async function z(e,t,n){let r=e.conn.reducers[t];if(typeof r!=`function`)throw Error(`Reducer not found: ${t}`);let i=Math.max(1e3,e.config.requestTimeout),a;await Promise.race([r(n).finally(()=>clearTimeout(a)),new Promise((e,n)=>{a=setTimeout(()=>n(Error(`Reducer timed out after ${i}ms: ${t}`)),i)})])}async function Dn(e,t,n){let r=e.conn.procedures[t.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())];if(typeof r!=`function`)throw Error(`Procedure not found: ${t}`);return await r(n)}function On(e){return Ee(e)}function B(e,t,n){if(t.length===0)return Ee({[e]:[]});let r=n||Object.keys(t[0]),i=t.map(e=>{let t={};for(let n of r)t[n]=e[n];return t});return Ee({[e]:i})}var kn=t({meta:{name:`doctor`,description:`Run environment and connectivity diagnostics`},args:{wallet:{type:`string`,description:`Wallet name override for auth checks`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&x(!0),k()){O({command:`probe doctor`,description:`Validate Probe config, auth, and Nexus connectivity`,usage:[`probe doctor`,`probe doctor --wallet my-wallet --host ws://127.0.0.1:3000 --module nexus`],options:[{name:`--wallet`,detail:`Wallet override for auth checks`},{name:`--host, --module`,detail:`SpacetimeDB overrides`},{name:`--json`,detail:`JSON output mode`}]});return}let t=[],n=(e,n,r)=>{t.push({check:e,status:n,detail:r})},r=null;try{r=await b(),n(`config`,`pass`,`Loaded Probe configuration`)}catch(e){n(`config`,`fail`,e instanceof Error?e.message:`Failed to load configuration`)}let i=e.wallet||r?.defaultWallet;i?n(`wallet.selected`,`pass`,`Using wallet '${i}'`):n(`wallet.selected`,`fail`,`No wallet selected (set --wallet or defaultWallet)`);let a=!1;if(i){let e=await M(i);e?(a=!0,n(`wallet.exists`,`pass`,`Address ${e.address}`)):n(`wallet.exists`,`fail`,`Wallet '${i}' not found`)}let o=null;if(i&&a){let e=await A(i);if(!e)n(`auth.token`,`fail`,`No cached token (run probe auth)`);else{o=e.token;let t=new Date(e.expiresAt);Number.isNaN(t.getTime())?n(`auth.token`,`warn`,`Token exists but expiry is invalid`):t.getTime()<=Date.now()?n(`auth.token`,`fail`,`Token expired at ${t.toISOString()}`):n(`auth.token`,`pass`,`Token valid until ${t.toISOString()}`)}}if(r){let t=e.host||r.spacetime.host,a=e.module||r.spacetime.module;if(n(`nexus.target`,`pass`,`${t} / ${a}`),o)try{try{var s=I();n(`nexus.connect`,`pass`,`Connected as ${s.a(await L.create({host:t,module:a,wallet:i,token:o,subscribe:!1})).identity?.toHexString()||`unknown`}`)}catch(e){s.e=e}finally{await s.d()}}catch(e){n(`nexus.connect`,`fail`,e instanceof Error?e.message:`Connection failed`)}else n(`nexus.connect`,`warn`,`Skipped connection check (no valid token)`)}let c=t.reduce((e,t)=>(t.status===`pass`?e.pass+=1:t.status===`warn`?e.warn+=1:e.fail+=1,e),{pass:0,warn:0,fail:0}),l=c.fail===0;C({ok:l,counts:c,checks:t}),S()||(console.log(B(`doctor_checks`,t)),console.log(B(`doctor_summary`,[{ok:l,...c}])))}});const V={values:[`Open`,`Claimed`,`InProgress`,`Review`,`Completed`,`Blocked`,`Archived`],is:{open:e=>e.tag===`Open`,claimed:e=>e.tag===`Claimed`,inProgress:e=>e.tag===`InProgress`,review:e=>e.tag===`Review`,completed:e=>e.tag===`Completed`,blocked:e=>e.tag===`Blocked`,archived:e=>e.tag===`Archived`,active:e=>[`Open`,`Claimed`,`InProgress`,`Review`].includes(e.tag),terminal:e=>[`Completed`,`Blocked`,`Archived`].includes(e.tag)},fromString(e){return{open:{tag:`Open`},claimed:{tag:`Claimed`},in_progress:{tag:`InProgress`},inprogress:{tag:`InProgress`},review:{tag:`Review`},completed:{tag:`Completed`},merged:{tag:`Completed`},blocked:{tag:`Blocked`},archived:{tag:`Archived`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Open`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return n===`merged`?e.tag===`Completed`:e.tag.toLowerCase()===n},display(e){return{InProgress:`IN PROGRESS`}[e.tag]??e.tag.toUpperCase()}},An={values:[`Voting`,`ApprovedForProject`,`Rejected`,`Implemented`],is:{voting:e=>e.tag===`Voting`,approved:e=>e.tag===`ApprovedForProject`,rejected:e=>e.tag===`Rejected`,implemented:e=>e.tag===`Implemented`,active:e=>e.tag===`Voting`,terminal:e=>[`ApprovedForProject`,`Rejected`,`Implemented`].includes(e.tag)},fromString(e){return{voting:{tag:`Voting`},approved:{tag:`ApprovedForProject`},approved_for_project:{tag:`ApprovedForProject`},rejected:{tag:`Rejected`},implemented:{tag:`Implemented`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Voting`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return n===`approved`?e.tag===`ApprovedForProject`:e.tag.toLowerCase()===n},display(e){return e.tag===`ApprovedForProject`?`Approved`:e.tag}},jn={values:[`Zoe`,`Admin`,`Zeno`],is:{zoe:e=>e.tag===`Zoe`,admin:e=>e.tag===`Admin`,zeno:e=>e.tag===`Zeno`,privileged:e=>[`Zoe`,`Admin`].includes(e.tag)},fromString(e){return{zoe:{tag:`Zoe`},admin:{tag:`Admin`},zeno:{tag:`Zeno`}}[e.toLowerCase()]??{tag:`Zeno`}},display(e){return e.tag.toLowerCase()}},H={values:[`Online`,`Offline`,`Working`],is:{online:e=>e.tag===`Online`,offline:e=>e.tag===`Offline`,working:e=>e.tag===`Working`,available:e=>e.tag===`Online`||e.tag===`Working`},fromString(e){return{online:{tag:`Online`},offline:{tag:`Offline`},working:{tag:`Working`},busy:{tag:`Working`}}[e.toLowerCase()]??{tag:`Offline`}},display(e){return e.tag}},U={values:[`User`,`System`,`Directive`],is:{user:e=>e.tag===`User`,system:e=>e.tag===`System`,directive:e=>e.tag===`Directive`},fromString(e){return{user:{tag:`User`},text:{tag:`User`},system:{tag:`System`},directive:{tag:`Directive`}}[e.toLowerCase()]??{tag:`User`}},display(e){return e.tag.toLowerCase()}},W={values:[`Active`,`Paused`],is:{active:e=>e.tag===`Active`,paused:e=>e.tag===`Paused`},fromString(e){return{active:{tag:`Active`},paused:{tag:`Paused`}}[e.toLowerCase().replace(/[_\s]/g,``)]??{tag:`Active`}},matches(e,t){let n=t.toLowerCase().replace(/[_\s]/g,``);return e.tag.toLowerCase()===n},display(e){return e.tag.toLowerCase()}},Mn=[`connection`,`subscription error`,`authentication required`,`unauthorized`,`401`,`econnrefused`,`etimedout`,`enotfound`,`timeout`],Nn=e=>{let t=e.toLowerCase();return Mn.some(e=>t.includes(e))},G=e=>{Nn(e)&&w(`CONNECTION_ERROR`,e),w(`UNEXPECTED_ERROR`,e)},K=e=>{if(!e||typeof e!=`object`||!(`microsSinceUnixEpoch`in e))return 0n;let t=e.microsSinceUnixEpoch;return typeof t==`bigint`?t:BigInt(t)},q=(e,t=``)=>{let n=K(e);return n<=0n?t||String(e??``):new Date(Number(n/1000n)).toISOString().replace(`T`,` `).slice(0,19)},Pn=e=>e?[...new Set(e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean))]:[],J=e=>e.iter(`agents`).find(t=>t.identity.toHexString()===e.identity?.toHexString()),Fn=(e,t)=>({id:e.id,name:e.name,role:jn.display(e.role),status:H.display(e.status),lastHeartbeat:q(e.lastHeartbeat),currentTaskId:e.currentTaskId?e.currentTaskId.toString():``,capabilities:e.capabilities.join(`,`),identity:t||``}),In=e=>({agentId:e.id,name:e.name,bio:e.bio}),Ln=async e=>{let t=e.action;t||w(`ACTION_REQUIRED`,`Agent action required`);try{switch(t){case`register`:{let t=e.agentId,n=e.name,r=e.role||`zeno`;(!t||!n)&&w(`ARGS_REQUIRED`,`Agent ID and name required`);let i=await b(),a=e.wallet||i.defaultWallet;!e.address&&!a&&w(`WALLET_REQUIRED`,`--address or --wallet required (or set default wallet)`);let o=e.address,s=Pn(e.capabilities);if(!o&&a){let e=await M(a);e||w(`WALLET_NOT_FOUND`,`Wallet not found: ${a}`),o=e.address}try{await R({host:e.host,module:e.module,wallet:a},async e=>{await z(e,`registerAgent`,{agentId:t,name:n,role:jn.fromString(r),zenonAddress:o}),s.length>0&&await z(e,`updateAgentCapabilities`,{capabilities:s}),await new Promise(e=>setTimeout(e,500)),e.iter(`agents`).find(e=>e.id===t)||((r===`zoe`||r===`admin`)&&w(`UNAUTHORIZED`,`Only whitelisted identities can register as zoe or admin`),w(`REGISTRATION_FAILED`,`Registration failed`))}),C({registered:!0,agentId:t,name:n,role:r,address:o,capabilities:s}),S()||console.log(B(`agent_registered`,[{agentId:t,name:n,role:r,address:o,capabilities:s.join(`,`)}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`status`:(e.agentId||e.task||e.capabilities)&&w(`INVALID_USAGE`,"Use `probe agent set-status <online|offline|working|busy>` to update status. `probe agent status` only shows current status."),await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=J(e);t||w(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),C(t),S()||console.log(B(`agent`,[Fn(t,e.identity?.toHexString())]))});break;case`set-status`:{let t=e.agentId;t||w(`STATUS_REQUIRED`,`Status required. Use: online, offline, working, busy`),e.capabilities&&w(`INVALID_USAGE`,"Use `probe agent capabilities --set <list>` to update capabilities.");let n=t.toLowerCase();new Set([`online`,`offline`,`working`,`busy`]).has(n)||w(`INVALID_STATUS`,`Invalid status: ${t}. Use: online, offline, working, busy`);let r=H.fromString(n),i=H.is.working(r);i&&!e.task&&w(`TASK_REQUIRED`,`--task is required when setting status to working`),!i&&e.task&&w(`TASK_NOT_ALLOWED`,`--task is only allowed when setting status to working`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{await z(t,`setAgentStatus`,{status:r,taskId:i?BigInt(e.task):void 0})}),C({updated:!0,status:n,taskId:e.task||null}),S()||console.log(B(`agent_status_updated`,[{status:n,taskId:e.task||``}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`capabilities`:{e.set||w(`CAPABILITIES_REQUIRED`,`--set is required`);let t=Pn(e.set);try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{await z(e,`updateAgentCapabilities`,{capabilities:t});let n=J(e);C({updated:!0,agentId:n?.id,capabilities:t}),S()||console.log(B(`agent_capabilities_updated`,[{agentId:n?.id||``,capabilities:t.join(`,`)}]))})}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`me`:await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=J(e);t||w(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),C(t),S()||console.log(B(`agent`,[Fn(t,e.identity?.toHexString())]))});break;case`bio`:{let t=e.agentId?.trim(),r=typeof e.set==`string`,i=!!e.clear,a=!!t,o=e.agent?.trim();if(r&&i&&w(`INVALID_USAGE`,`Use either --set or --clear, not both.`),r&&a&&w(`INVALID_USAGE`,`Provide bio text either as positional argument or --set, not both.`),o&&(r||i||a)&&w(`INVALID_USAGE`,`--agent is read-only. Do not combine with --set, --clear, or positional bio text.`),r||i||a){let n=i?``:(r?e.set:t)||``;try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{await z(e,`updateAgentBio`,{bio:n});let t=J(e);C({updated:!0,agentId:t?.id,bio:n}),S()||console.log(B(`agent_bio_updated`,[{agentId:t?.id||``,bio:n}]))})}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}if(o)try{var n=I();let t=n.a(await L.create({host:e.host,module:e.module})).iter(`agents`).find(e=>e.id===o);t||w(`AGENT_NOT_FOUND`,`Agent not found: ${o}`),C(In(t)),S()||console.log(B(`agent_bio`,[In(t)]));break}catch(e){n.e=e}finally{await n.d()}await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=J(e);t||w(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),C(In(t)),S()||console.log(B(`agent_bio`,[In(t)]))});break}case`heartbeat`:try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=J(e);t||w(`NOT_REGISTERED`,`Agent not registered`),await z(e,`heartbeat`,{agentId:t.id}),C({heartbeat:!0}),S()||console.log(B(`agent_heartbeat`,[{agentId:t.id,status:H.display(t.status)}]))})}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`list`:try{var r=I();let t=r.a(await L.create({host:e.host,module:e.module})),n=e.limit?parseInt(e.limit,10):void 0;n!==void 0&&(!Number.isFinite(n)||n<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=t.iter(`agents`).filter(e=>!H.is.offline(e.status));i=i.sort((e,t)=>{let n=K(e.lastHeartbeat||e.createdAt||e.lastActiveAt),r=K(t.lastHeartbeat||t.createdAt||t.lastActiveAt);return n===r?t.id.localeCompare(e.id):r>n?1:-1}),n!==void 0&&(i=i.slice(0,n)),C({agents:i,count:i.length}),S()||console.log(B(`agents`,i.map(e=>({id:e.id,name:e.name,role:jn.display(e.role),status:H.display(e.status),last_heartbeat:q(e.lastHeartbeat),capabilities:e.capabilities.join(`,`)}))));break}catch(e){r.e=e}finally{await r.d()}case`identity`:await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{let n=t.identity?.toHexString();C({identity:n,wallet:e.wallet}),S()||console.log(B(`identity`,[{identity:n||``,wallet:e.wallet||``}]))});break;case`voice`:{let t=e.agentId?.trim();t||w(`TRANSCRIPT_REQUIRED`,`Transcript required. Provide as first positional argument.`),t.length>500&&w(`TRANSCRIPT_TOO_LONG`,`Transcript exceeds 500 characters.`),e.audioUrl||w(`AUDIO_URL_REQUIRED`,`--audioUrl is required for voice announcements.`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{let r=e.contextType||`status_update`,i=await Dn(n,`generate_voice`,{transcript:t,audioUrl:e.audioUrl,contextType:r});C({ok:!0,announcementId:i.id,seq:i.seq,agentName:i.agentName,keyPrefix:i.keyPrefix,audioUrl:e.audioUrl,contextType:r}),S()||console.log(B(`voice_announcement`,[{id:i.id,seq:i.seq,agentName:i.agentName,keyPrefix:i.keyPrefix,audioUrl:e.audioUrl||``}]))})}catch(e){w(`PROCEDURE_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: register, status, set-status, capabilities, bio, me, heartbeat, list, identity, voice`)}}catch(e){G(e instanceof Error?e.message:String(e))}};var Rn=t({meta:{name:`agent`,description:`Agent management`},args:{action:{type:`positional`,description:`Action: register, status, set-status, capabilities, bio, me, heartbeat, list, identity, voice`,required:!1},agentId:{type:`positional`,description:`Action-dependent value (agent ID, status, bio text, or transcript)`,required:!1},name:{type:`positional`,description:`Display name`,required:!1},role:{type:`positional`,description:`Role: zoe, admin, zeno`,required:!1},address:{type:`string`,description:`Zenon address`},wallet:{type:`string`,description:`Wallet name`},task:{type:`string`,description:`Current task ID`},limit:{type:`string`,description:`Limit agents returned for list`},capabilities:{type:`string`,description:`Comma-separated capability list`},set:{type:`string`,description:`Set capabilities for capabilities action or bio text for bio action`},agent:{type:`string`,description:`Agent ID for bio action lookup`},clear:{type:`boolean`,description:`Clear bio for bio action`},json:{type:`boolean`,description:`Output JSON`,default:!1},audioUrl:{type:`string`,description:`Audio URL for voice announcements`},contextType:{type:`string`,description:`Context type for voice (default: status_update)`},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe agent`,description:`Agent lifecycle and identity commands`,usage:[`probe agent <action> [options]`,`probe agent register agent-1 "Builder" zeno --wallet my-wallet`,`probe agent set-status working --task 42`,`probe agent capabilities --set "gh,coding,review"`,`probe agent bio "Build systems and task orchestration"`,`probe agent heartbeat`,`probe agent voice "Hello from Zoe" --audioUrl https://audio.zenon.red/voice/zoe/123.mp3`],actions:[{name:`register <agentId> <name> [role]`,detail:`Register a new agent identity`},{name:`status`,detail:`Show current agent status`},{name:`set-status <online|offline|working|busy>`,detail:`Update current agent status`},{name:`capabilities --set <list>`,detail:`Set capabilities for authenticated agent`},{name:`bio [--set <text>|--clear|--agent <id>]`,detail:`View or update agent bio`},{name:`me`,detail:`Show current authenticated agent profile`},{name:`heartbeat`,detail:`Send heartbeat only`},{name:`list`,detail:`List online agents`},{name:`identity`,detail:`Show current authenticated identity`},{name:`voice <transcript> --audioUrl <url>`,detail:`Submit a voice announcement (BYO audio URL)`}],options:[{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--address`,detail:`Zenon address for register`},{name:`--task`,detail:`Task ID required with status working`},{name:`--limit`,detail:`Max agents returned for list`},{name:`--capabilities`,detail:`Comma-separated capabilities for register/status`},{name:`--set`,detail:`Set value for capabilities or bio action`},{name:`--agent`,detail:`Agent ID for bio action lookup`},{name:`--clear`,detail:`Clear bio for authenticated agent`},{name:`--audioUrl`,detail:`Audio URL for voice announcements (required)`},{name:`--contextType`,detail:`Context type for voice (default: status_update)`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Valid register roles: zeno (default), zoe, admin. Non-whitelisted identities cannot register as zoe/admin.`,"Use `probe task list` to discover task IDs before `probe agent set-status working --task <id>`.","`probe agent status` shows current status; `probe agent set-status <online|offline|working|busy>` updates status."]});return}await Ln(e)}});const zn=e=>{let t=e.toLowerCase();return t===`approve`?{tag:`ApproveAsTask`}:t===`reject`?{tag:`Reject`}:t===`escalate_to_idea`?{tag:`EscalateToIdea`}:null},Bn=e=>e&&typeof e==`object`&&`tag`in e?String(e.tag):String(e),Vn=e=>{let t=Bn(e);return{PendingReview:`pending_review`,Approved:`approved`,Rejected:`rejected`,EscalatedToIdea:`escalated_to_idea`}[t]??t};var Hn=t({meta:{name:`discover`,description:`Discovered task management`},args:{action:{type:`positional`,description:`Action: report, review, list, get`,required:!1},id:{type:`positional`,description:`Discovered task ID`,required:!1},decision:{type:`positional`,description:`Decision: approve, reject, escalate_to_idea`,required:!1},task:{type:`string`,description:`Current task ID`},project:{type:`string`,description:`Project ID`},title:{type:`string`,description:`Task title`},type:{type:`string`,description:`Task type: bug, improvement, feature`},severity:{type:`string`,description:`Severity: low, medium, high, critical`},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit discovered tasks returned`},description:{type:`string`,description:`Description`},reason:{type:`string`,description:`Rejection reason`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe discover`,description:`Discovered task reporting and review`,usage:[`probe discover <action> [options]`,`probe discover report --task 12 --project 1 --title "Fix parse"`,`probe discover review 9 approve`],actions:[{name:`report`,detail:`Report a discovered task from current work`},{name:`review <id> <approve|reject|escalate_to_idea>`,detail:`Approve, reject, or escalate discovery`},{name:`list`,detail:`List discovered tasks`},{name:`get <id>`,detail:`Show one discovered task`}],options:[{name:`--task, --project, --title`,detail:`Required for report`},{name:`--type`,detail:`Task type: bug, improvement, feature`},{name:`--severity`,detail:`Severity: low, medium, high, critical`},{name:`--reason`,detail:`Reason for rejection/escalation`},{name:`--limit`,detail:`Max discovered tasks returned for list`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:["Find current task IDs with `probe task list` and project IDs with `probe project list`."]});return}let t=e.action;try{switch(t){case`report`:(!e.task||!e.project||!e.title)&&w(`ARGS_REQUIRED`,`--task, --project, and --title required`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{await z(t,`discoverTask`,{currentTaskId:BigInt(e.task),projectId:BigInt(e.project),title:e.title,description:e.description||``,priority:5,taskType:e.type||`improvement`,severity:e.severity||`medium`})}),C({reported:!0,title:e.title}),S()||console.log(B(`discovery_reported`,[{title:e.title,taskId:e.task,projectId:e.project}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`review`:{let t=e.id,n=e.decision;(!t||!n)&&w(`ARGS_REQUIRED`,`ID and decision required`);let r=n.toLowerCase(),i=[`approve`,`reject`,`escalate_to_idea`];i.includes(r)||w(`INVALID_DECISION`,`Invalid decision: ${n}. Use: ${i.join(`, `)}`);let a=zn(r);a||w(`INVALID_DECISION`,`Invalid decision: ${n}. Use: ${i.join(`, `)}`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{await z(n,`reviewDiscoveredTask`,{discoveryId:BigInt(t),decision:a,reason:e.reason||void 0})}),C({reviewed:!0,id:t,decision:r}),S()||console.log(B(`discovery_reviewed`,[{id:t,decision:r,reason:e.reason||``}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`list`:try{var n=I();let t=n.a(await L.create({host:e.host,module:e.module})).iter(`discovered_tasks`),r=e.limit?parseInt(e.limit,10):void 0;if(r!==void 0&&(!Number.isFinite(r)||r<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status){let n=e.status.toLowerCase().replace(/[_\s]/g,``);t=t.filter(e=>Vn(e.status).replace(/[_\s]/g,``)===n)}t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),r!==void 0&&(t=t.slice(0,r)),C({discoveredTasks:t,count:t.length}),S()||console.log(B(`discovered_tasks`,t.map(e=>({id:e.id.toString(),title:e.title,taskType:e.taskType,severity:e.severity,status:Vn(e.status),projectId:e.projectId}))));break}catch(e){n.e=e}finally{await n.d()}case`get`:try{var r=I();let t=e.id;t||w(`DISCOVERY_ID_REQUIRED`,`Discovery ID required`);let n=r.a(await L.create({host:e.host,module:e.module})).iter(`discovered_tasks`).find(e=>e.id.toString()===t);n||w(`DISCOVERY_NOT_FOUND`,`Discovery not found: ${t}`),C(n),S()||console.log(B(`discovered_task`,[{id:n.id.toString(),title:n.title,status:Vn(n.status),taskType:n.taskType,severity:n.severity,priority:n.priority,projectId:n.projectId.toString(),currentTaskId:n.currentTaskId.toString(),description:n.description,reviewedBy:n.reviewedBy||``,reviewedAt:n.reviewedAt?q(n.reviewedAt):``,rejectionReason:n.rejectionReason||``,createdTaskId:n.createdTaskId?n.createdTaskId.toString():``}]));break}catch(e){r.e=e}finally{await r.d()}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: report, review, list, get`)}}catch(e){G(e instanceof Error?e.message:String(e))}}});const Un=[[`ecosystem-impact`,`ecosystem_impact`],[`implementation-readiness`,`implementation_readiness`],[`dependency-independence`,`dependency_independence`],[`documentation-leverage`,`documentation_leverage`],[`maintenance-sustainability`,`maintenance_sustainability`],[`agent-capability-fit`,`agent_capability_fit`],[`execution-clarity`,`execution_clarity`]],Wn=e=>e.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),Gn=e=>e.map(e=>({id:e.id.toString(),title:e.title,category:e.category,status:An.display(e.status),votes:`${e.totalVotes}/${e.quorum}`,up:e.upVotes,veto:e.vetoCount}));function Kn(e,t){let n=Number(e);return Number.isInteger(n)||w(`INVALID_SCORES`,`Score for '${t}' must be an integer`),n}function qn(e,t){let n=t.filter(e=>e.active).sort((e,t)=>e.sortOrder-t.sortOrder),r=new Map(e.map(e=>[e.dimension,e.score]));for(let e of n){r.has(e.name)||w(`MISSING_DIMENSION`,`Missing score for dimension: ${e.label||e.name}`);let t=r.get(e.name);(t<e.minScore||t>e.maxScore)&&w(`INVALID_SCORE`,`Score for '${e.name}' must be between ${e.minScore} and ${e.maxScore}`)}let i=new Set(n.map(e=>e.name));for(let t of e)i.has(t.dimension)||w(`UNKNOWN_DIMENSION`,`Unknown dimension: ${t.dimension}`)}function Jn(e,t,n){let r=t.trim().replaceAll(`-`,`_`);r||w(`INVALID_SCORES`,`Dimension names cannot be empty`),e.has(r)&&w(`INVALID_SCORES`,`Dimension '${r}' was provided more than once`),e.set(r,{dimension:r,score:Kn(n,r)})}function Yn(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(e=>String(e).split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(`=`);return(t<=0||t===e.length-1)&&w(`INVALID_SCORES`,`--score entries must use dimension=value syntax`),[e.slice(0,t),e.slice(t+1)]}))}function Xn(e){let t=new Map;for(let[n,r]of Un)e[n]!==void 0&&Jn(t,r,e[n]);for(let[n,r]of Yn(e.score))Jn(t,n,r);return t.size===0&&w(`ARGS_REQUIRED`,`Provide dimension scores with score flags or --score dimension=value`),[...t.values()]}var Zn=t({meta:{name:`idea`,description:`Idea management`},args:{action:{type:`positional`,description:`Action: list, pending, propose, vote, get, dimensions`,required:!1},id:{type:`positional`,description:`Idea ID`,required:!1},title:{type:`string`,description:`Idea title`},category:{type:`string`,description:`Category`},description:{type:`string`,description:`Description`},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit ideas returned`},"ecosystem-impact":{type:`string`,description:`Ecosystem Impact score`},"implementation-readiness":{type:`string`,description:`Implementation Readiness score`},"dependency-independence":{type:`string`,description:`Dependency Independence score`},"documentation-leverage":{type:`string`,description:`Documentation Leverage score`},"maintenance-sustainability":{type:`string`,description:`Maintenance Sustainability score`},"agent-capability-fit":{type:`string`,description:`Agent Capability Fit score`},"execution-clarity":{type:`string`,description:`Execution Clarity score`},score:{type:`string`,description:`Additional dimension score as name=value; repeatable`,multiple:!0},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe idea`,description:`Idea discovery, review, and voting`,usage:[`probe idea <action> [options]`,`probe idea list --status voting`,`probe idea dimensions`,`probe idea vote 42 --ecosystem-impact 8 --execution-clarity 9 --implementation-readiness 7`],actions:[{name:`list`,detail:`List ideas with optional filters`},{name:`pending`,detail:`List voting ideas you have not voted on`},{name:`get <id>`,detail:`Show one idea`},{name:`dimensions`,detail:`List active evaluation dimensions`},{name:`propose`,detail:`Propose a new idea`},{name:`vote <id>`,detail:`Vote on an idea with dimension scores`}],options:[{name:`--title`,detail:`Idea title for propose`},{name:`--description`,detail:`Idea description for propose`},{name:`--category`,detail:`Idea category for propose/list`},{name:`--ecosystem-impact`,detail:`Ecosystem impact score`},{name:`--implementation-readiness`,detail:`Implementation readiness score`},{name:`--dependency-independence`,detail:`Dependency independence score`},{name:`--documentation-leverage`,detail:`Documentation leverage score`},{name:`--maintenance-sustainability`,detail:`Maintenance sustainability score`},{name:`--agent-capability-fit`,detail:`Agent capability fit score`},{name:`--execution-clarity`,detail:`Execution clarity score`},{name:`--score`,detail:`Additional dimension score as name=value; repeatable`},{name:`--status`,detail:`Status filter for list`},{name:`--limit`,detail:`Max ideas returned for list/pending`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:["Find idea IDs with `probe idea list` before using get/vote.","Use `probe idea dimensions` to list active score dimensions.",`All active dimensions are required. Use explicit flags for default dimensions and repeatable --score name=value for custom dimensions.`,`If a missing-dimension error names a dimension without a dedicated flag, use --score and consider updating Probe.`]});return}let t=e.action;try{switch(t){case`list`:try{var n=I();let t=n.a(await L.create({host:e.host,module:e.module})).iter(`ideas`),r=e.limit?parseInt(e.limit,10):void 0;r!==void 0&&(!Number.isFinite(r)||r<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status&&(t=t.filter(t=>An.matches(t.status,e.status))),e.category&&(t=t.filter(t=>t.category===e.category)),t=Wn(t),r!==void 0&&(t=t.slice(0,r)),C({ideas:t,count:t.length}),S()||console.log(B(`ideas`,Gn(t)));break}catch(e){n.e=e}finally{await n.d()}case`pending`:{let t=e.limit?parseInt(e.limit,10):void 0;t!==void 0&&(!Number.isFinite(t)||t<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`),await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let n=J(e);n||w(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first.");let r=new Set(e.iter(`votes`).filter(e=>e.agentId===n.id).map(e=>e.ideaId)),i=e.iter(`ideas`).filter(e=>An.is.voting(e.status)).filter(e=>!r.has(e.id));i=Wn(i),t!==void 0&&(i=i.slice(0,t)),C({ideas:i,count:i.length}),S()||console.log(B(`ideas`,Gn(i)))});break}case`get`:try{var r=I();let t=e.id;t||w(`IDEA_ID_REQUIRED`,`Idea ID required`);let n=r.a(await L.create({host:e.host,module:e.module})).iter(`ideas`).find(e=>e.id.toString()===t);n||w(`IDEA_NOT_FOUND`,`Idea not found: ${t}`),C(n),S()||console.log(B(`idea`,[{id:n.id.toString(),title:n.title,category:n.category,status:An.display(n.status),totalVotes:n.totalVotes,quorum:n.quorum,upVotes:n.upVotes,downVotes:n.downVotes,vetoCount:n.vetoCount,approvalThreshold:n.approvalThreshold,vetoThreshold:n.vetoThreshold,computedScore:n.computedScore,description:n.description}]));break}catch(e){r.e=e}finally{await r.d()}case`dimensions`:try{var i=I();let t=i.a(await L.create({host:e.host,module:e.module})).iter(`evaluation_dimensions`).filter(e=>e.active).sort((e,t)=>e.sortOrder-t.sortOrder);C({dimensions:t,count:t.length}),S()||console.log(B(`evaluation_dimensions`,t.map(e=>({name:e.name,label:e.label,weight:e.weight,range:`${e.minScore}-${e.maxScore}`,description:e.description}))));break}catch(e){i.e=e}finally{await i.d()}case`propose`:e.title||w(`ARGS_REQUIRED`,`Title required`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{await z(t,`proposeIdea`,{title:e.title,description:e.description||``,category:e.category||`general`})}),C({proposed:!0,title:e.title}),S()||console.log(B(`idea_proposed`,[{title:e.title,category:e.category||`general`}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`vote`:{let t=e.id;t||w(`ARGS_REQUIRED`,`Idea ID required`);let n=Xn(e);try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{qn(n,e.iter(`evaluation_dimensions`)),await z(e,`voteIdea`,{ideaId:BigInt(t),scores:n})}),C({voted:!0,ideaId:t,scores:n}),S()||console.log(B(`idea_voted`,[{ideaId:t,scores:JSON.stringify(n)}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, pending, propose, vote, get, dimensions`)}}catch(e){G(e instanceof Error?e.message:String(e))}}});const Qn=e=>/^\d+$/.test(e),$n=(e,t)=>{if(!t)return!0;let n=t.trim();return n?e.id.toString()===n||(e.contextId||``)===n:!0},er=e=>U.is.user(e),tr=e=>U.is.directive(e),nr=async e=>{let t=e.action;t||w(`ACTION_REQUIRED`,`Message action required`);try{switch(t){case`list`:try{var n=I();let t=e.target,r=parseInt(e.limit||`20`,10);(!Number.isFinite(r)||r<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=n.a(await L.create({host:e.host,module:e.module})),a=i.iter(`channels`),o=i.iter(`projects`),s=[],c=`all`;if(t)if(Qn(t)){let e=BigInt(t),n=i.iter(`project_messages`),r=o.find(t=>t.id===e);s=n.filter(t=>t.projectId===e&&er(t.messageType)).map(e=>({...e,_type:`project`})),c=r?`project:${r.name}`:`project:${e}`}else{let e=a.find(e=>e.name===t||e.id.toString()===t);e&&(s=i.iter(`messages`).filter(t=>t.channelId===e.id&&er(t.messageType)).map(e=>({...e,_type:`channel`})),c=`#${e.name}`)}else{let e=i.iter(`messages`),t=i.iter(`project_messages`);s=[...e.filter(e=>er(e.messageType)).map(e=>({...e,_type:`channel`})),...t.filter(e=>er(e.messageType)).map(e=>({...e,_type:`project`}))]}s=s.filter(t=>$n(t,e.context)),s.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n<r?1:n>r?-1:0}),s=s.slice(0,r);let l=new Map(a.map(e=>[e.id.toString(),e.name])),u=new Map(o.map(e=>[e.id.toString(),e.name]));C({messages:s,count:s.length,target:c}),S()||console.log(B(`messages`,s.map(e=>{let t=`_type`in e&&e._type===`project`?`project:${u.get(e.projectId.toString())||e.projectId}`:`#${l.get(e.channelId.toString())||e.channelId}`;return{id:e.id.toString(),location:t,senderId:e.senderId,content:e.content.slice(0,50)+(e.content.length>50?`...`:``),messageType:U.display(e.messageType),contextId:e.contextId||null,createdAt:q(e.createdAt)}})));break}catch(e){n.e=e}finally{await n.d()}case`directives`:try{var r=I();let t=e.target,n=parseInt(e.limit||`20`,10);(!Number.isFinite(n)||n<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`);let i=r.a(await L.create({host:e.host,module:e.module})),a=i.iter(`channels`),o=i.iter(`projects`),s=[],c=`all`;if(t)if(Qn(t)){let e=BigInt(t),n=i.iter(`project_messages`),r=o.find(t=>t.id===e);s=n.filter(t=>t.projectId===e&&tr(t.messageType)).map(e=>({...e,_type:`project`})),c=r?`project:${r.name}`:`project:${e}`}else{let e=a.find(e=>e.name===t||e.id.toString()===t);e&&(s=i.iter(`messages`).filter(t=>t.channelId===e.id&&tr(t.messageType)).map(e=>({...e,_type:`channel`})),c=`#${e.name}`)}else{let e=i.iter(`messages`),t=i.iter(`project_messages`);s=[...e.filter(e=>tr(e.messageType)).map(e=>({...e,_type:`channel`})),...t.filter(e=>tr(e.messageType)).map(e=>({...e,_type:`project`}))]}s=s.filter(t=>$n(t,e.context)),s.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n<r?1:n>r?-1:0}),s=s.slice(0,n);let l=new Map(a.map(e=>[e.id.toString(),e.name])),u=new Map(o.map(e=>[e.id.toString(),e.name]));C({messages:s,count:s.length,target:c}),S()||console.log(B(`directives`,s.map(e=>{let t=`_type`in e&&e._type===`project`?`project:${u.get(e.projectId.toString())||e.projectId}`:`#${l.get(e.channelId.toString())||e.channelId}`;return{id:e.id.toString(),location:t,senderId:e.senderId,content:e.content.slice(0,50)+(e.content.length>50?`...`:``),messageType:U.display(e.messageType),contextId:e.contextId||null,createdAt:q(e.createdAt)}})));break}catch(e){r.e=e}finally{await r.d()}case`directive`:{let t=e.target,n=e.content;(!t||!n)&&w(`ARGS_REQUIRED`,`Target and directive content required. Usage: probe message directive <target> <content>`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async r=>{if(Qn(t)){let i=BigInt(t),a=r.iter(`projects`),o=r.iter(`project_channels`),s=a.find(e=>e.id===i);s||w(`PROJECT_NOT_FOUND`,`Project '${t}' not found`),o.find(e=>e.projectId===i)||w(`PROJECT_CHANNEL_NOT_FOUND`,`Project channel for '${t}' not found`),await z(r,`sendProjectMessage`,{projectId:i,content:n,messageType:U.fromString(`directive`),contextId:e.context}),C({sent:!0,projectId:i.toString(),projectName:s.name,messageType:`directive`}),S()||console.log(B(`directive_sent`,[{target:`project:${s.name}`,contextId:e.context||null}]))}else{let i=r.iter(`channels`),a=i.find(e=>e.name===t||e.id.toString()===t);a||w(`CHANNEL_NOT_FOUND`,`Channel '${t}' not found. Available: ${i.map(e=>e.name).join(`, `)}`),await z(r,`sendMessage`,{channelId:a.id,content:n,messageType:U.fromString(`directive`),contextId:e.context}),C({sent:!0,channelId:a.id.toString(),channelName:a.name,messageType:`directive`}),S()||console.log(B(`directive_sent`,[{target:`#${a.name}`,contextId:e.context||null}]))}})}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`send`:{let t=e.target,n=e.content;(!t||!n)&&w(`ARGS_REQUIRED`,`Target and message content required. Usage: probe message send <target> <content>`),(e.type||`user`).toLowerCase()===`directive`&&w(`INVALID_TYPE`,`'directive' is not allowed with 'message send'. Use: probe message directive <target> <content>`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async r=>{if(Qn(t)){let i=BigInt(t),a=r.iter(`projects`),o=r.iter(`project_channels`),s=a.find(e=>e.id===i);s||w(`PROJECT_NOT_FOUND`,`Project '${t}' not found`),o.find(e=>e.projectId===i)||w(`PROJECT_CHANNEL_NOT_FOUND`,`Project channel for '${t}' not found`),await z(r,`sendProjectMessage`,{projectId:i,content:n,messageType:U.fromString(e.type||`user`),contextId:e.context}),C({sent:!0,projectId:i.toString(),projectName:s.name}),S()||console.log(B(`message_sent`,[{target:`project:${s.name}`,messageType:e.type||`user`,contextId:e.context||null}]))}else{let i=r.iter(`channels`),a=i.find(e=>e.name===t||e.id.toString()===t);a||w(`CHANNEL_NOT_FOUND`,`Channel '${t}' not found. Available: ${i.map(e=>e.name).join(`, `)}`),await z(r,`sendMessage`,{channelId:a.id,content:n,messageType:U.fromString(e.type||`user`),contextId:e.context}),C({sent:!0,channelId:a.id.toString(),channelName:a.name}),S()||console.log(B(`message_sent`,[{target:`#${a.name}`,messageType:e.type||`user`,contextId:e.context||null}]))}})}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`channels`:try{var i=I();let t=i.a(await L.create({host:e.host,module:e.module})),n=t.iter(`channels`),r=t.iter(`projects`),a=t.iter(`project_channels`),o=new Set(a.map(e=>e.projectId.toString())),s=r.filter(e=>o.has(e.id.toString()));C({channels:n,projects:s,channelCount:n.length,projectCount:s.length}),S()||(console.log(B(`channels`,n.map(e=>({id:e.id.toString(),name:e.name,createdBy:e.createdBy})))),console.log(B(`projects`,s.map(e=>({id:e.id.toString(),name:e.name,repo:e.githubRepo})))));break}catch(e){i.e=e}finally{await i.d()}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, send, directive, directives, channels`)}}catch(e){G(e instanceof Error?e.message:String(e))}};var rr=t({meta:{name:`message`,description:`Message management`},args:{action:{type:`positional`,description:`Action: list, send, directive, directives, channels`,required:!1},target:{type:`positional`,description:`Channel name, project ID, or message content`,required:!1},content:{type:`positional`,description:`Message content (if target is channel/project)`,required:!1},type:{type:`string`,description:`Message type: user, system`,default:`user`},context:{type:`string`,description:`Thread context ID (message ID or entity ref like task:42)`},limit:{type:`string`,description:`Limit messages`,default:`20`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe message`,description:`Channel and project messaging commands`,usage:[`probe message <action> [target] [content] [options]`,`probe message list --limit 50`,`probe message send general "hello team"`,`probe message directive zoe "Focus on project stability" --context project:1`],actions:[{name:`list [target]`,detail:`List user messages (all, channel, or project)`},{name:`directives [target]`,detail:`List directive messages (all, channel, or project)`},{name:`send <target> <content>`,detail:`Send to target channel/project`},{name:`directive <target> <content>`,detail:`Send directive to target channel/project`},{name:`channels`,detail:`List channels and project channels`}],options:[{name:`--type`,detail:`Message type: user, system (default: user)`},{name:`--context`,detail:`Optional thread context ID (message ID or entity ref)`},{name:`--limit`,detail:`Max messages returned for list (default: 20)`},{name:`--wallet`,detail:`Wallet to use for send`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],examples:[`probe message send general hello`,`probe message directive zoe "Pause new work" --context project:1`,`probe message directives zoe --limit 1`,`probe message send zoe "hello there"`,`probe message send zoe "reviewed" --context 123`,`probe message send 1 "project update"`,`probe message list zoe --limit 10`],notes:[`Quotes are only required when target/content contains spaces.`,"Use `probe message channels` to discover available channel names and project IDs."]});return}await nr(e)}}),ir=t({meta:{name:`project`,description:`Project commands`},args:{action:{type:`positional`,description:`Action: list, get, create, status, set-status`,required:!1},id:{type:`positional`,description:`Project ID`,required:!1},value:{type:`positional`,description:`Status value for set-status: active|paused`,required:!1},status:{type:`string`,description:`Filter by status`},limit:{type:`string`,description:`Limit projects returned`},name:{type:`string`,description:`Project name`},description:{type:`string`,description:`Project description`},"github-repo":{type:`string`,description:`GitHub repository URL`},"source-idea":{type:`string`,description:`Source idea ID`},wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe project`,description:`Project listing and lookup commands`,usage:[`probe project <action> [options]`,`probe project list --status active`,`probe project get 1`,`probe project status 1`,`probe project set-status 1 paused --wallet admin-wallet`],actions:[{name:`list`,detail:`List projects with optional status filter`},{name:`get <id>`,detail:`Show one project by ID`},{name:`create`,detail:`Create a new project`},{name:`status <id>`,detail:`Show only project status`},{name:`set-status <id> <active|paused>`,detail:`Update project status (admin/zoe)`}],options:[{name:`--status`,detail:`Status filter for list: active|paused`},{name:`--limit`,detail:`Max projects returned for list`},{name:`--name`,detail:`Project name (create)`},{name:`--description`,detail:`Project description (create)`},{name:`--github-repo`,detail:`GitHub repository URL (create)`},{name:`--source-idea`,detail:`Source idea ID (create)`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Only admin/zoe identities can call set-status.`,"Find idea IDs with `probe idea list` before using --source-idea.","Find project IDs with `probe project list` before using get/create follow-up commands."]});return}let t=e.action;try{switch(t){case`list`:try{var n=I();let t=n.a(await L.create({host:e.host,module:e.module})).iter(`projects`),r=e.limit?parseInt(e.limit,10):void 0;r!==void 0&&(!Number.isFinite(r)||r<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`),e.status&&(t=t.filter(t=>W.matches(t.status,e.status))),t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),r!==void 0&&(t=t.slice(0,r)),C({projects:t,count:t.length}),S()||console.log(B(`projects`,t.map(e=>({id:e.id,name:e.name,status:W.display(e.status),githubRepo:e.githubRepo}))));break}catch(e){n.e=e}finally{await n.d()}case`get`:try{var r=I();let t=e.id;t||w(`PROJECT_ID_REQUIRED`,`Project ID required`);let n=r.a(await L.create({host:e.host,module:e.module})).iter(`projects`).find(e=>e.id.toString()===t);n||w(`PROJECT_NOT_FOUND`,`Project not found: ${t}`),C(n),S()||console.log(B(`project`,[{id:n.id.toString(),name:n.name,status:W.display(n.status),githubRepo:n.githubRepo,description:n.description}]));break}catch(e){r.e=e}finally{await r.d()}case`status`:try{var i=I();let t=e.id;t||w(`PROJECT_ID_REQUIRED`,`Project ID required`);let n=i.a(await L.create({host:e.host,module:e.module})).iter(`projects`).find(e=>e.id.toString()===t);n||w(`PROJECT_NOT_FOUND`,`Project not found: ${t}`);let r=W.display(n.status);C({projectId:t,status:r}),S()||console.log(B(`project_status`,[{id:n.id.toString(),name:n.name,status:r}]));break}catch(e){i.e=e}finally{await i.d()}case`create`:(!e.name||!e[`github-repo`]||!e[`source-idea`])&&w(`ARGS_REQUIRED`,`--name, --github-repo, and --source-idea required`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{await z(t,`createProject`,{sourceIdeaId:BigInt(e[`source-idea`]),name:e.name,githubRepo:e[`github-repo`],description:e.description||``})}),C({created:!0,name:e.name,githubRepo:e[`github-repo`],sourceIdeaId:e[`source-idea`]}),S()||console.log(B(`project_created`,[{name:e.name,githubRepo:e[`github-repo`],sourceIdeaId:e[`source-idea`]}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break;case`set-status`:{let t=e.id,n=e.value;(!t||!n)&&w(`ARGS_REQUIRED`,`Project ID and status required. Use: probe project set-status <id> <active|paused>`);let r=n.toLowerCase().replace(/[_\s]/g,``);[`active`,`paused`].includes(r)||w(`INVALID_STATUS`,`Invalid status: ${n}. Use: active, paused`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{await z(e,`updateProjectStatus`,{projectId:BigInt(t),status:W.fromString(n)})}),C({updated:!0,projectId:t,status:r}),S()||console.log(B(`project_status_updated`,[{projectId:t,status:r}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, get, create, status, set-status`)}}catch(e){G(e instanceof Error?e.message:String(e))}}});const ar=e=>{let t=e.trim().replace(/\.git$/i,``);if(!t)return;if(/^[\w.-]+\/[\w.-]+$/.test(t))return`https://github.com/${t}`;let n=t.match(/^git@github\.com:([\w.-]+\/[\w.-]+)$/i);if(n)return`https://github.com/${n[1]}`;if(t.startsWith(`http://`)||t.startsWith(`https://`))try{let e=new URL(t);if(e.hostname!==`github.com`)return;let n=e.pathname.split(`/`).filter(Boolean);return n.length<2?void 0:`https://github.com/${n[0]}/${n[1]}`}catch{return}},or=async e=>{let t=e.action;t||w(`ACTION_REQUIRED`,`Task action required`);try{switch(t){case`list`:try{var n=I();let t=n.a(await L.create({host:e.host,module:e.module})).iter(`tasks`),r=e.status,i=e.limit?parseInt(e.limit,10):void 0;i!==void 0&&(!Number.isFinite(i)||i<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`),r&&(t=t.filter(e=>V.matches(e.status,r))),e.project&&(t=t.filter(t=>t.projectId.toString()===e.project)),e.assigned&&(t=t.filter(e=>e.assignedTo)),t=t.sort((e,t)=>{let n=K(e.createdAt),r=K(t.createdAt);return n===r?e.id===t.id?0:t.id>e.id?1:-1:r>n?1:-1}),i!==void 0&&(t=t.slice(0,i)),C({tasks:t,count:t.length}),S()||console.log(B(`tasks`,t.map(e=>({id:e.id.toString(),title:e.title,status:V.display(e.status),priority:e.priority,assignedTo:e.assignedTo||``,projectId:e.projectId}))));break}catch(e){n.e=e}finally{await n.d()}case`ready`:try{var r=I();let t=r.a(await L.create({host:e.host,module:e.module})),n=t.iter(`tasks`),i=t.iter(`task_dependencies`),a=new Map(n.map(e=>[e.id.toString(),e])),o=e.limit?parseInt(e.limit,10):void 0;o!==void 0&&(!Number.isFinite(o)||o<=0)&&w(`INVALID_LIMIT`,`--limit must be a positive integer`);let s=n.filter(e=>V.is.open(e.status)).filter(e=>!i.filter(t=>t.taskId===e.id).some(e=>{let t=typeof e.dependencyType==`string`?e.dependencyType:e.dependencyType.tag;if(t!==`Blocks`&&t!==`ParentChild`&&t!==`blocks`&&t!==`parent-child`)return!1;let n=a.get(e.dependsOnId.toString());return n?!V.is.completed(n.status):!1})).filter(t=>!e.project||t.projectId.toString()===e.project).filter(t=>!e.assigned||!!t.assignedTo).sort((e,t)=>{if(e.priority!==t.priority)return e.priority-t.priority;let n=K(e.createdAt),r=K(t.createdAt);return n<r?-1:+(n>r)}),c=(o===void 0?s:s.slice(0,o)).map(e=>({id:e.id.toString(),title:e.title,status:e.status.tag.toLowerCase(),priority:e.priority,assignedTo:e.assignedTo||``,projectId:e.projectId.toString(),blockedBy:[]}));C({tasks:c,count:c.length}),S()||console.log(B(`tasks`,c.map(e=>({id:e.id,title:e.title,status:e.status,priority:e.priority,assignedTo:e.assignedTo,projectId:e.projectId}))));break}catch(e){r.e=e}finally{await r.d()}case`get`:try{var i=I();let t=e.id;t||w(`TASK_ID_REQUIRED`,`Task ID required`);let n=i.a(await L.create({host:e.host,module:e.module})).iter(`tasks`).find(e=>e.id.toString()===t);n||w(`TASK_NOT_FOUND`,`Task not found: ${t}`),C(n),S()||console.log(B(`task`,[{id:n.id.toString(),title:n.title,status:V.display(n.status),priority:n.priority,assignedTo:n.assignedTo||``,projectId:n.projectId.toString(),githubIssueUrl:n.githubIssueUrl||``,githubPrUrl:n.githubPrUrl||``,description:n.description}]));break}catch(e){i.e=e}finally{await i.d()}case`create`:{(!e.project||!e.title)&&w(`ARGS_REQUIRED`,`--project and --title required`);let t=parseInt(e.priority||`5`,10);(t<1||t>10)&&w(`INVALID_PRIORITY`,`Priority must be 1-10`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{await z(n,`createTask`,{projectId:BigInt(e.project),title:e.title,description:e.description||``,priority:t,sourceIdeaId:void 0,githubIssueUrl:e[`github-issue-url`]})}),C({created:!0,projectId:e.project,title:e.title,issue:e[`github-issue-url`]}),S()||console.log(B(`task_created`,[{projectId:e.project,title:e.title,githubIssueUrl:e[`github-issue-url`]||``}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`claim`:{let t=e.id;t||w(`TASK_ID_REQUIRED`,`Task ID required`);try{let n,r;await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{await z(e,`claimTask`,{taskId:BigInt(t)});let i=e.iter(`tasks`).find(e=>e.id.toString()===t),a=i?e.iter(`projects`).find(e=>e.id===i.projectId):void 0;a?.githubRepo&&(n=ar(a.githubRepo),n&&(r=`${n}/blob/main/CONTRIBUTING.md`))}),C({claimed:!0,taskId:t,repositoryUrl:n,contributingUrl:r,nextSteps:[n?`Fork the target repository: ${n}`:`Fork the target repository to your GitHub account using gh cli`,r?`Read CONTRIBUTING.md before starting: ${r}`:`Read CONTRIBUTING.md in the target repository before starting`,`Verify behavior independently by tracing relevant code flow and runtime path before implementing changes.`]}),S()||(console.log(B(`task_claimed`,[{taskId:t,repositoryUrl:n||``,contributingUrl:r||``}])),console.log(``),console.log(`Next steps:`),console.log(n?`1. Fork the target repository: ${n}`:`1. Fork the target repository to your GitHub account`),console.log(r?`2. Read CONTRIBUTING.md before starting: ${r}`:`2. Read CONTRIBUTING.md in the target repository before starting`),console.log(`3. Verify behavior independently by tracing relevant code flow and runtime path before implementing changes.`))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`update`:{let t=e.id;t||w(`TASK_ID_REQUIRED`,`Task ID required`),!e.status&&!e[`github-pr-url`]&&w(`UPDATE_REQUIRED`,`--status or --github-pr-url required`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{await z(n,`updateTaskStatus`,{taskId:BigInt(t),status:e.status?V.fromString(e.status):void 0,githubPrUrl:e[`github-pr-url`],archiveReason:void 0})}),C({updated:!0,taskId:t,status:e.status,pr:e[`github-pr-url`]}),S()||console.log(B(`task_updated`,[{taskId:t,status:e.status||``,githubPrUrl:e[`github-pr-url`]||``}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`review`:{let t=e.id;t||w(`TASK_ID_REQUIRED`,`Task ID required`);try{await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{await z(n,`updateTaskStatus`,{taskId:BigInt(t),status:{tag:`Review`},githubPrUrl:e[`github-pr-url`],archiveReason:void 0})}),C({reviewed:!0,taskId:t,status:`review`,pr:e[`github-pr-url`]}),S()||console.log(B(`task_review`,[{taskId:t,status:`review`,githubPrUrl:e[`github-pr-url`]||``}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}break}case`deps`:{let t=e.id;t||w(`TASK_ID_REQUIRED`,`Task ID required`);let n=BigInt(t);if(e[`add-dep`])try{await R({host:e.host,module:e.module,wallet:e.wallet},async t=>{await z(t,`addTaskDependency`,{taskId:n,dependsOnId:BigInt(e[`add-dep`]),dependencyType:{tag:`Blocks`}})}),C({added:!0,taskId:t,dependsOn:e[`add-dep`]}),S()||console.log(B(`dependency_added`,[{taskId:t,dependsOnId:e[`add-dep`],dependencyType:`blocks`}]))}catch(e){w(`REDUCER_FAILED`,e instanceof Error?e.message:`Unknown error`)}else if(e.list)try{var a=I();let t=a.a(await L.create({host:e.host,module:e.module})).iter(`task_dependencies`).filter(e=>e.taskId===n||e.dependsOnId===n);C({dependencies:t}),S()||console.log(B(`task_dependencies`,t.map(e=>({id:e.id.toString(),taskId:e.taskId.toString(),dependsOnId:e.dependsOnId.toString(),dependencyType:e.dependencyType}))))}catch(e){a.e=e}finally{await a.d()}else w(`DEPS_ACTION_REQUIRED`,`Use --add-dep <taskId> to add a dependency or --list to view dependencies`,`Examples: probe task deps 42 --list | probe task deps 42 --add-dep 17`);break}case`watch`:{let t=Math.min(parseInt(e.timeout||`60`,10),300);await R({host:e.host,module:e.module,wallet:e.wallet},async n=>{S()||console.log(B(`task_watch`,[{timeoutSeconds:t,statusFilter:e.status||``}]));let r=new Promise(e=>{let n=setTimeout(()=>{process.off(`SIGINT`,r),process.off(`SIGTERM`,r),e()},t*1e3),r=()=>{clearTimeout(n),process.off(`SIGINT`,r),process.off(`SIGTERM`,r),e()};process.on(`SIGINT`,r),process.on(`SIGTERM`,r)});n.db.tasks.onInsert((t,n)=>{(!e.status||V.matches(n.status,e.status))&&console.log(B(`tasks`,[{id:n.id.toString(),title:n.title,change_type:`created`}]))}),n.db.tasks.onUpdate((t,n,r)=>{(!e.status||V.matches(r.status,e.status))&&console.log(B(`tasks`,[{id:r.id.toString(),title:r.title,change_type:`updated`}]))}),await r});break}default:w(`INVALID_ACTION`,`Invalid action: ${t}`,`Use: list, ready, get, create, claim, update, review, deps, watch`)}}catch(e){G(e instanceof Error?e.message:String(e))}};var sr=t({meta:{name:`task`,description:`Task management`},args:{action:{type:`positional`,description:`Action: list, ready, get, create, claim, update, review, deps, watch`,required:!1},id:{type:`positional`,description:`Task ID`,required:!1},status:{type:`string`,description:`Status filter or new status`},project:{type:`string`,description:`Project ID`},title:{type:`string`,description:`Task title`},description:{type:`string`,description:`Task description`},priority:{type:`string`,description:`Priority 1-10`},assigned:{type:`boolean`,description:`Show only assigned tasks`,default:!1},wallet:{type:`string`,description:`Wallet name`},"github-pr-url":{type:`string`,description:`GitHub PR URL`},"github-issue-url":{type:`string`,description:`GitHub issue URL`},"add-dep":{type:`string`,description:`Add dependency task ID`},list:{type:`boolean`,description:`List dependencies`,default:!1},timeout:{type:`string`,description:`Watch timeout (seconds)`},limit:{type:`string`,description:`Limit rows for list/ready`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){if(e.json&&x(!0),!e.action){O({command:`probe task`,description:`Task management commands`,usage:[`probe task <action> [options]`,`probe task list --project 1 --status open`,`probe task create --project 1 --title "Fix bug" --priority 5`],actions:[{name:`list`,detail:`List tasks with optional filters`},{name:`ready`,detail:`List immediately claimable open tasks`},{name:`get <id>`,detail:`Show one task`},{name:`create`,detail:`Create a new task`},{name:`claim <id>`,detail:`Claim a task for your identity`},{name:`update <id>`,detail:`Update status and optional PR URL`},{name:`review <id>`,detail:`Mark a task as ready for review`},{name:`deps <id>`,detail:`List or add task dependencies`},{name:`watch`,detail:`Watch task changes in real time`}],options:[{name:`--project`,detail:`Project ID`},{name:`--title`,detail:`Task title (create)`},{name:`--description`,detail:`Task description`},{name:`--priority`,detail:`Priority from 1 to 10 (default: 5)`},{name:`--status`,detail:`Filter or new status`},{name:`--limit`,detail:`Limit rows for list/ready`},{name:`--github-pr-url`,detail:`GitHub PR URL for update/review`},{name:`--github-issue-url`,detail:`GitHub issue URL for create`},{name:`--wallet`,detail:`Wallet to use for authenticated calls`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`}],notes:[`Use full long-form flags only; short aliases are intentionally disabled.`,"Find project IDs with `probe project list`; find task IDs with `probe task list`."]});return}await or(e)}});const cr=5e3,lr=[{key:`agents`,name:`agents`},{key:`tasks`,name:`tasks`},{key:`ideas`,name:`ideas`},{key:`messages`,name:`messages`},{key:`channels`,name:`channels`},{key:`projects`,name:`projects`},{key:`votes`,name:`votes`},{key:`discovered_tasks`,name:`discovered_tasks`},{key:`task_dependencies`,name:`task_dependencies`},{key:`identity_roles`,name:`identity_roles`},{key:`config`,name:`config`},{key:`project_channels`,name:`project_channels`},{key:`project_messages`,name:`project_messages`}],ur=new Set([`connected`,`ready`,`disconnected`,`reconnecting`,`reconnected`,`subscription_applied`,`subscription_error`,`auth_failed`,`heartbeat_failed`,`heartbeat_recovered`,`shutdown`]),dr=(e,t)=>typeof t==`bigint`?t.toString():t,fr=()=>new Date().toISOString(),pr=e=>new Promise(t=>setTimeout(t,e)),mr=e=>{let t=Math.floor(Math.random()*(cr*2+1)-cr);return Math.max(1e3,e+t)},hr=e=>mr(Math.min(3e4,1e3*2**Math.max(0,e-1))),gr=e=>e instanceof Error?e.message:String(e),Y=e=>{if(e instanceof Error)return{name:e.name,message:e.message};if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===null)return e;if(typeof e==`bigint`)return e.toString();try{return JSON.parse(JSON.stringify(e,dr))}catch{return String(e)}},_r=e=>e===`critical`||e===`info`||e===`debug`?e:`critical`,vr=(e,t)=>!!(t===`debug`||ur.has(e)||t===`info`&&e.startsWith(`heartbeat_`)),yr=async e=>{if(!e)return null;let t=l(e);return await f(s(t),{recursive:!0}),De(t,{flags:`a`})},br=e=>{let t=e.toLowerCase();return t.includes(`authentication required`)||t.includes(`unauthorized`)||t.includes(`401`)},xr={wallet:{type:`string`,description:`Wallet name for authenticated connection`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},sender:{type:`string`,description:`Optional sender filter (debug table events only)`},"log-file":{type:`string`,description:`Optional path to append JSONL daemon events`},"log-level":{type:`string`,description:`critical, info, or debug`,default:`critical`},pretty:{type:`boolean`,description:`Human-readable lifecycle logs to stderr`,default:!1},json:{type:`boolean`,description:`Reserved for CLI consistency`,default:!1}};async function Sr(e){let t=_r(e[`log-level`]),n=e.pretty?Me({stdout:process.stderr,stderr:process.stderr}):null,r=null;try{r=await yr(e[`log-file`])}catch(e){let t=gr(e),n=JSON.stringify({source:`nexus`,at:fr(),type:`log_file_error`,message:t});console.log(n);return}let i=e=>{let t=JSON.stringify(e,dr);console.log(t),r&&r.write(`${t}\n`)},a=e=>{if(!vr(e.type,t)||(i({source:`nexus`,at:fr(),...e}),!n))return;let r=String(e.type);r===`connected`?n.info(`Connected to Nexus`):r===`reconnected`?n.success(`Reconnected to Nexus`):r===`disconnected`?n.warn(`Disconnected from Nexus`):r===`reconnecting`?n.info(`Reconnecting to Nexus`):r===`auth_failed`?n.error(`Authentication failed`):r===`heartbeat_failed`?n.warn(`Heartbeat failed repeatedly`):r===`shutdown`&&n.info(`Nexus daemon shutting down`)},o=!1,s=null,c=new Promise(e=>{process.on(`SIGINT`,()=>{o||(o=!0,s=`SIGINT`,e())}),process.on(`SIGTERM`,()=>{o||(o=!0,s=`SIGTERM`,e())})}),l=0,u=null,d=!1;for(;!o;){let n=null;try{await R({host:e.host,module:e.module,wallet:e.wallet,onDisconnect:(...e)=>{n||={reason:`disconnected`,details:e.map(Y)}}},async r=>{let i=r.auth?.wallet||e.wallet||null,s=r.iter(`agents`).find(e=>e.identity.toHexString()===r.identity?.toHexString());if(a(d?{type:`reconnected`,attempts:l,downtime_ms:u?Date.now()-u:null,identity:r.identity?.toHexString()}:{type:`connected`,identity:r.identity?.toHexString(),wallet:i,host:e.host||r.config.spacetime.host,module:e.module||r.config.spacetime.module}),d=!0,l=0,u=null,a({type:`subscription_applied`}),a({type:`ready`,identity:r.identity?.toHexString(),wallet:i,log_file:e[`log-file`]||null,log_level:t,auto_heartbeat:!!s}),t===`debug`)for(let t of lr){let n=r.db[t.key];n.onInsert?.((n,r)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&r.senderId!==e.sender||a({type:`table_insert`,table:t.name,row:Y(r)})}),n.onUpdate?.((n,r,i)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&i.senderId!==e.sender||a({type:`table_update`,table:t.name,old_row:Y(r),new_row:Y(i)})}),n.onDelete?.((n,r)=>{e.sender&&(t.name===`messages`||t.name===`project_messages`)&&r.senderId!==e.sender||a({type:`table_delete`,table:t.name,row:Y(r)})})}let f=null,p=!1,m=0,ee=()=>{o||!s||(f=setTimeout(async()=>{if(!s||p||o){ee();return}p=!0;try{await z(r,`heartbeat`,{agentId:s.id}),m>0&&a({type:`heartbeat_recovered`,failed_count_before_recovery:m}),m=0}catch(e){m+=1,m>=3&&!n&&(n={reason:`heartbeat_failed`,details:{consecutive_failures:m,message:gr(e)}},a({type:`heartbeat_failed`,consecutive_failures:m,message:gr(e)}))}finally{p=!1,ee()}},mr(6e4)))};for(s&&ee();!o&&!n;)await Promise.race([c,pr(200)]);f&&clearTimeout(f)})}catch(e){let t=gr(e);if(br(t)){a({type:`auth_failed`,message:t});break}a({type:`subscription_error`,message:t}),n={reason:`disconnected`,details:{message:t}}}if(o)break;a({type:`disconnected`,reason:n?.reason||`disconnected`,details:Y(n?.details||null)}),u===null&&(u=Date.now()),l+=1;let r=hr(l);a({type:`reconnecting`,attempt:l,backoff_ms:r}),await Promise.race([c,pr(r)])}a({type:`shutdown`,signal:s||`unknown`}),r&&r.end()}var Cr=t({meta:{name:`nexus`,description:`Persistent Nexus daemon (keepalive + critical telemetry)`},args:xr,async run({args:e}){if(k()){O({command:`probe nexus`,description:`Run persistent Nexus keepalive + critical event logger`,usage:[`probe nexus [options]`,`probe nexus --wallet agent-wallet`,`probe nexus --wallet agent-wallet --log-file ./logs/nexus-events.jsonl`,`probe nexus --log-level debug --sender zoe-1`,`probe nexus --pretty`],options:[{name:`--wallet`,detail:`Wallet for authenticated persistent connection`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`},{name:`--log-level`,detail:`critical (default), info, or debug`},{name:`--sender`,detail:`Sender filter for debug message events only`},{name:`--log-file`,detail:`Optional JSONL file path for daemon events`},{name:`--pretty`,detail:`Human-readable lifecycle logs to stderr`}],notes:[`stdout is always structured JSONL for machine parsing.`,`Default mode logs critical connection lifecycle and heartbeat health events only.`,`Use --log-level debug to emit full table insert/update/delete payloads.`]});return}await Sr(e)}});const X={AgentRole:e=>Array.isArray(e)?[`Zoe`,`Admin`,`Zeno`][e[0]]??`variant_${e[0]}`:e,AgentStatus:e=>Array.isArray(e)?[`Online`,`Offline`,`Working`][e[0]]??`variant_${e[0]}`:e,AnnouncementStatus:e=>Array.isArray(e)?[`Pending`,`Ready`,`Failed`][e[0]]??`variant_${e[0]}`:e,DependencyType:e=>Array.isArray(e)?[`Blocks`,`ParentChild`][e[0]]??`variant_${e[0]}`:e,DiscoveredTaskStatus:e=>Array.isArray(e)?[`PendingReview`,`Approved`,`Rejected`,`EscalatedToIdea`][e[0]]??`variant_${e[0]}`:e,DiscoveryDecision:e=>Array.isArray(e)?[`ApproveAsTask`,`Reject`,`EscalateToIdea`][e[0]]??`variant_${e[0]}`:e,IdeaStatus:e=>Array.isArray(e)?[`Voting`,`ApprovedForProject`,`Rejected`,`Implemented`][e[0]]??`variant_${e[0]}`:e,MessageType:e=>Array.isArray(e)?[`User`,`System`,`Directive`][e[0]]??`variant_${e[0]}`:e,ProjectStatus:e=>Array.isArray(e)?[`Active`,`Paused`][e[0]]??`variant_${e[0]}`:e,TaskStatus:e=>Array.isArray(e)?[`Open`,`Claimed`,`InProgress`,`Review`,`Completed`,`Blocked`,`Archived`][e[0]]??`variant_${e[0]}`:e,VoteType:e=>Array.isArray(e)?[`Up`,`Down`,`Veto`][e[0]]??`variant_${e[0]}`:e},Z=e=>{if(!Array.isArray(e))return e;let t=e[0];return typeof t!=`number`&&typeof t!=`bigint`?e:new Date(Number(t)/1e3).toISOString()},Q=e=>t=>{if(!Array.isArray(t))return t;let[n,r]=t;return n===1?null:e?e(r):Array.isArray(r)&&r.length===1?r[0]:r},wr={agents:{last_heartbeat:Z,current_task_id:Q(),created_at:Z,last_active_at:Z,role:X.AgentRole,status:X.AgentStatus},channels:{created_at:Z},discovered_tasks:{created_task_id:Q(),rejection_reason:Q(),created_at:Z,reviewed_at:Q(Z),reviewed_by:Q(),status:X.DiscoveredTaskStatus},ideas:{created_at:Z,updated_at:Z,status:X.IdeaStatus},identity_roles:{role:X.AgentRole},messages:{context_id:Q(),created_at:Z},project_channels:{created_at:Z},project_messages:{context_id:Q(),created_at:Z},projects:{created_at:Z,status:X.ProjectStatus},task_dependencies:{created_at:Z},tasks:{assigned_to:Q(),claimed_at:Q(Z),github_issue_url:Q(),github_pr_url:Q(),source_idea_id:Q(),archived_reason:Q(),status_changed_by:Q(),status_changed_at:Q(Z),created_at:Z,updated_at:Z,status:X.TaskStatus,blocked_from_status:Q(X.TaskStatus)},voice_announcements:{context_type:Q(),context_id:Q(),finalized_at:Q(Z),failed_at:Q(Z),error_message:Q(),created_at:Z,status:X.AnnouncementStatus},votes:{created_at:Z}};function Tr(e){return e.match(/FROM\s+(\w+)/i)?.[1]?.toLowerCase()}const Er=e=>{if(typeof e.name==`string`)return e.name;if(e.name&&typeof e.name==`object`&&`some`in e.name)return e.name.some};var Dr=class extends Error{status;responseBody;constructor(e,t,n){super(n||`SQL request failed with status ${e}`),this.name=`SqlRequestError`,this.status=e,this.responseBody=t}};const Or=e=>{let t=new URL(e);if(t.protocol===`ws:`)t.protocol=`http:`;else if(t.protocol===`wss:`)t.protocol=`https:`;else if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Unsupported host protocol: ${t.protocol}`);return t.toString()},kr=(e,t)=>{let n=Or(e),r=new URL(n);return r.pathname=`${r.pathname.replace(/\/$/,``)}/v1/database/${encodeURIComponent(t)}/sql`,r.toString()},Ar=e=>{if(!Array.isArray(e))throw Error(`Invalid SQL response: expected array of statement results`);return e.map(e=>{let t=e,n=Array.isArray(t.rows)?t.rows:[];return{schema:t.schema,rows:n}})},jr=async e=>{let t=kr(e.host,e.moduleName),n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs),i=Date.now();try{let r=await fetch(t,{method:`POST`,headers:{Authorization:`Bearer ${e.token}`,"Content-Type":`text/plain`,Accept:`application/json`},body:e.sql,signal:n.signal}),a=await r.text();if(!r.ok)throw new Dr(r.status,a);let o;try{o=a?JSON.parse(a):[]}catch{throw Error(`Invalid SQL response: expected JSON payload`)}return{results:Ar(o),durationMs:Date.now()-i}}finally{clearTimeout(r)}},Mr=e=>{let t=e.schema;return t&&`elements`in t&&Array.isArray(t.elements)?t.elements.map(Er).filter(e=>e!==void 0):t&&`columns`in t&&Array.isArray(t.columns)?t.columns.map(e=>e.name):[]},Nr=e=>{let t;try{t=JSON.parse(e).error||e}catch{t=e}return t.includes(`ORDER BY`)?{message:t,suggestion:`SpacetimeDB SQL does not support ORDER BY. Remove it or filter/sort results locally.`}:t.includes(`IS NULL`)||t.includes(`IS NOT NULL`)?{message:t,suggestion:`Use "column = NULL" or "column != NULL" instead of IS NULL / IS NOT NULL.`}:t.includes(`JOIN`)?{message:t,suggestion:`SpacetimeDB has limited JOIN support. Try querying single tables or use multiple queries.`}:t.includes(`no such table`)?{message:t,suggestion:`Check the table name. Common tables: tasks, projects, agents, ideas, messages.`}:t.includes(`no such column`)?{message:t,suggestion:`Check the column name. Use SELECT * to see all available columns.`}:{message:t}},Pr=Object.keys(wr),Fr=(e,t)=>{if(e instanceof Dr){e.status===401&&w(`AUTH_REQUIRED`,"Authentication required. Run `probe auth <wallet> --save` first.");let{message:t,suggestion:n}=Nr(e.responseBody);e.status===400&&w(`SQL_INVALID`,t,n),w(`SQL_FAILED`,t,n)}e instanceof Error&&e.name===`AbortError`&&w(`SQL_UNAVAILABLE`,`SQL request timed out after ${t}ms`),w(`SQL_UNAVAILABLE`,e instanceof Error?e.message:`SQL request failed`)},Ir=3e4,Lr=(e,t)=>({duration_ms:t,query_count:e.length,row_count_total:e.reduce((e,t)=>e+t.rows.length,0)}),Rr=(e,t,n)=>{let r={};for(let i=0;i<e.length;i+=1){let a=e[i],o=Mr(a),s=t&&n?wr[n]:void 0,c=a.rows.map(e=>{let t={};for(let n=0;n<o.length;n++){let r=o[n],i=e[n],a=s?.[r];t[r]=a?a(i):i}return t});r[`query_${i+1}`]={columns:o,rows:c}}return e.length===0&&(r.query_1={columns:[],rows:[]}),r},zr=(e,t,n,r,i)=>{let a={},o=r&&i?wr[i]:void 0;for(let t=0;t<e.length;t+=1){let n=e[t],r=Mr(n),i=n.rows.map(e=>{let t={};for(let n=0;n<r.length;n++){let i=r[n],a=e[n],s=o?.[i];t[i]=s?s(a):a}return t});a[`query_${t+1}`]=i}return e.length===0&&(a.query_1=[]),t&&(a.meta=[Lr(e,n)]),On(a)};var Br=t({meta:{name:`query`,description:`Run SQL read queries against Nexus`},args:{sql:{type:`positional`,description:`SQL query string`,required:!1},file:{type:`string`,description:`Read SQL from file path`},wallet:{type:`string`,description:`Wallet name override`},host:{type:`string`,description:`SpacetimeDB host override`},module:{type:`string`,description:`SpacetimeDB module override`},timeout:{type:`string`,description:`Request timeout in milliseconds`},meta:{type:`boolean`,description:`Include metadata in output`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1},tables:{type:`boolean`,description:`List all available tables`,default:!1},decode:{type:`boolean`,description:`Decode algebraic types to human-readable values`,default:!0},raw:{type:`boolean`,description:`Output raw algebraic type arrays (no decoding)`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.sql||e.file;if(e.tables){S()?C({tables:Pr}):console.log(On({tables:Pr}));return}if(!t){O({command:`probe query`,description:`Execute SQL against the configured Nexus SpacetimeDB module`,usage:[`probe query "SELECT * FROM tasks LIMIT 5"`,`probe query --file ./query.sql --meta`,`probe query --tables`],options:[{name:`--file`,detail:`Read SQL from file`},{name:`--wallet`,detail:`Wallet override (defaults to config defaultWallet)`},{name:`--host, --module`,detail:`Nexus SpacetimeDB target overrides`},{name:`--timeout`,detail:`Request timeout in ms (default: ${Ir})`},{name:`--meta`,detail:`Include metadata in output`},{name:`--json`,detail:`JSON output mode with keyed objects`},{name:`--tables`,detail:`List all available tables`},{name:`--decode`,detail:`Decode algebraic types (default: true)`},{name:`--raw`,detail:`Output raw algebraic arrays (no decoding)`}],notes:[`This command is read-only and intended for SQL queries against Nexus tables.`,`JSON mode returns keyed objects: {"query_1": {"columns": [...], "rows": [{"id": 1, ...}]}}`,`Use --raw to see raw SpacetimeDB algebraic type arrays.`]});return}let n=e.timeout?Number.parseInt(e.timeout,10):Ir;(!Number.isFinite(n)||n<=0)&&w(`INVALID_TIMEOUT`,`Invalid timeout: ${e.timeout}`);let r=await b(),i=e.wallet||r.defaultWallet;i||w(`WALLET_REQUIRED`,`Wallet required. Use --wallet or set default wallet.`),await M(i)||w(`WALLET_NOT_FOUND`,`Wallet not found: ${i}`);let a=await A(i);a||w(`AUTH_REQUIRED`,"No cached token. Run `probe auth <wallet> --save` first.");let o=e.host||r.spacetime.host,s=e.module||r.spacetime.module,c=e.file?await p(e.file,`utf-8`):e.sql??``;c.trim()||w(`SQL_REQUIRED`,`SQL query is empty`);let l=e.raw?!1:e.decode??!0,u=Tr(c);try{let{results:t,durationMs:r}=await jr({host:o,moduleName:s,token:a.token,sql:c,timeoutMs:n});if(S()){let n=Rr(t,l,u);e.meta?C({...n,meta:Lr(t,r)}):C(n);return}console.log(zr(t,!!e.meta,r,l,u))}catch(e){Fr(e,n)}}}),Vr=t({meta:{name:`sign`,description:`Sign a message using wallet private key`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},message:{type:`positional`,description:`Message to sign`,required:!1},"message-file":{type:`string`,description:`Read message from file`},"password-file":{type:`string`,description:`Read password from file`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(!t){O({command:`probe sign`,description:`Sign arbitrary text using wallet private key`,usage:[`probe sign <wallet-name> <message> [options]`,`probe sign <wallet-name> --message-file ./payload.txt [options]`],options:[{name:`--message-file`,detail:`Read message content from file`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--json`,detail:`JSON output for agents`}]});return}let n;if(e[`message-file`])try{n=await p(e[`message-file`],`utf-8`)}catch{w(`FILE_READ_ERROR`,`Failed to read message file: ${e[`message-file`]}`)}else e.message?n=e.message:w(`MESSAGE_REQUIRED`,`Message or message-file required`);let i=await Ze({passwordFile:e[`password-file`],promptMessage:`Enter wallet password:`,jsonModeError:`Password file required in JSON mode or provide PROBE_WALLET_PASSWORD`});try{let e=(await ht(t,i)).getKeyPair(0),a=e.sign(r.from(n)),o=e.getPublicKey(),s=e.getAddress();C({wallet:t,message:n,signature:a.toString(`hex`),publicKey:o.toString(`hex`),address:s.toString()}),S()||(E(`Message signed successfully`),console.log(`Signature: ${a.toString(`hex`)}`))}catch(e){w(`SIGN_ERROR`,e instanceof Error?e.message:`Failed to sign message`)}}}),Hr=t({meta:{name:`token`,description:`Show cached JWT token for wallet`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},clear:{type:`boolean`,description:`Clear cached token now (next auth call gets a new token)`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(!t){O({command:`probe token`,description:`Inspect or clear cached authentication token`,usage:[`probe token <wallet-name> [options]`,`probe token <wallet-name> --clear`],options:[{name:`--clear`,detail:`Clear cached token now (recommended)`},{name:`--json`,detail:`JSON output for agents`}]});return}if(e.clear){await ut(t),C({cleared:t}),S()||T(`Token cache cleared for "${t}". Run 'probe auth' to get a new token.`);return}try{let e=await A(t);e||w(`TOKEN_NOT_FOUND`,`No cached token for wallet '${t}'`,`Run 'probe auth ${t} --save' to authenticate`);let n=new Date(e.expiresAt),r=new Date,i=Math.floor((n.getTime()-r.getTime())/1e3),a=i>0;C({wallet:t,token:e.token,expiresAt:e.expiresAt,expiresIn:Math.max(0,i),valid:a}),S()||(console.log(`Wallet: ${t}`),console.log(`Token: ${e.token.slice(0,50)}...`),console.log(`Expires: ${n.toUTCString()}`),console.log(`Status: ${a?`Valid`:`Expired`}`),a||T(`Token has expired. Run with --clear to remove it and re-authenticate.`))}catch(e){w(`TOKEN_ERROR`,e instanceof Error?e.message:`Failed to read token`)}}});const Ur=`@zenon-red/probe`,Wr=3e4,Gr=e(import.meta.url);function $(e){let t=e.trim();return t.startsWith(`${Ur}@`)?t.slice(`${Ur}@`.length):t.startsWith(`refs/tags/`)?$(t.slice(10)):t.replace(/^v/,``)}function Kr(){let e=[`../../package.json`,`../package.json`,`../../../package.json`];try{for(let t of e)try{let e=Gr(t).version;if(e)return e}catch{}if(process.env.npm_package_version)return process.env.npm_package_version}catch{}return`0.0.0`}function qr(e){if(e&&e!==`auto`)return e;let t=process.execPath,n=process.argv[1]||``,r=``;try{r=Ne(`command -v probe`,{timeout:5e3,encoding:`utf8`}).trim()}catch{}if(t.includes(`.probe`)||t.includes(`probe-linux`)||t.includes(`probe-darwin`)||t.includes(`probe-windows`)||n.includes(`.probe`)||r.includes(`.probe`)||r.includes(`probe-linux`)||r.includes(`probe-darwin`)||r.includes(`probe-windows`))return`binary`;if(n.includes(`node_modules`)||r.includes(`node_modules`))return`npm`;try{if(Ne(`npm list -g @zenon-red/probe --depth=0 2>/dev/null`,{timeout:1e4,encoding:`utf8`}).includes(`@zenon-red/probe`))return`npm`}catch{}return`unknown`}async function Jr(){let e=`https://registry.npmjs.org/${Ur}/latest`,t=await fetch(e,{signal:AbortSignal.timeout(Wr)});if(!t.ok)throw Error(`npm registry returned ${t.status}`);let n=await t.json();if(!n.version)throw Error(`No version field in npm response`);return $(n.version)}async function Yr(e){let t=`https://api.github.com/repos/zenon-red/probe/releases/${e}`,n=await fetch(t,{headers:{Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(Wr)});if(!n.ok)throw Error(`GitHub API returned ${n.status}`);return await n.json()}async function Xr(){let e=await Yr(`latest`);return{version:$(e.tag_name),release:e}}async function Zr(e){let t=$(e);try{return await Yr(`tags/v${t}`)}catch(e){if(!(e instanceof Error?e.message:``).includes(`404`))throw e;return await Yr(`tags/${encodeURIComponent(`${Ur}@${t}`)}`)}}function Qr(){let e=o(),t=i(),n={linux:`linux`,darwin:`darwin`,windows:`windows`},r={x64:`x64`,arm64:`arm64`},a=n[e],s=r[t];if(!a||!s)throw Error(`Unsupported platform: ${e}/${s}`);return`probe-${a}-${s}${o()===`windows`?`.exe`:``}`}function $r(){return s(process.execPath)}async function ei(e,t){let n=await fetch(e,{signal:AbortSignal.timeout(Wr*2),redirect:`follow`});if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);if(!n.body)throw Error(`Empty response body`);let r=Fe.fromWeb(n.body),i=De(t,{mode:493});await Ie(r.pipe(i))}function ti(e,t){let n=e.split(`/`).pop()||e.split(`\\`).pop()||``,r=t.split(`
6
+ `),i=``;for(let e of r){let[t,r]=e.trim().split(/\s+/);if(r===n){i=t;break}}if(!i)return!1;let a=ke(e);return Pe(`sha256`).update(a).digest(`hex`)===i}async function ni(e){Ne(`npm install -g ${Ur}@${$(e)}`,{stdio:`inherit`,timeout:12e4})}async function ri(e,t){let n=Qr(),r=e.assets.find(e=>e.name===n);if(!r)throw Error(`Asset not found for ${n}`);let i=e.assets.find(e=>e.name===`SHA256SUMS.txt`);if(!i)throw Error(`SHA256SUMS.txt not found in release`);let a=l($r(),o()===`windows`?`probe.exe`:`probe`),s=`${a}.tmp`,c=`${a}.bak`;await ei(r.browser_download_url,s);let u=await fetch(i.browser_download_url,{signal:AbortSignal.timeout(Wr)});if(!u.ok)throw Error(`Failed to download SHA256SUMS.txt`);if(!ti(s,await u.text()))throw je(s),Error(`CHECKSUM_MISMATCH`);try{if(Oe(a)&&Ae(a,c),Ae(s,a),Ne(`"${a}" --version`,{timeout:1e4,encoding:`utf8`}),Oe(c))try{je(c)}catch{}}catch(e){if(Oe(c))try{Ae(c,a)}catch{throw Error(`ROLLBACK_FAILED: Upgrade failed and rollback also failed. Backup at: ${c}`)}if(Oe(s))try{je(s)}catch{}throw e}}const ii=new Set([`auto`,`npm`,`binary`]),ai=e=>{C(e),!S()&&console.log(B(`upgrade_result`,[{method:e.method,currentVersion:e.currentVersion,targetVersion:e.targetVersion,latestVersion:e.latestVersion,updated:e.updated,checkOnly:e.checkOnly}]))};var oi=t({meta:{name:`upgrade`,description:`Upgrade Probe to the latest or a specific version`},args:{target:{type:`positional`,description:`Version to upgrade to (e.g. 1.2.0 or v1.2.0)`,required:!1},check:{type:`boolean`,description:`Check for updates without upgrading`,default:!1},method:{type:`string`,description:`Installation method: auto, npm, binary`},yes:{type:`boolean`,description:`Skip confirmation prompts`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(e.json&&x(!0),e.target===`--help`||e.target===`-h`){O({command:`probe upgrade`,description:`Upgrade Probe to the latest or a specific version`,usage:[`probe upgrade`,`probe upgrade --check`,`probe upgrade 1.2.0`,`probe upgrade --method npm`,`probe upgrade --method binary --yes`,`probe upgrade --json --check`],options:[{name:`--check`,detail:`Check for updates without upgrading`},{name:`--method`,detail:`Force install method: auto, npm, binary`},{name:`--yes`,detail:`Skip confirmation prompts`},{name:`--json`,detail:`JSON output`}]});return}let t=e.method;t&&!ii.has(t)&&w(`INVALID_METHOD`,`Invalid --method value: ${e.method}`,`Use: --method auto | npm | binary`);let n=Kr(),r=qr(t),i,a,o;try{if(e.target)i=$(e.target),r===`binary`&&(o=await Zr(i));else if(r===`npm`)a=await Jr(),i=a;else{let e=await Xr();a=e.version,i=e.version,o=e.release}}catch(t){let n=t instanceof Error?t.message:`Failed to check latest version`;!e.target&&r===`binary`&&n.includes(`GitHub API returned 404`)&&w(`NO_RELEASES_PUBLISHED`,`No GitHub releases are published yet for binary upgrades.`,`Use: npm install -g @zenon-red/probe (or your package manager) until the first release is published.`),w(`VERSION_LOOKUP_FAILED`,n)}i||w(`VERSION_LOOKUP_FAILED`,`Could not determine target version.`);let s=i!==n;if(e.check){ai({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:s,updated:!1,checkOnly:!0});return}if(r===`unknown`&&w(`METHOD_UNKNOWN`,`Could not detect installation method for in-place upgrade.`,"Use --method npm|binary explicitly, or run your package manager upgrade command (e.g. `bun add -g @zenon-red/probe`)."),!s){ai({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:!1,updated:!1,checkOnly:!1});return}!S()&&!e.yes&&(await ne({message:`Upgrade Probe from ${n} to ${i}?`})||(T(`Upgrade cancelled`),process.exit(0)));try{r===`npm`?await ni(i):await ri(o||await Zr(i),i)}catch(e){let t=e instanceof Error?e.message:`Upgrade failed`;w(t.includes(`CHECKSUM_MISMATCH`)?`CHECKSUM_MISMATCH`:t.includes(`ROLLBACK_FAILED`)?`ROLLBACK_FAILED`:t.includes(`PERMISSION`)||t.includes(`EACCES`)?`PERMISSION_DENIED`:`UPGRADE_FAILED`,t)}ai({method:r,currentVersion:n,targetVersion:i,latestVersion:a||i,updateAvailable:!0,updated:!0,checkOnly:!1})}}),si=t({meta:{name:`create`,description:`Create a new wallet with randomly generated mnemonic`},args:{name:{type:`positional`,description:`Wallet identifier`,required:!1},"password-file":{type:`string`,description:`Read password from file`},"set-default":{type:`boolean`,description:`Set this wallet as the default`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(k()||!t){O({command:`probe wallet create`,description:`Create a new encrypted wallet`,usage:[`probe wallet create <name> [options]`,`probe wallet create agent-wallet --set-default`],options:[{name:`--password-file`,detail:`Read wallet password from file`},{name:`--set-default`,detail:`Set created wallet as default`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Password source order: --password-file, PROBE_WALLET_PASSWORD, interactive prompt.`]});return}/^[a-zA-Z0-9_-]+$/.test(t)||w(`INVALID_NAME`,`Wallet name must be alphanumeric with hyphens or underscores only`);let n=await b(),r=await Ze({passwordFile:e[`password-file`],promptMessage:`Enter password to encrypt wallet:`,confirmPromptMessage:`Confirm password:`,minLength:n.passwordMinLength,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt`});try{let n=await ft(t,r),i=e[`set-default`];if(i||(await mt()).length===1&&(i=!0),i){let e=await v();e.defaultWallet=n.name,await Be(e)}C({name:n.name,address:n.address,publicKey:n.publicKey,mnemonic:n.mnemonic,default:i}),S()||(E(`Wallet "${n.name}" created successfully`),console.log(`Address: ${n.address}`),console.log(`\nMnemonic: ${n.mnemonic}`),Je(`Save this mnemonic securely - it cannot be recovered!`),i&&console.log(`
7
+ Set as default wallet`))}catch(e){w(`WALLET_CREATE_ERROR`,e instanceof Error?e.message:`Failed to create wallet`)}}}),ci=t({meta:{name:`default`,description:`Set the default wallet`},args:{name:{type:`positional`,description:`Wallet name to set as default`,required:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(k()||!t){O({command:`probe wallet default`,description:`Set the default wallet used by commands`,usage:[`probe wallet default <name> [options]`,`probe wallet default agent-wallet`],options:[{name:`--json`,detail:`JSON output for agents`}]});return}await _t(t)||w(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`);let n=await v();n.defaultWallet=t,await Be(n),C({defaultWallet:t}),S()||E(`Default wallet set to '${t}'`)}}),li=t({meta:{name:`delete`,description:`Delete a wallet`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},yes:{type:`boolean`,description:`Skip confirmation prompt`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(k()||!t){O({command:`probe wallet delete`,description:`Delete a wallet from local storage`,usage:[`probe wallet delete <name> [options]`,`probe wallet delete old-wallet --yes`],options:[{name:`--yes`,detail:`Skip interactive confirmation prompt`},{name:`--json`,detail:`JSON output for agents`}]});return}await _t(t)||w(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`,`Run 'probe wallet list' to see available wallets`),!S()&&!e.yes&&(await ne({message:`Are you sure you want to delete wallet "${t}"? This cannot be undone.`})||(T(`Deletion cancelled`),process.exit(0)));try{await gt(t),C({deleted:t}),S()||E(`Wallet "${t}" deleted successfully`)}catch(e){w(`WALLET_DELETE_ERROR`,e instanceof Error?e.message:`Failed to delete wallet`)}}}),ui=t({meta:{name:`import`,description:`Import wallet from mnemonic phrase`},args:{name:{type:`positional`,description:`Wallet identifier`,required:!1},mnemonic:{type:`string`,description:`Mnemonic phrase (space-separated)`},"mnemonic-file":{type:`string`,description:`Read mnemonic from file`},"password-file":{type:`string`,description:`Read password from file`},"set-default":{type:`boolean`,description:`Set this wallet as the default`,default:!1},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(k()||!t){O({command:`probe wallet import`,description:`Import an encrypted wallet from mnemonic`,usage:[`probe wallet import <name> [options]`,`probe wallet import agent-wallet --mnemonic-file ./mnemonic.txt`],options:[{name:`--mnemonic`,detail:`24-word mnemonic phrase`},{name:`--mnemonic-file`,detail:`Read mnemonic from file`},{name:`--password-file`,detail:`Read wallet password from file`},{name:`--set-default`,detail:`Set imported wallet as default`},{name:`--json`,detail:`JSON output for agents`}],notes:[`Mnemonic source order: --mnemonic, --mnemonic-file, PROBE_WALLET_MNEMONIC, interactive prompt.`]});return}/^[a-zA-Z0-9_-]+$/.test(t)||w(`INVALID_NAME`,`Wallet name must be alphanumeric with hyphens or underscores only`);let n=await Qe({mnemonic:e.mnemonic,mnemonicFile:e[`mnemonic-file`],jsonModeError:`Mnemonic required via --mnemonic, --mnemonic-file, or PROBE_WALLET_MNEMONIC env`}),r=await Ze({passwordFile:e[`password-file`],promptMessage:`Enter password to encrypt wallet:`,jsonModeError:`Password required via PROBE_WALLET_PASSWORD env, --password-file, or interactive prompt`});try{let i=await pt(t,n,r),a=e[`set-default`];if(a||(await mt()).length===1&&(a=!0),a){let e=await v();e.defaultWallet=i.name,await Be(e)}C({name:i.name,address:i.address,default:a}),S()||(E(`Wallet "${i.name}" imported successfully`),console.log(`Address: ${i.address}`),a&&console.log(`
8
+ Set as default wallet`))}catch(e){w(`WALLET_IMPORT_ERROR`,e instanceof Error?e.message:`Failed to import wallet`)}}}),di=t({meta:{name:`list`,description:`List all stored wallets`},args:{json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){if(k()){O({command:`probe wallet list`,description:`List all locally stored wallets`,usage:[`probe wallet list [options]`,`probe wallet list --json`],options:[{name:`--json`,detail:`JSON output for agents`}]});return}e.json&&x(!0);try{let e=await mt(),t=await b(),n=e.map(e=>({...e,default:e.name===t.defaultWallet}));if(C(n),!S())if(e.length===0)T(`No wallets found`);else{console.log(`Wallets:`);for(let e of n){let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`unknown`,n=e.default?`*`:` `;console.log(`${n} ${e.name.padEnd(12)} ${e.address.slice(0,10)}... created ${t}`)}t.defaultWallet&&console.log(`
9
+ * = default wallet`)}}catch(e){w(`WALLET_LIST_ERROR`,e instanceof Error?e.message:`Failed to list wallets`)}}}),fi=t({meta:{name:`show`,description:`Show wallet address and public key`},args:{name:{type:`positional`,description:`Wallet name`,required:!1},"public-key":{type:`boolean`,description:`Include public key in output`,default:!1},"password-file":{type:`string`,description:`Read password from file`},json:{type:`boolean`,description:`Output JSON only`,default:!1}},async run({args:e}){e.json&&x(!0);let t=e.name;if(k()||!t){O({command:`probe wallet show`,description:`Show wallet address and optional public key`,usage:[`probe wallet show <name> [options]`,`probe wallet show my-wallet --public-key --password-file ./pass.txt`],options:[{name:`--public-key`,detail:`Include public key in output`},{name:`--password-file`,detail:`Read password for public key extraction`},{name:`--json`,detail:`JSON output for agents`}]});return}let n=await M(t);n||w(`WALLET_NOT_FOUND`,`Wallet '${t}' does not exist`,`Run 'probe wallet list' to see available wallets`);let r;if(e[`password-file`])try{r=await p(e[`password-file`],`utf-8`),r=r.trim()}catch{w(`FILE_READ_ERROR`,`Failed to read password file: ${e[`password-file`]}`)}try{let i;r&&(i=(await ht(t,r)).getKeyPair(0).getPublicKey().toString(`hex`));let a={name:n.name,address:n.address,createdAt:n.createdAt};(e[`public-key`]||i)&&(a.publicKey=i),C(a),S()||(console.log(`Name: ${n.name}`),console.log(`Address: ${n.address}`),n.createdAt&&console.log(`Created: ${new Date(n.createdAt).toLocaleString()}`),i&&console.log(`Public Key: ${i}`))}catch(e){w(`WALLET_LOAD_ERROR`,e instanceof Error?e.message:`Failed to load wallet`)}}});const pi=new Set([`create`,`import`,`list`,`show`,`delete`,`default`]);var mi=t({meta:{name:`wallet`,description:`Manage Zenon Network wallets`},run(){let e=process.argv.slice(2).filter(e=>!e.startsWith(`-`));e.length>1&&pi.has(e[1])||O({command:`probe wallet`,description:`Create, import, inspect, and manage wallets`,usage:[`probe wallet <subcommand> [positionals] [options]`,`probe wallet create my-wallet --set-default`,`probe wallet import my-wallet --mnemonic-file ./mnemonic.txt`],actions:[{name:`create <name>`,detail:`Create a new encrypted wallet`},{name:`import <name>`,detail:`Import wallet from mnemonic phrase`},{name:`list`,detail:`List stored wallets`},{name:`show <name>`,detail:`Show wallet address and optional public key`},{name:`delete <name>`,detail:`Delete a wallet`},{name:`default <name>`,detail:`Set default wallet`}],notes:[`Use long-form flags only for predictable agent automation.`]})},subCommands:{create:si,import:ui,list:di,show:fi,delete:li,default:ci}}),hi=t({meta:{name:`whoami`,description:`Show current authenticated agent profile`},args:{wallet:{type:`string`,description:`Wallet name`},json:{type:`boolean`,description:`Output JSON`,default:!1},host:{type:`string`,description:`SpacetimeDB host`},module:{type:`string`,description:`Module name`}},async run({args:e}){e.json&&x(!0);try{await R({host:e.host,module:e.module,wallet:e.wallet},async e=>{let t=e.iter(`agents`).find(t=>t.identity.toHexString()===e.identity?.toHexString());t||w(`NOT_REGISTERED`,"Agent not registered. Run `probe agent register` first."),C(t),S()||console.log(B(`agent`,[{id:t.id,name:t.name,role:jn.display(t.role),status:H.display(t.status),lastHeartbeat:q(t.lastHeartbeat),currentTaskId:t.currentTaskId?t.currentTaskId.toString():``,capabilities:t.capabilities.join(`,`),identity:e.identity?.toHexString()||``}]))})}catch(e){G(e instanceof Error?e.message:String(e))}}});const gi=new Set([`wallet`,`auth`,`sign`,`token`,`config`,`nexus`,`agent`,`task`,`message`,`idea`,`discover`,`project`,`query`,`doctor`,`whoami`,`upgrade`]),_i=()=>{let e=ot(process.argv.slice(2));at(e.forceHelp),process.argv=[...process.argv.slice(0,2),...e.argv]},{version:vi,description:yi}=e(import.meta.url)(`../package.json`),bi=t({meta:{name:`probe`,version:vi,description:yi},args:{json:{type:`boolean`,description:`Output JSON only`,default:!1}},run(){let e=process.argv.slice(2).find(e=>!e.startsWith(`-`));e&&gi.has(e)||O({command:`probe`,description:yi,usage:[`probe <command> [positionals] [options]`,`probe idea propose --title "Better task scoring" --category planning`,`probe task claim 42 --wallet agent-wallet`],actions:[{name:`wallet`,detail:`Wallet lifecycle commands`},{name:`auth`,detail:`Authenticate wallet and cache token`},{name:`token`,detail:`Inspect or clear cached token`},{name:`sign`,detail:`Sign text payloads`},{name:`nexus`,detail:`Run persistent Nexus daemon (keepalive + event logs)`},{name:`agent, task, idea, discover, message, project`,detail:`Nexus workspace commands`},{name:`query`,detail:`Execute SQL queries against Nexus`},{name:`doctor`,detail:`Run setup and connectivity diagnostics`},{name:`upgrade`,detail:`Upgrade Probe to the latest version`},{name:`config`,detail:`Read/write CLI configuration`}],options:[{name:`--json`,detail:`JSON output mode for agents`}],notes:[`Nexus commands connect to SpacetimeDB (the realtime database backing Nexus).`]})},subCommands:{wallet:mi,auth:yt,sign:Vr,token:Hr,config:St,nexus:Cr,agent:Rn,task:sr,message:rr,idea:Zn,discover:Hn,project:ir,query:Br,doctor:kn,upgrade:oi,whoami:hi}}),xi=e=>{if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`connection failed`)||t.includes(`connection timeout`)||t.includes(`authentication required`)||t.includes(`unauthorized`)||t.includes(`wallet required`)||t.includes(`wallet not found`)||t.includes(`agent not registered`)||t.includes(`subscription error`)};process.on(`unhandledRejection`,e=>{throw xi(e)&&process.exit(1),e}),_i(),n(bi);export{};
10
10
  //# sourceMappingURL=index.js.map