@north-light/cli 0.3.730 → 0.3.732
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/errors.d.ts +5 -0
- package/dist/api/errors.js +1 -1
- package/dist/builtin-memory/northlight-apps/get-started.md +4 -4
- package/dist/clients/attach/overlays/graph.d.ts +2 -0
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/viewer.js +500 -500
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys/import/move.d.ts +2 -0
- package/dist/commands/sys/import/move.js +9 -7
- package/dist/commands/sys/join.js +1 -1
- package/dist/commands/sys/signin.js +2 -2
- package/dist/core/canvas/canvas.d.ts +1 -1
- package/dist/core/canvas/canvas.js +16 -16
- package/dist/core/canvas/history.d.ts +1 -1
- package/dist/core/canvas/history.js +8 -8
- package/dist/core/canvas/tree.d.ts +4 -0
- package/dist/core/canvas/tree.js +6 -6
- package/dist/core/conversation-store/row-store.js +13 -13
- package/dist/core/directory/join.d.ts +6 -26
- package/dist/core/directory/join.js +1 -1
- package/dist/core/environment-starter-script.d.ts +1 -1
- package/dist/core/environment-starter-script.js +4 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/model-auth/activations.js +1 -1
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/storage/client.js +2 -2
- package/dist/daemon/api/bridge.js +2 -2
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/shares.js +1 -1
- package/dist/daemon/crtrd.js +8 -8
- package/dist/daemon/manage.d.ts +2 -7
- package/dist/daemon/manage.js +3 -3
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/apps/get-started.md +4 -4
- package/docs/cli/join-northlight.md +16 -22
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/errors.js +11 -0
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +18 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -3
- package/packages/crouter-api/dist/commands/sys/import/move.js +12 -0
- package/packages/crouter-api/dist/commands/sys/join.js +5 -37
- package/packages/crouter-api/dist/commands/sys/signin.js +6 -4
- package/packages/crouter-api/dist/core/canvas/canvas.js +7 -3
- package/packages/crouter-api/dist/core/canvas/history.js +3 -3
- package/packages/crouter-api/dist/core/canvas/tree.js +20 -0
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -2
- package/packages/crouter-api/dist/core/directory/join.js +35 -86
- package/packages/crouter-api/dist/core/environment-starter-script.js +4 -1
- package/packages/crouter-api/dist/core/grants/sync.js +1 -1
- package/packages/crouter-api/dist/core/providers/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +4 -1
- package/packages/crouter-api/dist/core/storage/client.js +1 -1
- package/packages/crouter-api/dist/daemon/manage.js +2 -16
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/core/directory/join-lock.d.ts +0 -13
- package/dist/core/directory/join-lock.js +0 -1
- package/packages/crouter-api/dist/core/directory/join-lock.js +0 -61
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=k(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=x();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=B(i)?be(i):"reload";B(i)||E({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=x();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),z()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof H)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&w()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=w()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&w()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await Q(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:C,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>_)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||U())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>_)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&M(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(l=>l.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)F(d.operationId,d,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),D()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
|
|
1
|
+
var J=Object.defineProperty;var h=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as L,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as V}from"../shared/env.js";import{coalesceBrokerInbox as Y,entryCards as K}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Q,claimBrokerMail as Z,brokerExtensionState as ee,brokerRecovery as te,mutateBrokerFault as D,recordConversationWriteFault as ie}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ne}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as se,startupClaimsHeld as re}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ae}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as de,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as le,generateAndCommitInitialName as fe}from"./broker-local.js";import{emitEvent as O}from"../core/events/emit.js";import{errorClassFromError as he}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as P,brokerIdleTurnStart as ce,brokerRunTurnBusy as me,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as pe}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ye=3e4,ge=5*6e4,H="inbox daemon unreachable",U=16;let v,be=0;class B extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function ve(){return{tickMs:z(),debounceMs:j()}}h(ve,"resolveCadence");function w(){const r=G();return r===void 0||r.trim()===""?void 0:r}h(w,"currentNodeId");function q(){const r=X();return r!==void 0&&r!==""&&ue(r)}h(q,"profilePaused");function _(r){try{return he(r)}catch{return{class:"unknown"}}}h(_,"safeErrorClass");function E(r){try{O(r)}catch{}}h(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}h(g,"emitFreshBestEffort");function T(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}h(T,"emitStoredBestEffort");function we(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}h(we,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}h(b,"deliveryFields");function _e(r){T(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}h(_e,"emitDeliveryCompleted");function M(r,t,e,i){T(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}h(M,"emitDeliveryFailure");function R(r,t){T(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}h(R,"emitDeliveryAbandoned");function Ee(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
+
`):""}h(Ee,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(W,"isSessionShutdownReason");function Ie(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(Ie,"disposalReasonForShutdown");function ke(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ke,"boundedRuntimeReason");class xe{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=L();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(o=>o.awaitingDequeue!==void 0))return;const n=C(Ee(i.content)),s=this.pendingHandoffs.find(o=>o.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?Ie(i):"reload";W(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ke(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const o of this.signalUnsubscribers.splice(0))o();const s=n;{const o=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of o)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),V()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ye,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ge)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;D(n,{op:"record",input:{link:"daemon\u2192node",op:H,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&te(t).then(e=>e.fault?.op===H?D(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&me())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new B(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof B)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(re()){this.waitingForStartup||(this.waitingForStartup=!0,se(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),P()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await Z(t,"wake",this.reportBodies)}catch(a){throw S(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let o=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ne(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?y.fresh(d=>{this.pendingHandoffs.push({...x([a.entry],"visible"),operationId:d,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),o=!0))}return o&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||q()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),o=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),a=this.isIdle()&&o.length>0&&o.every(l=>l.tier==="deferred"),f=this.visibleRoute(i)==="critical",d=!a&&!f&&e.length>0,c=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(d)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await ee(t)).situational_card}catch(o){this.raiseSituationalFatal(n,o)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...K(n));return i}digest(t,e){try{return Y(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let o;try{o=x(e,t)}catch(d){this.raiseReadFatal(n,d)}let a;try{y.fresh(d=>{a=d,E({level:"info",event:"inbox.delivery.started",operation_id:d,fields:b(o)}),i()})}catch(d){return a===void 0&&this.raiseReadFatal(n,d),M(a,o,"send",d),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...o,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,o){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(d=>d.entry_id)}),i.forEach((d,c)=>{const l=s&&c===i.length-1;this.pi.sendMessage({customType:F,content:d,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},o,f)}sendVisible(t,e,i,n,s,o){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:F,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(de(i,n),s==="idle"){const a=ce();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},o,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(o=>e.has(o.entry_id)),n=new Set(i.map(o=>o.entry_id)),s=this.buffer.filter(o=>!n.has(o.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const d of e.visibleEntries)n.add(d.entry_id);for(const d of e.hiddenEntries)n.add(d.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id))};if(this.runNode&&s==="steer"){let d=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(d=p)});const c=e.visibleEntries.slice(0,d+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(c,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const $=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)$.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const o=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=o;for(const d of f)for(const c of d.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const d=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,d,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const d=this.sendVisible(a.entries,a.cards,a.text,we(a),s,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await le(t,a.text).catch(()=>{}),fe(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||q())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const o of i)await this.sendPromptJoinDelivery(t,"visible",o.entries,[...o.cards,o.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(f){this.raiseReadFatal("poll",f)}let o;try{await y.fresh(async f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const d of n)await t.sendCustomMessage({customType:F,content:d,display:!0})})}catch(f){throw o===void 0&&this.raiseReadFatal("poll",f),M(o,s,"send",f),f}o===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:o,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Q(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const o of e.receipts){const a=s.results.find(f=>f.delivery_id===o.delivery_id);if(a?.outcome!==o.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(o=>o.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const o of e.handoffs)M(o.operationId,o,"receipt_commit",s);return O({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ie(t,s),P()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(o=>!s.has(o.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(o=>!this.claims.has(o)));for(const s of n)i&&_e(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ae(),o=new Set(this.buffer.map(l=>l.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),f=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!a.has(m))),d=new Set(f.flatMap(l=>[...l.entryIds])),c=[...this.claims.keys()].filter(l=>s||d.has(l)&&!o.has(l));return c.length===0?"settled":(this.pendingCommit={handoffs:f,entryIds:c,receipts:c.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Se(r,t){v?.dispose("reload",!1);const e=new xe(r,t,++be);v=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[pe]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(Se,"installWatcher");function Ce(r){const t=Se(r,ve());return()=>t.dispose("shutdown",!1)}h(Ce,"registerCanvasInboxWatcher");var Ge=Ce;export{Ge as default,Ce as registerCanvasInboxWatcher};
|
package/docs/apps/get-started.md
CHANGED
|
@@ -36,12 +36,12 @@ Then pick what your app does from the sections in the sidebar: [use our AI](/doc
|
|
|
36
36
|
|
|
37
37
|
## Run `crtr cloud apps` yourself
|
|
38
38
|
|
|
39
|
-
Everything on this site works with the SDK's own commands and the web console. If you also run crouter, the agent runtime Northlight is built on, you can
|
|
39
|
+
Everything on this site works with the SDK's own commands and the web console. If you also run crouter, the agent runtime Northlight is built on, you can sign your machine in to your Northlight account and manage your apps with `crtr cloud apps`, or let your own crouter agents build and manage them.
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
|
-
npm
|
|
43
|
-
crtr sys
|
|
42
|
+
npm i -g @north-light/cli@latest
|
|
43
|
+
crtr sys signin
|
|
44
44
|
crtr cloud apps mine
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
`crtr sys signin` asks you to approve once in your browser. The full steps, and what signing in changes on your machine, are in [Sign in a machine to your Northlight account](https://crouter.docs.northlight.ai/docs/cli/join-northlight). The CLI is [`@north-light/cli`](https://www.npmjs.com/package/@north-light/cli) on npm, and crouter's own docs are at [crouter.docs.northlight.ai](https://crouter.docs.northlight.ai).
|
|
@@ -1,37 +1,31 @@
|
|
|
1
1
|
---
|
|
2
|
-
title:
|
|
3
|
-
description:
|
|
2
|
+
title: Sign in a machine to your Northlight account
|
|
3
|
+
description: Sign a laptop in to your Northlight account with crtr sys signin so crtr cloud apps commands run as you, and the crtr cloud apps command list.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# Sign in a machine to your Northlight account
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
Signing in makes this machine one of your Northlight account's machines, so `crtr cloud …` commands run as you. Sign in when you want to run `crtr cloud apps` yourself, or to let your own crtr agents build and manage your Northlight apps. Building an app works without it too: the [SDK docs site](https://sdk.docs.northlight.ai/docs/get-started) uses `npx @north-light/sdk` and the web console.
|
|
9
9
|
|
|
10
|
-
Create your account at `https://account.northlight.ai/signup` first. Then install the CLI
|
|
10
|
+
Create your account at `https://account.northlight.ai/signup` first. Then install the CLI and sign in:
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
```bash
|
|
13
|
+
npm i -g @north-light/cli@latest && crtr sys signin
|
|
14
|
+
```
|
|
13
15
|
|
|
14
|
-
|
|
15
|
-
2. The page shows the join command with the token filled in. On your laptop, run it from a plain terminal: `crtr sys join --directory https://account.northlight.ai --token <token>`. Leave your crtr windows open: join stops the daemon itself, holds it down while it writes your identity (so an open viewer cannot restart it early), and starts it again on the joined settings. Run it outside any crtr node, because a node's engine stops with the daemon; from inside one, join refuses with `join_inside_node`. Add `--name <label>` to name the machine on the page. The token works once and expires at the time the page shows; the page shows it only once.
|
|
16
|
+
`crtr sys signin` prints a code and opens the confirm page in your browser. Check the code and click **Allow** once. That one approval signs this computer in to your account, moves this computer's crtr records into it, and registers the computer as one of your account's machines (a signing key is made on the computer; only its public half goes to the directory). Run it from a plain terminal. A computer that signed in earlier without being registered is registered by running `crtr sys signin` again.
|
|
16
17
|
|
|
17
|
-
|
|
18
|
-
crtr sys join --directory https://account.northlight.ai --token <token> --name my-laptop
|
|
19
|
-
```
|
|
18
|
+
Check it: `crtr cloud apps mine` lists the apps you manage.
|
|
20
19
|
|
|
21
|
-
|
|
22
|
-
3. Check it: `crtr cloud apps mine` lists the apps you manage. Before you have joined, it answers `not_joined` and prints these same steps.
|
|
20
|
+
Things to know first:
|
|
23
21
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
- **
|
|
27
|
-
- **There is no unjoin.** The only undo is removing the machine on `/account/machines`.
|
|
28
|
-
- **Removing the machine stops it.** Once you choose **Remove** next to a machine, it gets no new tokens at once and the ones it holds expire within 5 minutes. After that its `cloud` commands answer `machine_revoked`: "This machine was removed from your Northlight account." It stays that way until you create a new join token and run `crtr sys join` again. Files on the computer stay on it.
|
|
29
|
-
- **Your Northlight runtime is unchanged.** `/account/machines` lists it as "Northlight (hosted)", the default: your runtime in Northlight's cloud. Your chat agent at `https://chat.northlight.ai` still runs `crtr cloud apps …` as before.
|
|
30
|
-
- **Joining is not importing.** Join only lets this machine run `crtr cloud …` as you; its nodes and documents stay in its own crtr home. `crtr sys import start` is the separate step that moves them into your Northlight account and turns this computer into a machine your cloud runtime drives.
|
|
22
|
+
- **Signing in moves your crtr home into the account.** Your nodes, crons, usage and history become yours on Northlight, and the computer then runs as a machine your cloud runtime drives.
|
|
23
|
+
- **Removing the machine stops it.** Once you choose **Remove** next to a machine on `/account/machines`, it gets no new tokens at once and the ones it holds expire within 5 minutes. After that its `cloud` commands answer `machine_revoked`: "This machine was removed from your Northlight account." Run `crtr sys signin` again to register it. Files on the computer stay on it.
|
|
24
|
+
- **Your Northlight runtime is unchanged.** `/account/machines` lists it as "Northlight (hosted)", the default: your runtime in Northlight's cloud.
|
|
31
25
|
|
|
32
26
|
## `crtr cloud apps`
|
|
33
27
|
|
|
34
|
-
Every app-management leaf of Northlight's `cloud` provider runs as you and needs a
|
|
28
|
+
Every app-management leaf of Northlight's `cloud` provider runs as you and needs a signed-in machine. `--app-id` takes `app:<client id>` or the bare client id.
|
|
35
29
|
|
|
36
30
|
Your Northlight chat agent at `https://chat.northlight.ai` can run these commands as you, from your Northlight runtime. It can list and change an app (`mine` and `set-scopes` were checked on production). It cannot delete one. Generate keys on your laptop and give an agent only a public JWK, never the private key.
|
|
37
31
|
|
|
@@ -54,6 +48,6 @@ Your Northlight chat agent at `https://chat.northlight.ai` can run these command
|
|
|
54
48
|
| `crtr cloud apps testers list --app-id <id>` | Lists the testers. |
|
|
55
49
|
| `crtr cloud apps testers remove --app-id <id> --email …` (or `--phone …`) | Removes a tester and revokes their grants for the app. Not yet run on production. |
|
|
56
50
|
| `crtr cloud apps set-run-notice-url --app-id <id> --url …` (or `--clear`) | Sets or clears the URL the runtime posts run notices to. https only, plain http on localhost for development, at most 512 characters. |
|
|
57
|
-
| `crtr cloud apps delete --app-id <id> --confirm <client id>` | Deletes the app and removes every person's grant for it. Only you at a
|
|
51
|
+
| `crtr cloud apps delete --app-id <id> --confirm <client id>` | Deletes the app and removes every person's grant for it. Only you at a signed-in machine's terminal can run it: an agent, including your chat agent, is refused with `provider_refused`. |
|
|
58
52
|
|
|
59
53
|
Deleting an app removes every person's grant for it and cannot be undone. Each runtime deletes the app's runs, space and schedules, and the app's next refresh fails with `invalid_grant`. Apps that hold the provider role cannot be deleted.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.732",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.732",
|
|
162
|
+
"@north-light/plugin": "0.3.732",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -985,9 +985,10 @@ export class CrtrClient {
|
|
|
985
985
|
return new Uint8Array(await response.arrayBuffer());
|
|
986
986
|
}
|
|
987
987
|
/** The lean attach-graph projection: display rows, topology, and focus state
|
|
988
|
-
* in one daemon-owned read rather than the full node-summary list.
|
|
989
|
-
|
|
990
|
-
|
|
988
|
+
* in one daemon-owned read rather than the full node-summary list. With
|
|
989
|
+
* `root`, only the tree that contains that node. */
|
|
990
|
+
canvasGraph(root) {
|
|
991
|
+
return this.request('GET', root === undefined ? routes.canvasGraph() : `${routes.canvasGraph()}?root=${encodeURIComponent(root)}`);
|
|
991
992
|
}
|
|
992
993
|
prune(req) {
|
|
993
994
|
return this.request('POST', routes.canvasPrune(), req);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.72';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -55,6 +55,17 @@ export function isDaemonTransportApiError(error) {
|
|
|
55
55
|
|| error.code === 'northlight_unreachable')) || (error.status === 504 && (error.code === 'request_timeout' || error.code === 'deadline_exceeded'))
|
|
56
56
|
|| (error.status >= 500 && error.code === 'daemon_health_unavailable');
|
|
57
57
|
}
|
|
58
|
+
/** A daemon answer that says nothing about the caller's data: the daemon was unreachable, starting, draining for a
|
|
59
|
+
* restart (503 `startup_blocked`), overloaded, or failed server-side. Retrying the same request later can succeed, so a
|
|
60
|
+
* long-lived caller (a broker's inbox poll) retries it rather than treating it as corrupt state. A 4xx other than
|
|
61
|
+
* 408/429 is about the request itself and is not transient. */
|
|
62
|
+
export function isTransientDaemonApiError(error) {
|
|
63
|
+
if (!(error instanceof APIError))
|
|
64
|
+
return false;
|
|
65
|
+
const { status, code, retryable } = error;
|
|
66
|
+
return isDaemonTransportApiError(error) || retryable === true || code === 'startup_blocked'
|
|
67
|
+
|| status === 408 || status === 429 || status >= 500;
|
|
68
|
+
}
|
|
58
69
|
/** The daemon refused the caller's node token. A teardown revokes the broker's token before its process stops, so a broker
|
|
59
70
|
* that sees this on a poll is being shut down, not hitting a corrupt state. */
|
|
60
71
|
export function isTokenRevokedApiError(error) {
|
|
@@ -124,6 +124,8 @@ export class GraphOverlay {
|
|
|
124
124
|
pendingConfirm;
|
|
125
125
|
snapshot;
|
|
126
126
|
snapshotSeq = 0;
|
|
127
|
+
loading = false;
|
|
128
|
+
reloadQueued = false;
|
|
127
129
|
/** True when `source` is a `RemoteCanvasSource` — gates every local disk/
|
|
128
130
|
* SQLite adornment (tokens, activity, fault, attach, focus) to a safe
|
|
129
131
|
* default and makes Enter/r/m/x no-op instead of shelling local lifecycle
|
|
@@ -202,6 +204,15 @@ export class GraphOverlay {
|
|
|
202
204
|
refresh() {
|
|
203
205
|
if (this.handle === undefined)
|
|
204
206
|
return;
|
|
207
|
+
// One read at a time. The 5 s chrome poll calls this; when a read takes
|
|
208
|
+
// longer than the poll, superseding the in-flight read discarded every
|
|
209
|
+
// result and the overlay never left "loading". Instead, let the read finish
|
|
210
|
+
// and run one more afterwards.
|
|
211
|
+
if (this.loading) {
|
|
212
|
+
this.reloadQueued = true;
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.loading = true;
|
|
205
216
|
const seq = ++this.snapshotSeq;
|
|
206
217
|
void this.buildSnapshot().then((snapshot) => {
|
|
207
218
|
if (seq !== this.snapshotSeq)
|
|
@@ -214,6 +225,12 @@ export class GraphOverlay {
|
|
|
214
225
|
// writing raw stderr bytes into the frame.
|
|
215
226
|
this.onRefreshFailure(err);
|
|
216
227
|
this.tui.requestRender();
|
|
228
|
+
}).finally(() => {
|
|
229
|
+
this.loading = false;
|
|
230
|
+
if (this.reloadQueued) {
|
|
231
|
+
this.reloadQueued = false;
|
|
232
|
+
this.refresh();
|
|
233
|
+
}
|
|
217
234
|
});
|
|
218
235
|
}
|
|
219
236
|
invalidate() {
|
|
@@ -234,7 +251,7 @@ export class GraphOverlay {
|
|
|
234
251
|
focused: new Set(),
|
|
235
252
|
};
|
|
236
253
|
}
|
|
237
|
-
const graph = await cliClient().canvasGraph();
|
|
254
|
+
const graph = await cliClient().canvasGraph(this.self);
|
|
238
255
|
const subscriptions = new Map();
|
|
239
256
|
const subscribers = new Map();
|
|
240
257
|
// Edges arrive in `created` order — the same order the per-node reads
|
|
@@ -26,7 +26,6 @@ const daemonStart = defineLeaf({
|
|
|
26
26
|
summary: 'start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)',
|
|
27
27
|
params: [
|
|
28
28
|
{ kind: 'flag', name: 'prepare', type: 'bool', required: false, constraint: 'Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup.' },
|
|
29
|
-
{ kind: 'flag', name: 'force', type: 'bool', required: false, default: false, constraint: 'Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck.' },
|
|
30
29
|
],
|
|
31
30
|
output: [
|
|
32
31
|
{ name: 'started', type: 'boolean', required: true, constraint: 'True when a new daemon process was spawned; false when one was already running.' },
|
|
@@ -39,14 +38,13 @@ const daemonStart = defineLeaf({
|
|
|
39
38
|
],
|
|
40
39
|
outputKind: 'object',
|
|
41
40
|
effects: [
|
|
42
|
-
'Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.',
|
|
43
41
|
'Spawns dist/daemon/crtrd-cli.js detached + unref\'d; it outlives this process.',
|
|
44
42
|
'Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid.'
|
|
45
43
|
],
|
|
46
44
|
},
|
|
47
45
|
run: async (input) => {
|
|
48
46
|
try {
|
|
49
|
-
const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready'
|
|
47
|
+
const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready' });
|
|
50
48
|
return result;
|
|
51
49
|
}
|
|
52
50
|
catch (error) {
|
|
@@ -17,6 +17,7 @@ import { buildSourceJson } from '../../../core/import/export/source.js';
|
|
|
17
17
|
import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
|
|
18
18
|
import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
|
|
19
19
|
import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
|
|
20
|
+
import { registerSignedInMac } from '../../../core/directory/join.js';
|
|
20
21
|
import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
|
|
21
22
|
import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
|
|
22
23
|
import { isPidAlive } from '../../../core/canvas/pid.js';
|
|
@@ -214,11 +215,22 @@ export async function finishMove(move) {
|
|
|
214
215
|
}
|
|
215
216
|
writeMachineCredential(credential.credential);
|
|
216
217
|
writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
|
|
218
|
+
await registerThisMac(move.directoryUrl);
|
|
217
219
|
await stopAllDaemons();
|
|
218
220
|
await spawnDaemon();
|
|
219
221
|
// Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
|
|
220
222
|
deleteMoveRecord();
|
|
221
223
|
}
|
|
224
|
+
/** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
|
|
225
|
+
export async function registerThisMac(directoryUrl) {
|
|
226
|
+
try {
|
|
227
|
+
await registerSignedInMac(directoryUrl, await personBearer(directoryUrl));
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
// A directory that predates person-credential registration refuses it; the move is done either way, and `crtr sys signin` again registers once the directory accepts.
|
|
231
|
+
process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
222
234
|
const ACTIVATION_ATTEMPTS = 3;
|
|
223
235
|
const ACTIVATION_GAP_MS = 30_000;
|
|
224
236
|
/** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
|
|
@@ -1,15 +1,8 @@
|
|
|
1
1
|
// `crtr sys join` registers this runtime with its directory before the daemon starts.
|
|
2
2
|
import { defineLeaf } from '../../core/command.js';
|
|
3
|
-
import { existsSync } from 'node:fs';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import { pluginsDir } from '../../core/scope.js';
|
|
6
3
|
import { joinDirectory } from '../../core/directory/join.js';
|
|
7
|
-
import { apiSocketPath } from '../../core/canvas/paths.js';
|
|
8
4
|
import { listProcessTable } from '../../core/canvas/pid.js';
|
|
9
|
-
import { daemonAnswers } from '../../core/layout-migrate/index.js';
|
|
10
5
|
import { envNodeId } from '../../shared/env.js';
|
|
11
|
-
import { isDaemonRunning } from '../../daemon/pidfile.js';
|
|
12
|
-
import { findDaemonPids, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
|
|
13
6
|
/** Whether a broker (a node's engine) is an ancestor of this process, or cannot be ruled out. Stopping the daemon kills every broker, so a join run from one would die mid-way. */
|
|
14
7
|
export function insideBroker() {
|
|
15
8
|
const table = listProcessTable();
|
|
@@ -27,33 +20,14 @@ export function insideBroker() {
|
|
|
27
20
|
}
|
|
28
21
|
return false;
|
|
29
22
|
}
|
|
30
|
-
/** Daemon control for a person's computer. A container whose daemon is the launcher's PID 1 keeps the offline contract. */
|
|
31
|
-
function daemonControl() {
|
|
32
|
-
if (process.platform === 'linux' && (process.env['CRTR_LAUNCHER_SOCKET'] || existsSync('/run/crtr/launcher.sock')))
|
|
33
|
-
return undefined;
|
|
34
|
-
return {
|
|
35
|
-
// The process table too: a successor spawned just before the join took its lock has no pidfile or socket yet, but boots on the settings the join is about to replace.
|
|
36
|
-
running: async () => isDaemonRunning() || findDaemonPids().length > 0 || await daemonAnswers(apiSocketPath()),
|
|
37
|
-
stop: async () => { await stopAllDaemons(); },
|
|
38
|
-
start: async () => { await spawnDaemon(); },
|
|
39
|
-
// A bare `crtr cloud …` is an unknown command until a daemon's grant sync has installed the `cloud` plugin.
|
|
40
|
-
firstSync: async () => {
|
|
41
|
-
const dir = pluginsDir('user');
|
|
42
|
-
const deadline = Date.now() + 20_000;
|
|
43
|
-
while (dir && Date.now() < deadline && !existsSync(join(dir, 'cloud', 'commands.json')))
|
|
44
|
-
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
45
|
-
},
|
|
46
|
-
insideNode: insideBroker,
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
23
|
export const sysJoinLeaf = defineLeaf({
|
|
50
24
|
name: 'join',
|
|
51
|
-
description: 'register
|
|
52
|
-
whenToUse: '
|
|
25
|
+
description: 'register a hosted runtime with its directory using the provisioning enrollment token, before its daemon starts',
|
|
26
|
+
whenToUse: 'only at a hosted runtime\'s first boot, before the daemon starts, with the enrollment token provisioning passed in. A person\'s own computer registers through `crtr sys signin`.',
|
|
53
27
|
help: {
|
|
54
28
|
name: 'sys join',
|
|
55
29
|
summary: 'exchange a directory enrollment token for a new runtime client key and record the returned identity',
|
|
56
|
-
guide: 'Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon\'s next start replaces this install\'s person with the owner everywhere in canvas.db
|
|
30
|
+
guide: 'Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon\'s next start replaces this install\'s person with the owner everywhere in canvas.db and sets `runtime.issuer` and `runtime.audience` from the key file. It never touches a daemon: while one answers it refuses `daemon_running`. Presenting the token of the stored successful registration again finishes without calling the directory. Any other token generates a new key and registers again.',
|
|
57
31
|
params: [
|
|
58
32
|
{ kind: 'flag', name: 'directory', type: 'string', required: true, constraint: 'Directory base URL (http or https) that minted the token.' },
|
|
59
33
|
{ kind: 'flag', name: 'token', type: 'string', required: true, sensitive: true, constraint: 'Single-use enrollment token. Sensitive: never echoed in output or errors.' },
|
|
@@ -67,19 +41,13 @@ export const sysJoinLeaf = defineLeaf({
|
|
|
67
41
|
{ name: 'canvas_rewrite', type: 'string', required: true, constraint: 'Always `next daemon start`: when canvas.db identity fields are rewritten.' },
|
|
68
42
|
{ name: 'url', type: 'string', required: true, constraint: 'Runtime URL, written to `runtime.audience`.' },
|
|
69
43
|
{ name: 'registered', type: 'boolean', required: true, constraint: 'False when the token matched the stored registration and the directory was not called.' },
|
|
70
|
-
{ name: 'daemon', type: 'string', required: true, constraint: '`restarted` (a daemon was stopped and started on the joined settings), `started` (none was running; join started one and waited, up to 20s, for its first grant sync to install the account\'s provider plugins, so `crtr cloud …` resolves), `not_running` (none was started: a hosted container\'s launcher owns its daemon), or `restart_failed` (joined, but the new daemon did not start: see `daemon_error`, then run `crtr sys daemon start`).' },
|
|
71
|
-
{ name: 'daemon_error', type: 'string', required: false, constraint: 'Why the new daemon did not start, with `daemon: restart_failed`.' },
|
|
72
44
|
],
|
|
73
45
|
outputKind: 'object',
|
|
74
46
|
effects: [
|
|
75
|
-
'Holds `<runtime>/join.lock` (its pid) from the start until the daemon is back; `ensureDaemon` and `sys daemon start` (without `--force`) decline to start a daemon while a live process holds it (including a start already in flight when the join began). A lock whose holder died is reclaimed.',
|
|
76
|
-
'A running daemon is stopped (SIGTERM, then SIGKILL, plus strays) after the directory accepts the registration and before the local writes, then started again. Every broker dies with it and is revived by the new daemon. If the join fails after the stop, the daemon is started again anyway. With no daemon running join starts one anyway, because a bare `crtr cloud …` is an unknown command (it never autostarts a daemon) until a daemon\'s grant sync has installed the provider plugins. Refuses `join_inside_node` when run from inside a node and a daemon is running; refuses `daemon_running` where a container launcher owns the daemon.',
|
|
77
47
|
'On a new token: calls the directory once; on success writes `<runtime>/secrets/runtime-client.json` (mode 0600) with the private key, registration and the token\'s SHA-256, replacing any earlier key file. A refused or failed call writes nothing.',
|
|
78
48
|
'Sends name, platform, crtr version, installed plugin ids and sandbox state with the public key. Before the request it writes `runtime-client.pending.json` (mode 0600); a rerun with the same token and directory reuses that key, so a lost reply is retried safely. The file is deleted on success or a refusal.',
|
|
79
|
-
'
|
|
80
|
-
'Rewrites the legacy local person\'s profile grantees to `app:terminal`.',
|
|
81
|
-
'At the next daemon start, before any listener, the person this install minted (or still the legacy local person) is replaced by the owner in every canvas.db column that holds a person: node, token, grant, cron, audit and usage subjects and grantees, the person\'s identity, and queued cron births. References to the install\'s local terminal grant are cleared and that local grant mirror is deleted so grant sync installs the directory\'s. Free text is unchanged. The start after that changes nothing.',
|
|
49
|
+
'At the next daemon start, before any listener, the person this install minted is replaced by the owner in every canvas.db column that holds a person, and the legacy local person\'s profile grantees become `app:terminal`.',
|
|
82
50
|
],
|
|
83
51
|
},
|
|
84
|
-
run: async (input) => ({ ...(await joinDirectory(input['directory'], input['token'], input['name'] || undefined
|
|
52
|
+
run: async (input) => ({ ...(await joinDirectory(input['directory'], input['token'], input['name'] || undefined)), canvas_rewrite: 'next daemon start' }),
|
|
85
53
|
});
|
|
@@ -12,7 +12,7 @@ import { envNodeId } from '../../shared/env.js';
|
|
|
12
12
|
import { ExitCode } from '../../types.js';
|
|
13
13
|
import { insideBroker } from './join.js';
|
|
14
14
|
import { cliClient } from '../api-client.js';
|
|
15
|
-
import { defaultDirectoryUrl, finishMove, runMove, settleEarlierMove } from './import/move.js';
|
|
15
|
+
import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
|
|
16
16
|
import { WAIT_FOR_PID_ENV } from './import/start.js';
|
|
17
17
|
/** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
|
|
18
18
|
function openBrowser(url) {
|
|
@@ -62,12 +62,12 @@ function startDetachedMove(notify) {
|
|
|
62
62
|
const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
|
|
63
63
|
export const sysSigninLeaf = defineLeaf({
|
|
64
64
|
name: 'signin',
|
|
65
|
-
description: 'sign this computer\'s crtr in to the person\'s Northlight account',
|
|
65
|
+
description: 'sign this computer\'s crtr in to the person\'s Northlight account and register it as one of their machines',
|
|
66
66
|
whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`',
|
|
67
67
|
help: {
|
|
68
68
|
name: 'sys signin',
|
|
69
|
-
summary: 'pair this computer with the person\'s Northlight account in the browser,
|
|
70
|
-
guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
|
|
69
|
+
summary: 'pair this computer with the person\'s Northlight account in the browser, move this computer\'s records into it, and register it with the directory',
|
|
70
|
+
guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account\'s machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
|
|
71
71
|
params: [
|
|
72
72
|
{ kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
|
|
73
73
|
],
|
|
@@ -81,6 +81,7 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
81
81
|
'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
|
|
82
82
|
'On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account\'s result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.',
|
|
83
83
|
'On a moved computer: restarts the daemon so it reconnects to Northlight.',
|
|
84
|
+
'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
|
|
84
85
|
],
|
|
85
86
|
},
|
|
86
87
|
run: async (input) => {
|
|
@@ -97,6 +98,7 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
97
98
|
const machine = readMachineConfig();
|
|
98
99
|
if (machine !== undefined) {
|
|
99
100
|
const { account } = await signIn(directoryUrl, showSignIn, { accept: sameAccountOnly(machine) });
|
|
101
|
+
await registerThisMac(directoryUrl);
|
|
100
102
|
await stopAllDaemons();
|
|
101
103
|
await spawnDaemon();
|
|
102
104
|
return { account };
|
|
@@ -582,8 +582,9 @@ export async function updateNodeTelemetry(nodeId, telemetry) {
|
|
|
582
582
|
/** Stored fields the attach graph displays, plus the two live execution cues it
|
|
583
583
|
* needs. This keeps the interactive graph off the full node-summary projection
|
|
584
584
|
* and its unused runtime, outcome, and placement fields. */
|
|
585
|
-
export async function graphNodes() {
|
|
586
|
-
const
|
|
585
|
+
export async function graphNodes(ids) {
|
|
586
|
+
const db = await openDb();
|
|
587
|
+
const sql = `SELECT
|
|
587
588
|
node_id, name, description, cycles, kind, status, frozen_at,
|
|
588
589
|
telemetry_context_tokens, telemetry_last_activity,
|
|
589
590
|
pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -591,7 +592,10 @@ export async function graphNodes() {
|
|
|
591
592
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
592
593
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
593
594
|
fault_provider_error_json
|
|
594
|
-
FROM node_rows WHERE ${NOT_A_SPARE} ORDER BY created
|
|
595
|
+
FROM node_rows WHERE ${NOT_A_SPARE}${ids === undefined ? '' : ' AND node_id = ANY(?::text[])'} ORDER BY created`;
|
|
596
|
+
const rows = (ids === undefined
|
|
597
|
+
? await db.prepare(sql).all()
|
|
598
|
+
: await db.prepareUncached(sql).all([...ids]));
|
|
595
599
|
return rows.map((row) => {
|
|
596
600
|
const pid = row['pi_pid'] ?? null;
|
|
597
601
|
const pidAlive = isPidPresent(pid);
|
|
@@ -454,10 +454,10 @@ export async function resolveRef(ref) {
|
|
|
454
454
|
ts: messages[messages.length - 1]?.ts ?? node.created,
|
|
455
455
|
nodeName: node.name,
|
|
456
456
|
body: rendered,
|
|
457
|
-
raw:
|
|
457
|
+
raw: async () => {
|
|
458
458
|
const { header, entries } = await conversationStore().read(conversationIdFromPath(file));
|
|
459
459
|
return [header, ...entries].map((entry) => `${JSON.stringify(entry)}\n`).join('');
|
|
460
|
-
}
|
|
460
|
+
},
|
|
461
461
|
path: file,
|
|
462
462
|
};
|
|
463
463
|
}
|
|
@@ -472,7 +472,7 @@ export async function resolveRef(ref) {
|
|
|
472
472
|
ts: msg.ts,
|
|
473
473
|
nodeName: node.name,
|
|
474
474
|
body: msg.text,
|
|
475
|
-
raw:
|
|
475
|
+
raw: () => rawSessionLine(file, index),
|
|
476
476
|
path: file,
|
|
477
477
|
};
|
|
478
478
|
}
|
|
@@ -84,6 +84,26 @@ export async function setSubscriptionActive(subscriber, publisher, active) {
|
|
|
84
84
|
AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(active ? null : configToJson(PASSIVE), (await nodeObject(db, subscriber)).id, (await nodeObject(db, publisher)).id);
|
|
85
85
|
});
|
|
86
86
|
}
|
|
87
|
+
/** `node` and every node in the tree that contains it: climb first managers (oldest subscriber) to the top, then take that
|
|
88
|
+
* top node's whole subtree. The attach graph climbs the same way, so the tree it draws is exactly this set. Empty when `node`
|
|
89
|
+
* is not a node. */
|
|
90
|
+
export async function treeContaining(node) {
|
|
91
|
+
const db = await openDb();
|
|
92
|
+
const self = await getById(db, node);
|
|
93
|
+
if (self?.type !== 'node')
|
|
94
|
+
return [];
|
|
95
|
+
let top = self.id;
|
|
96
|
+
const seen = new Set([top]);
|
|
97
|
+
for (;;) {
|
|
98
|
+
const manager = (await treeEdges(db, 'AND oo.id = ?', top))[0]?.from_id;
|
|
99
|
+
if (manager === undefined || seen.has(manager))
|
|
100
|
+
break;
|
|
101
|
+
seen.add(manager);
|
|
102
|
+
top = manager;
|
|
103
|
+
}
|
|
104
|
+
const below = (await db.prepareUncached(SUBTREE_ALL_IDS_SQL).all(top, top)).map((r) => r.id);
|
|
105
|
+
return [top, ...below];
|
|
106
|
+
}
|
|
87
107
|
/** Who watches `publisher` in the tree — the targets a push fans out to. */
|
|
88
108
|
export async function subscribersOf(publisher) {
|
|
89
109
|
return (await treeEdges(await openDb(), 'AND oo.id = ?', publisher)).map((e) => ({ node_id: e.from_id, active: e.active, created: e.created }));
|