@aria-cli/server 1.0.19
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/README.md +17 -0
- package/dist/.aria-build-stamp.json +4 -0
- package/dist/auth/api-key.d.ts +106 -0
- package/dist/config.d.ts +28 -0
- package/dist/daemon-launcher.d.ts +23 -0
- package/dist/daemon-launcher.js +3 -0
- package/dist/index-5tav2m70.js +3 -0
- package/dist/index-6extw9n6.js +2 -0
- package/dist/index-9n50yafd.js +3 -0
- package/dist/index-9xs3gn0p.js +2 -0
- package/dist/index-ghh3ag4c.js +548 -0
- package/dist/index-mnt9k223.js +15 -0
- package/dist/index-pe0pkp0v.js +2 -0
- package/dist/index-raeajnr7.js +2 -0
- package/dist/index-rr0sea4c.js +2 -0
- package/dist/index-zge0mhc0.js +3 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +1 -0
- package/dist/peer-principal-auth.d.ts +37 -0
- package/dist/routes/arions.d.ts +34 -0
- package/dist/routes/council.d.ts +15 -0
- package/dist/routes/entrypoint-errors.d.ts +7 -0
- package/dist/routes/health.d.ts +6 -0
- package/dist/routes/invite-relay.d.ts +2 -0
- package/dist/routes/local-control.d.ts +3 -0
- package/dist/routes/message.d.ts +17 -0
- package/dist/routes/network.d.ts +14 -0
- package/dist/routes/pair.d.ts +57 -0
- package/dist/routes/pair.js +1 -0
- package/dist/routes/pipeline-mailbox.d.ts +10 -0
- package/dist/routes/relay.d.ts +29 -0
- package/dist/routes/resume.d.ts +2 -0
- package/dist/routes/run-control-surface.d.ts +24 -0
- package/dist/routes/run.d.ts +6 -0
- package/dist/routes/runtime-bootstrap.d.ts +3 -0
- package/dist/routes/runtime-node-advertisement.d.ts +3 -0
- package/dist/routes/runtime-run-room.d.ts +8 -0
- package/dist/routes/shared.d.ts +45 -0
- package/dist/routes/stream.d.ts +10 -0
- package/dist/routes/validation.d.ts +7 -0
- package/dist/routes/ws-revocation.d.ts +25 -0
- package/dist/runtime/attached-sender-inbox.d.ts +3 -0
- package/dist/runtime/authoritative-peer-endpoint.d.ts +27 -0
- package/dist/runtime/continuity-bind-suspicion.d.ts +39 -0
- package/dist/runtime/continuity-verification.d.ts +54 -0
- package/dist/runtime/decorate-runtime-surface.d.ts +2 -0
- package/dist/runtime/durable-network-store-surface.d.ts +51 -0
- package/dist/runtime/error-diagnostic.d.ts +12 -0
- package/dist/runtime/headless-dispatch-handler.d.ts +30 -0
- package/dist/runtime/host-supervisor.d.ts +109 -0
- package/dist/runtime/host-supervisor.js +1 -0
- package/dist/runtime/join-control.d.ts +3 -0
- package/dist/runtime/local-control-api.d.ts +63 -0
- package/dist/runtime/local-control-api.js +1 -0
- package/dist/runtime/local-control-pairing.d.ts +12 -0
- package/dist/runtime/local-control-socket.d.ts +48 -0
- package/dist/runtime/log-file-sink.d.ts +21 -0
- package/dist/runtime/network-read-control.d.ts +17 -0
- package/dist/runtime/network-state-stores.d.ts +2 -0
- package/dist/runtime/node-metadata.d.ts +22 -0
- package/dist/runtime/node-metadata.js +1 -0
- package/dist/runtime/node-runtime.d.ts +157 -0
- package/dist/runtime/node-store-revocation-store.d.ts +42 -0
- package/dist/runtime/node-store.d.ts +184 -0
- package/dist/runtime/node-store.js +1 -0
- package/dist/runtime/pinned-control-session.d.ts +41 -0
- package/dist/runtime/principal-binding-authority.d.ts +173 -0
- package/dist/runtime/reachable-control-host.d.ts +5 -0
- package/dist/runtime/runtime-admin-api.d.ts +16 -0
- package/dist/runtime/runtime-authority-registry.d.ts +55 -0
- package/dist/runtime/runtime-autonomous-loop.d.ts +40 -0
- package/dist/runtime/runtime-bootstrap-authority.d.ts +5 -0
- package/dist/runtime/runtime-bootstrap-record.d.ts +21 -0
- package/dist/runtime/runtime-event-journal.d.ts +21 -0
- package/dist/runtime/runtime-outbox.d.ts +35 -0
- package/dist/runtime/runtime-registry.d.ts +33 -0
- package/dist/runtime/runtime-registry.js +1 -0
- package/dist/runtime/runtime-run-control.d.ts +71 -0
- package/dist/runtime/stale-owner-error.d.ts +13 -0
- package/dist/runtime-run-control-0r21xdh5.js +2 -0
- package/dist/server.d.ts +84 -0
- package/dist/session-history-messages.d.ts +3 -0
- package/dist/session-history.d.ts +28 -0
- package/dist/shared-4jsvhy6g.js +1 -0
- package/dist/types.d.ts +299 -0
- package/dist/utils/rate-limiter.d.ts +25 -0
- package/dist/utils/sanitize-error.d.ts +10 -0
- package/package.json +82 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{C as w0,D as r$,E as T0,F as d1,I as A2,J as E2,M as w2,N as i1}from"./index-pe0pkp0v.js";import{O as x1,P as T1,Q as V4}from"./index-rr0sea4c.js";import{$ as d$,S as B4,W as F4,X as t$,Z as H4,_ as x4,aa as h0,ba as l$,ca as T4}from"./index-9n50yafd.js";import{fa as _4,ha as J4,ia as p1}from"./index-5tav2m70.js";import{ka as X$,la as O$,ma as W4,na as $0,oa as W$,pa as x0,qa as f0,ra as R$,sa as a1}from"./index-6extw9n6.js";import{ta as U0}from"./index-raeajnr7.js";import{ya as d}from"./index-ghh3ag4c.js";import{Aa as L0}from"./index-9xs3gn0p.js";import{createHash as LQ,randomUUID as N8}from"node:crypto";import{appendFileSync as P8,mkdirSync as S8}from"node:fs";import{homedir as b8}from"node:os";import{join as U4}from"node:path";import*as L4 from"node:v8";import{computeSigningKeyFingerprint as C8}from"@aria-cli/aria";import{ClientIdSchema as I8,LocalRuntimeSummarySchema as k8,PrincipalFingerprintSchema as q8,SigningPublicKeySchema as h8,TlsCaFingerprintSchema as D4,RuntimeIdSchema as y8}from"@aria-cli/tools";import{log as p$}from"@aria-cli/types";import*as l0 from"node:fs";import*as B0 from"node:path";import{createHash as Z4,randomBytes as G4,randomUUID as $8}from"node:crypto";import{computeSigningKeyFingerprint as Z8,ensureMeshCerts as G8,MdnsDiscoveryService as Q8,NearbyPeerDiscoveryAuthority as Y8,NetworkIntelligenceCoordinator as X8,PrivateLanDiscoveryService as O8,ReplayGuard as Q4,processAriaMessageEvent as W8,resolveAdvertisedDiscoveryHosts as V8,createEnvelope as j8,signEnvelope as z8,tlsFetch as U8}from"@aria-cli/aria";import{MessageStore as _8}from"@aria-cli/memoria/storage";import{ClientIdSchema as Y4,NodeIdSchema as q0,PeerTransportIdSchema as J8,PrincipalFingerprintSchema as y$,SigningPublicKeySchema as j4,TlsCaFingerprintSchema as h$,RuntimeIdSchema as B8}from"@aria-cli/tools";import{RelayPendingResponseSchema as F8}from"@aria-cli/tools/network-runtime";import{PeerDiscoveryService as H8,StunClient as x8}from"@aria-cli/wireguard";import{NetworkStateStore as T8}from"@aria-cli/wireguard/network-state-store";import{log as m}from"@aria-cli/types";import{buildRuntimeBootstrapRecord as L8}from"@aria-cli/aria/server-discovery";import _6 from"fastify";import J6 from"@fastify/cors";import B6 from"@fastify/websocket";import F6 from"node:crypto";import H6 from"path";import{MemoriaPool as x6}from"@aria-cli/aria/server-memory";import{createRuntimeDefaultRouter as T6}from"@aria-cli/aria/server-models";import{createRuntimeAuthContext as L6}from"@aria-cli/auth";import{log as u0}from"@aria-cli/types";import{MessageStore as D6}from"@aria-cli/memoria";import{PrincipalFingerprintSchema as K6}from"@aria-cli/tools";import{NetworkStateStore as R6}from"@aria-cli/wireguard/network-state-store";import*as j0 from"node:fs";import*as e$ from"node:net";import*as y0 from"node:path";import{AcceptInviteRequestSchema as S4,AcceptInviteTokenRequestSchema as b4,AttachedClientAuthSchema as x$,AttachedClientViewSchema as C4,CancelInviteRequestSchema as I4,CreateInviteRequestSchema as k4,DirectPairRequestSchema as q4,InboxCursorSchema as o$,InboxListRequestSchema as r0,InvitePeerRequestSchema as h4,LocalControlSocketAttachClientRequestSchema as $2,LocalControlSocketAttachClientResponseSchema as Z2,LocalControlSocketDetachClientRequestSchema as G2,LocalControlSocketDetachClientResponseSchema as y4,LocalControlSocketErrorResponseSchema as v4,LocalControlSocketRequestSchema as m4,LocalControlSocketSuccessResponseSchema as C0,NearbyPeerViewSchema as g4,OutboundMessageSchema as t0,PendingInviteViewSchema as c4,PairRequestDecisionSchema as u4,RepairPeerRequestSchema as l4,RevokePeerRequestSchema as p4,RuntimeAutonomousLoopCommandSchema as d4,RuntimeEventCursorSchema as i4,RuntimeEventSchema as a4,ResumeRunRequestSchema as s$,RuntimeRunEventSchema as n4,RunRequestSchema as e0,PersistedInboxEventSchema as d0,PeerViewEventSchema as o4,LOCAL_HTTP_CLIENT_ID_HEADER as Q2,LOCAL_HTTP_CLIENT_PROOF_HEADER as Y2}from"@aria-cli/tools";import{LOCAL_HTTP_CLIENT_ID_HEADER as n8,LOCAL_HTTP_CLIENT_PROOF_HEADER as o8}from"@aria-cli/tools";function $$($,Z){let G=$;if(G.ariaLocalHttpClientAuthority){G.ariaLocalHttpClientAuthority=Z;return}try{$.decorate("ariaLocalHttpClientAuthority",Z)}catch{G.ariaLocalHttpClientAuthority=Z}}function W0($,Z){let G=Z.headers[Q2],Q=typeof G==="string"?G.trim():Array.isArray(G)?G.find((O)=>typeof O==="string")?.trim():"",Y=Z.headers[Y2],X=typeof Y==="string"?Y.trim():Array.isArray(Y)?Y.find((O)=>typeof O==="string")?.trim():"";if(!Q)return{ok:!1,error:"attached-local-client-only",reason:"missing_client_id"};if(!X)return{ok:!1,error:"attached-local-client-only",reason:"missing_proof"};let W=$.ariaLocalHttpClientAuthority;if(!W)return{ok:!1,error:"attached-local-client-only",reason:"no_authority"};if(!W.authorizeAttachedClient(Q,X))return{ok:!1,error:"attached-local-client-only",reason:"invalid_or_expired_lease"};return{ok:!0,clientId:Q}}function Z$($){return Boolean($.headers[Q2]||$.headers[Y2])}function s4($){return $ instanceof Error?$.message:String($)}async function t4($){await new Promise((Z)=>setTimeout(Z,Math.max($,0)))}function X2($,Z){let G=r0.optional().parse(Z);return $.map((Q)=>d0.parse(Q)).filter((Q)=>typeof G?.cursor?.afterCreatedAt==="number"?Q.createdAt>=G.cursor.afterCreatedAt:!0)}async function*r4($,Z,G){if(!$.listDirectClientInbox)throw new T0("no_authority");let Q=new Set,Y=G?.afterCreatedAt??0;while(!0){let X=X2(await $.listDirectClientInbox(Z,{limit:100,unreadOnly:!1,...Y>0?{cursor:{afterCreatedAt:Y}}:{}})),W=!1;for(let O of X){if(Q.has(O.id))continue;Q.add(O.id),Y=Math.max(Y,O.createdAt),W=!0,yield O}if(!W)await t4(1000)}}function e4($){let Z=y0.dirname($);while(!0){if(j0.existsSync(Z)){if(!j0.statSync(Z).isDirectory())throw Error(`[local-control-socket] Socket parent path must resolve through directories: ${Z}`);return}let G=y0.dirname(Z);if(G===Z)return;Z=G}}async function $Z($,Z,G,Q){let Y=$.localControl;switch(Z){case"submitRun":return Q&&Y.submitRunAsAttachedClient?(await Y.submitRunAsAttachedClient(Q,e0.parse(G))).wait():(await $.localControl.submitRun(e0.parse(G))).wait();case"resumeRun":return Q&&Y.resumeRunAsAttachedClient?Y.resumeRunAsAttachedClient(Q,s$.parse(G)):$.localControl.resumeRun(s$.parse(G));case"streamRun":throw Error("streamRun is handled as a streaming socket method");case"sendBestEffort":return Q&&Y.sendBestEffortAsAttachedClient?Y.sendBestEffortAsAttachedClient(Q,t0.parse(G)):$.localControl.sendBestEffort(t0.parse(G));case"sendDurable":return Q&&Y.sendDurableAsAttachedClient?Y.sendDurableAsAttachedClient(Q,t0.parse(G)):$.localControl.sendDurable(t0.parse(G));case"listInbox":return(await $.listInbox(r0.optional().parse(G))).map((X)=>d0.parse(X));case"listPeers":return(await $.listPeers()).map((X)=>o4.parse(X));case"listNearbyPeers":return(await $.listNearbyPeers()).map((X)=>g4.parse(X));case"listAttachedClients":if(!$.listAttachedClients)throw new T0("no_authority");if(!Q)throw new T0("missing_client_id");return(await $.listAttachedClients(Q)).map((X)=>C4.parse(X));case"listDirectClientInbox":if(!$.listDirectClientInbox)throw new T0("no_authority");if(!Q)throw new T0("missing_client_id");return X2(await $.listDirectClientInbox(Q,r0.optional().parse(G)));case"subscribeDirectClientInbox":throw Error("subscribeDirectClientInbox is handled as a streaming socket method");case"getRuntimeStatus":return $.localControl.getRuntimeStatus();case"startAutonomousLoop":if(!$.localControl.startAutonomousLoop)throw Error("Local control autonomous-loop start unavailable");return $.localControl.startAutonomousLoop(d4.optional().parse(G));case"stopAutonomousLoop":if(!$.localControl.stopAutonomousLoop)throw Error("Local control autonomous-loop stop unavailable");return $.localControl.stopAutonomousLoop();case"getRuntimeBootstrap":return $.localControl.getRuntimeBootstrap();case"listPendingPairRequests":return $.localControl.listPendingPairRequests();case"respondToPairRequest":return $.localControl.respondToPairRequest(u4.parse(G));case"createInvite":return $.localControl.createInvite(k4.parse(G));case"listPendingInvites":return(await $.localControl.listPendingInvites()).map((X)=>c4.parse(X));case"acceptInviteToken":return $.localControl.acceptInviteToken(b4.parse(G));case"cancelInvite":return $.localControl.cancelInvite(I4.parse(G));case"invitePeer":return $.localControl.invitePeer(h4.parse(G));case"acceptInvite":return $.localControl.acceptInvite(S4.parse(G));case"directPair":return $.localControl.directPair(q4.parse(G));case"revokePeer":return $.localControl.revokePeer(p4.parse(G));case"repairPeer":return $.localControl.repairPeer(l4.parse(G));case"attachClient":{let X=$2.parse(G),W=Z2.parse(await $.attachClient(X));return $.log?.("info",`[local-control-socket] client attached: clientId=${W.clientId} kind=${X.clientKind}`),W}case"detachClient":{let X=G2.parse(G);return $.log?.("info",`[local-control-socket] client detached: clientId=${X.clientId}`),y4.parse(await $.detachClient(X))}default:throw Error(`Unsupported local control method: ${String(Z)}`)}}async function O2($){let Z=y0.resolve($.socketPath.trim());e4(Z);let G=t$(Z);j0.mkdirSync(y0.dirname(G),{recursive:!0,mode:448});try{j0.rmSync(G,{force:!0})}catch{}let Q=e$.createServer((Y)=>{let X="";Y.setEncoding("utf8");let W=(O,j,V)=>{let z=j instanceof T0;if(z)$.log?.("warn",`[local-control-socket] auth rejected: reason=${j.reason} method=${V?.method??"?"} clientId=${V?.clientId??"?"} requestId=${O??"?"}`);let U=v4.parse({id:O??"local-control-error",ok:!1,error:s4(j),...z?{reason:j.reason}:{},diagnostic:r$(j)});Y.end(`${JSON.stringify(U)}
|
|
2
|
+
`)};Y.on("data",(O)=>{X+=O;let j=X.indexOf(`
|
|
3
|
+
`);if(j===-1)return;let V=X.slice(0,j);X="",(async()=>{let z,U,F;try{let R=JSON.parse(V);z=typeof R.id==="string"?R.id:void 0,U=typeof R.method==="string"?R.method:void 0,F=typeof R.auth?.clientId==="string"?R.auth.clientId:void 0;let J=m4.parse(R);if(J.method==="listAttachedClients"||J.method==="listDirectClientInbox"||J.method==="subscribeDirectClientInbox"){let T=x$.parse(J.auth);if(!$.authorizeAttachedClient?.(T))throw new T0($.authorizeAttachedClient?"invalid_or_expired_lease":"no_authority")}let _=J.auth?x$.parse(J.auth):void 0;if(_&&!$.authorizeAttachedClient?.(_))throw new T0($.authorizeAttachedClient?"invalid_or_expired_lease":"no_authority");if(J.method==="watchInbox"){let T=new AbortController,K=()=>T.abort();Y.once("close",K),Y.once("error",K);let N=await $.listInbox(r0.optional().parse(J.payload));for(let E of N){let B=C0.parse({id:J.id,ok:!0,payload:d0.parse(E)});Y.write(`${JSON.stringify(B)}
|
|
4
|
+
`)}let w=Date.now();while(!T.signal.aborted){if(await new Promise((B)=>{let L=setTimeout(B,500),C=()=>{clearTimeout(L),B()};T.signal.addEventListener("abort",C,{once:!0}),$.onMessageReceived?.(()=>{clearTimeout(L),T.signal.removeEventListener("abort",C),B()})}),T.signal.aborted)break;let E=(await $.listInbox({cursor:{afterCreatedAt:w},limit:100,unreadOnly:!1})).filter((B)=>B.createdAt>w);for(let B of E){let L=C0.parse({id:J.id,ok:!0,payload:d0.parse(B)});if(Y.write(`${JSON.stringify(L)}
|
|
5
|
+
`),B.createdAt>w)w=B.createdAt}}Y.removeListener("close",K),Y.removeListener("error",K),Y.end();return}if(J.method==="streamRun"){let T=$.localControl,K=new AbortController,N=()=>K.abort();Y.once("close",N),Y.once("error",N);let w=_&&T.streamRunAsAttachedClient?T.streamRunAsAttachedClient(_,e0.parse(J.payload),K.signal):$.localControl.streamRun(e0.parse(J.payload),K.signal);for await(let E of w){let B=C0.parse({id:J.id,ok:!0,payload:n4.parse(E)});Y.write(`${JSON.stringify(B)}
|
|
6
|
+
`)}Y.removeListener("close",N),Y.removeListener("error",N),Y.end();return}if(J.method==="subscribeRuntimeEvents"){let T=new AbortController,K=()=>T.abort();Y.once("close",K),Y.once("error",K);for await(let N of $.subscribeRuntimeEvents(i4.optional().parse(J.payload))){if(T.signal.aborted)break;let w=C0.parse({id:J.id,ok:!0,payload:a4.parse(N)});Y.write(`${JSON.stringify(w)}
|
|
7
|
+
`)}Y.removeListener("close",K),Y.removeListener("error",K),Y.end();return}if(J.method==="subscribeDirectClientInbox"){let T=x$.parse(J.auth),K=new AbortController,N=()=>K.abort();Y.once("close",N),Y.once("error",N);let w=$.subscribeDirectClientInbox?.(T,o$.optional().parse(J.payload))??r4($,T,o$.optional().parse(J.payload));for await(let E of w){if(K.signal.aborted)break;let B=C0.parse({id:J.id,ok:!0,payload:d0.parse(E)});Y.write(`${JSON.stringify(B)}
|
|
8
|
+
`)}Y.removeListener("close",N),Y.removeListener("error",N),Y.end();return}if(J.method==="attachClient"){let T=$2.parse(J.payload),K=Z2.parse(await $.attachClient(T)),N=C0.parse({id:J.id,ok:!0,payload:K});if(T.lease){let w=!1,E=()=>{if(w)return;w=!0,$.detachClient(G2.parse({clientId:K.clientId})).catch(()=>{})};Y.once("close",E),Y.once("error",E),$.onClientLeaseSocket?.(K.clientId,Y),Y.write(`${JSON.stringify(N)}
|
|
9
|
+
`);return}Y.end(`${JSON.stringify(N)}
|
|
10
|
+
`);return}let D=await $Z($,J.method,J.payload,J.auth),f=C0.parse({id:J.id,ok:!0,payload:D});Y.end(`${JSON.stringify(f)}
|
|
11
|
+
`)}catch(R){W(z,R,{method:U,clientId:F})}})()}),Y.on("error",()=>{Y.destroy()})});return await new Promise((Y,X)=>{Q.once("error",X),Q.listen(G,()=>Y())}),j0.chmodSync(G,384),{socketPath:G,async close(){await new Promise((Y,X)=>{Q.close((W)=>W?X(W):Y())});try{j0.rmSync(G,{force:!0})}catch{}}}}async function W2($,Z,G,Q){let{submitRunViaRuntimeControl:Y}=await import("./runtime-run-control-0r21xdh5.js");return Y($,Z,G,Q)}async function V2($,Z,G,Q){let{resumeRunViaRuntimeControl:Y}=await import("./runtime-run-control-0r21xdh5.js");return Y($,Z,G,Q)}async function j2(){let[{parseStreamRequest:$,invalidStreamRequest:Z,streamRunViaRuntimeControl:G},Q]=await Promise.all([import("./runtime-run-control-0r21xdh5.js"),import("./shared-4jsvhy6g.js")]);return{parseStreamRequest:$,invalidStreamRequest:Z,streamRunViaRuntimeControl:G,getToolResultHighlight:Q.getToolResultHighlight}}var ZZ={type:"object",required:["task"],properties:{task:{type:"string",minLength:1},arion:{type:"string"},cwd:{type:"string"},history:{type:"array",items:{}},requestedModel:{type:"string",minLength:1},preferredTier:{type:"string",enum:["fast","balanced","powerful","ensemble"]},budget:{type:"number",exclusiveMinimum:0},maxTurns:{type:"integer",minimum:1},autonomy:{type:"string",enum:["minimal","balanced","high","full"]},allowedTools:{type:"array",items:{type:"string"}},deniedTools:{type:"array",items:{type:"string"}},noMemory:{type:"boolean"},systemPrompt:{type:"string"},approvalMode:{type:"string",enum:["pause","approve","deny"]},askUserAnswers:{type:"array",items:{type:"string"}}}};async function z2($){let Z=new w0(10,60000);$.post("/api/v1/run",{schema:{body:ZZ}},async(G,Q)=>{if(!Z.check(G.ip))return Q.status(429).send({success:!1,error:"Rate limit exceeded"});let{task:Y}=G.body;if(!Y||Y.trim()==="")return Q.status(400).send({success:!1,error:"Task is required and cannot be empty"});let X=W0($,G);if(!X.ok&&Z$(G))return Q.status(403).send({success:!1,error:X.error,reason:X.reason});let W=await W2($,G.body,G.log,X.ok?{clientId:X.clientId}:void 0);return Q.status(W.status).send(W.body)})}import{RunState as GZ}from"@aria-cli/aria";var QZ={type:"object",required:["state"],properties:{state:{type:"object"},arion:{type:"string"},cwd:{type:"string"},requestedModel:{type:"string",minLength:1},preferredTier:{type:"string",enum:["fast","balanced","powerful","ensemble"]},budget:{type:"number",exclusiveMinimum:0},maxTurns:{type:"integer",minimum:1},autonomy:{type:"string",enum:["minimal","balanced","high","full"]},allowedTools:{type:"array",items:{type:"string"}},deniedTools:{type:"array",items:{type:"string"}},noMemory:{type:"boolean"},systemPrompt:{type:"string"},approvalMode:{type:"string",enum:["pause","approve","deny"]},askUserAnswers:{type:"array",items:{type:"string"}}}};async function U2($){let Z=new w0(10,60000);$.post("/api/v1/resume",{schema:{body:QZ}},async(G,Q)=>{if(!Z.check(G.ip))return Q.status(429).send({success:!1,error:"Rate limit exceeded"});let{state:Y}=G.body;if(!Y||typeof Y!=="object")return Q.status(400).send({success:!1,error:"state is required"});let X;try{X=GZ.fromJSON(JSON.stringify(Y))}catch(O){return Q.status(400).send({success:!1,error:`Invalid state: ${O instanceof Error?O.message:"validation failed"}`})}if(typeof X.input!=="string"||X.input.trim()==="")return Q.status(400).send({success:!1,error:"state.input must be a non-empty string"});let W=await V2($,{...G.body,state:X},G.log);return Q.status(W.status).send(W.body)})}import{nanoid as _2}from"nanoid";import*as K0 from"fs";import*as B2 from"os";import*as G$ from"crypto";function F2(){return`${process.env.HOME||B2.homedir()}/.aria`}function H2(){return`${F2()}/api-keys.json`}function x2($){return G$.createHash("sha256").update($).digest("hex")}function Q$(){try{let $=H2();if(K0.existsSync($))return JSON.parse(K0.readFileSync($,"utf-8"))}catch($){console.warn("[Server] Failed to load API keys config:",$ instanceof Error?$.message:String($))}return{keys:[]}}function T2($){let Z=F2();if(!K0.existsSync(Z))K0.mkdirSync(Z,{recursive:!0});K0.writeFileSync(H2(),JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async function O9($,Z={}){let G=`aria_${_2(32)}`,Q=_2(12),Y=new Date().toISOString(),X=Q$();if(Z.replaceExistingName)X.keys=X.keys.filter((W)=>W.name!==$);if(Z.prunePrefix&&Z.maxKeysForPrefix!==void 0){let W=Math.max(0,Z.maxKeysForPrefix),O=X.keys.filter((V)=>V.name.startsWith(Z.prunePrefix)).sort((V,z)=>V.createdAt.localeCompare(z.createdAt)),j=Math.max(0,O.length-W+1);if(j>0){let V=new Set(O.slice(0,j).map((z)=>z.id));X.keys=X.keys.filter((z)=>!V.has(z.id))}}return X.keys.push({id:Q,name:$,keyHash:x2(G),createdAt:Y}),T2(X),{key:G,id:Q,name:$,createdAt:Y}}async function L2($){let Z=Q$(),G=x2($),Q=Buffer.from(G,"hex"),Y=!1;for(let X of Z.keys){let W=Buffer.from(X.keyHash,"hex");if(W.length===Q.length&&G$.timingSafeEqual(W,Q))Y=!0}return Y}function D2($){if(!$)return;try{return new URL($,"http://localhost").searchParams.get("api_key")||void 0}catch{return}}var D0=new Map,K2=10,YZ=60000;var J2=1e4;function T$($){let Z=Date.now(),G=D0.get($);if(!G||Z>=G.resetAt){if(!D0.has($))XZ();return D0.set($,{count:1,resetAt:Z+YZ}),!1}return G.count+=1,G.count>=K2}function R2($){let Z=Date.now(),G=D0.get($);if(!G)return!1;if(Z>=G.resetAt)return D0.delete($),!1;return G.count>=K2}function XZ(){if(D0.size<=J2)return;let $=D0.size-J2,Z=0;for(let G of D0.keys()){if(Z>=$)break;D0.delete(G),Z++}}function W9(){return Q$().keys.map(({id:Z,name:G,createdAt:Q})=>({id:Z,name:G,createdAt:Q}))}function V9($){let Z=Q$(),G=Z.keys.length;if(Z.keys=Z.keys.filter((Q)=>Q.id!==$),Z.keys.length<G)return T2(Z),!0;return!1}function t($,Z){if($.readyState===1)$.send(JSON.stringify(Z))}async function M2($){$.get("/api/v1/stream",{websocket:!0,preValidation:async(Z,G)=>{let Q=Z.ip||Z.socket?.remoteAddress||"unknown";if(Q==="127.0.0.1"||Q==="::1"||Q==="::ffff:127.0.0.1")return;if(R2(Q))return G.code(429).send({error:"Too many failed attempts. Try again later."});let X=Z.headers["x-api-key"]||D2(Z.url);if(!X)return T$(Q),G.code(401).send({error:"API key required. Set x-api-key header."});if(!await L2(X))return T$(Q),G.code(401).send({error:"Invalid API key"})}},async(Z,G)=>{let Q=!1,Y=new AbortController,X=!1,W=W0($,G);if(!W.ok&&Z$(G)){t(Z,{type:"error",error:W.error,reason:W.reason}),Z.close();return}let O=W.ok?{clientId:W.clientId}:void 0;Z.on("close",async()=>{Q=!0,Y.abort()}),Z.on("message",(j)=>{if(X){t(Z,{type:"error",error:"Already processing a request"});return}X=!0,(async()=>{let V=!1;try{let z;try{z=JSON.parse(j.toString())}catch{if(!Q)t(Z,{type:"error",error:"Invalid JSON message"});return}let U=await j2(),F=U.parseStreamRequest(z),R=F.request&&$.ariaRunControl?.streamRun?$.ariaRunControl.streamRun(F.request,Y.signal,O):F.request?U.streamRunViaRuntimeControl($,F.request,G.log,Y.signal,O):U.invalidStreamRequest(F.error??"Invalid request"),J=!1,x=!1;$:for await(let _ of R){if(Q)break;switch(_.type){case"text_delta":t(Z,{type:"chunk",content:_.content});break;case"error":if(J=!0,!Q)t(Z,{type:"error",error:_.error.message}),V=!0;break $;case"paused":if(x=!0,!Q)t(Z,{type:"paused",reason:"Run paused: pending tool calls require approval before resume",state:_.state}),V=!0;break $;case"tool_start":t(Z,{type:"tool_start",id:_.id,name:_.name,input:_.input});break;case"tool_result":let D=U.getToolResultHighlight(_.name,_.input,_.result);t(Z,{type:"tool_result",id:_.id,name:_.name,durationMs:_.durationMs,result:_.result,...D.highlighted?{highlighted:D.highlighted,language:D.language}:{}});break;case"usage_update":t(Z,{type:"usage_update",usage:_.usage});break;case"turn_complete":t(Z,{type:"turn_complete",turnNumber:_.turnNumber});break;case"guardrail_rejected":t(Z,{type:"guardrail_rejected",stage:_.stage,message:_.message});break;case"handoff_start":t(Z,{type:"handoff_start",target:_.target,id:_.id});break;case"handoff_result":t(Z,{type:"handoff_result",target:_.target,result:_.result,id:_.id});break;case"span_start":t(Z,{type:"span_start",spanId:_.spanId,spanType:_.spanType,name:_.name});break;case"span_end":t(Z,{type:"span_end",spanId:_.spanId,durationMs:_.durationMs});break;case"pipeline_timing":t(Z,{type:"pipeline_timing",report:_.report});break;case"thinking_end":t(Z,{type:"thinking_end",blocks:_.blocks??[],durationMs:_.durationMs});break;case"native_tool_result":t(Z,{type:"native_tool_result",metadata:_.metadata});break;default:break}}if(X=!1,!V&&!J&&!Q&&!x)t(Z,{type:"done"})}catch(z){if(G.log.error({err:z},"[Server] Sanitized error:"),!Q&&!V)X=!1,t(Z,{type:"error",error:"Internal server error"})}finally{X=!1}})()})})}import{ArionConsultation as OZ}from"@aria-cli/aria/server-arions";var v0=null;function K9(){v0=null}function R9($){v0=$}async function WZ($){if(v0)return v0;let{ariaMemoriaFactory:Z,ariaRouter:G}=$,Q=await w2(Z,G);return v0=new OZ({async chat(X){return{content:(await G.chat({messages:X.messages,tier:X.tier??"balanced"})).content}}},Q,Z),v0}var VZ={type:"object",required:["topic","arions"],properties:{topic:{type:"string",minLength:1},arions:{type:"array",items:{type:"string"},minItems:2}}};async function f2($){let Z=new w0(10,60000);$.post("/api/v1/council",{schema:{body:VZ},attachValidation:!0},async(G,Q)=>{if(!Z.check(G.ip))return Q.status(429).send({error:"Rate limit exceeded"});if(G.validationError){let O=G.validationError.message;if(O.includes("arions")||O.includes("items")||O.includes("fewer"))return Q.status(400).send({error:"Council requires at least 2 Arions"});return Q.status(400).send({error:O})}let{topic:Y,arions:X}=G.body;if(X.length<2)return Q.status(400).send({error:"Council requires at least 2 Arions"});let W=X.find((O)=>E2(O));if(W)return Q.status(400).send({error:`Invalid arion name: "${W}"`});try{let j=await(await WZ($)).council(X,Y),V={topic:j.topic,participants:j.participants,discussion:j.contributions,consensus:j.conclusion,agreements:j.agreements,disagreements:j.disagreements};return Q.send(V)}catch(O){let j=A2(O,G.log);return Q.status(500).send({error:j})}})}import{AcceptInviteRequestSchema as oZ,AcceptInviteResponseSchema as sZ,AcceptInviteTokenRequestSchema as p2,AcceptInviteTokenResponseSchema as d2,AttachedClientViewSchema as tZ,CancelInviteRequestSchema as i2,CancelInviteResponseSchema as a2,CreateInviteRequestSchema as n2,CreateInviteResponseSchema as o2,DirectPairRequestSchema as rZ,DirectPairResponseSchema as eZ,InvitePeerRequestSchema as s2,InvitePeerResultSchema as t2,NearbyPeerViewSchema as $3,PendingInviteViewSchema as r2,PairRequestDecisionSchema as Z3,PairRequestResponseSchema as G3,PendingPairRequestViewSchema as Q3,PeerViewEventSchema as Y3,RepairPeerRequestSchema as e2,RepairPeerResponseSchema as $1,RevokePeerRequestSchema as X3,RevokePeerResponseSchema as O3,RuntimeStatusSchema as Z1,derivePeerStateFromLegacyStatus as W3}from"@aria-cli/tools";import{randomBytes as FZ}from"node:crypto";import*as V$ from"node:fs";import*as z0 from"node:path";import{buildPeerUrl as M$,certFingerprint as S2,createDirectPairEnvelope as HZ,deserializeInviteToken as xZ,decryptToken as TZ,deriveSharedKey as LZ,generateEphemeralKeypair as DZ,isPrivateLanIP as KZ,signEphemeralKey as RZ,signingKeyFingerprint as D$,tlsFetch as i0,verifyEphemeralKeySignature as MZ}from"@aria-cli/aria";import*as b2 from"@aria-cli/wireguard";import{CreateInviteResponseSchema as AZ,PendingInviteViewSchema as EZ,CancelInviteResponseSchema as wZ,AcceptInviteTokenResponseSchema as fZ,NodeIdSchema as a0,PeerTransportIdSchema as C2,PrincipalFingerprintSchema as NZ,SigningPublicKeySchema as A$,TlsCaFingerprintSchema as PZ,RuntimeBootstrapRecordSchema as SZ,RuntimeNodeAdvertisementSchema as bZ,assertSupportedNetworkRuntimeProtocolVersion as I2}from"@aria-cli/tools";import{canonicalizeAuthoritativeDirectEndpoint as jZ}from"@aria-cli/tools";class R0 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="AuthoritativePeerEndpointError"}}function zZ($){if(!($ instanceof Error))return null;if($.message.includes("direct transport endpoint conflict"))return new R0("endpoint_conflict","Direct transport endpoint already owned by another peer principal");if($.message.includes("endpoint revision conflict"))return new R0("conflicting_revision","Rejected conflicting endpoint revision");return null}function UZ($){let Z=new d({ariaHome:$.ariaHome,...typeof $.ownerGeneration==="number"?{ownerGeneration:$.ownerGeneration}:{}});try{return Z.readPeerBinding($.nodeId)}finally{Z.close()}}function _Z($){if(typeof $.ownerGeneration==="number"&&Number.isInteger($.ownerGeneration))return $.ownerGeneration;let Z=new d({ariaHome:$.ariaHome});try{let G=Z.readNodeMetadata()?.nodeId;if(!G)return 1;return Math.max(Z.readRuntimeOwnerRecord(G)?.ownerGeneration??0,Z.readRuntimeBootstrapRecord(G)?.ownerGeneration??0,1)}finally{Z.close()}}function JZ($){let Z=new d({ariaHome:$.ariaHome,ownerGeneration:_Z($)});try{Z.restorePeerBinding($.nodeId,$.previousBinding)}finally{Z.close()}}function BZ($){let Z=jZ({endpointHost:$.endpointHost,endpointPort:$.endpointPort}),G=Z.endpointHost??$.endpointHost.trim();if(!G)throw Error("Authoritative peer endpoint mutation requires a non-empty endpoint host");return{endpointHost:G,endpointPort:Z.endpointPort??$.endpointPort,endpointRevision:$.endpointRevision}}function Y$($){let Z=UZ({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration,nodeId:$.nodeId}),G;try{G=$.authority.commitPeerEndpointProjection({nodeId:$.nodeId,endpointHost:$.endpointHost,endpointPort:$.endpointPort,endpointRevision:$.endpointRevision})}catch(Y){let X=zZ(Y);if(X)throw X;throw Y}if(G.kind==="not_found")throw new R0("not_found","Peer not found");if(G.kind==="stale")throw new R0("stale_revision","Rejected stale endpoint revision");let Q=BZ({endpointHost:$.endpointHost,endpointPort:$.endpointPort,endpointRevision:$.endpointRevision});try{let Y=$.apply({binding:G.binding,...Q,decision:G.kind});return{decision:G.kind,binding:G.binding,projected:Y}}catch(Y){if(G.kind==="applied")JZ({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration,nodeId:$.nodeId,previousBinding:Z});throw Y}}var CZ=new Set(["localhost","127.0.0.1","::1"]),L$=null;async function IZ(){if(!L$)L$=import("@aria-cli/tools").then(($)=>$.DirectPairResponseSchema);return L$}async function N2($,Z){let Q=(await IZ()).safeParse($);if(!Q.success)throw Error(`${Z} returned an invalid direct-pair receipt — upgrade needed`);return Q.data}class Y0 extends Error{statusCode;constructor($,Z){super(Z);this.statusCode=$;this.name="LocalControlRepairError"}}function kZ($){return $==="::1"||$==="localhost"||/^127\./.test($)}function qZ($){if(CZ.has($))return!0;return $.toLowerCase().endsWith(".localhost")}function hZ($){let Z;try{Z=new URL($)}catch{throw Error(`Invalid coordination URL: ${$}`)}let G=Z.hostname.toLowerCase();if(Z.protocol==="https:")return Z;if(Z.protocol==="http:"&&qZ(G))return Z;throw Error(`Insecure coordination URL "${$}". Use https:// (http:// allowed only for localhost).`)}function yZ($){let Z=$.trim().toLowerCase();if(!/^[a-f0-9]{16,128}$/.test(Z))throw Error("Invalid fingerprint format for trusted CA path");return Z}function vZ($){let Z=$.trim().toLowerCase();if(!/^[a-f0-9]{16,128}$/.test(Z))throw Error("Invalid fingerprint format for trusted CA path");return Z}function mZ($,Z){let G=vZ(Z),Q=z0.resolve(z0.join($,"network","trusted-cas")),Y=z0.resolve(z0.join(Q,`${G}.pem`));if(!Y.startsWith(`${Q}${z0.sep}`))throw Error("Trusted CA path escapes trusted-cas directory");return Y}function k2($,Z){if(!$)return;let G=yZ($),Q=D$(Z);if(!(Q===G||Q.startsWith(G)))throw Error("Responder signing key fingerprint mismatch")}function q2($){if(!$.ariaPairControl)throw Error("Runtime pair control unavailable");return $.ariaPairControl}function j$($){if(!$.ariaNetworkManager)throw Error("Network manager unavailable");return $.ariaNetworkManager}function E$($){let Z=$.ariaNetworkManager,G=Z?.getConfig(),Q=Z?.getLocalDisplayNameSnapshot?.()?.trim(),Y=C2.safeParse(G?.publicKey).data,X=typeof G?.signingPublicKey==="string"?A$.safeParse(G.signingPublicKey).data:void 0,W=typeof G?.signingPrivateKey==="string"?G.signingPrivateKey:"";if(!Q)throw Error("Local display snapshot unavailable — pairing requires runtime identity");if(!Y||!X||!W)throw Error("Local signing identity unavailable — pairing requires network keys");return{localDisplayNameSnapshot:Q,publicKey:Y,signingPublicKey:X,signingPrivateKey:W,endpointRevision:typeof G?.endpointRevision==="number"?G.endpointRevision:void 0,coordinationUrl:typeof G?.coordinationUrl==="string"?G.coordinationUrl:void 0,externalEndpoint:G?.externalEndpoint&&typeof G.externalEndpoint==="object"?G.externalEndpoint:void 0,listenPort:typeof G?.listenPort==="number"?G.listenPort:void 0}}function gZ($){let Z=$0($);if(!Z)throw Error("Principal binding authority unavailable — pairing requires nodeId");return Z.resolveLocalNodeIdentity().nodeId}async function h2($,Z){let G=j$($),Q=E$($),Y=await x0($,"Local runtime bootstrap unavailable for invite creation"),X=w$({runtimeConfig:Q,runtimeBootstrap:Y}),W=G.invite(Z.inviteLabel,{...typeof Z.durationMs==="number"?{durationMs:Z.durationMs}:{},controlEndpoint:X,caCert:Y.tls.caCertPem}),O=b2.decodeInviteToken(W.token);return AZ.parse({inviteToken:W.token,pendingInvite:{inviteId:O.tokenNonce,...Z.inviteLabel?{inviteLabel:Z.inviteLabel}:{},createdAt:new Date(O.createdAt).toISOString(),expiresAt:O.expiresAt>0?new Date(O.expiresAt).toISOString():null}})}function y2($){let Z=j$($),G=Z.listPendingInvites;if(!G)throw Error("Network manager listPendingInvites unavailable");return G.call(Z).map((Q)=>EZ.parse({inviteId:Q.inviteId,...Q.inviteLabel?{inviteLabel:Q.inviteLabel}:{},createdAt:new Date(Q.createdAt).toISOString(),...Q.expiresAt===null?{expiresAt:null}:{expiresAt:new Date(Q.expiresAt).toISOString()}}))}async function v2($,Z){let G=j$($),Q=G.acceptInvite?.bind(G);if(!Q)throw Error("Network manager acceptInvite unavailable");let Y=E$($),X=await x0($,"Local runtime bootstrap unavailable for invite acceptance"),W=w$({runtimeConfig:Y,runtimeBootstrap:X}),O=await Q(Z.inviteToken,{controlEndpoint:W});if(O.nodeId&&!O.signingPublicKey)$.log.warn(`[acceptInviteToken] Invite accepted but peer ${String(O.nodeId)} has no signingPublicKey — peer binding not written, peer will not appear in listPeers`);if(O.nodeId&&O.signingPublicKey){let j=$0($);if(j){let V=A$.safeParse(O.signingPublicKey),z=a0.parse(O.nodeId);if(V.success){let U=O$(V.data);if(U){let F=X$({nodeId:z,principalFingerprint:U,signingPublicKey:V.data});if(!("error"in F))j.commitFirstTrustBind(F,{transportPublicKey:C2.parse(O.publicKey),continuityRevision:1,endpointHost:O.endpointHost??void 0,endpointPort:O.endpointPort??void 0,endpointRevision:O.endpointRevision??0,displayNameSnapshot:O.name,controlEndpointHost:O.controlEndpointHost??void 0,controlEndpointPort:O.controlEndpointPort??void 0,controlTlsCaFingerprint:O.controlTlsCaFingerprint??void 0,projectSigningKey:!1})}}}}return fZ.parse({success:!0,nodeId:O.nodeId,...O.name?{displayNameSnapshot:O.name}:{}})}function m2($,Z){let G=j$($),Q=G.cancelInvite;if(!Q)throw Error("Network manager cancelInvite unavailable");return wZ.parse({cancelled:Q.call(G,Z.inviteId),inviteId:Z.inviteId})}function w$($){return{host:R$({peerHost:$.peerHost,externalHost:$.runtimeConfig.externalEndpoint?.address?.trim()??$.runtimeBootstrap.controlEndpoint.host}),port:$.runtimeBootstrap.controlEndpoint.port,tlsCaFingerprint:PZ.parse($.runtimeBootstrap.tls.caFingerprint),tlsServerIdentity:f0($.runtimeBootstrap),protocolVersion:$.runtimeBootstrap.protocolVersion,endpointRevision:$.runtimeConfig.endpointRevision??0}}function P2($){return{host:R$({peerHost:$.peerHost,externalHost:$.runtimeConfig.externalEndpoint?.address?.trim()}),port:$.runtimeConfig.listenPort??$.daemonPort}}function cZ($){let Z=$.server.address();if(typeof Z==="object"&&Z&&typeof Z.port==="number")return Z.port;return $.config.port}function K$($,Z,G){if(!Z||!G)return;let Q=mZ($,Z);V$.mkdirSync(z0.dirname(Q),{recursive:!0}),V$.writeFileSync(Q,G)}function uZ($){try{let Z=JSON.parse($);if(Z.token)return Z.token}catch{}return $}async function lZ($){let{server:Z,request:G,requestedNodeId:Q,localTransportEndpoint:Y,localControlEndpoint:X,localEphemeralPrivateKey:W,ariaDir:O,mode:j,statusPayload:V,canonicalCaCertPem:z,canonicalCaFingerprint:U}=$;if(!V.accepted||V.status==="rejected")throw Error(`${G.displayName} rejected the pairing request`);if(!V.encryptedToken||!V.ephemeralPublicKey||!V.ephemeralKeySignature||!V.nonce||!V.tag)throw Error("Encrypted pairing required but response missing ECDH fields");if(U&&V.caCert&&S2(V.caCert)!==U)throw Error(`${G.displayName} pair response TLS authority drifted from runtime bootstrap`);let F=LZ(W,V.ephemeralPublicKey),R=TZ({ciphertext:V.encryptedToken,nonce:V.nonce,tag:V.tag},F),J=uZ(R),x=xZ(J),_=x?.claims.issuerNodeId,D=A$.safeParse(x?.claims.issuerSigningPublicKey?.trim()),f=D.success?D.data:void 0,T=Q;if(!_)throw Error("Invite token did not carry issuer nodeId");if(!f)throw Error("Invite token did not carry issuer signing public key");if(_!==T)throw Error("Invite token issuer nodeId did not match the requested durable nodeId");if(!MZ(V.ephemeralPublicKey,V.ephemeralKeySignature,f))throw Error("Responder ephemeral key signature invalid — possible MITM");k2(G.principalFingerprint,f);let N=typeof x?.claims.issuerDisplayName==="string"&&x.claims.issuerDisplayName.trim().length>0?x.claims.issuerDisplayName.trim():_,w=await q2(Z).acceptInvite({inviteToken:J,nodeId:a0.parse(_),displayNameSnapshot:N,transportEndpoint:Y,controlEndpoint:X});return K$(O,G.controlEndpoint.tlsCaFingerprint,V.caCert??z),{nodeId:w.nodeId,...w.displayNameSnapshot?{displayNameSnapshot:w.displayNameSnapshot}:{},mode:j,pairingProofState:"pending_verification"}}async function pZ($){let{request:Z,requestedNodeId:G}=$,Q=Z.controlEndpoint.tlsServerIdentity,Y=await i0(M$(Z.controlEndpoint.host,Z.controlEndpoint.port,"/api/v1/runtime/bootstrap"),{expectedCaFingerprint:Z.controlEndpoint.tlsCaFingerprint}),X=await Y.json(),W=typeof X==="object"&&X!==null&&"error"in X&&typeof X.error==="string"?X.error:void 0;if(!Y.ok||W)throw Error(W??`HTTP ${Y.status}`);let O=W$(SZ.parse(X),`${Z.displayName} runtime bootstrap`);if(I2(O.protocolVersion,"runtime bootstrap"),O.nodeId!==G)throw Error(`${Z.displayName} advertised nodeId ${O.nodeId} but the requested durable nodeId was ${G}`);if(O.controlEndpoint.port!==Z.controlEndpoint.port)throw Error(`${Z.displayName} runtime bootstrap control port drifted from discovery`);if(O.tls.caFingerprint!==Z.controlEndpoint.tlsCaFingerprint)throw Error(`${Z.displayName} runtime bootstrap TLS fingerprint mismatched discovery`);let j=f0(O,`${Z.displayName} runtime bootstrap`);if(Q&&j!==Q)throw Error(`${Z.displayName} runtime bootstrap missing pinned TLS identity`);if(Y.peerCaCert&&S2(Y.peerCaCert)!==O.tls.caFingerprint)throw Error(`${Z.displayName} runtime bootstrap CA cert mismatched TLS handshake`);return{bootstrap:O,tlsIdentity:j}}async function dZ($){let Z=f0($.remoteRuntimeBootstrap,`${$.request.displayName} runtime bootstrap`),G=await i0(M$($.request.controlEndpoint.host,$.request.controlEndpoint.port,"/api/v1/runtime/node"),{ca:$.remoteRuntimeBootstrap.tls.caCertPem,expectedTlsIdentity:Z}),Q=await G.json();if(!G.ok){let X=typeof Q==="object"&&Q!==null&&"error"in Q&&typeof Q.error==="string"?Q.error:`HTTP ${G.status}`;throw Error(X)}let Y=bZ.parse(Q);if(Y.nodeId!==$.requestedNodeId)throw Error(`${$.request.displayName} advertised nodeId ${Y.nodeId} but the requested durable nodeId was ${$.requestedNodeId}`);return Y}async function g2($,Z){let G=$.ariaBasePath??z0.join(process.env.HOME??"",".aria"),Q=gZ($),Y=E$($),X=cZ($),W=await x0($,"Local runtime bootstrap"),O=w$({runtimeConfig:Y,runtimeBootstrap:W,peerHost:Z.controlEndpoint.host}),j=P2({runtimeConfig:Y,daemonPort:X,peerHost:Z.controlEndpoint.host}),V=Z.nodeId.trim();if(I2(Z.controlEndpoint.protocolVersion,"invite control endpoint"),Z.transport!=="wan"&&!kZ(Z.controlEndpoint.host)&&!KZ(Z.controlEndpoint.host))throw Error(`Rejected: ${Z.controlEndpoint.host} is not a private LAN address.`);let z=DZ(),U=RZ(z.publicKey,Buffer.from(Y.signingPrivateKey,"base64")),F={displayNameSnapshot:W.displayNameSnapshot??Y.localDisplayNameSnapshot,nodeId:Q,signingPublicKey:W.signingPublicKey,port:X,ephemeralPublicKey:z.publicKey,ephemeralKeySignature:U,caCert:W.tls.caCertPem};if(Z.transport==="wan"){if(!Z.principalFingerprint)throw Error("WAN peer identity is missing signing fingerprint; pairing refused");if(!Y.coordinationUrl)throw Error("No coordination server configured for WAN pairing");let E=hZ(Y.coordinationUrl),B=await i0(new URL("/api/v1/pair/relay",E).toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetNodeId:V,...F})}),L=await B.json();if(!B.ok||L.error||!L.requestId)throw Error(L.error??`HTTP ${B.status}`);let C=await i0(new URL(`/api/v1/pair/status/${L.requestId}`,E).toString()),g=await C.json();if(!C.ok||g.error)throw Error(g.error??`HTTP ${C.status}`);return lZ({server:$,request:Z,requestedNodeId:V,localTransportEndpoint:j,localControlEndpoint:O,localEphemeralPrivateKey:z.privateKey,ariaDir:G,mode:"wan_pair",statusPayload:g})}if(!Z.controlEndpoint.tlsCaFingerprint)throw Error(`${Z.displayName} did not advertise TLS fingerprint — upgrade needed`);let{bootstrap:R,tlsIdentity:J}=await pZ({request:Z,requestedNodeId:V});K$(G,R.tls.caFingerprint,R.tls.caCertPem);let x=await dZ({request:Z,requestedNodeId:V,remoteRuntimeBootstrap:R});k2(Z.principalFingerprint,x.signingPublicKey);let _=x.displayNameSnapshot?.trim(),D=FZ(32).toString("base64"),f=HZ({principalNodeId:a0.parse(Q),targetNodeId:x.nodeId,targetSigningPublicKey:x.signingPublicKey,targetTransportPublicKey:x.transportPublicKey,..._?{targetDisplayNameSnapshot:_}:{},signingPublicKey:Y.signingPublicKey,signingPrivateKey:Y.signingPrivateKey,payload:{peerNodeId:a0.parse(Q),principalFingerprint:NZ.parse(D$(Y.signingPublicKey)),peerWgPubkey:Y.publicKey,peerSigningPubkey:Y.signingPublicKey,transportEndpoint:P2({runtimeConfig:Y,daemonPort:X,peerHost:Z.controlEndpoint.host}),controlEndpoint:O,peerDisplayName:Y.localDisplayNameSnapshot,psk:D}}),T=await i0(M$(Z.controlEndpoint.host,Z.controlEndpoint.port,"/api/v1/pair/direct"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({envelope:f}),ca:R.tls.caCertPem,expectedTlsIdentity:J}),K=await T.json(),N=typeof K==="object"&&K!==null&&"error"in K&&typeof K.error==="string"?K.error:void 0;if(!T.ok||N)throw Error(N??`HTTP ${T.status}`);await N2(K,Z.displayName);let w=await q2($).directPair({peerNodeId:x.nodeId,principalFingerprint:D$(x.signingPublicKey),peerWgPubkey:x.transportPublicKey,peerSigningPubkey:x.signingPublicKey,transportEndpoint:{host:Z.controlEndpoint.host,port:x.transportEndpoint.port},controlEndpoint:Z.controlEndpoint,..._?{peerDisplayName:_}:{},psk:D});return await N2(w,_??x.nodeId),K$(G,R.tls.caFingerprint,R.tls.caCertPem),{nodeId:x.nodeId,..._?{displayNameSnapshot:_}:{},mode:"lan_direct",pairingProofState:"pending_verification"}}function c2($,Z){let G=$.ariaNetworkManager;if(!G?.applyPeerRepair)throw new Y0(503,"Peer repair is unavailable — authoritative repair mutator not present");let Q=G.applyPeerRepair.bind(G),Y={nodeId:Z.nodeId,endpointHost:Z.endpointHost,endpointPort:Z.endpointPort,endpointRevision:Z.endpointRevision},X=$0($,{ownerGeneration:$.ariaOwnerGeneration})?.resolveRemoteBinding(Z.nodeId),W=(z)=>{if(!z.repaired){let U=String(z.errorCode);if(U==="not_found")throw new Y0(404,"Peer not found");if(U==="revoked")throw new Y0(409,"Peer revoked");if(U==="stale_revision")throw new Y0(409,"Peer repair rejected stale endpoint revision");if(U==="conflicting_revision")throw new Y0(409,"Peer repair rejected conflicting endpoint revision");throw new Y0(409,`Peer ${U} cannot complete repair while awaiting state convergence`)}return z},O=()=>{let z=Q(Y);if(!z.repaired)W(z);throw new Y0(503,"Peer repair is unavailable — durable peer binding missing")};if(typeof Z.endpointRevision!=="number"||!Number.isInteger(Z.endpointRevision)||Z.endpointRevision<0)throw new Y0(400,"Peer repair requires a non-negative endpointRevision");let j=$0($,{ownerGeneration:$.ariaOwnerGeneration});if(!j)throw new Y0(503,"Peer repair is unavailable — principal binding authority not present");let V=$.ariaBasePath;if(!V)throw new Y0(503,"Peer repair is unavailable — ARIA base path not present");try{let z=Y$({ariaHome:V,ownerGeneration:$.ariaOwnerGeneration,authority:j,nodeId:Z.nodeId,endpointHost:Z.endpointHost,endpointPort:Z.endpointPort,endpointRevision:Z.endpointRevision,apply:({endpointHost:U,endpointPort:F,endpointRevision:R})=>W(Q({nodeId:Z.nodeId,endpointHost:U,endpointPort:F,endpointRevision:R}))}).projected;return{repaired:!0,nodeId:a0.parse(z.nodeId),endpointHost:z.endpointHost,endpointPort:z.endpointPort,endpointRevision:z.endpointRevision}}catch(z){if(z instanceof R0){if(z.code==="not_found"){if(!X)throw new Y0(404,z.message);O()}throw new Y0(409,`Peer repair ${z.message.toLowerCase()}`)}if(z instanceof Y0)throw z;throw z}}import{NodeIdSchema as u2,PeerTransportIdSchema as l2}from"@aria-cli/tools/network-runtime";function iZ($){let Z=$.ariaBasePath?.trim();if(!Z)return new Map;let G;try{return G=new d({ariaHome:Z}),new Map(G.listPeerBindings().flatMap((Q)=>{let Y=u2.safeParse(Q.nodeId?.trim()),X=l2.safeParse(Q.transportPublicKey?.trim());if(!Y.success||!X.success)return[];return[[Y.data,{nodeId:Y.data,transportPublicKey:X.data,...Q.displayNameSnapshot?{displayNameSnapshot:Q.displayNameSnapshot}:{}}]]}))}catch{return new Map}finally{G?.close()}}function aZ($,Z){let G=u2.safeParse($.nodeId);if(!G.success)return null;let Q=G.data,Y=Z.get(Q);if(!Y)return null;if(Y.transportPublicKey!==$.publicKey)return null;return{nodeId:Y.nodeId,transportPublicKey:l2.parse($.publicKey),displayNameSnapshot:Y.displayNameSnapshot??$.name,status:$.status,endpointHost:$.endpointHost,endpointPort:$.endpointPort,endpointRevision:$.endpointRevision??0,lastHandshake:$.lastHandshake,createdAt:$.createdAt,updatedAt:$.updatedAt??$.createdAt}}function nZ($){let Z=$.ariaNetworkManager;if(!Z)return[];let G=iZ($);return Z.listPeers().flatMap((Q)=>{let Y=aZ(Q,G);return Y?[Y]:[]})}function z$($){if($.ariaNetworkReadControl?.listPeers)return;U0($,"ariaNetworkReadControl",{listPeers:async()=>nZ($)})}function G1($,Z){let G=$.headers.host;if(typeof G==="string"){let Q=G.split(":").at(-1);if(Q){let Y=Number.parseInt(Q,10);if(Number.isFinite(Y)&&Y>0){if((Y===80||Y===443)&&Z>0)return Z;return Y}}}return Z}class m0 extends Error{statusCode;constructor($,Z){super(Z);this.statusCode=$;this.name="LocalControlRouteError"}}function M0($,Z=400){if($ instanceof m0)return $;if(typeof $==="object"&&$!==null&&"statusCode"in $&&typeof $.statusCode==="number")return new m0($.statusCode,$ instanceof Error?$.message:String($));return new m0(Z,$ instanceof Error?$.message:String($))}async function Q1($){z$($);let Z=(Y)=>W0($,Y);U0($,"ariaPeerLocalControl",{listPeers:async()=>{return(await $.ariaNetworkReadControl?.listPeers()??[]).map((X)=>{let W=W3(X);return Y3.parse({nodeId:X.nodeId,transportPublicKey:X.transportPublicKey,displayNameSnapshot:X.displayNameSnapshot,identityState:W.identityState,transportState:W.transportState,endpointRevision:X.endpointRevision,updatedAt:new Date(X.updatedAt).toISOString(),lastSeenAt:X.lastHandshake?new Date(X.lastHandshake).toISOString():void 0})})},listNearbyPeers:async()=>[],createInvite:async(Y)=>{let X=n2.parse(Y);return o2.parse(await h2($,X))},listPendingInvites:async()=>y2($).map((Y)=>r2.parse(Y)),acceptInviteToken:async(Y)=>{let X=p2.parse(Y);return d2.parse(await v2($,X))},cancelInvite:async(Y)=>{let X=i2.parse(Y);return a2.parse(m2($,X))},invitePeer:async(Y)=>{let X=s2.parse(Y);return t2.parse(await g2($,X))},repairPeer:async(Y)=>{let X=e2.parse(Y);return $1.parse(c2($,X))}});let G=()=>{let Y=$.ariaPairControl;if(!Y)throw new m0(503,"Local control pair surface unavailable");return Y},Q=()=>{let Y=$.ariaNetworkAdminControl;if(!Y)throw new m0(503,"Local control network admin surface unavailable");return Y};$.get("/api/v1/local-control/runtime-status",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});if($.ariaRuntimeLocalControl?.getRuntimeStatus){let V=await $.ariaRuntimeLocalControl.getRuntimeStatus();return X.send(Z1.parse({...V,port:G1(Y,V.port)}))}let j=$0($)?.resolveLocalNodeIdentity().nodeId;if(!j||!$.ariaRuntimeId)return X.status(503).send({error:"Runtime status unavailable"});return X.send(Z1.parse({nodeId:j,runtimeId:$.ariaRuntimeId,port:G1(Y,$.config.port),attachedClients:$.ariaAttachedClientControl?.countAttachedClients(),autonomousLoop:{status:"stopped",intervalMs:null,lastWakeTickAt:null,lastCheckpointResult:"never",safetyPolicySummary:{},ownerClientKind:null}}))}),$.get("/api/v1/local-control/attached-clients",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});let O=$.ariaAttachedClientControl;if(!O)return X.status(503).send({error:"Attached client directory unavailable"});let j=await O.listAttachedClients({clientId:W.clientId});return X.send({clients:j.map((V)=>tZ.parse(V))})}),$.get("/api/v1/local-control/peers",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});let O=await $.ariaPeerLocalControl?.listPeers();return X.send({peers:O??[]})}),$.get("/api/v1/local-control/nearby-peers",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});let O=await $.ariaPeerLocalControl?.listNearbyPeers();return X.send({peers:(O??[]).map((j)=>$3.parse(j))})}),$.get("/api/v1/local-control/pending-pair-requests",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=await G().listPendingPairRequests();return X.send({requests:O.map((j)=>Q3.parse(j))})}catch(O){let j=M0(O,500);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/respond-pair-request",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=Z3.parse(Y.body),j=await G().respondToPairRequest(O);return X.send(G3.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.get("/api/v1/local-control/invites",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=await $.ariaPeerLocalControl?.listPendingInvites();return X.send({invites:(O??[]).map((j)=>r2.parse(j))})}catch(O){let j=M0(O,500);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/invites",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=n2.parse(Y.body),j=await $.ariaPeerLocalControl?.createInvite(O);return X.send(o2.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/accept-invite-token",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=p2.parse(Y.body),j=await $.ariaPeerLocalControl?.acceptInviteToken(O);return X.send(d2.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/cancel-invite",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=i2.parse(Y.body),j=await $.ariaPeerLocalControl?.cancelInvite(O);return X.send(a2.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/peer-invite",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=s2.parse(Y.body),j=await $.ariaPeerLocalControl?.invitePeer(O);return X.send(t2.parse(j))}catch(O){return X.status(400).send({error:O instanceof Error?O.message:String(O)})}}),$.post("/api/v1/local-control/accept-invite",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=oZ.parse(Y.body),j=await G().acceptInvite(O);return X.send(sZ.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/direct-pair",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=rZ.parse(Y.body),j=await G().directPair(O,Y);return X.send(eZ.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/revoke-peer",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=X3.parse(Y.body),j=await Q().revokePeer(O);return X.send(O3.parse(j))}catch(O){let j=M0(O);return X.status(j.statusCode).send({error:j.message})}}),$.post("/api/v1/local-control/repair-peer",async(Y,X)=>{let W=Z(Y);if(!W.ok)return X.status(403).send({error:W.error,reason:W.reason});try{let O=e2.parse(Y.body),j=await $.ariaPeerLocalControl?.repairPeer(O);return X.send($1.parse(j))}catch(O){let j=O instanceof Y0?O.statusCode:400;return X.status(j).send({error:O instanceof Error?O.message:String(O)})}})}import{RuntimeBootstrapRecordSchema as V3}from"@aria-cli/tools";async function Y1($){$.get("/api/v1/runtime/bootstrap",async(Z,G)=>{let Q;try{Q=await x0($,"Runtime bootstrap")}catch{return G.status(503).send({error:"Runtime bootstrap unavailable"})}return G.send(V3.parse(Q))})}import{RuntimeNodeAdvertisementSchema as j3}from"@aria-cli/tools";import{resolveAdvertisedDiscoveryHosts as z3}from"@aria-cli/aria";function U3($){if(typeof $!=="string")return;let Z=$.trim();return Z.length>0?Z:void 0}async function X1($){$.get("/api/v1/runtime/node",async(Z,G)=>{let Q=await x0($,"Runtime node advertisement"),Y=Q.nodeId,X=f0(Q),W=Q.signingPublicKey,O=Q.transportPublicKey,j=$.ariaNetworkManager,V=j?.getConfig?.()??null,z=typeof V?.listenPort==="number"?V.listenPort:Q.transportEndpoint.port,U=V?.externalEndpoint&&typeof V.externalEndpoint==="object"&&!Array.isArray(V.externalEndpoint)?U3(V.externalEndpoint.address):void 0,F=z3({controlHost:Q.controlEndpoint.host,externalHost:U});return G.send(j3.parse({nodeId:Y,principalFingerprint:X,signingPublicKey:W,transportPublicKey:O,transportEndpoint:{host:U??Q.transportEndpoint.host,port:z},controlEndpoint:{host:Q.controlEndpoint.host,port:Q.controlEndpoint.port,tlsCaFingerprint:Q.tls.caFingerprint,tlsServerIdentity:X,protocolVersion:Q.protocolVersion,endpointRevision:typeof V?.endpointRevision==="number"?V.endpointRevision:0},displayNameSnapshot:j?.getLocalDisplayNameSnapshot?.()?.trim()||Q.displayNameSnapshot||void 0,protocolVersion:Q.protocolVersion,publicationRevision:Q.bootstrapRevision,...F.length>0?{advertisedHosts:F}:{}}))})}import*as n0 from"node:crypto";import*as U$ from"node:fs";import*as P$ from"node:path";import{ControlEndpointAdvertisementSchema as x3,InboxAddressSchema as I0,JoinRouteBodySchema as T3,JoinRouteBodyJsonSchema as L3,NETWORK_RUNTIME_PROTOCOL_VERSION as D3,NodeIdSchema as f$,OutboundMessageSchema as W1,SigningPublicKeySchema as K3,createAckedDeliveryReceipt as V1,PersistedInboxEventSchema as j1,RuntimeDeliveryReceiptSchema as z1,RuntimeQueuedReceiptSchema as U1,assertSupportedNetworkRuntimeProtocolVersion as R3}from"@aria-cli/tools";import{ControlEndpointAdvertisementSchema as _3,NodeIdSchema as J3,PrincipalFingerprintSchema as B3,SigningPublicKeySchema as F3}from"@aria-cli/tools";function O1($){if($.ariaJoinControl?.completeJoin)return;U0($,"ariaJoinControl",{completeJoin:async(Z)=>{let G=$.ariaNetworkManager;if(!G?.completeJoin)throw Error("Network manager not available for join completion");let Q=await x0($,"Local runtime bootstrap unavailable for join completion"),Y=$0($);if(!Y)throw Error("Principal binding authority unavailable for join completion");let X=J3.parse(Z.nodeId),W=B3.parse(Z.principalFingerprint),O=F3.parse(Z.peerSigningKey),j=X$({nodeId:X,principalFingerprint:W,signingPublicKey:O});if("error"in j)throw Error("Join principalFingerprint must match the signing public key fingerprint");let V=_3.safeParse(Z.peerControlEndpoint);if(!V.success)throw Error("Join control endpoint must advertise tlsServerIdentity");let z=V.data;if(z.tlsServerIdentity!==W)throw Error("Join control endpoint tlsServerIdentity must match the signing principal fingerprint");let U=Z.displayNameSnapshot?.trim()&&Z.displayNameSnapshot.trim().length>0?Z.displayNameSnapshot.trim():X,F=new d({ariaHome:$.ariaBasePath,ownerGeneration:Q.ownerGeneration}),R=F.readPeerBinding(X);F.close();let J=Y.commitFirstTrustBind(j,{transportPublicKey:Z.peerPublicKey,continuityRevision:1,endpointHost:Z.peerTransportEndpoint.host,endpointPort:Z.peerTransportEndpoint.port,endpointRevision:z.endpointRevision??0,displayNameSnapshot:U,controlEndpointHost:z.host,controlEndpointPort:z.port,controlTlsCaFingerprint:z.tlsCaFingerprint,projectSigningKey:!1});try{await G.completeJoin({nodeId:X,principalFingerprint:W,peerPublicKey:Z.peerPublicKey,peerSigningKey:Z.peerSigningKey,peerTransportEndpoint:Z.peerTransportEndpoint,peerControlEndpoint:z,displayNameSnapshot:U,inviteTokenNonce:Z.inviteTokenNonce})}catch(x){throw H3({ariaHome:$.ariaBasePath,ownerGeneration:Q.ownerGeneration,nodeId:X,previousBinding:R}),x}return $.ariaPeerSigningKeyStore?.set?.({nodeId:J.nodeId,displayName:J.displayNameSnapshot??J.nodeId,signingPublicKey:Z.peerSigningKey}),{effectiveName:J.displayNameSnapshot??U}}})}function H3($){let Z=new d({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration});try{if($.previousBinding)Z.commitPairContinuity($.previousBinding);else Z.deletePeerBinding($.nodeId)}finally{Z.close()}}var N0=new Map,_1=1000,J1=3;var g0=new Map,B1=60000,F1=4,M3=1e4;function _0($){let Z=P$.join(process.env.HOME??"/tmp",".aria","audit");try{U$.mkdirSync(Z,{recursive:!0});let G={...$,timestamp:Date.now(),event:"join_attempt"};U$.appendFileSync(P$.join(Z,"network.jsonl"),JSON.stringify(G)+`
|
|
12
|
+
`)}catch{}}class _$ extends Error{constructor(){super("Message store not available");this.name="RuntimeMessageStoreUnavailableError"}}function A3($){return x3.shape.tlsServerIdentity.parse(Reflect.get($,"principalFingerprint"))}function E3($){let{ariaMessageStore:Z,ariaNodeId:G}=$;if(!Z||!G)throw new _$;return{messageStore:Z,inboxAddress:I0.parse({kind:"node",nodeId:G})}}function N$($,Z){let G=$.ariaMessageStore;if(!G)throw new _$;return{messageStore:G,inboxAddress:I0.parse({kind:"client",clientId:Z})}}function w3($){let Z=$.ariaRuntimeOutbox;if(!Z)throw Error("Runtime outbox not available");return Z}function H1($,Z){let G=w3($),Q=G[Z];if(typeof Q!=="function")throw Error(`Runtime outbox ${Z} not available`);return Q.bind(G)}async function L1($){U0($,"ariaRuntimeMessageControl",{sendBestEffort:async(Z)=>{let G=W1.parse(Z);if(G.recipientInbox?.kind==="client"){let{messageStore:Y}=N$($,G.recipientInbox.clientId),X=G.rawMessage;if(!X.id||!X.sender?.id||!X.sender?.name||!X.sender?.type||!X.recipient?.id||!X.recipient?.name||!X.type||!X.content)throw Error("Client-targeted delivery requires a complete rawMessage");let W={id:X.id,sender:{id:X.sender.id,name:X.sender.name,type:X.sender.type},recipient:{id:X.recipient.id,name:X.recipient.name},replyTo:X.replyTo,correlationId:X.correlationId,questId:X.questId,type:X.type,content:X.content,metadata:X.metadata,priority:X.priority,signature:X.signature,timestamp:X.timestamp??Date.now()};return Y.store(W,"received",G.recipientInbox),U1.parse(V1({transport:"local_runtime",sessionState:"none",deliveryReadiness:"can_queue_only"}))}let Q=await H1($,"sendBestEffort")(G.rawMessage);return U1.parse(Q)},sendDurable:async(Z)=>{let G=W1.parse(Z);if(G.recipientInbox?.kind==="client"){let{messageStore:Y}=N$($,G.recipientInbox.clientId),X=G.rawMessage;if(!X.id||!X.sender?.id||!X.sender?.name||!X.sender?.type||!X.recipient?.id||!X.recipient?.name||!X.type||!X.content)throw Error("Client-targeted delivery requires a complete rawMessage");let W=X.timestamp??Date.now(),O={id:X.id,sender:{id:X.sender.id,name:X.sender.name,type:X.sender.type},recipient:{id:X.recipient.id,name:X.recipient.name},replyTo:X.replyTo,correlationId:X.correlationId,questId:X.questId,type:X.type,content:X.content,metadata:X.metadata,priority:X.priority,signature:X.signature,timestamp:W};return Y.store(O,"received",G.recipientInbox),z1.parse({...V1({transport:"local_runtime",sessionState:"none",deliveryReadiness:"can_queue_only"}),storedAt:W})}let Q=await H1($,"sendDurable")(G.rawMessage);return z1.parse(Q)},listDirectClientInbox:async(Z)=>{let{messageStore:G}=N$($,Z.clientId),Q=I0.parse({kind:"client",clientId:Z.clientId}),Y=Math.min(Math.max(Z.limit??100,1),1000),X=Z.unreadOnly??!1,W=X?G.getUnreadForInbox(Q,Y):G.searchInbox(Q,"",{limit:Y}),O=$.ariaNodeId,j=O?X?G.getUnreadForInbox(I0.parse({kind:"node",nodeId:O}),Y):G.searchInbox(I0.parse({kind:"node",nodeId:O}),"",{limit:Y}):[],V=new Set;return[...W,...j].filter((U)=>{if(V.has(U.id))return!1;return V.add(U.id),!0}).sort((U,F)=>U.created_at-F.created_at).slice(0,Y).map((U)=>{let F=null;if(U.metadata)try{let _=JSON.parse(U.metadata).senderInbox;if(_?.kind==="client"&&_.clientId)F=_.clientId}catch{}let R=U.recipient_id,J=typeof R==="string"&&R.startsWith("client-")?R:null;return j1.parse({id:U.id,senderNodeId:U.sender_id,senderDisplayNameSnapshot:U.sender_name,senderType:"sender_type"in U&&typeof U.sender_type==="string"?U.sender_type:void 0,senderClientId:F,recipientClientId:J,inboxAddress:I0.parse({kind:U.inbox_address_kind,...U.inbox_address_kind==="client"?{clientId:U.inbox_address_id}:{nodeId:f$.parse(U.inbox_address_id)}}),type:U.type,content:U.content,priority:"priority"in U&&typeof U.priority==="number"?U.priority:0,createdAt:U.created_at,correlationId:"correlation_id"in U&&typeof U.correlation_id<"u"?U.correlation_id:void 0,replyTo:"reply_to"in U&&typeof U.reply_to<"u"?U.reply_to:void 0})})},listInbox:async(Z)=>{let{messageStore:G,inboxAddress:Q}=E3($),Y=Math.min(Math.max(Z?.limit??100,1),1000);return(Z?.unreadOnly??!1?G.getUnreadForInbox(Q,Y):G.searchInbox(Q,"",{limit:Y})).map((O)=>j1.parse({id:O.id,senderNodeId:O.sender_id,senderDisplayNameSnapshot:O.sender_name,senderType:"sender_type"in O&&typeof O.sender_type==="string"?O.sender_type:void 0,inboxAddress:I0.parse({kind:O.inbox_address_kind,...O.inbox_address_kind==="client"?{clientId:O.inbox_address_id}:{nodeId:f$.parse(O.inbox_address_id)}}),type:O.type,content:O.content,priority:"priority"in O&&typeof O.priority==="number"?O.priority:0,createdAt:O.created_at,correlationId:"correlation_id"in O&&typeof O.correlation_id<"u"?O.correlation_id:void 0,replyTo:"reply_to"in O&&typeof O.reply_to<"u"?O.reply_to:void 0}))}}),O1($),$.get("/api/v1/join/challenge",async(Z,G)=>{let Q=Date.now();for(let[W,O]of g0)if(Q-O.createdAt>B1)g0.delete(W);if(g0.size>M3)return G.status(429).send({error:"Too many pending challenges"});let Y=n0.randomBytes(32).toString("hex"),X=n0.randomBytes(16).toString("hex");return g0.set(X,{challenge:Y,createdAt:Q}),G.send({challenge:`${X}:${Y}`,difficulty:F1,expiresIn:B1})}),$.post("/api/v1/join",{schema:{body:L3}},async(Z,G)=>{let Q=`join:${Z.ip}:${Z.body.nodeId}`,Y=Date.now();if(N0.size>_1/2){for(let[w,E]of N0.entries())if(E.resetAt<=Y)N0.delete(w)}let X=N0.get(Q);if(X&&Y<X.resetAt){if(X.count++,X.count>J1)return _0({peerLabel:Z.body.displayNameSnapshot??Z.body.nodeId,ip:Z.ip,success:!1,reason:"rate_limited"}),G.status(429).send({error:`Join rate limit exceeded (${J1}/min)`})}else{N0.set(Q,{count:1,resetAt:Y+60000});while(N0.size>_1){let w=N0.keys().next().value;if(!w)break;N0.delete(w)}}{let w=Z.body.proofOfWork.indexOf(":");if(w<0)return G.status(400).send({error:"Invalid proof-of-work format"});let E=Z.body.proofOfWork.slice(0,w),B=Z.body.proofOfWork.slice(w+1),L=g0.get(E);if(!L)return G.status(400).send({error:"Invalid or expired proof-of-work challenge"});g0.delete(E);let C=n0.createHash("sha256").update(L.challenge+B).digest("hex"),g="0".repeat(F1);if(!C.startsWith(g))return G.status(400).send({error:"Proof-of-work solution invalid"})}let W=T3.parse(Z.body),{peerPublicKey:O,signingPublicKey:j,nodeId:V,transportEndpoint:z,controlEndpoint:U,displayNameSnapshot:F,inviteTokenNonce:R,protocolVersion:J}=W,x=A3(Z.body);if(!U)return G.status(400).send({error:"Join requires a control endpoint advertisement"});let _=f$.parse(V),D=K3.parse(j);if($.ariaRevocationStore?.isPeerRevoked?.(_))return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"peer_principal_revoked"}),G.status(403).send({error:"Peer has been revoked — contact network administrator to re-invite"});let f;try{f=R3(J,"join")}catch(w){return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:`unsupported_protocol_version_${String(J)}`}),G.status(400).send({error:w.message})}let T=$.ariaJoinControl?.completeJoin;if(!T)return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"join_control_unavailable"}),G.status(503).send({error:"Join control not available"});let K;try{K=(await T({nodeId:_,principalFingerprint:x,peerPublicKey:O,peerSigningKey:D,peerTransportEndpoint:z,peerControlEndpoint:U,displayNameSnapshot:F,inviteTokenNonce:R})).effectiveName}catch(w){let E=String(F??V).replace(/[\x00-\x1f]/g,"").slice(0,64),B=String(w.message??"").replace(/[\x00-\x1f]/g,"").slice(0,200);if(Z.log.warn(`completeJoin failed for ${E}: ${B}`),B==="Network manager not available for join completion")return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"network_manager_unavailable"}),G.status(503).send({error:B});if(B==="Invalid signing public key")return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"invalid_signing_public_key"}),G.status(400).send({error:B});if(B==="Join principalFingerprint must match the signing public key fingerprint")return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"principal_fingerprint_mismatch"}),G.status(400).send({error:B});if(B==="Join control endpoint must advertise tlsServerIdentity")return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"missing_control_tls_identity"}),G.status(400).send({error:B});if(B==="Join control endpoint tlsServerIdentity must match the signing principal fingerprint")return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"control_tls_identity_mismatch"}),G.status(400).send({error:B});return _0({peerLabel:F??V,ip:Z.ip,success:!1,reason:"join_rejected"}),G.status(403).send({error:"Join rejected"})}_0({peerLabel:K,ip:Z.ip,success:!0});let N=Math.min(f,D3);return G.status(200).send({joined:!0,nodeId:V,...K?{displayNameSnapshot:K}:{},protocolVersion:N})}),$.get("/api/v1/messages",async(Z,G)=>{let Q=W0($,Z);if(!Q.ok)return G.status(403).send({error:Q.error,reason:Q.reason});if(!$.ariaRuntimeMessageControl)return G.status(503).send({error:"Message store not available"});let Y=Math.min(Math.max(parseInt(Z.query.limit??"20",10)||20,1),1000),X=Z.query.unread!=="false",W;try{W=await $.ariaRuntimeMessageControl.listInbox({limit:Y,unreadOnly:X})}catch(O){if(O instanceof _$)return G.status(503).send({error:"Message store not available"});throw O}return G.send({messages:W,count:W.length})}),$.get("/api/v1/messages/direct-client",async(Z,G)=>{let Q=W0($,Z);if(!Q.ok)return G.status(403).send({error:Q.error,reason:Q.reason});if(!$.ariaRuntimeMessageControl?.listDirectClientInbox)return G.status(503).send({error:"Direct client inbox not available"});let Y=Math.min(Math.max(parseInt(Z.query.limit??"20",10)||20,1),1000),X=Z.query.unread!=="false",W=await $.ariaRuntimeMessageControl.listDirectClientInbox({clientId:Q.clientId,limit:Y,unreadOnly:X});return G.send({messages:W,count:W.length})}),$.post("/api/v1/message/relay",async(Z,G)=>{let Q=W0($,Z);if(!Q.ok)return G.status(403).send({error:Q.error,reason:Q.reason});if(!$.ariaRuntimeMessageControl)return G.status(503).send({error:"Runtime outbox not available",delivered:!1});try{let Y=Z.body._rawMessage;if(Y&&Y.id&&Y.sender&&Y.recipient&&Y.content){let X=T1(Y,x1(Q.clientId)),W=Z.body.deliveryMode==="best_effort"?await $.ariaRuntimeMessageControl.sendBestEffort({rawMessage:X}):await $.ariaRuntimeMessageControl.sendDurable({rawMessage:X});return G.send({id:X.id,...W})}return G.status(400).send({error:"Missing _rawMessage with id, sender, recipient, content"})}catch(Y){return G.status(500).send({error:`Relay send failed: ${Y instanceof Error?Y.message:String(Y)}`,delivered:!1})}})}import{computeContextHash as f3,validateEnvelope as N3}from"@aria-cli/aria";import{canHeartbeat as P3,derivePeerStateFromLegacyStatus as S3,NetworkRouteRevokeRequestJsonSchema as b3,NetworkRouteRevokeRequestSchema as C3,NodeIdSchema as J0,PeerTransportIdSchema as D1,SigningPublicKeySchema as K1}from"@aria-cli/tools";function I3($,Z){let G=$0($,{ownerGeneration:$.ariaOwnerGeneration});if(!G)return;let Q=G.resolveVerifiedPrincipalByFingerprint(Z);if(!Q||Q==="ambiguous")return Q;return{nodeId:Q.nodeId,displayNameSnapshot:Q.displayNameSnapshot?.trim()||Q.nodeId,...Q.signingPublicKey?{signingPublicKey:K1.parse(Q.signingPublicKey)}:{},principalFingerprint:Q.principalFingerprint,transportPublicKey:D1.parse(Q.transportPublicKey),...Q.isLocalAuthority?{isLocalAuthority:!0}:{}}}function k3($,Z){let G=$0($)?.resolveRemoteBinding(Z);if(!G)return;return{nodeId:G.nodeId,displayNameSnapshot:G.displayNameSnapshot?.trim()||G.nodeId,...G.signingPublicKey?{signingPublicKey:K1.parse(G.signingPublicKey)}:{},principalFingerprint:G.principalFingerprint,transportPublicKey:D1.parse(G.transportPublicKey)}}function q3($){let Z=$0($.server);if(!Z)throw Error("Local principal binding authority unavailable");let G=J0.parse(Z.resolveLocalNodeIdentity().nodeId),Q=$.server.ariaRevocationStore?.getPeerRevocationGeneration?.($.targetNodeId)??0;return{localNodeId:G,targetNodeId:$.targetNodeId,revocationGeneration:Q+1,operatorConfirmation:$.operatorConfirmation}}function h3($,Z){let G=$.ariaBasePath?.trim();if(!G)return;let Q=new d({ariaHome:G});try{let Y=Q.readRuntimeOwnerRecord(Z)?.ownerGeneration??0,X=Q.readRuntimeBootstrapRecord(Z)?.ownerGeneration??0,W=Math.max(Y,X,0);return W>0?W:void 0}finally{Q.close()}}function S$($){return $.payload&&typeof $.payload==="object"&&!Array.isArray($.payload)?$.payload:null}function b$($,Z){if($.operation!==Z.operation)switch(Z.label){case"peer listing":return{valid:!1,error:"Envelope operation mismatch for peer listing"};case"registration":return{valid:!1,error:"Envelope operation mismatch for registration"};case"revocation":return{valid:!1,error:"Envelope operation mismatch for revocation"}}if($.target.nodeId!==Z.targetNodeId)switch(Z.label){case"peer listing":return{valid:!1,error:"Envelope target mismatch for peer listing"};case"registration":return{valid:!1,error:"Envelope target mismatch for registration"};case"revocation":return{valid:!1,error:"Envelope target mismatch for revocation"}}let G=f3({method:"POST",path:Z.path,body:Z.payload,operation:Z.operation,targetKey:Z.targetNodeId});if($.contextHash!==G)switch(Z.label){case"peer listing":return{valid:!1,error:"Envelope context mismatch for peer listing"};case"registration":return{valid:!1,error:"Register body does not match signed envelope payload"};case"revocation":return{valid:!1,error:"Envelope context mismatch for revocation"}}return{valid:!0}}function C$($,Z,G){let Q,Y=!1,X,W=N3($,{keyResolver:(O)=>{let j=I3(Z,O);if(j==="ambiguous"){Y=!0,Q=void 0;return}return Q=j,Q?.signingPublicKey},nonceStore:G,authorize:Z.ariaPeerTrustStore?(O,j,V)=>{let z=J0.safeParse(O.nodeId);if(!z.success||!Q)return X="Unable to resolve authenticated peer principal",!1;if(z.data!==Q.nodeId)return X="Envelope principal claim does not match authenticated durable principal",!1;if(Q.isLocalAuthority)return!0;let F={"network.register":"send_message","network.revoke":"revoke_peer","network.list_peers":"send_message","pair.relay":"delegate_task"}[j];return V.nodeId,!F||Z.ariaPeerTrustStore.peerHasCapability(z.data,F)}:(O,j,V)=>{let z=J0.safeParse(O.nodeId);if(V.nodeId,!z.success||!Q)return X="Unable to resolve authenticated peer principal",!1;if(z.data!==Q.nodeId)return X="Envelope principal claim does not match authenticated durable principal",!1;return!0}});if(Y)return{valid:!1,error:"Unable to resolve authenticated peer principal"};if(!W.valid&&X)return{valid:!1,error:X};if(W.valid&&Q){let O=$.principal?.nodeId?.trim();if(O&&O!==Q.nodeId)return{valid:!1,error:"Envelope principal claim does not match authenticated durable principal"};return{...W,principalFingerprint:Q.principalFingerprint,principal:Q}}return W}function y3($,Z){let G=Z.nodeId;if(Z.decision.targetNodeId!==G)throw Error("Revocation decision target mismatch");let Q=$0($,{ownerGeneration:$.ariaOwnerGeneration??h3($,Z.decision.localNodeId)});if(!Q)throw Error("Local principal binding authority unavailable");if($.ariaRevocationStore)$.ariaRevocationStore.revoke({nodeId:G,...Z.displayNameSnapshot?{displayNameSnapshot:Z.displayNameSnapshot}:{},fingerprint:Z.fingerprint,revokedAt:Z.revokedAt,localNodeId:Z.decision.localNodeId,operatorConfirmation:Z.decision.operatorConfirmation,revocationGeneration:Z.decision.revocationGeneration});return Q.recordVerifiedRevocation({nodeId:G,fingerprint:Z.fingerprint,revocationGeneration:Z.decision.revocationGeneration,revokedAt:Z.revokedAt,revokedBy:Z.decision.localNodeId,operatorConfirmation:Z.decision.operatorConfirmation,...Z.displayNameSnapshot?{displayNameSnapshot:Z.displayNameSnapshot}:{}}),$.ariaPeerSigningKeyStore?.delete(G),$.ariaRelayCleanup?.(G),$.ariaRevocationBroadcast?.({nodeId:G,...Z.displayNameSnapshot?{displayNameSnapshot:Z.displayNameSnapshot}:{},revokedAt:Z.revokedAt}),{revoked:!0,nodeId:Z.nodeId,...Z.displayNameSnapshot?{displayNameSnapshot:Z.displayNameSnapshot}:{}}}function v3($,Z,G,Q){let Y=$.ariaNetworkManager;if(!Y)throw Error("Network manager not available");if(!Y.applyPeerRevocation)throw Error("Network manager missing applyPeerRevocation()");let X=$0($);if(!X)throw Error("Local principal binding authority unavailable");let W=J0.parse(X.resolveLocalNodeIdentity().nodeId),O="local_operator_confirmed",j=W;if(Q.envelope){let _=C$(Q.envelope,$,Z);if(!_.valid)throw Error(_.error??"Envelope validation failed");if(!_.principal?.nodeId||_.principal.nodeId!==W)throw Error("Remote revocation not permitted — revocation is a local operator decision only");if(j=_.principal.nodeId??W,!S$(Q.envelope))throw Error("MutationEnvelope payload must be an object");let f=b$(Q.envelope,{operation:"network.revoke",label:"revocation",path:"/api/v1/network/revoke",targetNodeId:Q.nodeId,payload:{nodeId:Q.nodeId}});if(!f.valid)throw Error(f.error)}if(!G.check(j))throw Error("Rate limit exceeded for revocations");let V=k3($,Q.nodeId);if(!V?.nodeId)throw Error("Peer not found");let{nodeId:z,displayNameSnapshot:U,principalFingerprint:F}=V;if(!z||!F)throw Error("Peer not found");let R=J0.parse(z),J=q3({server:$,targetNodeId:R,operatorConfirmation:O}),x=Y.applyPeerRevocation({nodeId:R,fingerprint:F});if(!x.revoked)throw Error(x.errorCode==="principal_unresolved"?"Peer principal unresolved":"Peer not found");return y3($,{nodeId:R,displayNameSnapshot:U??x.displayNameSnapshot,fingerprint:F,revokedAt:x.revokedAt,decision:J})}async function m3($,Z){let G=$.ariaNetworkManager;if(!G)throw Error("Network manager not available");if(!G.applyPeerRegistration)throw Error("Network manager missing applyPeerRegistration()");let Q=G.applyPeerRegistration.bind(G),Y=(U)=>{if(!U.registered){let F=String(U.errorCode);if(F==="not_found")throw Error("Peer not found");if(F==="revoked")throw Error("Peer revoked");if(F==="missing_endpoint_revision")throw Error("endpointRevision required for endpoint mutations");if(F==="stale_revision")throw Error("Rejected stale endpoint revision");if(F==="conflicting_revision")throw Error("Rejected conflicting endpoint revision");if(F==="node_id_mismatch")throw Error("Rejected durable nodeId rewrite for authenticated peer");throw Error(`Peer ${F} cannot complete register while awaiting pending_verification state convergence`)}return U},X=await $.ariaNetworkReadControl?.getPeerView?.(Z.nodeId);if(X){let{identityState:U}=S3(X);if(!P3(U))throw Error(`Peer ${X.status} cannot complete register while awaiting pending_verification state convergence`)}let{endpointHost:W,endpointPort:O}=Z,j=typeof W==="string"&&typeof O==="number",V=$.ariaBasePath,z=null;if(j){if(!V)throw Error("ARIA base path unavailable for endpoint registration");let U=$0($,{ownerGeneration:$.ariaOwnerGeneration});if(!U)throw Error("Principal binding authority unavailable for endpoint registration");try{z=Y$({ariaHome:V,ownerGeneration:$.ariaOwnerGeneration,authority:U,nodeId:Z.nodeId,endpointHost:W,endpointPort:O,endpointRevision:Z.endpointRevision??0,apply:({endpointHost:F,endpointPort:R,endpointRevision:J})=>{return Y(Q({nodeId:Z.nodeId,endpointHost:F,endpointPort:R,endpointRevision:J}))}}).projected}catch(F){if(F instanceof R0)throw Error(F.message);throw F}}if(z??=Y(Q({nodeId:Z.nodeId,...Z.endpointHost!==void 0?{endpointHost:Z.endpointHost}:{},...Z.endpointPort!==void 0?{endpointPort:Z.endpointPort}:{},...Z.endpointRevision!==void 0?{endpointRevision:Z.endpointRevision}:{}})),typeof z.endpointRevision!=="number"||!Number.isInteger(z.endpointRevision)||z.endpointRevision<0)throw Error("Invariant violation: successful registration must include a non-negative endpointRevision");return z}async function R1($){if(z$($),!$.ariaNonceStore)throw Error("DurableNonceStore required for network routes. Decorate server with ariaNonceStore before registering network routes.");if(!$.ariaNonceStore.isDurable)throw Error("DurableNonceStore required — InMemoryNonceStore is not crash-safe. "+"Use DurableNonceStore backed by SQLite.");let Z=$.ariaNonceStore,G=new w0(10,60000);U0($,"ariaNetworkAdminControl",{revokePeer:async(Q)=>v3($,Z,G,{nodeId:Q.nodeId,envelope:Q.envelope,rateLimitFallbackKey:Q.rateLimitFallbackKey??"local-runtime"})}),U0($,"ariaNetworkRegistrationControl",{registerPeer:async(Q)=>m3($,Q)}),$.post("/api/v1/network/peers",{schema:{body:{type:"object",properties:{envelope:{type:"object"}}}}},async(Q,Y)=>{let X=$.ariaNetworkReadControl?.listPeers;if(!X)return Y.status(503).send({error:"Network manager not available"});if(!Q.body.envelope)return Y.status(401).send({error:"MutationEnvelope required"});let W=C$(Q.body.envelope,$,Z);if(!W.valid)return Y.status(403).send({error:W.error??"Envelope validation failed"});let O=J0.safeParse(W.principal?.nodeId).data;if(!O)return Y.status(403).send({error:"Unable to resolve authenticated peer principal"});let j=S$(Q.body.envelope);if(!j)return Y.status(400).send({error:"MutationEnvelope payload must be an object"});let V=b$(Q.body.envelope,{operation:"network.list_peers",label:"peer listing",path:"/api/v1/network/peers",targetNodeId:O,payload:j});if(!V.valid)return Y.status(403).send({error:V.error});try{return Y.send({peers:await X()})}catch(z){let U=z instanceof Error?z.message:String(z);if(U==="Network manager not available")return Y.status(503).send({error:U});throw z}}),$.post("/api/v1/network/register",{schema:{body:{type:"object",required:["nodeId"],properties:{nodeId:{type:"string",minLength:1,maxLength:512},displayNameSnapshot:{type:"string",maxLength:256},endpointHost:{type:"string",maxLength:256},endpointPort:{type:"integer",minimum:1,maximum:65535},endpointRevision:{type:"integer",minimum:0},capabilities:{type:"array",items:{type:"string",maxLength:50},maxItems:20},envelope:{type:"object"}}}}},async(Q,Y)=>{let X=$.ariaNetworkRegistrationControl?.registerPeer;if(!X)return Y.status(503).send({error:"Network manager not available"});if(!Q.body.envelope)return Y.status(401).send({error:"MutationEnvelope required for registration"});let W=C$(Q.body.envelope,$,Z);if(!W.valid)return Y.status(403).send({error:W.error??"Envelope validation failed"});let O=S$(Q.body.envelope);if(!O)return Y.status(400).send({error:"MutationEnvelope payload must be an object"});let j=W.principal?.nodeId;if(!j)return Y.status(403).send({error:"Unable to resolve authenticated peer principal"});let V=J0.parse(j);if(typeof Q.body.endpointHost==="string"||typeof Q.body.endpointPort==="number"){if(!(typeof Q.body.endpointHost==="string"&&typeof Q.body.endpointPort==="number"))return Y.status(400).send({error:"endpointHost and endpointPort must be provided together"});if(typeof Q.body.endpointRevision!=="number"||!Number.isInteger(Q.body.endpointRevision)||Q.body.endpointRevision<0)return Y.status(400).send({error:"endpointRevision required for endpoint mutations"})}let U=J0.parse(Q.body.nodeId.trim());if(U!==V)return Y.status(403).send({error:"Register body nodeId does not match authenticated durable principal"});let F={nodeId:U};if(typeof Q.body.nodeId==="string"&&Q.body.nodeId.trim().length>0&&Q.body.nodeId.trim()!==j)return Y.status(403).send({error:"Envelope principal claim does not match registration nodeId"});if(typeof Q.body.displayNameSnapshot==="string"&&Q.body.displayNameSnapshot.trim().length>0)F.displayNameSnapshot=Q.body.displayNameSnapshot;if(typeof Q.body.endpointHost==="string")F.endpointHost=Q.body.endpointHost;if(typeof Q.body.endpointPort==="number")F.endpointPort=Q.body.endpointPort;if(typeof Q.body.endpointRevision==="number")F.endpointRevision=Q.body.endpointRevision;if(Array.isArray(Q.body.capabilities))F.capabilities=[...Q.body.capabilities];let R=b$(Q.body.envelope,{operation:"network.register",label:"registration",path:"/api/v1/network/register",targetNodeId:J0.parse(j),payload:F});if(!R.valid)return Y.status(403).send({error:R.error});let J=typeof O.nodeId==="string"&&O.nodeId.trim().length>0?J0.parse(O.nodeId.trim()):void 0;if(J&&U!==J)return Y.status(403).send({error:"Envelope payload mismatch for registration nodeId"});let x=typeof O.endpointHost==="string"&&O.endpointHost.length>0?O.endpointHost:void 0;if(typeof Q.body.endpointHost==="string"&&Q.body.endpointHost.length>0&&x&&Q.body.endpointHost!==x)return Y.status(403).send({error:"Envelope payload mismatch for registration endpointHost"});let _=typeof O.endpointPort==="number"&&Number.isInteger(O.endpointPort)&&O.endpointPort>=1&&O.endpointPort<=65535?O.endpointPort:void 0;if(typeof Q.body.endpointPort==="number"&&_!==void 0&&Q.body.endpointPort!==_)return Y.status(403).send({error:"Envelope payload mismatch for registration endpointPort"});let D=typeof O.endpointRevision==="number"&&Number.isInteger(O.endpointRevision)&&O.endpointRevision>=0?O.endpointRevision:void 0;if(typeof Q.body.endpointRevision==="number"&&D!==void 0&&Q.body.endpointRevision!==D)return Y.status(403).send({error:"Envelope payload mismatch for registration endpointRevision"});try{let f=await X({nodeId:V,...Q.body.endpointHost!==void 0||x!==void 0?{endpointHost:Q.body.endpointHost??x}:{},...Q.body.endpointPort!==void 0||_!==void 0?{endpointPort:Q.body.endpointPort??_}:{},...Q.body.endpointRevision!==void 0||D!==void 0?{endpointRevision:Q.body.endpointRevision??D}:{}});return Y.send({registered:!0,nodeId:f.nodeId,...f.displayNameSnapshot?{displayNameSnapshot:f.displayNameSnapshot}:{},peerStatus:f.peerStatus,lastSeen:f.lastSeen,heartbeatUpdated:f.heartbeatUpdated,endpointUpdated:f.endpointUpdated,endpointRevision:f.endpointRevision})}catch(f){let T=f instanceof Error?f.message:String(f);if(T==="Network manager not available"||T==="Network manager missing applyPeerRegistration()")return Y.status(503).send({error:T});if(T==="Peer not found")return Y.status(404).send({error:T});if(T==="Peer revoked")return Y.status(409).send({error:T});if(T==="Direct transport endpoint already owned by another peer principal")return Y.status(409).send({error:T});if(T==="endpointRevision required for endpoint mutations")return Y.status(400).send({error:T});if(T==="Rejected durable nodeId rewrite for authenticated peer"||T==="Rejected stale endpoint revision"||T==="Rejected conflicting endpoint revision"||T.includes("cannot complete register while awaiting pending_verification state convergence"))return Y.status(409).send({error:T});throw f}}),$.post("/api/v1/network/revoke",{schema:{body:b3}},async(Q,Y)=>{let X=$.ariaNetworkAdminControl?.revokePeer;if(!X)return Y.status(503).send({error:"Network manager not available"});try{let W=C3.parse(Q.body),O=J0.parse(W.nodeId);return Y.send(await X({nodeId:O,envelope:W.envelope,rateLimitFallbackKey:Q.ip}))}catch(W){let O=W instanceof Error?W.message:String(W);if(O==="Network manager not available"||O==="Network manager missing applyPeerRevocation()")return Y.status(503).send({error:O});if(O.includes("Remote revocation not permitted"))return Y.status(403).send({error:O});if(O==="Peer not found")return Y.status(404).send({error:O});if(O==="Rate limit exceeded for revocations")return Y.status(429).send({error:O});return Y.status(403).send({error:O})}}),$.get("/api/v1/network/revocations",async(Q,Y)=>{let X=W0($,Q);if(!X.ok)return Y.status(403).send({error:X.error,reason:X.reason});let W=$.ariaRevocationStore;if(!W)return Y.status(503).send({error:"Revocation store not available"});return Y.send({revocations:W.list().map((O)=>({nodeId:O.nodeId,...O.displayNameSnapshot?{displayNameSnapshot:O.displayNameSnapshot}:{},fingerprint:O.fingerprint,revokedAt:O.revokedAt,localNodeId:O.localNodeId,operatorConfirmation:O.operatorConfirmation,...O.reason?{reason:O.reason}:{},...typeof O.revocationGeneration==="number"?{revocationGeneration:O.revocationGeneration}:{}}))})})}import*as c0 from"node:crypto";import{RelayHealthTracker as l3}from"@aria-cli/aria";import{NodeIdSchema as A1,SigningPublicKeySchema as p3}from"@aria-cli/tools";import{NodeIdSchema as g3,PeerTransportIdSchema as c3}from"@aria-cli/tools/network-runtime";var u3=O$;function M1($,Z){let G=$0($)?.resolveRemoteBinding(Z);if(!G)return;return{nodeId:G.nodeId,principalFingerprint:G.principalFingerprint,transportPublicKey:c3.parse(G.transportPublicKey),continuityRevision:G.continuityRevision,displayNameSnapshot:G.displayNameSnapshot}}function J$($,Z,G){let Q=g3.safeParse(Z);if(!Q.success)return{ok:!1,error:"Invalid nodeId"};let Y=$0($);if(!Y)return{ok:!1,error:"Unknown peer"};let X=Y.resolveNodeIdFromVerifiedPrincipal({claimedNodeId:Q.data,signingPublicKey:G});if(!X)return{ok:!1,error:"Unknown peer"};let W=u3(G);if(!W)return{ok:!1,error:"Invalid signing public key"};if(X.principalFingerprint!==W)return{ok:!1,error:"Signing key mismatch"};return{ok:!0,fingerprint:W,nodeId:X.nodeId,...X.displayNameSnapshot?{displayNameSnapshot:X.displayNameSnapshot}:{}}}var d3=65535,i3=1000,a3=32;function n3($,Z){let G=M1($,Z);if(!G)return{ok:!1,error:"Target peer not registered"};return{ok:!0,nodeId:G.nodeId,...G.displayNameSnapshot?{displayNameSnapshot:G.displayNameSnapshot}:{}}}async function E1($){let Z=new Map,G=new l3;$.decorate("ariaRelayCleanup",(Q)=>{let Y=Z.get(Q);if(!Y)return;Z.delete(Q);try{Y.socket.close()}catch{}}),$.get("/api/v1/relay",{websocket:!0},(Q,Y)=>{let X=!1,W=null,O=null,j=null,V=null,z=null,U=setTimeout(()=>{if(!X)G0(Q,{type:"auth_error",error:"Authentication timeout"}),Q.close()},30000);Q.on("message",(J)=>{try{let x=typeof J==="string"?J:J.toString(),_=JSON.parse(x);if(!X)F(_);else R(_)}catch(x){G0(Q,{type:"error",error:x instanceof Error?x.message:"Invalid message"})}}),Q.on("close",()=>{if(clearTimeout(U),z&&Z.get(z.nodeId)===z)Z.delete(z.nodeId)}),Q.on("error",()=>{if(clearTimeout(U),z&&Z.get(z.nodeId)===z)Z.delete(z.nodeId)});function F(J){if(J.type==="auth"){let{nodeId:x,signingPublicKey:_}=J,D=A1.safeParse(x);if(!D.success){G0(Q,{type:"auth_error",error:"Invalid nodeId"}),Q.close();return}if(typeof _!=="string"){G0(Q,{type:"auth_error",error:"Missing signing public key"}),Q.close();return}let f=p3.safeParse(_);if(!f.success){G0(Q,{type:"auth_error",error:"Invalid signing public key"}),Q.close();return}let T=J$($,D.data,f.data);if(!T.ok){G0(Q,{type:"auth_error",error:T.error}),Q.close();return}O=T.nodeId,j=T.displayNameSnapshot??null,V=f.data,W=c0.randomBytes(a3).toString("hex"),G0(Q,{type:"challenge",nonce:W})}else if(J.type==="challenge_response"){if(!W||!O||!V){G0(Q,{type:"auth_error",error:"No pending challenge"}),Q.close();return}let x=J.signature;if(typeof x!=="string"){G0(Q,{type:"auth_error",error:"Missing signature"}),Q.close();return}if(!o3(W,x,V)){G0(Q,{type:"auth_error",error:"Invalid signature"}),Q.close();return}clearTimeout(U),X=!0;let _=Z.get(O);if(_)try{_.socket.close()}catch{}let D={nodeId:O,...j?{displayNameSnapshot:j}:{},signingPublicKey:V,socket:Q,packetCount:0,windowStart:Date.now()};z=D,Z.set(O,D),G0(Q,{type:"auth_ok",nodeId:O,...j?{displayNameSnapshot:j}:{}}),W=null}}function R(J){if(J.type!=="relay"||!z)return;let{toNodeId:x,data:_}=J,D=A1.safeParse(x);if(!D.success){G0(Q,{type:"error",error:"Target nodeId required"});return}if(typeof _!=="string")return;let f=Date.now(),T=n3($,D.data);if(!T.ok){G0(Q,{type:"error",error:T.error}),G.record(D.data,!1,0);return}let K=Date.now();if(K-z.windowStart>60000)z.packetCount=0,z.windowStart=K;if(z.packetCount++,z.packetCount>i3){G0(Q,{type:"error",error:"Rate limit exceeded"});return}if(Math.ceil(_.length*3/4)>d3){G0(Q,{type:"error",error:"Payload too large"});return}let w=Z.get(T.nodeId);if(!w){G0(Q,{type:"peer_offline",nodeId:T.nodeId,...T.displayNameSnapshot?{displayNameSnapshot:T.displayNameSnapshot}:{}}),G.record(T.nodeId,!1,0);return}G0(w.socket,{type:"relay",fromNodeId:z.nodeId,...z.displayNameSnapshot?{displayNameSnapshot:z.displayNameSnapshot}:{},data:_});let E=Date.now()-f;G.record(T.nodeId,!0,E)}})}function G0($,Z){try{$.send(JSON.stringify(Z))}catch{}}function o3($,Z,G){try{let Q=Buffer.from(G,"base64"),Y=c0.createPublicKey({key:Q,format:"der",type:"spki"});return c0.verify(null,Buffer.from($),Y,Buffer.from(Z,"base64"))}catch{return!1}}import*as f1 from"node:crypto";import{tlsFetch as w1}from"@aria-cli/aria";import*as N1 from"@aria-cli/wireguard";import{JoinRequestSchema as s3}from"@aria-cli/tools";function t3($,Z){if(Z<=0)return"";let[G,Q]=$.split(":",2);if(!G||!Q)throw Error("Join challenge payload malformed");let Y=0;for(;;){let X=`${G}:${Y}`,W=f1.createHash("sha256").update(`${X}:${Q}`).digest(),O=0;for(let j of W){if(j===0){O+=8;continue}O+=Math.clz32(j)-24;break}if(O>=Z)return X;Y+=1}}async function P1($){$.post("/api/v1/invite-relay/join",async(Z,G)=>{try{let Q=Z.body&&typeof Z.body==="object"?Z.body:{},Y=typeof Q.inviteToken==="string"&&Q.inviteToken.trim().length>0?Q.inviteToken.trim():null;if(!Y)return G.status(400).send({error:"inviteToken is required"});let X=s3.parse(Q.joinRequest),W=N1.decodeInviteToken(Y),O=W.controlEndpoint,j=W.caCert?.trim(),V=O?.tlsServerIdentity?.trim();if(!O||!j||!V)return G.status(400).send({error:"Invite token missing relay bootstrap trust data"});let z=`https://${O.host}:${O.port}/api/v1/join/challenge`,U=await w1(z,{ca:j,expectedTlsIdentity:V});if(U.status!==200)return G.status(502).send({error:`Invite relay challenge failed: ${U.status}`});let F=await U.json();if(!F.challenge||typeof F.challenge!=="string")return G.status(502).send({error:"Invite relay challenge payload was invalid"});let R=t3(F.challenge,F.difficulty??4),J=`https://${O.host}:${O.port}/api/v1/join`,x=JSON.stringify({...X,proofOfWork:R}),_=await w1(J,{method:"POST",body:x,ca:j,expectedTlsIdentity:V,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(x).toString()}});if(_.status!==200)return G.status(502).send({error:`Invite relay join failed: ${_.status}`});return G.send(await _.json())}catch(Q){return G.status(400).send({error:Q.message})}})}import*as k0 from"node:crypto";import{NodeIdSchema as r3,SigningPublicKeySchema as e3}from"@aria-cli/tools";var $6=32,Z6=16;async function S1($){let Z=new Map,G=50,Q=1000,Y=new Map,X=0;$.get("/api/v1/ws/revocations",{websocket:!0},(W,O)=>{let j=O.ip??O.socket?.remoteAddress??"unknown",V=Y.get(j)??0;if(V>=50||X>=1000){W.close(1013,"Too many connections");return}Y.set(j,V+1),X++;let z=!1,U=!0,F=null,R=null,J=null,x=null,_=null,D=setTimeout(()=>{if(!z)X0(W,{type:"auth_error",error:"Authentication timeout"}),W.close()},1e4);W.on("message",(K)=>{try{let N=typeof K==="string"?K:K.toString(),w;try{w=JSON.parse(N)}catch{X0(W,{type:z?"error":"auth_error",error:"Malformed message"}),W.close();return}if(!z)T(w)}catch(N){X0(W,{type:z?"error":"auth_error",error:N instanceof Error?N.message:"Authentication failed"}),W.close()}});function f(){if(!U)return;U=!1;let K=(Y.get(j)??1)-1;if(K<=0)Y.delete(j);else Y.set(j,K);X--}W.on("close",()=>{if(clearTimeout(D),J&&Z.get(J)?.socket===W)Z.delete(J);f()}),W.on("error",()=>{if(clearTimeout(D),J&&Z.get(J)?.socket===W)Z.delete(J);f()});function T(K){if(K.type==="auth"){let{nodeId:N,signingPublicKey:w}=K,E=r3.safeParse(N);if(!E.success){X0(W,{type:"auth_error",error:"Invalid nodeId"}),W.close();return}if(typeof w!=="string"){X0(W,{type:"auth_error",error:"Missing signing public key"}),W.close();return}let B=e3.safeParse(w);if(!B.success){X0(W,{type:"auth_error",error:"Invalid signing public key"}),W.close();return}let L=J$($,E.data,B.data);if(!L.ok){X0(W,{type:"auth_error",error:L.error}),W.close();return}if($.ariaRevocationStore?.isPeerRevoked?.(L.nodeId)){X0(W,{type:"auth_error",error:"Peer has been revoked"}),W.close();return}J=L.nodeId,x=L.displayNameSnapshot??null,_=w,F=k0.randomBytes($6).toString("hex"),R=k0.randomBytes(Z6).toString("hex");let C=`${F}:${R}`;X0(W,{type:"challenge",nonce:C})}else if(K.type==="challenge_response"){if(!F||!R||!J||!_){X0(W,{type:"auth_error",error:"No pending challenge"}),W.close();return}let N=K.signature;if(typeof N!=="string"){X0(W,{type:"auth_error",error:"Missing signature"}),W.close();return}let w=`${F}:${R}`;if(!G6(w,N,_)){X0(W,{type:"auth_error",error:"Invalid signature"}),W.close();return}if($.ariaRevocationStore?.isPeerRevoked?.(J)){X0(W,{type:"auth_error",error:"Peer has been revoked"}),W.close();return}let E=Z.get(J);if(E&&E.socket!==W)try{E.socket.close()}catch{}Z.set(J,{socket:W,...x?{displayNameSnapshot:x}:{}}),clearTimeout(D),z=!0,X0(W,{type:"auth_ok",nodeId:J,...x?{displayNameSnapshot:x}:{}})}}}),$.decorate("ariaRevocationBroadcast",(W)=>{let O=W.nodeId,j=W.displayNameSnapshot??Z.get(O)?.displayNameSnapshot,V=Z.get(O);if(V){Z.delete(O);try{X0(V.socket,{type:"revoked",nodeId:O,...j?{displayNameSnapshot:j}:{}}),V.socket.close()}catch{}}for(let[,z]of Z)try{X0(z.socket,{type:"revocation",nodeId:O,...j?{displayNameSnapshot:j}:{},revokedAt:W.revokedAt})}catch{}})}function X0($,Z){try{$.send(JSON.stringify(Z))}catch{}}function G6($,Z,G){try{let Q=Buffer.from(G,"base64"),Y=k0.createPublicKey({key:Q,format:"der",type:"spki"});return k0.verify(null,Buffer.from($),Y,Buffer.from(Z,"base64"))}catch{return!1}}import{existsSync as Q6,mkdirSync as Y6,readFileSync as X6,renameSync as O6,writeFileSync as W6}from"fs";import{dirname as V6}from"path";var b1=500;function j6($){if(!Array.isArray($))return;let Z=[];for(let G of $){if(!G||typeof G!=="object")continue;let Q=G;if(typeof Q.id!=="string"||typeof Q.name!=="string")continue;Z.push({id:Q.id,name:Q.name,arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:void 0,...typeof Q.thoughtSignature==="string"?{thoughtSignature:Q.thoughtSignature}:{}})}return Z.length>0?Z:void 0}function C1($){let Z=[];for(let G of $){if(!G||typeof G!=="object")continue;let Q=typeof G.role==="string"?G.role:"";if(!Q)continue;let Y=typeof G.content==="string"?G.content:"",X=typeof G.name==="string"?G.name:void 0,W=typeof G.toolCallId==="string"?G.toolCallId:void 0,O=j6(G.toolCalls);Z.push({role:Q,content:Y,...X?{name:X}:{},...W?{toolCallId:W}:{},...O?{toolCalls:O}:{}})}return Z}function I1($){if($.size<=b1)return;let Z=[...$.values()].sort((G,Q)=>{let Y=Date.parse(G.updatedAt)-Date.parse(Q.updatedAt);if(Y!==0)return Y;return Date.parse(G.createdAt)-Date.parse(Q.createdAt)});for(let G of Z){if($.size<=b1)break;$.delete(G.id)}}function z6($){let Z=new Map;if(!Q6($))return Z;try{let G=JSON.parse(X6($,"utf-8"));if(!G||typeof G!=="object"||!Array.isArray(G.sessions))return Z;for(let Q of G.sessions){if(!Q||typeof Q!=="object")continue;if(typeof Q.id!=="string")continue;Z.set(Q.id,{id:Q.id,arionName:typeof Q.arionName==="string"?Q.arionName:null,createdAt:typeof Q.createdAt==="string"?Q.createdAt:new Date().toISOString(),updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:new Date().toISOString(),completedAt:typeof Q.completedAt==="string"?Q.completedAt:null,messages:C1(Array.isArray(Q.messages)?Q.messages:[])})}}catch{return new Map}return I1(Z),Z}function U6($,Z){let G=V6($);Y6(G,{recursive:!0});let Q={version:1,sessions:[...Z.values()]},Y=`${$}.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}.tmp`;W6(Y,JSON.stringify(Q),"utf-8"),O6(Y,$)}function k1($){let Z=z6($),G=()=>{I1(Z);try{U6($,Z)}catch(Q){console.warn("[Server] Failed to persist session history:",Q instanceof Error?Q.message:String(Q))}};return{upsertSession(Q,Y,X){let W=new Date().toISOString(),O=Z.get(Q),j=C1(Y),V=X?.completed===!0;Z.set(Q,{id:Q,arionName:X?.arionName??O?.arionName??null,createdAt:O?.createdAt??W,updatedAt:W,completedAt:V?O?.completedAt??W:null,messages:j.length>0?j:O?.messages??[]}),G()},markCompleted(Q){let Y=new Date().toISOString(),X=Z.get(Q);Z.set(Q,{id:Q,arionName:X?.arionName??null,createdAt:X?.createdAt??Y,updatedAt:Y,completedAt:X?.completedAt??Y,messages:X?.messages??[]}),G()},markStaleSessionsCompleted(Q){let Y=Date.now()-Q*86400000,X=new Date().toISOString(),W=0;for(let O of Z.values()){if(O.completedAt!==null)continue;if(O.messages.length===0)continue;if(Date.parse(O.updatedAt)>=Y)continue;O.completedAt=O.completedAt??X,O.updatedAt=X,W++}if(W>0)G();return W},getIncompleteSessions(Q){return[...Z.values()].filter((Y)=>Y.completedAt===null&&Y.messages.length>0).sort((Y,X)=>Date.parse(X.updatedAt)-Date.parse(Y.updatedAt)).slice(0,Math.max(0,Q)).map((Y)=>({id:Y.id,messageCount:Y.messages.length}))},getIncompleteSessionsWithMetadata(Q){return[...Z.values()].filter((Y)=>Y.completedAt===null&&Y.messages.length>0).sort((Y,X)=>Date.parse(X.updatedAt)-Date.parse(Y.updatedAt)).slice(0,Math.max(0,Q)).map((Y)=>({id:Y.id,messageCount:Y.messages.length,arionName:Y.arionName??void 0}))},getSession(Q){let Y=Z.get(Q);if(!Y)return null;return{id:Y.id,messages:Y.messages.map((X)=>({role:X.role,content:X.content,...X.toolCallId?{toolCallId:X.toolCallId}:{},...X.toolCalls?{toolCalls:[...X.toolCalls]}:{}}))}}}}import{DurableNonceStore as q1,DurablePairStore as h1,InviteConsumeLedger as y1,PeerSigningKeyStore as v1,PeerTrustStore as m1,RevocationStore as nG}from"@aria-cli/aria";function g1($){let Z=new d({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration});return{revoke(G){Z.revoke(G)},isPeerRevoked(G){return Z.isPeerRevoked(G)},read(G){let Q=Z.readRevocation(G);if(!Q)return null;return{...Q,localNodeId:Q.revokedBy}},getPeerRevocationGeneration(G){return Z.getPeerRevocationGeneration(G)},clearRevocationForNodeId(G,Q){return Z.clearRevocationForNodeId(G,Q)},list(){return Z.listRevocations().map((G)=>({...G,localNodeId:G.revokedBy}))},close(){Z.close()}}}function c1($){let Z=g1({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration}),G=new v1($.networkStateDb),Q=new h1($.networkStateDb),Y=new q1($.networkStateDb),X=new m1($.networkStateDb),W=new y1($.networkStateDb);return{revocationStore:Z,peerSigningKeyStore:G,durablePairStore:Q,nonceStore:Y,peerTrustStore:X,inviteConsumeLedger:W}}var u1=Symbol.for("@aria-cli/server/process-handlers-registered");async function M6(){let[{recoverCrashedSessions:$},{ArionStorage:Z}]=await Promise.all([import("@aria-cli/aria/server-crash-recovery"),import("@aria-cli/aria/server-arion-storage")]);return{recoverCrashedSessions:$,ArionStorage:Z}}function A6(){let $=process;if($[u1])return;$[u1]=!0,process.on("unhandledRejection",(Z)=>{console.error("[Server] Unhandled promise rejection:",Z)}),process.on("uncaughtException",(Z)=>{console.error("[Server] Uncaught exception — shutting down:",Z),process.exit(1)})}function E6($){try{let Z=new URL($);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="::1"||Z.hostname==="[::1]"}catch{return!1}}function w6($){if(!$)return $;try{let Z=new URL($,"http://localhost");if(Z.searchParams.has("api_key"))return Z.searchParams.set("api_key","REDACTED"),Z.pathname+Z.search}catch{return $.replace(/([?&])api_key=[^&]*/g,"$1api_key=REDACTED")}return $}function f6($,Z){if(Z&&typeof Z.upsertSession==="function")return Z;return $}function N6($,Z){let G=$.getIncompleteSessionsWithMetadata;if(typeof G==="function")return G(Z);return $.getIncompleteSessions(Z).map((Q)=>({id:Q.id,messageCount:Q.messageCount,arionName:void 0}))}function l1($,Z){let G=$.trim()||"ARIA";return Z?.memoriaPath||`arions/${G}/memory.db`}function P6($){return F6.createHash("sha256").update(Buffer.from($,"base64")).digest("hex")}function S6($){let Z=$?.trim();if(Z)return Z;let G=process.env.ARIA_HOME?.trim();if(G)return G;return d1()}async function n1($={}){let{port:Z=3000,host:G="127.0.0.1",enableCrashRecovery:Q=!0,crashRecoverySessionHistory:Y}=$,X=S6($.basePath),O=($.nodeId?await p1({ariaHome:X,nodeId:$.nodeId}):null)?.nodeId??$.nodeId,j=$.ownerGeneration??(O?1:void 0),V=_6({...$.tls&&{https:{cert:$.tls.cert,key:$.tls.key}},logger:$.silent?!1:{level:"info",serializers:{req(B){let L=B;return{method:L.method,url:w6(L.url),hostname:L.hostname,remoteAddress:L.ip}}}},connectionTimeout:330000,requestTimeout:330000,bodyLimit:1048576});V.register(J6,{origin:(B,L)=>{if(!B||E6(B))L(null,!0);else L(Error("Not allowed by CORS"),!1)},methods:["GET","POST","PUT","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"]}),V.decorate("config",{port:Z,host:G}),V.decorate("ariaRuntimeId",$.runtimeId),V.decorate("ariaNodeId",O),V.decorate("ariaOwnerGeneration",j),V.decorate("ariaBasePath",X);let z=new R6({ariaHome:X}),U=z.getDatabase();V.addHook("onClose",async()=>{z.close()});let F=k1(H6.join(X,"server-session-history.json")),R=Y??F,J=f6(F,Y),x=L6({ariaHome:X}),_=$.router??await T6({ariaHome:X,anthropic:x.legacyApiKeys.anthropic,openai:x.legacyApiKeys.openai,google:x.legacyApiKeys.google,...x.bedrock?{bedrock:x.bedrock}:{},authResolver:$.authResolver??x.authResolver}),D=$.memoriaFactory??new x6(X,_).toFactory();V.decorate("ariaMemoriaFactory",D),V.decorate("ariaRouter",_),V.decorate("ariaSessionHistory",J),V.decorate("ariaAuthResolver",$.authResolver??x.authResolver);try{let L=(await D.get(l1($.arionName??"ARIA"))).storage?.getDatabase();if(L)V.decorate("ariaMessageStore",new D6(L))}catch(B){u0.debug("[Server] MessageStore not available — /api/v1/message requires EventQueue sink or will return 503:",B?.message??B)}let f=D;V.addHook("onClose",async()=>{await f.closeAll()});let T,K,N=!1;try{let B=c1({ariaHome:X,networkStateDb:U,ownerGeneration:j??1});K=B.revocationStore,V.decorate("ariaRevocationStore",K),T=B.peerSigningKeyStore,V.decorate("ariaPeerSigningKeyStore",T),V.decorate("ariaDurablePairStore",B.durablePairStore),V.decorate("ariaNonceStore",B.nonceStore),V.decorate("ariaPeerTrustStore",B.peerTrustStore),V.decorate("ariaInviteConsumeLedger",B.inviteConsumeLedger),N=!0}catch{u0.debug("[Server] Durable network stores not available")}if(K)V.addHook("onClose",async()=>{K?.close()});if($.networkManager)V.decorate("ariaNetworkManager",$.networkManager),$.networkManager.addPeerActivationListener?.(({nodeId:L,displayNameSnapshot:C,signingPublicKey:g})=>{T?.set(L,g,C);let r=V.ariaPeerTrustStore;if(r?.getTier(L)==="probe")r.setTier({nodeId:L,displayName:C,fingerprint:K6.parse(P6(g)),tier:"member",promotedBy:"verified-ingress",reason:"Verified signed ingress activated paired peer"});u0.debug(`[Server] Peer "${C}" activated after identity verification`)});if(G!=="127.0.0.1"&&G!=="localhost"&&!$.tls)throw Error("Refusing to bind to non-localhost without TLS. Provide tls config or use host=127.0.0.1.");if($.attachedLocalHttpClientAuthority)$$(V,$.attachedLocalHttpClientAuthority);if(V.get("/health",async()=>{return{status:"ok"}}),await V.register(B6),V.setSchemaErrorFormatter((B,L)=>{let g=B[0]?.message||"Validation failed";return Error(g)}),V.setErrorHandler((B,L,C)=>{if(B.validation)return C.status(400).send({success:!1,error:B.message});throw B}),await z2(V),V.register(U2),V.register(M2),V.register(i1),V.register(f2),await L1(V),await Q1(V),await Y1(V),await X1(V),N)await S1(V);if(N)await R1(V);await E1(V),await a1(V),await P1(V),A6();let w=!1,E=async(B)=>{if(!Q)return;if(B?.startup&&w)return;if(!D||!_||!R)return;if(B?.startup)w=!0;let{recoverCrashedSessions:L,ArionStorage:C}=await M6(),r=N6(R,3),Z0=new C(X);await Z0.initialize().catch((v)=>{u0.warn("[Server] Storage initialization failed:",v?.message??v)});let c=async(v)=>{let I=v.trim()||"ARIA",i=await Z0.get(I).catch(()=>null);return l1(I,i)};if(r.length===0){let v=await c("ARIA");try{let I=await D.get(v),i=await L({sessionHistory:R,memoria:I,router:_,signal:B?.signal});if(i.recovered>0)console.debug(`[Server] Recovered learning from ${i.recovered} incomplete session${i.recovered===1?"":"s"}.`)}catch(I){console.warn("[Server] Crash recovery failed:",I?.message??String(I))}finally{if(typeof D?.evict==="function")await D.evict(v).catch((I)=>{u0.warn("[Server] Memoria factory evict failed:",I?.message??I)})}return}let Q0=new Map;for(let v of r){let I=(v.arionName?.trim()||"ARIA").toLowerCase(),i=Q0.get(I)??[];i.push(v),Q0.set(I,i)}let P=0,q=0;for(let[v,I]of Q0.entries()){if(B?.signal?.aborted)break;let i=new Set(I.map((a)=>a.id)),o=I[0]?.arionName?.trim()||v||"ARIA",F0=await c(o),P0={getIncompleteSessions(a){return I.slice(0,Math.max(0,a)).map((S0)=>({id:S0.id,messageCount:S0.messageCount}))},getSession(a){if(!i.has(a))return null;return R.getSession(a)},markCompleted(a){if(!i.has(a))return;R.markCompleted(a)},markStaleSessionsCompleted(a){return R.markStaleSessionsCompleted(a)}};try{let a=await D.get(F0),S0=await L({sessionHistory:P0,memoria:a,router:_,signal:B?.signal});P+=S0.recovered,q+=S0.errors}catch(a){q++,console.warn("[Server] Crash recovery failed:",a?.message??String(a))}finally{if(typeof D?.evict==="function")await D.evict(F0).catch((a)=>{u0.warn("[Server] Memoria factory evict failed:",a?.message??a)})}}if(P>0)console.debug(`[Server] Recovered learning from ${P} incomplete session${P===1?"":"s"}.`);if(q>0)console.warn(`[Server] Crash recovery encountered ${q} error${q===1?"":"s"}.`)};return V.decorate("ariaRecoverCrashedSessions",async(B)=>{await E({signal:B})}),{server:V,listen:async()=>{return await E({startup:!0}),V.listen({port:Z,host:G})}}}import{DirectPairRequestSchema as b6,DirectPairResponseSchema as C6,PendingPairRequestViewSchema as I6,RevokePeerRequestSchema as k6,RevokePeerResponseSchema as q6,PairRequestDecisionSchema as h6,PairRequestResponseSchema as y6}from"@aria-cli/tools";function o1($){let{server:Z}=$,G=()=>{let Y=Z.ariaPairControl;if(!Y)throw Error("Runtime admin surface unavailable");return Y},Q=()=>{let Y=Z.ariaNetworkAdminControl;if(!Y)throw Error("Runtime admin surface unavailable");return Y};return{async listPendingPairRequests(){return(await G().listPendingPairRequests()).map((Y)=>I6.parse(Y))},async respondToPairRequest(Y){return y6.parse(await G().respondToPairRequest(h6.parse(Y)))},async directPair(Y){return C6.parse(await G().directPair(b6.parse(Y)))},async revokePeer(Y){return q6.parse(await Q().revokePeer(k6.parse(Y)))}}}import{buildRuntimeBootstrapRecord as v6}from"@aria-cli/aria/server-discovery";function I$($,Z,G){let Q=$.readRuntimeBootstrapRecord(Z);if(!Q)return 1;return Q.bootstrapRevision+1}function s1($){let Z=$.networkManager.getConfig?.()??null,G=v6({nodeId:$.nodeId,runtimeId:$.runtimeId,ownerGeneration:$.ownerGeneration,controlPort:$.controlPort,caFingerprint:$.caFingerprint,caCertPem:$.caCertPem,networkManager:$.networkManager,networkConfig:Z,displayNameSnapshot:$.displayNameSnapshot,controlHost:$.controlHost,bootstrapRevision:I$($.nodeStore,$.nodeId,$.ownerGeneration),phase:$.phase});return $.nodeStore.writeRuntimeBootstrapRecord(G)}import*as k$ from"node:path";import*as e1 from"node:fs/promises";import{randomUUID as t1}from"node:crypto";import{AgentRunner as m6,RunSession as g6,runWakeLoop as c6,SqliteEventQueue as u6,StuckDetector as l6,CorrectionLadder as p6,AuditLog as d6,runPostRunProcessing as i6,ReplayGuard as a6,DurableDelegationStore as n6}from"@aria-cli/aria";import{QuestStore as o6}from"@aria-cli/memoria/storage";import{NodeIdSchema as s6,PrincipalFingerprintSchema as t6}from"@aria-cli/tools";import{log as r1}from"@aria-cli/types";function r6($,Z,G,Q){let Y=new m6($),X=async()=>!1;function W(O){let V={...Z,...O,maxTurns:null,onApprovalNeeded:X,stateDir:G};if(Q){let z=typeof V.activeQuestId==="string"?V.activeQuestId.trim():"",U=z.length>0?Q.ensureMemoriaSessionId(z):void 0;if(U){try{Q.session.observer?.setSessionId(U)}catch(F){console.warn("[runtime-autonomous-loop] Observer session binding failed (non-critical):",F?.message)}if(Q.session.observationEngine)V.observationEngine=Q.session.observationEngine,V.observationSessionId=U,V.originalSystemPrompt=Q.session.originalSystemPrompt}}return V}return{stream(O,j){return Y.stream(O,W(j))},async resume(O,j){return Y.resume(O,W(j))}}}class q${options;started=!1;starting=!1;stopController=null;bootstrapAbortController=null;startPromise=null;loopPromise=null;session=null;releaseMailbox=null;lastWakeTickAt=null;lastCheckpointResult="never";currentWakeTrigger=null;constructor($){this.options=$}summarizeSafetyPolicy(){return{...this.options.safetyPolicy?.allowedToolCategories?{allowedToolCategories:[...this.options.safetyPolicy.allowedToolCategories]}:{},...this.options.safetyPolicy?.allowedShellCommands?{allowedShellCommands:[...this.options.safetyPolicy.allowedShellCommands]}:{},...typeof this.options.safetyPolicy?.maxWriteOpsPerMinute==="number"?{maxWriteOpsPerMinute:this.options.safetyPolicy.maxWriteOpsPerMinute}:{},...typeof this.options.safetyPolicy?.maxGitPushesPerHour==="number"?{maxGitPushesPerHour:this.options.safetyPolicy.maxGitPushesPerHour}:{}}}getStatusSummary($){return{status:this.started||this.starting||this.startPromise?"running":"stopped",intervalMs:this.options.intervalMs??null,lastWakeTickAt:this.lastWakeTickAt,lastCheckpointResult:this.lastCheckpointResult,safetyPolicySummary:this.summarizeSafetyPolicy(),ownerClientKind:$}}async start(){if(this.started)return;if(this.startPromise){await this.startPromise;return}this.starting=!0,this.bootstrapAbortController=new AbortController;let $=this.options.signal?AbortSignal.any([this.options.signal,this.bootstrapAbortController.signal]):this.bootstrapAbortController.signal;this.startPromise=(async()=>{let{ariaHome:Z,arionName:G,runtimeControl:Q,router:Y,memoriaFactory:X,runSessionConfig:W,mcpServers:O,authResolver:j,intervalMs:V,safetyPolicy:z,nodeStore:U}=this.options,F=new a6,R=Q.networkManager,J={verificationConfig:{freshnessGuard:F,replayGuard:F},...Q.nodeId?{localInboxAddress:{kind:"node",nodeId:Q.nodeId}}:{},commitIngressReceipt:U?(_,D)=>{let{resolvedNodeId:f,resolvedPeerFingerprint:T}=D;if(!f)throw Error("[runtime-autonomous-loop] Accepted ingress is missing resolvedNodeId");if(!T)throw Error("[runtime-autonomous-loop] Accepted ingress is missing resolvedPeerFingerprint");U.commitIngressReceipt({messageId:String(_.id),senderNodeId:f,senderFingerprint:t6.parse(T),runtimeId:Q.runtimeId})}:void 0,activateVerifiedPeer:typeof R.activatePendingPeer==="function"?(_)=>{R.activatePendingPeer?.(s6.parse(_))}:void 0,revocationStore:Q.revocationStore,collectiveMemory:Q.networkCoordinator?.collectiveMemory},x=await g6.create({arionName:G,config:W,storagePath:Z,router:Y,memoriaFactory:X,abortSignal:$,initialTask:"Autonomous daemon wake loop",mcpServers:O,authResolver:j,networkManager:Q.networkManager,runtimeId:Q.runtimeId,nodeId:Q.nodeId,runtimeIngressAuthority:J});try{let _=x.memoria.storage?.getDatabase();if(!_)throw Error(`Memoria database unavailable for arion "${G}"`);let D=x.toRunOptions({maxTurns:null});if(Q.networkCoordinator)D.networkIntelligence=Q.networkCoordinator;let f=k$.join(Z,"arions",G,"daemon");await e1.mkdir(f,{recursive:!0});let T=new o6(_),K=new n6(_);try{for(let P of K.findRecoverable())K.fail(P.id,"Process crashed — recovered on runtime startup")}catch(P){console.warn(`[runtime-autonomous-loop] Delegation crash recovery failed (non-critical): ${P}`)}let N=new u6(_),w=new l6,E=new p6,B=new d6(k$.join(f,"audit.jsonl")),L=x.getRuntimeOutbox();if(L)this.releaseMailbox=Q.registerMailbox(L);let{nodeId:C,networkManager:g}=Q;if(g.addMessageListener)g.addMessageListener(()=>{return this.currentWakeTrigger?.(),!1});if(L&&C){let P=L;x.errorHandler.setBroadcaster({broadcast(q){try{for(let v of R?.listPeers?.()??[])if(v.status==="active"){let I=v.nodeId;if(!I)continue;let i={id:`msg-${t1()}`,version:1,sender:{id:C,name:G,type:"leader"},type:q.type,content:JSON.stringify(q.payload),recipient:{id:I,name:v.name},metadata:{errorBroadcast:!0},priority:0,timestamp:Date.now()};P.sendBestEffort(i)}}catch{}}})}let r=new Map,Z0=(P)=>{let q=P.trim();if(!q)return;let v=r.get(q);if(v)return v;let I=t1();try{x.memoria.session(I)}catch(i){console.warn("[runtime-autonomous-loop] Memoria session start failed (non-critical):",i?.message)}return r.set(q,I),I},c=new AbortController,Q0=AbortSignal.any([$,c.signal]);this.stopController=c,this.session=x,this.loopPromise=c6({arionName:G,runtimeId:Q.runtimeId,localNodeId:C,stateDir:f,ariaDir:Z,intervalMs:V??60000,questStore:T,createRunner:()=>r6(Y,D,f,{session:x,ensureMemoriaSessionId:Z0}),buildSystemPrompt:()=>x.systemPrompt,signal:Q0,eventQueue:N,stuckDetector:w,correctionLadder:E,safetyPolicy:z,auditLog:B,mailbox:x.mailbox,messageStore:x.messageStore,freshnessGuard:J.verificationConfig?.freshnessGuard,replayGuard:J.verificationConfig?.replayGuard,commitIngressReceipt:J.commitIngressReceipt,activateVerifiedPeer:J.activateVerifiedPeer,delegationExecutor:x.remoteDelegationSettlement,peerKeyRegistry:{get(P){return R.getAllPeerSigningKeysByPrincipal?.()?.get(P)},get size(){return R.getAllPeerSigningKeysByPrincipal?.()?.size??0}},revocationStore:J.revocationStore,collectiveMemory:J.collectiveMemory,recoverCrashedSessions:Q.server.server.ariaRecoverCrashedSessions?({signal:P})=>Q.server.server.ariaRecoverCrashedSessions?.(P):void 0,onWakeTick:(P)=>{this.lastWakeTickAt=P},onWakeReady:(P)=>{this.currentWakeTrigger=P},onCheckpointWriteResult:(P)=>{this.lastCheckpointResult=P},onQuestPostRun:async({quest:P,task:q,response:v,messages:I,signal:i,runReflection:o})=>{let F0=r.get(P.id);try{await i6(x,{task:q,arionName:G,config:W,storagePath:Z,router:Y,memoriaFactory:X,abortSignal:i,mcpServers:O,authResolver:j},v,F0,{runReflection:o,runDeepConsolidation:o,messages:I})}finally{if(F0)r.delete(P.id)}}}).catch((P)=>{this.lastCheckpointResult="error";let q=P instanceof Error?P.message:String(P);if(q.includes("Daemon lock already held")){r1.warn(`[runtime-autonomous-loop] Skipping autonomous loop for "${G}": ${q}`);return}throw r1.error(`[runtime-autonomous-loop] Fatal wake-loop failure for "${G}": ${q}`),P}),this.started=!0}catch(_){throw this.releaseMailbox?.(),this.releaseMailbox=null,this.stopController?.abort(),this.stopController=null,this.loopPromise=null,await x.close(),this.session=null,_}finally{if(this.starting=!1,!this.started)this.bootstrapAbortController=null,this.startPromise=null}})(),await this.startPromise}async stop(){if(!this.started&&!this.starting&&!this.startPromise)return;this.bootstrapAbortController?.abort(),this.stopController?.abort();try{await this.startPromise}catch{}let $=this.loopPromise,Z=this.session,G=this.releaseMailbox;this.started=!1,this.starting=!1,this.bootstrapAbortController=null,this.startPromise=null,this.stopController=null,this.loopPromise=null,this.session=null,this.releaseMailbox=null;try{await $}catch{}finally{G?.(),await Z?.close()}}}import{createRuntimeOutbox as e6}from"@aria-cli/aria/messaging";function $4($={}){return e6($)}var D8=new Set(["localhost","127.0.0.1","::1"]);function X4($){let Z=j4.safeParse($);return Z.success?Z.data:void 0}function z4($){if(D8.has($))return!0;return $.toLowerCase().endsWith(".localhost")}function O4($){let Z;try{Z=new URL($)}catch{throw Error(`Invalid coordination URL: ${$}`)}let G=Z.hostname.toLowerCase();if(Z.protocol==="https:")return Z;if(Z.protocol==="http:"&&z4(G))return Z;throw Error(`Insecure coordination URL "${$}". Use https:// (http:// allowed only for localhost).`)}function K8($){let{startTunnel:Z,stopTunnel:G,heartbeat:Q,applyPeerRepair:Y,activeTunnelCount:X}=$;if(typeof Z!=="function"||typeof G!=="function"||typeof Q!=="function"||typeof Y!=="function"||typeof X!=="number")throw Error("[node-runtime] Peer discovery requires startTunnel, stopTunnel, heartbeat, applyPeerRepair, and activeTunnelCount on the runtime network manager.");return{startTunnel:Z.bind($),stopTunnel:G.bind($),heartbeat:Q.bind($),applyPeerRepair:Y.bind($),activeTunnelCount:X}}function R8($){if($.port)return Number.parseInt($.port,10);return $.protocol==="https:"?443:80}function v$($){if(typeof $!=="string")return;let Z=$.trim();if(!Z)return;return Z.replace(/^\[|\]$/g,"").toLowerCase()}function M8($,Z){let G=B0.resolve(B0.join($,"network","trusted-cas")),Q=B0.resolve(B0.join(G,`${Z.trim().toLowerCase()}.pem`));if(!Q.startsWith(`${G}${B0.sep}`))throw Error("Trusted CA path escapes trusted-cas directory");return Q}function A8($,Z){if(!Z)return;try{return l0.readFileSync(M8($,Z),"utf8")}catch{return}}function E8($){if($.coordinationUrl.protocol!=="https:")return;let Z=v$($.coordinationUrl.hostname),G=R8($.coordinationUrl),Q=v$($.localExternalAddress);if(G===$.localBoundPort&&Z&&(z4(Z)||Q!==void 0&&Z===Q))return{coordinationCaCert:$.localCaCert,coordinationTlsIdentity:$.nodeId};if(!Z)return;let X=new W4({ariaHome:$.ariaHome}).resolveBindingByControlEndpoint({host:Z,port:G});if(!X||X==="ambiguous")return;let W=A8($.ariaHome,X.controlTlsCaFingerprint);if(!W)return;return{coordinationCaCert:W,coordinationTlsIdentity:X.principalFingerprint}}function w8($){return{displayNameSnapshot:$.displayNameSnapshot,nodeId:q0.parse($.nodeId),host:$.host,port:$.port,principalFingerprint:y$.parse($.fingerprint),version:$.version,...$.tlsCaFingerprint?{tlsCaFingerprint:$.tlsCaFingerprint}:{},...$.transport?{transport:$.transport}:{},...$.status?{status:$.status}:{}}}class o0 extends Error{}function f8($){if(!$.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='messages'").get())throw new o0("legacy messages schema requires hard reset: missing messages table");let G=new Set($.prepare("PRAGMA table_info(messages)").all().map((X)=>X.name)),Q=["inbox_address_kind","inbox_address_id"].filter((X)=>!G.has(X));if(Q.length>0)throw new o0(`legacy messages schema requires hard reset: missing columns: ${Q.join(", ")}`);if($.prepare("SELECT COUNT(*) AS count FROM messages WHERE inbox_address_kind IS NULL OR inbox_address_id IS NULL").get().count>0)throw new o0("legacy messages schema requires hard reset: null inbox address rows")}class m${options;nodeId;runtimeIdValue;started=!1;runtimeControl=null;networkStateStore;relayPollTimer;stunClient;discoveryService;mdnsDiscovery;privateLanDiscovery;nearbyPeerDiscovery;nodeStore;ownsNetworkManager=!1;ownsNodeStore=!1;bootstrapOwnerGeneration=1;unsubscribeRuntimeIngressListener;unsubscribeTransportListener;localControlSocket;autonomousLoop;autonomousLoopStartPromise=null;autonomousLoopBootstrap;networkingReadyResolve;networkingReadyReject;networkingReady;constructor($){this.options=$;this.nodeId=$.nodeId;let Z=$.networkManager?.getLocalDisplayNameSnapshot?.()?.trim()||$.arionName;this.runtimeIdValue=B8.parse(`${Z}~${G4(2).toString("hex")}`),this.autonomousLoopBootstrap={memoriaFactory:$.memoriaFactory,router:$.router,authResolver:$.authResolver,runSessionConfig:$.runSessionConfig,mcpServers:$.mcpServers,daemonSafetyPolicy:$.daemonSafetyPolicy,autonomousIntervalMs:$.autonomousIntervalMs},this.networkingReady=new Promise((G,Q)=>{this.networkingReadyResolve=G,this.networkingReadyReject=Q})}get runtimeId(){return this.runtimeIdValue}resolvedBootstrapOwnerGeneration(){return this.options.ownerGenerationHint??this.options.ownerGeneration??1}nextBootstrapRevision($){if(!this.nodeStore)return 0;return I$(this.nodeStore,this.nodeId,$)}resolveBootstrapControlHost($){let Z=($??this.runtimeControl?.networkManager)?.getConfig?.();return v$(Z?.externalEndpoint?.address)??"127.0.0.1"}isRecoverableDaemonBindError($){let Z=$?.code;return Z==="EADDRINUSE"||Z==="EADDRNOTAVAIL"||Z==="EAFNOSUPPORT"}daemonBindCandidates($){let Z=[],G=(Q,Y)=>{if(!Z.some((X)=>X.host===Q&&X.port===Y))Z.push({host:Q,port:Y})};if(G("0.0.0.0",$),$!==0)G("0.0.0.0",0);if(G("127.0.0.1",$),$!==0)G("127.0.0.1",0);return Z}publishBootstrapPhase($,Z){if(!this.nodeStore)return;let G=this.nextBootstrapRevision(Z.ownerGeneration),Q=this.nodeStore.writeRuntimeBootstrapRecord(L8({nodeId:this.nodeId,runtimeId:Z.runtimeId,arionName:this.options.arionName,ownerGeneration:Z.ownerGeneration,bootstrapRevision:G,phase:$,controlPort:Z.controlPort,controlHost:Z.controlHost??this.resolveBootstrapControlHost(Z.networkManager),caFingerprint:h$.parse(Z.certs.fingerprint),caCertPem:Z.certs.caCert,networkManager:Z.networkManager,displayNameSnapshot:Z.displayNameSnapshot,publishedAt:new Date().toISOString(),degradedReason:Z.degradedReason,failedPhase:Z.failedPhase}));if(Q.ownerGeneration!==Z.ownerGeneration||Q.bootstrapRevision!==G)throw Error(`[node-runtime] Runtime bootstrap publication rejected for ${this.nodeId} at generation ${Z.ownerGeneration} revision ${G}`)}configureAutonomousLoop($){return this.autonomousLoopBootstrap={...this.autonomousLoopBootstrap,...$},this.autonomousLoopBootstrap}summarizeAutonomousLoopSafetyPolicy(){return{...this.autonomousLoopBootstrap.daemonSafetyPolicy?.allowedToolCategories?{allowedToolCategories:[...this.autonomousLoopBootstrap.daemonSafetyPolicy.allowedToolCategories]}:{},...this.autonomousLoopBootstrap.daemonSafetyPolicy?.allowedShellCommands?{allowedShellCommands:[...this.autonomousLoopBootstrap.daemonSafetyPolicy.allowedShellCommands]}:{},...typeof this.autonomousLoopBootstrap.daemonSafetyPolicy?.maxWriteOpsPerMinute==="number"?{maxWriteOpsPerMinute:this.autonomousLoopBootstrap.daemonSafetyPolicy.maxWriteOpsPerMinute}:{},...typeof this.autonomousLoopBootstrap.daemonSafetyPolicy?.maxGitPushesPerHour==="number"?{maxGitPushesPerHour:this.autonomousLoopBootstrap.daemonSafetyPolicy.maxGitPushesPerHour}:{}}}getAutonomousLoopStatus(){if(this.autonomousLoop)return this.autonomousLoop.getStatusSummary(this.options.ownerClientKind??null);return{status:"stopped",intervalMs:this.autonomousLoopBootstrap.autonomousIntervalMs??null,lastWakeTickAt:null,lastCheckpointResult:"never",safetyPolicySummary:this.summarizeAutonomousLoopSafetyPolicy(),ownerClientKind:this.options.ownerClientKind??null}}async stopAutonomousLoop(){if(this.autonomousLoop)await this.autonomousLoop.stop(),this.autonomousLoop=void 0;this.autonomousLoopStartPromise=null}async startAutonomousLoop(){let{memoriaFactory:$,router:Z}=this.autonomousLoopBootstrap;if(!this.runtimeControl||!$||!Z)return;if(this.autonomousLoopStartPromise){await this.autonomousLoopStartPromise;return}if(!this.autonomousLoop)this.autonomousLoop=new q$({ariaHome:this.options.ariaHome,arionName:this.options.arionName,runtimeControl:this.runtimeControl,router:Z,memoriaFactory:$,runSessionConfig:this.autonomousLoopBootstrap.runSessionConfig??{activeArion:this.options.arionName},mcpServers:this.autonomousLoopBootstrap.mcpServers,authResolver:this.autonomousLoopBootstrap.authResolver,intervalMs:this.autonomousLoopBootstrap.autonomousIntervalMs,safetyPolicy:this.autonomousLoopBootstrap.daemonSafetyPolicy,signal:this.options.signal,nodeStore:this.nodeStore});this.autonomousLoopStartPromise=this.autonomousLoop.start().catch((G)=>{if(G instanceof Error&&G.kind==="StaleOwnerError"){let Q=G;m.warn(`[node-runtime] Runtime superseded at generation ${Q.claimedGeneration} (current: ${Q.currentGeneration}). Shutting down immediately.`),this.shutdown().catch(()=>{});return}m.error(`[node-runtime] Autonomous loop failed to start for "${this.options.arionName}": ${G instanceof Error?G.message:String(G)}`)}),await this.autonomousLoopStartPromise}async start(){if(this.started&&this.runtimeControl)return;let{ariaHome:$,arionName:Z,signal:G,nodeId:Q}=this.options,Y=this.options.memoriaFactory,X=this.options.nodeStore??new d({ariaHome:$});if(this.bootstrapOwnerGeneration=this.options.ownerGenerationHint??Math.max(X.readRuntimeOwnerRecord(this.nodeId)?.ownerGeneration??0,X.readRuntimeBootstrapRecord(this.nodeId)?.ownerGeneration??0)+1,!this.options.nodeStore)X.close();this.nodeStore??=this.options.nodeStore??new d({ariaHome:$,ownerGeneration:this.bootstrapOwnerGeneration}),this.ownsNodeStore=!this.options.nodeStore;let W=this.nodeStore,O=null,j;this.networkStateStore??=new T8({ariaHome:$});let V;try{V=this.networkStateStore.getDatabase(),this.networkStateStore.claimOwnerEpoch(this.bootstrapOwnerGeneration)}catch(H){if(H instanceof Error&&H.kind==="StaleOwnerError")throw H;throw Error(`[node-runtime] Canonical network state store unavailable: ${H instanceof Error?H.message:String(H)}`)}if(Y&&typeof Y.get==="function")try{let A=(await Y.get(`arions/${Z}/memory.db`)).storage?.getDatabase();if(A)f8(A),O=new _8(A),j=new Q4}catch(H){if(H instanceof o0)throw Error(`[node-runtime] Canonical runtime message store unavailable: ${H.message}`);m.debug(`[node-runtime] Runtime message store unavailable for ${Z}: ${H instanceof Error?H.message:String(H)}`)}let z=this.options.networkManager;if(!z)try{let{createRequire:H}=await import("node:module"),h=await import(H(import.meta.url).resolve("@aria-cli/wireguard/network")),u=new h.PeerRegistry(V),b=new h.NetworkManager($,Z,u);b.setLocalNodeId(this.nodeId),await b.initialize(),z=b}catch(H){throw Error(`[node-runtime] NetworkManager unavailable: ${H instanceof Error?H.message:String(H)}`)}let U=z,F=U.getConfig(),R=X4(F?.signingPublicKey),J=R?Z8(R):null;if(!J)throw Error("[node-runtime] Runtime principal fingerprint unavailable");let x=this.nodeId,_=x,D=G8($,J);if(!D.serverCert||!D.serverKey)throw Error("TLS certificates unavailable — networking requires TLS for all peer communication.");m.debug(`[node-runtime] TLS CA fingerprint: ${D.fingerprint}`);let f=F?.coordinationUrl&&typeof F.publicKey==="string"&&R&&F.signingPrivateKey?K8(z):void 0,T=U.getLocalDisplayNameSnapshot?.()?.trim();if(!T)throw Error("[node-runtime] Runtime bootstrap display name unavailable");let K=this.runtimeIdValue,N=this.resolvedBootstrapOwnerGeneration(),w=this.options.silent??!1,E=this.options.port??0,B=async(H)=>await n1({port:H.port,host:H.host,basePath:$,arionName:this.options.arionName,nodeId:this.nodeId,networkManager:z,memoriaFactory:Y,router:this.options.router,authResolver:this.options.authResolver,enableCrashRecovery:!1,runtimeId:K,ownerGeneration:N,tls:{cert:D.serverCert,key:D.serverKey},silent:w}),L,C,g;for(let H of this.daemonBindCandidates(E)){let A;try{A=await B(H),C=await A.listen(),L=A;break}catch(S){if(g=S,await A?.server.close().catch(()=>{return}),!this.isRecoverableDaemonBindError(S))throw S;m.warn(`[node-runtime] daemon bind ${H.host}:${H.port} failed (${S.code??"unknown"}); retrying`)}}if(!L||!C)throw g instanceof Error?g:Error(String(g));let r=L.server.ariaMessageStore;if(r)O=r,j??=new Q4;let Z0=typeof C==="string"&&C.includes(":")?Number.parseInt(C.split(":").pop(),10):0;if(!Z0)throw Error("Server bound to port 0 — OS failed to assign a port");m.debug(`[node-runtime] HTTPS server listening on ${C}`);let c=L.server.ariaRevocationStore;if(!c)throw await L.server.close(),Error("[node-runtime] Canonical revocation authority unavailable");let Q0=N,P=(H,A={})=>{this.publishBootstrapPhase(H,{controlPort:Z0,runtimeId:K,ownerGeneration:Q0,certs:D,networkManager:z,displayNameSnapshot:T,...A})},q=()=>{let H=W.readRuntimeBootstrapRecord(this.nodeId);if(!H||H.runtimeId!==K||H.ownerGeneration!==Q0||!["control_ready","network_ready","mesh_ready"].includes(H.phase))return;P(H.phase)};if(R)L.server.ariaPeerSigningKeyStore?.set(this.nodeId,R,T);this.ownsNetworkManager=!this.options.networkManager;let v=new Set,I=(H,A={})=>{let S=W.appendRuntimeEvent({nodeId:this.nodeId,runtimeId:K,kind:H,payload:A});for(let h of v)h(S);return S},i=async function*(H){let A=H?.afterRevision??0,S=W.listRuntimeEvents().filter((b)=>(b.revision??0)>A),h,u=(b)=>{if((b.revision??0)<=A)return;S.push(b);let l=h;h=void 0,l?.()};v.add(u);try{while(!0){if(S.length>0){yield S.shift();continue}await new Promise((b)=>{h=b})}}finally{v.delete(u)}},o=$4({receiptStore:W,localNodeId:this.nodeId,signingKey:typeof F?.signingPrivateKey==="string"?F.signingPrivateKey:void 0,onReceiptCommitted:(H)=>{let A=H.status==="queued_for_route"?"durable_send_queued":H.status==="dispatching"?"durable_send_dispatching":H.status==="acked"?"durable_send_acked":H.status==="expired"?"durable_send_expired":null;if(!A)return;I(A,{messageId:H.messageId,senderNodeId:H.senderNodeId,recipientNodeId:H.recipientNodeId,transport:H.transport,status:H.status,deliveryLifecycleRevision:H.deliveryLifecycleRevision,updatedAt:H.updatedAt})},faultCheckpoint:typeof this.options.faultCheckpoint==="function"?(H,A)=>this.options.faultCheckpoint?.(H,A):void 0}),F0=new Set,P0=new Map,a=(H,A)=>{if(!H)return;P0.set(H,A)},S0=(H)=>{if(!H)return;P0.delete(H)},M4=(H)=>{let A=P0.get(H);if(A)return A;let S=z.getActiveTransports?.()?.find((h)=>h.nodeId===H);if(S)return a(H,S.transport),S.transport;return},A4=(H)=>{let{sender:A,recipient:S}=H;if(!A?.name||!S?.name||!A.id||!S.id)return;let h=q0.safeParse(A.id).data,u=q0.safeParse(S.id).data;if(!h||!u)return;let b=M4(h);if(!b)return;try{b.sendPlaintext(Buffer.from(JSON.stringify({deliveryAck:{protocolVersion:1,messageId:String(H.id),senderNodeId:u,recipientNodeId:h,storedAt:Date.now()}})))}catch(l){m.debug(`[node-runtime] delivery ack send failed for ${String(H.id)}: ${l instanceof Error?l.message:String(l)}`)}};{let H=z,A=[],S=!1,h=(p,y,n)=>{let H0=A.findIndex((M)=>M.nodeId===n);if(H0>=0){A[H0]={displayNameSnapshot:p,transport:y,nodeId:n};return}A.push({displayNameSnapshot:p,transport:y,nodeId:n})},u=(p,y)=>{this.options.mailboxRef.current.registerTunnel(p,y)},b=()=>{if(S||!this.options.mailboxRef?.current)return;for(let{transport:p,nodeId:y}of A)u(y,p);A.length=0,S=!0},l=(p,y,n)=>{if(a(n,y),o.registerTunnel(n,y),this.options.mailboxRef?.current)b(),u(n,y);else h(p,y,n);this.options.onTransportEstablished?.(p,y)},E0=(p,y)=>{let n=H.getActiveTransports?.()?.find((M)=>M.nodeId===y);if(n){if(a(y,n.transport),o.registerTunnel(q0.parse(y),n.transport),this.options.mailboxRef?.current)b(),u(y,n.transport);else h(n.displayNameSnapshot,n.transport,y);return}S0(y),o.unregisterTunnel(q0.parse(y)),this.options.mailboxRef?.current?.unregisterTunnel(q0.parse(y));let H0=A.findIndex((M)=>M.nodeId===y);if(H0>=0)A.splice(H0,1);this.options.onTransportTornDown?.(p)};this.unsubscribeTransportListener=H.addTransportListener?.({onRouteBootstrapAvailable:(p,y,n)=>{this.options.mailboxRef?.current?.registerTunnel(n,y)},onTransportUp:l,onTransportDown:E0});for(let{displayNameSnapshot:p,transport:y,nodeId:n}of H.getActiveTransports?.()??[])l(p,y,n);if(this.options.mailboxRef){let p=setInterval(()=>{if(this.options.mailboxRef?.current)b(),clearInterval(p)},2000);if(p.unref)p.unref()}}let E4=!(this.options.ownerClientKind==="local-api"&&this.options.runtimeLifecycle==="scoped"),w4,i$,a$,f4=new Promise((H,A)=>{i$=H,a$=A}),N4=()=>f4;setImmediate(()=>{this.startNetworkingSubsystems({enableBackgroundDiscovery:E4,networkManager:z,networkStateDb:V,peerDiscoveryNetworkManager:f,certs:D,boundPort:Z0,localNodeId:x,localDisplayNameSnapshot:T,localSigningPublicKey:R,ariaHome:$,signal:G,runtimeId:K,republishCurrentBootstrapPhaseIfEndpointChanged:q,commitBootstrapPhase:P,resolveDiscoveryBarrier:i$,rejectDiscoveryBarrier:a$})});let F$=[];if(F$.push(z.addDeliveryAckListener((H)=>{o.handleDeliveryAck(H)})),O)F$.push(z.addMessageListener((H)=>{let A=H;if(!A?.id||!A.sender||!A.content)return!1;if(!_)return m.debug("[node-runtime] Rejected ingress message: missing local recipient node id"),!1;let S=W8({id:`runtime-${String(A.id)}`,source:"arion",content:JSON.stringify({ariaMessage:A})},O,{createQuest(){return null}},m,z.getAllPeerSigningKeysByPrincipal?.()??new Map,void 0,c,void 0,{verificationConfig:{expectedRecipientNodeId:_,...j?{freshnessGuard:j}:{}},localInboxAddress:{kind:"node",nodeId:_},commitIngressReceipt:(h,u)=>{let{resolvedNodeId:b,resolvedPeerFingerprint:l}=u;if(!b)throw Error("[node-runtime] accepted ingress is missing resolvedNodeId");if(!l)throw Error("[node-runtime] accepted ingress is missing resolvedPeerFingerprint");W.commitIngressReceipt({messageId:String(A.id),senderNodeId:q0.parse(b),senderFingerprint:y$.parse(l),runtimeId:K})},commitVerifiedPeerActivation:typeof z.activatePendingPeer==="function"?(h)=>{if(!h.resolvedNodeId)throw Error("[node-runtime] accepted ingress is missing resolvedNodeId for activation");z.activatePendingPeer?.(h.resolvedNodeId)}:void 0,acknowledgeReceipt:A4,faultCheckpoint:typeof this.options.faultCheckpoint==="function"?(h,u)=>this.options.faultCheckpoint?.(h,u):void 0});if(!S)m.debug(`[node-runtime] Rejected remote ingress message ${String(A.id)} sender=${String(A.sender?.id??"unknown")} recipient=${String(A.recipient?.id??"unknown")}`);return S?!0:!1}));this.unsubscribeRuntimeIngressListener=()=>{for(let H of F$.splice(0))H()};let P4=(H)=>{let A=z;if(A.getActiveTransports)for(let{transport:u,nodeId:b}of A.getActiveTransports())H.registerTunnel(b,u);let S;if(A.addTransportListener)S=A.addTransportListener({onRouteBootstrapAvailable:(u,b,l)=>{H.registerTunnel(l,b)},onTransportUp:(u,b,l)=>{H.registerTunnel(l,b)},onTransportDown:(u,b)=>{let l=A.getActiveTransports?.()?.find((E0)=>E0.nodeId===b);if(l){H.registerTunnel(b,l.transport);return}H.unregisterTunnel(b)}});let h=Symbol("attachedMailbox");if(F0.add(h),this.options.mailboxRef)this.options.mailboxRef.current=H;return()=>{if(S?.(),F0.delete(h),this.options.mailboxRef?.current===H)this.options.mailboxRef.current=null}};try{if(!L.server.ariaRuntimeOutbox)L.server.decorate("ariaRuntimeOutbox",o);else L.server.ariaRuntimeOutbox=o}catch{L.server.ariaRuntimeOutbox=o}P("starting");let H$="tls_bound";P("tls_bound");try{let H=o1({server:L.server}),A=(M)=>Z4("sha256").update(M).digest("hex"),S=new Map,h=(M)=>M.state==="live"&&(!M.leaseSocket||!M.leaseSocket.destroyed&&M.leaseSocket.writable),u=(M)=>M!=="daemon-launcher",b=()=>{let M=Array.from(S.values()).filter((e)=>h(e)&&u(e.clientKind)),k=new Set,s=0;for(let e of M){if(e.pid!=null){if(k.has(e.pid))continue;k.add(e.pid)}s++}return s},l=(M)=>{let k=S.get(M.clientId);if(!k||k.state!=="live")return!1;return k.clientAuthTokenHash===A(M.clientAuthToken)},E0=async({clientId:M})=>{let k=Array.from(S.entries()).filter(([,V0])=>h(V0)).filter(([,V0])=>u(V0.clientKind)),s=new Map,e=[];for(let V0 of k){let O0=V0[1].pid;if(O0==null){e.push(V0);continue}let n$=s.get(O0);if(!n$||V0[1].attachedAt>n$[1].attachedAt)s.set(O0,V0)}let b0=[...s.values(),...e],s0=S.get(M)?.pid;return b0.map(([V0,O0])=>({clientId:V0,clientKind:O0.clientKind,displayLabel:O0.displayName?`${O0.displayName} (pid ${O0.pid??"?"})`:O0.pid?`${Z} (pid ${O0.pid})`:O0.clientKind==="pipe"?"Attached pipe":"Attached terminal",self:V0===M||s0!=null&&O0.pid!=null&&s0===O0.pid,attachedAt:O0.attachedAt,lastSeenAt:O0.lastSeenAt}))},p=V4({status:()=>({nodeId:this.nodeId,runtimeId:K,port:Z0,attachedClients:b(),autonomousLoop:this.getAutonomousLoopStatus()}),startAutonomousLoop:async(M)=>{return this.configureAutonomousLoop({...typeof M?.intervalMs==="number"?{autonomousIntervalMs:M.intervalMs}:{},...M?.safetyPolicy?{daemonSafetyPolicy:M.safetyPolicy}:{}}),await this.startAutonomousLoop(),{nodeId:this.nodeId,runtimeId:K,port:Z0,attachedClients:b(),autonomousLoop:this.getAutonomousLoopStatus()}},stopAutonomousLoop:async()=>{return await this.stopAutonomousLoop(),{nodeId:this.nodeId,runtimeId:K,port:Z0,attachedClients:b(),autonomousLoop:this.getAutonomousLoopStatus()}},server:L.server,subscribeRuntimeEvents:i});try{if(!L.server.ariaRuntimeLocalControl)L.server.decorate("ariaRuntimeLocalControl",p);else L.server.ariaRuntimeLocalControl=p}catch{L.server.ariaRuntimeLocalControl=p}$$(L.server,{authorizeAttachedClient:(M,k)=>{let s=Y4.safeParse(M);if(!s.success)return!1;return l({clientId:s.data,clientAuthToken:k})}});try{if(!L.server.ariaAttachedClientControl)L.server.decorate("ariaAttachedClientControl",{listAttachedClients:E0,countAttachedClients:b,authorizeAttachedClient:l});else L.server.ariaAttachedClientControl={listAttachedClients:E0,countAttachedClients:b,authorizeAttachedClient:l}}catch{L.server.ariaAttachedClientControl={listAttachedClients:E0,countAttachedClients:b,authorizeAttachedClient:l}}let y=()=>{let M=L.server.ariaRuntimeMessageControl;if(!M)throw Error("Runtime message control unavailable for local attach");return M},n=()=>{let M=L.server.ariaPeerLocalControl;if(!M)throw Error("Peer local control unavailable for local attach");return M},H0=async()=>(this.nearbyPeerDiscovery?.getVisiblePeers()??[]).map(w8);try{let k={...L.server.ariaPeerLocalControl??{},listNearbyPeers:async()=>H0()};if(!L.server.ariaPeerLocalControl)L.server.decorate("ariaPeerLocalControl",k);else L.server.ariaPeerLocalControl=k}catch{L.server.ariaPeerLocalControl={listNearbyPeers:async()=>H0()}}H$="control_ready",this.localControlSocket=await O2({socketPath:this.options.runtimeSocketPath??B0.join($,"node",`${this.nodeId}.sock`),localControl:p,listInbox:async(M)=>(await y().listInbox({limit:M?.limit??100,unreadOnly:M?.unreadOnly??!1})).filter((k)=>typeof M?.cursor?.afterCreatedAt==="number"?k.createdAt>=M.cursor.afterCreatedAt:!0),listDirectClientInbox:async(M,k)=>{let s=y().listDirectClientInbox;if(!s)throw Error("Direct client inbox not available");let e=k?.cursor?.afterCreatedAt,b0=await s({clientId:M.clientId,limit:k?.limit??100,unreadOnly:k?.unreadOnly??!1});return typeof e==="number"?b0.filter((p0)=>p0.createdAt>=e):b0},subscribeRuntimeEvents:i,listPeers:async()=>n().listPeers(),listNearbyPeers:async()=>H0(),attachClient:async({clientKind:M,pid:k,displayName:s})=>{let e=Y4.parse(k?`client-pid-${k}`:`client-${$8()}`),b0=S.get(e),p0=G4(32).toString("hex"),s0=b0?.attachedAt??new Date().toISOString();return S.set(e,{clientKind:M,attachedAt:s0,lastSeenAt:new Date().toISOString(),clientAuthTokenHash:A(p0),state:"live",pid:k,displayName:s}),I("client_attached",{clientId:e,clientKind:M,ownership:b0?"reattached":"new"}),{clientId:e,clientAuthToken:p0}},onClientLeaseSocket:(M,k)=>{let s=S.get(M);if(s)s.leaseSocket=k},listAttachedClients:async(M)=>E0({clientId:M.clientId}),authorizeAttachedClient:l,detachClient:async({clientId:M})=>{let k=S.get(M);if(!k)return{detached:!1};return k.state="draining",L.server.ariaMessageStore?.deleteForInbox?.({kind:"client",clientId:M}),S.delete(M),I("client_detached",{clientId:M,clientKind:k.clientKind}),{detached:!0}},onMessageReceived:(M)=>{z.addMessageListener?.(()=>{return M(),!1})},log:(M,k)=>{try{let s=B0.join($,"logs");l0.mkdirSync(s,{recursive:!0});let e=JSON.stringify({ts:new Date().toISOString(),level:M,source:"local-control-socket",message:k});l0.appendFileSync(B0.join(s,"daemon-auth.jsonl"),e+`
|
|
13
|
+
`)}catch{}}}),P("control_ready"),this.runtimeControl={nodeId:this.nodeId,runtimeId:K,displayNameSnapshot:T,port:Z0,networkManager:z,server:L,certs:D,runtimeOutbox:o,revocationStore:c,networkCoordinator:w4,localControl:p,runtimeAdmin:H,waitForInitialDiscovery:N4,registerMailbox:P4};try{if(!L.server.ariaRuntimeBootstrapControl)L.server.decorate("ariaRuntimeBootstrapControl",{getRuntimeBootstrap:async()=>{let M=W.readRuntimeBootstrapRecord(this.nodeId);if(!M)throw Error("Runtime bootstrap unavailable");return M}});else L.server.ariaRuntimeBootstrapControl={getRuntimeBootstrap:async()=>{let M=W.readRuntimeBootstrapRecord(this.nodeId);if(!M)throw Error("Runtime bootstrap unavailable");return M}}}catch{L.server.ariaRuntimeBootstrapControl={getRuntimeBootstrap:async()=>{let M=W.readRuntimeBootstrapRecord(this.nodeId);if(!M)throw Error("Runtime bootstrap unavailable");return M}}}H$="network_ready",P("network_ready"),this.started=!0}catch(H){try{P("degraded",{degradedReason:H instanceof Error?H.message:String(H),failedPhase:H$})}catch{}if(this.relayPollTimer)clearTimeout(this.relayPollTimer);if(this.unsubscribeRuntimeIngressListener?.(),this.unsubscribeTransportListener?.(),this.stunClient?.stop(),this.discoveryService?.stop(),await this.nearbyPeerDiscovery?.stop(),this.unsubscribeRuntimeIngressListener=void 0,this.unsubscribeTransportListener=void 0,this.relayPollTimer=void 0,this.stunClient=void 0,this.discoveryService=void 0,this.mdnsDiscovery=void 0,this.privateLanDiscovery=void 0,this.nearbyPeerDiscovery=void 0,this.autonomousLoop){try{await this.autonomousLoop.stop()}catch{}this.autonomousLoop=void 0}this.autonomousLoopStartPromise=null;try{await this.localControlSocket?.close()}catch{}this.localControlSocket=void 0;try{await L?.server.close()}catch{}if(this.ownsNetworkManager)try{await z.shutdown?.()}catch{}if(this.ownsNodeStore){try{this.nodeStore?.close()}catch{}this.nodeStore=void 0,this.ownsNodeStore=!1}throw this.networkStateStore?.close(),this.networkStateStore=void 0,this.ownsNetworkManager=!1,this.runtimeControl=null,this.started=!1,H}}async startNetworkingSubsystems($){let{enableBackgroundDiscovery:Z,networkManager:G,networkStateDb:Q,peerDiscoveryNetworkManager:Y,certs:X,boundPort:W,localNodeId:O,localDisplayNameSnapshot:j,localSigningPublicKey:V,ariaHome:z,signal:U,runtimeId:F,republishCurrentBootstrapPhaseIfEndpointChanged:R,commitBootstrapPhase:J,resolveDiscoveryBarrier:x,rejectDiscoveryBarrier:_}=$;m.info("[node-runtime] Starting networking subsystems (deferred)");try{let D,f=async()=>{};if(Z){D=new X8(Q);let T=G;this.stunClient=new x8(void 0,60000),this.stunClient.start((E)=>{let B=T.getConfig();if(!B)return;if(B.externalEndpoint?.address!==E.address||B.externalEndpoint?.port!==E.port)m.debug(`[node-runtime] STUN endpoint changed: ${B.externalEndpoint?.address??"?"}:${B.externalEndpoint?.port??"?"} → ${E.address}:${E.port}`),T.updateExternalEndpoint?.(E.address,E.port),R(),this.discoveryService?.heartbeat().catch(()=>{}),T.resetRelayUpgradeBackoff?.()});let K=T.getConfig();if(K?.coordinationUrl){let E;try{E=O4(K.coordinationUrl).toString()}catch(L){m.debug(`[node-runtime] Peer discovery disabled: ${L.message}`)}let B=X4(K.signingPublicKey);if(E&&typeof K.publicKey==="string"&&B&&K.signingPrivateKey&&Y){let L=new URL(E),C=E8({ariaHome:z,nodeId:this.nodeId,coordinationUrl:L,localCaCert:X.caCert,localBoundPort:W,localExternalAddress:K.externalEndpoint?.address});if(L.protocol==="https:"&&!C)m.debug(`[node-runtime] Peer discovery disabled: no pinned coordination trust for ${E}`);else{let g=J8.parse(K.publicKey),r=y$.parse(Z4("sha256").update(Buffer.from(B,"base64")).digest("hex")),Z0=(c,Q0)=>{let q=j8({operation:c,principal:{nodeId:O,principalFingerprint:r,transportPublicKey:g,bindingGeneration:1,displayNameSnapshot:j},target:{nodeId:O,principalFingerprint:r,transportPublicKey:g,bindingGeneration:1,displayNameSnapshot:j},namespace:"mesh",policyEpoch:1,payload:Q0});return z8(q,K.signingPrivateKey)};this.discoveryService=new H8({networkManager:Y,nodeId:this.nodeId,coordinationUrl:E,displayNameSnapshot:j,signal:U,pollIntervalMs:60000,signingPublicKey:B,signingPrivateKey:K.signingPrivateKey,envelopeSigner:Z0,...C??{},getLocalRegistrationState:()=>{let c=T.getConfig(),Q0=c?.externalEndpoint?.address?.trim(),P=c?.listenPort,q=typeof c?.endpointRevision==="number"?c.endpointRevision:void 0;if(!Q0||typeof P!=="number"||!Number.isInteger(P)||P<1)return;return{endpointHost:Q0,endpointPort:P,endpointRevision:typeof q==="number"&&Number.isInteger(q)&&q>=0?q:0}}}),this.discoveryService.on("peerJoined",(c)=>{m.debug(`[node-runtime] Peer discovered: ${c}`)}),this.discoveryService.on("peerLeft",(c)=>{m.debug(`[node-runtime] Peer left: ${c}`)}),this.discoveryService.on("error",(c)=>{m.debug(`[node-runtime] Peer discovery error: ${c.message}`)}),this.discoveryService.start(),f=()=>this.discoveryService.waitForInitialSync()}}}if(V){this.mdnsDiscovery=new Q8({nodeId:this.nodeId,displayNameSnapshot:j,signingPublicKey:V,httpPort:W,signal:U,tlsCaFingerprint:h$.parse(X.fingerprint)}),this.mdnsDiscovery.on("peerFound",(B)=>{m.debug(`[node-runtime] mDNS peer visible: ${B.displayNameSnapshot} (${B.host})`)}),this.mdnsDiscovery.on("peerLost",(B)=>{m.debug(`[node-runtime] mDNS peer gone: ${B}`)}),this.mdnsDiscovery.on("error",(B)=>{m.debug(`[node-runtime] mDNS disabled (multicast may be blocked): ${B.message}`)});let E=[this.mdnsDiscovery];if(Z)this.privateLanDiscovery=new O8({nodeId:this.nodeId,displayNameSnapshot:j,signingPublicKey:V,httpPort:W,signal:U,tlsCaFingerprint:h$.parse(X.fingerprint),getAdvertisedHosts:()=>{let B=T.getConfig();return V8({externalHost:B?.externalEndpoint?.address})}}),this.privateLanDiscovery.on("peerFound",(B)=>{m.debug(`[node-runtime] private-LAN peer visible: ${B.displayNameSnapshot} (${B.host})`)}),this.privateLanDiscovery.on("peerLost",(B)=>{m.debug(`[node-runtime] private-LAN peer gone: ${B.nodeId} (${B.host})`)}),this.privateLanDiscovery.on("error",(B)=>{m.debug(`[node-runtime] private-LAN discovery degraded: ${B.message}`)}),E.push(this.privateLanDiscovery);this.nearbyPeerDiscovery=new Y8(E),this.nearbyPeerDiscovery.start()}let N=T.getConfig(),w;if(N?.coordinationUrl)try{w=O4(N.coordinationUrl).toString()}catch{w=void 0}if(w){let E=new Set,B=U,L=(this.runtimeControl?.server.server).ariaPairControl;if(!L?.ingestRelayedPairRequest)throw Error("Relay pairing requires runtime-owned pair control ingestion");let C=L.ingestRelayedPairRequest,g=async()=>{if(B?.aborted)return;try{let r=T.getConfig(),Z0=r?.signingPrivateKey,c=j4.safeParse(r?.signingPublicKey).data;if(!Z0||!c)return;let Q0=Date.now().toString(),P=`relay-pending:${O}:${Q0}`,q="";try{let{createPrivateKey:o,sign:F0}=await import("node:crypto"),P0=o({key:Buffer.from(Z0,"base64"),format:"der",type:"pkcs8"});q=F0(null,Buffer.from(P,"utf8"),P0).toString("base64")}catch{return}let v=new URLSearchParams({targetNodeId:O,signingPublicKey:c,signature:q,timestamp:Q0}),I=await U8(`${w}/api/v1/pair/relay-pending?${v}`,{signal:AbortSignal.timeout(5000)});if(!I.ok)return;let i=F8.parse(await I.json());if(!i.requests?.length)return;for(let o of i.requests){if(E.has(o.id))continue;try{await C(o),E.add(o.id)}catch{E.delete(o.id)}}if(E.size>1e4)E.clear()}catch{}finally{if(!B?.aborted)this.relayPollTimer=setTimeout(()=>{g()},5000)}};g()}}else m.debug("[node-runtime] Skipping private-LAN, coordination, STUN, and relay discovery for scoped local-api runtime");if(m.info("[node-runtime] Networking subsystems started successfully (deferred)"),this.discoveryService)f().then(()=>{J("mesh_ready"),x()}).catch((T)=>{try{J("degraded",{degradedReason:T instanceof Error?T.message:String(T),failedPhase:"mesh_ready"})}catch{}x()});else J("mesh_ready"),x();this.networkingReadyResolve?.()}catch(D){m.error(`[node-runtime] Failed to start networking subsystems: ${D instanceof Error?D.message:String(D)}`);try{J("degraded",{degradedReason:D instanceof Error?D.message:String(D),failedPhase:"mesh_ready"})}catch{}x(),this.networkingReadyReject?.(D instanceof Error?D:Error(String(D)))}}async shutdown(){if(!this.started||!this.runtimeControl)return;if(this.publishBootstrapPhase("stopped",{controlPort:this.runtimeControl.port,runtimeId:this.runtimeControl.runtimeId,ownerGeneration:this.resolvedBootstrapOwnerGeneration(),certs:this.runtimeControl.certs,networkManager:this.runtimeControl.networkManager,displayNameSnapshot:this.runtimeControl.displayNameSnapshot}),this.relayPollTimer)clearTimeout(this.relayPollTimer);if(this.unsubscribeRuntimeIngressListener?.(),this.unsubscribeTransportListener?.(),this.stunClient?.stop(),this.discoveryService?.stop(),await this.nearbyPeerDiscovery?.stop(),this.autonomousLoop)await this.autonomousLoop.stop(),this.autonomousLoop=void 0;this.autonomousLoopStartPromise=null,await this.localControlSocket?.close(),this.localControlSocket=void 0;try{await this.runtimeControl.server.server.close()}catch{}if(this.ownsNetworkManager)try{await this.runtimeControl.networkManager.shutdown?.()}catch{}if(this.ownsNodeStore)this.nodeStore?.close();this.networkStateStore?.close(),this.runtimeControl=null,this.started=!1,this.relayPollTimer=void 0,this.stunClient=void 0,this.discoveryService=void 0,this.mdnsDiscovery=void 0,this.privateLanDiscovery=void 0,this.nearbyPeerDiscovery=void 0,this.networkStateStore=void 0,this.nodeStore=void 0,this.ownsNodeStore=!1,this.bootstrapOwnerGeneration=1,this.unsubscribeRuntimeIngressListener=void 0,this.unsubscribeTransportListener=void 0}control(){if(!this.runtimeControl)throw Error("[node-runtime] start() must be called before control()");return this.runtimeControl}}class g${nodeStore;ownsNodeStore;constructor($){if($.nodeStore){this.nodeStore=$.nodeStore,this.ownsNodeStore=!1;return}if(!$.ariaHome)throw Error("[runtime-event-journal] ariaHome or nodeStore is required");this.nodeStore=new d({ariaHome:$.ariaHome}),this.ownsNodeStore=!0}close(){if(this.ownsNodeStore)this.nodeStore.close()}record($){return this.nodeStore.appendRuntimeEvent($)}list(){return this.nodeStore.listRuntimeEvents()}}function v8($){let Z=$.networkManager.getConfig?.();if(typeof Z?.signingPublicKey!=="string"||Z.signingPublicKey.trim().length===0)throw Error(`[host-supervisor] Runtime control missing durable principal TLS identity for ${$.nodeId}`);let G=h8.parse(Z.signingPublicKey.trim()),Q=C8(G);if(!Q)throw Error(`[host-supervisor] Runtime control missing durable principal TLS identity for ${$.nodeId}`);return q8.parse(Q)}function m8($){let Z=$.nodeStore.readRuntimeBootstrapRecord($.nodeId);if(!Z)return;try{let G=W$(Z,`[host-supervisor] Runtime bootstrap for ${$.nodeId}`);return{host:G.controlEndpoint.host,port:G.controlEndpoint.port,tlsCaFingerprint:D4.parse(G.tls.caFingerprint),tlsServerIdentity:f0(G,`[host-supervisor] Runtime bootstrap for ${$.nodeId}`),protocolVersion:G.protocolVersion}}catch(G){p$.warn(`[host-supervisor] Suppressing local control endpoint for ${$.nodeId}: ${G instanceof Error?G.message:String(G)}`);return}}class K4 extends Error{nodeId;ownerPid;ownerRuntimeId;constructor($){super(`[host-supervisor] Refusing to start a second runtime for node ${$.nodeId}; live owner pid ${$.runtimePid} already claims runtime ${$.runtimeId}`);this.name="HostSupervisorSplitBrainError",this.nodeId=$.nodeId,this.ownerPid=$.runtimePid,this.ownerRuntimeId=$.runtimeId}}var A0=new Map,B$=new Map,c$=null;function g8($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}async function u$($,Z){let G=B$.get($)??Promise.resolve(),Q,Y=new Promise((X)=>{Q=X});B$.set($,G.then(()=>Y)),await G;try{return await Z()}finally{if(Q?.(),B$.get($)===Y)B$.delete($)}}var c8=600000,u8=12;class R4{runtimeRoot;heartbeatIntervalMs;staleClientTtlMs;runtimeFactory;isPidAlive;heartbeatCount=0;memoryLogPath=null;peakRssMb=0;isHeartbeatStale($){let Z=new Date($.lastHeartbeat).getTime();if(isNaN(Z))return!0;let G=this.now().getTime()-this.heartbeatIntervalMs*3;return Z<G}now;resolveNode;gcRanOnce=!1;constructor($={}){this.runtimeRoot=$.runtimeRoot??B4(),this.heartbeatIntervalMs=$.heartbeatIntervalMs??5000,this.staleClientTtlMs=$.staleClientTtlMs??c8,this.runtimeFactory=$.runtimeFactory??(async(Z)=>{let G=new m$(Z);return{runtimeId:G.runtimeId,start:()=>G.start(),configureAutonomousLoop:(Q)=>G.configureAutonomousLoop(Q),startAutonomousLoop:()=>G.startAutonomousLoop(),shutdown:()=>G.shutdown(),runtimeControl:()=>G.control()}}),this.isPidAlive=$.isPidAlive??g8,this.now=$.now??(()=>new Date),this.resolveNode=$.resolveNode??J4}runStartupGCOnce(){if(this.gcRanOnce)return;this.gcRanOnce=!0;try{let $=T4(this.runtimeRoot);if($.removedOwnerRecords>0||$.removedSockets>0)console.log(`[host-supervisor] Startup GC: removed ${$.removedOwnerRecords} stale owner records and ${$.removedSockets} orphaned sockets`)}catch{}}async attach($){this.runStartupGCOnce();let Z=_4($.ariaHome),G=await this.resolveNode({ariaHome:Z});return u$(G.nodeId,async()=>{let Q=new d({ariaHome:Z}),Y=A0.get(G.nodeId);if(Y)return Q.close(),this.attachClient(Y,$.clientKind,"reattached",$.runtimeLifecycle??"persistent");let X=Q.readRuntimeOwnerRecord(G.nodeId),W=Q.readRuntimeBootstrapRecord(G.nodeId),O=Math.max(X?.ownerGeneration??0,W?.ownerGeneration??0)+1;if(Q.close(),X){let z=this.isPidAlive(X.runtimePid),U=this.isHeartbeatStale(X);if(z&&!U)throw new K4(X)}let j=new d({ariaHome:Z,ownerGeneration:O}),V=new g$({nodeStore:j});if(X)j.removeRuntimeOwnerRecord(X.nodeId),h0(this.runtimeRoot,X.nodeId),l$(this.runtimeRoot,X.nodeId),V.record({nodeId:G.nodeId,runtimeId:X.runtimeId,kind:"runtime_stale",payload:{staleRuntimePid:X.runtimePid,staleRuntimeId:X.runtimeId}});try{let z=F4(this.runtimeRoot,G.nodeId),U=await this.runtimeFactory({ariaHome:Z,arionName:$.arionName,nodeId:G.nodeId,ownerGenerationHint:O,runtimeSocketPath:z,nodeStore:j,memoriaFactory:$.memoriaFactory,router:$.router,authResolver:$.authResolver,networkManager:$.networkManager,port:$.port,mailboxRef:$.mailboxRef,runSessionConfig:$.runSessionConfig,mcpServers:$.mcpServers,daemonSafetyPolicy:$.daemonSafetyPolicy,autonomousIntervalMs:$.autonomousIntervalMs,ownerClientKind:$.clientKind,runtimeLifecycle:$.runtimeLifecycle,silent:$.silent}),F=U.runtimeId?y8.parse(U.runtimeId):void 0;if(!F)throw Error("[host-supervisor] Runtime factory did not expose a stable runtimeId");let R=this.now().toISOString(),J=this.writeRuntimeOwnerRecord({schemaVersion:1,nodeId:G.nodeId,ariaHome:Z,runtimePid:process.pid,runtimeId:F,displayNameSnapshot:$.arionName,runtimeSocket:z,startedAt:R,lastHeartbeat:R,ownerGeneration:O});await U.start();let x=U.runtimeControl?.()??U.control?.();if(!x)throw Error("[host-supervisor] Runtime factory did not expose a control surface");if(x.runtimeId!==F)throw Error("[host-supervisor] Runtime control runtimeId drifted during startup");let _=this.writeRuntimeOwnerRecord({...J,displayNameSnapshot:x.displayNameSnapshot??$.arionName,lastHeartbeat:this.now().toISOString()}),D={nodeId:G.nodeId,ariaHome:Z,runtime:U,runtimeControl:x,ownerRecord:_,nodeStore:j,eventJournal:V,clients:new Map,heartbeatTimer:this.startHeartbeatLoop(G.nodeId)};A0.set(G.nodeId,D),D.ownerRecord=this.writeHeartbeatRecord(D),this.publishBootstrapRecord(D,"mesh_ready"),D.eventJournal.record({nodeId:D.nodeId,runtimeId:D.runtimeControl.runtimeId,kind:"runtime_started",payload:{ownerGeneration:D.ownerRecord.ownerGeneration,runtimeSocket:D.ownerRecord.runtimeSocket}});let f=this.attachClient(D,$.clientKind,"started",$.runtimeLifecycle??"persistent");if($.clientKind==="daemon-launcher")setTimeout(()=>{D.runtime.startAutonomousLoop?.()},0);return f}catch(z){throw j.removeRuntimeOwnerRecord(G.nodeId),h0(this.runtimeRoot,G.nodeId),V.close(),j.close(),z}})}async shutdownRuntime($){await u$($,async()=>{let Z=A0.get($);if(!Z){h0(this.runtimeRoot,$);return}try{await Z.runtime.shutdown()}catch(G){throw G}clearInterval(Z.heartbeatTimer);try{Z.eventJournal.record({nodeId:Z.nodeId,runtimeId:Z.runtimeControl.runtimeId,kind:"runtime_stopped",payload:{remainingClients:Z.clients.size}}),this.publishBootstrapRecord(Z,"stopped")}finally{A0.delete($),Z.nodeStore.removeRuntimeOwnerRecord($),h0(this.runtimeRoot,$),l$(this.runtimeRoot,$),Z.eventJournal.close(),Z.nodeStore.close()}})}async startRuntimeAutonomousLoop($,Z){await u$($,async()=>{let G=A0.get($);if(!G)throw Error(`[host-supervisor] Cannot start autonomous loop; runtime ${$} is not owned by this process`);try{G.runtime.configureAutonomousLoop?.(Z),await G.runtime.startAutonomousLoop?.()}catch(Q){throw p$.error(`[host-supervisor] Failed to start autonomous loop for node ${$}: ${Q instanceof Error?Q.message:String(Q)}`),Q}})}listRuntimes(){return x4(this.runtimeRoot).filter((Z)=>{if(Z.runtimePid===process.pid&&A0.has(Z.nodeId))return!0;if(this.isPidAlive(Z.runtimePid))return!0;return h0(this.runtimeRoot,Z.nodeId),!1}).sort((Z,G)=>G.lastHeartbeat.localeCompare(Z.lastHeartbeat)).map((Z)=>{let G=A0.get(Z.nodeId),Q=Z.lastHeartbeat,Y=G?m8(G):void 0;return k8.parse({nodeId:Z.nodeId,runtimeId:Z.runtimeId,lastHeartbeat:Q,controlEndpoint:Y,displayNameSnapshot:Z.displayNameSnapshot})})}attachClient($,Z,G,Q="persistent"){let Y=this.now().toISOString(),X=I8.parse(`client-${N8()}`);return $.clients.set(X,{clientId:X,clientKind:Z,attachedAt:Y,lastSeenAt:Y}),$.eventJournal.record({nodeId:$.nodeId,runtimeId:$.runtimeControl.runtimeId,kind:"client_attached",payload:{clientId:X,clientKind:Z,ownership:G}}),{nodeId:$.nodeId,runtimeId:$.runtimeControl.runtimeId,clientId:X,ownership:G,control:$.runtimeControl.localControl,runtime:$.runtimeControl,release:async(W)=>{if($.clients.delete(X),$.eventJournal.record({nodeId:$.nodeId,runtimeId:$.runtimeControl.runtimeId,kind:"client_detached",payload:{clientId:X,clientKind:Z}}),G==="started"&&Q==="scoped"&&W?.preserveRuntime!==!0)await this.shutdownRuntime($.nodeId)}}}startHeartbeatLoop($){let Z=setInterval(()=>{let G=A0.get($);if(!G){clearInterval(Z);return}if(G.ownerRecord=this.writeHeartbeatRecord(G),this.evictStaleClients(G),this.heartbeatCount++,this.heartbeatCount%u8===0)this.logMemorySnapshot(G)},this.heartbeatIntervalMs);return Z.unref?.(),Z}evictStaleClients($){let Z=this.now().getTime()-this.staleClientTtlMs;for(let[G,Q]of $.clients)if(new Date(Q.lastSeenAt).getTime()<Z)$.clients.delete(G),p$.debug(`[host-supervisor] Evicted stale client ${G} (${Q.clientKind}, last seen ${Q.lastSeenAt})`),$.eventJournal.record({nodeId:$.nodeId,runtimeId:$.runtimeControl.runtimeId,kind:"client_detached",payload:{clientId:G,clientKind:Q.clientKind,reason:"stale_eviction"}})}logMemorySnapshot($){try{if(!this.memoryLogPath){let X=U4(b8(),".aria","logs");S8(X,{recursive:!0}),this.memoryLogPath=U4(X,"memory-timeline.jsonl")}let Z=process.memoryUsage(),G=L4.getHeapStatistics(),Q=Math.round(Z.rss/1024/1024);if(Q>this.peakRssMb)this.peakRssMb=Q;let Y={ts:new Date().toISOString(),pid:process.pid,uptimeS:Math.round(process.uptime()),rssMb:Q,peakRssMb:this.peakRssMb,heapUsedMb:Math.round(Z.heapUsed/1024/1024*10)/10,heapTotalMb:Math.round(Z.heapTotal/1024/1024*10)/10,externalMb:Math.round(Z.external/1024/1024*10)/10,arrayBuffersMb:Math.round(Z.arrayBuffers/1024/1024*10)/10,heapSpaces:{totalPhysicalSizeKb:Math.round(G.total_physical_size/1024),mallocedMemoryKb:Math.round(G.malloced_memory/1024),externalMemoryKb:Math.round(G.external_memory/1024),nativeContexts:G.number_of_native_contexts,detachedContexts:G.number_of_detached_contexts},clients:$.clients.size};P8(this.memoryLogPath,JSON.stringify(Y)+`
|
|
14
|
+
`)}catch{}}writeHeartbeatRecord($){let Z={...$.ownerRecord,lastHeartbeat:this.now().toISOString()},G=this.writeRuntimeOwnerRecord(Z);return $.ownerRecord=G,G}writeRuntimeOwnerRecord($){let Z=A0.get($.nodeId),G;if(Z)G=Z.nodeStore.writeRuntimeOwnerRecord($);else{let Q=new d({ariaHome:$.ariaHome,ownerGeneration:$.ownerGeneration});try{G=Q.writeRuntimeOwnerRecord($)}finally{Q.close()}}return d$(this.runtimeRoot,G),G}publishBootstrapRecord($,Z){let G=$.nodeStore.readRuntimeBootstrapRecord($.nodeId);if(G&&G.runtimeId===$.runtimeControl.runtimeId&&G.ownerGeneration===$.ownerRecord.ownerGeneration&&G.phase===Z)return;v8($.runtimeControl),s1({nodeStore:$.nodeStore,nodeId:$.nodeId,runtimeId:$.runtimeControl.runtimeId,ownerGeneration:$.ownerRecord.ownerGeneration,controlPort:$.runtimeControl.port,caFingerprint:D4.parse($.runtimeControl.certs.fingerprint),caCertPem:$.runtimeControl.certs.caCert,networkManager:$.runtimeControl.networkManager,displayNameSnapshot:$.runtimeControl.displayNameSnapshot,phase:Z,controlHost:"127.0.0.1"})}}function IQ(){if(!c$)c$=new R4;return c$}function kQ($,Z){return H4($,Z)}function qQ($,Z){h0($,Z)}function hQ($,Z){let G=new d({ariaHome:Z.ariaHome,ownerGeneration:Z.ownerGeneration});try{let Q=G.writeRuntimeOwnerRecord(Z);return d$($,Q),Q}finally{G.close()}}
|
|
15
|
+
export{Q$ as k,T2 as l,O9 as m,L2 as n,W9 as o,V9 as p,K9 as q,R9 as r,n1 as s,g$ as t,o1 as u,m$ as v,K4 as w,R4 as x,IQ as y,kQ as z,qQ as A,hQ as B};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getErrorMessage as R}from"@aria-cli/types";function w(J,X=new Set){if(X.has(J))return{message:"[circular error reference]"};if(J instanceof Error){X.add(J);let Y={...J,name:J.name,message:J.message,...J.stack?{stack:J.stack}:{}};if(J.cause!==void 0)Y.cause=w(J.cause,X);return Y}if(J&&typeof J==="object")return X.add(J),{...J,...typeof J.message==="string"?{}:{message:R(J)}};return{message:R(J)}}class j extends Error{code="attached-local-client-only";reason;constructor(J){super("attached-local-client-only");this.name="AttachedClientAuthError",this.reason=J}}import{readFileSync as f,existsSync as b,statSync as M}from"fs";import{homedir as h}from"os";import{join as k}from"path";var u=["fast","balanced","powerful","ensemble"];function y(J){return typeof J==="string"&&u.includes(J)}var I=null,L=null,z=null,N=0,U=new Map;function K(J){let X=J?.trim();if(X)return X;let Y=process.env.ARIA_HOME?.trim();if(Y)return Y;return k(process.env.HOME||h(),".aria")}function A(J){if(!b(J))return null;try{return M(J).mtimeMs}catch{return null}}function d(J){let X={...J,env:J.env?{...J.env}:void 0};if(!X.env)return X;for(let[Y,Q]of Object.entries(X.env))if(typeof Q==="string"&&Q.startsWith("${")&&Q.endsWith("}")){let Z=Q.slice(2,-1);X.env[Y]=process.env[Z]||""}return X}function g(J){if(!J.name||typeof J.name!=="string")throw Error('Invalid MCP server config: missing "name" field');if(!J.transport)throw Error(`MCP server "${J.name}": missing "transport" field`);if(!["stdio","sse"].includes(J.transport))throw Error(`MCP server "${J.name}": unknown transport "${J.transport}"`);if(J.transport==="stdio"&&!J.command)throw Error(`MCP server "${J.name}": stdio transport requires "command" field`);if(J.transport==="sse"&&!J.url)throw Error(`MCP server "${J.name}": sse transport requires "url" field`)}function x(J){if(!b(J))return null;try{return JSON.parse(f(J,"utf-8"))}catch{return null}}function q(J,X){if(!J||typeof J!=="object")return[];let Y=J.mcp;if(!Y||typeof Y!=="object"||!Array.isArray(Y.servers))return[];let Q=Y.servers.filter(($)=>!!$&&typeof $==="object"&&typeof $.name==="string"),Z=[];for(let $ of Q)try{let B=d($);g(B),Z.push(B)}catch(B){console.warn(`[Server] Skipping invalid MCP server config from ${X}: ${B instanceof Error?B.message:String(B)}`)}return Z}function v(J,X){let Y=new Set(X.map((Q)=>Q.name));return[...J.filter((Q)=>!Y.has(Q.name)),...X]}function p(){let J=k(K(),"config.json"),X=A(J);if(I&&L===X)return I;try{let Y=x(J);if(Y)return I={activeArion:typeof Y.activeArion==="string"?Y.activeArion:void 0,preferredTier:y(Y.preferredTier)?Y.preferredTier:void 0},z=q(Y,`${K()}/config.json`),L=X,N++,U.clear(),I}catch{}return I={},z=[],L=X,N++,U.clear(),I}function $J(J){p();let X=z??[];if(!J)return[...X];let Y=k(J,"aria.config.json"),Q=A(Y),Z=U.get(J);if(Z&&Z.mtimeMs===Q&&Z.globalVersion===N)return[...Z.servers];let $=x(Y);if(!$){let _=[...X];return U.set(J,{mtimeMs:Q,globalVersion:N,servers:_}),_}let B=q($,Y),W=v(X,B);return U.set(J,{mtimeMs:Q,globalVersion:N,servers:W}),[...W]}import{getErrorStatusCode as m,getErrorMessage as l}from"@aria-cli/types";function c(J){if(!J||typeof J!=="object")return;let X=J;if(X.expose===!0&&typeof X.publicMessage==="string"&&X.publicMessage.trim().length>0)return X.publicMessage;return}function F(J,X){let Y=m(J),Q=c(J);if(Q){if(X&&(Y===void 0||Y>=500))X.error(J,"[Server] Sanitized error:");return Q}if(Y!==void 0&&Y>=400&&Y<500)return l(J);if(X)X.error(J,"[Server] Sanitized error:");return"Internal server error"}function T(J){return J.includes("/")||J.includes("\\")||J.includes("..")||/^[/~]/.test(J)}import{ArionManager as n,ArionStorage as i}from"@aria-cli/aria/server-arions";import{MemoriaPool as t}from"@aria-cli/aria/server-memory";import{createRuntimeDefaultRouter as o}from"@aria-cli/aria/server-models";import{createRuntimeAuthContext as s}from"@aria-cli/auth";class E{maxRequests;windowMs;maxKeys;windows=new Map;constructor(J,X,Y=1e4){this.maxRequests=J,this.windowMs=X,this.maxKeys=Y}check(J){let X=Date.now(),Y=X-this.windowMs;if(this.windows.size>=this.maxKeys&&!this.windows.has(J))this.cleanup(Y);let Q=this.windows.get(J);if(!Q)Q=[],this.windows.set(J,Q);while(Q.length>0&&Q[0]<=Y)Q.shift();if(Q.length>=this.maxRequests)return!1;return Q.push(X),!0}cleanup(J){for(let[X,Y]of this.windows){while(Y.length>0&&Y[0]<=J)Y.shift();if(Y.length===0)this.windows.delete(X)}}}var H=null;async function a(){if(!H){let J=s({ariaHome:K()});H=await o({ariaHome:K(),anthropic:J.legacyApiKeys.anthropic,openai:J.legacyApiKeys.openai,google:J.legacyApiKeys.google,...J.bedrock?{bedrock:J.bedrock}:{},authResolver:J.authResolver})}return H}var V=null,G=null;function zJ(){H=null,V=null,G=null}function kJ(J){V=J,G=null}async function r(J,X,Y){if(V)return V;if(!G)G=(async()=>{let Q=K(Y),Z=new i(Q),$=X??await a(),B=J??new t(Q,$).toFactory(),W=new n(Z,B);if(await W.initialize(),typeof W.setRouter==="function")W.setRouter($);return V=W,W})().catch((Q)=>{throw G=null,Q});return G}var e={type:"object",required:["name","personality"],properties:{name:{type:"string",minLength:1},personality:{type:"object",required:["traits","style"],properties:{traits:{type:"array",items:{type:"string"},minItems:1},style:{type:"string",enum:["formal","casual","technical","friendly"]},quirks:{type:"array",items:{type:"string"}}}},skills:{type:"array",items:{type:"object",required:["name","level"],properties:{name:{type:"string"},level:{type:"string",enum:["beginner","intermediate","advanced","expert"]},description:{type:"string"}}}},profile:{type:"object",properties:{background:{type:"string"}}},strengths:{type:"array",items:{type:"string"}},weaknesses:{type:"array",items:{type:"string"}}}};async function EJ(J){let X=new E(20,60000),Y=await r(J.ariaMemoriaFactory,J.ariaRouter,J.ariaBasePath);J.get("/api/v1/arions",async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let $=await Y.list();return Z.send({arions:$})}),J.get("/api/v1/arions/:name",async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let{name:$}=Q.params;if(T($))return Z.status(400).send({error:`Invalid arion name: "${$}"`});let B=await Y.get($);if(!B)return Z.status(404).send({error:`Arion not found: ${$}`});return Z.send({arion:B})}),J.post("/api/v1/arions",{schema:{body:e}},async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let{name:$,personality:B,skills:W,profile:_,strengths:P,weaknesses:S}=Q.body;if(T($))return Z.status(400).send({error:`Invalid arion name: "${$}"`});let C={name:$,personality:B,skills:W,profile:_,strengths:P,weaknesses:S};try{let O=await Y.hatch(C);return Z.status(201).send({arion:O})}catch(O){let D=O instanceof Error?O.message:"Failed to create arion";if(D.includes("already exists"))return Z.status(400).send({error:D});return Z.status(500).send({error:F(O,Q.log)})}}),J.delete("/api/v1/arions/:name",async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let{name:$}=Q.params,{confirm:B}=Q.query;if(T($))return Z.status(400).send({error:`Invalid arion name: "${$}"`});if(B!=="true")return Z.status(400).send({error:"Retirement requires explicit confirmation. Add ?confirm=true to the request."});try{return await Y.retire($,{confirm:!0}),Z.send({success:!0})}catch(W){let _=W instanceof Error?W.message:"Failed to retire arion";if(_.includes("not found"))return Z.status(404).send({error:_});if(_.includes("default"))return Z.status(400).send({error:_});return Z.status(500).send({error:F(W,Q.log)})}}),J.put("/api/v1/arions/:name/rest",async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let{name:$}=Q.params;if(T($))return Z.status(400).send({error:`Invalid arion name: "${$}"`});try{return await Y.rest($),Z.send({success:!0})}catch(B){let W=B instanceof Error?B.message:"Failed to rest arion";if(W.includes("not found"))return Z.status(404).send({error:W});if(W.includes("retired"))return Z.status(400).send({error:W});return Z.status(500).send({error:F(B,Q.log)})}}),J.put("/api/v1/arions/:name/wake",async(Q,Z)=>{if(!X.check(Q.ip))return Z.status(429).send({error:"Rate limit exceeded"});let{name:$}=Q.params;if(T($))return Z.status(400).send({error:`Invalid arion name: "${$}"`});try{return await Y.wake($),Z.send({success:!0})}catch(B){let W=B instanceof Error?B.message:"Failed to wake arion";if(W.includes("not found"))return Z.status(404).send({error:W});if(W.includes("retired"))return Z.status(400).send({error:W});return Z.status(500).send({error:F(B,Q.log)})}})}
|
|
2
|
+
export{E as C,w as D,j as E,K as F,p as G,$J as H,F as I,T as J,zJ as K,kJ as L,r as M,EJ as N};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Aa as k}from"./index-9xs3gn0p.js";import{randomUUID as D}from"node:crypto";import{AcceptInviteRequestSchema as V,AcceptInviteResponseSchema as M,AcceptInviteTokenRequestSchema as T,AcceptInviteTokenResponseSchema as B,DirectPairRequestSchema as N,DirectPairResponseSchema as F,InboxAddressSchema as O,InboxListRequestSchema as H,InvitePeerRequestSchema as K,InvitePeerResultSchema as Q,CancelInviteRequestSchema as j,CancelInviteResponseSchema as G,CreateInviteRequestSchema as U,CreateInviteResponseSchema as _,NearbyPeerViewSchema as J,OutboundMessageSchema as d,PairRequestDecisionSchema as $,PairRequestResponseSchema as z,PendingInviteViewSchema as W,PeerViewEventSchema as h,PendingPairRequestViewSchema as X,PersistedInboxEventSchema as Y,RepairPeerRequestSchema as Z,RepairPeerResponseSchema as ee,RevokePeerRequestSchema as te,RevokePeerResponseSchema as ne,ResumeRunRequestSchema as y,RuntimeRunEventSchema as q,RunRequestSchema as P,RunResultSchema as v,RuntimeDeliveryReceiptSchema as S,RuntimeEventCursorSchema as re,RuntimeBootstrapRecordSchema as se,RuntimeQueuedReceiptSchema as g,RuntimeStatusSchema as C}from"@aria-cli/tools";import{InboxAddressSchema as w}from"@aria-cli/tools";function b(t){return w.parse({kind:"client",clientId:t})}function A(t,o){let a=t.metadata&&typeof t.metadata==="object"&&!Array.isArray(t.metadata)?{...t.metadata}:{};if(a.senderInbox!==void 0)return{...t,metadata:a};return{...t,metadata:{...a,senderInbox:w.parse(o)}}}async function R(t){if(t.ariaRunControl)return t.ariaRunControl;let{ensureRuntimeRunControl:o}=await import("./runtime-run-control-0r21xdh5.js");if(o(t),!t.ariaRunControl)throw Error("Local control run surface unavailable");return t.ariaRunControl}function E(t){return{runId:`run-${D()}`,wait:()=>t}}async function ae(t){await new Promise((o)=>setTimeout(o,Math.max(t,0)))}async function*L(t,o={pollIntervalMs:1000}){let a=new Map,c=o.initialAfterCreatedAt??0;while(!0){let I=await t(),u=!1;for(let i of I){if(typeof i.createdAt==="number"&&i.createdAt<c)continue;let m=typeof i.id==="string"?i.id:i.nodeId;if(typeof m==="string"){let p=o.getVersionKey?.(i)??JSON.stringify(i);if(a.get(m)===p)continue;a.set(m,p)}if(typeof i.createdAt==="number")c=Math.max(c,i.createdAt);u=!0,yield i}if(!u)await ae(o.pollIntervalMs)}}function Re(t){let o=t.pollIntervalMs??1000,a=()=>{if(!t.server)throw Error("Local control server transport unavailable");return t.server},c=()=>{let e=a().ariaRuntimeMessageControl;if(!e)throw Error("Local control message surface unavailable");return e},I=()=>{let e=a().ariaRuntimeBootstrapControl;if(!e)throw Error("Local control bootstrap surface unavailable");return e},u=()=>{let e=a().ariaPeerLocalControl;if(!e)throw Error("Local control peer surface unavailable");return e},i=()=>{let e=a().ariaPairControl;if(!e)throw Error("Local control pair surface unavailable");return e},m=()=>{let e=a().ariaNetworkAdminControl;if(!e)throw Error("Local control network admin surface unavailable");return e},p=async()=>{let e=typeof t.status==="function"?await t.status():t.status;return C.parse(e)},f=async(e)=>{let n=H.optional().parse(e);return(await c().listInbox({limit:n?.limit??100,unreadOnly:n?.unreadOnly??!1})).map((s)=>Y.parse({...s,inboxAddress:O.parse(s.inboxAddress)})).filter((s)=>typeof n?.cursor?.afterCreatedAt==="number"?s.createdAt>=n.cursor.afterCreatedAt:!0)};return{async submitRun(e){let n=P.parse(e),r=(await R(a())).submitRun;if(!r)throw Error("Local control run surface unavailable");return E(r(n).then((s)=>v.parse(s)))},async submitRunAsAttachedClient(e,n){let r=P.parse(n),s=(await R(a())).submitRun;if(!s)throw Error("Local control run surface unavailable");return E(s(r,{clientId:e.clientId}).then((l)=>v.parse(l)))},async resumeRun(e){let n=y.parse(e),r=(await R(a())).resumeRun;if(!r)throw Error("Local control resume surface unavailable");return v.parse(await r(n))},async resumeRunAsAttachedClient(e,n){let r=y.parse(n),s=(await R(a())).resumeRun;if(!s)throw Error("Local control resume surface unavailable");return v.parse(await s(r,{clientId:e.clientId}))},async*streamRun(e,n){let r=P.parse(e),s=(await R(a())).streamRun;if(!s)throw Error("Local control stream surface unavailable");for await(let l of s(r,n))yield q.parse(l)},async*streamRunAsAttachedClient(e,n,r){let s=P.parse(n),l=(await R(a())).streamRun;if(!l)throw Error("Local control stream surface unavailable");for await(let x of l(s,r,{clientId:e.clientId}))yield q.parse(x)},subscribeRuntimeEvents(e){if(!t.subscribeRuntimeEvents)throw Error("Local control runtime event surface unavailable");return t.subscribeRuntimeEvents(re.optional().parse(e))},async sendBestEffort(e){let n=d.parse(e);return g.parse(await c().sendBestEffort(n))},async sendBestEffortAsAttachedClient(e,n){let r=d.parse(n);return g.parse(await c().sendBestEffort({...r,rawMessage:A(r.rawMessage,b(e.clientId))}))},async sendDurable(e){let n=d.parse(e);return S.parse(await c().sendDurable(n))},async sendDurableAsAttachedClient(e,n){let r=d.parse(n);return S.parse(await c().sendDurable({...r,rawMessage:A(r.rawMessage,b(e.clientId))}))},listInbox:f,subscribeInbox(e){return L(()=>f({limit:100,unreadOnly:!1}),{pollIntervalMs:o,initialAfterCreatedAt:e?.afterCreatedAt??0})},async listPeers(){return(await u().listPeers()).map((e)=>h.parse(e))},async listNearbyPeers(){return(await u().listNearbyPeers()).map((e)=>{let n=e,{tlsFingerprint:r,...s}=e;return J.parse({...s,...n.tlsCaFingerprint===void 0&&typeof r==="string"?{tlsCaFingerprint:r}:{}})})},subscribePeers(){return L(async()=>(await u().listPeers()).map((e)=>h.parse(e)),{pollIntervalMs:o,getVersionKey:(e)=>[e.updatedAt,e.endpointRevision,e.identityState,e.transportState,e.lastSeenAt??"",e.transportPublicKey,e.displayNameSnapshot??""].join("|")})},async getRuntimeStatus(){return p()},...t.startAutonomousLoop?{async startAutonomousLoop(e){return C.parse(await t.startAutonomousLoop?.(e))}}:{},...t.stopAutonomousLoop?{async stopAutonomousLoop(){return C.parse(await t.stopAutonomousLoop?.())}}:{},async getRuntimeBootstrap(){return se.parse(await I().getRuntimeBootstrap())},async listPendingPairRequests(){return(await i().listPendingPairRequests()).map((e)=>X.parse(e))},async respondToPairRequest(e){return z.parse(await i().respondToPairRequest($.parse(e)))},async createInvite(e){return _.parse(await u().createInvite(U.parse(e)))},async listPendingInvites(){return(await u().listPendingInvites()).map((e)=>W.parse(e))},async acceptInviteToken(e){return B.parse(await u().acceptInviteToken(T.parse(e)))},async cancelInvite(e){return G.parse(await u().cancelInvite(j.parse(e)))},async invitePeer(e){return Q.parse(await u().invitePeer(K.parse(e)))},async acceptInvite(e){return M.parse(await i().acceptInvite(V.parse(e)))},async directPair(e){return F.parse(await i().directPair(N.parse(e)))},async revokePeer(e){return ne.parse(await m().revokePeer(te.parse(e)))},async repairPeer(e){return ee.parse(await u().repairPeer(Z.parse(e)))}}}
|
|
2
|
+
export{b as O,A as P,Re as Q};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{HtmlHighlighter as y,detectLanguageFromToolContext as m}from"@aria-cli/aria/server-runner";import{defaultCostConfig as h}from"@aria-cli/aria/server-models";function f(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let o of e){if(typeof o==="string"){t.push(o);continue}if(!o||typeof o!=="object")continue;let n=o;if(typeof n.text==="string")t.push(n.text);else if(typeof n.content==="string")t.push(n.content)}return t.join(`
|
|
2
|
+
`)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text;if(typeof t.content==="string")return t.content}return""}function p(e){if(!Array.isArray(e))return;let t=[];for(let o of e){if(!o||typeof o!=="object")continue;let n=o;if(typeof n.id!=="string"||typeof n.name!=="string")continue;t.push({id:n.id,name:n.name,arguments:n.arguments&&typeof n.arguments==="object"?n.arguments:void 0,...typeof n.thoughtSignature==="string"?{thoughtSignature:n.thoughtSignature}:{}})}return t.length>0?t:void 0}function c(e){let t=[];for(let o of e){if(!o||typeof o!=="object")continue;let n=o,r=typeof n.role==="string"?n.role:"";if(r!=="user"&&r!=="assistant"&&r!=="tool"&&r!=="system")continue;let s=f(n.content),i=typeof n.name==="string"?n.name:void 0,u=typeof n.toolCallId==="string"?n.toolCallId:void 0,l=p(n.toolCalls);t.push({role:r,content:s,...i?{name:i}:{},...u?{toolCallId:u}:{},...l?{toolCalls:l}:{}})}return t}function x(e){return[{role:"user",content:e}]}var w=Symbol("approval_pause"),d="ASK_USER_ANSWERS_EXHAUSTED";class a extends Error{code=d;questions;constructor(e,t=[]){super(e);this.name="AskUserAnswersExhaustedError",this.questions=t}}function A(e){return async()=>{switch(e){case"approve":return!0;case"deny":return!1;default:return w}}}function k(e,t="pause"){return async(o)=>{if(t==="pause"&&e.length<o.length)throw new a("ask_user needs more answers than were provided. Resume the run with askUserAnswers.",o);let n=[];for(let r of o){let s=e.shift();if(s===void 0)throw new a("ask_user requested more answers than provided. Supply askUserAnswers in the request body.",o);n.push({answer:s})}return n}}function E(e){if(e instanceof a)return!0;if(!e||typeof e!=="object")return!1;let t=e;return t.code===d||t.name==="AskUserAnswersExhaustedError"}var g=new y;function M(e,t,o){if(!o||typeof o!=="object")return{};let n=o,r=typeof n.data==="string"?n.data:typeof n.message==="string"?n.message:typeof n.content==="string"?n.content:null;if(!r||r.trim()==="")return{};if(!g)return{};try{let s=m(e,t)??void 0,i=g.highlight(r,s);return{highlighted:i.code,language:s??i.language}}catch{return{}}}function T(e){if(!Array.isArray(e))return;let t=c(e).map((o)=>({role:o.role,content:o.content,...o.name?{name:o.name}:{},...o.toolCallId?{toolCallId:o.toolCallId}:{},...o.toolCalls?{toolCalls:o.toolCalls.map((n)=>({id:n.id,name:n.name,arguments:n.arguments??{},...n.thoughtSignature?{thoughtSignature:n.thoughtSignature}:{}}))}:{}}));return t.length>0?t:void 0}function P(e){let t=e.approvalMode??"pause",o=e.askUserAnswers??[],n={onApprovalNeeded:A(t),workingDir:e.workingDir,userInteraction:{ask:k([...o],"pause")},...e.inboxAddress?{inboxAddress:e.inboxAddress}:{}};if(typeof e.budget==="number")n.costConfig={...h,maxCostPerRequest:e.budget};if(typeof e.maxTurns==="number")n.maxTurns=e.maxTurns;if(e.autonomy)n.autonomy=e.autonomy;if(e.systemPrompt)n.systemPrompt=e.systemPrompt;if(e.noMemory||e.allowedTools||e.deniedTools){let r=[...e.deniedTools??[]];if(e.noMemory)r.push("group:memory");n.toolPolicy={...e.allowedTools?{allow:e.allowedTools}:{},...r.length>0?{deny:r}:{}}}return n}
|
|
3
|
+
export{c as a,x as b,w as c,a as d,A as e,k as f,E as g,M as h,T as i,P as j};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { createServer, type ServerConfig, type ServerInstance } from "./server.js";
|
|
2
|
+
export { NODE_METADATA_SCHEMA_VERSION, canonicalizeAriaHome, nodeMetadataPathForAriaHome, readResolvedNodeSync, resolveOrCreateNode, type ResolvedNode, } from "./runtime/node-metadata.js";
|
|
3
|
+
export { NODE_STORE_SCHEMA_VERSION, NodeStore, nodeStorePathForAriaHome, } from "./runtime/node-store.js";
|
|
4
|
+
export { RuntimeEventJournal } from "./runtime/runtime-event-journal.js";
|
|
5
|
+
export { NodeRuntime, type NodeRuntimeOptions, type NodeRuntimeMailbox, type NodeRuntimeControl, type NodeRuntimeCerts, } from "./runtime/node-runtime.js";
|
|
6
|
+
export { createLocalControlApi, type LocalControlApi, type RunHandle, type PendingPairRequestView, type PairRequestDecision, type PairRequestResponse, type InvitePeerRequest, type InvitePeerResult, type AcceptInviteRequest, type AcceptInviteResponse, type DirectPairRequest, type DirectPairResponse, type RevokePeerRequest, type RevokePeerResponse, type RepairPeerRequest, type RepairPeerResponse, type ResumeRunRequest, type RunRequest, type RunResult, type OutboundMessage, type RuntimeQueuedReceipt, type RuntimeDeliveryReceipt, type InboxCursor, type PersistedInboxEvent, type PeerViewEvent, type RuntimeStatus, } from "./runtime/local-control-api.js";
|
|
7
|
+
export { createRuntimeAdminApi, type RuntimeAdminApi } from "./runtime/runtime-admin-api.js";
|
|
8
|
+
export { HostSupervisor, HostSupervisorSplitBrainError, getHostSupervisor, resolveRuntimeRootDirectory, findRuntimeOwnerRecordByAriaHome, runtimeOwnerRecordPathForNodeId, runtimeSocketsDirectory, runtimeSocketPathForNodeId, readRuntimeOwnerRecord, writeRuntimeOwnerRecord, removeRuntimeOwnerRecord, listRuntimeOwnerRecords, type HostSupervisorOptions, type HostSupervisorAttachInput, type HostSupervisorAttachment, type HostClientKind, } from "./runtime/host-supervisor.js";
|
|
9
|
+
export { generateApiKey, validateApiKey, loadApiKeys, saveApiKeys, listApiKeys, deleteApiKey, type ApiKeyEntry, type GenerateKeyResult, } from "./auth/api-key.js";
|
|
10
|
+
export { setArionManager, resetArionManager } from "./routes/arions.js";
|
|
11
|
+
export { setArionConsultation, resetArionConsultation } from "./routes/council.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as _,B as $,k as J,l as K,m as L,n as M,o as N,p as O,q as P,r as Q,s as R,t as S,u as U,v as V,w as W,x as X,y as Y,z as Z}from"./index-mnt9k223.js";import{K as H,L as I}from"./index-pe0pkp0v.js";import{Q as T}from"./index-rr0sea4c.js";import{S as B,U as C,V as D,W as E,_ as F,da as G}from"./index-9n50yafd.js";import{ea as q,fa as w,ga as x,ha as z,ja as A}from"./index-5tav2m70.js";import"./index-6extw9n6.js";import"./index-raeajnr7.js";import{va as b,xa as f,ya as g}from"./index-ghh3ag4c.js";import"./index-9xs3gn0p.js";export{$ as writeRuntimeOwnerRecord,M as validateApiKey,I as setArionManager,Q as setArionConsultation,K as saveApiKeys,C as runtimeSocketsDirectory,E as runtimeSocketPathForNodeId,D as runtimeOwnerRecordPathForNodeId,B as resolveRuntimeRootDirectory,z as resolveOrCreateNode,H as resetArionManager,P as resetArionConsultation,_ as removeRuntimeOwnerRecord,Z as readRuntimeOwnerRecord,A as readResolvedNodeSync,f as nodeStorePathForAriaHome,x as nodeMetadataPathForAriaHome,J as loadApiKeys,F as listRuntimeOwnerRecords,N as listApiKeys,Y as getHostSupervisor,L as generateApiKey,G as findRuntimeOwnerRecordByAriaHome,O as deleteApiKey,R as createServer,U as createRuntimeAdminApi,T as createLocalControlApi,w as canonicalizeAriaHome,S as RuntimeEventJournal,g as NodeStore,V as NodeRuntime,b as NODE_STORE_SCHEMA_VERSION,q as NODE_METADATA_SCHEMA_VERSION,W as HostSupervisorSplitBrainError,X as HostSupervisor};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { FastifyInstance } from "fastify";
|
|
2
|
+
import { type NodeId, type PeerTransportId, type PrincipalFingerprint, type RuntimeBootstrapRecord } from "@aria-cli/tools/network-runtime";
|
|
3
|
+
import { principalFingerprintFromSigningPublicKey } from "./runtime/principal-binding-authority.js";
|
|
4
|
+
type SharedSigningPublicKey = RuntimeBootstrapRecord["signingPublicKey"];
|
|
5
|
+
export type AuthoritativePeerBinding = {
|
|
6
|
+
nodeId: NodeId;
|
|
7
|
+
principalFingerprint: PrincipalFingerprint;
|
|
8
|
+
transportPublicKey: PeerTransportId;
|
|
9
|
+
continuityRevision: number;
|
|
10
|
+
displayNameSnapshot?: string;
|
|
11
|
+
};
|
|
12
|
+
export type AuthoritativeSignedPeerBinding = AuthoritativePeerBinding & {
|
|
13
|
+
signingPublicKey: SharedSigningPublicKey;
|
|
14
|
+
};
|
|
15
|
+
export type DurablePeerRecord = {
|
|
16
|
+
nodeId: NodeId;
|
|
17
|
+
displayNameSnapshot?: string;
|
|
18
|
+
signingPublicKey: SharedSigningPublicKey;
|
|
19
|
+
};
|
|
20
|
+
export declare const signingPublicKeyFingerprint: typeof principalFingerprintFromSigningPublicKey;
|
|
21
|
+
export declare function hasAuthoritativePeerRegistry(server: FastifyInstance): boolean;
|
|
22
|
+
export declare function readAuthoritativePeerBinding(server: FastifyInstance, nodeId: NodeId): AuthoritativePeerBinding | undefined;
|
|
23
|
+
export declare function readAuthoritativePeerBindingByNodeId(server: FastifyInstance, claimedNodeId: string): AuthoritativePeerBinding | undefined;
|
|
24
|
+
export declare function listAuthoritativePeerBindings(server: FastifyInstance): AuthoritativePeerBinding[];
|
|
25
|
+
export declare function listAuthoritativeSignedPeerBindings(server: FastifyInstance): AuthoritativeSignedPeerBinding[];
|
|
26
|
+
export declare function getDurablePeerRecords(server: FastifyInstance): DurablePeerRecord[];
|
|
27
|
+
export declare function resolveAuthoritativeSignedPeerByFingerprint(server: FastifyInstance, principalFingerprint: PrincipalFingerprint): AuthoritativeSignedPeerBinding | "ambiguous" | undefined;
|
|
28
|
+
export declare function validateSocketPeerPrincipalAuth(server: FastifyInstance, claimedNodeId: string, signingPublicKey: SharedSigningPublicKey): {
|
|
29
|
+
ok: true;
|
|
30
|
+
fingerprint: PrincipalFingerprint;
|
|
31
|
+
nodeId: NodeId;
|
|
32
|
+
displayNameSnapshot?: string;
|
|
33
|
+
} | {
|
|
34
|
+
ok: false;
|
|
35
|
+
error: string;
|
|
36
|
+
};
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { FastifyInstance } from "fastify";
|
|
2
|
+
import { ArionManager, type MemoriaFactory } from "@aria-cli/aria/server-arions";
|
|
3
|
+
import type { ModelRouter } from "@aria-cli/models";
|
|
4
|
+
import "../types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Get (or lazily create) the shared model router for all server routes.
|
|
7
|
+
* This ensures rate limiters, connection pools, and other stateful
|
|
8
|
+
* resources are shared rather than duplicated per-route.
|
|
9
|
+
*/
|
|
10
|
+
export declare function getSharedRouter(): Promise<ModelRouter>;
|
|
11
|
+
/**
|
|
12
|
+
* Reset the ArionManager singleton (for testing)
|
|
13
|
+
*/
|
|
14
|
+
export declare function resetArionManager(): void;
|
|
15
|
+
/**
|
|
16
|
+
* Set a custom ArionManager (for testing)
|
|
17
|
+
*/
|
|
18
|
+
export declare function setArionManager(manager: ArionManager): void;
|
|
19
|
+
/**
|
|
20
|
+
* Create and initialize the ArionManager instance.
|
|
21
|
+
* Uses the server-owned ARIA base path for storage.
|
|
22
|
+
*
|
|
23
|
+
* aria-mhq.2 fix: accepts optional MemoriaFactory parameter so callers
|
|
24
|
+
* can inject the server-level singleton. Falls back to creating a local
|
|
25
|
+
* factory if none provided (for backward compatibility / testing).
|
|
26
|
+
*/
|
|
27
|
+
export declare function createArionManager(injectedFactory?: MemoriaFactory, injectedRouter?: ModelRouter, basePathOverride?: string): Promise<ArionManager>;
|
|
28
|
+
/**
|
|
29
|
+
* Check whether an arion name contains path traversal or separator characters.
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* Register Arion management API routes
|
|
33
|
+
*/
|
|
34
|
+
export declare function registerArionsRoute(server: FastifyInstance): Promise<void>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { FastifyInstance } from "fastify";
|
|
2
|
+
import { ArionConsultation } from "@aria-cli/aria/server-arions";
|
|
3
|
+
import "../types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Reset the ArionConsultation singleton (for testing)
|
|
6
|
+
*/
|
|
7
|
+
export declare function resetArionConsultation(): void;
|
|
8
|
+
/**
|
|
9
|
+
* Set a custom ArionConsultation (for testing)
|
|
10
|
+
*/
|
|
11
|
+
export declare function setArionConsultation(consultation: ArionConsultation): void;
|
|
12
|
+
/**
|
|
13
|
+
* Register Council API route
|
|
14
|
+
*/
|
|
15
|
+
export declare function registerCouncilRoute(server: FastifyInstance): Promise<void>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function getEntrypointErrorStatus(error: unknown, fallbackStatus?: number): number;
|
|
2
|
+
export declare function resolveEntrypointError(error: unknown, logger?: {
|
|
3
|
+
error: (...args: unknown[]) => void;
|
|
4
|
+
}, fallbackStatus?: number): {
|
|
5
|
+
status: number;
|
|
6
|
+
message: string;
|
|
7
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { FastifyInstance } from "fastify";
|
|
2
|
+
import "../types.js";
|
|
3
|
+
export declare function registerHealthRoute(server: FastifyInstance, _options?: {
|
|
4
|
+
networkManager?: import("@aria-cli/tools").NetworkManagerRef;
|
|
5
|
+
nodeId?: import("@aria-cli/tools").NodeId;
|
|
6
|
+
}): Promise<void>;
|