@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,3 +1,3 @@
|
|
|
1
|
-
var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ce}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as h,ConversationNotFoundError as U}from"../conversation-store/index.js";import{isAbsolute as ue}from"node:path";import{findNodeBySessionFile as fe,getNode as R,updateNode as $,beginExecution as we,ExecutionAlreadyLive as me,recordExecutionPid as de,abortExecution as F,endLiveExecution as he,unbindSession as G,recordLaunch as pe,setFrozen as ve,clearFrozen as K,fullName as _e}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ye}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ke}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as ge,drainBearings as be,hasRetainedReports as Re,readGoal as E,readYieldMessage as Ee,RUNTIME_RESTART_CONTINUATION as xe}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Se,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as $e}from"./host.js";import{isCloudRole as Fe}from"../canvas/person.js";import{asNodePerson as Ae}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Oe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineLaunchUncertainError as Pe,MachineOfflineError as Be}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as Y}from"./blaxel-environment.js";import{recordLaunchFailure as De}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as q,remoteMachineEnvironmentOf as Me,checkBilledWake as Te,EnvironmentImagePending as Le,imageForWake as ze}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as He,liveExecutionForNode as Ue,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ke}from"../../daemon/drain.js";import{appMemoryFull as We,appMemoryTooSmall as Je,boundFleet as Q,brokerCapReached as Z,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as je}from"./memory-admission.js";import{beginBootFaultAttempt as Ve,clearFault as Xe,hasAdmittedTurn as Ye,readFault as qe}from"../canvas/recovery.js";import{clearNodeLedger as I,forkNodeLedger as Qe,noticeChangedWhileDone as Ze}from"./ledger.js";import{forkSourceNode as Ie,rootOfSpine as er}from"./nodes.js";import{ApiError as rr}from"../../api/errors.js";import{grantSnapshotMissing as ir}from"../../daemon/readiness.js";import{checkGrantActive as tr,checkStart as nr}from"./start-check.js";import{isReviewCompanionBound as ar}from"../review/companion.js";import{assertProfileActive as or}from"../profiles/manifest.js";import{isPidAlive as sr}from"../canvas/pid.js";import{crtrHome as lr,jobDir as cr}from"../canvas/paths.js";import{contextDir as ur,ensureNodeDirs as fr,nodeAgentDir as wr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as mr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as dr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await h().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof U)return{};throw a}}s(hr,"resumeArgs");async function ee(e){const r=_(e);if(r===null)return!1;try{return await h().header(r),!0}catch(i){if(i instanceof U)return!1;throw i}}s(ee,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await h().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function vr(e){const r=_(e);if(r===null)return!0;const i=(await h().header(r)).header.cwd;return typeof i!="string"||H(i)}s(vr,"sessionCwdExists");async function _r(e,r,i,t){const a=r.pi_session_file;if(!a||!await ee(a))return{};const u=await fe(a);return u!==null&&u.node_id!==e&&sr(u.pi_pid)?{}:t&&!await vr(a)?{}:await hr(r,i)}s(_r,"resumableSessionArgs");async function yr(e){return await j(e)===null&&await Ee(e)===null&&!await Re(e)}s(yr,"isUnstartedBirth");async function wi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(wi,"hasFreshGroundState");async function mi(e,r){const i=await re(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function di(e,r,i){return re(e,{...r,viewerAttach:!0},i)}s(di,"decideAttachRevive");async function re(e,r,i){const t=Fe()?await R(e):null;return t===null?await ie(e,r,i):await Ae({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ie(e,r,i))}s(re,"decideRevive");async function ie(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);or(t.profile_id),ce(t.grantee);const a=Q(),u=t.grantee==="app:terminal"&&await ir();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await tr(t),await nr(t),await Y(t.profile_id??null)!==null&&await Te(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new rr(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await te(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ke();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const p=!k&&await a.reserveSlot(e);let o=null;if(p){try{o=await je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw Je(o);if(!p||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?We(o):Z(P().automaticReviveCap,await a.occupancy());return await te(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await br(e,t,r)}}finally{a.releaseReservation(e)}}s(ie,"decideReviveAsCaller");async function te(e,r,i){r.frozen_at==null&&(await ve(e,new Date().toISOString()),await he(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(te,"freezeForWait");async function kr(e,r){const i=await Y(r.profile_id??null),t=await Me(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(kr,"assertRecordedCwdExists");async function gr(e,r,i){const t=mr(r.cwd,r.profile_id).plans.get("node:start")??[];await dr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await wr(e),contextDir:await ur(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:lr(),profile:r.profile_id??null}})}s(gr,"runNodeStartHooks");async function br(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await kr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await ar(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);const p=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(p&&(typeof o!="string"||!ue(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=p&&typeof o=="string";if(w&&!await ee(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ne}=P();if(t!==null){const l=await ze(t);if(l.state==="pending")throw new Le(t,l.error)}const ae=t!==null?X("blaxel"):a?X("machine"):Oe;let f;try{f=await we(e,{daemonEpoch:Q().epoch(),cap:ne,...t!==null?{runner:"blaxel",release:q()}:a?{runner:"machine",release:q()}:{}})}catch(l){if(l instanceof He)throw Z(l.cap,l.live);if(l instanceof me)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await _r(e,r,x,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await yr(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Ye(e)&&!await pr(d.resumeSessionPath)?(await E(e))?.trim():void 0,M=S!==void 0&&S!=="",oe=w||D||M,T=r.cycle_pending===!0||B;await $(e,{cycle_pending:T}),r.cycle_pending=T,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const se=(await h().header(await h().fork(N,e))).path;c=y(r,{resumeSessionPath:se,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await Qe(e,(await Ie(o))?.node_id??null)}else if(M)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:xe}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await I(e)}else{const n=await be(r,f);c=y(r,{...d,prompt:await ge(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await I(e)}c.env={...c.env,CRTR_SUBTREE:await er(e)},m!==null&&(c.env[Ce]=Se(m)),r.status==="done"&&r.last_settled_at!=null&&await Ze(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await qe(e))?.op!=="conversation_write_failed"&&await Xe(e,{preserveEpisode:!0});const L=await Ve(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ye(e),await fr(e,r.grantee),await gr(e,r,oe),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await $e(e,c,r.cwd);await Ge(f,z);let b;try{const n=await Ue(e);if(b=await ae.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Be)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ke(e,"notice.crash",`Child crashed \u2014 ${_e(r)} (${e}) failed to relaunch and is now dead: ${n.message}
|
|
1
|
+
var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as pe,abortExecution as F,endLiveExecution as he,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as xe,readGoal as x,readYieldMessage as Ee,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as mr}from"../command-hooks/transport/exec-lifecycle.js";async function dr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(dr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function hr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(hr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await hr(a)?{}:await dr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await Ee(e)===null&&!await xe(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const h=!k&&await a.reserveSlot(e);let o=null;if(h){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!h||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await a.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await he(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const h=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(h&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=h&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const E=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await vr(e,r,E,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(d.resumeSessionPath)?(await x(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await x(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
|
|
2
2
|
|
|
3
|
-
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await
|
|
3
|
+
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(E=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:E})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,dr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
|
|
@@ -203,16 +203,11 @@ export declare class MachineOfflineError extends Error {
|
|
|
203
203
|
readonly environmentId: string;
|
|
204
204
|
readonly sent: boolean;
|
|
205
205
|
readonly code = "machine_offline";
|
|
206
|
+
readonly status = 503;
|
|
206
207
|
/** True when the call was written to the link before it dropped: the machine may have run it. False: it ran nowhere. */
|
|
207
208
|
constructor(environmentId: string, detail?: string, sent?: boolean);
|
|
208
209
|
}
|
|
209
|
-
/**
|
|
210
|
-
* and never starts another. After the link returns `status` of that execution decides: running is adopted, gone is ended. */
|
|
211
|
-
export declare class MachineLaunchUncertainError extends MachineOfflineError {
|
|
212
|
-
readonly uncertain = true;
|
|
213
|
-
constructor(environmentId: string, detail: string);
|
|
214
|
-
}
|
|
215
|
-
/** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The caller runs `status` before a new `start`. */
|
|
210
|
+
/** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The machine runner reports a lost `start` as offline after send. */
|
|
216
211
|
export declare class MachineLostError extends Error {
|
|
217
212
|
readonly environmentId: string;
|
|
218
213
|
readonly callId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var n=Object.defineProperty;var o=(t,e)=>n(t,"name",{value:e,configurable:!0});const c=["start","wake","stop","status","status.all","delete","viewer","cron.run","cron.cancel","job.stop","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize","repo.identify"];class i extends Error{static{o(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";status=503;constructor(e,r,s=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=s}}class l extends Error{static{o(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{o(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,s){super(`${r} on machine ${e} failed: ${s}`),this.environmentId=e,this.op=r}}export{c as MACHINE_OPS,d as MachineCallFailedError,l as MachineLostError,i as MachineOfflineError};
|
|
@@ -4,8 +4,6 @@ export interface MachineRunnerDeps {
|
|
|
4
4
|
environmentOf?(nodeId: string): Promise<string>;
|
|
5
5
|
/** Mints the execution's node token (the execution must be `launching` and have none). Default: `mintNodeToken`. */
|
|
6
6
|
mintToken?(input: RunnerStartInput): Promise<string>;
|
|
7
|
-
/** Whether this execution already has a node token (a previous `start` minted it). Default: a `node_tokens` row for the execution. */
|
|
8
|
-
tokenMinted?(executionId: string): Promise<boolean>;
|
|
9
7
|
}
|
|
10
8
|
/** The machine environment of a node's profile, or null when the profile points at no machine environment. */
|
|
11
9
|
export declare function machineEnvironmentOfNode(nodeId: string): Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var i=(e,n)=>d(e,"name",{value:n,configurable:!0});import{openDb as m}from"../../../canvas/db.js";import{mintExecutionToken as f}from"../../../canvas/node-tokens.js";import{callMachine as c}from"./call.js";import{machineEnvironmentOfProfile as w}from"./environment.js";import{MachineLostError as l,MachineOfflineError as u}from"./ops.js";async function h(e){const n=await(await m()).prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);return n?.profile_id==null?null:await w(n.profile_id)}i(h,"machineEnvironmentOfNode");const E=i(async e=>{const n=await h(e);if(n===null)throw new Error(`node ${e} has no machine environment`);return n},"defaultEnvironmentOf"),s=i(e=>e instanceof Error?e:new Error(String(e)),"asError");function M(e={}){const n=e.environmentOf??E;return{kind:"machine",async start(r){const a=await n(r.nodeId),t=await(e.mintToken??(o=>f(o.executionId,o.nodeId)))(r);try{return{pid:(await c(a,"start",{...r,nodeToken:t})).pid,exited:null}}catch(o){throw o instanceof l?new u(a,o.message,!0):o}},async wake(r){return await c(await n(r.nodeId),"wake",{execution:r})},async stop(r,a){try{const t=await c(await n(r.nodeId),"stop",{execution:r,options:a});return t.error===void 0?{confirmed:t.confirmed}:{confirmed:t.confirmed,error:new Error(t.error)}}catch(t){return{confirmed:!1,error:s(t)}}},async status(r){try{return await c(await n(r.nodeId),"status",{execution:r})}catch(a){return{state:"unknown",error:s(a).message}}},async delete(r){await c(await n(r),"delete",{nodeId:r})},async viewerAddress(r){return{kind:"machine",environmentId:await n(r.nodeId),nodeId:r.nodeId}}}}i(M,"createMachineRunner");export{M as createMachineRunner,h as machineEnvironmentOfNode};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Q=Object.defineProperty;var u=(e,n)=>Q(e,"name",{value:n,configurable:!0});import{mkdtempSync as Y,rmSync as Z,writeFileSync as V}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ee,encodeAttachControlInput as ne,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as q}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as x}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"direct",run:"surface reload --pane {pane}"}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(x).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function G(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${x(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${x(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${x(`${r} >/dev/null 2>&1`)}`}}u(G,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${x(t)}`}}u(de,"directCommand");function j(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${x(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${x(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${x(n)}`}}case"command":return G(e.run);case"direct":return de(e.run);case"popup":return G(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(j,"menuActionCommand");function me(e){return j(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function z(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(z,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=z(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=z(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function F(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const h=_.find(w=>w.id===l);if(h===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:h.name.toLowerCase(),action:{kind:"literal-input",input:ne(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(F,"resolvedMenuActions");function K(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(K,"menuItems");function Pe(e){const n=e??q().bindings;return N(" crtr ",K(n,F(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
1
|
+
var Y=Object.defineProperty;var u=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{mkdtempSync as Z,rmSync as V,writeFileSync as ee}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ne,encodeAttachControlInput as q,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as G}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as h}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"literal-input",input:q("crtr.attach.reload-viewer")}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(h).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function j(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${h(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${h(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${h(`${r} >/dev/null 2>&1`)}`}}u(j,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${h(t)}`}}u(de,"directCommand");function z(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${h(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${h(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${h(n)}`}}case"command":return j(e.run);case"direct":return de(e.run);case"popup":return j(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(z,"menuActionCommand");function me(e){return z(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function F(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(F,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=F(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=F(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function K(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:q(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(K,"resolvedMenuActions");function R(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(R,"menuItems");function Pe(e){const n=e??G().bindings;return N(" crtr ",R(n,K(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
2
2
|
`).find(r=>{const s=B(r);return s?.table===e&&s.key===n})??null:null}u($,"bindingAt");function Le(e){const n=f(["list-keys","-T",p]);if(!n.ok)return[];const t=new Set(n.stdout.split(`
|
|
3
|
-
`).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function
|
|
4
|
-
`,"utf8"),f(["source-file",t])}finally{
|
|
3
|
+
`).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function W(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(W,"isInstalledPair");function ke(e){if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.bindingId=="string"&&ne.has(n.bindingId)&&typeof n.gesture=="string"&&typeof n.key=="string"&&(typeof n.original=="string"||n.original===null)&&typeof n.wrapper=="string"&&(n.state==="owned"||n.state==="relinquished")}u(ke,"isWrappedRootBinding");function he(){const e=f(["show-options","-s","-q",A]);if(!e.ok)return null;if(e.stdout==="")return{pairs:[],wrappers:[]};const n=f(["show-options","-s","-qv",A]);if(!n.ok)return null;try{const t=JSON.parse(n.stdout);if(Array.isArray(t))return t.every(W)?{pairs:t,wrappers:[]}:null;if(typeof t!="object"||t===null)return null;const r=t;return!Array.isArray(r.pairs)||!r.pairs.every(W)||!Array.isArray(r.wrappers)||!r.wrappers.every(ke)?null:{pairs:r.pairs,wrappers:r.wrappers}}catch{return null}}u(he,"readManifest");function X(e){return f(["set-option","-s",A,JSON.stringify(e)])}u(X,"writeManifest");function C(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;")}u(C,"tmuxKeyArgument");function xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/;/g,"\\;")}"`}u(xe,"tmuxCommandToken");function ye(e){let n=null,t="";for(let r=0;r<e.length;r+=1){const s=e[r];if(n===null&&(s==="'"||s==='"')){n=s,t+=s;continue}if(n===s){n=null,t+=s;continue}if(s==="\\"&&r+1<e.length){const o=e[r+1];n===null&&o===";"?t+=";":t+=s+o,r+=1;continue}t+=s}return t}u(ye,"bindingCommandForBranch");function be(e){const n=Z(M(O(),"crtr-tmux-binding-")),t=M(n,"binding.conf");try{return ee(t,`${e}
|
|
4
|
+
`,"utf8"),f(["source-file",t])}finally{V(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function H(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(H,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?G():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=he();if(l===null)return o.push({code:"tmux-error",message:`tmux is unavailable or ${A} is malformed`}),{ok:!1,installed:c,diagnostics:o};const x=new Map;for(const i of s){const a=_.find(d=>d.id===i);if(!(a===void 0||!re(a))){for(const d of r.gestures(i))if(!d.includes(" > "))for(const m of v(d))x.has(m)||x.set(m,{bindingId:i,gesture:d})}}const w=new Set,I=[];for(const i of l.wrappers){const a=x.get(i.key),d=$(p,i.key);if(d!==null&&d===i.original)continue;if(i.state==="relinquished"||d!==i.wrapper){w.add(i.key),a!==void 0&&I.push({...i,...a,state:"relinquished"});continue}const m=H(i);m.ok||(w.add(i.key),I.push(i),o.push({code:"tmux-error",bindingId:i.bindingId,gesture:i.gesture,message:`could not restore tmux binding ${p}:${i.key}: ${m.stderr}`}))}for(const i of l.pairs){if(i.table===p&&w.has(i.key))continue;const a=f(["unbind-key","-T",i.table,C(i.key)]);!a.ok&&$(i.table,i.key)!==null&&o.push({code:"tmux-error",message:`could not remove crouter binding ${i.table}:${i.key}: ${a.stderr}`})}if(o.some(i=>i.code==="tmux-error")){const i=X({pairs:l.pairs,wrappers:I});return i.ok||o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${i.stderr}`}),{ok:!1,installed:c,diagnostics:o}}const E=u((i,a,d,m,k)=>{if($(i,a)!==null)return o.push({code:"occupied",bindingId:m,gesture:k,message:`${i}:${a} is already bound by tmux; ${m} was not installed`}),!1;const g=f(["bind-key","-T",i,C(a),...d]);return g.ok?(c.push({table:i,key:a}),!0):(o.push({code:"tmux-error",bindingId:m,gesture:k,message:`could not install ${m}: ${g.stderr}`}),!1)},"install"),P=K(r),J=N(" crtr ",R(r,P));for(const i of r.gestures("crtr.tmux.menu.open"))for(const a of v(i))E(p,a,J,"crtr.tmux.menu.open",i);for(const i of _){if(i.pair?.field!=="menu")continue;const a=_.find(y=>y.id===i.pair?.pairedId);if(a?.pair?.field!=="global")continue;const d=i.id,m=a.id,k=P.get(d),g=k===void 0?null:z(k.action);if(g===null)throw new Error(`no direct tmux action for paired menu binding ${d}`);for(const y of r.gestures(m))for(const Q of v(y))E(p,Q,g.argv,m,y)}for(const i of["crtr.tmux.node.next","crtr.tmux.node.previous","crtr.tmux.inbox.toggle"])for(const a of r.gestures(i))for(const d of v(a))E(p,d,ve(i),i,a);const L=[];for(const[i,a]of x){if(w.has(i))continue;const d=$(p,i);if(d===null)continue;const m=B(d);if(m===null||m.command===""){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not parse occupied tmux binding ${p}:${i}`});continue}const k=f(["bind-key",...m.repeat?["-r"]:[],"-T",p,C(i),"if-shell","-F","#{!=:#{@crtr_attach},}",`send-keys ${xe(i)}`,ye(m.command)]);if(!k.ok){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not wrap ${p}:${i}: ${k.stderr}`});continue}const g=$(p,i);if(g===null||!g.includes("@crtr_attach")){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not fingerprint wrapped tmux binding ${p}:${i}`});continue}const y={...a,key:i,original:d,wrapper:g,state:"owned"};I.push(y),L.push(y)}const D=X({pairs:c,wrappers:I});if(!D.ok){o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${D.stderr}`});for(const i of L)$(p,i.key)===i.wrapper&&H(i)}return{ok:o.every(i=>i.code!=="tmux-error"),installed:c,diagnostics:o}}u(Ie,"reconcileTmuxBindings");export{Pe as crouterMenuTmuxArgs,we as inboxToggleTmuxCommand,De as installTmuxBindings,Le as occupiedTmuxRootGestures};
|
|
@@ -274,16 +274,6 @@ export declare function paneStartCommand(pane: string): string | undefined;
|
|
|
274
274
|
export declare function swapPanes(source: string, target: string): string | null;
|
|
275
275
|
/** The foreground command name of a pane (`#{pane_current_command}`). */
|
|
276
276
|
export declare function paneCurrentCommand(pane: string): string | undefined;
|
|
277
|
-
/** The pane's root process pid (`#{pane_pid}`) — the process tmux launched in
|
|
278
|
-
* the pane (the viewer itself, or the login shell hosting it). undefined when
|
|
279
|
-
* tmux is unreachable or the pane is gone. */
|
|
280
|
-
export declare function panePid(pane: string): number | undefined;
|
|
281
|
-
/** Kill a pane's current process and re-run the SAME command line it was
|
|
282
|
-
* started with (`respawn-pane -k` with no command reuses the pane's original
|
|
283
|
-
* command). Used to hot-reload a viewer pane in place: the fresh process
|
|
284
|
-
* re-resolves `crtr` and picks up the currently selected runtime generation,
|
|
285
|
-
* while the pane id, geometry, and the node's broker are untouched. */
|
|
286
|
-
export declare function respawnPaneInPlace(pane: string): boolean;
|
|
287
277
|
/** Turn a pi argv array into a single shell command string.
|
|
288
278
|
*
|
|
289
279
|
* The binary defaults to `CRTR_PI_BINARY` when that env var is set, else the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var T=Object.defineProperty;var r=(n
|
|
2
|
-
`)){const
|
|
3
|
-
`).filter(
|
|
4
|
-
`).filter(
|
|
5
|
-
`)){const[i,a,c,
|
|
6
|
-
`).filter(e=>e!=="")}r(D,"listWindowIds");function
|
|
1
|
+
var T=Object.defineProperty;var r=(t,n)=>T(t,"name",{value:n,configurable:!0});import{execFile as f,spawnSync as d}from"node:child_process";import{encodeAttachControlInput as M}from"../keybindings/index.js";import{listProcessTable as C}from"../canvas/pid.js";import{bundledPiCommandForShell as $}from"./pi-cli.js";import{shellQuote as m}from"../../shared/shell-quote.js";import{envPiBinaryOverride as L}from"../../shared/env.js";const p=5e3;function s(t){const n=d("tmux",t,{encoding:"utf8",timeout:p,killSignal:"SIGKILL"});return{timedOut:n.error?.code==="ETIMEDOUT",ok:n.status===0,stdout:(n.stdout??"").trim(),stderr:(n.stderr??"").trim()}}r(s,"tmux");function l(t,n){return s(t===void 0||t===""?n:["-S",t,...n])}r(l,"tmuxOnSocket");function F(){return process.env.TMUX!==void 0&&process.env.TMUX!==""}r(F,"inTmux");function nt(){return d("tmux",["list-sessions"],{encoding:"utf8",stdio:"ignore",timeout:p,killSignal:"SIGKILL"}).status===0}r(nt,"tmuxSessionsReachable");function et(){return d("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:p,killSignal:"SIGKILL"}).status===0}r(et,"tmuxClientsReachable");function rt(t){if(t==="")return null;const n=s(["list-panes","-a","-F","#{pane_id} #{@crtr_node}"]);if(!n.ok)return null;for(const e of n.stdout.split(`
|
|
2
|
+
`)){const o=e.indexOf(" ");if(!(o<0)&&e.slice(o+1)===t){const u=e.slice(0,o);if(u!=="")return u}}return null}r(rt,"paneOfNode");function N(){if(!F())return null;const t=s(["display-message","-p","#{session_name} #{window_id} #{pane_id}"]);if(!t.ok)return null;const[n,e,o]=t.stdout.split(" ");return{session:n,window:e,pane:o}}r(N,"currentTmux");function ot(){const t=d("tmux",["-V"],{stdio:"ignore",timeout:p,killSignal:"SIGKILL"});return t.error===void 0&&t.status===0}r(ot,"tmuxAvailable");function st(t){return d("tmux",t,{stdio:"inherit"}).status??1}r(st,"tmuxInteractive");function A(t){return s(["has-session","-t",t]).ok}r(A,"sessionExists");function R(){const t=s(["show-options","-s","terminal-overrides"]).stdout;/Enbp=\\+E/.test(t)||s(["set-option","-sga","terminal-overrides","*:Enbp=\\E[?2004h:Dsbp=\\E[?2004l"])}r(R,"ensureBracketedPaste");function V(){R(),s(["set-option","-s","focus-events","on"])}r(V,"ensureServerOptions");function it(t,n){A(t)||s(["new-session","-d","-s",t,"-c",n]),V()}r(it,"ensureSession");function g(t){const n=[];for(const[e,o]of Object.entries(t))n.push("-e",`${e}=${o}`);return n}r(g,"envFlags");function ut(t){const n=s(["new-window","-d","-a","-P","-F","#{window_id} #{pane_id}","-t",`${t.session}:`,"-n",t.name,"-c",t.cwd,...g(t.env),t.command]);if(!n.ok)return null;const[e,o]=n.stdout.split(" ");return e===void 0||e===""||o===void 0||o===""?null:{window:e,pane:o}}r(ut,"openNodeWindow");function at(t,n){const e=s(["split-window","-d",...n.vertical===!0?[]:["-h"],...n.before===!0?["-b"]:[],...n.size!==void 0?["-l",String(n.size)]:[],"-P","-F","#{pane_id}","-t",t,"-c",n.cwd,...g(n.env),n.command]);return e.ok&&e.stdout!==""?e.stdout:null}r(at,"splitWindow");function ct(t,n){return!(N()?.session===t)&&!s(["switch-client","-t",t]).ok?!1:s(["select-window","-t",n]).ok}r(ct,"focusWindow");function dt(t){return s(["kill-window","-t",t]).ok}r(dt,"closeWindow");function pt(t,n){return s(["rename-window","-t",t,n]).ok}r(pt,"renameWindow");function lt(t){const n=s(["break-pane","-d","-P","-F","#{window_id} #{pane_id}","-s",t]);if(!n.ok)return null;const[e,o]=n.stdout.split(" ");return e===void 0||e===""||o===void 0||o===""?null:{window:e,pane:o}}r(lt,"breakPane");function ft(t){return s(["kill-pane","-t",t]).ok}r(ft,"closePane");function mt(t,n,e){return s(h(t,n,e)).ok}r(mt,"displayPopup");function wt(t,n,e){return new Promise(o=>{try{f("tmux",h(t,n,e),i=>o(i===null)).stdin?.end()}catch{o(!1)}})}r(wt,"displayPopupAsync");function h(t,n,e){return["display-popup","-E","-t",t,"-d",n,"-w","90%","-h","90%",e]}r(h,"displayPopupArgs");function xt(t,n){const e=s(["display-message","-p","-t",`${t}:${n}`,"#{pane_id}"]);return e.ok&&e.stdout!==""?e.stdout:null}r(xt,"paneOfWindow");function gt(t){const n=s(["display-message","-p","-t",t,"#{window_id}"]);return n.ok&&n.stdout!==""?n.stdout:null}r(gt,"windowOfPane");function kt(t){const n=s(["display-message","-p","-t",t,"#{session_name} #{window_id}"]);if(!n.ok)return null;const e=/^(.*) (@\d+)$/.exec(n.stdout);return e===null||e[1]===""?null:{session:e[1],window:e[2]}}r(kt,"paneLocation");function _t(t){const n=s(["display-message","-p","-t",t,"#{window_index}"]);return!n.ok||!/^\d+$/.test(n.stdout)?null:Number.parseInt(n.stdout,10)}r(_t,"windowIndex");function ht(t){return W(t)==="live"}r(ht,"paneExists");function y(t,n){return n.timedOut?"unknown":n.ok&&n.stdout===t?"live":"gone"}r(y,"paneStateFrom");function W(t){return y(t,s(["display-message","-p","-t",t,"#{pane_id}"]))}r(W,"paneState");async function yt(t,n=p){return await new Promise(e=>{try{f("tmux",["display-message","-p","-t",t,"#{pane_id}"],{encoding:"utf8",timeout:n,killSignal:"SIGKILL"},(o,u)=>{const i=o!==null&&o.killed===!0;e(y(t,{ok:o===null,stdout:String(u).trim(),timedOut:i}))})}catch{e("gone")}})}r(yt,"paneStateAsync");function St(t){const n=s(["display-message","-p","-t",t,"#{pane_id} #{pane_dead}"]);return n.ok&&n.stdout===`${t} 0`}r(St,"paneRunning");function Pt(){const t=s(["list-panes","-a","-F","#{pane_id}"]);return t.ok?new Set(t.stdout.split(`
|
|
3
|
+
`).filter(n=>n!=="")):null}r(Pt,"listLivePanes");const B=2e3;async function It(){const t=await new Promise(n=>{try{f("tmux",["list-panes","-a","-F","#{pane_id}"],{encoding:"utf8",timeout:B,maxBuffer:4194304},(e,o)=>n(e?null:o))}catch{n(null)}});return t===null?null:new Set(t.trim().split(`
|
|
4
|
+
`).filter(n=>n!==""))}r(It,"listLivePanesAsync");function vt(t){const n=s(["display-message","-p","-t",t,"#{pane_current_path}"]);return n.ok&&n.stdout!==""?n.stdout:null}r(vt,"paneCurrentPath");function bt(t){const n=s(["display-message","-p","-t",t,"#{pane_width} #{pane_height}"]);if(!n.ok)return null;const[e,o]=n.stdout.split(" "),u=Number.parseInt(e,10),i=Number.parseInt(o,10);return Number.isInteger(u)&&u>0&&Number.isInteger(i)&&i>0?{cols:u,rows:i}:null}r(bt,"paneSize");function Ot(t,n,e=4e3){const o=r(u=>{const i=["display-message",...u?["-C"]:[],"-d",String(e)];return n!==void 0&&n!==""&&i.push("-t",n),i.push(t),i},"args");return s(o(!0)).ok||s(o(!1)).ok}r(Ot,"displayMessage");function Et(t,n,e){return s(["set-option","-p","-t",t,n,e]).ok}r(Et,"setPaneOption");function Tt(t,n){const e=s(["show-options","-p","-t",t,"-q","-v",n]);return e.ok?e.stdout:void 0}r(Tt,"getPaneOption");const K="@crtr_viewer_at";let S=0,P=Promise.resolve();function Mt(t){if(t==="")return;const n=Math.max(Date.now(),S+1);S=n,P=P.then(()=>new Promise(e=>{try{f("tmux",["set-option","-p","-t",t,K,String(n)],()=>e())}catch{e()}}))}r(Mt,"stampViewerPaneAsync");function U(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}r(U,"escapeRegex");function k(t,n){const e=t.replace(/^"|"$/g,"");return new RegExp(`(?:^|\\s)surface\\s+attach\\s+to\\s+${U(n)}(?:\\s|$)`).test(e)}r(k,"looksLikeViewerCommand");function G(){const t=C();if(t===null)return null;const n=new Map,e=new Map;for(const{pid:o,ppid:u,command:i}of t){e.set(o,i);const a=n.get(u)??[];a.push(o),n.set(u,a)}return{childrenOf:n,commandOf:e}}r(G,"readProcessTree");function j(t,n,e){const o=[n];for(;o.length>0;){const u=o.pop();if(k(t.commandOf.get(u)??"",e))return!0;const i=t.childrenOf.get(u);i!==void 0&&o.push(...i)}return!1}r(j,"processTreeHasViewer");function Ct(t){const n=l(t,["list-panes","-a","-F","#{pane_id} #{session_name} #{@crtr_node} #{@crtr_viewer_at}"]);if(!n.ok||n.stdout==="")return[];const e=[];let o;for(const u of n.stdout.split(`
|
|
5
|
+
`)){const[i,a,c,v]=u.split(" ");if(i===void 0||i===""||a===void 0||a===""||c===void 0||c==="")continue;const _=l(t,["display-message","-p","-t",i,"#{pane_current_command} #{pane_start_command} #{pane_pid}"]);if(!_.ok)continue;const[b="",O="",E]=_.stdout.split(" ");if(!(k(b,c)||k(O,c))){o??=G();const x=Number.parseInt(E,10);if(o===null||!Number.isInteger(x)||x<=0||!j(o,x,c))continue}const w=Number.parseInt(v??"",10);e.push({pane:i,session:a,nodeId:c,stampMs:Number.isSafeInteger(w)&&w>=0?w:0})}return e}r(Ct,"liveViewerPanes");function $t(t,n,e){return l(t,["send-keys","-l","-t",n,M(e)]).ok}r($t,"sendAttachControl");function Lt(t,n,e){const o=r(u=>{const i=["display-message",...u?["-C"]:[]];return n!==void 0&&n!==""&&i.push("-c",n),i.push(e),i},"args");return l(t,o(!0)).ok||l(t,o(!1)).ok}r(Lt,"displayClientMessage");function I(t){return["respawn-pane","-k","-c",t.cwd,...g(t.env),"-t",t.pane,t.command]}r(I,"respawnPaneArgs");function Ft(t){return s(I(t)).ok}r(Ft,"respawnPaneSync");function Nt(t){return z(`tmux ${I(t).map(m).join(" ")} >/dev/null 2>&1`)}r(Nt,"respawnPaneInBackground");function z(t){return s(["run-shell","-b",t]).ok}r(z,"runShellInBackground");function At(t){const n=s(["display-message","-p","-t",t,"#{pane_start_command}"]);return n.ok?n.stdout:void 0}r(At,"paneStartCommand");function Rt(t,n){const e=s(["swap-pane","-s",t,"-t",n]);return e.ok?null:e.stderr===""?"tmux swap-pane failed":e.stderr}r(Rt,"swapPanes");function Vt(t){const n=s(["display-message","-p","-t",t,"#{pane_current_command}"]);return n.ok&&n.stdout!==""?n.stdout:void 0}r(Vt,"paneCurrentCommand");function Wt(t,n=L()??$(m)){return[n,...t.map(m)].join(" ")}r(Wt,"piCommand");function D(t){const n=s(["list-windows","-t",t,"-F","#{window_id}"]);return!n.ok||n.stdout===""?[]:n.stdout.split(`
|
|
6
|
+
`).filter(e=>e!=="")}r(D,"listWindowIds");function Bt(t,n){return t==null||n==null?!1:D(t).includes(n)}r(Bt,"windowAlive");function Kt(t,n){return s(["select-window","-t",`${t}:${n}`]).ok}r(Kt,"selectWindow");function Ut(t,n){return s(["select-layout","-t",t,n]).ok}r(Ut,"selectLayout");function Gt(t){return s(["select-pane","-t",t]).ok}r(Gt,"selectPane");function jt(t){return s(["switch-client","-t",t]).ok}r(jt,"switchClient");function zt(t,n){return s(["send-keys","-t",t,n,"Enter"]).ok}r(zt,"sendKeysEnter");export{K as VIEWER_STAMP_OPTION,lt as breakPane,ft as closePane,dt as closeWindow,N as currentTmux,Lt as displayClientMessage,Ot as displayMessage,mt as displayPopup,wt as displayPopupAsync,it as ensureSession,ct as focusWindow,Tt as getPaneOption,F as inTmux,Pt as listLivePanes,It as listLivePanesAsync,D as listWindowIds,Ct as liveViewerPanes,ut as openNodeWindow,Vt as paneCurrentCommand,vt as paneCurrentPath,ht as paneExists,kt as paneLocation,rt as paneOfNode,xt as paneOfWindow,St as paneRunning,bt as paneSize,At as paneStartCommand,W as paneState,yt as paneStateAsync,Wt as piCommand,pt as renameWindow,Nt as respawnPaneInBackground,Ft as respawnPaneSync,z as runShellInBackground,s as runTmux,Ut as selectLayout,Gt as selectPane,Kt as selectWindow,$t as sendAttachControl,zt as sendKeysEnter,A as sessionExists,Et as setPaneOption,m as shellQuote,at as splitWindow,Mt as stampViewerPaneAsync,Rt as swapPanes,jt as switchClient,ot as tmuxAvailable,et as tmuxClientsReachable,st as tmuxInteractive,nt as tmuxSessionsReachable,Bt as windowAlive,_t as windowIndex,gt as windowOfPane};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { importedIntoNorthlight } from '../../shared/env.js';
|
|
2
|
+
import type { PersonSnapshot, SettingsOp } from './person-store.js';
|
|
3
|
+
export declare const TERMINAL_APP = "app:terminal";
|
|
4
|
+
export { importedIntoNorthlight };
|
|
5
|
+
/** The user settings with the terminal app's install block in place of their `plugins` and `marketplaces` keys. */
|
|
6
|
+
export declare function withAppInstalls(snapshot: PersonSnapshot, raw: Record<string, unknown> | null): Record<string, unknown> | null;
|
|
7
|
+
/** Split a user-settings write into the settings op (without install keys) and, when the installs changed, the app-block op. */
|
|
8
|
+
export declare function splitUserSettingsWrite(snapshot: PersonSnapshot, next: Record<string, unknown>, ifRevision: string): SettingsOp[];
|
|
9
|
+
/** Once per imported Mac: the import moved no installs into the terminal app's block, while the legacy `runtime/scope/config.json` and the
|
|
10
|
+
* plugin directories still name them. Copy every missing marketplace and plugin row into the block; rows already there win. A provider
|
|
11
|
+
* bundle (`provider` in its manifest) is the runtime's, refreshed on grant sync, and is not an install. A marker file ends the migration. */
|
|
12
|
+
export declare function migrateLegacyInstallsOnce(): Promise<void>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var I=Object.defineProperty;var p=(o,i)=>I(o,"name",{value:i,configurable:!0});import{importedIntoNorthlight as x}from"../../shared/env.js";import{appRevisionOf as l}from"./person-store.js";const g="app:terminal";function _(o,i){const c=o.apps[g];return c===void 0&&i===null?null:{...i??{},plugins:structuredClone(c?.plugins??{}),marketplaces:structuredClone(c?.marketplaces??{})}}p(_,"withAppInstalls");function j(o,i,c){const{plugins:w,marketplaces:b,...s}=i,n=o.apps[g],u=[{op:"settings.replace",owner:"user",raw:s,ifRevision:c}],d={plugins:Object.fromEntries(Object.entries(w??{}).filter(([,y])=>y.source_marketplace!==void 0)),marketplaces:b??{}},k={plugins:n?.plugins??{},marketplaces:n?.marketplaces??{}};return l(d)!==l(k)&&u.push({op:"app-plugins.replace",app:g,...d,ifRevision:l(n)}),u}p(j,"splitUserSettingsWrite");const h={name:"crouter-official-marketplace",url:"https://github.com/crouton-labs/crouter-official-marketplace.git"};async function C(){if(!x())return;const{existsSync:o,readFileSync:i,readdirSync:c,writeFileSync:w,mkdirSync:b}=await import("node:fs"),{join:s}=await import("node:path"),{runtimeRoot:n}=await import("../layout.js"),u=s(n(),"import","app-installs-migrated");if(o(u))return;const{writeSettings:S}=await import("./person-store.js"),{readPluginManifest:d}=await import("../manifest.js"),k=p(a=>a.code==="ENOENT","missing"),y=(()=>{try{return JSON.parse(i(s(n(),"scope","config.json"),"utf8"))}catch(a){if(k(a))return{};throw a}})(),O=p(a=>{try{return c(a,{withFileTypes:!0}).filter(e=>!e.name.startsWith(".")&&(e.isDirectory()||e.isSymbolicLink())).map(e=>e.name)}catch(e){if(k(e))return[];throw e}},"onDisk"),v=s(n(),"plugins");await S(a=>{const e=a.apps[g],r=structuredClone({plugins:e?.plugins??{},marketplaces:e?.marketplaces??{}});for(const[t,m]of Object.entries(y.marketplaces??{}))r.marketplaces[t]===void 0&&(r.marketplaces[t]=t===h.name?{...m,url:h.url}:m);for(const t of O(s(n(),"marketplaces")))r.marketplaces[t]===void 0&&t===h.name&&(r.marketplaces[t]={url:h.url,ref:"main"});for(const t of O(v)){if(r.plugins[t]!==void 0)continue;const m=d(s(v,t));if(m===null||m.provider!==void 0)continue;const f=y.plugins?.[t];f?.source_marketplace!==void 0&&(r.plugins[t]={enabled:f.enabled??!0,source_marketplace:f.source_marketplace,...f.version===void 0?{}:{version:f.version}})}return l(r)===l(e)?[]:[{op:"app-plugins.replace",app:g,plugins:r.plugins,marketplaces:r.marketplaces,ifRevision:l(e)}]}),b(s(n(),"import"),{recursive:!0}),w(u,`${new Date().toISOString()}
|
|
2
|
+
`)}p(C,"migrateLegacyInstallsOnce");export{g as TERMINAL_APP,x as importedIntoNorthlight,C as migrateLegacyInstallsOnce,j as splitUserSettingsWrite,_ as withAppInstalls};
|
package/dist/core/spaces/stop.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var D=Object.defineProperty;var c=(t,r)=>D(t,"name",{value:r,configurable:!0});import{randomUUID as x}from"node:crypto";import{readJobSupervisorState as J,signalBashJob as k,unfinishedBashJobIds as O}from"../bash-jobs.js";import{contextDir as M}from"../canvas/node-agent-paths.js";import{getNode as P}from"../canvas/index.js";import{withCanvasWrite as R,openDb as h}from"../canvas/db.js";import{finishJob as $,ownerRunsRemotely as A,runningJobs as N,startJob as W}from"../graph/jobs.js";import{getById as S,nodeObject as C}from"../graph/objects.js";import{readLiveSession as H}from"../canvas/sessions.js";import{conversationStore as L}from"../conversation-store/index.js";import{requestBrokerTeardown as _}from"../runtime/host.js";import{holdRecovery as q,waitForRecoveryHold as F}from"../runtime/recovery-hold.js";async function T(t,r,e){return await R(async n=>{const a=await S(n,t);return a===null||a.type!=="job"?!1:(await $(n,a,{killedBy:await r(n),...e===void 0?{}:{reason:e}}),!0)})}c(T,"killBashJobObject");async function nt(t,r,e){return await R(async n=>{const a=await S(n,r);if(a!==null){if(a.type!=="job")throw new Error(`${r} names a ${a.type}`);return a}return await W(n,await C(n,t),{id:r,...e})})}c(nt,"recordBashJobObject");const y=new Map;async function U(t,r,e){return await F(t)==="lapsed"?await Y(t,r,e):await _(t,{excludePid:e.excludePid})}c(U,"stopHeldElsewhere");async function Y(t,r,e={}){const n=y.get(t);if(n)return n;const a=await P(t);if(!a)return Promise.resolve({confirmed:!1,error:new Error(`missing node ${t}`)});const g=(await H(t))?.sessionId,b=c(async()=>await(await h()).prepare(`SELECT type, body_json FROM run_events WHERE node_id = ?
|
|
2
|
-
AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1`).get(t),"latestTurn"),j=a.run_id!==null&&a.pi_pid!==null&&(await b())?.type==="node.turn.started",u=await q(t);if(u===null)return await U(t,r,e);const B=_(t,{excludePid:e.excludePid,...e.startAfter?{startAfter:e.startAfter}:{}}),
|
|
2
|
+
AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1`).get(t),"latestTurn"),j=a.run_id!==null&&a.pi_pid!==null&&(await b())?.type==="node.turn.started",u=await q(t);if(u===null)return await U(t,r,e);const B=_(t,{excludePid:e.excludePid,...e.startAfter?{startAfter:e.startAfter}:{}}),p=(async()=>{const w=await B;if(!w.confirmed)return w;try{const o=c(()=>({confirmed:!1,error:new Error(`the recovery hold on ${t} lapsed during its stop`)}),"lost");if(!await u.renew())return o();const l=new Map((await N(await h(),t)).map(s=>[s.jobId,s]));if(await A(await h(),t)){if(!e.deleting)for(const s of l.keys())await T(s,async()=>null,r)}else{const s=await M(t);for(const i of new Set([...l.keys(),...O(s)])){const d=J(s,i),m=d.pgid??l.get(i)?.pgid??null,f=d.pgidIdentity??l.get(i)?.pgidIdentity??null;if(m===null||f===null)throw new Error(`bash job ${i} could not be stopped`);await k(m,f,t),!e.deleting&&l.has(i)&&await T(i,async()=>null,r)}}if(!await u.renew())return o();if(j&&g&&!e.deleting){if((await b())?.type!=="node.turn.started")return await u.renew()?(await e.after?.(),w):o();const i=L(),{entries:d}=await i.read(g),m=d.at(-1),f=new Date().toISOString(),E=r==="permission_revoked",v={type:"message",id:x(),parentId:m?.id??null,timestamp:f,message:{role:"assistant",content:[],api:"openai-completions",provider:"crouter",model:"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:E?"error":"aborted",errorMessage:r,timestamp:Date.now()}};await i.append(g,[v,{type:"custom",id:x(),parentId:v.id,timestamp:f,customType:"crtr-turn-end",data:E?{stop_reason:"error",error:{code:"model_error",message:r}}:{stop_reason:"aborted"}}])}return await u.renew()?(await e.after?.(),w):o()}catch(o){return{confirmed:!1,error:o instanceof Error?o:new Error(String(o))}}})().finally(()=>u.release().catch(()=>{}));return y.set(t,p),p.finally(()=>{y.get(t)===p&&y.delete(t)}),p}c(Y,"stopNodeSandboxes");export{T as killBashJobObject,nt as recordBashJobObject,Y as stopNodeSandboxes};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Run `fn`, collecting the steps recorded beneath it. */
|
|
2
|
-
export declare function collectStepTimings<T>(fn: () => Promise<T>): Promise<{
|
|
2
|
+
export declare function collectStepTimings<T>(fn: () => Promise<T>, steps?: Array<[string, number]>): Promise<{
|
|
3
3
|
value: T;
|
|
4
4
|
steps: Array<[string, number]>;
|
|
5
5
|
}>;
|
|
@@ -15,3 +15,9 @@ export declare function sinceCollectionStart(): number;
|
|
|
15
15
|
export declare function timedStep<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
16
16
|
/** The `Server-Timing` header value for these steps: `name;dur=<ms>` joined by commas. */
|
|
17
17
|
export declare function serverTimingHeader(steps: ReadonlyArray<readonly [string, number]>): string;
|
|
18
|
+
export declare function markReceived(req: object): void;
|
|
19
|
+
export declare function markAuthenticated(req: object): void;
|
|
20
|
+
export declare function receiptOf(req: object): {
|
|
21
|
+
receivedAt: number;
|
|
22
|
+
authenticatedAt?: number;
|
|
23
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});import{AsyncLocalStorage as c}from"node:async_hooks";import{monitorEventLoopDelay as p}from"node:perf_hooks";const r=new c;async function m(e,t=[]){const n=p({resolution:5});n.enable();try{return{value:await r.run({steps:t,start:performance.now()},e),steps:t}}finally{n.disable(),n.count>0&&t.push(["event_loop_delay_max",n.max/1e6],["event_loop_delay_p99",n.percentile(99)/1e6])}}o(m,"collectStepTimings");function w(){return r.getStore()!==void 0}o(w,"isCollectingStepTimings");function x(e){const t=/^\s*(select|insert|update|delete|with|savepoint|release|rollback)\b/i.exec(e)?.[1]?.toLowerCase()??"other",n=/\b(?:from|into|update)\s+(?:only\s+)?([a-z_][a-z0-9_.]*)/i.exec(e)?.[1]?.toLowerCase().replace(/\W/g,"_");return n===void 0?t:`${t}_${n}`}o(x,"statementLabel");function s(e,t){r.getStore()?.steps.push([e,t])}o(s,"addStepTiming");function g(){const e=r.getStore();return e===void 0?0:performance.now()-e.start}o(g,"sinceCollectionStart");async function v(e,t){const n=performance.now();try{return await t()}finally{s(e,performance.now()-n)}}o(v,"timedStep");function y(e){return e.map(([t,n])=>`${t};dur=${n.toFixed(1)}`).join(", ")}o(y,"serverTimingHeader");const i=new WeakMap;function _(e){i.set(e,{receivedAt:performance.now()})}o(_,"markReceived");function S(e){const t=i.get(e);t!==void 0&&(t.authenticatedAt=performance.now())}o(S,"markAuthenticated");function b(e){return i.get(e)??{receivedAt:performance.now()}}o(b,"receiptOf");export{s as addStepTiming,m as collectStepTimings,w as isCollectingStepTimings,S as markAuthenticated,_ as markReceived,b as receiptOf,y as serverTimingHeader,g as sinceCollectionStart,x as statementLabel,v as timedStep};
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
process error: ${
|
|
3
|
-
stderr: ${
|
|
4
|
-
`))if(c.startsWith("worktree "))n=c.slice(9).trim();else if(n!==null&&
|
|
5
|
-
`).map(_=>_.trim()).filter(_=>_!==""),f=j(N(n.stdout),y);if(f.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${f.collisions.join(", ")}`};const p=s(async()=>{const _=await i(["merge","--ff-only",r],t);return _.status===0?{ok:!0}:{ok:!1,detail:u(_)}},"merge");if(f.kind==="direct")return p();const w=await i(["rev-parse","--verify","--quiet","refs/stash"],t),A=w.status===0?w.stdout.trim():null,m=await i(["stash","push","--message",`crtr landing ${e}`],t);if(m.status!==0)return{ok:!1,detail:u(m)};const k=await i(["rev-parse","--verify","--quiet","refs/stash"],t),o=k.status===0?k.stdout.trim():null;if(o===null||o===A)return p();const h=`local changes from ${t} are retained in stash ${o}; recover them with \`git -C ${D(t)} stash apply ${o}\` and resolve any conflict.`,g=await p();return g.ok?(await i(["stash","apply",o],t)).status===0?(await O(t,o),{ok:!0}):(await i(["reset","--hard",r],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${r} because local changes conflicted with it. ${h}`}):(await i(["stash","apply",o],t)).status===0?(await O(t,o),g):{ok:!1,detail:`${g.detail}
|
|
6
|
-
${h}`}}s(V,"landIntoBaseCheckout");async function x(t){const e=await $(t);if(e===null)throw new l("unknown_node",`unknown node: ${t}`,"Run this from a live node, or pass a real node id once that command supports it.");const a=e?.managed_worktree?.state==="open"?e.managed_worktree:null;if(a===null)throw new l("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to close for this node.");return X(t,a,await R(t,a))}s(x,"closeLocked");async function X(t,e,a){if(a.kind==="blocked"){const r=(await $(t))?.managed_worktree;throw r!=null&&r.state==="open"&&await F(t,{at:new Date().toISOString(),blocked:a.blocked}),new l("land_base_failed",a.blocked,a.next,a.detail)}return a.disposal!==void 0&&await B(t,a.disposal),await Q(t,e,"pending"),a.result}s(X,"persistCloseOutcome");async function R(t,e){if(!b(e.path))throw new l("worktree_missing",`managed worktree path is missing: ${e.path}`,z(e));if(await U(e.path))throw new l("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await d(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new l("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const r=await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(r!==e.branch){if((await i(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||r==="HEAD"||!await M(e.repo_root,e.path,r))throw new l("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${r==="HEAD"?"detached HEAD":r})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await S(e.path,e,n)===null)throw new l("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${r} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${r} through its own workflow before closing.`);const h=await E(e.path);if(!await M(e.repo_root,e.path,r)||await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==r||await d(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new l("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return{kind:"closed",disposal:{observed_branch:r,observed_sha:n,common_dir:h,authorized:new Date().toISOString()},result:{node_id:t,branch:r,worktree_path:e.path,landed_sha:n,...v(e),branch_delete_error:`${r} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}}if(await S(e.path,e,n)!==null)return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:n,...v(e)}};let c;try{c=await J(e.path,e.base_ref)}catch(o){if(!(o instanceof l)||o.code!=="missing_base_branch"||n!==e.base_sha)throw o;return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,...v(e)}}}const y=await i(["rebase",c],e.path);if(y.status!==0)throw new l("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,u(y));const f=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),p=s((o,h,g)=>({kind:"blocked",blocked:o,next:h,detail:g}),"blocked"),w=await i(["merge-base","--is-ancestor",c,f],e.path);if(w.status!==0)return p(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",u(w));const A=await d(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),m=K(A,e.base_ref);let k;if(m!==null){const o=await i(["rev-parse","HEAD"],m);if(o.status!==0||o.stdout.trim()!==c)return p(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${m}, then rerun \`crtr node worktree close\`.`,o.status!==0?u(o):`expected ${c}, found ${o.stdout.trim()}`);const h=await V(m,e.branch,c,f);if(!h.ok)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${m} in a state that blocks a fast-forward.`,h.detail);k=h.stash}else{const o=await i(["update-ref",`refs/heads/${e.base_ref}`,f,c],e.path);if(o.status!==0)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",u(o))}return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:f,...v(e),...k===void 0?{}:{base_checkout_stash:k}}}}s(R,"closeOutcome");async function he(t){const e=(await $(t))?.managed_worktree;if(e==null||e.state!=="open")return x(t);if(!b(e.path)){const c=await G(t);if(c!==null)return Y(t,c)}const a=(await $(t))?.managed_worktree;if(a==null||a.state!=="open")return x(t);const r=b(a.path)?a.path:a.repo_root,n=await E(r);return H(L(n),()=>x(t),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${n}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}s(he,"closeManagedWorktreeAsync");async function de(t,e){if(!b(e.path)){const r=await T(t,e);if(r!==null)return{kind:"concluded",conclusion:r}}const a=await E(b(e.path)?e.path:e.repo_root);return H(L(a),()=>R(t,e),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}s(de,"closeManagedWorktreeOnHost");function Y(t,e){return{node_id:t,branch:e.dropped.branch,worktree_path:e.dropped.worktree_path,landed_sha:e.landedSha,worktree_removed:!0,branch_deleted:e.dropped.branch_deleted,...e.dropped.branch_delete_error===void 0?{}:{branch_delete_error:e.dropped.branch_delete_error}}}s(Y,"concludedCloseResult");export{he as closeManagedWorktreeAsync,de as closeManagedWorktreeOnHost,Y as concludedCloseResult,X as persistCloseOutcome};
|
|
1
|
+
var L=Object.defineProperty;var o=(r,e)=>L(r,"name",{value:e,configurable:!0});import{existsSync as u,realpathSync as M}from"node:fs";import{resolve as O}from"node:path";import{getNode as k,recordDisposalGrant as R,recordLandIntent as P}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as v}from"./exclusive-lock.js";import{gitAsync as l}from"./git.js";import{proveBranchContained as A}from"./worktree-containment.js";import{concludeAbsentManagedWorktreeAsync as B,concludeAbsentManagedWorktreeOnHost as F}from"./worktree-mutation-async.js";import{WORKTREE_LOCK_WAIT_MS as D,checkoutPathForBranchInList as G,missingWorktreeRecoveryHint as I,persistClosedWorktreeState as T,samePath as q,worktreeLockPathForCommonDir as E,WorktreeError as s}from"./worktree.js";import{shellQuote as x}from"../shared/shell-quote.js";function p(r){return(r.stderr.trim()||r.stdout.trim()).trim()}o(p,"detailOf");async function h(r,e,t,a){const n=await l(e,r);if(n.status!==0)throw new s(t,`git ${e.join(" ")} failed`,a,p(n));return n.stdout.trim()}o(h,"runGit");async function w(r){const e=await h(r,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return M(O(r,e))}o(w,"commonGitDir");async function K(r,e){const t=`refs/heads/${e}`,a=await l(["show-ref","--verify","--quiet",t],r);if(a.status===1&&a.executionFailed!==!0)throw new s("missing_base_branch",`managed worktree base '${e}' does not name an existing local branch`,"The base must be a local branch that landing can fast-forward \u2014 freshen your local branch from origin first (rebase-not-merge), then base on it.");if(a.status!==0){const n=a.processError===void 0?"":`
|
|
2
|
+
process error: ${a.processError}`;throw new s("base_branch_inspection_failed",`could not inspect local base branch '${e}' (git show-ref exited with status ${a.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${a.status}
|
|
3
|
+
stderr: ${a.stderr.trim()||"<empty>"}${n}`)}return h(r,["rev-parse","--verify",t],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(K,"resolveLandableBase");async function N(r){for(const e of["rebase-merge","rebase-apply"]){const t=await h(r,["rev-parse","--git-path",e],"git_path_failed","Inspect the worktree manually, then retry.");if(u(t))return!0}return!1}o(N,"rebaseInProgress");async function H(r,e,t){const a=await l(["worktree","list","--porcelain"],r);if(a.status!==0)return!1;let n=null;for(const c of a.stdout.split(`
|
|
4
|
+
`))if(c.startsWith("worktree "))n=c.slice(9).trim();else if(n!==null&&q(n,e)&&c===`branch refs/heads/${t}`)return!0;return!1}o(H,"registeredWorktree");function _(r){return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${r.path} remains intact. After its node exits, run \`git -C ${x(r.repo_root)} worktree remove ${x(r.path)}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${r.branch} remains checked out at ${r.path}; delete it only after that checkout is removed and its landed commit is still contained in ${r.base_ref}.`}}o(_,"deferredCleanupResult");async function j(r,e){const t=await l(["merge","--ff-only",e],r);return t.status===0?{ok:!0}:{ok:!1,detail:p(t)}}o(j,"landIntoBaseCheckout");async function g(r){const e=await k(r);if(e===null)throw new s("unknown_node",`unknown node: ${r}`,"Run this from a live node, or pass a real node id once that command supports it.");const t=e?.managed_worktree?.state==="open"?e.managed_worktree:null;if(t===null)throw new s("no_managed_worktree",`node ${r} has no open managed worktree`,"Nothing to close for this node.");return z(r,t,await W(r,t))}o(g,"closeLocked");async function z(r,e,t){if(t.kind==="blocked"){const a=(await k(r))?.managed_worktree;throw a!=null&&a.state==="open"&&await P(r,{at:new Date().toISOString(),blocked:t.blocked}),new s("land_base_failed",t.blocked,t.next,t.detail)}return t.disposal!==void 0&&await R(r,t.disposal),await T(r,e,"pending"),t.result}o(z,"persistCloseOutcome");async function W(r,e){if(!u(e.path))throw new s("worktree_missing",`managed worktree path is missing: ${e.path}`,I(e));if(await N(e.path))throw new s("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new s("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const a=await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await h(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(a!==e.branch){if((await l(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||a==="HEAD"||!await H(e.repo_root,e.path,a))throw new s("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${a==="HEAD"?"detached HEAD":a})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await A(e.path,e,n)===null)throw new s("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${a} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${a} through its own workflow before closing.`);const d=await w(e.path);if(!await H(e.repo_root,e.path,a)||await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==a||await h(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new s("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return{kind:"closed",disposal:{observed_branch:a,observed_sha:n,common_dir:d,authorized:new Date().toISOString()},result:{node_id:r,branch:a,worktree_path:e.path,landed_sha:n,..._(e),branch_delete_error:`${a} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}}if(await A(e.path,e,n)!==null)return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:n,..._(e)}};let c;try{c=await K(e.path,e.base_ref)}catch(i){if(!(i instanceof s)||i.code!=="missing_base_branch"||n!==e.base_sha)throw i;return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,..._(e)}}}const y=await l(["rebase",c],e.path);if(y.status!==0)throw new s("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,p(y));const b=await h(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),m=o((i,d,S)=>({kind:"blocked",blocked:i,next:d,detail:S}),"blocked"),$=await l(["merge-base","--is-ancestor",c,b],e.path);if($.status!==0)return m(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",p($));const C=await h(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),f=G(C,e.base_ref);if(f!==null){const i=await l(["rev-parse","HEAD"],f);if(i.status!==0||i.stdout.trim()!==c)return m(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${f}, then rerun \`crtr node worktree close\`.`,i.status!==0?p(i):`expected ${c}, found ${i.stdout.trim()}`);const d=await j(f,b);if(!d.ok)return m(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${f} in a state that blocks a fast-forward.`,d.detail)}else{const i=await l(["update-ref",`refs/heads/${e.base_ref}`,b,c],e.path);if(i.status!==0)return m(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",p(i))}return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:b,..._(e)}}}o(W,"closeOutcome");async function ne(r){const e=(await k(r))?.managed_worktree;if(e==null||e.state!=="open")return g(r);if(!u(e.path)){const c=await B(r);if(c!==null)return Q(r,c)}const t=(await k(r))?.managed_worktree;if(t==null||t.state!=="open")return g(r);const a=u(t.path)?t.path:t.repo_root,n=await w(a);return v(E(n),()=>g(r),{timeoutMs:Math.min(D,25e3),timeoutError:o(()=>new s("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${n}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(ne,"closeManagedWorktreeAsync");async function oe(r,e){if(!u(e.path)){const a=await F(r,e);if(a!==null)return{kind:"concluded",conclusion:a}}const t=await w(u(e.path)?e.path:e.repo_root);return v(E(t),()=>W(r,e),{timeoutMs:Math.min(D,25e3),timeoutError:o(()=>new s("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${t}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(oe,"closeManagedWorktreeOnHost");function Q(r,e){return{node_id:r,branch:e.dropped.branch,worktree_path:e.dropped.worktree_path,landed_sha:e.landedSha,worktree_removed:!0,branch_deleted:e.dropped.branch_deleted,...e.dropped.branch_delete_error===void 0?{}:{branch_delete_error:e.dropped.branch_delete_error}}}o(Q,"concludedCloseResult");export{ne as closeManagedWorktreeAsync,oe as closeManagedWorktreeOnHost,Q as concludedCloseResult,z as persistCloseOutcome};
|
|
@@ -1,41 +1,3 @@
|
|
|
1
|
-
/** Tracked-but-modified and untracked paths from `git status --porcelain`. */
|
|
2
|
-
export interface CheckoutStatus {
|
|
3
|
-
/** Paths with modifications to a tracked file (staged, unstaged, or both). */
|
|
4
|
-
tracked: string[];
|
|
5
|
-
/** Paths Git does not track at all. */
|
|
6
|
-
untracked: string[];
|
|
7
|
-
}
|
|
8
|
-
/** Split `git status --porcelain` (v1 format) into tracked modifications and
|
|
9
|
-
* untracked paths. A rename entry (`R old -> new`) reports the destination:
|
|
10
|
-
* that is the path an incoming commit would collide with. */
|
|
11
|
-
export declare function parseStatusPorcelain(porcelain: string): CheckoutStatus;
|
|
12
|
-
export type LandPlan =
|
|
13
|
-
/** Nothing local overlaps the incoming commits — fast-forward directly. */
|
|
14
|
-
{
|
|
15
|
-
kind: 'direct';
|
|
16
|
-
}
|
|
17
|
-
/** Local modifications touch incoming files; land underneath them. */
|
|
18
|
-
| {
|
|
19
|
-
kind: 'stash';
|
|
20
|
-
overlapping: string[];
|
|
21
|
-
}
|
|
22
|
-
/** An incoming commit adds a path that already exists here, untracked. */
|
|
23
|
-
| {
|
|
24
|
-
kind: 'refuse';
|
|
25
|
-
collisions: string[];
|
|
26
|
-
};
|
|
27
|
-
/** How to fast-forward a base checkout that may hold local changes.
|
|
28
|
-
*
|
|
29
|
-
* Git is less fragile than it looks here: a fast-forward refuses only when an
|
|
30
|
-
* incoming commit touches a file with local modifications, so DISJOINT local
|
|
31
|
-
* changes are carried along fine and need no stash at all. Overlap is the
|
|
32
|
-
* blocker, not dirt.
|
|
33
|
-
*
|
|
34
|
-
* Untracked files are different. They also do not block a fast-forward unless
|
|
35
|
-
* an incoming commit adds the same path — and that collision is a refusal
|
|
36
|
-
* rather than a stash, because sweeping a person's untracked file into a stash
|
|
37
|
-
* to make room for a commit is not a trade this code may make on their behalf. */
|
|
38
|
-
export declare function planLandIntoCheckout(status: CheckoutStatus, incoming: readonly string[]): LandPlan;
|
|
39
1
|
/** The `git update-ref --stdin` body that deletes a managed branch ONLY while
|
|
40
2
|
* the ref that proved its content already landed is still at the exact SHA the
|
|
41
3
|
* proof inspected. Compare-and-delete is the whole ownership guard: a branch
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){if(t.length<4)continue;const r=t.slice(0,2),i=t.slice(3),c=i.includes(" -> ")?i.slice(i.indexOf(" -> ")+4):i,l=c.startsWith('"')&&c.endsWith('"')?c.slice(1,-1):c;r==="??"?s.push(l):r!=="!!"&&n.push(l)}return{tracked:n,untracked:s}}o(u,"parseStatusPorcelain");function f(e,n){const s=new Set(n),t=e.untracked.filter(i=>s.has(i));if(t.length>0)return{kind:"refuse",collisions:t};const r=e.tracked.filter(i=>s.has(i));return r.length>0?{kind:"stash",overlapping:r}:{kind:"direct"}}o(f,"planLandIntoCheckout");function h(e,n,s,t){return`verify ${s} ${t}
|
|
1
|
+
var i=Object.defineProperty;var r=(e,n)=>i(e,"name",{value:n,configurable:!0});function a(e,n,t,f){return`verify ${t} ${f}
|
|
3
2
|
delete refs/heads/${e} ${n}
|
|
4
|
-
`}
|
|
3
|
+
`}r(a,"refDeleteTransactionStdin");export{a as refDeleteTransactionStdin};
|