@north-light/cli 0.3.781 → 0.3.783
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 +9 -19
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/charges.d.ts +3 -3
- package/dist/api/dto/charges.js +1 -1
- package/dist/api/dto/inbox.d.ts +2 -0
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/README.md +3 -2
- package/dist/builtin-memory/crouter-sdk/client.md +3 -3
- package/dist/builtin-memory/crouter-sdk/docker.md +6 -10
- package/dist/builtin-memory/crouter-sdk/release-notes.md +25 -3
- package/dist/builtin-memory/crouter-sdk/sourcing.md +94 -0
- package/dist/builtin-memory/insights/capture.md +2 -2
- package/dist/builtin-memory/internal/marketplaces.md +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/builtin-memory/northlight-apps/cli.md +1 -1
- package/dist/builtin-memory/northlight-apps/coding-agents.md +1 -1
- package/dist/builtin-memory/northlight-apps/get-started.md +2 -2
- package/dist/builtin-memory/northlight-apps/guides/watchable-objects.md +1 -1
- package/dist/builtin-memory/northlight-apps/how-it-fits.md +1 -1
- package/dist/builtin-memory/northlight-apps/let-their-ai-use-your-app.md +1 -4
- package/dist/builtin-memory/northlight-apps/quickstart.md +1 -1
- package/dist/cli.js +2 -8
- package/dist/clients/attach/command.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/viewer.js +524 -524
- package/dist/clients/inbox/controller.d.ts +34 -11
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/clients/inbox/dto-adapt.d.ts +1 -0
- package/dist/clients/inbox/dto-adapt.js +1 -1
- package/dist/clients/inbox/surface.js +1 -1
- package/dist/commands/canvas-config.js +2 -2
- package/dist/commands/canvas-use.js +1 -1
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/pkg/account-installs.d.ts +9 -0
- package/dist/commands/pkg/account-installs.js +1 -0
- package/dist/commands/profile/default.js +1 -1
- package/dist/commands/sys/setup-core.d.ts +1 -52
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup-wizard.d.ts +4 -9
- package/dist/commands/sys/setup-wizard.js +2 -1
- package/dist/commands/sys/setup.js +1 -1
- package/dist/commands/sys/signin.d.ts +1 -1
- package/dist/commands/sys/signin.js +6 -3
- package/dist/core/command.d.ts +1 -2
- package/dist/core/command.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/requests.d.ts +2 -0
- package/dist/core/human/requests.js +18 -18
- package/dist/core/ledger/check.d.ts +6 -2
- package/dist/core/ledger/check.js +1 -1
- package/dist/core/llm/run.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/broker/cli-relay.d.ts +0 -2
- package/dist/core/runtime/broker/cli-relay.js +1 -1
- package/dist/core/runtime/broker/run-turn-queue.js +1 -1
- package/dist/core/runtime/broker/turn-cause.d.ts +2 -0
- package/dist/core/runtime/broker/turn-cause.js +1 -1
- package/dist/core/runtime/first-run-offer.d.ts +2 -6
- package/dist/core/runtime/first-run-offer.js +2 -10
- package/dist/core/runtime/front-door.js +8 -9
- package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
- package/dist/core/runtime/start-refusal-notice.js +1 -0
- package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
- package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.js +5 -5
- package/dist/daemon/machine-link/config.d.ts +2 -4
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.js +2 -2
- package/dist/daemon/postgres/cluster.d.ts +3 -3
- package/dist/daemon/postgres/cluster.js +5 -5
- package/dist/daemon/postgres/supervisor.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/apps/cli.md +1 -1
- package/docs/apps/coding-agents.md +1 -1
- package/docs/apps/get-started.md +2 -2
- package/docs/apps/guides/watchable-objects.md +1 -1
- package/docs/apps/how-it-fits.md +1 -1
- package/docs/apps/let-their-ai-use-your-app.md +1 -4
- package/docs/apps/quickstart.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +3 -2
- package/docs/sdk/client.md +3 -3
- package/docs/sdk/docker.md +5 -9
- package/docs/sdk/release-notes.md +25 -3
- package/docs/sdk/sourcing.md +91 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/charges.js +1 -1
- package/packages/crouter-api/dist/daemon/machine-link/config.js +3 -5
- package/packages/crouter-api/dist/daemon/manage.js +3 -3
- 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/scripts/install-runtime.mjs +1 -1
- package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
- package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
- package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
- package/dist/commands/sys/panels/plugins-panel.js +0 -1
- package/dist/core/northlight/previews.d.ts +0 -22
- package/dist/core/northlight/previews.js +0 -1
- package/dist/core/runtime/front-door-login.d.ts +0 -2
- package/dist/core/runtime/front-door-login.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
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};
|
|
1
|
+
var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}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 H,brokerIdleTurnStart as me,brokerRunTurnBusy as pe,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ye}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ge=3e4,be=5*6e4,U="inbox daemon unreachable",B=16;let v,ve=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function we(){return{tickMs:V(),debounceMs:z()}}c(we,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&ue(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function _e(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}}))}}c(_e,"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-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(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}}}c(b,"deliveryFields");function Ee(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ee,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function Ie(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
|
+
`):""}c(Ie,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function ke(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(ke,"disposalReasonForShutdown");function xe(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}c(xe,"boundedRuntimeReason");class Se{static{c(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=G();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=c((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(a=>a.awaitingDequeue!==void 0))return;const n=C(Ie(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),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=$(i)?ke(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:xe(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=O();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 a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...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 o of a)R(o,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=O().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"),Y()),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(ge,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<be)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,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&&ie(t).then(e=>e.fault?.op===U?N(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&&pe())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 q(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 q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{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"}}),H()?.("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 ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}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(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&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||W()||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)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}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 te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}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(...Q(n));return i}digest(t,e){try{return K(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 a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){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 o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=me();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,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(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.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 f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.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(d,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 J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.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 a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,_e(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.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||W())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.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.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(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}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 D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.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 a of e.handoffs)T(a.operationId,a,"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 ne(t,s),H()?.("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(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ee(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=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.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 Ce(r,t){v?.dispose("reload",!1);const e=new Se(r,t,++ve);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ye]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Ce,"installWatcher");function Fe(r){const t=Ce(r,we());return()=>t.dispose("shutdown",!1)}c(Fe,"registerCanvasInboxWatcher");var je=Fe;export{je as default,Fe as registerCanvasInboxWatcher};
|
package/docs/apps/cli.md
CHANGED
|
@@ -21,7 +21,7 @@ With no dependencies installed, `npx` downloads the newest published release of
|
|
|
21
21
|
| `npx @north-light/sdk register [--name <text>] [--scope <scope>]... [--logo <url>] [--justification <text>] [--redirect-uri <uri>]... [--issuer <url>]` | Run in a project made by `init`, after `login`: registers the app with the public key from `local/app-key.json`, adds each `--scope` beyond `crtr:llm crtr:act`, and writes `CROUTER_CLIENT_ID` and `CROUTER_ISSUER` to `local/app.env`. | No |
|
|
22
22
|
| `npx @north-light/sdk apps <leaf> [--app <client id>] [--issuer <url>] [leaf flags] [--json]` | Call one app-management leaf with the login and print its answer as JSON. Leaves: `mine`, `get`, `update`, `set-logo --file <path>`, `set-brand-color --color <#rrggbb|none>`, `set-redirect-uris`, `asks`, `set-scopes`, `set-requires`, `set-run-notice-url`, `keys list\|add\|retire\|delete\|set-jwks-uri\|remove-jwks-uri`, `testers list\|add\|remove`. `--app` defaults to `CROUTER_CLIENT_ID` in `local/app.env`; `keys add` takes `--key-file <path>` and sends only the public half. Deleting an app, its marketplace listing, monthly spend cap, sharing and provider role are console-only: those leaves exit 1 and name the console page, with no request. | No |
|
|
23
23
|
|
|
24
|
-
`keygen` and `env` are the only commands that can call `crtr`, and only with `--app`. The rest of this site never uses `--app`, so crtr is optional
|
|
24
|
+
`keygen` and `env` are the only commands that can call `crtr`, and only with `--app`. The rest of this site never uses `--app`, so crtr is optional. `login`, `logout`, `whoami`, `register` and `apps` call only the Northlight directory.
|
|
25
25
|
|
|
26
26
|
## Details
|
|
27
27
|
|
|
@@ -5,7 +5,7 @@ description: What npx @north-light/sdk init and skill install for Claude Code, C
|
|
|
5
5
|
|
|
6
6
|
# Use your coding agent
|
|
7
7
|
|
|
8
|
-
The `northlight` skill teaches a coding agent the whole path in the [quick setup](/docs/quickstart): the commands, the code patterns and the rules. With it, your agent signs you up, logs in, registers the app and runs it, and you choose **Allow** twice in your browser: once on the login page, once on the app's consent page. `npx @north-light/sdk init` installs it into your project. The skill needs no account to install, and works
|
|
8
|
+
The `northlight` skill teaches a coding agent the whole path in the [quick setup](/docs/quickstart): the commands, the code patterns and the rules. With it, your agent signs you up, logs in, registers the app and runs it, and you choose **Allow** twice in your browser: once on the login page, once on the app's consent page. `npx @north-light/sdk init` installs it into your project. The skill needs no account to install, and works on any machine.
|
|
9
9
|
|
|
10
10
|
## Install it
|
|
11
11
|
|
package/docs/apps/get-started.md
CHANGED
|
@@ -36,7 +36,7 @@ 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.
|
|
39
|
+
Everything on this site works with the SDK's own commands and the web console. You can also sign your Mac in to your Northlight account with the `crtr` CLI and manage your apps with `crtr cloud apps`. The agents that run commands there run on Northlight; your Mac is a machine they can use.
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
42
|
npm i -g @north-light/cli@latest
|
|
@@ -44,4 +44,4 @@ crtr sys signin
|
|
|
44
44
|
crtr cloud apps mine
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
`crtr sys signin` asks you to approve once in your browser. The
|
|
47
|
+
`crtr sys signin` asks you to approve once in your browser. The CLI is [`@north-light/cli`](https://www.npmjs.com/package/@north-light/cli) on npm.
|
|
@@ -7,7 +7,7 @@ description: Give each person a canvas object per thing in your app, let their a
|
|
|
7
7
|
|
|
8
8
|
`PostgresObjectStore` from `@north-light/sdk/stores/postgres` keeps one canvas object per person for each thing in your app (a problem, a ticket, a workspace), links the person's nodes to it, and delivers events to it from a database outbox. An agent that runs `crtr <your-plugin> thing watch T-12` then receives the events you publish for T-12.
|
|
9
9
|
|
|
10
|
-
Your app declares the object kinds and their events in its plugin with `definePlugin({objectKinds})
|
|
10
|
+
Your app declares the object kinds and their events in its plugin with `definePlugin({objectKinds})`. The store registers objects of those kinds. Install `pg` in your app.
|
|
11
11
|
|
|
12
12
|
## Create the tables
|
|
13
13
|
|
package/docs/apps/how-it-fits.md
CHANGED
|
@@ -41,6 +41,6 @@ The person's AI subscription pays for model calls, and what your app may do on t
|
|
|
41
41
|
|
|
42
42
|
## What you operate
|
|
43
43
|
|
|
44
|
-
You operate your server, its sessions, its database and its `ConnectionStore`. You register the app in the console and keep its key pair. Northlight operates the directory and the runtimes; you do not run either, and there is no local Northlight to start.
|
|
44
|
+
You operate your server, its sessions, its database and its `ConnectionStore`. You register the app in the console and keep its key pair. Northlight operates the directory and the runtimes; you do not run either, and there is no local Northlight to start.
|
|
45
45
|
|
|
46
46
|
The directory's discovery document at `https://account.northlight.ai/.well-known/openid-configuration` lists the endpoints, the `S256` PKCE method and `private_key_jwt` as the only token authentication method.
|
|
@@ -53,11 +53,8 @@ A group's `who` says who may be granted it: `own` (only your own app), `user` (t
|
|
|
53
53
|
|
|
54
54
|
## Guides
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
The plugin kit `@north-light/plugin` adds commands to the Northlight runtime.
|
|
57
57
|
|
|
58
58
|
| Page | What it covers |
|
|
59
59
|
|---|---|
|
|
60
|
-
| [Plugin docs](https://crouter.docs.northlight.ai/docs/plugin) | What `@north-light/plugin` does and how a plugin is installed |
|
|
61
|
-
| [Commands](https://crouter.docs.northlight.ai/docs/plugin/commands) | Branches, leaves, parameters, outputs, groups and `who` |
|
|
62
|
-
| [Deploying](https://crouter.docs.northlight.ai/docs/plugin/deploying) | `auth: {issuer, audience, providerId}`, `ctx.caller`, versions and breaking changes |
|
|
63
60
|
| [Manage your app](/docs/guides/manage-your-app) | The console's **Provider** tab beside the others |
|
package/docs/apps/quickstart.md
CHANGED
|
@@ -9,7 +9,7 @@ description: From no account to a running app that signs a person in with Northl
|
|
|
9
9
|
npx @north-light/sdk@latest init my-app
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
This command creates a small Node server, a signing key and an env file. About ten minutes later you have an app on your laptop that signs you in with Northlight, starts an agent run on your own Northlight runtime, and texts your phone. The app runs on your machine and talks to Northlight's production directory at `https://account.northlight.ai`. There is no local Northlight stack to run.
|
|
12
|
+
This command creates a small Node server, a signing key and an env file. About ten minutes later you have an app on your laptop that signs you in with Northlight, starts an agent run on your own Northlight runtime, and texts your phone. The app runs on your machine and talks to Northlight's production directory at `https://account.northlight.ai`. There is no local Northlight stack to run.
|
|
13
13
|
|
|
14
14
|
You need Node.js 20.6 or later (the start command uses `--env-file`) and a phone that can receive iMessage. The server was run on Node 20.6, 20.20, 22.14, 22.22 and 26.12.
|
|
15
15
|
|
|
@@ -5,7 +5,7 @@ description: When deciding how an application should host or reconnect to an age
|
|
|
5
5
|
|
|
6
6
|
# Why a daemon
|
|
7
7
|
|
|
8
|
-
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd
|
|
8
|
+
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd` (in production the Northlight control plane at `api-fleet.northlight.ai`), owns the durable canvas and starts, stops, and recovers brokers. This separation lets a node continue after the terminal that created or displayed it has gone away.
|
|
9
9
|
|
|
10
10
|
```mermaid
|
|
11
11
|
flowchart LR
|
package/docs/sdk/README.md
CHANGED
|
@@ -25,11 +25,12 @@ const node = await crtr.createNode({ prompt: 'List the top-level directories her
|
|
|
25
25
|
|
|
26
26
|
| Page | Covers |
|
|
27
27
|
|---|---|
|
|
28
|
-
| [Getting started](./getting-started.md) | Install, `new Crouter()` on
|
|
28
|
+
| [Getting started](./getting-started.md) | Install, `new Crouter()` on a signed-in machine's socket, `CRTRD_TOKEN` for a browser or remote app, Chrome's local-network prompt |
|
|
29
29
|
| [Client construction](./client.md) | Every constructor option and its environment-variable fallback; per-request options |
|
|
30
|
+
| [Sourcing reads](./sourcing.md) | `sourcing.read`: Mac first, then hosted search; the route table, the routing rule, `SourcingUnavailableError`, `SOURCING_RUN_RULE` |
|
|
30
31
|
| [Resource map](./resources.md) | Every namespace with its routes, and the `client.request()` escape hatch |
|
|
31
32
|
| [Errors](./errors.md) | The daemon's scoped-token and wire errors, and identifier validation |
|
|
32
|
-
| [Docker environment](./docker.md) |
|
|
33
|
+
| [Docker environment](./docker.md) | Northlight-internal: `@north-light/env-docker`, the CI image helper used by pr-review |
|
|
33
34
|
| [Release notes](https://sdk.docs.northlight.ai/docs/release-notes) | Behavior changes an existing app must act on, newest first |
|
|
34
35
|
|
|
35
36
|
## Where the agents read this
|
package/docs/sdk/client.md
CHANGED
|
@@ -22,14 +22,14 @@ An app that signs people in with Northlight uses `OAuth2Client` and `oauth.clien
|
|
|
22
22
|
| Option | Type | Default | Meaning |
|
|
23
23
|
|---|---|---|---|
|
|
24
24
|
| `baseURL` | `string` | `CRTR_BASE_URL`, else unset | `http(s)://host:port` of a daemon TCP listener. |
|
|
25
|
-
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket. Node only; throws in a browser. |
|
|
25
|
+
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket of a signed-in machine's own daemon. Node only; throws in a browser. |
|
|
26
26
|
| `token` | `string` | `CRTRD_TOKEN` | Sent as `Authorization: Bearer <token>`. The token the daemon was started with (`CRTRD_TOKEN`); a scoped token's ceiling is enforced per request (see [Getting started](./getting-started.md#a-token-that-holds-less-than-the-owner)). Ignored by a unix-socket daemon, which authenticates by filesystem permission. |
|
|
27
27
|
| `timeout` | `number` (ms) | `30_000` | Per-request wall clock. Does not apply to a stream. |
|
|
28
28
|
| `maxRetries` | `number` | `2` | Transient-failure retries. Never applied to `POST` or `PATCH` — see [Errors](./errors.md). |
|
|
29
29
|
| `defaultHeaders` | `Record<string, string>` | `{}` | Merged into every request. |
|
|
30
30
|
| `headers` | `Record<string, string>` | unset | Merged after `defaultHeaders`; a matching name wins unless `token` is set, in which case the generated `Authorization` header wins at construction. |
|
|
31
31
|
| `fetch` | `typeof fetch` | global `fetch`, or the socket implementation when `socketPath` is used | Transport override, for proxies and instrumentation. |
|
|
32
|
-
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` |
|
|
32
|
+
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` | For a signed-in machine's own daemon socket: on a cold socket, run `crtr sys daemon start` and retry once. Node only. |
|
|
33
33
|
|
|
34
34
|
### Environment-variable fallbacks
|
|
35
35
|
|
|
@@ -52,7 +52,7 @@ There is one request path. The client issues every request through the Web `fetc
|
|
|
52
52
|
|
|
53
53
|
## Autostart
|
|
54
54
|
|
|
55
|
-
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
55
|
+
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
56
56
|
|
|
57
57
|
Autostart is Node-only and applies only to the socket transport. A `baseURL` client cannot start a daemon it may not even share a machine with, so `autostart` defaults to `false` there; setting it to `true` on a `baseURL` client throws `CrouterError` (`autostart is only valid for the local socket transport`).
|
|
58
58
|
|
package/docs/sdk/docker.md
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Docker environment
|
|
3
|
-
description:
|
|
3
|
+
description: Northlight-internal helper that runs the crtrd CI image for the pr-review workflow.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Docker environment
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`@north-light/env-docker` runs a crouter daemon in a container and tells you how to reach it. It is a separate package because container lifecycle is real work the SDK does not otherwise do — and it **has no dependencies**, including on the SDK itself.
|
|
8
|
+
`@north-light/env-docker` is Northlight-internal: `Northlight-Systems/shared`'s pr-review workflow uses it to run the `crtrd` CI image (`ghcr.io/northlight-systems/crtrd`) in a container. It is not a way to run or self-host crtr; production is the Northlight control plane at `api-fleet.northlight.ai`. It has no dependencies, including on the SDK itself.
|
|
11
9
|
|
|
12
10
|
```bash
|
|
13
11
|
npm i @north-light/env-docker
|
|
@@ -19,11 +17,9 @@ npm i @north-light/env-docker
|
|
|
19
17
|
import { start } from '@north-light/env-docker';
|
|
20
18
|
import Crouter from '@north-light/sdk';
|
|
21
19
|
|
|
22
|
-
const env = await start({ volume: '
|
|
20
|
+
const env = await start({ volume: 'ci-home' });
|
|
23
21
|
const client = new Crouter(env.connection());
|
|
24
22
|
|
|
25
|
-
await client.runs.start({ prompt: 'Do the thing.' });
|
|
26
|
-
|
|
27
23
|
await env.stop();
|
|
28
24
|
```
|
|
29
25
|
|
|
@@ -63,6 +59,6 @@ const client = new Crouter(env.connection());
|
|
|
63
59
|
|
|
64
60
|
`connection()` is typed structurally — `{ baseURL: string; headers?: Record<string, string> }` — which is how the package stays dependency-free while producing something the SDK accepts directly.
|
|
65
61
|
|
|
66
|
-
## The volume
|
|
62
|
+
## The volume
|
|
67
63
|
|
|
68
|
-
The `volume` you pass is the container's canvas home
|
|
64
|
+
The `volume` you pass is the container's canvas home. Reuse it across `start` calls to keep state; use a fresh one to start from nothing. `start()` mounts an existing named volume unchanged.
|
|
@@ -7,6 +7,28 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.783
|
|
11
|
+
|
|
12
|
+
### Every limit refusal carries `details.payment`
|
|
13
|
+
|
|
14
|
+
A `402 cap_exhausted` now always has `details.payment = { reason, message, pay_url, reset_at }`, whatever limit refused: `app_limit` (link to the app's page on the account site), `card_limit` (billing limit), `card_required`, `operator_stop`, and the new `person_limit` (a limit set with `crtr sys spend`; no link). `message` is the sentence to show the person and is also the error's top-level message. `PAYMENT_REFUSAL_REASONS` gains `operator_stop` and `person_limit`; treat an unknown reason as a sentence with no button. The `nothing_left` link is now `<directory>/account/pay`.
|
|
15
|
+
|
|
16
|
+
## 0.3.781
|
|
17
|
+
|
|
18
|
+
`sourcing.read` and `SOURCING_RUN_RULE`. Additive: no request or response an existing app sends or reads changes.
|
|
19
|
+
|
|
20
|
+
- `sourcing.read(client, request, options?)` reads from the person's Mac (or their GitHub account) first and Northlight's hosted `search` second, and resolves `{served_by, data, cost_usd?, fallback_reason?}`. LinkedIn reads have no hosted path. See [sourcing](/docs/reference/sourcing).
|
|
21
|
+
- `SourcingUnavailableError` (`code: 'sourcing_unavailable'`, status 503, with `attempts`, `retryAt`, `budget`) is raised when no path can serve the read now.
|
|
22
|
+
- `SOURCING_RUN_RULE` is the same rule as text for run prompts that hold `device:browser`.
|
|
23
|
+
|
|
24
|
+
### `payment.reason` can be `account_held`
|
|
25
|
+
|
|
26
|
+
`PaymentRefusalDTO.reason` now lists `account_held`, which the directory already sent while a new account waits for approval. Treat it like any refusal the person cannot fix by paying: show `message`, no link.
|
|
27
|
+
|
|
28
|
+
`GET /v1/human/inbox?include=page`. Additive: without the query the response is unchanged.
|
|
29
|
+
|
|
30
|
+
- With `include=page`, each page ticket carries an optional `page` field holding the same body `GET /v1/human/inbox/:ticket_id` returns, so a client can open every listed page without a read per page. A page that cannot be read is listed without `page`.
|
|
31
|
+
|
|
10
32
|
## 0.3.759
|
|
11
33
|
|
|
12
34
|
### A grant can hold a whole provider as `<provider>:*`
|
|
@@ -331,7 +353,7 @@ Every other `canvas` method and `customObjects.receive`/`ack` remain absent from
|
|
|
331
353
|
- `definePlugin({objectKinds})` declares canvas object kinds by name relative to the plugin (`repo`), each `{ description, events: { <name>: { level: 1-10, supersedes? } }, read?: { command: [...] } }`. The bundle the kit serves carries them in `bundle.json` `object_kinds`, keyed `<providerId>.<name>`: `providerId` is the `auth.providerId` the handler was given, else the plugin name. `definePlugin` throws `PluginDefinitionError` for a relative name that is not lowercase letters, digits and `-`, a blank description, more than 64 events, a level outside 1-10, and a `read.command` that is not a non-streaming leaf of the plugin. Building the bundle throws if the prefixed kind is not one crouter accepts (a provider id with capitals or `_`, or one of crouter's reserved roots such as `repo` or `report`).
|
|
332
354
|
- `ctx.caller.crtr` carries the calling node: `{ node?, machine?, profile?, run? }`, parsed by the exported `parseCrtrCaller(header)` from the request's `Crtr-Caller`. It is absent when the header names no field. The runtime asserts that header and the bearer token does not cover it, so use it to tell which of the verified `sub`'s nodes called, never to authorize; authorize on `sub`.
|
|
333
355
|
|
|
334
|
-
See
|
|
356
|
+
See Local plugins and Object kinds and the calling node.
|
|
335
357
|
|
|
336
358
|
### `nodes.revive` reports `ready` (additive)
|
|
337
359
|
|
|
@@ -375,7 +397,7 @@ Plugins can now declare canvas object kinds and act on the canvas, and an app to
|
|
|
375
397
|
|
|
376
398
|
### Plugin manifests declare `object_kinds` and `scopes` (additive)
|
|
377
399
|
|
|
378
|
-
`plugin.json` and `bundle.json` take two optional top-level blocks. `object_kinds` maps a kind name (`<plugin>.<name>`, so the first segment is the plugin's own name) to `{ description, events, read? }`: `events` holds up to 64 entries `{ level: 1-10, supersedes?: boolean }`, and `read.command` is a leaf path below the plugin's root command. That leaf must answer once: a leaf declared `rest.streaming: true` is refused as a `read.command`. `scopes` lists the canvas scopes the plugin asks for. A provider bundle may not declare `scopes`: a cloud app's scopes come from directory consent. Install, update and enable refuse an invalid block and keep the installed version; a kind another owner already holds is reported as `kind_owned` and the plugin's other kinds still apply. `crtr pkg plugin install|update|enable` print these as `warnings`, plus `appScopes` (the scopes the plugin's token now carries). Plugin authors: see
|
|
400
|
+
`plugin.json` and `bundle.json` take two optional top-level blocks. `object_kinds` maps a kind name (`<plugin>.<name>`, so the first segment is the plugin's own name) to `{ description, events, read? }`: `events` holds up to 64 entries `{ level: 1-10, supersedes?: boolean }`, and `read.command` is a leaf path below the plugin's root command. That leaf must answer once: a leaf declared `rest.streaming: true` is refused as a `read.command`. `scopes` lists the canvas scopes the plugin asks for. A provider bundle may not declare `scopes`: a cloud app's scopes come from directory consent. Install, update and enable refuse an invalid block and keep the installed version; a kind another owner already holds is reported as `kind_owned` and the plugin's other kinds still apply. `crtr pkg plugin install|update|enable` print these as `warnings`, plus `appScopes` (the scopes the plugin's token now carries). Plugin authors: see Local plugins.
|
|
379
401
|
|
|
380
402
|
`ReconcilePackagesDTO` (the answer of `POST /v1/documents/reconcile-packages`) gains two optional fields: `kinds` (`applied` with `outcome` of `inserted`, `updated` or `unchanged`; `refused` with code `kind_owned`; `invalid` plugins with the reason) and `tokens` (`granted` plugins with their scopes, and `revoked` plugin names).
|
|
381
403
|
|
|
@@ -400,7 +422,7 @@ Each enabled local plugin that declares `object_kinds` or `scopes`, or serves ov
|
|
|
400
422
|
|
|
401
423
|
### `Crtr-Caller` and `Crtr-Signature` on local HTTP calls (additive)
|
|
402
424
|
|
|
403
|
-
Every HTTP call to a plugin carries `Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>` (fields in that order, empty ones left out, header omitted when none). Calls to a local plugin's endpoint origin also carry `Crtr-Signature: v1,t=<unix seconds>,h=<signed header names>,sig=<base64url HMAC-SHA256 keyed by the plugin's token>` plus a fresh `Crtr-Request-Id`. A manifest cannot set these three header names. Provider calls carry `Crtr-Caller` too. Plugin authors: the canonical string and a reference verifier are in
|
|
425
|
+
Every HTTP call to a plugin carries `Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>` (fields in that order, empty ones left out, header omitted when none). Calls to a local plugin's endpoint origin also carry `Crtr-Signature: v1,t=<unix seconds>,h=<signed header names>,sig=<base64url HMAC-SHA256 keyed by the plugin's token>` plus a fresh `Crtr-Request-Id`. A manifest cannot set these three header names. Provider calls carry `Crtr-Caller` too. Plugin authors: the canonical string and a reference verifier are in Local plugins.
|
|
404
426
|
|
|
405
427
|
crtrd signs the call; the CLI never holds the token. `POST /v1/plugins/:name/call-headers` (new operation `plugins.call-headers`, person and broker callers) takes only digests, `{ method, url, body_sha256, header_names, headers_sha256 }`, and answers `{ headers }` (`Crtr-Caller`, and `Crtr-Signature` when the URL is on the installed endpoint's origin and that endpoint is loopback). Any other URL gets `Crtr-Caller` only. An unknown or disabled plugin and a provider plugin answer `404 not_found`; malformed digests answer `400 invalid_request`. SDK: `CrtrClient.plugins.callHeaders(name, request)`, `PluginCallHeadersRequestDTO`, `PluginCallHeadersDTO`, `routes.pluginCallHeaders(name)`.
|
|
406
428
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Sourcing reads
|
|
3
|
+
description: Read a person, company or page from the person's own Mac first, then from Northlight's hosted search, with one result shape and one "not now" error.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Sourcing reads
|
|
7
|
+
|
|
8
|
+
`sourcing.read(client, request, options?)` reads one thing about a person, company or page. It tries the person's own Mac (or their linked GitHub account) first. When that path cannot be used now, it tries Northlight's hosted `search` provider, which Northlight pays for up to the app's caps. It never writes, never sleeps and never retries.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { sourcing, SourcingUnavailableError } from '@north-light/sdk';
|
|
12
|
+
|
|
13
|
+
try {
|
|
14
|
+
const r = await sourcing.read(runtime, { read: 'github.user', login: 'octocat' }, { scopes: grantedScopes });
|
|
15
|
+
// r.served_by: 'device' | 'integrations' | 'hosted'
|
|
16
|
+
// r.data, r.cost_usd? (hosted only), r.fallback_reason? (hosted only: why path 1 did not serve it)
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error instanceof SourcingUnavailableError) {
|
|
19
|
+
// error.attempts, error.retryAt (ISO or null), error.budget, error.retryable
|
|
20
|
+
} else throw error;
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`client` is anything with `providers.call`: a `Crouter` or the client from `oauth.appClient(userId)`. The app's grant needs `device:browser` for Mac reads, `integrations:github_read` for GitHub, and the `search` scopes for hosted reads (`search:search`, `search:contents`, `search:answer`, `search:people`).
|
|
25
|
+
|
|
26
|
+
## Route table
|
|
27
|
+
|
|
28
|
+
| `read` | Path 1 | Path 2 (hosted `search`) |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `linkedin.profile`, `linkedin.search`, `linkedin.company` | Mac, `@northlight/linkedin` `getProfile`, `searchPeople`, `getCompany` | **none** |
|
|
31
|
+
| `x.profile` | Mac, `@northlight/x` `getProfile` | `people x-profile` |
|
|
32
|
+
| `x.search` | Mac, `@northlight/x` `searchUsers` | none |
|
|
33
|
+
| `x.posts` | Mac, `@northlight/x` `searchPosts` | `search` with `include-domains x.com` |
|
|
34
|
+
| `github.user` | `integrations` `github read` (the person's own GitHub account) | `people github-user` |
|
|
35
|
+
| `github.repos` | `integrations` `github read` | none (a profile is not a repo list) |
|
|
36
|
+
| `web.search`, `web.contents`, `web.answer` | none | `search`, `contents`, `answer` |
|
|
37
|
+
| `email.work` | none | `people work-email` |
|
|
38
|
+
|
|
39
|
+
There is no hosted LinkedIn path. A LinkedIn read the Mac cannot serve ends in `sourcing_unavailable`; retry at `retryAt` once the Mac is back or the limit window passes.
|
|
40
|
+
|
|
41
|
+
## The rule
|
|
42
|
+
|
|
43
|
+
Path 1 is skipped, with no call, when `options.scopes` is given and lacks the scope for that path, or when `options.browser === false` (the app's last device probe found no Chrome). The attempt is recorded as `skipped:no_scope` or `skipped:no_browser`.
|
|
44
|
+
|
|
45
|
+
| Path 1 returns | Result |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `device_offline`, `device_timeout`, `provider_not_connected`, `machine_required`, `helper_not_installed`, `browser_profile_not_open` | Fall through (the Mac cannot be used now) |
|
|
48
|
+
| `site_signed_out`, `wrong_site` | Fall through (not signed in to the site) |
|
|
49
|
+
| `rate_limited` | Fall through; `retry_after_s` is carried to `retryAt` |
|
|
50
|
+
| `lib_broken` | Fall through |
|
|
51
|
+
| `account_not_linked`, `account_reconnect_required` (GitHub) | Fall through |
|
|
52
|
+
| `js_exception`, `outcome_unknown` | Fall through. Reads never return `outcome_unknown`; it is treated as `js_exception`. A `js_exception` whose message names the site function's `NotFound`, `Validation` or `PermissionDenied` is the answer instead |
|
|
53
|
+
| `not_found`, `invalid_argument`, `permission_error`, `scope_missing`, and any code not listed | **Thrown as is.** The person does not exist, the input is bad, or the grant is wrong |
|
|
54
|
+
|
|
55
|
+
| Hosted returns | Result |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `limit_reached`, `payment_required`, `cap_exhausted` (HTTP 402) | Stop: `SourcingUnavailableError` with `budget: true`; `retryAt` is the refusal's `reset_at` |
|
|
58
|
+
| `provider_rate_limited`, `provider_capacity`, `vendor_unavailable` | `SourcingUnavailableError`, retryable, `retryAt` from `retry_after_s` |
|
|
59
|
+
| `price_over_maximum` | Stop: thrown as is |
|
|
60
|
+
| anything else | Thrown as is |
|
|
61
|
+
|
|
62
|
+
## `SourcingUnavailableError`
|
|
63
|
+
|
|
64
|
+
`code: 'sourcing_unavailable'`, `status: 503`. Retryable when any attempt was transient.
|
|
65
|
+
|
|
66
|
+
| Field | Meaning |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `attempts` | One entry per path tried or skipped: `{path, code, retry_after_s?, reset_at?}` |
|
|
69
|
+
| `retryAt` | ISO time of the earliest `retry_after_s` or `reset_at` across the attempts, or `null` |
|
|
70
|
+
| `budget` | `true` when the hosted refusal was a 402 |
|
|
71
|
+
|
|
72
|
+
The app decides what to do: leave the work queued, show "Mac offline and hosted budget used up", and try again after `retryAt`.
|
|
73
|
+
|
|
74
|
+
## Options
|
|
75
|
+
|
|
76
|
+
| Option | Use |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `scopes` | The scopes the grant holds, so a path without its scope is skipped without a call |
|
|
79
|
+
| `browser` | `false` skips the Mac path (the app's last probe found no Chrome) |
|
|
80
|
+
| `machine` | Which Mac takes the device calls, when the person has more than one |
|
|
81
|
+
| `githubAccount` | The linked GitHub account label, when the person has several |
|
|
82
|
+
| `execTimeoutMs` | The Mac script budget (default 30000) |
|
|
83
|
+
| `signal` | Aborts the read |
|
|
84
|
+
|
|
85
|
+
## Cost and logging
|
|
86
|
+
|
|
87
|
+
Device and integrations reads cost Northlight nothing and are not metered. `served_by` says which path answered; for `hosted`, `cost_usd` is the top-level `cost_usd` of the hosted answer (dollars), when the leaf returns one. Add it to your own per-pass cost.
|
|
88
|
+
|
|
89
|
+
## Rule text for agent runs
|
|
90
|
+
|
|
91
|
+
`SOURCING_RUN_RULE` is the same rule written for an agent. Append it to the prompt of any run that holds `device:browser`, so a run that reads LinkedIn with `crtr device browser` follows the same fall-through, no-hosted-LinkedIn and stop rules.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.783",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.783",
|
|
161
|
+
"@north-light/plugin": "0.3.783",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -819,8 +819,8 @@ export class CrtrClient {
|
|
|
819
819
|
// ---- Humanloop inbox (Northlight crouter-inbox v1, inbox-contract.md §A) --
|
|
820
820
|
/** Pending page/review tickets across every available crouter-owned
|
|
821
821
|
* humanloop root. */
|
|
822
|
-
listHumanInbox() {
|
|
823
|
-
return this.request('GET', routes.humanInbox());
|
|
822
|
+
listHumanInbox(opts = {}) {
|
|
823
|
+
return this.request('GET', opts.includePages === true ? withQuery(routes.humanInbox(), { include: 'page' }) : routes.humanInbox());
|
|
824
824
|
}
|
|
825
825
|
/** Read one page ticket by its opaque ticket id (pending, resolved, or canceled). */
|
|
826
826
|
getHumanInboxPage(ticketId) {
|
|
@@ -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.86';
|
|
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`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// The money ledger's read and limit surfaces: `charges.list`, `spend_limits.list`, `spend_limits.set`, `spend_limits.remove`.
|
|
2
2
|
// (`limits.*` and `/v1/limits` are the per-app memory and disk caps; these are dollar limits.)
|
|
3
3
|
/** Why a call was refused for payment. `reason` is what an app branches on; never the message text. */
|
|
4
|
-
export const PAYMENT_REFUSAL_REASONS = ['trial_ended', 'card_required', 'card_limit', 'nothing_left', 'app_limit', 'team_limit', 'app_unpaid'];
|
|
4
|
+
export const PAYMENT_REFUSAL_REASONS = ['trial_ended', 'card_required', 'card_limit', 'nothing_left', 'app_limit', 'team_limit', 'app_unpaid', 'account_held', 'operator_stop', 'person_limit'];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/daemon/machine-link/config.ts — what a Mac knows about its own machine environment after import (design-import I13):
|
|
2
2
|
// `runtime/machine.json` ({apiUrl, environmentId, runId, directoryUrl, account}, written by the exporter's finish step) and the machine credential at
|
|
3
|
-
// `runtime/secrets/machine-credential` (mode 0600). A
|
|
3
|
+
// `runtime/secrets/machine-credential` (mode 0600). A computer with no `machine.json` is not signed in to Northlight and has no machine environment.
|
|
4
4
|
// Also the move record `runtime/import/move.json` (0600): where a move to Northlight that `crtr sys signin` started stands, from before the drain until the
|
|
5
5
|
// computer has switched over (design-crtr-northlight-signin component 4).
|
|
6
6
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
@@ -48,7 +48,5 @@ export function readOrCreateInstallId() {
|
|
|
48
48
|
writeFileSync(path, `${id}\n`);
|
|
49
49
|
return id;
|
|
50
50
|
}
|
|
51
|
-
/**
|
|
52
|
-
export const
|
|
53
|
-
/** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
|
|
54
|
-
export const computerIsUnset = () => readMachineConfig() === undefined && !hasLocalCanvas() && joinedIssuer() === null;
|
|
51
|
+
/** A computer with no `machine.json` and no join registration is not signed in to Northlight: it has no control plane to reach until `crtr sys signin`. */
|
|
52
|
+
export const computerIsNotSignedIn = () => readMachineConfig() === undefined && joinedIssuer() === null;
|
|
@@ -16,7 +16,7 @@ import { hostExecPath } from '../core/runtime/branded-host.js';
|
|
|
16
16
|
// reaches openDb) so the CLI daemon front door stays canvas.db-free (plan B-0).
|
|
17
17
|
import { isDaemonRunning, readPidfile, isPidAlive } from './pidfile.js';
|
|
18
18
|
import { DAEMON_STARTUP_WINDOW_MS } from './startup-policy.js';
|
|
19
|
-
import {
|
|
19
|
+
import { computerIsNotSignedIn, readMachineConfig } from './machine-link/config.js';
|
|
20
20
|
import { exclusiveLockOwnerPid } from '../core/exclusive-lock.js';
|
|
21
21
|
import { onDiskMigrationLockPath } from '../core/canvas/paths.js';
|
|
22
22
|
import { envNoDaemonAutostart } from '../shared/env.js';
|
|
@@ -690,8 +690,8 @@ export function ensureDaemon(deps = {}) {
|
|
|
690
690
|
const now = deps.now ?? Date.now;
|
|
691
691
|
if (autostartDisabled())
|
|
692
692
|
return;
|
|
693
|
-
// A computer
|
|
694
|
-
if (!deps.spawnDaemon &&
|
|
693
|
+
// A computer that is not signed in to Northlight has no control plane to start a daemon for (`crtr sys signin` comes first).
|
|
694
|
+
if (!deps.spawnDaemon && computerIsNotSignedIn())
|
|
695
695
|
return;
|
|
696
696
|
if (autostartInFlight)
|
|
697
697
|
return;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.783",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|