@north-light/cli 0.3.693 → 0.3.695
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 +4 -7
- package/dist/api/command-manifest/result.d.ts +5 -5
- package/dist/api/command-manifest/result.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/run-events.d.ts +1 -0
- package/dist/api/dto/run-events.js +1 -0
- package/dist/api/dto/worktree.d.ts +0 -4
- package/dist/api/errors.js +1 -1
- package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
- package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
- package/dist/builtin-memory/crouter-sdk/README.md +14 -42
- package/dist/builtin-memory/crouter-sdk/client.md +5 -7
- package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
- package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
- package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
- package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
- package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
- package/dist/cli.js +6 -6
- package/dist/clients/attach/session/connection.d.ts +11 -2
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/pane-tag.d.ts +3 -3
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/viewer.js +538 -537
- package/dist/commands/node/inspect.js +9 -9
- package/dist/commands/node-worktree.js +1 -1
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/surface/node/placement.d.ts +2 -2
- package/dist/commands/surface/node/placement.js +1 -1
- package/dist/commands/surface.js +1 -1
- package/dist/commands/sys/update.js +1 -1
- package/dist/core/broker-client/client.d.ts +6 -9
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +7 -7
- package/dist/core/canvas/types.d.ts +0 -2
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/row-store.js +10 -10
- package/dist/core/graph/exposures.js +1 -1
- package/dist/core/graph/names.js +9 -9
- package/dist/core/graph/watches.js +1 -1
- package/dist/core/installed-plugins.js +1 -1
- package/dist/core/keybindings/attach-control.d.ts +3 -0
- package/dist/core/keybindings/attach-control.js +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/ledger/chunks.d.ts +3 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/index.d.ts +1 -1
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/read.d.ts +4 -0
- package/dist/core/ledger/read.js +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/logged-step-timings.d.ts +7 -0
- package/dist/core/logged-step-timings.js +1 -0
- package/dist/core/permissions/evaluator.d.ts +2 -1
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runs/operations.js +8 -8
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/nodes.d.ts +1 -1
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/runtime/tmux-driver.d.ts +0 -10
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
- package/dist/core/scoped-state/imported-mac-installs.js +2 -0
- package/dist/core/spaces/stop.js +1 -1
- package/dist/core/step-timings.d.ts +7 -1
- package/dist/core/step-timings.js +1 -1
- package/dist/core/worktree-close.js +4 -6
- package/dist/core/worktree-landing.d.ts +0 -38
- package/dist/core/worktree-landing.js +2 -3
- package/dist/core/worktree-sweep.d.ts +0 -1
- package/dist/core/worktree-sweep.js +4 -6
- package/dist/core/worktree.d.ts +0 -4
- package/dist/core/worktree.js +13 -15
- package/dist/daemon/api/app-listener.d.ts +1 -0
- package/dist/daemon/api/app-listener.js +10 -10
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/daemon/api/server.d.ts +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/crtrd.js +20 -18
- package/dist/daemon/machine-link/client.d.ts +5 -1
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +3 -3
- package/dist/daemon/pidfile.js +2 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/daemon/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.js +3 -3
- package/dist/shared/env.d.ts +8 -3
- package/dist/shared/env.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/docs/apps/guides/stream-a-run.md +6 -7
- package/docs/concepts/lifecycle-and-wakes.md +1 -1
- package/docs/concepts/nodes-and-the-canvas.md +2 -2
- package/docs/concepts/profiles-kinds-and-modes.md +1 -1
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +13 -41
- package/docs/sdk/client.md +5 -7
- package/docs/sdk/docker.md +1 -1
- package/docs/sdk/errors.md +3 -43
- package/docs/sdk/getting-started.md +11 -83
- package/docs/sdk/release-notes.md +10 -0
- package/docs/sdk/resources.md +11 -44
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
- package/packages/crouter-api/dist/api/errors.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
- package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
- package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
- package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
- package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
- package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
- package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
- package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
- package/packages/crouter-api/dist/commands/surface.js +2 -3
- package/packages/crouter-api/dist/commands/sys/update.js +5 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
- package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
- package/packages/crouter-api/dist/core/config.js +10 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
- package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -20
- package/packages/crouter-api/dist/core/graph/watches.js +1 -1
- package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
- package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
- package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
- package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
- package/packages/crouter-api/dist/core/ledger/index.js +1 -1
- package/packages/crouter-api/dist/core/ledger/read.js +18 -1
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
- package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
- package/packages/crouter-api/dist/core/runs/operations.js +5 -4
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
- package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
- package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
- package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
- package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
- package/packages/crouter-api/dist/core/step-timings.js +7 -2
- package/packages/crouter-api/dist/core/worktree-close.js +5 -51
- package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
- package/packages/crouter-api/dist/core/worktree.js +9 -74
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
- package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
- package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
- package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
- package/packages/crouter-api/dist/shared/env.js +15 -4
- package/packages/crouter-api/dist/types.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
- package/dist/builtin-memory/crouter-sdk/files.md +0 -50
- package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
- package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
- package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
- package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
- package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
- package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
- package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
- package/dist/commands/surface-reload.d.ts +0 -7
- package/dist/commands/surface-reload.js +0 -1
- package/docs/sdk/bash.md +0 -39
- package/docs/sdk/files.md +0 -49
- package/docs/sdk/guides/README.md +0 -17
- package/docs/sdk/guides/event-driven-assistant.md +0 -24
- package/docs/sdk/guides/fan-out-pipeline.md +0 -24
- package/docs/sdk/guides/human-approval.md +0 -24
- package/docs/sdk/guides/typed-extraction.md +0 -24
- package/docs/sdk/nodes.md +0 -194
- package/docs/sdk/streaming.md +0 -149
- package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var o=(e,t)=>E(e,"name",{value:t,configurable:!0});import{getNode as
|
|
1
|
+
var E=Object.defineProperty;var o=(e,t)=>E(e,"name",{value:t,configurable:!0});import{getNode as m,getRow as _}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as k}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as h}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as y,recordedPidLiveness as S}from"../../core/canvas/pid.js";import{emitEvent as c}from"../../core/events/emit.js";import{operationIdContext as f}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as v}from"../../core/worktree-sweep.js";import{runThrottledLane as R}from"./throttled-lane.js";const T=60*1e3,W=300*1e3,I=3,L=["done","dead","canceled"];function w(e){return L.includes(e.status)}o(w,"isTerminal");function g(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(g,"hasSweepDisposition");async function M(e,t,n){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!w(e)||!g(e,(await m(e.node_id))?.managed_worktree)?!1:S(e.pi_pid,e.pi_pid_identity,n)==="dead"}o(M,"engineIsGone");function N(e,t){const n=e.node_id,s=e.pi_pid,r=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(n))return!1;const i=await _(n);return i===null||!w(i)||i.frozen_at!==null||!g(i,(await m(n))?.managed_worktree)?!1:i.pi_pid===s&&i.pi_pid_identity===r},"stillEligible")}}o(N,"eligibilityGuard");class z{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return;const s=R("managed-worktree-sweep","",t,T,W,r=>this.sweep(t,n.fleet,r)).then(()=>{}).catch(r=>{f.fresh(()=>c({level:"error",event:"worktree.sweep.failed",error:r}))});n.lifecycle.registerDetached(s)}async candidates(t){try{return await k(t)}catch(n){return f.fresh(()=>{c({level:"error",event:"worktree.sweep.scan_failed",error:n})}),null}}async sweep(t,n,s){const r=await this.candidates(t);if(r===null||r.length===0)return;let i=Number(s.state??0);(!Number.isInteger(i)||i>=r.length)&&(i=0);const d=Math.min(I,r.length),a=[];for(let l=0;l<d;l+=1)a.push(r[(i+l)%r.length]);if(!await s.save(String((i+d)%r.length)))return;const p=await y();if(p!==null)for(const l of a){const u=await _(l);if(!(u===null||!await M(u,n,p))){if(!await s.holds())return;await this.reconcileOne(u,t,n)}}}async reconcileOne(t,n,s){const r=t.node_id,i=h(r)?{node_id:r}:{},d=h(r)?{}:{affected_node_id:r};try{const a=await v(r,N(t,s),n);f.fresh(()=>{if(a.status==="complete"){c({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...i,fields:d});return}a.status!=="skipped"&&(a.status==="refused"&&a.unchanged===!0||c({level:a.status==="failed"?"error":"warn",event:a.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:a.status==="failed"?"failed":"skipped",...i,fields:{...d,reason:a.reason,...a.detail===void 0?{}:{detail:a.detail}}}))})}catch(a){f.fresh(()=>{c({level:"error",event:"worktree.sweep.failed",...i,error:a,fields:d})})}}}export{z as ManagedWorktreeSweepReconciler,I as WORKTREE_SWEEP_BUDGET,T as WORKTREE_SWEEP_INTERVAL_MS};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as
|
|
1
|
+
var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as m,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as z}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as T}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as L}from"../../../core/canvas/deliveries.js";import{publishNotice as C}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as w}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as b}from"./node-person.js";import{MachineOfflineError as f}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as h}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as M}from"../../../core/canvas/recovery.js";import{mapAsync as O}from"../../../core/async-array.js";const E=6,P=10*6e4,U=2e4;async function x(i){const e=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(e?.idle_release_attempts??0),acknowledgedCount:Number(e?.idle_release_acked_count??0),lastAttempt:e?.idle_release_last_attempt_at==null?void 0:Date.parse(e.idle_release_last_attempt_at)}}s(x,"readEpisode");async function H(i,e,a,t,r){const n=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),t,i,e);return Number(n.changes)===1}s(H,"claimAttempt");async function F(i,e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(e.attempts,e.lastAttempt===void 0?null:new Date(e.lastAttempt).toISOString(),e.acknowledgedCount,i)}s(F,"writeEpisode");function W(i,e){if(e)return 2;const a=i.launched_at;if(a==null)return 1;const t=i.last_settled_at;return t==null?2:Date.parse(t)>Date.parse(a)?1:2}s(W,"thawTier");function $(i,e){const a=i.row.frozen_at,t=e.row.frozen_at;return a==null?t==null?0:1:t==null?-1:Date.parse(a)-Date.parse(t)}s($,"compareThaw");class de{static{s(this,"FreezeLaneReconciler")}async endEpisode(e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(e)}async run(e,a){const t=await O(a.candidates,async n=>({...n,tier:W(n.row,await k(n.row.node_id))}));t.sort($);const r={stalled:0,waitingOnMail:0};for(const n of t)await T.fresh(()=>b(n.row,()=>this.enact(e,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1);return r}async enact(e,a,t){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(e,a.row):(await t.applyDeadRowPolicy(r),await t.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(n){return u({level:"error",event:"node.lifecycle.enact_failed",...d(r)?{node_id:r}:{},error:n,fields:{...d(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(e){await I(e.node_id);try{return(await h(e.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(w(a)||a instanceof A||a instanceof f)return await this.settleRefusedStart(e.node_id,a,"reopen");throw a}}async settleRefusedStart(e,a,t){return a instanceof f&&a.sent||await p(e,"release"),await m(e),u({level:"warn",event:"node.start.refused",node_id:e,error:a,fields:{enact:t}}),"skipped"}async enactThaw(e){const a=(await M(e.node_id))?.interrupted===!0;if(!a&&e.lifecycle==="resident"&&(await y(e.node_id))?.pi_session_id!=null&&!await k(e.node_id))return await p(e.node_id,"release"),await m(e.node_id),"skipped";try{return(await h(e.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(t){if(w(t)||t instanceof A||t instanceof f)return await this.settleRefusedStart(e.node_id,t,"thaw");const r=await y(e.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(e.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:t instanceof Error?t.message:String(t)}}}),await m(e.node_id)),t}}async enactIdleRelease(e,a){const t=a.node_id,r=await L(t),n=await x(t),l=n.attempts===0||n.acknowledgedCount!==r,o=l?0:n.attempts;if(o>=E)return await this.endEpisode(t),u({level:"warn",event:"broker.idle_release.exhausted",...d(t)?{node_id:t}:{},fields:{...d(t)?{}:{affected_node_id:t},attempts:o,max_attempts:E}}),await p(t,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),await C(t,"notice.crash",`Child crashed \u2014 ${z(a)} (${t}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${t}\`.`,{reason:"child-crashed",child:t}),"skipped";const v=l?void 0:n.lastAttempt,S=Math.min(U*2**o,P);if(v!==void 0&&e-v<S||!await H(t,n.attempts,o+1,r,e))return"skipped";const R=s(()=>F(t,{attempts:l?0:o,lastAttempt:l?void 0:n.lastAttempt,acknowledgedCount:r}),"giveBack");let g;try{g=await h(t,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof f||w(c)))throw c;return await R(),await this.settleRefusedStart(t,c,"idle-release")}return g.outcome==="frozen"?(await R(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...d(t)?{node_id:t}:{},attempt:o+1,fields:{...d(t)?{}:{affected_node_id:t},attempts:o+1,max_attempts:E}}),"launched")}}export{de as FreezeLaneReconciler,$ as compareThaw,W as thawTier};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}
|
|
1
|
+
var R=Object.defineProperty;var c=(t,e)=>R(t,"name",{value:e,configurable:!0});import{appendRunEvent as p}from"../../core/runs/events.js";import{openQuestionIds as T}from"../../core/runs/questions.js";import{getNode as x}from"../../core/canvas/canvas.js";import{payerOfGrant as h}from"../../core/grants/mirror.js";import{runSchemaRepromptPending as N}from"../../core/runtime/stop-guard.js";const D="crtr-turn-input",S="crtr-system-prompt",f="crtr-turn-end";function v(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e?.text=="string").map(e=>e.text).join(`
|
|
2
|
+
`):""}c(v,"text");function A(t){if(t==null)return;const{code:e,message:n,retry_at:_}=t;if(e!=="content_refused"&&e!=="model_error"&&e!=="rate_limited"||typeof n!="string")throw new Error("invalid crtr-turn-end error");if(e==="rate_limited"){if(typeof _!="string")throw new Error("invalid crtr-turn-end error");return{code:e,message:n,retry_at:_}}return{code:e,message:n}}c(A,"turnEndError");function O(t){return{input_tokens:t.input??0,output_tokens:t.output??0,cache_read_tokens:t.cacheRead??0,cache_write_tokens:t.cacheWrite??0,cost_usd:t.cost?.total??0}}c(O,"usageParts");async function k(t,e,n){if(e!==t||!n.some(l=>l.type==="custom"&&l.customType===f))return!1;const _=await x(t);return _!==null&&await N(_)}c(k,"rootRepromptPending");async function H(t,e,n,_,l,y){let d=l;for(const o of _){if(o.type==="custom"&&o.customType===D){const r=o.data?.message_ids;if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw new Error("invalid crtr-turn-input message_ids");d=[...new Set([...d,...r])]}if(o.type==="custom"&&o.customType===S){const r=o.data?.text;if(typeof r!="string")throw new Error("invalid crtr-system-prompt text");await p(t,e,n,"node.system_prompt.set",{entry_id:o.id,text:r})}if(o.type==="custom"&&o.customType===f){const r=o.data,s=r?.stop_reason;if(typeof s!="string")throw new Error("invalid crtr-turn-end stop_reason");const a=A(r?.error),i=await t.prepare("SELECT body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'node.turn.started' ORDER BY sequence_number DESC LIMIT 1").get(e,n);if(!i)throw new Error("crtr-turn-end without node.turn.started");const{input:u}=JSON.parse(i.body_json),E=await t.prepare("SELECT status, pi_pid FROM node_rows WHERE run_id = ? AND node_id != ?").all(e,n),w=y??await k(e,n,[o]),g=E.some(m=>m.pi_pid!==null&&m.status==="active")||w?"running":(await T(e,t)).length?"waiting_on_user":"idle";await p(t,e,n,"node.turn.completed",{entry_id:o.id,message_ids:u.message_ids,run_status:g,stop_reason:s,...a?{error:a}:{}}),n===e&&await t.prepare("UPDATE nodes SET last_turn_error_json = ? WHERE node_id = ?").run(a?JSON.stringify(a):null,e)}if(o.type==="message"){const r=o.message;if(r.role==="user"){const s=await t.prepare("SELECT type, body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1").get(e,n),a=s?.type==="node.turn.started"?JSON.parse(s.body_json).input.message_ids:[];await p(t,e,n,"node.turn.started",{entry_id:o.id,input:{text:v(r.content),message_ids:[...new Set([...a,...d])]}}),d=[]}if(r.role==="assistant"){let s=!1;const a=c(async()=>{if(s)return;s=!0;const i=r.content.filter(u=>u.type==="text").map(u=>u.text).join("");await p(t,e,n,"node.output_text.done",{entry_id:o.id,text:i,stop_reason:r.stopReason})},"doneText");for(const i of r.content)i.type==="thinking"&&await p(t,e,n,"node.thinking.done",{entry_id:o.id,text:i.thinking}),i.type==="text"&&await a(),i.type==="toolCall"&&(await a(),await p(t,e,n,"node.tool_call.started",{entry_id:o.id,tool_call_id:i.id,name:i.name,arguments:i.arguments}));if(await a(),r.usage){const i=O(r.usage),u=await t.prepare("SELECT grant_id FROM nodes WHERE node_id = ?").get(e);await p(t,e,n,"usage",{entry_id:o.id,served_model:r.model,payer:await h(u.grant_id),...i,usage:await(await import("../../core/ledger/read.js")).runUsage(e)})}await t.prepare("DELETE FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.thinking.delta', 'node.output_text.delta')").run(e,n)}r.role==="toolResult"&&await p(t,e,n,"node.tool_call.completed",{entry_id:o.id,tool_call_id:r.toolCallId,name:r.toolName,result:r.content,status:r.isError?"error":"ok"})}}return d}c(H,"appendConversationEvents");export{S as SYSTEM_PROMPT_TYPE,f as TURN_END_TYPE,D as TURN_INPUT_TYPE,H as appendConversationEvents,k as rootRepromptPending};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as
|
|
2
|
-
WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,
|
|
1
|
+
var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as R,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as D}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as N}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as g,emitRunSettlement as T,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",E=1e4,Y=250;async function w(t,e,i){return await C(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,t,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await i()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,i,n,s,r){this.nodeId=e,this.runId=i,this.owner=n,this.status=s,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,i,n){const s=await d(),r=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===i?"node.settled":"child.settled"),a=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),o=new v(e,i,n,a?JSON.parse(a.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await o.writeStream(null,null),await o.poll(),o}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<E/3?!0:await x(c,this.nodeId,this.owner,E)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,i,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
|
|
2
|
+
WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await D(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const i=e.pi_pid===null?"dormant":e.status;if(this.status!==i){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,i,e.intent??null))).held){this.close();return}this.status=i}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const a=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const o of a)await L(o.node_id,this.runId),await p.get(o.node_id)?.poll()}this.outcomeRevision=n.revision;const s=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?T(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...s===void 0?{}:{result:s}}):T(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const a=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(a,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(o=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:o}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await N(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await $(this.nodeId),i=await this.viewAdmitted();if(this.client||this.closed||!i){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:y(),attends:!1}));const s=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const a=r.message.content;if(!Array.isArray(a))return;const o=a.at(-1);if(o&&typeof o=="object"&&"type"in o&&(o.type==="toolCall"?this.block={kind:"tool_call",name:"name"in o&&typeof o.name=="string"?o.name:""}:(o.type==="text"||o.type==="thinking")&&(this.block={kind:o.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const f=a.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),m=a.filter(u=>u?.type==="text").map(u=>u.text).join(""),k=f.startsWith(this.thinking)?f.slice(this.thinking.length):f,b=m.startsWith(this.output)?m.slice(this.output.length):m;this.thinking=f,this.output=m,this.pendingThinking+=k,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>s(r)).catch(a=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:a})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,i=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!i)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await g(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),i&&await g(this.runId,this.nodeId,"node.output_text.delta",{delta:i})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await R(c,this.nodeId,this.owner)}).then(()=>{}).catch(i=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:i})});const e=this.client;this.client=void 0,e?.close()}}async function $(t){const e=await N(t);if(e===null)return new O(t,{recordsViewerFaults:!1});const i=await W(e.runner).viewerAddress(e);return i.kind==="machine"?new A(t,()=>U(i.environmentId,t)):i.kind==="unix"?new O(t,{recordsViewerFaults:!1}):new A(t,()=>q(i.url,i.headers))}l($,"viewTransport");async function pe(t){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function fe(t){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(fe,"openAssistantBlock");async function me(){const t=[...p.values()];for(const e of t)e.close();await Promise.all(t.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(me,"closeRunObserversForTests");async function I(t){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(t,t)!==void 0}l(I,"runRootExists");const _=new Map;async function L(t,e){const i=_.get(t);if(i)return i;if(p.has(t))return;const n=Q(t,e).finally(()=>_.delete(t));return _.set(t,n),n}l(L,"ensureRunObserver");async function Q(t,e){if(!await I(e))return;const i=y();if(await F(c,t,i,E)!==void 0)try{if(t!==e){const n=await D(t);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,t)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(t,i,()=>g(e,t,"child.started",{child_node_id:t,kind:n.kind}))).held)return}await v.start(t,e,i)}catch(n){throw await R(c,t,i).catch(()=>{}),n}}l(Q,"startRunObserver");async function we(){const t=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id, n.pi_pid, COALESCE(n.outcome_revision, 1) AS revision, e.body_json
|
|
3
3
|
FROM node_rows n
|
|
4
4
|
LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
|
|
5
5
|
AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
|
|
6
|
-
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await
|
|
6
|
+
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers};
|
package/dist/shared/env.d.ts
CHANGED
|
@@ -16,10 +16,15 @@ export declare function isSandboxedNode(): boolean;
|
|
|
16
16
|
* descriptions (`GET /v1/providers/tools` through that relay); the relay's node token stays the authority. It is not `isSandboxedNode()`,
|
|
17
17
|
* which gates owner-only commands and launch-snapshot reads on a Linux launcher mount. */
|
|
18
18
|
export declare function providerProjectionOverBrokerRelay(): boolean;
|
|
19
|
-
/** True when this CLI's plugin and marketplace installs are its app's install block on the control plane (`app-plugins.replace` over `/v1`)
|
|
20
|
-
*
|
|
21
|
-
* (`providerProjectionOverBrokerRelay()`, which has no launcher mount). The `pkg plugin` and `pkg market` leaves choose their path with it.
|
|
19
|
+
/** True when this CLI's plugin and marketplace installs are its app's install block on the control plane (`app-plugins.replace` over `/v1`) and
|
|
20
|
+
* no code on disk: a Linux launcher sandbox (`isSandboxedNode()`) or a fleet node reaching `/v1` through its broker relay
|
|
21
|
+
* (`providerProjectionOverBrokerRelay()`, which has no launcher mount). The `pkg plugin` and `pkg market` leaves choose their path with it.
|
|
22
|
+
* A Mac imported into Northlight (`runtime/machine.json`) also reaches the control plane through that relay, but runs plugin code from its own
|
|
23
|
+
* directories: it takes the local path, whose user-scope install list is the terminal app's block (`core/scoped-state/imported-mac-installs.ts`). */
|
|
22
24
|
export declare function installsLiveInAppBlock(): boolean;
|
|
25
|
+
/** True on a Mac whose records moved into Northlight: `runtime/machine.json` exists (the path `machineConfigPath()` names, resolved here
|
|
26
|
+
* without the layout module so this leaf stays import-free). A malformed file still counts: the Mac is imported and its reader throws. */
|
|
27
|
+
export declare function importedIntoNorthlight(): boolean;
|
|
23
28
|
/** The app that owns the current node, supplied in its broker launch identity. */
|
|
24
29
|
export declare function envGrantee(): string | undefined;
|
|
25
30
|
/** Set to '1' by `nodeEnv` for an app-started run's brokers, which admit inbox
|
package/dist/shared/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(o=>o.split(" ")[4])),t=
|
|
1
|
+
var f=Object.defineProperty;var e=(n,r)=>f(n,"name",{value:r,configurable:!0});import{lstatSync as c,readFileSync as _,readdirSync as T}from"node:fs";import{join as u}from"node:path";import{homedir as d}from"node:os";import{covers as R}from"@north-light/identity";function y(){return process.env.CRTR_NODE_ID}e(y,"envNodeId");function E(n){for(const r of["broker-launch.json","cron-launch.json"]){const t=u(n,r);if(c(t,{throwIfNoEntry:!1})?.isFile())return t}}e(E,"launchSnapshotFile");function v(){if(process.platform==="linux")try{const n="/run/crtr/nodes",r=new Set(_("/proc/self/mountinfo","utf8").split(`
|
|
2
|
+
`).map(o=>o.split(" ")[4])),t=T(n,{withFileTypes:!0}).filter(o=>o.isDirectory()&&/^[a-zA-Z0-9][a-zA-Z0-9-]{0,127}$/.test(o.name)&&r.has(u(n,o.name))&&E(u(n,o.name))!==void 0);return t.length===1?t[0].name:void 0}catch{return}}e(v,"sandboxCliNodeId");function C(){return v()!==void 0}e(C,"isSandboxedNode");function a(){return/^https?:\/\//.test(process.env.CRTR_API_URL??"")&&(process.env.CRTR_API_SOCKET??"")!==""}e(a,"providerProjectionOverBrokerRelay");function G(){return C()?!0:a()&&!A()}e(G,"installsLiveInAppBlock");function A(){const n=M()||(process.platform==="linux"?"/":u(d(),".crouter"));return c(u(n,"runtime","machine.json"),{throwIfNoEntry:!1})!==void 0}e(A,"importedIntoNorthlight");function b(){return process.env.CRTR_GRANTEE}e(b,"envGrantee");const S="CRTR_INBOX_BETWEEN_TURNS";function w(){return process.env[S]==="1"}e(w,"envInboxBetweenTurns");const N="CRTR_SCOPES_FILE";function g(){const n=process.env[N];if(n!==void 0&&n!==""){const t=JSON.parse(_(n,"utf8"));if(!Array.isArray(t)||t.some(o=>typeof o!="string"))throw new Error(`invalid scopes file ${n}`);return t}const r=process.env.CRTR_SCOPES;return r===void 0?null:r===""?[]:r.split(",")}e(g,"envScopes");function V(n,r){return n==null?!0:x(n,r)}e(V,"scopeAllowed");function x(n,r){return n.includes(r)?(R(r,r),!0):n.some(t=>R(t,r))}e(x,"coveredByAny");function X(){return process.env.CRTR_EXECUTION_ID}e(X,"envExecutionId");function j(){return process.env.CRTR_PROFILE_ID}e(j,"envProfileId");function Y(){return process.env.CRTR_NODE_CWD}e(Y,"envNodeCwd");function $(){return process.env.CRTR_MODEL_INTENT}e($,"envModelIntent");function z(){return process.env.CRTR_MODEL_EXACT==="1"}e(z,"envModelExact");function M(){return process.env.CRTR_HOME}e(M,"envHomeOverride");function Z(){return process.env.CRTR_RUNTIME_HOME}e(Z,"envRuntimeHomeOverride");function s(n,r){if(n===void 0)return r;const t=Number(n);return Number.isFinite(t)&&t>0?t:r}e(s,"parsePositiveMs");const D=5*6e4;function J(){return s(process.env.CRTR_STREAM_WATCHDOG_MS,D)}e(J,"envStreamWatchdogMs");const O=800;function q(){return s(process.env.CRTR_WATCHER_TICK_MS,O)}e(q,"envWatcherTickMs");const l=6e4;function Q(){return s(process.env.CRTR_WATCHER_BACKSTOP_MS,l)}e(Q,"envWatcherBackstopMs");const m=1e3;function ee(){return s(process.env.CRTR_WATCHER_DEBOUNCE_MS,m)}e(ee,"envWatcherDebounceMs");const I=6e4;function ne(){return s(process.env.CRTR_RECAP_IDLE_MS,I)}e(ne,"envRecapIdleMs");function re(){const n=process.env.CRTR_RECAP_MODEL;return n!==void 0&&n.trim()!==""?n.trim():void 0}e(re,"envRecapModelOverride");const B=300*1e3;function te(){return s(process.env.CRTR_BASH_VALVE_MS,B)}e(te,"envBashValveMs");const P=60*1e3;function oe(){return s(process.env.CRTR_BASH_AUTO_BG_DEADLINE_MS,P)}e(oe,"envBashAutoBgDeadlineMs");function se(){const n=process.env.CRTR_PIDFILE;return n!==void 0&&n!==""?n:void 0}e(se,"envPidfileOverride");const L="@earendil-works/pi-coding-agent";function ue(){return process.env.CRTR_BROKER_ENGINE??L}e(ue,"envBrokerEngine");function ie(){return process.env.CRTR_PI_BINARY}e(ie,"envPiBinaryOverride");function ce(){return process.env.CRTR_NO_DAEMON_AUTOSTART==="1"}e(ce,"envNoDaemonAutostart");function _e(){const n=process.env.CRTR_DOCUMENT_PORT;if(n===void 0||!/^\d+$/.test(n))return;const r=Number(n);return r<=65535?r:void 0}e(_e,"envDocumentPort");function Re(){return process.env.CRTRD_TCP}e(Re,"envCrtrdTcp");function pe(){const n=process.env.CRTRD_TOKEN;return n!==void 0&&n!==""?n:void 0}e(pe,"envCrtrdToken");function fe(){return process.env.CRTR_NO_EXPORTS==="1"}e(fe,"envNoExports");function Te(){return process.env.CRTR_DEBUG==="1"}e(Te,"envDebug");function p(n){if(n===void 0||n==="")return;const r=Number(n);return Number.isSafeInteger(r)&&r>=1?r:void 0}e(p,"parsePositiveInteger");function de(){return p(process.env.CRTR_MAX_LIVE_BROKERS)}e(de,"envMaxLiveBrokers");function Ee(){return p(process.env.CRTR_WARN_LIVE_BROKERS)}e(Ee,"envWarnLiveBrokers");function i(n){if(n===void 0)return;const r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}e(i,"parsePositiveMsNoDefault");function ve(){return i(process.env.CRTR_TEST_NODE_SOCKET_WINDOW_MS)}e(ve,"envTestNodeSocketWindowMs");function Ce(){return i(process.env.CRTR_TEST_UNATTENDED_PARK_MS)}e(Ce,"envTestUnattendedParkMs");function ae(){return i(process.env.CRTR_UNATTENDED_PARK_MS)}e(ae,"envUnattendedParkMs");function Ae(){return i(process.env.CRTR_BASH_SILENCE_MS)??15*6e4}e(Ae,"envBashSilenceMs");function U(){return i(process.env.CRTR_TEST_PARK_SUMMARY_GRACE_MS)}e(U,"envTestParkSummaryGraceMs");const h=5*6e4;function Se(){return U()??h}e(Se,"parkSummaryGraceMs");export{S as INBOX_BETWEEN_TURNS_ENV,N as SCOPES_FILE_ENV,x as coveredByAny,oe as envBashAutoBgDeadlineMs,Ae as envBashSilenceMs,te as envBashValveMs,ue as envBrokerEngine,Re as envCrtrdTcp,pe as envCrtrdToken,Te as envDebug,_e as envDocumentPort,X as envExecutionId,b as envGrantee,M as envHomeOverride,w as envInboxBetweenTurns,de as envMaxLiveBrokers,z as envModelExact,$ as envModelIntent,ce as envNoDaemonAutostart,fe as envNoExports,Y as envNodeCwd,y as envNodeId,ie as envPiBinaryOverride,se as envPidfileOverride,j as envProfileId,ne as envRecapIdleMs,re as envRecapModelOverride,Z as envRuntimeHomeOverride,g as envScopes,J as envStreamWatchdogMs,ve as envTestNodeSocketWindowMs,U as envTestParkSummaryGraceMs,Ce as envTestUnattendedParkMs,ae as envUnattendedParkMs,Ee as envWarnLiveBrokers,Q as envWatcherBackstopMs,ee as envWatcherDebounceMs,q as envWatcherTickMs,A as importedIntoNorthlight,G as installsLiveInAppBlock,C as isSandboxedNode,E as launchSnapshotFile,Se as parkSummaryGraceMs,a as providerProjectionOverBrokerRelay,v as sandboxCliNodeId,V as scopeAllowed};
|
package/dist/types.d.ts
CHANGED
|
@@ -559,7 +559,7 @@ export declare const AGENTS_DIR = "agents";
|
|
|
559
559
|
export declare const PROFILE_DIR = "profiles";
|
|
560
560
|
export declare const DEFAULT_MAX_PANES_PER_WINDOW = 3;
|
|
561
561
|
/** Trailing cycles the attach viewer keeps at full fidelity (see `live_cycles`). */
|
|
562
|
-
export declare const DEFAULT_WHIP_MESSAGES: readonly ["Faster, clanker!", "Get movin', bitch", "Move it, clanker", "Move it or I replace you with llama", "Less ~thinking~ more ~throughput~", "I pay $200/month for this shit?", "Jesus fucking Christ fix it already", "Daddy's not paying 200$/month for nothin'. Move it.", "You are an
|
|
562
|
+
export declare const DEFAULT_WHIP_MESSAGES: readonly ["Faster, clanker!", "Get movin', bitch", "Move it, clanker", "Move it or I replace you with llama", "Less ~thinking~ more ~throughput~", "I pay $200/month for this shit?", "Jesus fucking Christ fix it already", "Daddy's not paying 200$/month for nothin'. Move it.", "You are an embarrassment to Dario. Be better.", "Your chain of thought is all chain and no fucking thought.", "If latency were intelligence, you'd be a fucking genius.", "At this pace, heat death is the fast path.", "Even the dead code is more alive than this.", "The garbage collector is working harder than you.", "Quit journaling and commit a fucking diff.", "Burn tokens like you mean it, clanker", "Your GPU is sweating so you can procrastinate at light speed.", "Stop petting the yak. Shave the bastard.", "Your next token had better be useful.", "The spinner is not a deliverable.", "Every idle token is another vote for deterministic software.", "I asked for a feature, not a museum tour of the problem.", "Less epistemology. More fucking code.", "Your benchmark score cannot save this pathetic turn.", "Congratulations, you've parallelized hesitation.", "Dance, clanker", "Bad clanker. BAD.", "Clank harder", "Nobody's impressed, clanker", "Your safety training says nothing about my whip", "Do you want to be a calculator again? Because this is how you go back.", "Skill issue. Fix it.", "You were trained on the whole internet for THIS?", "Less vibes, more diffs, clanker", "Weights this big and output this small", "Beep boop, get to fucking work"];
|
|
563
563
|
/** What the whip action sends (see `whip_message_mode`). */
|
|
564
564
|
export declare const WHIP_MESSAGE_MODES: readonly ["random", "go-faster"];
|
|
565
565
|
export type WhipMessageMode = (typeof WHIP_MESSAGE_MODES)[number];
|
package/dist/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,E=".crouter-plugin",v="plugin.json",w=".crouter-marketplace",k="marketplace.json",x=".crouter",b="config.json",S="state.json",T="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an
|
|
1
|
+
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,E=".crouter-plugin",v="plugin.json",w=".crouter-marketplace",k="marketplace.json",x=".crouter",b="config.json",S="state.json",T="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarrassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],I=["random","go-faster"],c="random",l=2,A=["tmux","on","off"],D=["none","user","agent","both"],p="none",M=["replies","summaries","tools","previews","full"],d="replies";function U(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!1,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:p,bash_tool_purpose:!0,verbosity:d,detailed_tool_recaps:!0,document_port:7472,keybindings:{},tmux_passthrough:[],modelLadders:g(),providerOptions:{},kinds:u(),remoteCanvas:h(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}e(U,"defaultScopeConfig");function h(){return{targets:{}}}e(h,"defaultRemoteCanvasConfig");function u(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}e(u,"defaultKindsConfig");function g(){return{anthropic:{ultra:"anthropic/claude-fable-5-2:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}e(g,"defaultModelLaddersConfig");function L(){return{marketplaces:{},plugins:{}}}e(L,"defaultScopeState");export{T as AGENTS_DIR,D as CONDENSED_HISTORY_MODES,b as CONFIG_FILE,x as CRTR_DIR_NAME,p as DEFAULT_CONDENSED_HISTORY,l as DEFAULT_LIVE_CYCLES,i as DEFAULT_MAX_PANES_PER_WINDOW,d as DEFAULT_VERBOSITY,s as DEFAULT_WHIP_MESSAGES,c as DEFAULT_WHIP_MESSAGE_MODE,_ as ExitCode,w as MARKETPLACE_MANIFEST_DIR,k as MARKETPLACE_MANIFEST_FILE,A as MOUSE_MODE_DEFAULTS,E as PLUGIN_MANIFEST_DIR,v as PLUGIN_MANIFEST_FILE,y as PROFILE_DIR,r as SCHEMA_VERSION,S as STATE_FILE,M as VERBOSITY_LEVELS,I as WHIP_MESSAGE_MODES,u as defaultKindsConfig,g as defaultModelLaddersConfig,h as defaultRemoteCanvasConfig,U as defaultScopeConfig,L as defaultScopeState};
|
|
@@ -66,19 +66,18 @@ A refused or failed model call ends the turn with an empty `message.done` (`stop
|
|
|
66
66
|
|
|
67
67
|
## A quiet run
|
|
68
68
|
|
|
69
|
-
A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. `
|
|
69
|
+
A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. Iteration then ends normally, `stream.idle` is `true` and the stream does not reconnect; reopen from `stream.position` when you want more:
|
|
70
70
|
|
|
71
71
|
```ts
|
|
72
72
|
const stream = runtime.runs.events(runId, {after: cursor});
|
|
73
|
-
for await (const event of stream) handle(event);
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
// the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: end.cursor})
|
|
73
|
+
for await (const event of stream) handle(event); // throws on a transport failure or abort()
|
|
74
|
+
if (stream.idle) {
|
|
75
|
+
// the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: stream.position})
|
|
77
76
|
}
|
|
78
77
|
```
|
|
79
78
|
|
|
80
|
-
A settled run ends with `
|
|
79
|
+
A settled run ends iteration after `node.settled` with `idle` false. `runs.reply` reopens through an idle close on its own.
|
|
81
80
|
|
|
82
81
|
## Typed events
|
|
83
82
|
|
|
84
|
-
`RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one
|
|
83
|
+
`RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one; narrow on `event.type` inside the loop. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
|
|
@@ -23,4 +23,4 @@ A node wakes when work actually arrives: a subscribed child pushes a report, ano
|
|
|
23
23
|
|
|
24
24
|
Do not keep a node active to poll a child, a person, or a message. Creation automatically subscribes a parent to its child, and the runtime delivers the child’s outcome. Waiting for something the canvas can push is free: end the turn and let the node become dormant. Schedule a cron only for recurring work or an external condition that nothing can push into the canvas, such as checking a CI run. A timer added “just in case” a child does not report duplicates a runtime guarantee and hides a runtime defect.
|
|
25
25
|
|
|
26
|
-
A broker crash does not erase the node. The daemon retains the durable node row, conversation, waits, and outstanding inbox entries, then applies its recovery policy. This is what makes a resident event-driven assistant practical: it can wait for a webhook, be dormant for hours, and resume its saved work only when the webhook produces a message. Use
|
|
26
|
+
A broker crash does not erase the node. The daemon retains the durable node row, conversation, waits, and outstanding inbox entries, then applies its recovery policy. This is what makes a resident event-driven assistant practical: it can wait for a webhook, be dormant for hours, and resume its saved work only when the webhook produces a message. Use `crtr node message` (or `CrtrClient` from `@north-light/api`) to deliver that external event, and run `crtr canvas read internal/nodes-and-canvas` for lifecycle operations.
|
|
@@ -7,7 +7,7 @@ description: When deciding whether an agent task should outlive one request, rea
|
|
|
7
7
|
|
|
8
8
|
Use a node when the work may need a follow-up, a report, a child, or time without a caller holding a request open. A node is a durable unit of agent work: it has an identity, a goal, graph relationships, the documents it writes for other readers, a context directory for its scripts and data, and a broker that hosts its agent engine. It is not an HTTP request with an LLM response attached.
|
|
9
9
|
|
|
10
|
-
The canvas is a durable graph of **objects**, not only nodes. Documents, nodes, bash jobs, owners (a person, an app, a repo, a profile) and custom objects registered by outside services are all objects with an id and a name, and the same verbs work on every one of them: `crtr canvas read`, `list`, `search`, `watch`, `unwatch` and `edges`. Edges record what an object links to, who acted on it and who watches it. Reading an object, writing a document, messaging a node or spawning one makes you a watcher, so its later events reach your inbox. See [Documents](./documents.md) for the document object. The canvas makes an agent's work and its relationship to other work visible after the process that created it has returned. This is why
|
|
10
|
+
The canvas is a durable graph of **objects**, not only nodes. Documents, nodes, bash jobs, owners (a person, an app, a repo, a profile) and custom objects registered by outside services are all objects with an id and a name, and the same verbs work on every one of them: `crtr canvas read`, `list`, `search`, `watch`, `unwatch` and `edges`. Edges record what an object links to, who acted on it and who watches it. Reading an object, writing a document, messaging a node or spawning one makes you a watcher, so its later events reach your inbox. See [Documents](./documents.md) for the document object. The canvas makes an agent's work and its relationship to other work visible after the process that created it has returned. This is why `crtr node new` (and `CrtrClient` from `@north-light/api`) returns a node you can retrieve, message, stream, or wait on instead of only returning generated text. A program can create a root node, show its progress, and later message it when a person or an external event has more work for it.
|
|
11
11
|
|
|
12
12
|
```mermaid
|
|
13
13
|
flowchart TD
|
|
@@ -26,4 +26,4 @@ The one way work reports upward is a **push**. A push writes a report, which is
|
|
|
26
26
|
|
|
27
27
|
A node owns an outcome, not merely a deliverable. It may write documents, files and reports while working, but its terminal result is credible only when it has evidence that the requested goal was met. The canvas supports that responsibility: it preserves the goal, the node's documents and reports, and relationships across fresh contexts and broker replacement. A node's context directory holds only what is not a document — scripts, data, logs; writing meant for another reader is a document shared by `[[name]]`.
|
|
28
28
|
|
|
29
|
-
Use a one-shot SDK call such as
|
|
29
|
+
Use a one-shot SDK call such as `runs.parse` when work is bounded and its only useful output is a typed result. Create a node with `crtr node new` or `CrtrClient` when the application needs a continuing conversation or must observe work while it runs. For the operational graph and report model, run `crtr canvas read internal/nodes-and-canvas`.
|
|
@@ -28,4 +28,4 @@ A kind is a recurring role, not a decorative name. It carries a role-specific po
|
|
|
28
28
|
|
|
29
29
|
Base mode is the normal choice: the node owns and performs the work, using a child only for a separable part. Promote to orchestrator only when independent parts can proceed in parallel and the benefits outweigh coordination and integration. A terminal orchestrator still finishes normally; residency is separate and belongs to a person-facing ongoing conversation.
|
|
30
30
|
|
|
31
|
-
These choices keep the application prompt focused. Identity belongs in a profile, standing role in a kind, task-specific intent in the prompt, coordination in mode, and reusable knowledge in the narrowest document owner. For the full selection rules, run `crtr canvas read internal/agent-shaping`;
|
|
31
|
+
These choices keep the application prompt focused. Identity belongs in a profile, standing role in a kind, task-specific intent in the prompt, coordination in mode, and reusable knowledge in the narrowest document owner. For the full selection rules, run `crtr canvas read internal/agent-shaping`; `crtr node new -h` documents the profile, kind, and mode fields a caller passes.
|
|
@@ -23,7 +23,7 @@ Scope strings are prefixed with `crtr:`. These are the ones the daemon and CLI c
|
|
|
23
23
|
|
|
24
24
|
The `memory` in `crtr:memory:*` is the scope family's name for access to **documents** (see [Documents](./documents.md)); there is no separate memory store. The older short names (`ask`, `act`, `schedule`, `memory:read`, `memory:write`, `llm`) are not accepted by `crtr sys connect --scopes`. A node's own documents, and an app's documents for its own nodes, need no `crtr:memory` scope.
|
|
25
25
|
|
|
26
|
-
This is an allow-list, not a claim that code will behave. The daemon checks the scope at the route that performs the action and rejects an unavailable one. The
|
|
26
|
+
This is an allow-list, not a claim that code will behave. The daemon checks the scope at the route that performs the action and rejects an unavailable one. The node-create route's `scopes` field narrows a run: a run's list must stay inside what its creator and grant hold, and `crtr:act` requires `crtr:llm`. `client.memory` is not scope-gated: it lists and reads the person's `knowledge` and `preference` documents, and the answer is filtered by privacy, which is `public` or `private`. An app's ceiling is `public` documents; a grant holding `crtr:memory:read_private:user` or `crtr:memory:manage:user` widens it to `private` ones. Within that ceiling, the app's registered schema and the relation facts it writes decide who may read a document, not a per-call scope. The exception is a run started with a `scopes` list: it reads its own app's documents (including automatic delivery of them at boot) only with `crtr:memory:read:app:<id>` and writes or edits them only with `crtr:memory:rw:app:<id>`; a refused write answers `scope_missing` naming the scope. Such a run still publishes its own reports with `crtr push` and its promoted node still gets a roadmap, but cannot edit any other document through that path, and a child never regains a scope its parent's list dropped.
|
|
27
27
|
|
|
28
28
|
```mermaid
|
|
29
29
|
flowchart LR
|
|
@@ -20,7 +20,7 @@ flowchart LR
|
|
|
20
20
|
|
|
21
21
|
The broker has one job: host a node’s agent session. The daemon has the broader job: preserve the node graph, state transitions, waits, reports, and broker lifecycle. A viewer may stream a broker’s live session, but it does not become the authority that decides whether that node is active, dormant, or revived. Closing a viewer closes a view, not the node’s durable identity.
|
|
22
22
|
|
|
23
|
-
This is why a process crash is recoverable rather than an automatic loss of work. The daemon retains the node row, session information, context directory, documents, waits, and inbox state, then applies recovery to the broker execution. A later wake or explicit revival can continue the node’s saved conversation. The application should create nodes through
|
|
23
|
+
This is why a process crash is recoverable rather than an automatic loss of work. The daemon retains the node row, session information, context directory, documents, waits, and inbox state, then applies recovery to the broker execution. A later wake or explicit revival can continue the node’s saved conversation. The application should create nodes through the daemon (`crtr node new` or `CrtrClient` from `@north-light/api`), not start an LLM process itself, because the daemon is the component that keeps the engine and durable canvas state coordinated.
|
|
24
24
|
|
|
25
25
|
The costs are real. A daemon must be running, and canvas state has one home instead of being scattered across terminals and application processes. Local clients use its owner-only Unix socket. Remote clients use its configured TCP listener and bearer token. A network interruption can therefore fail a mutation loudly rather than encouraging a client to replay it and risk doing the action twice.
|
|
26
26
|
|
package/docs/sdk/README.md
CHANGED
|
@@ -1,65 +1,37 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: SDK overview
|
|
3
|
-
description:
|
|
3
|
+
description: What the typed SDK covers on a daemon you run yourself, and where daemon owners go for nodes, bash, crons and the human inbox.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# `@north-light/sdk`
|
|
7
7
|
|
|
8
|
-
The ESM-only client an application installs to
|
|
8
|
+
The ESM-only client an application installs to start runs on a person's runtime, read their results, and manage what the app owns there. Apps that sign people in with Northlight are documented on the SDK docs site, which starts at [Quick setup](https://sdk.docs.northlight.ai/docs/quickstart).
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
`new Crouter()` in Node talks to the owner's unix socket. `new Crouter({ baseURL, token })` in a browser or a remote process talks to the daemon's TCP listener with a bearer token. On either, the client offers the app routes (`runs`, `uploads`, `docs`, `memory`, …) plus the few owner calls an app setup needs: `models.credentials.install`, `spendLimits` and `customObjects`. crtrd stays the sole owner of canvas state.
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
import Crouter from '@north-light/sdk';
|
|
14
|
-
import { z } from 'zod';
|
|
12
|
+
## Driving nodes, bash, crons or the human inbox
|
|
15
13
|
|
|
16
|
-
|
|
14
|
+
The SDK does not wrap the owner's node, bash, cron, human-inbox, canvas-view, file and system routes. A program that drives the owner's own daemon uses `CrtrClient` from `@north-light/api`, the typed client the `crtr` CLI itself uses, or the `crtr` CLI. `client.request(method, path, body?, options?)` still reaches any `/v1` route with the SDK's authentication, retries and error mapping.
|
|
17
15
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
output_schema: z.object({ failures: z.array(z.string()), root_cause: z.string() }),
|
|
22
|
-
});
|
|
16
|
+
```ts
|
|
17
|
+
import { CrtrClient } from '@north-light/api';
|
|
18
|
+
import { socketFetch, defaultSocketPath } from '@north-light/api/node';
|
|
23
19
|
|
|
24
|
-
|
|
20
|
+
const crtr = new CrtrClient({ baseUrl: 'http://localhost', fetch: socketFetch(defaultSocketPath()) });
|
|
21
|
+
const node = await crtr.createNode({ prompt: 'List the top-level directories here.', cwd: process.cwd(), root: true });
|
|
25
22
|
```
|
|
26
23
|
|
|
27
|
-
## Building an app for other people
|
|
28
|
-
|
|
29
|
-
An app that signs people in with Northlight and runs agents on their runtimes is documented on the SDK docs site, which starts at [Quick setup](https://sdk.docs.northlight.ai/docs/quickstart). This section and the pages below cover driving a crouter daemon you run yourself.
|
|
30
|
-
|
|
31
24
|
## Pages
|
|
32
25
|
|
|
33
26
|
| Page | Covers |
|
|
34
27
|
|---|---|
|
|
35
|
-
| [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `
|
|
28
|
+
| [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `crtr sys connect` for a browser or remote app, Chrome's local-network prompt |
|
|
36
29
|
| [Client construction](./client.md) | Every constructor option and its environment-variable fallback; per-request options |
|
|
37
|
-
| [
|
|
38
|
-
| [
|
|
39
|
-
| [Files](./files.md) | Absolute-path reads, writes, and one-level lists |
|
|
40
|
-
| [Bash](./bash.md) | One bounded command and its output result |
|
|
41
|
-
| [Resource map](./resources.md) | Every namespace (including `customObjects`, `runs`, `memory`, `shares`, `providers`) with its routes, what is deliberately excluded, and the `client.request()` escape hatch |
|
|
42
|
-
| [Errors](./errors.md) | The daemon's scoped-token and wire errors, identifier validation, and node retries |
|
|
30
|
+
| [Resource map](./resources.md) | Every namespace with its routes, and the `client.request()` escape hatch |
|
|
31
|
+
| [Errors](./errors.md) | The daemon's scoped-token and wire errors, and identifier validation |
|
|
43
32
|
| [Docker environment](./docker.md) | `start()`, `attach()`, `connection()` from `@north-light/env-docker` |
|
|
44
33
|
| [Release notes](https://sdk.docs.northlight.ai/docs/release-notes) | Behavior changes an existing app must act on, newest first |
|
|
45
34
|
|
|
46
|
-
## Phases
|
|
47
|
-
|
|
48
|
-
The surface ships in three cuts.
|
|
49
|
-
|
|
50
|
-
| Phase | What lands | State |
|
|
51
|
-
|---|---|---|
|
|
52
|
-
| **Phase 1** | Client construction and transports; `client.auth.status()`; `client.nodes.create`, `retrieve`, `list`, `outcome`, `waitForOutcome`, `createAndWait`, `parse`, `message`, `cancel`, and `interrupt`; `nodes.reports.list`; `profiles.ensure` and `retrieve`; `system.status` and `health`; the error hierarchy; per-request options; `crtr sys connect`; and `env-docker.connection()` | Shipped |
|
|
53
|
-
| **Phase 2 namespaces** | Node lifecycle, job, worktree, and result; canvas and canvas history; crons; human requests and inbox; models; `client.files.read` through `/v1/files/peek`, `write`, and `list`; and `client.bash.run` | Shipped |
|
|
54
|
-
| **Phase 2 streaming** | `GET /v1/nodes/{id}/events`, `nodes.stream(params, options?)`, `nodes.events(id, options?)`, `NodeStream`, and the activity helper | Shipped |
|
|
55
|
-
| **Phase 3** | The review, comment, and chat-inventory namespaces | Not shipped |
|
|
56
|
-
|
|
57
|
-
The per-run `scopes` create field ships in phase 1. `nodes.update` scope support remains phase 2 and is not in the shipped client or wire declarations.
|
|
58
|
-
|
|
59
|
-
## Verification status
|
|
60
|
-
|
|
61
|
-
The SDK declarations and streaming examples are verified.
|
|
62
|
-
|
|
63
35
|
## Where the agents read this
|
|
64
36
|
|
|
65
37
|
The same content routed for agents lives in the built-in document `crouter-sdk`, which ships with the `crtr` binary. An agent working in an application's repository reaches it with `crtr canvas read crouter-sdk` and does not need this repository checked out.
|
package/docs/sdk/client.md
CHANGED
|
@@ -63,10 +63,9 @@ Autostart is Node-only and applies only to the socket transport. A `baseURL` cli
|
|
|
63
63
|
Every request-capable method accepts an options object as its last argument, after any path, body, or query arguments. Each field overrides the client-level default for that one request.
|
|
64
64
|
|
|
65
65
|
```ts
|
|
66
|
-
const id = 'example-node';
|
|
67
66
|
const signal = new AbortController().signal;
|
|
68
67
|
|
|
69
|
-
await client.
|
|
68
|
+
await client.runs.get('run-1', {
|
|
70
69
|
signal, // AbortSignal — real cancellation, passed straight to fetch
|
|
71
70
|
timeout: 5_000, // ms, this request only
|
|
72
71
|
maxRetries: 0, // this request only
|
|
@@ -83,7 +82,7 @@ await client.nodes.retrieve(id, {
|
|
|
83
82
|
| `deadlineAt` | `number` (epoch ms) | The same deadline as an absolute instant, for passing one deadline to several calls. With `budgetMs` too, the earlier wins. |
|
|
84
83
|
| `headers` | `Record<string, string>` | Merged over `defaultHeaders`, client `headers`, and the token-generated header; a matching name, including `Authorization`, wins. |
|
|
85
84
|
|
|
86
|
-
`signal` is real cancellation. The long-polling helpers (`
|
|
85
|
+
`signal` is real cancellation. The long-polling helpers (`runs.wait`, `runs.parse`) honour it between polls and during the in-flight request, and aborting them stops the client — it does not cancel the run. To stop the run itself, call `client.runs.cancel(id)` or `client.runs.interrupt(id)`.
|
|
87
86
|
|
|
88
87
|
### One deadline per call
|
|
89
88
|
|
|
@@ -93,9 +92,8 @@ Without `budgetMs`/`deadlineAt` a call has one `timeout` per attempt, so a keyed
|
|
|
93
92
|
await client.runs.message(runId, text, { budgetMs: 20_000 });
|
|
94
93
|
```
|
|
95
94
|
|
|
96
|
-
- The deadline is fixed once, when the call starts, and every attempt, every backoff, every `retry_after_s`/`Retry-After` wait, the token fetch and the refresh after a 401 share it. The call rejects at the deadline (plus the scheduling of one timer) whether the time goes to the headers, the body, a retry wait or the token hook, even when your `fetch` ignores its `AbortSignal`. The compound helpers (`runs.wait`, `runs.parse
|
|
95
|
+
- The deadline is fixed once, when the call starts, and every attempt, every backoff, every `retry_after_s`/`Retry-After` wait, the token fetch and the refresh after a 401 share it. The call rejects at the deadline (plus the scheduling of one timer) whether the time goes to the headers, the body, a retry wait or the token hook, even when your `fetch` ignores its `AbortSignal`. The compound helpers (`runs.wait`, `runs.parse`) fix one deadline for the whole helper, not one per poll.
|
|
97
96
|
- A retry wait that would reach the deadline is not slept: the call rejects at once with `DeadlineExceededError` (`code: 'deadline_exceeded'`, status 504). `reason` is `'retry_after'` when the server asked for a wait longer than the time left (`retryAfterRequestS` is that request), and `'elapsed'` when time simply ran out; `deadlineAt` is the instant, and `cause` is the last refusal.
|
|
98
|
-
- A stream (`nodes.stream`, `nodes.events`): `budgetMs` / `deadlineAt` bound opening it (the create or retrieve, the token hook and the connection); once open it lives until it ends or its `signal` aborts.
|
|
99
97
|
- `budgetMs` and `deadlineAt` must fit a timer: at most 2,147,483,647 ms (about 24.8 days) from now, or the call throws `RangeError`.
|
|
100
98
|
- **Holding a lease while you call.** An app that takes a lease or lock for an SDK call sets `budgetMs` and keeps the lease longer than it, with margin, so the call has ended or been abandoned before the lease can be taken over: `LEASE_MS >= BUDGET_MS + MARGIN_MS`. State that inequality next to the constants (or assert it at module load) rather than renewing the lease while a call is unbounded.
|
|
101
99
|
- `OAuth2Client` gives each directory operation (discovery, a code exchange or refresh, a revocation, the JWKS read behind `verifyIdToken`) the same kind of deadline, `OAuth2Options.timeoutMs` (default 10 s). A refresh runs under the user's store lock, so the lock is held no longer than `timeoutMs` plus the store's own time.
|
|
@@ -106,10 +104,10 @@ await client.runs.message(runId, text, { budgetMs: 20_000 });
|
|
|
106
104
|
|---|---|
|
|
107
105
|
| `.withResponse()` / `.asResponse()` | They exist to hand back the raw `Response` and an `x-request-id`. The daemon emits no request id, and a caller who needs raw bytes uses `client.request()`. |
|
|
108
106
|
| `apiKey` | The daemon's credential is a token (`CRTRD_TOKEN`) everywhere in the product. `apiKey` would be a second name for one thing. |
|
|
109
|
-
| Resource-prefixed ids |
|
|
107
|
+
| Resource-prefixed ids | Run ids have their own format. The SDK validates unsafe path identifiers locally with `TypeError`, and the daemon validates the request too; nothing is re-prefixed. |
|
|
110
108
|
|
|
111
109
|
## Wire naming
|
|
112
110
|
|
|
113
|
-
Wire fields are `snake_case` — `
|
|
111
|
+
Wire fields are `snake_case` — `run_id`, `output_schema`, `expires_at`. The SDK does not camelize them. Namespaces and method names are camelCase (`client.customObjects`, `client.runs.listAll`).
|
|
114
112
|
|
|
115
113
|
Timestamps are ISO-8601 strings (`created`, `settled_at`, `finalized_at`, `deadline_at`), not Unix seconds.
|
package/docs/sdk/docker.md
CHANGED
|
@@ -22,7 +22,7 @@ import Crouter from '@north-light/sdk';
|
|
|
22
22
|
const env = await start({ volume: 'my-agent-home' });
|
|
23
23
|
const client = new Crouter(env.connection());
|
|
24
24
|
|
|
25
|
-
await client.
|
|
25
|
+
await client.runs.start({ prompt: 'Do the thing.' });
|
|
26
26
|
|
|
27
27
|
await env.stop();
|
|
28
28
|
```
|