@codified/cli 0.1.8 → 0.1.9
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 +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -263,7 +263,7 @@ Respond with JSON only. No markdown, no explanation.`,n=await this.anthropic.mes
|
|
|
263
263
|
`),segment:r.segment,skipContext:!1});return await this.mcp.approveStudy(i.studyId),this.activeStudies.set(e.id,i.studyId),this.planner.updatePlanStatus(e.id,"in_progress"),e.externalStudyId=i.studyId,await this.mcp.sendToParticipant(i.studyId),null}startPolling(e){let r=this.activeStudies.get(e);if(!r)return;let i=setInterval(async()=>{try{await this.checkStudyProgress(e,r)}catch(n){console.error(`[collection/external] Error polling study ${r}:`,n)}},this.config.progressPollIntervalMs);this.pollTimers.set(e,i)}stopPolling(e){let r=this.pollTimers.get(e);r&&(clearInterval(r),this.pollTimers.delete(e))}async checkStudyProgress(e,r){(await this.mcp.getStudyProgress(r)).completed>=this.config.minInterviewsForSynthesis&&await this.collectResults(e,r)&&(this.stopPolling(e),this.planner.updatePlanStatus(e,"completed"))}async collectResults(e,r){let i=this.planner.getPlan(e);if(!i)return null;let n=[];for(let o of i.questions){let s=R3(o);if(!s)continue;let a=await this.mcp.queryInsights(s);a.quotes.length>0&&n.push({source:G$(r),content:JSON.stringify(a),metadata:{type:"insight",topic:s,quoteCount:a.quotes.length,studyId:r}})}for(let o of i.questions){let s=await this.mcp.searchTranscripts(o);for(let a of s)n.push({source:G$(r),content:a.excerpt,metadata:{type:"transcript_excerpt",interviewId:a.interviewId,userId:a.userId,studyId:r}})}return n.length===0?null:{planId:e,rawData:n,structuredOutput:null,completedAt:new Date().toISOString()}}async addParticipants(e,r){let i=this.activeStudies.get(e);i&&(await this.mcp.registerUsers(r),await this.mcp.sendToParticipant(i,r.map(n=>n.userId)))}getStudyId(e){return this.activeStudies.get(e)}stopAll(){for(let[e]of this.pollTimers)this.stopPolling(e)}}});function B$(t,e){return{system:`internal-${t}`,reference:e,agentId:null,reliability:.7}}var D3,zs,ob=m(()=>{"use strict";Ne();D3={responseTimeoutMs:4320*60*1e3,channels:{}},zs=class{constructor(e,r,i){this.planner=e;this.eventBus=r;this.config={...D3,...i}}config;pendingRequests=new Map;async execute(e){switch(e.method.type){case"team_dm":return this.executeTeamDm(e);case"document_request":return this.executeDocumentRequest(e);case"tribal_knowledge_mining":return this.executeTribalKnowledgeMining(e);default:return null}}async executeTeamDm(e){let r=e.method,i=r.channel,n=this.config.channels[i];if(!n)return console.warn(`[collection/internal] Channel "${i}" not configured`),null;let o=await this.buildGapContext(e.gapIds),s=await n.sendRequest({recipient:r.targetRole,subject:`Context request: ${o.summary}`,body:this.formatTeamDmBody(o,e.questions),questions:e.questions,metadata:{planId:e.id,gapIds:e.gapIds,method:"team_dm"}});return s?this.responseToResult(e.id,s,i):(this.trackPendingRequest(e.id,i),this.planner.updatePlanStatus(e.id,"in_progress"),null)}async executeDocumentRequest(e){let r=e.method,i=this.config.channels.slack??this.config.channels.email;if(!i)return console.warn("[collection/internal] No channel configured for document request"),null;let n=await this.buildGapContext(e.gapIds),o=await i.sendRequest({recipient:r.targetPerson,subject:`Document request: ${r.topic}`,body:this.formatDocumentRequestBody(r.topic,n),questions:[`Can you share documentation about: ${r.topic}?`,...e.questions],metadata:{planId:e.id,gapIds:e.gapIds,method:"document_request",topic:r.topic}});return o?this.responseToResult(e.id,o,"document_request"):(this.trackPendingRequest(e.id,"document_request"),this.planner.updatePlanStatus(e.id,"in_progress"),null)}async executeTribalKnowledgeMining(e){let r=e.method,i=this.config.channels.slack??this.config.channels.email;if(!i)return console.warn("[collection/internal] No channel configured for tribal knowledge mining"),null;let n=await this.buildGapContext(e.gapIds),o=await i.sendRequest({recipient:r.targetTeam,subject:`Knowledge request: ${r.topic}`,body:this.formatTribalKnowledgeBody(r.topic,r.targetTeam,n,e.questions),questions:e.questions,metadata:{planId:e.id,gapIds:e.gapIds,method:"tribal_knowledge_mining",targetTeam:r.targetTeam,topic:r.topic}});return o?this.responseToResult(e.id,o,"tribal_knowledge_mining"):(this.trackPendingRequest(e.id,"tribal_knowledge_mining"),this.planner.updatePlanStatus(e.id,"in_progress"),null)}async handleResponse(e,r){let i=this.pendingRequests.get(e);return i?(this.pendingRequests.delete(e),this.responseToResult(e,r,i.channel)):null}checkTimeouts(){let e=Date.now(),r=[];for(let[i,n]of this.pendingRequests)e-n.sentAt>this.config.responseTimeoutMs&&(r.push(i),this.pendingRequests.delete(i),this.planner.updatePlanStatus(i,"failed"));return r}trackPendingRequest(e,r){this.pendingRequests.set(e,{planId:e,sentAt:Date.now(),channel:r})}responseToResult(e,r,i){let n=[];n.push({source:B$(i,r.responderId),content:r.rawText,metadata:{responderId:r.responderId,responderName:r.responderName,respondedAt:r.respondedAt,channel:i}});for(let[o,s]of Object.entries(r.answers))n.push({source:B$(i,r.responderId),content:s,metadata:{question:o,responderId:r.responderId,channel:i,type:"structured_answer"}});return{planId:e,rawData:n,structuredOutput:null,completedAt:new Date().toISOString()}}async buildGapContext(e){let r=[];for(let i of e){let n=await Ze(i,{layers:["permanent","draft"]});if(n){let o=n.metadata?.description??"Unknown context gap";r.push(o)}}return{summary:r.length>0?r[0]:"Context gap requiring team input",descriptions:r}}formatTeamDmBody(e,r){let i=["Hi! We've identified a gap in our product context that your expertise could help fill.","",`Context: ${e.summary}`];if(e.descriptions.length>1){i.push("","Related gaps:");for(let n of e.descriptions)i.push(` - ${n}`)}i.push("","Questions:");for(let n of r)i.push(` - ${n}`);return i.join(`
|
|
264
264
|
`)}formatDocumentRequestBody(e,r){return[`We're looking for documentation or artifacts related to: ${e}`,"",`This will help fill a context gap: ${r.summary}`,"","Any of the following would be helpful:"," - Design docs, RFCs, or decision records"," - Meeting notes or discussion summaries"," - Data analysis or research findings"," - Links to relevant internal wiki pages"].join(`
|
|
265
265
|
`)}formatTribalKnowledgeBody(e,r,i,n){let o=[`Hi ${r} team! We're trying to capture institutional knowledge about: ${e}`,"",`Background: ${i.summary}`,"","We'd love to hear the team's perspective on:"];for(let s of n)o.push(` - ${s}`);return o.push("","Any context \u2014 even informal, partial, or anecdotal \u2014 is valuable."),o.join(`
|
|
266
|
-
`)}}});import{randomUUID as A3}from"node:crypto";function sb(){return{system:"collection-pipeline",reference:"structuring",agentId:null,reliability:.75}}function L3(t){return{decision:"Decision",feature:"Feature",metric:"Metric",signal:"CustomerSignal",customer_signal:"CustomerSignal",feedback:"CustomerSignal",code:"CodeArtifact",code_artifact:"CodeArtifact",discussion:"Discussion",person:"Person",gap:"Gap",study:"Study"}[t.toLowerCase()]??"CustomerSignal"}var C3,qs,ab=m(()=>{"use strict";Vr();Ne();C3={minNodeConfidence:.5,defaultLayer:"draft"},qs=class{constructor(e,r,i){this.extractor=e;this.eventBus=r;this.config={...C3,...i}}config;async process(e,r){let i=[],n=[],o=[],s=await this.extractor.extract(e.rawData),a=new Map;for(let u=0;u<s.entities.length;u++){let l=s.entities[u];if(l.confidence<this.config.minNodeConfidence)continue;let d=e.rawData[l.sourceIndex],p=await this.createEntityNode(l,d);p&&(i.push(p),a.set(u,p))}for(let u of s.relations){let l=a.get(u.fromEntityIndex),d=a.get(u.toEntityIndex);if(!l||!d)continue;let p=await this.createRelationEdge(u,l,d);p&&n.push(p)}for(let u of r)for(let l of i){let d=await Ir({type:"addresses",sourceId:l,targetId:u,confidence:.8,weight:1,evidence:`Created from collection plan ${e.planId}`,source:sb()});d&&n.push(d.id)}for(let u of r)await this.checkGapResolution(u,i.length)&&(o.push(u),await this.resolveGap(u));let c={createdNodeIds:i,createdEdgeIds:n,gapsResolved:o,confidence:this.computeOverallConfidence(s)};return e.structuredOutput=c,c}async createEntityNode(e,r){let i=await qr({type:L3(e.type),layer:this.config.defaultLayer,confidence:e.confidence,source:r.source,properties:e.properties});return i?(await this.eventBus.publisher.publish({eventId:A3(),timestamp:new Date().toISOString(),source:sb(),subject:te.graph.nodeCreated,nodeId:i.id,nodeType:i.type,layer:this.config.defaultLayer,branchId:null}),i.id):null}async createRelationEdge(e,r,i){return(await Ir({type:e.edgeType,sourceId:r,targetId:i,confidence:e.confidence,weight:1,evidence:e.evidence,source:sb()}))?.id??null}async checkGapResolution(e,r){let i=await Ze(e,{layers:["permanent","draft"]});if(!i)return!1;let n=i.metadata?.gapType??"missing_data",s=((await wr({targetId:e,types:["addresses"]}))?.length??0)+r,c={missing_data:3,stale:1,contradiction:2,untested_assumption:5,missing_validation:3,coverage_gap:2}[n]??3;return s>=c}async resolveGap(e){await lr(e,{metadata:{status:"resolved",resolvedAt:new Date().toISOString(),resolvedBy:"collection-pipeline"}})}computeOverallConfidence(e){if(e.entities.length===0)return 0;let r=e.entities.reduce((n,o)=>n+o.confidence,0)/e.entities.length,i=e.relations.length>0?e.relations.reduce((n,o)=>n+o.confidence,0)/e.relations.length:0;return e.relations.length>0?.6*r+.4*i:r}}});async function j3(t,e){let r=await hi(),i=new Zd(r,t,e);return await i.start(),i}var Zd,z$=m(()=>{"use strict";Vr();nb();ib();ob();ab();nb();ib();ob();ab();Zd=class{constructor(e,r,i){this.eventBus=e;this.planner=new Gs(e),this.external=new Bs(r.mcpClient,this.planner,e,i?.external),this.internal=new zs(this.planner,e,{...i?.internal,channels:r.channels??i?.internal?.channels??{}}),this.structuring=new qs(r.entityExtractor,e,i?.structuring)}planner;external;internal;structuring;async start(){console.log("[collection] Starting collection service..."),await this.planner.start(),console.log("[collection] Planner listening for gap events"),console.log("[collection] Collection service ready")}async executePlan(e){let r=this.planner.getPlan(e);if(!r||!await this.planner.approvePlan(e))return null;let n=null;switch(r.method.type){case"customer_interview":n=await this.external.execute(r),n||this.external.startPolling(e);break;case"team_dm":case"document_request":case"tribal_knowledge_mining":n=await this.internal.execute(r);break;case"micro_survey":case"market_signal":console.warn(`[collection] Method "${r.method.type}" not yet implemented`);break}return n&&(await this.structuring.process(n,r.gapIds),this.planner.updatePlanStatus(e,"completed")),n}async processAsyncResult(e,r){let i=this.planner.getPlan(e);i&&(await this.structuring.process(r,i.gapIds),this.planner.updatePlanStatus(e,"completed"))}async stop(){console.log("[collection] Stopping collection service..."),this.external.stopAll(),await this.eventBus.close(),console.log("[collection] Stopped.")}}});var Jd={};yt(Jd,{BootstrapRunner:()=>Us,CollectionPlanner:()=>Gs,CollectionService:()=>Zd,ConnectorRegistry:()=>As,DEFAULT_INGEST_CONFIG:()=>tb,ExternalCollector:()=>Bs,GapEngine:()=>Hd,GapQueue:()=>Ds,GitHubConnector:()=>Ls,GitMiner:()=>js,GraphClient:()=>$s,InternalCollector:()=>zs,LocalGitConnector:()=>Cs,ProactiveScanner:()=>Rs,ReactiveDetector:()=>Ps,StagingPipeline:()=>Fs,StructuringPipeline:()=>qs,createCollectionService:()=>j3,createIngestService:()=>$3,startGapEngine:()=>x3});var Yd=m(()=>{"use strict";$$();L$();z$()});import{randomUUID as F3}from"node:crypto";function M3(){return{system:"metabolism-service",reference:"gating",agentId:null,reliability:1}}var U3,Vs,cb=m(()=>{"use strict";Vr();Ne();Ne();Ne();U3={minConfidence:.7,maxStagingAgeDays:60,discardConfidenceThreshold:.3},Vs=class{constructor(e,r){this.eventBus=e;this.config={...U3,...r}}config;async start(){this.eventBus.subscriber.subscribe(te.graph.nodeCreated,async e=>{e.layer==="draft"&&await this.evaluateNode(e.nodeId)},{group:"metabolism-gating"})}async evaluateNode(e){let r=await Ze(e,{layers:["draft"]});if(!r)return{nodeId:e,decision:"discard",reason:"Node not found or not in draft layer"};if(!await Kd(r.type))return this.makeResult(e,"discard","Unknown node type \u2014 no schema registered");if(r.confidence<this.config.minConfidence){let c=(Date.now()-new Date(r.createdAt).getTime())/864e5;return c>this.config.maxStagingAgeDays&&r.confidence<this.config.discardConfidenceThreshold?(await fi(e),this.makeResult(e,"discard",`Stale draft: ${Math.round(c)} days old, confidence ${r.confidence.toFixed(2)}`)):this.makeResult(e,"hold",`Confidence ${r.confidence.toFixed(2)} below threshold ${this.config.minConfidence}`)}let o=(await mi({type:r.type,layers:["permanent"],limit:5})).find(c=>{let u=c.metadata,l=r.metadata;return u?.title===l?.title||u?.name===l?.name});if(o)return this.makeResult(e,"hold",`Potential duplicate of node ${o.id}`);let s=await wr({nodeId:e,types:["contradicts"]});if(s.length>0)return this.makeResult(e,"hold",`Contradicts ${s.length} existing node(s) \u2014 needs resolution`);await ho(e,"permanent");let a=this.makeResult(e,"promote","Passed all gating criteria");return await this.eventBus.publisher.publish({eventId:F3(),timestamp:new Date().toISOString(),source:M3(),subject:te.metabolism.gate,nodeIds:[e],action:"gate_accepted"}),a}async evaluateAll(){let e=await mi({layers:["draft"],limit:500}),r=[];for(let i of e){let n=await this.evaluateNode(i.id);r.push(n)}return r}makeResult(e,r,i){return{nodeId:e,decision:r,reason:i}}}});import{randomUUID as q$}from"node:crypto";function V$(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var G3,Qs,ub=m(()=>{"use strict";Vr();Ne();Ne();Ne();G3={intervalMs:360*60*1e3,batchSize:200,staleEventThreshold:Sr.aging},Qs=class{constructor(e,r){this.eventBus=e;this.config={...G3,...r}}config;timer=null;start(){this.runDecayCycle().catch(e=>console.error("[metabolism/decay] Error in initial cycle:",e)),this.timer=setInterval(()=>{this.runDecayCycle().catch(e=>console.error("[metabolism/decay] Error in decay cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async runDecayCycle(){let e=new Date,r=0,i=0,n=0,o=0;for(;;){let s=await mi({layers:["permanent"],limit:this.config.batchSize,offset:o});if(s.length===0)break;for(let a of s){let c=await Fc(a.id),u={nodeType:a.type,lastUpdated:new Date(a.updatedAt),corroborationCount:c,sourceReliability:a.source.reliability,now:e},l=pi(u),d=Ud(a.freshness),p=Ud(l);Math.abs(l-a.freshness)>.01&&(await lr(a.id,{metadata:{_freshness_computed:l}}),i++,d!=="stale"&&d!=="archival_candidate"&&(p==="stale"||p==="archival_candidate")&&(n++,await this.eventBus.publisher.publish({eventId:q$(),timestamp:e.toISOString(),source:V$("decay"),subject:te.gap.stale,gapNodeId:a.id,severity:p==="archival_candidate"?"high":"medium",affectedNodeIds:[a.id],description:`Node freshness decayed to ${l.toFixed(2)} (${p}): ${a.type} "${a.metadata?.title??a.metadata?.name??a.id}"`}))),r++}if(o+=s.length,s.length<this.config.batchSize)break}return i>0&&await this.eventBus.publisher.publish({eventId:q$(),timestamp:e.toISOString(),source:V$("decay"),subject:te.metabolism.decay,nodeIds:[],action:"decay"}),{processed:r,freshnessUpdated:i,staleDetected:n}}}});import{randomUUID as lb}from"node:crypto";function db(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var B3,Ks,pb=m(()=>{"use strict";Vr();Ne();Ne();Ne();B3={archivalThreshold:Sr.archivalCandidate,gracePeriodDays:ky,batchSize:100,intervalMs:1440*60*1e3},Ks=class{constructor(e,r){this.eventBus=e;this.config={...B3,...r}}config;timer=null;start(){setTimeout(()=>{this.runPruningCycle().catch(e=>console.error("[metabolism/pruning] Error in initial cycle:",e))},6e4),this.timer=setInterval(()=>{this.runPruningCycle().catch(e=>console.error("[metabolism/pruning] Error in pruning cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async runPruningCycle(){let e=0,r=0,i=0;for(;;){let n=await mi({layers:["permanent"],maxFreshness:this.config.archivalThreshold,limit:this.config.batchSize,offset:i});if(n.length===0)break;for(let o of n){if((Date.now()-new Date(o.updatedAt).getTime())/864e5<this.config.gracePeriodDays)continue;let a=await wr({targetId:o.id,limit:10});if(await this.hasActiveDependencies(o.id,a.map(u=>u.fromId))){r++;continue}await fi(o.id),e++,await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.graph.nodeArchived,nodeId:o.id,nodeType:o.type,reason:"freshness_decay"})}if(i+=n.length,n.length<this.config.batchSize)break}return e>0&&await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.metabolism.prune,nodeIds:[],action:"prune"}),{archived:e,skippedDependencies:r}}async pruneSubgraph(e,r){let i=await yn({startId:e,direction:"both",maxDepth:5,layers:["permanent"]}),n=0,o=0;for(let s of i.nodes){let a=await wr({targetId:s.id,limit:20}),c=new Set(i.nodes.map(l=>l.id));if(a.filter(l=>!c.has(l.fromId)).length>0){o++;continue}await fi(s.id),n++,await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.graph.nodeArchived,nodeId:s.id,nodeType:s.type,reason:"manual"})}return{archived:n,skippedDependencies:o}}async hasActiveDependencies(e,r){for(let i of r){let n=await Ze(i,{layers:["permanent"]});if(n&&n.freshness>this.config.archivalThreshold)return!0}return!1}}});import{randomUUID as z3}from"node:crypto";function fb(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var q3,Hs,mb=m(()=>{"use strict";Vr();Ne();q3={recencyWeight:.4,corroborationWeight:.3,sourceReliabilityWeight:.2,specificityWeight:.1,autoResolveThreshold:.2},Hs=class{constructor(e,r){this.eventBus=e;this.config={...q3,...r}}config;async start(){this.eventBus.subscriber.subscribe(te.graph.edgeCreated,async e=>{e.edgeType==="contradicts"&&await this.resolveContradiction(e.fromNodeId,e.toNodeId)},{group:"metabolism-contradiction"})}async resolveContradiction(e,r){let i=await Ze(e),n=await Ze(r);if(!i||!n)return{nodeA:e,nodeB:r,strategy:"escalate",winnerId:null,reason:"One or both nodes not found"};let o=await this.scoreNode(i),s=await this.scoreNode(n),a=Math.abs(o-s),c,u=null,l;if(a>=this.config.autoResolveThreshold){c="supersede",o>s?(u=i.id,l=`Node A scores ${o.toFixed(2)} vs Node B ${s.toFixed(2)}: newer/better-evidenced`):(u=n.id,l=`Node B scores ${s.toFixed(2)} vs Node A ${o.toFixed(2)}: newer/better-evidenced`);let d=u===i.id?n.id:i.id;await lr(d,{metadata:{superseded_by:u}}),await Ir({type:"supersedes",sourceId:u,targetId:d,confidence:.8,weight:1,evidence:l,source:fb("contradiction-resolver")})}else this.couldCoexist(i,n)?(c="coexist",l=`Score difference ${a.toFixed(2)} below threshold and nodes cover different contexts`):(c="escalate",l=`Score difference ${a.toFixed(2)} below auto-resolve threshold ${this.config.autoResolveThreshold}`,await qr({type:"Gap",layer:"permanent",confidence:.9,source:fb("contradiction-resolver"),properties:{gapType:"contradiction",severity:"high",status:"detected",description:`Unresolved contradiction between ${i.type} nodes: "${i.metadata?.title??i.id}" vs "${n.metadata?.title??n.id}"`,detectedBy:"metabolism-service",resolutionPath:"Run a study or collect additional evidence to resolve",impactDescription:l}}),await this.eventBus.publisher.publish({eventId:z3(),timestamp:new Date().toISOString(),source:fb("contradiction-resolver"),subject:te.gap.semantic,gapNodeId:e,severity:"high",affectedNodeIds:[e,r],description:`Contradiction: ${l}`}));return{nodeA:e,nodeB:r,strategy:c,winnerId:u,reason:l}}async scoreNode(e){let n=(Date.now()-new Date(e.updatedAt).getTime())/(1e3*60*60*24),o=Math.exp(-.01*n),s=await Fc(e.id),a=Math.min(1,s/3),c=e.source.reliability,u=Object.keys(e.metadata).filter(d=>!d.startsWith("_")).length,l=Math.min(1,u/10);return this.config.recencyWeight*o+this.config.corroborationWeight*a+this.config.sourceReliabilityWeight*c+this.config.specificityWeight*l}couldCoexist(e,r){let i=e.metadata?.customerSegment,n=r.metadata?.customerSegment;if(i&&n&&i!==n)return!0;let o=e.metadata?.channel,s=r.metadata?.channel;return!!(o&&s&&o!==s)}}});import{randomUUID as Q$}from"node:crypto";function K$(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var V3,Ws,hb=m(()=>{"use strict";Vr();Ne();V3={intervalMs:300*1e3},Ws=class{constructor(e,r){this.eventBus=e;this.config={...V3,...r}}config;timer=null;start(){this.timer=setInterval(()=>{this.expireHotNodes().catch(e=>console.error("[metabolism/hot-layer] Error in TTL cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async expireHotNodes(){let e=await ae("SELECT * FROM expire_hot_nodes()"),r=0,i=0;for(let n of e.rows)n.action==="promoted_to_draft"?(r++,await this.eventBus.publisher.publish({eventId:Q$(),timestamp:new Date().toISOString(),source:K$("hot-layer"),subject:te.graph.nodePromoted,nodeId:n.node_id,nodeType:"unknown",fromLayer:"hot",toLayer:"draft"})):n.action==="deleted"&&(i++,await this.eventBus.publisher.publish({eventId:Q$(),timestamp:new Date().toISOString(),source:K$("hot-layer"),subject:te.graph.nodeArchived,nodeId:n.node_id,nodeType:"unknown",reason:"freshness_decay"}));return{promoted:r,deleted:i}}}});var H$={};yt(H$,{ContradictionResolver:()=>Hs,DecayEngine:()=>Qs,GatingService:()=>Vs,HotLayerService:()=>Ws,MetabolismService:()=>Xd,PruningService:()=>Ks,createMetabolismService:()=>Q3});async function Q3(t){let e=await hi(),r=new Xd(e,t);return await r.start(),r}var Xd,W$=m(()=>{"use strict";Vr();cb();ub();pb();mb();hb();cb();ub();pb();mb();hb();Xd=class{constructor(e,r){this.eventBus=e;this.gating=new Vs(e,r?.gating),this.decay=new Qs(e,r?.decay),this.pruning=new Ks(e,r?.pruning),this.contradictions=new Hs(e,r?.contradiction),this.hotLayer=new Ws(e,r?.hotLayer)}gating;decay;pruning;contradictions;hotLayer;async start(){console.log("[metabolism] Starting metabolism service..."),await this.gating.start(),await this.contradictions.start(),this.decay.start(),this.pruning.start(),this.hotLayer.start(),console.log("[metabolism] All subsystems running:"),console.log(" - Gating: listening for draft node events"),console.log(" - Contradiction resolver: listening for contradicts edges"),console.log(" - Decay engine: scheduled freshness recomputation"),console.log(" - Pruning: scheduled archival of stale nodes"),console.log(" - Hot layer: scheduled TTL expiry")}async stop(){console.log("[metabolism] Stopping metabolism service..."),this.decay.stop(),this.pruning.stop(),this.hotLayer.stop(),await this.eventBus.close(),console.log("[metabolism] Stopped.")}}});async function Z$(t){let e=process.env.VOYAGE_API_KEY;if(!e)return null;try{let r=await fetch("https://api.voyageai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({input:[t],model:"voyage-3-lite"})});return r.ok?(await r.json()).data?.[0]?.embedding??null:null}catch{return null}}var ep,J$=m(()=>{"use strict";Ne();Ne();Ne();Ne();Ne();ep=class{async createNode(e){let r=[e.metadata?.title,e.metadata?.description].filter(Boolean).join(". "),i=r?await Z$(r):null,n={type:e.type,layer:e.layer,source:e.source,tags:e.tags,branchId:e.branchId,metadata:e.metadata,properties:{...e},embedding:i??void 0};return delete n.properties.type,delete n.properties.layer,delete n.properties.source,delete n.properties.tags,delete n.properties.branchId,delete n.properties.metadata,qr(n)}async getNode(e){return Ze(e)}async updateNode(e,r){let i=await lr(e,{properties:r,confidence:r.metadata?.confidence,tags:r.tags});if(!i)throw new Error(`Node ${e} not found`);return i}async deleteNode(e){await fi(e)}async promoteNode(e,r,i){let n=await ho(e,i);if(!n)throw new Error(`Node ${e} not found`);return n}async createEdge(e){let r={type:e.type,sourceId:e.fromId,targetId:e.toId,confidence:e.confidence,weight:e.weight,evidence:e.evidence??void 0,source:e.source,branchId:e.branchId};return Ir(r)}async getEdge(e){return Vd(e)}async updateEdge(e,r){let i=await $y(e,{confidence:r.confidence,weight:r.weight,evidence:r.evidence??void 0});if(!i)throw new Error(`Edge ${e} not found`);return i}async deleteEdge(e){await Py(e)}async search(e,r){let i=await Z$(e);if(i)return(await Ry({embedding:i,nodeTypes:r?.nodeTypes,layers:r?.layers,limit:r?.limit??20})).map(d=>d.node);let n=["superseded_by IS NULL"],o=[],s=1;n.push(`(properties::text ILIKE $${s} OR metadata::text ILIKE $${s} OR $${s} = ANY(tags))`),o.push(`%${e}%`),s++,r?.nodeTypes?.length&&(n.push(`type = ANY($${s++})`),o.push(r.nodeTypes)),r?.layers?.length?(n.push(`layer = ANY($${s++})`),o.push(r.layers)):(n.push(`layer = ANY($${s++})`),o.push(["permanent","draft","hot"])),r?.minFreshness!==void 0&&(n.push(`freshness >= $${s++}`),o.push(r.minFreshness));let a=r?.limit??20;o.push(a);let c=`SELECT * FROM nodes WHERE ${n.join(" AND ")} ORDER BY freshness DESC LIMIT $${s}`;return(await ae(c,o)).rows}async traverse(e,r){return(await yn({startId:e,direction:{outgoing:"outbound",incoming:"inbound",both:"both"}[r.direction??"both"],edgeTypes:r.edgeTypes,maxDepth:r.maxDepth??3,minFreshness:r.minConfidence,limit:r.limit??50})).nodes}async getNeighbors(e,r){let i={},n=r??"both";n==="outgoing"?i.sourceId=e:n==="incoming"?i.targetId=e:i.nodeId=e;let o=await wr(i),s=[];for(let a of o){let c=a.fromId===e?a.toId:a.fromId,u=await Ze(c);u&&s.push({node:u,edge:a})}return s}async getGaps(e){let r=["type = 'Gap'","superseded_by IS NULL"],i=[],n=1;e?.status?.length&&(r.push(`properties->>'status' = ANY($${n++})`),i.push(e.status)),e?.severity?.length&&(r.push(`properties->>'severity' = ANY($${n++})`),i.push(e.severity));let o=e?.limit??50;i.push(o);let s=`SELECT * FROM nodes WHERE ${r.join(" AND ")} ORDER BY freshness DESC LIMIT $${n}`;return(await ae(s,i)).rows}async createBranch(e,r){return Ay({name:e,purpose:r,createdBy:"api"})}async getBranch(e){return Cy(e)}async listBranches(){return Ly()}async mergeBranch(e){return jy(e)}async deleteBranch(e){await Fy(e,"Deleted via API")}}});var Y$={};yt(Y$,{GraphServiceAdapter:()=>ep});var X$=m(()=>{"use strict";J$()});function _(t,e,r){function i(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=s.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in a||(a[p]=u[p].bind(a))}}let n=r?.Parent??Object;class o extends n{}Object.defineProperty(o,"name",{value:t});function s(a){var c;let u=r?.Parent?new o:this;i(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}function st(t){return t&&Object.assign(zc,t),zc}var gb,tp,Qr,yi,zc,Zs=m(()=>{gb=Object.freeze({status:"aborted"});tp=Symbol("zod_brand"),Qr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},yi=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},zc={}});var C={};yt(C,{BIGINT_FORMAT_RANGES:()=>wb,Class:()=>bb,NUMBER_FORMAT_RANGES:()=>Ib,aborted:()=>Ti,allowsEval:()=>Tb,assert:()=>J3,assertEqual:()=>K3,assertIs:()=>W3,assertNever:()=>Z3,assertNotEqual:()=>H3,assignProp:()=>vi,base64ToUint8Array:()=>tP,base64urlToUint8Array:()=>mQ,cached:()=>Ys,captureStackTrace:()=>np,cleanEnum:()=>fQ,cleanRegex:()=>Qc,clone:()=>Bt,cloneDef:()=>X3,createTransparentProxy:()=>oQ,defineLazy:()=>he,esc:()=>rp,escapeRegex:()=>Nr,extend:()=>cQ,finalizeIssue:()=>Yt,floatSafeRemainder:()=>vb,getElementAtPath:()=>eQ,getEnumValues:()=>Vc,getLengthableOrigin:()=>Wc,getParsedType:()=>iQ,getSizableOrigin:()=>Hc,hexToUint8Array:()=>gQ,isObject:()=>go,isPlainObject:()=>_i,issue:()=>Xs,joinValues:()=>S,jsonStringifyReplacer:()=>Js,merge:()=>lQ,mergeDefs:()=>Gn,normalizeParams:()=>L,nullish:()=>bi,numKeys:()=>nQ,objectClone:()=>Y3,omit:()=>aQ,optionalKeys:()=>Sb,parsedType:()=>A,partial:()=>dQ,pick:()=>sQ,prefixIssues:()=>dr,primitiveTypes:()=>xb,promiseAllObject:()=>tQ,propertyKeyTypes:()=>Kc,randomString:()=>rQ,required:()=>pQ,safeExtend:()=>uQ,shallowClone:()=>Eb,slugify:()=>_b,stringifyPrimitive:()=>D,uint8ArrayToBase64:()=>rP,uint8ArrayToBase64url:()=>hQ,uint8ArrayToHex:()=>yQ,unwrapMessage:()=>qc});function K3(t){return t}function H3(t){return t}function W3(t){}function Z3(t){throw new Error("Unexpected value in exhaustive check")}function J3(t){}function Vc(t){let e=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,n])=>e.indexOf(+i)===-1).map(([i,n])=>n)}function S(t,e="|"){return t.map(r=>D(r)).join(e)}function Js(t,e){return typeof e=="bigint"?e.toString():e}function Ys(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function bi(t){return t==null}function Qc(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function vb(t,e){let r=(t.toString().split(".")[1]||"").length,i=e.toString(),n=(i.split(".")[1]||"").length;if(n===0&&/\d?e-\d?/.test(i)){let c=i.match(/\d?e-(\d?)/);c?.[1]&&(n=Number.parseInt(c[1]))}let o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function he(t,e,r){let i;Object.defineProperty(t,e,{get(){if(i!==eP)return i===void 0&&(i=eP,i=r()),i},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Y3(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function vi(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Gn(...t){let e={};for(let r of t){let i=Object.getOwnPropertyDescriptors(r);Object.assign(e,i)}return Object.defineProperties({},e)}function X3(t){return Gn(t._zod.def)}function eQ(t,e){return e?e.reduce((r,i)=>r?.[i],t):t}function tQ(t){let e=Object.keys(t),r=e.map(i=>t[i]);return Promise.all(r).then(i=>{let n={};for(let o=0;o<e.length;o++)n[e[o]]=i[o];return n})}function rQ(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let i=0;i<t;i++)r+=e[Math.floor(Math.random()*e.length)];return r}function rp(t){return JSON.stringify(t)}function _b(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function go(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _i(t){if(go(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(go(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Eb(t){return _i(t)?{...t}:Array.isArray(t)?[...t]:t}function nQ(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Nr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,e,r){let i=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(i._zod.parent=t),i}function L(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function oQ(t){let e;return new Proxy({},{get(r,i,n){return e??(e=t()),Reflect.get(e,i,n)},set(r,i,n,o){return e??(e=t()),Reflect.set(e,i,n,o)},has(r,i){return e??(e=t()),Reflect.has(e,i)},deleteProperty(r,i){return e??(e=t()),Reflect.deleteProperty(e,i)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,i){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(r,i,n){return e??(e=t()),Reflect.defineProperty(e,i,n)}})}function D(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Sb(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function sQ(t,e){let r=t._zod.def,i=r.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Gn(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return vi(this,"shape",s),s},checks:[]});return Bt(t,o)}function aQ(t,e){let r=t._zod.def,i=r.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Gn(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return vi(this,"shape",s),s},checks:[]});return Bt(t,o)}function cQ(t,e){if(!_i(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let o=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Gn(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return vi(this,"shape",o),o}});return Bt(t,n)}function uQ(t,e){if(!_i(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Gn(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return vi(this,"shape",i),i}});return Bt(t,r)}function lQ(t,e){let r=Gn(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e._zod.def.shape};return vi(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:[]});return Bt(t,r)}function dQ(t,e,r){let n=e._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Gn(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return vi(this,"shape",c),c},checks:[]});return Bt(e,s)}function pQ(t,e,r){let i=Gn(e._zod.def,{get shape(){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return vi(this,"shape",o),o}});return Bt(e,i)}function Ti(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function dr(t,e){return e.map(r=>{var i;return(i=r).path??(i.path=[]),r.path.unshift(t),r})}function qc(t){return typeof t=="string"?t:t?.message}function Yt(t,e,r){let i={...t,path:t.path??[]};if(!t.message){let n=qc(t.inst?._zod.def?.error?.(t))??qc(e?.error?.(t))??qc(r.customError?.(t))??qc(r.localeError?.(t))??"Invalid input";i.message=n}return delete i.inst,delete i.continue,e?.reportInput||delete i.input,i}function Hc(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function A(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Xs(...t){let[e,r,i]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:i}:{...e}}function fQ(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function tP(t){let e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r}function rP(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function mQ(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return tP(e+r)}function hQ(t){return rP(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gQ(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)r[i/2]=Number.parseInt(e.slice(i,i+2),16);return r}function yQ(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var eP,np,Tb,iQ,Kc,xb,Ib,wb,bb,Y=m(()=>{eP=Symbol("evaluating");np="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};Tb=Ys(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});iQ=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Kc=new Set(["string","number","symbol"]),xb=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ib={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},wb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};bb=class{constructor(...e){}}});function Jc(t,e=r=>r.message){let r={},i=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:r}}function Yc(t,e=r=>r.message){let r={_errors:[]},i=n=>{for(let o of n.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)r._errors.push(e(o));else{let s=r,a=0;for(;a<o.path.length;){let c=o.path[a];a===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(e(o))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return i(t),r}function Nb(t,e=r=>r.message){let r={errors:[]},i=(n,o=[])=>{var s,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>i({issues:u},c.path));else if(c.code==="invalid_key")i({issues:c.issues},c.path);else if(c.code==="invalid_element")i({issues:c.issues},c.path);else{let u=[...o,...c.path];if(u.length===0){r.errors.push(e(c));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(l.properties??(l.properties={}),(s=l.properties)[p]??(s[p]={errors:[]}),l=l.properties[p]):(l.items??(l.items=[]),(a=l.items)[p]??(a[p]={errors:[]}),l=l.items[p]),f&&l.errors.push(e(c)),d++}}};return i(t),r}function iP(t){let e=[],r=t.map(i=>typeof i=="object"?i.key:i);for(let i of r)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function Ob(t){let e=[],r=[...t.issues].sort((i,n)=>(i.path??[]).length-(n.path??[]).length);for(let i of r)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${iP(i.path)}`);return e.join(`
|
|
266
|
+
`)}}});import{randomUUID as A3}from"node:crypto";function sb(){return{system:"collection-pipeline",reference:"structuring",agentId:null,reliability:.75}}function L3(t){return{decision:"Decision",feature:"Feature",metric:"Metric",signal:"CustomerSignal",customer_signal:"CustomerSignal",feedback:"CustomerSignal",code:"CodeArtifact",code_artifact:"CodeArtifact",discussion:"Discussion",person:"Person",gap:"Gap",study:"Study"}[t.toLowerCase()]??"CustomerSignal"}var C3,qs,ab=m(()=>{"use strict";Vr();Ne();C3={minNodeConfidence:.5,defaultLayer:"draft"},qs=class{constructor(e,r,i){this.extractor=e;this.eventBus=r;this.config={...C3,...i}}config;async process(e,r){let i=[],n=[],o=[],s=await this.extractor.extract(e.rawData),a=new Map;for(let u=0;u<s.entities.length;u++){let l=s.entities[u];if(l.confidence<this.config.minNodeConfidence)continue;let d=e.rawData[l.sourceIndex],p=await this.createEntityNode(l,d);p&&(i.push(p),a.set(u,p))}for(let u of s.relations){let l=a.get(u.fromEntityIndex),d=a.get(u.toEntityIndex);if(!l||!d)continue;let p=await this.createRelationEdge(u,l,d);p&&n.push(p)}for(let u of r)for(let l of i){let d=await Ir({type:"addresses",sourceId:l,targetId:u,confidence:.8,weight:1,evidence:`Created from collection plan ${e.planId}`,source:sb()});d&&n.push(d.id)}for(let u of r)await this.checkGapResolution(u,i.length)&&(o.push(u),await this.resolveGap(u));let c={createdNodeIds:i,createdEdgeIds:n,gapsResolved:o,confidence:this.computeOverallConfidence(s)};return e.structuredOutput=c,c}async createEntityNode(e,r){let i=await qr({type:L3(e.type),layer:this.config.defaultLayer,confidence:e.confidence,source:r.source,properties:e.properties});return i?(await this.eventBus.publisher.publish({eventId:A3(),timestamp:new Date().toISOString(),source:sb(),subject:te.graph.nodeCreated,nodeId:i.id,nodeType:i.type,layer:this.config.defaultLayer,branchId:null}),i.id):null}async createRelationEdge(e,r,i){return(await Ir({type:e.edgeType,sourceId:r,targetId:i,confidence:e.confidence,weight:1,evidence:e.evidence,source:sb()}))?.id??null}async checkGapResolution(e,r){let i=await Ze(e,{layers:["permanent","draft"]});if(!i)return!1;let n=i.metadata?.gapType??"missing_data",s=((await wr({targetId:e,types:["addresses"]}))?.length??0)+r,c={missing_data:3,stale:1,contradiction:2,untested_assumption:5,missing_validation:3,coverage_gap:2}[n]??3;return s>=c}async resolveGap(e){await lr(e,{metadata:{status:"resolved",resolvedAt:new Date().toISOString(),resolvedBy:"collection-pipeline"}})}computeOverallConfidence(e){if(e.entities.length===0)return 0;let r=e.entities.reduce((n,o)=>n+o.confidence,0)/e.entities.length,i=e.relations.length>0?e.relations.reduce((n,o)=>n+o.confidence,0)/e.relations.length:0;return e.relations.length>0?.6*r+.4*i:r}}});async function j3(t,e){let r=await hi(),i=new Zd(r,t,e);return await i.start(),i}var Zd,z$=m(()=>{"use strict";Vr();nb();ib();ob();ab();nb();ib();ob();ab();Zd=class{constructor(e,r,i){this.eventBus=e;this.planner=new Gs(e),this.external=new Bs(r.mcpClient,this.planner,e,i?.external),this.internal=new zs(this.planner,e,{...i?.internal,channels:r.channels??i?.internal?.channels??{}}),this.structuring=new qs(r.entityExtractor,e,i?.structuring)}planner;external;internal;structuring;async start(){console.log("[collection] Starting collection service..."),await this.planner.start(),console.log("[collection] Planner listening for gap events"),console.log("[collection] Collection service ready")}async executePlan(e){let r=this.planner.getPlan(e);if(!r||!await this.planner.approvePlan(e))return null;let n=null;switch(r.method.type){case"customer_interview":n=await this.external.execute(r),n||this.external.startPolling(e);break;case"team_dm":case"document_request":case"tribal_knowledge_mining":n=await this.internal.execute(r);break;case"micro_survey":case"market_signal":console.warn(`[collection] Method "${r.method.type}" not yet implemented`);break}return n&&(await this.structuring.process(n,r.gapIds),this.planner.updatePlanStatus(e,"completed")),n}async processAsyncResult(e,r){let i=this.planner.getPlan(e);i&&(await this.structuring.process(r,i.gapIds),this.planner.updatePlanStatus(e,"completed"))}async stop(){console.log("[collection] Stopping collection service..."),this.external.stopAll(),await this.eventBus.close(),console.log("[collection] Stopped.")}}});var Jd={};yt(Jd,{BootstrapRunner:()=>Us,CollectionPlanner:()=>Gs,CollectionService:()=>Zd,ConnectorRegistry:()=>As,DEFAULT_INGEST_CONFIG:()=>tb,ExternalCollector:()=>Bs,GapEngine:()=>Hd,GapQueue:()=>Ds,GitHubConnector:()=>Ls,GitMiner:()=>js,GraphClient:()=>$s,InternalCollector:()=>zs,LocalGitConnector:()=>Cs,ProactiveScanner:()=>Rs,ReactiveDetector:()=>Ps,StagingPipeline:()=>Fs,StructuringPipeline:()=>qs,createCollectionService:()=>j3,createIngestService:()=>$3,startGapEngine:()=>x3});var Yd=m(()=>{"use strict";$$();L$();z$()});import{randomUUID as F3}from"node:crypto";function M3(){return{system:"metabolism-service",reference:"gating",agentId:null,reliability:1}}var U3,Vs,cb=m(()=>{"use strict";Vr();Ne();Ne();Ne();U3={minConfidence:.7,maxStagingAgeDays:60,discardConfidenceThreshold:.3},Vs=class{constructor(e,r){this.eventBus=e;this.config={...U3,...r}}config;async start(){this.eventBus.subscriber.subscribe(te.graph.nodeCreated,async e=>{e.layer==="draft"&&await this.evaluateNode(e.nodeId)},{group:"metabolism-gating"})}async evaluateNode(e){let r=await Ze(e,{layers:["draft"]});if(!r)return{nodeId:e,decision:"discard",reason:"Node not found or not in draft layer"};if(!await Kd(r.type))return this.makeResult(e,"discard","Unknown node type \u2014 no schema registered");if(r.confidence<this.config.minConfidence){let c=(Date.now()-new Date(r.createdAt).getTime())/864e5;return c>this.config.maxStagingAgeDays&&r.confidence<this.config.discardConfidenceThreshold?(await fi(e),this.makeResult(e,"discard",`Stale draft: ${Math.round(c)} days old, confidence ${r.confidence.toFixed(2)}`)):this.makeResult(e,"hold",`Confidence ${r.confidence.toFixed(2)} below threshold ${this.config.minConfidence}`)}let o=(await mi({type:r.type,layers:["permanent"],limit:5})).find(c=>{let u=c.metadata,l=r.metadata;return u?.title===l?.title||u?.name===l?.name});if(o)return this.makeResult(e,"hold",`Potential duplicate of node ${o.id}`);let s=await wr({nodeId:e,types:["contradicts"]});if(s.length>0)return this.makeResult(e,"hold",`Contradicts ${s.length} existing node(s) \u2014 needs resolution`);await ho(e,"permanent");let a=this.makeResult(e,"promote","Passed all gating criteria");return await this.eventBus.publisher.publish({eventId:F3(),timestamp:new Date().toISOString(),source:M3(),subject:te.metabolism.gate,nodeIds:[e],action:"gate_accepted"}),a}async evaluateAll(){let e=await mi({layers:["draft"],limit:500}),r=[];for(let i of e){let n=await this.evaluateNode(i.id);r.push(n)}return r}makeResult(e,r,i){return{nodeId:e,decision:r,reason:i}}}});import{randomUUID as q$}from"node:crypto";function V$(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var G3,Qs,ub=m(()=>{"use strict";Vr();Ne();Ne();Ne();G3={intervalMs:360*60*1e3,batchSize:200,staleEventThreshold:Sr.aging},Qs=class{constructor(e,r){this.eventBus=e;this.config={...G3,...r}}config;timer=null;start(){this.runDecayCycle().catch(e=>console.error("[metabolism/decay] Error in initial cycle:",e)),this.timer=setInterval(()=>{this.runDecayCycle().catch(e=>console.error("[metabolism/decay] Error in decay cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async runDecayCycle(){let e=new Date,r=0,i=0,n=0,o=0;for(;;){let s=await mi({layers:["permanent"],limit:this.config.batchSize,offset:o});if(s.length===0)break;for(let a of s){let c=await Fc(a.id),u={nodeType:a.type,lastUpdated:new Date(a.updatedAt),corroborationCount:c,sourceReliability:a.source.reliability,now:e},l=pi(u),d=Ud(a.freshness),p=Ud(l);Math.abs(l-a.freshness)>.01&&(await lr(a.id,{metadata:{_freshness_computed:l}}),i++,d!=="stale"&&d!=="archival_candidate"&&(p==="stale"||p==="archival_candidate")&&(n++,await this.eventBus.publisher.publish({eventId:q$(),timestamp:e.toISOString(),source:V$("decay"),subject:te.gap.stale,gapNodeId:a.id,severity:p==="archival_candidate"?"high":"medium",affectedNodeIds:[a.id],description:`Node freshness decayed to ${l.toFixed(2)} (${p}): ${a.type} "${a.metadata?.title??a.metadata?.name??a.id}"`}))),r++}if(o+=s.length,s.length<this.config.batchSize)break}return i>0&&await this.eventBus.publisher.publish({eventId:q$(),timestamp:e.toISOString(),source:V$("decay"),subject:te.metabolism.decay,nodeIds:[],action:"decay"}),{processed:r,freshnessUpdated:i,staleDetected:n}}}});import{randomUUID as lb}from"node:crypto";function db(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var B3,Ks,pb=m(()=>{"use strict";Vr();Ne();Ne();Ne();B3={archivalThreshold:Sr.archivalCandidate,gracePeriodDays:ky,batchSize:100,intervalMs:1440*60*1e3},Ks=class{constructor(e,r){this.eventBus=e;this.config={...B3,...r}}config;timer=null;start(){setTimeout(()=>{this.runPruningCycle().catch(e=>console.error("[metabolism/pruning] Error in initial cycle:",e))},6e4),this.timer=setInterval(()=>{this.runPruningCycle().catch(e=>console.error("[metabolism/pruning] Error in pruning cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async runPruningCycle(){let e=0,r=0,i=0;for(;;){let n=await mi({layers:["permanent"],maxFreshness:this.config.archivalThreshold,limit:this.config.batchSize,offset:i});if(n.length===0)break;for(let o of n){if((Date.now()-new Date(o.updatedAt).getTime())/864e5<this.config.gracePeriodDays)continue;let a=await wr({targetId:o.id,limit:10});if(await this.hasActiveDependencies(o.id,a.map(u=>u.fromId))){r++;continue}await fi(o.id),e++,await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.graph.nodeArchived,nodeId:o.id,nodeType:o.type,reason:"freshness_decay"})}if(i+=n.length,n.length<this.config.batchSize)break}return e>0&&await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.metabolism.prune,nodeIds:[],action:"prune"}),{archived:e,skippedDependencies:r}}async pruneSubgraph(e,r){let i=await yn({startId:e,direction:"both",maxDepth:5,layers:["permanent"]}),n=0,o=0;for(let s of i.nodes){let a=await wr({targetId:s.id,limit:20}),c=new Set(i.nodes.map(l=>l.id));if(a.filter(l=>!c.has(l.fromId)).length>0){o++;continue}await fi(s.id),n++,await this.eventBus.publisher.publish({eventId:lb(),timestamp:new Date().toISOString(),source:db("pruning"),subject:te.graph.nodeArchived,nodeId:s.id,nodeType:s.type,reason:"manual"})}return{archived:n,skippedDependencies:o}}async hasActiveDependencies(e,r){for(let i of r){let n=await Ze(i,{layers:["permanent"]});if(n&&n.freshness>this.config.archivalThreshold)return!0}return!1}}});import{randomUUID as z3}from"node:crypto";function fb(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var q3,Hs,mb=m(()=>{"use strict";Vr();Ne();q3={recencyWeight:.4,corroborationWeight:.3,sourceReliabilityWeight:.2,specificityWeight:.1,autoResolveThreshold:.2},Hs=class{constructor(e,r){this.eventBus=e;this.config={...q3,...r}}config;async start(){this.eventBus.subscriber.subscribe(te.graph.edgeCreated,async e=>{e.edgeType==="contradicts"&&await this.resolveContradiction(e.fromNodeId,e.toNodeId)},{group:"metabolism-contradiction"})}async resolveContradiction(e,r){let i=await Ze(e),n=await Ze(r);if(!i||!n)return{nodeA:e,nodeB:r,strategy:"escalate",winnerId:null,reason:"One or both nodes not found"};let o=await this.scoreNode(i),s=await this.scoreNode(n),a=Math.abs(o-s),c,u=null,l;if(a>=this.config.autoResolveThreshold){c="supersede",o>s?(u=i.id,l=`Node A scores ${o.toFixed(2)} vs Node B ${s.toFixed(2)}: newer/better-evidenced`):(u=n.id,l=`Node B scores ${s.toFixed(2)} vs Node A ${o.toFixed(2)}: newer/better-evidenced`);let d=u===i.id?n.id:i.id;await lr(d,{metadata:{superseded_by:u}}),await Ir({type:"supersedes",sourceId:u,targetId:d,confidence:.8,weight:1,evidence:l,source:fb("contradiction-resolver")})}else this.couldCoexist(i,n)?(c="coexist",l=`Score difference ${a.toFixed(2)} below threshold and nodes cover different contexts`):(c="escalate",l=`Score difference ${a.toFixed(2)} below auto-resolve threshold ${this.config.autoResolveThreshold}`,await qr({type:"Gap",layer:"permanent",confidence:.9,source:fb("contradiction-resolver"),properties:{gapType:"contradiction",severity:"high",status:"detected",description:`Unresolved contradiction between ${i.type} nodes: "${i.metadata?.title??i.id}" vs "${n.metadata?.title??n.id}"`,detectedBy:"metabolism-service",resolutionPath:"Run a study or collect additional evidence to resolve",impactDescription:l}}),await this.eventBus.publisher.publish({eventId:z3(),timestamp:new Date().toISOString(),source:fb("contradiction-resolver"),subject:te.gap.semantic,gapNodeId:e,severity:"high",affectedNodeIds:[e,r],description:`Contradiction: ${l}`}));return{nodeA:e,nodeB:r,strategy:c,winnerId:u,reason:l}}async scoreNode(e){let n=(Date.now()-new Date(e.updatedAt).getTime())/(1e3*60*60*24),o=Math.exp(-.01*n),s=await Fc(e.id),a=Math.min(1,s/3),c=e.source.reliability,u=Object.keys(e.metadata).filter(d=>!d.startsWith("_")).length,l=Math.min(1,u/10);return this.config.recencyWeight*o+this.config.corroborationWeight*a+this.config.sourceReliabilityWeight*c+this.config.specificityWeight*l}couldCoexist(e,r){let i=e.metadata?.customerSegment,n=r.metadata?.customerSegment;if(i&&n&&i!==n)return!0;let o=e.metadata?.channel,s=r.metadata?.channel;return!!(o&&s&&o!==s)}}});import{randomUUID as Q$}from"node:crypto";function K$(t){return{system:"metabolism-service",reference:t,agentId:null,reliability:1}}var V3,Ws,hb=m(()=>{"use strict";Vr();Ne();V3={intervalMs:300*1e3},Ws=class{constructor(e,r){this.eventBus=e;this.config={...V3,...r}}config;timer=null;start(){this.timer=setInterval(()=>{this.expireHotNodes().catch(e=>console.error("[metabolism/hot-layer] Error in TTL cycle:",e))},this.config.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async expireHotNodes(){let e=await ae("SELECT * FROM expire_hot_nodes()"),r=0,i=0;for(let n of e.rows)n.action==="promoted_to_draft"?(r++,await this.eventBus.publisher.publish({eventId:Q$(),timestamp:new Date().toISOString(),source:K$("hot-layer"),subject:te.graph.nodePromoted,nodeId:n.node_id,nodeType:"unknown",fromLayer:"hot",toLayer:"draft"})):n.action==="deleted"&&(i++,await this.eventBus.publisher.publish({eventId:Q$(),timestamp:new Date().toISOString(),source:K$("hot-layer"),subject:te.graph.nodeArchived,nodeId:n.node_id,nodeType:"unknown",reason:"freshness_decay"}));return{promoted:r,deleted:i}}}});var H$={};yt(H$,{ContradictionResolver:()=>Hs,DecayEngine:()=>Qs,GatingService:()=>Vs,HotLayerService:()=>Ws,MetabolismService:()=>Xd,PruningService:()=>Ks,createMetabolismService:()=>Q3});async function Q3(t){let e=await hi(),r=new Xd(e,t);return await r.start(),r}var Xd,W$=m(()=>{"use strict";Vr();cb();ub();pb();mb();hb();cb();ub();pb();mb();hb();Xd=class{constructor(e,r){this.eventBus=e;this.gating=new Vs(e,r?.gating),this.decay=new Qs(e,r?.decay),this.pruning=new Ks(e,r?.pruning),this.contradictions=new Hs(e,r?.contradiction),this.hotLayer=new Ws(e,r?.hotLayer)}gating;decay;pruning;contradictions;hotLayer;async start(){console.log("[metabolism] Starting metabolism service..."),await this.gating.start(),await this.contradictions.start(),this.decay.start(),this.pruning.start(),this.hotLayer.start(),console.log("[metabolism] All subsystems running:"),console.log(" - Gating: listening for draft node events"),console.log(" - Contradiction resolver: listening for contradicts edges"),console.log(" - Decay engine: scheduled freshness recomputation"),console.log(" - Pruning: scheduled archival of stale nodes"),console.log(" - Hot layer: scheduled TTL expiry")}async stop(){console.log("[metabolism] Stopping metabolism service..."),this.decay.stop(),this.pruning.stop(),this.hotLayer.stop(),await this.eventBus.close(),console.log("[metabolism] Stopped.")}}});async function Z$(t){let e=process.env.VOYAGE_API_KEY;if(!e)return null;try{let r=await fetch("https://api.voyageai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({input:[t],model:"voyage-3-lite"})});return r.ok?(await r.json()).data?.[0]?.embedding??null:null}catch{return null}}var ep,J$=m(()=>{"use strict";Ne();Ne();Ne();Ne();Ne();ep=class{async createNode(e){let r=[e.metadata?.title,e.metadata?.description].filter(Boolean).join(". "),i=r?await Z$(r):null,n={type:e.type,layer:e.layer,source:e.source,tags:e.tags,branchId:e.branchId,metadata:e.metadata,properties:{...e},embedding:i??void 0};return delete n.properties.type,delete n.properties.layer,delete n.properties.source,delete n.properties.tags,delete n.properties.branchId,delete n.properties.metadata,qr(n)}async getNode(e){return Ze(e)}async updateNode(e,r){let i=await lr(e,{properties:r,confidence:r.metadata?.confidence,tags:r.tags});if(!i)throw new Error(`Node ${e} not found`);return i}async deleteNode(e){await fi(e)}async promoteNode(e,r,i){let n=await ho(e,i);if(!n)throw new Error(`Node ${e} not found`);return n}async createEdge(e){let r={type:e.type,sourceId:e.fromId,targetId:e.toId,confidence:e.confidence,weight:e.weight,evidence:e.evidence??void 0,source:e.source,branchId:e.branchId};return Ir(r)}async getEdge(e){return Vd(e)}async updateEdge(e,r){let i=await $y(e,{confidence:r.confidence,weight:r.weight,evidence:r.evidence??void 0});if(!i)throw new Error(`Edge ${e} not found`);return i}async deleteEdge(e){await Py(e)}async search(e,r){let i=await Z$(e);if(i)return(await Ry({embedding:i,nodeTypes:r?.nodeTypes,layers:r?.layers,limit:r?.limit??20})).map(p=>p.node);let n=["superseded_by IS NULL"],o=[],s=1,a=e.split(/\s+/).filter(d=>d.length>1);if(a.length>0){let d=a.map(p=>{o.push(`%${p}%`);let f=s++;return`(properties::text ILIKE $${f} OR metadata::text ILIKE $${f} OR $${f} = ANY(tags))`});n.push(`(${d.join(" OR ")})`)}r?.nodeTypes?.length&&(n.push(`type = ANY($${s++})`),o.push(r.nodeTypes)),r?.layers?.length?(n.push(`layer = ANY($${s++})`),o.push(r.layers)):(n.push(`layer = ANY($${s++})`),o.push(["permanent","draft","hot"])),r?.minFreshness!==void 0&&(n.push(`freshness >= $${s++}`),o.push(r.minFreshness));let c=r?.limit??20;o.push(c);let u=`SELECT * FROM nodes WHERE ${n.join(" AND ")} ORDER BY freshness DESC LIMIT $${s}`;return(await ae(u,o)).rows}async traverse(e,r){return(await yn({startId:e,direction:{outgoing:"outbound",incoming:"inbound",both:"both"}[r.direction??"both"],edgeTypes:r.edgeTypes,maxDepth:r.maxDepth??3,minFreshness:r.minConfidence,limit:r.limit??50})).nodes}async getNeighbors(e,r){let i={},n=r??"both";n==="outgoing"?i.sourceId=e:n==="incoming"?i.targetId=e:i.nodeId=e;let o=await wr(i),s=[];for(let a of o){let c=a.fromId===e?a.toId:a.fromId,u=await Ze(c);u&&s.push({node:u,edge:a})}return s}async getGaps(e){let r=["type = 'Gap'","superseded_by IS NULL"],i=[],n=1;e?.status?.length&&(r.push(`properties->>'status' = ANY($${n++})`),i.push(e.status)),e?.severity?.length&&(r.push(`properties->>'severity' = ANY($${n++})`),i.push(e.severity));let o=e?.limit??50;i.push(o);let s=`SELECT * FROM nodes WHERE ${r.join(" AND ")} ORDER BY freshness DESC LIMIT $${n}`;return(await ae(s,i)).rows}async createBranch(e,r){return Ay({name:e,purpose:r,createdBy:"api"})}async getBranch(e){return Cy(e)}async listBranches(){return Ly()}async mergeBranch(e){return jy(e)}async deleteBranch(e){await Fy(e,"Deleted via API")}}});var Y$={};yt(Y$,{GraphServiceAdapter:()=>ep});var X$=m(()=>{"use strict";J$()});function _(t,e,r){function i(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=s.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in a||(a[p]=u[p].bind(a))}}let n=r?.Parent??Object;class o extends n{}Object.defineProperty(o,"name",{value:t});function s(a){var c;let u=r?.Parent?new o:this;i(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}function st(t){return t&&Object.assign(zc,t),zc}var gb,tp,Qr,yi,zc,Zs=m(()=>{gb=Object.freeze({status:"aborted"});tp=Symbol("zod_brand"),Qr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},yi=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},zc={}});var C={};yt(C,{BIGINT_FORMAT_RANGES:()=>wb,Class:()=>bb,NUMBER_FORMAT_RANGES:()=>Ib,aborted:()=>Ti,allowsEval:()=>Tb,assert:()=>J3,assertEqual:()=>K3,assertIs:()=>W3,assertNever:()=>Z3,assertNotEqual:()=>H3,assignProp:()=>vi,base64ToUint8Array:()=>tP,base64urlToUint8Array:()=>mQ,cached:()=>Ys,captureStackTrace:()=>np,cleanEnum:()=>fQ,cleanRegex:()=>Qc,clone:()=>Bt,cloneDef:()=>X3,createTransparentProxy:()=>oQ,defineLazy:()=>he,esc:()=>rp,escapeRegex:()=>Nr,extend:()=>cQ,finalizeIssue:()=>Yt,floatSafeRemainder:()=>vb,getElementAtPath:()=>eQ,getEnumValues:()=>Vc,getLengthableOrigin:()=>Wc,getParsedType:()=>iQ,getSizableOrigin:()=>Hc,hexToUint8Array:()=>gQ,isObject:()=>go,isPlainObject:()=>_i,issue:()=>Xs,joinValues:()=>S,jsonStringifyReplacer:()=>Js,merge:()=>lQ,mergeDefs:()=>Gn,normalizeParams:()=>L,nullish:()=>bi,numKeys:()=>nQ,objectClone:()=>Y3,omit:()=>aQ,optionalKeys:()=>Sb,parsedType:()=>A,partial:()=>dQ,pick:()=>sQ,prefixIssues:()=>dr,primitiveTypes:()=>xb,promiseAllObject:()=>tQ,propertyKeyTypes:()=>Kc,randomString:()=>rQ,required:()=>pQ,safeExtend:()=>uQ,shallowClone:()=>Eb,slugify:()=>_b,stringifyPrimitive:()=>D,uint8ArrayToBase64:()=>rP,uint8ArrayToBase64url:()=>hQ,uint8ArrayToHex:()=>yQ,unwrapMessage:()=>qc});function K3(t){return t}function H3(t){return t}function W3(t){}function Z3(t){throw new Error("Unexpected value in exhaustive check")}function J3(t){}function Vc(t){let e=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,n])=>e.indexOf(+i)===-1).map(([i,n])=>n)}function S(t,e="|"){return t.map(r=>D(r)).join(e)}function Js(t,e){return typeof e=="bigint"?e.toString():e}function Ys(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function bi(t){return t==null}function Qc(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function vb(t,e){let r=(t.toString().split(".")[1]||"").length,i=e.toString(),n=(i.split(".")[1]||"").length;if(n===0&&/\d?e-\d?/.test(i)){let c=i.match(/\d?e-(\d?)/);c?.[1]&&(n=Number.parseInt(c[1]))}let o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function he(t,e,r){let i;Object.defineProperty(t,e,{get(){if(i!==eP)return i===void 0&&(i=eP,i=r()),i},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Y3(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function vi(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Gn(...t){let e={};for(let r of t){let i=Object.getOwnPropertyDescriptors(r);Object.assign(e,i)}return Object.defineProperties({},e)}function X3(t){return Gn(t._zod.def)}function eQ(t,e){return e?e.reduce((r,i)=>r?.[i],t):t}function tQ(t){let e=Object.keys(t),r=e.map(i=>t[i]);return Promise.all(r).then(i=>{let n={};for(let o=0;o<e.length;o++)n[e[o]]=i[o];return n})}function rQ(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let i=0;i<t;i++)r+=e[Math.floor(Math.random()*e.length)];return r}function rp(t){return JSON.stringify(t)}function _b(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function go(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _i(t){if(go(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(go(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Eb(t){return _i(t)?{...t}:Array.isArray(t)?[...t]:t}function nQ(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Nr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,e,r){let i=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(i._zod.parent=t),i}function L(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function oQ(t){let e;return new Proxy({},{get(r,i,n){return e??(e=t()),Reflect.get(e,i,n)},set(r,i,n,o){return e??(e=t()),Reflect.set(e,i,n,o)},has(r,i){return e??(e=t()),Reflect.has(e,i)},deleteProperty(r,i){return e??(e=t()),Reflect.deleteProperty(e,i)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,i){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(r,i,n){return e??(e=t()),Reflect.defineProperty(e,i,n)}})}function D(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Sb(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function sQ(t,e){let r=t._zod.def,i=r.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Gn(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return vi(this,"shape",s),s},checks:[]});return Bt(t,o)}function aQ(t,e){let r=t._zod.def,i=r.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Gn(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return vi(this,"shape",s),s},checks:[]});return Bt(t,o)}function cQ(t,e){if(!_i(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let o=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Gn(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return vi(this,"shape",o),o}});return Bt(t,n)}function uQ(t,e){if(!_i(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Gn(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return vi(this,"shape",i),i}});return Bt(t,r)}function lQ(t,e){let r=Gn(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e._zod.def.shape};return vi(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:[]});return Bt(t,r)}function dQ(t,e,r){let n=e._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Gn(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return vi(this,"shape",c),c},checks:[]});return Bt(e,s)}function pQ(t,e,r){let i=Gn(e._zod.def,{get shape(){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return vi(this,"shape",o),o}});return Bt(e,i)}function Ti(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function dr(t,e){return e.map(r=>{var i;return(i=r).path??(i.path=[]),r.path.unshift(t),r})}function qc(t){return typeof t=="string"?t:t?.message}function Yt(t,e,r){let i={...t,path:t.path??[]};if(!t.message){let n=qc(t.inst?._zod.def?.error?.(t))??qc(e?.error?.(t))??qc(r.customError?.(t))??qc(r.localeError?.(t))??"Invalid input";i.message=n}return delete i.inst,delete i.continue,e?.reportInput||delete i.input,i}function Hc(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function A(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Xs(...t){let[e,r,i]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:i}:{...e}}function fQ(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function tP(t){let e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r}function rP(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function mQ(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return tP(e+r)}function hQ(t){return rP(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gQ(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)r[i/2]=Number.parseInt(e.slice(i,i+2),16);return r}function yQ(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var eP,np,Tb,iQ,Kc,xb,Ib,wb,bb,Y=m(()=>{eP=Symbol("evaluating");np="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};Tb=Ys(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});iQ=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Kc=new Set(["string","number","symbol"]),xb=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ib={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},wb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};bb=class{constructor(...e){}}});function Jc(t,e=r=>r.message){let r={},i=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:r}}function Yc(t,e=r=>r.message){let r={_errors:[]},i=n=>{for(let o of n.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)r._errors.push(e(o));else{let s=r,a=0;for(;a<o.path.length;){let c=o.path[a];a===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(e(o))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return i(t),r}function Nb(t,e=r=>r.message){let r={errors:[]},i=(n,o=[])=>{var s,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>i({issues:u},c.path));else if(c.code==="invalid_key")i({issues:c.issues},c.path);else if(c.code==="invalid_element")i({issues:c.issues},c.path);else{let u=[...o,...c.path];if(u.length===0){r.errors.push(e(c));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(l.properties??(l.properties={}),(s=l.properties)[p]??(s[p]={errors:[]}),l=l.properties[p]):(l.items??(l.items=[]),(a=l.items)[p]??(a[p]={errors:[]}),l=l.items[p]),f&&l.errors.push(e(c)),d++}}};return i(t),r}function iP(t){let e=[],r=t.map(i=>typeof i=="object"?i.key:i);for(let i of r)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function Ob(t){let e=[],r=[...t.issues].sort((i,n)=>(i.path??[]).length-(n.path??[]).length);for(let i of r)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${iP(i.path)}`);return e.join(`
|
|
267
267
|
`)}var nP,Zc,Xt,kb=m(()=>{Zs();Y();nP=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Js,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Zc=_("$ZodError",nP),Xt=_("$ZodError",nP,{Parent:Error})});var ea,ip,ta,op,ra,$b,na,Pb,sp,vQ,ap,_Q,cp,TQ,up,EQ,lp,xQ,dp,SQ,pp,IQ,fp,wQ,Rb=m(()=>{Zs();kb();Y();ea=t=>(e,r,i,n)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qr;if(s.issues.length){let a=new(n?.Err??t)(s.issues.map(c=>Yt(c,o,st())));throw np(a,n?.callee),a}return s.value},ip=ea(Xt),ta=t=>async(e,r,i,n)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(n?.Err??t)(s.issues.map(c=>Yt(c,o,st())));throw np(a,n?.callee),a}return s.value},op=ta(Xt),ra=t=>(e,r,i)=>{let n=i?{...i,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},n);if(o instanceof Promise)throw new Qr;return o.issues.length?{success:!1,error:new(t??Zc)(o.issues.map(s=>Yt(s,n,st())))}:{success:!0,data:o.value}},$b=ra(Xt),na=t=>async(e,r,i)=>{let n=i?Object.assign(i,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},n);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>Yt(s,n,st())))}:{success:!0,data:o.value}},Pb=na(Xt),sp=t=>(e,r,i)=>{let n=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return ea(t)(e,r,n)},vQ=sp(Xt),ap=t=>(e,r,i)=>ea(t)(e,r,i),_Q=ap(Xt),cp=t=>async(e,r,i)=>{let n=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return ta(t)(e,r,n)},TQ=cp(Xt),up=t=>async(e,r,i)=>ta(t)(e,r,i),EQ=up(Xt),lp=t=>(e,r,i)=>{let n=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return ra(t)(e,r,n)},xQ=lp(Xt),dp=t=>(e,r,i)=>ra(t)(e,r,i),SQ=dp(Xt),pp=t=>async(e,r,i)=>{let n=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return na(t)(e,r,n)},IQ=pp(Xt),fp=t=>async(e,r,i)=>na(t)(e,r,i),wQ=fp(Xt)});var Or={};yt(Or,{base64:()=>Hb,base64url:()=>mp,bigint:()=>ev,boolean:()=>rv,browserEmail:()=>AQ,cidrv4:()=>Qb,cidrv6:()=>Kb,cuid:()=>Db,cuid2:()=>Ab,date:()=>Zb,datetime:()=>Yb,domain:()=>jQ,duration:()=>Ub,e164:()=>Wb,email:()=>Gb,emoji:()=>Bb,extendedDuration:()=>NQ,guid:()=>Mb,hex:()=>FQ,hostname:()=>LQ,html5Email:()=>PQ,idnEmail:()=>DQ,integer:()=>tv,ipv4:()=>zb,ipv6:()=>qb,ksuid:()=>jb,lowercase:()=>ov,mac:()=>Vb,md5_base64:()=>MQ,md5_base64url:()=>GQ,md5_hex:()=>UQ,nanoid:()=>Fb,null:()=>nv,number:()=>hp,rfc5322Email:()=>RQ,sha1_base64:()=>zQ,sha1_base64url:()=>qQ,sha1_hex:()=>BQ,sha256_base64:()=>QQ,sha256_base64url:()=>KQ,sha256_hex:()=>VQ,sha384_base64:()=>WQ,sha384_base64url:()=>ZQ,sha384_hex:()=>HQ,sha512_base64:()=>YQ,sha512_base64url:()=>XQ,sha512_hex:()=>JQ,string:()=>Xb,time:()=>Jb,ulid:()=>Cb,undefined:()=>iv,unicodeEmail:()=>oP,uppercase:()=>sv,uuid:()=>yo,uuid4:()=>OQ,uuid6:()=>kQ,uuid7:()=>$Q,xid:()=>Lb});function Bb(){return new RegExp(CQ,"u")}function aP(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Jb(t){return new RegExp(`^${aP(t)}$`)}function Yb(t){let e=aP({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${e}(?:${r.join("|")})`;return new RegExp(`^${sP}T(?:${i})$`)}function Xc(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function eu(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var Db,Ab,Cb,Lb,jb,Fb,Ub,NQ,Mb,yo,OQ,kQ,$Q,Gb,PQ,RQ,oP,DQ,AQ,CQ,zb,qb,Vb,Qb,Kb,Hb,mp,LQ,jQ,Wb,sP,Zb,Xb,ev,tv,hp,rv,nv,iv,ov,sv,FQ,UQ,MQ,GQ,BQ,zQ,qQ,VQ,QQ,KQ,HQ,WQ,ZQ,JQ,YQ,XQ,gp=m(()=>{Y();Db=/^[cC][^\s-]{8,}$/,Ab=/^[0-9a-z]+$/,Cb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lb=/^[0-9a-vA-V]{20}$/,jb=/^[A-Za-z0-9]{27}$/,Fb=/^[a-zA-Z0-9_-]{21}$/,Ub=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,NQ=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Mb=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yo=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,OQ=yo(4),kQ=yo(6),$Q=yo(7),Gb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,PQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,RQ=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,oP=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,DQ=oP,AQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,CQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";zb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Vb=t=>{let e=Nr(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},Qb=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Kb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Hb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mp=/^[A-Za-z0-9_-]*$/,LQ=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,jQ=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Wb=/^\+[1-9]\d{6,14}$/,sP="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zb=new RegExp(`^${sP}$`);Xb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ev=/^-?\d+n?$/,tv=/^-?\d+$/,hp=/^-?\d+(?:\.\d+)?$/,rv=/^(?:true|false)$/i,nv=/^null$/i,iv=/^undefined$/i,ov=/^[^A-Z]*$/,sv=/^[^a-z]*$/,FQ=/^[0-9a-fA-F]*$/;UQ=/^[0-9a-fA-F]{32}$/,MQ=Xc(22,"=="),GQ=eu(22),BQ=/^[0-9a-fA-F]{40}$/,zQ=Xc(27,"="),qQ=eu(27),VQ=/^[0-9a-fA-F]{64}$/,QQ=Xc(43,"="),KQ=eu(43),HQ=/^[0-9a-fA-F]{96}$/,WQ=Xc(64,""),ZQ=eu(64),JQ=/^[0-9a-fA-F]{128}$/,YQ=Xc(86,"=="),XQ=eu(86)});function cP(t,e,r){t.issues.length&&e.issues.push(...dr(r,t.issues))}var Ve,uP,yp,bp,av,cv,uv,lv,dv,pv,fv,mv,hv,ia,gv,yv,bv,vv,_v,Tv,Ev,xv,Sv,vp=m(()=>{Zs();gp();Y();Ve=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),uP={number:"number",bigint:"bigint",object:"date"},yp=_("$ZodCheckLessThan",(t,e)=>{Ve.init(t,e);let r=uP[typeof e.value];t._zod.onattach.push(i=>{let n=i._zod.bag,o=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=i=>{(e.inclusive?i.value<=e.value:i.value<e.value)||i.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),bp=_("$ZodCheckGreaterThan",(t,e)=>{Ve.init(t,e);let r=uP[typeof e.value];t._zod.onattach.push(i=>{let n=i._zod.bag,o=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=i=>{(e.inclusive?i.value>=e.value:i.value>e.value)||i.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),av=_("$ZodCheckMultipleOf",(t,e)=>{Ve.init(t,e),t._zod.onattach.push(r=>{var i;(i=r._zod.bag).multipleOf??(i.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):vb(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),cv=_("$ZodCheckNumberFormat",(t,e)=>{Ve.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),i=r?"int":"number",[n,o]=Ib[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=n,a.maximum=o,r&&(a.pattern=tv)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:i,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,inclusive:!0,continue:!e.abort});return}}a<n&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}}),uv=_("$ZodCheckBigIntFormat",(t,e)=>{Ve.init(t,e);let[r,i]=wb[e.format];t._zod.onattach.push(n=>{let o=n._zod.bag;o.format=e.format,o.minimum=r,o.maximum=i}),t._zod.check=n=>{let o=n.value;o<r&&n.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),o>i&&n.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}}),lv=_("$ZodCheckMaxSize",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.size!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(i._zod.bag.maximum=e.maximum)}),t._zod.check=i=>{let n=i.value;n.size<=e.maximum||i.issues.push({origin:Hc(n),code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),dv=_("$ZodCheckMinSize",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.size!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(i._zod.bag.minimum=e.minimum)}),t._zod.check=i=>{let n=i.value;n.size>=e.minimum||i.issues.push({origin:Hc(n),code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),pv=_("$ZodCheckSizeEquals",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.size!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag;n.minimum=e.size,n.maximum=e.size,n.size=e.size}),t._zod.check=i=>{let n=i.value,o=n.size;if(o===e.size)return;let s=o>e.size;i.issues.push({origin:Hc(n),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!e.abort})}}),fv=_("$ZodCheckMaxLength",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.length!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(i._zod.bag.maximum=e.maximum)}),t._zod.check=i=>{let n=i.value;if(n.length<=e.maximum)return;let s=Wc(n);i.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),mv=_("$ZodCheckMinLength",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.length!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(i._zod.bag.minimum=e.minimum)}),t._zod.check=i=>{let n=i.value;if(n.length>=e.minimum)return;let s=Wc(n);i.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),hv=_("$ZodCheckLengthEquals",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=i=>{let n=i.value;return!bi(n)&&n.length!==void 0}),t._zod.onattach.push(i=>{let n=i._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=i=>{let n=i.value,o=n.length;if(o===e.length)return;let s=Wc(n),a=o>e.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!e.abort})}}),ia=_("$ZodCheckStringFormat",(t,e)=>{var r,i;Ve.init(t,e),t._zod.onattach.push(n=>{let o=n._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(i=t._zod).check??(i.check=()=>{})}),gv=_("$ZodCheckRegex",(t,e)=>{ia.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),yv=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ov),ia.init(t,e)}),bv=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sv),ia.init(t,e)}),vv=_("$ZodCheckIncludes",(t,e)=>{Ve.init(t,e);let r=Nr(e.includes),i=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=i,t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),_v=_("$ZodCheckStartsWith",(t,e)=>{Ve.init(t,e);let r=new RegExp(`^${Nr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(i=>{let n=i._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=i=>{i.value.startsWith(e.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:i.value,inst:t,continue:!e.abort})}}),Tv=_("$ZodCheckEndsWith",(t,e)=>{Ve.init(t,e);let r=new RegExp(`.*${Nr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(i=>{let n=i._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=i=>{i.value.endsWith(e.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:i.value,inst:t,continue:!e.abort})}});Ev=_("$ZodCheckProperty",(t,e)=>{Ve.init(t,e),t._zod.check=r=>{let i=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(i instanceof Promise)return i.then(n=>cP(n,r,e.property));cP(i,r,e.property)}}),xv=_("$ZodCheckMimeType",(t,e)=>{Ve.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(i=>{i._zod.bag.mime=e.mime}),t._zod.check=i=>{r.has(i.value.type)||i.issues.push({code:"invalid_value",values:e.mime,input:i.value.type,inst:t,continue:!e.abort})}}),Sv=_("$ZodCheckOverwrite",(t,e)=>{Ve.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var tu,Iv=m(()=>{tu=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let i=e.split(`
|
|
268
268
|
`).filter(s=>s),n=Math.min(...i.map(s=>s.length-s.trimStart().length)),o=i.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,r=this?.args,n=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,n.join(`
|
|
269
269
|
`))}}});var wv,Nv=m(()=>{wv={major:4,minor:3,patch:6}});function Wv(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function EP(t){if(!mp.test(t))return!1;let e=t.replace(/[-_]/g,i=>i==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Wv(r)}function xP(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[i]=r;if(!i)return!1;let n=JSON.parse(atob(i));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}function dP(t,e,r){t.issues.length&&e.issues.push(...dr(r,t.issues)),e.value[r]=t.value}function Sp(t,e,r,i,n){if(t.issues.length){if(n&&!(r in i))return;e.issues.push(...dr(r,t.issues))}t.value===void 0?r in i&&(e.value[r]=void 0):e.value[r]=t.value}function SP(t){let e=Object.keys(t.shape);for(let i of e)if(!t.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);let r=Sb(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function IP(t,e,r,i,n,o){let s=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in e){if(a.has(d))continue;if(u==="never"){s.push(d);continue}let p=c.run({value:e[d],issues:[]},i);p instanceof Promise?t.push(p.then(f=>Sp(f,r,d,e,l))):Sp(p,r,d,e,l)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}function pP(t,e,r,i){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;let n=t.filter(o=>!Ti(o));return n.length===1?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Yt(s,i,st())))}),e)}function fP(t,e,r,i){let n=t.filter(o=>o.issues.length===0);return n.length===1?(e.value=n[0].value,e):(n.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Yt(s,i,st())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}function Ov(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(_i(t)&&_i(e)){let r=Object.keys(e),i=Object.keys(t).filter(o=>r.indexOf(o)!==-1),n={...t,...e};for(let o of i){let s=Ov(t[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};n[o]=s.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=e[i],s=Ov(n,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function mP(t,e,r){let i=new Map,n;for(let a of e.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let c of a.keys)i.has(c)||i.set(c,{}),i.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)i.has(c)||i.set(c,{}),i.get(c).r=!0;else t.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&n&&t.issues.push({...n,keys:o}),Ti(t))return t;let s=Ov(e.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}function _p(t,e,r){t.issues.length&&e.issues.push(...dr(r,t.issues)),e.value[r]=t.value}function hP(t,e,r,i,n,o,s){t.issues.length&&(Kc.has(typeof i)?r.issues.push(...dr(i,t.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:o,issues:t.issues.map(a=>Yt(a,s,st()))})),e.issues.length&&(Kc.has(typeof i)?r.issues.push(...dr(i,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:o,key:i,issues:e.issues.map(a=>Yt(a,s,st()))})),r.value.set(t.value,e.value)}function gP(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function yP(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}function bP(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function vP(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Tp(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}function Ep(t,e,r){if(t.issues.length)return t.aborted=!0,t;if((r.direction||"forward")==="forward"){let n=e.transform(t.value,t);return n instanceof Promise?n.then(o=>xp(t,o,e.out,r)):xp(t,n,e.out,r)}else{let n=e.reverseTransform(t.value,t);return n instanceof Promise?n.then(o=>xp(t,o,e.in,r)):xp(t,n,e.in,r)}}function xp(t,e,r,i){return t.issues.length?(t.aborted=!0,t):r._zod.run({value:e,issues:t.issues},i)}function _P(t){return t.value=Object.freeze(t.value),t}function TP(t,e,r,i){if(!t){let n={code:"custom",input:r,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(n.params=i._zod.def.params),e.issues.push(Xs(n))}}var ce,bo,Ue,kv,$v,Pv,Rv,Dv,Av,Cv,Lv,jv,Fv,Uv,Mv,Gv,Bv,zv,qv,Vv,Qv,Kv,Hv,Zv,Jv,Yv,Xv,e_,Ip,t_,ru,wp,r_,n_,i_,o_,s_,a_,c_,u_,l_,d_,wP,p_,nu,f_,m_,h_,Np,g_,y_,b_,v_,__,T_,E_,Op,x_,S_,I_,w_,N_,O_,k_,$_,P_,iu,R_,D_,A_,C_,L_,j_,F_=m(()=>{vp();Zs();Iv();Rb();gp();Y();Nv();Y();ce=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=wv;let i=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&i.unshift(t);for(let n of i)for(let o of n._zod.onattach)o(t);if(i.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let n=(s,a,c)=>{let u=Ti(s),l;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(u)continue;let p=s.issues.length,f=d._zod.check(s);if(f instanceof Promise&&c?.async===!1)throw new Qr;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(u||(u=Ti(s,p)))});else{if(s.issues.length===p)continue;u||(u=Ti(s,p))}}return l?l.then(()=>s):s},o=(s,a,c)=>{if(Ti(s))return s.aborted=!0,s;let u=n(a,i,c);if(u instanceof Promise){if(c.async===!1)throw new Qr;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let u=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>o(l,s,a)):o(u,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Qr;return c.then(u=>n(u,i,a))}return n(c,i,a)}}he(t,"~standard",()=>({validate:n=>{try{let o=$b(t,n);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Pb(t,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),bo=_("$ZodString",(t,e)=>{ce.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Xb(t._zod.bag),t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ue=_("$ZodStringFormat",(t,e)=>{ia.init(t,e),bo.init(t,e)}),kv=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Mb),Ue.init(t,e)}),$v=_("$ZodUUID",(t,e)=>{if(e.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(i===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=yo(i))}else e.pattern??(e.pattern=yo());Ue.init(t,e)}),Pv=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Gb),Ue.init(t,e)}),Rv=_("$ZodURL",(t,e)=>{Ue.init(t,e),t._zod.check=r=>{try{let i=r.value.trim(),n=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=n.href:r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Dv=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Bb()),Ue.init(t,e)}),Av=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Fb),Ue.init(t,e)}),Cv=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Db),Ue.init(t,e)}),Lv=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ab),Ue.init(t,e)}),jv=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Cb),Ue.init(t,e)}),Fv=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Lb),Ue.init(t,e)}),Uv=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=jb),Ue.init(t,e)}),Mv=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Yb(e)),Ue.init(t,e)}),Gv=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Zb),Ue.init(t,e)}),Bv=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Jb(e)),Ue.init(t,e)}),zv=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ub),Ue.init(t,e)}),qv=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=zb),Ue.init(t,e),t._zod.bag.format="ipv4"}),Vv=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=qb),Ue.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Qv=_("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=Vb(e.delimiter)),Ue.init(t,e),t._zod.bag.format="mac"}),Kv=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Qb),Ue.init(t,e)}),Hv=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Kb),Ue.init(t,e),t._zod.check=r=>{let i=r.value.split("/");try{if(i.length!==2)throw new Error;let[n,o]=i;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Zv=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Hb),Ue.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Wv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Jv=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=mp),Ue.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{EP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Yv=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Wb),Ue.init(t,e)});Xv=_("$ZodJWT",(t,e)=>{Ue.init(t,e),t._zod.check=r=>{xP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),e_=_("$ZodCustomStringFormat",(t,e)=>{Ue.init(t,e),t._zod.check=r=>{e.fn(r.value)||r.issues.push({code:"invalid_format",format:e.format,input:r.value,inst:t,continue:!e.abort})}}),Ip=_("$ZodNumber",(t,e)=>{ce.init(t,e),t._zod.pattern=t._zod.bag.pattern??hp,t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let o=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...o?{received:o}:{}}),r}}),t_=_("$ZodNumberFormat",(t,e)=>{cv.init(t,e),Ip.init(t,e)}),ru=_("$ZodBoolean",(t,e)=>{ce.init(t,e),t._zod.pattern=rv,t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),wp=_("$ZodBigInt",(t,e)=>{ce.init(t,e),t._zod.pattern=ev,t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}}),r_=_("$ZodBigIntFormat",(t,e)=>{uv.init(t,e),wp.init(t,e)}),n_=_("$ZodSymbol",(t,e)=>{ce.init(t,e),t._zod.parse=(r,i)=>{let n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:t}),r}}),i_=_("$ZodUndefined",(t,e)=>{ce.init(t,e),t._zod.pattern=iv,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(r,i)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:t}),r}}),o_=_("$ZodNull",(t,e)=>{ce.init(t,e),t._zod.pattern=nv,t._zod.values=new Set([null]),t._zod.parse=(r,i)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),s_=_("$ZodAny",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),a_=_("$ZodUnknown",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),c_=_("$ZodNever",(t,e)=>{ce.init(t,e),t._zod.parse=(r,i)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),u_=_("$ZodVoid",(t,e)=>{ce.init(t,e),t._zod.parse=(r,i)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:t}),r}}),l_=_("$ZodDate",(t,e)=>{ce.init(t,e),t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,o=n instanceof Date;return o&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...o?{received:"Invalid Date"}:{},inst:t}),r}});d_=_("$ZodArray",(t,e)=>{ce.init(t,e),t._zod.parse=(r,i)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);let o=[];for(let s=0;s<n.length;s++){let a=n[s],c=e.element._zod.run({value:a,issues:[]},i);c instanceof Promise?o.push(c.then(u=>dP(u,r,s))):dP(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});wP=_("$ZodObject",(t,e)=>{if(ce.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let i=Ys(()=>SP(e));he(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let n=go,o=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=i.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=s.shape;for(let p of s.keys){let f=d[p],h=f._zod.optout==="optional",g=f._zod.run({value:u[p],issues:[]},c);g instanceof Promise?l.push(g.then(x=>Sp(x,a,p,u,h))):Sp(g,a,p,u,h)}return o?IP(l,u,a,c,i.value,t):l.length?Promise.all(l).then(()=>a):a}}),p_=_("$ZodObjectJIT",(t,e)=>{wP.init(t,e);let r=t._zod.parse,i=Ys(()=>SP(e)),n=p=>{let f=new tu(["shape","payload","ctx"]),h=i.value,g=I=>{let k=rp(I);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let x=Object.create(null),E=0;for(let I of h.keys)x[I]=`key_${E++}`;f.write("const newResult = {};");for(let I of h.keys){let k=x[I],$=rp(I),K=p[I]?._zod?.optout==="optional";f.write(`const ${k} = ${g(I)};`),K?f.write(`
|
|
@@ -653,7 +653,7 @@ builder.objectType('MyObject', {
|
|
|
653
653
|
`),Qk(i);try{await Kk(i)}catch(h){console.error(" \u2717 Failed to start Docker services:",h.message),process.exit(1)}console.log(" \u2713 PostgreSQL on :5432"),console.log(" \u2713 NATS on :4222"),console.log(" Waiting for PostgreSQL to accept connections..."),await Hk(i)||(console.error(` \u2717 PostgreSQL did not become ready within 120s
|
|
654
654
|
`),process.exit(1)),console.log(" \u2713 PostgreSQL is ready")}console.log(`
|
|
655
655
|
[4/6] Database migrations`);try{let f=Fk(),h=await Wk(s,f),g=h.applied.length+h.skipped.length;h.applied.length>0?console.log(` \u2713 Schema applied (${h.applied.length} migration${h.applied.length>1?"s":""} applied, ${h.skipped.length} already up-to-date)`):console.log(` \u2713 Schema up-to-date (${g} migration${g>1?"s":""})`)}catch(f){console.error(" \u2717 Migration failed:",f.message),process.exit(1)}console.log(`
|
|
656
|
-
[5/6] Project config`),B2(r,{recursive:!0});let c=xs(r,"config.json"),u={version:"0.1.
|
|
656
|
+
[5/6] Project config`),B2(r,{recursive:!0});let c=xs(r,"config.json"),u={version:"0.1.9",database:s,nats:a,anthropicApiKey:o,projectRoot:e,createdAt:new Date().toISOString()};jd(c,JSON.stringify(u,null,2)+`
|
|
657
657
|
`,"utf-8"),console.log(" \u2713 .codify/config.json created");let l=xs(e,".gitignore");if(Zk(l)){let f=Jk(l,"utf-8");f.includes(".codify")||(jd(l,f.trimEnd()+`
|
|
658
658
|
.codify/
|
|
659
659
|
`,"utf-8"),console.log(" \u2713 .codify/ added to .gitignore"))}else jd(l,`.codify/
|
|
@@ -721,7 +721,7 @@ builder.objectType('MyObject', {
|
|
|
721
721
|
ERROR: ANTHROPIC_API_KEY not set.`),console.error(` Export your API key: export ANTHROPIC_API_KEY=sk-...
|
|
722
722
|
`)):console.error(`
|
|
723
723
|
ERROR: ${e}
|
|
724
|
-
`),process.exit(1)}});var $c=new gn;$c.name("codify").description("Codify \u2014 Living Context Graph for AI-Native Teams").version("0.1.
|
|
724
|
+
`),process.exit(1)}});var $c=new gn;$c.name("codify").description("Codify \u2014 Living Context Graph for AI-Native Teams").version("0.1.9").addHelpText("after",`
|
|
725
725
|
Quick Start:
|
|
726
726
|
codify init Set up infrastructure and configure project
|
|
727
727
|
codify bootstrap Mine git history into the context graph
|