@north-light/cli 0.3.713 → 0.3.715
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +4 -0
- package/dist/api/dto/execution-start.d.ts +9 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +2 -0
- package/dist/clients/attach/input/controller.js +1 -1
- package/dist/clients/attach/input/local-files.d.ts +3 -1
- package/dist/clients/attach/input/local-files.js +8 -3
- package/dist/clients/attach/render/chat-view.d.ts +1 -1
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/viewer.js +526 -521
- package/dist/commands/node/inspect.js +5 -5
- package/dist/commands/profile/environment.js +2 -2
- package/dist/commands/sys/feedback.js +5 -5
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +1 -1
- package/dist/core/canvas/deliveries.js +10 -10
- package/dist/core/canvas/executions.d.ts +0 -2
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
- package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/types.d.ts +1 -0
- package/dist/core/checkout-identities.js +1 -1
- package/dist/core/environment-recipe.d.ts +1 -0
- package/dist/core/environment-recipe.js +1 -1
- package/dist/core/import/load/bind.d.ts +8 -0
- package/dist/core/import/load/bind.js +15 -15
- package/dist/core/import/load/prepare.d.ts +8 -1
- package/dist/core/import/load/prepare.js +9 -7
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/ledger/rates.d.ts +0 -2
- package/dist/core/ledger/rates.js +1 -1
- package/dist/core/llm/run.d.ts +1 -1
- package/dist/core/pool-credential-store.d.ts +5 -5
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker-wedge.d.ts +1 -2
- package/dist/core/runtime/broker-wedge.js +2 -2
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/runtime/runner/types.d.ts +0 -2
- package/dist/core/runtime/spawn.js +1 -1
- package/dist/core/subscription-state.d.ts +3 -3
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/feedback.d.ts +2 -0
- package/dist/daemon/api/handlers/feedback.js +9 -0
- package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
- package/dist/daemon/api/handlers/git-credential.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -12
- package/dist/daemon/fleet.js +2 -2
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/holder.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +3 -3
- package/dist/daemon/reconcilers/ledger-storage.js +2 -4
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
- package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
- package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
- package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
- package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
- package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
- package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
- package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
- package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
- package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
- package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
- package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/core/subscription-state.js +70 -81
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
- package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
- 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 +3 -2
- package/scripts/sandbox-start.mjs +1 -1
- package/scripts/self-update.mjs +5 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as ae}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as re,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await re(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,a=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(a)||t<a?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,a,r){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return a?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":r?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,a)=>{if(process.platform==="linux"&&J(Q)){if(a!=="SIGTERM"&&a!=="SIGKILL")throw new Error(`unsupported launcher signal ${a}`);return X({operation:"stop",pid:t,signal:a}).then(()=>{})}process.kill(t,a)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const a=He();for(const r of await ie())t.held.has(r)||await D.fresh(async()=>{try{await this.handleFatalFault(r)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(r)?{node_id:r}:{fields:{affected_node_id:r}},error:n})}});for(const r of t.rows){const n=r.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||r.status!=="active"&&r.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(r,s,t.fleet,e),await this.handleWedgeDetection(r,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(r,d,e),await this.handleRemoteWedge(r,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,a)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const r of await Pe())await t.fleet.has(r)||await T(r);await ke(e)}async parkResetCondition(e,t,a,r){if(t.pi_session_id==null||t.pi_pid!==a||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,r)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,a,r,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,a,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,r);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,r);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,r);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,r);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,r)))}}async requestParkSummary(e,t){try{const a=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:a}})}catch(a){if(await T(e)===void 0)return;if(a instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:a})}}async warnOverCapInTmux(e,t,a){const r=Date.now();if(r-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=r;const{warning:n,automaticReviveCap:s}=t,d=a.stalled+a.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:a.stalled,frozen_waiting_on_mail:a.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${a.stalled} stalled, ${a.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
-
`).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const
|
|
3
|
-
`)[0]??"").slice(0,200),o=
|
|
1
|
+
var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as re}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as ae,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await ae(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,r,a){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return r?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":a?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=He();for(const a of await ie())t.held.has(a)||await D.fresh(async()=>{try{await this.handleFatalFault(a)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(a)?{node_id:a}:{fields:{affected_node_id:a}},error:n})}});for(const a of t.rows){const n=a.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||a.status!=="active"&&a.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(a,s,t.fleet,e),await this.handleWedgeDetection(a,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(a,d,e),await this.handleRemoteWedge(a,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,r)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const a of await Pe())await t.fleet.has(a)||await T(a);await ke(e)}async parkResetCondition(e,t,r,a){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,a)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,r,a,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,r,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,a);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,a);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,a);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,a);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,a)))}}async requestParkSummary(e,t){try{const r=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await T(e)===void 0)return;if(r instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const a=Date.now();if(a-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=a;const{warning:n,automaticReviveCap:s}=t,d=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
+
`).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const r=await he(e.runner).stop(e,{reason:t});return r.confirmed?await me(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:r.error}),r}async handleRemoteYieldStall(e,t,r){const a=e.node_id;if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null){await h(a,"stall_noticed_at");return}const n=await A(a,"stall_noticed_at");if(n===void 0){await I(a,"stall_noticed_at",r);return}q(!0,!1,r-n)==="kill"&&(await N(a))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(a)?{node_id:a}:{},fields:{...c(a)?{}:{affected_node_id:a},execution_id:t.executionId,elapsed_ms:r-n,grace_ms:U}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,r){const a=e.node_id,n=await b(e);if(n===null){await h(a,"wedge_noticed_at");return}const s=r-n;if(s<O)return;const d=await S(a);if(d===null||(await N(a))?.executionId!==t.executionId||await b(d)!==n||await A(a,"wedge_noticed_at")===n)return;await I(a,"wedge_noticed_at",n);const l=Math.round(s/6e4);await K(a,{quietForMs:s,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${$(d)} (${a}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${l}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null||s===null){await h(n,"stall_noticed_at"),s!==null&&this.yieldTermedAt.delete(s);return}const d=await A(n,"stall_noticed_at");if(d===void 0){await I(n,"stall_noticed_at",a);return}const l={since:d,termedAt:this.yieldTermedAt.get(s)};if(q(!0,!1,a-l.since)!=="kill")return;const o=await S(n);if(!(r.get(n)!==t||o?.pi_pid!==t.pid||o.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(l.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(s,a),l.termedAt=a,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.since,grace_ms:U}})}else a-l.termedAt>=G&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.termedAt,grace_ms:G,stall_elapsed_ms:a-l.since}})}async signalYieldStall(e,t,r){try{return await this.signal(t,r),!0}catch(a){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:a,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:r}}),!1}}async handleWedgeDetection(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity),d=await b(e);if(d===null||s===null){await h(n,"wedge_noticed_at");return}const l=a-d,o=l>=O?await this.sampleTree(t.pid):null,p=await S(n),u=p===null?null:await b(p);if(r.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==d)return;const w=o?.cpuPercent??null,k=o?.hasDescendants??null;if(Ge({busy:!0,quietForMs:l,cpuPercent:w,hasDescendants:k})!=="wedged"||await A(n,"wedge_noticed_at")===d)return;await I(n,"wedge_noticed_at",d);const v=$(p),E=Math.round((l??O)/6e4),g=k??!0,y=!g&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let M=!1,m=!1;if(!g&&y===null){M=!0;try{await this.signal(t.pid,"SIGTERM"),m=!0}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}})}}const P=Ke(`${v} (${n})`,E,g,y!==null,m);await K(n,{quietForMs:l,cpuPercent:w,hasDescendants:g,kickAttempted:M,kicked:m,kickSuppressionReason:y,pid:t.pid,label:P})}async handleFatalFault(e,t=!0){const r=await L(e);if(r===null||r.retry.disposition!=="fatal"||r.link!=="pi\u2192provider"||r.notifiedSince===r.since)return;const a=await S(e),n=await Y(e),s=a!==null?$(a):e,d=r.kind==="auth",l=(r.message.split(`
|
|
3
|
+
`)[0]??"").slice(0,200),o=r.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(o.ratelimit===void 0?"":` Rate limit: ${o.ratelimit.scope??"account"}${o.ratelimit.claim===void 0?"":` (${o.ratelimit.claim})`}${o.ratelimit.model===void 0?"":` on ${o.ratelimit.model}`}.`),u=r.kind==="context-overflow",w=Ve(a,typeof o?.code=="string"?o.code:void 0),k=u||w,v=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${l}`:`got a non-retryable ${r.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(d?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${l}.${p}`,E=u?"failed":"hit a fatal provider fault",g=new Set((await ne(e)).map(m=>m.node_id)),y=await fe(await x(),await ue(await x(),e)),M=[{relation:"Child",recipients:y.filter(m=>g.has(m))},{relation:"Watched node",recipients:y.filter(m=>!g.has(m))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:r.kind,link:r.link,terminal_overflow:u,terminal_provider_fault:w}}),await ce(async()=>{for(const{relation:m,recipients:P}of M)P.length!==0&&await W(e,"notice.crash",`${m} ${E} \u2014 ${s} (${e}) ${v}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:r.kind,message:l,...o===void 0?{}:{provider_error:o}},"normal",null,P);await oe(r.faultId),t&&k&&await re(e,"crash",{reason:u?"context_overflow":o?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:r.message,fault_kind:r.kind,error_class:de(r).class,...typeof o?.code=="string"?{provider_code:o.code}:{},...o?.payment===void 0?{}:{payment:o.payment}}}})}),t&&k&&this.teardownBroker(e,n).then(m=>{m.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m.error??new Error("Broker teardown not confirmed")})},m=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m}))}}export{Nt as BrokerSupervisionReconciler,H as parkSummaryGraceMsForDaemon,K as reportWedge,Ve as settlesOnFatalProviderFault,He as unattendedParkMsForDaemon,Ke as wedgeLabel};
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var D=Object.defineProperty;var f=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as w}from"../../core/canvas/db.js";import{getNode as M}from"../../core/canvas/canvas.js";import{LEDGER_ENV as O,storageUsdPerGbMonth as E,warnRateUnset as N}from"../../core/ledger/rates.js";import{emitEvent as g}from"../../core/events/emit.js";import{operationIdContext as _}from"../../core/events/operation-id.js";import{billingAccountOf as T}from"../../core/ledger/account.js";import{writeInfraCharge as L}from"../../core/ledger/infra-allowance.js";import{usageMonth as y}from"../../core/ledger/months.js";import{startCandidateOf as A}from"../../core/runtime/start-check.js";import{runThrottledLane as C}from"./throttled-lane.js";const v=60*6e4,I=10*6e4,U=1024**3;async function K(){if(E()===null)return;const n=await(await w()).prepare("SELECT cursor FROM reconciler_leases WHERE lane = 'ledger-storage' AND key = ''").get(),e=n?.cursor==null?null:JSON.parse(n.cursor).state;return e===null?null:e.slice(0,7)}f(K,"storageSettledThrough");function G(n){const[e,r]=n.split("-").map(Number);return y(new Date(Date.UTC(e,r-2,1)))}f(G,"previousMonth");const S=f(n=>{const[e,r]=n.split("-").map(Number);return y(new Date(Date.UTC(e,r,1)))},"nextMonth"),x=f(n=>{const[e,r]=n.split("-").map(Number);return new Date(Date.UTC(e,r,1)).toISOString()},"endOf");class q{static{f(this,"LedgerStorageReconciler")}run(e,r){if(!r.lifecycle.acceptsDetachedWork())return;const a=_.fresh(()=>C("ledger-storage","",e,v,I,async o=>{await this.pass(e,o)})).then(()=>{}).catch(o=>{_.fresh(()=>g({level:"error",event:"ledger.storage.failed",error:o}))});r.lifecycle.registerDetached(a)}async pass(e,r){const a=G(y(new Date(e))),o={month:null,rows:0,failed:0},l=E();if(l===null)return N("ledger-storage",O.storageUsdPerGbMonth),o;const i=r?.state?.slice(0,7)??null,c=[];if(i===null)c.push(a);else for(let s=S(i);s<=a;s=S(s))c.push(s);for(const s of c){if(o.month=s,!await this.settleMonth(s,l,r,o))break;await r?.save(s)}return(o.rows>0||o.failed>0)&&g({level:"info",event:"ledger.storage.settled",outcome:"succeeded",fields:{...o}}),o}async settleMonth(e,r,a,o){const l=x(e),i=await w(),c=new Map,s=f((t,d)=>{c.set(t,(c.get(t)??0)+Number(d))},"add");for(const t of await i.prepare("SELECT split_part(blob_key, '/', 2) AS node, sum(bytes) AS bytes FROM conversation_parts WHERE created < ? GROUP BY 1").all(l))s(t.node,t.bytes);for(const t of await i.prepare(`SELECT x.node, sum(u.size) AS bytes FROM (
|
|
2
2
|
SELECT DISTINCT upload_id, split_part(blob_key, '/', 2) AS node FROM upload_uses WHERE blob_key LIKE 'attachments/%') x
|
|
3
|
-
JOIN uploads u ON u.upload_id = x.upload_id WHERE u.created_at < ? GROUP BY x.node`).all(
|
|
4
|
-
SELECT DISTINCT node_id, sandbox_name FROM executions WHERE runner = 'blaxel' AND sandbox_name IS NOT NULL AND started_at < ?) x
|
|
5
|
-
JOIN nodes n ON n.node_id = x.node_id JOIN objects o ON o.id = n.node_id AND (o.deleted_at IS NULL OR o.deleted_at >= ?) JOIN profiles p ON p.id = n.profile_id JOIN environments e ON e.object = p.environment_id GROUP BY x.node_id`).all(i,i))g(e.node).diskGb+=Number(e.mb)/2/1024;const y=new Map;for(const[e,a]of _){const p=await A(e),u=p===null?null:await v(p);if(u===null)continue;const f=y.get(u.payer)??{sub:u.sub,grantee:u.grantee,bytes:0,diskGb:0,node:e};f.bytes+=a.bytes,f.diskGb+=a.diskGb,y.set(u.payer,f)}const x=new Date(Date.parse(i)-1);let w=0;for(const[e,a]of y){if(d&&!await d.holds())return!1;try{const{account:p,billable:u}=await G(n,e),f=[{id:`storage:${e}:${t}:r2`,provider:"r2",gbMonths:a.bytes/F,rate:c},{id:`storage:${e}:${t}:blaxel`,provider:"blaxel",gbMonths:a.diskGb,rate:m}];for(const l of f){if(l.rate===null||l.gbMonths<=0)continue;const L=l.gbMonths*l.rate;(await I({id:l.id,at:x,kind:"storage",what:l.provider==="r2"?"object storage":"sandbox disk",units:{gb_months:l.gbMonths},usd:L,payer:e,funding:"bill",sub:a.sub,grantee:a.grantee,provider:l.provider,causedBy:null,account:p},u)).written&&(r.rows+=1)}}catch(p){r.failed+=1,w+=1,E({level:"warn",event:"ledger.storage.payer_failed",error:p,fields:{payer:e,month:t}})}}return w===0}}export{U as LEDGER_STORAGE_INTERVAL_MS,te as LedgerStorageReconciler,ee as storageSettledThrough};
|
|
3
|
+
JOIN uploads u ON u.upload_id = x.upload_id WHERE u.created_at < ? GROUP BY x.node`).all(l))s(t.node,t.bytes);for(const t of await i.prepare("SELECT node_id AS node, sum(size) AS bytes FROM files WHERE completed_at IS NOT NULL AND completed_at < ? GROUP BY node_id").all(l))s(t.node,t.bytes);const b=new Map;for(const[t,d]of c){const p=await M(t),u=p===null?null:await A(p);if(u===null)continue;const m=b.get(u.payer)??{sub:u.sub,grantee:u.grantee,bytes:0,node:t};m.bytes+=d,b.set(u.payer,m)}const R=new Date(Date.parse(l)-1);let h=0;for(const[t,d]of b){if(a&&!await a.holds())return!1;try{const{account:p,billable:u}=await T(i,t),m=d.bytes/U;if(m<=0)continue;(await L({id:`storage:${t}:${e}:r2`,at:R,kind:"storage",what:"object storage",units:{gb_months:m},usd:m*r,payer:t,funding:"bill",sub:d.sub,grantee:d.grantee,provider:"r2",causedBy:null,account:p},u)).written&&(o.rows+=1)}catch(p){o.failed+=1,h+=1,g({level:"warn",event:"ledger.storage.payer_failed",error:p,fields:{payer:t,month:e}})}}return h===0}}export{v as LEDGER_STORAGE_INTERVAL_MS,q as LedgerStorageReconciler,K as storageSettledThrough};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as
|
|
1
|
+
var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as c}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as p}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const a=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return a>0&&t-a<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await c(s);return t?.runner==="process"&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,a){await this.pass(t,{rows:[e],fleet:a})}async pass(t,e){const a=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,a))}catch(i){const o=n.node_id;E({level:i instanceof R?"warn":"error",event:i instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(o)?{node_id:o}:{fields:{affected_node_id:o}},error:i})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:a})}async classifyRow(t,e,a,n){const i=e.node_id;if(X(e)){if(H(e,await a.fleet.has(i)))return;if(S(e)&&!await a.fleet.has(i)&&!f(e.profile_id)&&!await I(i)&&!k(e,t)&&await p(i)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(i);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(i):n.push({row:e,enact:"thaw"}));return}if(await a.fleet.has(i)){const r=await c(i);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await p(i))try{if(await Q(r)==="lost")return}catch(l){if(l instanceof x)return;throw l}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await a.fleet.has(i)){f(e.profile_id)?await a.fleet.interruptForProfilePause(i):await this.thawMark(e);return}}if(await K(i,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(i);return}if(await I(i))return;const o=e.pi_pid==null?await v(i):null,u=o!==null&&D(o),m=o!==null&&!u&&M(o),h=e.pi_pid!=null?await b(i):null,_=u||m||h!==null;if(_&&!await a.fleet.hasProfilePauseInterruption(i)){const r=h??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const l=await c(i);if(l!==null&&l.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await p(i)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!m){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await a.fleet.isClaimed(i)||Z(e,t,await v(i)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:i}),n.push({row:e,enact:"thaw"});return}if(!_)return;const y=O(await z(i),(await A(i))?.interrupted===!0,await U(i));if(y==="respawn-fresh"||y==="respawn-resume"){n.push({row:e,enact:"policy"});return}await a.fleet.applyDeadRowPolicy(i),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.715",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.715",
|
|
162
|
+
"@north-light/plugin": "0.3.715",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -417,6 +417,10 @@ export class CrtrClient {
|
|
|
417
417
|
gitCredential(environmentId, req) {
|
|
418
418
|
return this.request('POST', routes.environmentGitCredential(environmentId), req);
|
|
419
419
|
}
|
|
420
|
+
/** File a crtr harness report as an issue on the crouter repository (a cloud node's report; the control plane attaches the node, environment and person). */
|
|
421
|
+
postFeedback(req) {
|
|
422
|
+
return this.request('POST', routes.feedback(), req);
|
|
423
|
+
}
|
|
420
424
|
brokerExtensionState(id) {
|
|
421
425
|
return this.request('GET', routes.nodeBrokerExtensionState(this.nodePath(id)));
|
|
422
426
|
}
|
|
@@ -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.70';
|
|
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`. */
|
|
@@ -32,6 +32,7 @@ export const routes = {
|
|
|
32
32
|
executionStart: (id) => `${V}/executions/${id}/start`,
|
|
33
33
|
executionImportUnpacked: (id) => `${V}/executions/${id}/import-unpacked`,
|
|
34
34
|
environmentGitCredential: (id) => `${V}/environments/${id}/git-credential`,
|
|
35
|
+
feedback: () => `${V}/feedback`,
|
|
35
36
|
nodeOutcome: (id) => `${V}/nodes/${id}/outcome`,
|
|
36
37
|
nodeOutcomeDelivery: (id) => `${V}/nodes/${id}/outcome-delivery`,
|
|
37
38
|
nodeEvents: (id) => `${V}/nodes/${id}/events`,
|
|
@@ -290,7 +290,7 @@ export class InputController {
|
|
|
290
290
|
sent();
|
|
291
291
|
this.editor.setText('');
|
|
292
292
|
this.tui.requestRender();
|
|
293
|
-
void attachLocalFiles(expanded, request).then((final) => {
|
|
293
|
+
void attachLocalFiles(expanded, request, this.hooks.whenBrokerReady).then((final) => {
|
|
294
294
|
if (!deliver(final) && this.editor.getText().trim() === '') {
|
|
295
295
|
this.editor.setText(typed);
|
|
296
296
|
this.tui.requestRender();
|
|
@@ -51,12 +51,25 @@ function mib(bytes) {
|
|
|
51
51
|
export function hasLocalPaths(text) {
|
|
52
52
|
return findLocalPaths(text).length > 0;
|
|
53
53
|
}
|
|
54
|
+
/** The runtime note attachLocalFiles appends, found at the end of a user message. */
|
|
55
|
+
const TRAILING_RUNTIME_NOTE = /\n\n<runtime>\n[\s\S]*?\n<\/runtime>\s*$/;
|
|
56
|
+
/** A user message's text without the trailing runtime note: the note is for the node, not the person. */
|
|
57
|
+
export function withoutRuntimeNote(text) {
|
|
58
|
+
return text.replace(TRAILING_RUNTIME_NOTE, '');
|
|
59
|
+
}
|
|
54
60
|
/** Send each local file `text` names to the node and rewrite its path; append a `<runtime>` note for every file that could not go. */
|
|
55
|
-
export async function attachLocalFiles(text, request) {
|
|
61
|
+
export async function attachLocalFiles(text, request, brokerReady = () => Promise.resolve(true)) {
|
|
56
62
|
const matches = findLocalPaths(text);
|
|
57
63
|
if (matches.length === 0)
|
|
58
64
|
return text;
|
|
59
65
|
const notes = [];
|
|
66
|
+
// A viewer that attached before the node's runtime finished starting has no broker to take a file yet: wait for it.
|
|
67
|
+
if (!(await brokerReady())) {
|
|
68
|
+
const named = [...new Set(matches.filter((m) => readLocal(m.path).kind === 'file').map((m) => m.raw))];
|
|
69
|
+
if (named.length === 0)
|
|
70
|
+
return text;
|
|
71
|
+
return `${text}\n\n<runtime>\n${named.map((raw) => `the node's runtime was not ready, so ${raw} was not sent to you.`).join('\n')}\n</runtime>`;
|
|
72
|
+
}
|
|
60
73
|
const sent = new Map();
|
|
61
74
|
const replaced = [];
|
|
62
75
|
for (const match of matches) {
|
|
@@ -84,7 +97,10 @@ export async function attachLocalFiles(text, request) {
|
|
|
84
97
|
replaced.push({ match, to: reply.path });
|
|
85
98
|
}
|
|
86
99
|
catch (error) {
|
|
87
|
-
|
|
100
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
101
|
+
notes.push(error?.code === 'unknown_frame'
|
|
102
|
+
? `this node's runtime is too old to receive files from the viewer; ${match.raw} was not sent.`
|
|
103
|
+
: `file ${match.raw} could not be uploaded (${message}).`);
|
|
88
104
|
}
|
|
89
105
|
}
|
|
90
106
|
let out = text;
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// `renderCall`/`renderResult` hooks degrade to the default ToolExecutionComponent
|
|
22
22
|
// path while builtin tools, diffs, and partial-result streaming keep working.
|
|
23
23
|
import { Container, Loader, Markdown, Spacer, Text } from '@earendil-works/pi-tui';
|
|
24
|
+
import { withoutRuntimeNote } from '../input/local-files.js';
|
|
24
25
|
import { AssistantMessageComponent, BashExecutionComponent, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomMessageComponent, parseSkillBlock, SkillInvocationMessageComponent, ToolExecutionComponent, UserMessageComponent, } from '@earendil-works/pi-coding-agent';
|
|
25
26
|
import { attachMarkdownTheme } from '../config.js';
|
|
26
27
|
import { ContextMessageComponent } from './context-message.js';
|
|
@@ -1686,7 +1687,7 @@ export class ChatView {
|
|
|
1686
1687
|
return;
|
|
1687
1688
|
const parts = [
|
|
1688
1689
|
new Spacer(1),
|
|
1689
|
-
new Markdown(trimmed, 1, 1, attachMarkdownTheme(), { color: this.dimStyle }),
|
|
1690
|
+
new Markdown(withoutRuntimeNote(trimmed).trim(), 1, 1, attachMarkdownTheme(), { color: this.dimStyle }),
|
|
1690
1691
|
];
|
|
1691
1692
|
for (const part of parts)
|
|
1692
1693
|
this.pendingContainer.addChild(part);
|
|
@@ -1716,7 +1717,7 @@ export class ChatView {
|
|
|
1716
1717
|
if (message.role === 'user')
|
|
1717
1718
|
seen.add(this.userMessageText(message).trim());
|
|
1718
1719
|
}
|
|
1719
|
-
return this.pendingSends.filter((sent) => sent.resend && !seen.has(sent.text)).map((sent) => sent.text);
|
|
1720
|
+
return this.pendingSends.filter((sent) => sent.resend && !seen.has(withoutRuntimeNote(sent.text).trim())).map((sent) => sent.text);
|
|
1720
1721
|
}
|
|
1721
1722
|
/** The pending messages were handed to a parked node's wake message, so a reconnect must not send them again. */
|
|
1722
1723
|
stopResendingPendingSends() {
|
|
@@ -1728,7 +1729,7 @@ export class ChatView {
|
|
|
1728
1729
|
confirmPendingSend(text) {
|
|
1729
1730
|
// The engine may reshape the text (image blocks, wrapping); with no exact
|
|
1730
1731
|
// match the oldest pending send is the one that landed.
|
|
1731
|
-
const exact = this.pendingSends.findIndex((sent) => sent.text === text);
|
|
1732
|
+
const exact = this.pendingSends.findIndex((sent) => withoutRuntimeNote(sent.text).trim() === text);
|
|
1732
1733
|
const index = exact >= 0 ? exact : 0;
|
|
1733
1734
|
if (this.pendingSends.length === 0)
|
|
1734
1735
|
return;
|
|
@@ -1747,7 +1748,7 @@ export class ChatView {
|
|
|
1747
1748
|
seen.add(this.userMessageText(message).trim());
|
|
1748
1749
|
}
|
|
1749
1750
|
for (const sent of [...this.pendingSends]) {
|
|
1750
|
-
if (!seen.has(sent.text))
|
|
1751
|
+
if (!seen.has(withoutRuntimeNote(sent.text).trim()))
|
|
1751
1752
|
continue;
|
|
1752
1753
|
this.pendingSends.splice(this.pendingSends.indexOf(sent), 1);
|
|
1753
1754
|
for (const part of sent.parts)
|
|
@@ -1940,16 +1941,16 @@ export class ChatView {
|
|
|
1940
1941
|
// Tool payloads that cannot serialize are not transcript text.
|
|
1941
1942
|
}
|
|
1942
1943
|
}
|
|
1943
|
-
/** Concatenate the text blocks of a user message (string or content array). */
|
|
1944
|
+
/** Concatenate the text blocks of a user message (string or content array), without the viewer's trailing runtime note. */
|
|
1944
1945
|
userMessageText(message) {
|
|
1945
1946
|
const content = message.content;
|
|
1946
1947
|
if (typeof content === 'string')
|
|
1947
|
-
return content;
|
|
1948
|
+
return withoutRuntimeNote(content);
|
|
1948
1949
|
if (!Array.isArray(content))
|
|
1949
1950
|
return '';
|
|
1950
|
-
return content
|
|
1951
|
+
return withoutRuntimeNote(content
|
|
1951
1952
|
.filter((c) => typeof c === 'object' && c !== null && c.type === 'text')
|
|
1952
1953
|
.map((c) => c.text)
|
|
1953
|
-
.join('');
|
|
1954
|
+
.join(''));
|
|
1954
1955
|
}
|
|
1955
1956
|
}
|
|
@@ -93,6 +93,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
|
|
|
93
93
|
onColor: hooks.setChipColor,
|
|
94
94
|
onPromptSent: hooks.onPromptSent,
|
|
95
95
|
onMessageSent: hooks.onMessageSent,
|
|
96
|
+
whenBrokerReady: hooks.whenBrokerReady,
|
|
96
97
|
frecency: hooks.frecency,
|
|
97
98
|
knownRefNames: () => editor.getResolvedRefNames(),
|
|
98
99
|
// Global display toggles (Ctrl+O tools / Ctrl+T thinking) — pure render
|
|
@@ -462,9 +462,22 @@ onConnected) {
|
|
|
462
462
|
socket.send(frame);
|
|
463
463
|
reconnect.probe();
|
|
464
464
|
};
|
|
465
|
+
// Uploading a file needs the broker: a message naming one waits here for the first welcome, at most a minute.
|
|
466
|
+
let brokerReadyResolve = () => { };
|
|
467
|
+
const brokerReady = new Promise((resolve) => { brokerReadyResolve = resolve; });
|
|
468
|
+
const whenBrokerReady = () => {
|
|
469
|
+
if (welcomed)
|
|
470
|
+
return Promise.resolve(true);
|
|
471
|
+
if (settled)
|
|
472
|
+
return Promise.resolve(false);
|
|
473
|
+
let timer;
|
|
474
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(false), 60_000); timer.unref?.(); });
|
|
475
|
+
return Promise.race([brokerReady, timeout]).finally(() => clearTimeout(timer));
|
|
476
|
+
};
|
|
465
477
|
const onFirstWelcome = () => {
|
|
466
478
|
welcomed = true;
|
|
467
479
|
settled = true;
|
|
480
|
+
brokerReadyResolve(true);
|
|
468
481
|
for (const frame of heldFrames.splice(0))
|
|
469
482
|
socket.send(frame);
|
|
470
483
|
};
|
|
@@ -492,6 +505,7 @@ onConnected) {
|
|
|
492
505
|
},
|
|
493
506
|
onMessageSent: (text, viaSocket) => chatView.addPendingSend(text, viaSocket),
|
|
494
507
|
send: sendToBroker,
|
|
508
|
+
whenBrokerReady,
|
|
495
509
|
frecency,
|
|
496
510
|
});
|
|
497
511
|
const whip = () => {
|
|
@@ -912,6 +926,7 @@ onConnected) {
|
|
|
912
926
|
// Text sent while the dial was still running has no broker to hold it: deliver it as the wake message a parked viewer's own sends use.
|
|
913
927
|
// An engine command (`/x`, `!x`) is refused as a later parked submission is, and returned to the editor.
|
|
914
928
|
settled = true;
|
|
929
|
+
brokerReadyResolve(false);
|
|
915
930
|
chatView.stopResendingPendingSends();
|
|
916
931
|
const refused = [];
|
|
917
932
|
for (const frame of heldFrames.splice(0)) {
|
|
@@ -175,9 +175,10 @@ const nodeShow = defineLeaf({
|
|
|
175
175
|
hints.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${reports.map((r) => r['node_id']).join(', ')}).`);
|
|
176
176
|
hints.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${id}\`.`);
|
|
177
177
|
const result = { node, fault: node.fault ?? null, reports, managers, pending_crons, paths, follow_up: hints.join('\n') };
|
|
178
|
-
// The environment read answers 400 for a profile that runs on a machine
|
|
179
|
-
|
|
180
|
-
|
|
178
|
+
// The environment read answers 400 for a profile that runs on a machine, and 404 for a profile the caller cannot see
|
|
179
|
+
// (another app's): reading a node does not require its owning profile to be visible, so that is not a failure.
|
|
180
|
+
const inSandbox = node.runner === 'blaxel' || node.profile_id !== null && await client.getProfileEnvironment(node.profile_id).then(() => true, (err) => {
|
|
181
|
+
if (err instanceof ApiError && (err.status === 400 || err.status === 404))
|
|
181
182
|
return false;
|
|
182
183
|
return rethrowAsCliError(err);
|
|
183
184
|
});
|
|
@@ -13,6 +13,7 @@ const ENVIRONMENT_OUTPUT = [
|
|
|
13
13
|
{ name: 'setup_script', type: 'string', required: false, constraint: 'The script the image build runs; null when none.' },
|
|
14
14
|
{ name: 'pi_packages', type: 'string', required: false, constraint: 'pi package sources, one per line; null when none.' },
|
|
15
15
|
{ name: 'memory_mb', type: 'number', required: true, constraint: 'Memory of new sandboxes: 2048, 4096 or 8192.' },
|
|
16
|
+
{ name: 'allow_pull_request_write', type: 'boolean', required: true, constraint: 'Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write.' },
|
|
16
17
|
{ name: 'recipe_revision', type: 'number', required: true, constraint: 'Raised by one each time the recipe changes.' },
|
|
17
18
|
{ name: 'image_revision', type: 'number', required: false, constraint: 'The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build.' },
|
|
18
19
|
{ name: 'image_error', type: 'string', required: false, constraint: 'Why the last image build failed; null when it did not.' },
|
|
@@ -40,7 +41,7 @@ const showLeaf = defineLeaf({
|
|
|
40
41
|
});
|
|
41
42
|
const setLeaf = defineLeaf({
|
|
42
43
|
name: 'set',
|
|
43
|
-
description: "change a cloud profile's repositories, setup script, pi packages or
|
|
44
|
+
description: "change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",
|
|
44
45
|
whenToUse: 'a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.',
|
|
45
46
|
help: {
|
|
46
47
|
name: 'profile environment set',
|
|
@@ -50,6 +51,7 @@ const setLeaf = defineLeaf({
|
|
|
50
51
|
{ kind: 'flag', name: 'repo', type: 'string', required: false, repeatable: true, constraint: 'GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each.' },
|
|
51
52
|
{ kind: 'flag', name: 'setup-script-file', type: 'path', required: false, constraint: 'File holding the setup script the image build runs as root.' },
|
|
52
53
|
{ kind: 'flag', name: 'pi-package', type: 'string', required: false, repeatable: true, constraint: 'pi package source (repeat per package); replaces the whole list.' },
|
|
54
|
+
{ kind: 'flag', name: 'allow-pull-request-write', type: 'bool', required: false, constraint: 'Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image.' },
|
|
53
55
|
{ kind: 'flag', name: 'memory', type: 'int', required: false, constraint: 'Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory.' },
|
|
54
56
|
],
|
|
55
57
|
output: [...ENVIRONMENT_OUTPUT],
|
|
@@ -62,6 +64,7 @@ const setLeaf = defineLeaf({
|
|
|
62
64
|
const file = input['setupScriptFile'];
|
|
63
65
|
const packages = input['piPackage'];
|
|
64
66
|
const memory = input['memory'];
|
|
67
|
+
const allowPrWrite = input['allowPullRequestWrite'];
|
|
65
68
|
if (memory !== undefined && ![2, 4, 8].includes(memory))
|
|
66
69
|
throw usage('`--memory` is 2, 4 or 8 (GB).');
|
|
67
70
|
const req = {
|
|
@@ -69,9 +72,10 @@ const setLeaf = defineLeaf({
|
|
|
69
72
|
...(file !== undefined ? { setup_script: readFileSync(resolve(file), 'utf8') } : {}),
|
|
70
73
|
...(packages !== undefined && packages.length > 0 ? { pi_packages: packages.join('\n') } : {}),
|
|
71
74
|
...(memory !== undefined ? { memory_mb: memory * 1024 } : {}),
|
|
75
|
+
...(allowPrWrite !== undefined ? { allow_pull_request_write: allowPrWrite } : {}),
|
|
72
76
|
};
|
|
73
77
|
if (Object.keys(req).length === 0)
|
|
74
|
-
throw usage('pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`.');
|
|
78
|
+
throw usage('pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.');
|
|
75
79
|
return output(await cliClient().setProfileEnvironment(id, req));
|
|
76
80
|
},
|
|
77
81
|
});
|
|
@@ -21,7 +21,7 @@ import { defineLeaf } from '../../core/command.js';
|
|
|
21
21
|
import { usage } from '../../core/errors.js';
|
|
22
22
|
import { userScopeRoot } from '../../core/scope.js';
|
|
23
23
|
import { readTelemetry } from '../../core/canvas/telemetry.js';
|
|
24
|
-
import { ApiError } from '../../api/index.js';
|
|
24
|
+
import { ApiError, routes } from '../../api/index.js';
|
|
25
25
|
import { cliClient } from '../api-client.js';
|
|
26
26
|
import { projectTier1Event, readLogSnapshot } from '../../core/events/read.js';
|
|
27
27
|
import { readPackageVersion } from './shared.js';
|
|
@@ -125,6 +125,16 @@ function buildBody(message, ctx) {
|
|
|
125
125
|
* answer with a `url` naming where the report landed; anything else about the
|
|
126
126
|
* response body is the backend's business, not ours. */
|
|
127
127
|
async function deliverToEndpoint(endpoint, title, body, message, ctx) {
|
|
128
|
+
// The endpoint is the control plane's own feedback route (a cloud sandbox): the node token lives in the broker's relay, so the call goes through it.
|
|
129
|
+
const apiUrl = process.env['CRTR_API_URL'];
|
|
130
|
+
if (apiUrl !== undefined && apiUrl !== '' && endpoint === `${apiUrl.replace(/\/$/, '')}${routes.feedback()}`) {
|
|
131
|
+
try {
|
|
132
|
+
return { url: (await cliClient().postFeedback({ title, body })).url };
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
return { error: `${ENDPOINT_ENV} failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
128
138
|
const token = process.env[TOKEN_ENV];
|
|
129
139
|
try {
|
|
130
140
|
const res = await fetch(endpoint, {
|
|
@@ -201,7 +211,7 @@ export const sysFeedbackLeaf = defineLeaf({
|
|
|
201
211
|
],
|
|
202
212
|
outputKind: 'object',
|
|
203
213
|
effects: [
|
|
204
|
-
`Sends the report where this install delivers harness feedback: the ${ENDPOINT_ENV} endpoint when the deployment sets one, otherwise a
|
|
214
|
+
`Sends the report where this install delivers harness feedback: the ${ENDPOINT_ENV} endpoint when the deployment sets one, otherwise a GitHub issue on ${FEEDBACK_REPO} via gh.`,
|
|
205
215
|
'On delivery failure, writes the report to ~/.crouter/feedback/ instead — never lost.',
|
|
206
216
|
],
|
|
207
217
|
},
|
|
@@ -164,7 +164,7 @@ export class BrokerClient extends EventEmitter {
|
|
|
164
164
|
const entry = this.pending.get(frame.id);
|
|
165
165
|
this.pending.delete(frame.id);
|
|
166
166
|
clearTimeout(entry.timer);
|
|
167
|
-
entry.reject(new Error(frame.message || `request failed: ${frame.code}`));
|
|
167
|
+
entry.reject(Object.assign(new Error(frame.message || `request failed: ${frame.code}`), { code: frame.code }));
|
|
168
168
|
return;
|
|
169
169
|
}
|
|
170
170
|
this.emit('frame', frame);
|
|
@@ -108,6 +108,7 @@ function rowFrom(r) {
|
|
|
108
108
|
parent: r['parent'] ?? null,
|
|
109
109
|
created: r['created'],
|
|
110
110
|
intent: r['intent'] ?? null,
|
|
111
|
+
cycle_pending: r['cycle_pending'] === 1,
|
|
111
112
|
frozen_at: r['frozen_at'] ?? null,
|
|
112
113
|
respawn_failures: r['respawn_failures'] ?? 0,
|
|
113
114
|
respawn_not_before: r['respawn_not_before'] ?? null,
|
|
@@ -153,7 +154,6 @@ async function metaFrom(r, worktree) {
|
|
|
153
154
|
fork_from: r['fork_from'] ?? null,
|
|
154
155
|
fork_source_file: r['fork_source_file'] ?? null,
|
|
155
156
|
passive_default: r['passive_default'] === 1,
|
|
156
|
-
cycle_pending: r['cycle_pending'] === 1,
|
|
157
157
|
model_override: r['model_override'] ?? null,
|
|
158
158
|
scopes: r['scopes_json'] == null ? null : JSON.parse(r['scopes_json']),
|
|
159
159
|
persona_ack: r['persona_ack_json'] == null ? undefined : JSON.parse(r['persona_ack_json']),
|
|
@@ -30,7 +30,7 @@ export function deliveryFrom(row) {
|
|
|
30
30
|
}
|
|
31
31
|
async function executionIsLive(db, nodeId, executionId, rejectRefresh) {
|
|
32
32
|
const row = await db.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
|
|
33
|
-
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh'" : ''}`).get(nodeId, executionId);
|
|
33
|
+
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh' AND n.cycle_pending = 0" : ''}`).get(nodeId, executionId);
|
|
34
34
|
return row !== undefined;
|
|
35
35
|
}
|
|
36
36
|
async function nodeMailRows(db, nodeId, executionId, wake, freshIds, deferredRun = false) {
|
|
@@ -21,7 +21,6 @@ function hydrate(row) {
|
|
|
21
21
|
endedAt: row['ended_at'] ?? null,
|
|
22
22
|
exitReason: row['exit_reason'] ?? null,
|
|
23
23
|
runner: row['runner'],
|
|
24
|
-
sandboxName: row['sandbox_name'] ?? null,
|
|
25
24
|
attempt: Number(row['attempt']),
|
|
26
25
|
release: row['release'] ?? null,
|
|
27
26
|
heartbeatAt: row['heartbeat_at'] ?? null,
|
|
@@ -91,8 +90,8 @@ export async function beginExecution(nodeId, input) {
|
|
|
91
90
|
await revokeNodeTokens(db, 'node_id', nodeId, at);
|
|
92
91
|
const executionId = randomUUID();
|
|
93
92
|
const attempt = input.attempt ?? Number((await db.prepare('SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?').get(nodeId)).next);
|
|
94
|
-
await db.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner,
|
|
95
|
-
.run(executionId, nodeId, input.daemonEpoch, at, input.runner ?? 'process',
|
|
93
|
+
await db.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)")
|
|
94
|
+
.run(executionId, nodeId, input.daemonEpoch, at, input.runner ?? 'process', attempt, input.release ?? null, input.launchJson ?? null);
|
|
96
95
|
return executionId;
|
|
97
96
|
});
|
|
98
97
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 30;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -30,7 +30,7 @@ export const machineCheckoutHandlers = {
|
|
|
30
30
|
// ---------------------------------------------------------------------------------------------------------------- the control plane's side
|
|
31
31
|
/** Ask the Mac for the checkout chains of `dirs` and store the answers. A call that fails (offline, lost, refused) stores nothing and returns false. */
|
|
32
32
|
export async function warmMachineCheckouts(environment, dirs) {
|
|
33
|
-
const wanted = [...new Set(dirs.map((d) => resolve(d)))];
|
|
33
|
+
const wanted = [...new Set(dirs.map((d) => resolve(d)))].sort(); // one row order for every writer, so two warms of one Mac cannot deadlock
|
|
34
34
|
if (wanted.length === 0)
|
|
35
35
|
return true;
|
|
36
36
|
let answer;
|
|
@@ -55,5 +55,8 @@ export async function patchEnvironment(environmentId, patch) {
|
|
|
55
55
|
}
|
|
56
56
|
if (patch.memory_mb !== undefined)
|
|
57
57
|
await db.prepare('UPDATE environments SET memory_mb = ? WHERE object = ?').run(patch.memory_mb, environmentId);
|
|
58
|
+
// Not part of the recipe: the credential route reads it per request, so it raises no revision and builds no image.
|
|
59
|
+
if (patch.allow_pull_request_write !== undefined)
|
|
60
|
+
await db.prepare('UPDATE environments SET allow_pull_request_write = ? WHERE object = ?').run(String(patch.allow_pull_request_write), environmentId);
|
|
58
61
|
});
|
|
59
62
|
}
|