@north-light/cli 0.3.714 → 0.3.715
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +4 -0
- package/dist/api/dto/execution-start.d.ts +9 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +3 -3
- package/dist/commands/profile/environment.js +2 -2
- package/dist/commands/sys/feedback.js +5 -5
- package/dist/core/canvas/executions.d.ts +0 -2
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/environment-recipe.d.ts +1 -0
- package/dist/core/environment-recipe.js +1 -1
- package/dist/core/ledger/rates.d.ts +0 -2
- package/dist/core/ledger/rates.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/runtime/runner/types.d.ts +0 -2
- package/dist/core/runtime/spawn.js +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/feedback.d.ts +2 -0
- package/dist/daemon/api/handlers/feedback.js +9 -0
- package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
- package/dist/daemon/api/handlers/git-credential.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/reconcilers/ledger-storage.js +2 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
- package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
- package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
- package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
- package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
- package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-start.mjs +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}:{},...
|
|
1
|
+
var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as w}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as u}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...t}=e;return t}n(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:n(async e=>{const{id:r}=await c(e.profile);return h(await u().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:n(async e=>{const{id:r}=await c(e.profile),t=e.repo,s=e.setupScriptFile,o=e.piPackage,i=e.memory,a=e.allowPullRequestWrite;if(i!==void 0&&![2,4,8].includes(i))throw m("`--memory` is 2, 4 or 8 (GB).");const l={...t!==void 0&&t.length>0?{repositories:t}:{},...s!==void 0?{setup_script:w(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
|
|
2
|
+
`)}:{},...i!==void 0?{memory_mb:i*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await u().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,v]});export{A as environmentBranch};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)[0].trim();return`[feedback] ${n.length>80?n.slice(0,79)+"\u2026":n}`}a(
|
|
1
|
+
var g=Object.defineProperty;var a=(r,e)=>g(r,"name",{value:e,configurable:!0});import{spawnSync as w}from"node:child_process";import{mkdirSync as k,writeFileSync as b}from"node:fs";import{join as m}from"node:path";import u from"node:os";import{defineLeaf as v}from"../../core/command.js";import{usage as T}from"../../core/errors.js";import{userScopeRoot as $}from"../../core/scope.js";import{readTelemetry as E}from"../../core/canvas/telemetry.js";import{ApiError as R,routes as _}from"../../api/index.js";import{cliClient as p}from"../api-client.js";import{projectTier1Event as N,readLogSnapshot as O}from"../../core/events/read.js";import{readPackageVersion as S}from"./shared.js";const y="Northlight-Systems/crouter",l="CRTR_FEEDBACK_ENDPOINT",C="CRTR_FEEDBACK_TOKEN",D=15e3;async function I(){const r=process.env,e=r.CRTR_NODE_ID??null;let t=null,n=[];if(e!==null){const s=await L(e);s!==null&&typeof s.cycles=="number"&&(t=s.cycles),n=F(e)}const o=e!==null?E(e).context_tokens??null:null;return{version:S(),platform:`${u.platform()} ${u.release()} (${u.arch()})`,nodeId:e,kind:r.CRTR_KIND??null,mode:r.CRTR_MODE??null,lifecycle:r.CRTR_LIFECYCLE??null,cwd:r.CRTR_NODE_CWD??process.cwd(),cycle:t,contextTokens:o,logTail:n}}a(I,"collectContext");async function L(r){try{return await p().getNode(r)}catch(e){if(e instanceof R)return null;throw e}}a(L,"fetchNodeOrNull");function F(r){try{return O({nodeId:r,component:"broker"},!1).items.filter(e=>e.kind==="event").slice(-15).map(e=>JSON.stringify(N(e.envelope)))}catch{return[]}}a(F,"readRecentActivity");function P(r,e){const n=(r!==void 0&&r.trim()!==""?r.trim():void 0)??e.split(`
|
|
2
|
+
`)[0].trim();return`[feedback] ${n.length>80?n.slice(0,79)+"\u2026":n}`}a(P,"deriveTitle");function j(r,e){const t=[`| crtr version | \`${e.version}\` |`,`| platform | ${e.platform} |`];e.nodeId!==null&&(t.push(`| node id | \`${e.nodeId}\` |`),t.push(`| kind / mode / lifecycle | ${e.kind??"?"} / ${e.mode??"?"} / ${e.lifecycle??"?"} |`),e.cycle!==null&&t.push(`| cycle | ${e.cycle} |`),e.contextTokens!==null&&t.push(`| context tokens | ${e.contextTokens.toLocaleString("en-US")} |`)),e.cwd!==null&&t.push(`| working dir | \`${e.cwd}\` |`);const n=[r.trim(),"","---","_Filed via `crtr sys feedback` \u2014 context below auto-attached by the harness._","","### Environment","| | |","|---|---|",...t];return e.logTail.length>0&&n.push("",`### Recent node activity (last ${e.logTail.length} log events)`,"```jsonl",...e.logTail,"```"),n.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}a(j,"buildBody");async function q(r,e,t,n,o){const s=process.env[
|
|
5
|
-
`).filter(o=>o.startsWith("http")).pop()??t.stdout.trim()}:{error:t.error!==void 0?`gh not available: ${t.error.message}`:t.stderr?.trim()||`gh exited ${t.status}`}}a(
|
|
4
|
+
`}a(j,"buildBody");async function q(r,e,t,n,o){const s=process.env.CRTR_API_URL;if(s!==void 0&&s!==""&&r===`${s.replace(/\/$/,"")}${_.feedback()}`)try{return{url:(await p().postFeedback({title:e,body:t})).url}}catch(i){return{error:`${l} failed: ${i instanceof Error?i.message:String(i)}`}}const c=process.env[C];try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...c!==void 0&&c!==""?{authorization:`Bearer ${c}`}:{}},body:JSON.stringify({title:e,body:t,message:n,context:o}),signal:AbortSignal.timeout(D)});if(!i.ok){const h=(await i.text().catch(()=>"")).trim().slice(0,400);return{error:`${l} returned HTTP ${i.status}${h===""?"":`: ${h}`}`}}const d=await i.json().catch(()=>null),f=typeof d?.url=="string"?d.url:void 0;return f===void 0?{}:{url:f}}catch(i){return{error:`${l} unreachable: ${i instanceof Error?i.message:String(i)}`}}}a(q,"deliverToEndpoint");function A(r,e){const t=w("gh",["issue","create","--repo",y,"--title",r,"--body-file","-"],{input:e,encoding:"utf8"});return t.error===void 0&&t.status===0?{url:t.stdout.trim().split(`
|
|
5
|
+
`).filter(o=>o.startsWith("http")).pop()??t.stdout.trim()}:{error:t.error!==void 0?`gh not available: ${t.error.message}`:t.stderr?.trim()||`gh exited ${t.status}`}}a(A,"deliverToGitHub");function K(r,e){const t=m($(),"feedback");k(t,{recursive:!0});const n=new Date().toISOString().replace(/[:.]/g,"-"),o=m(t,`${n}.md`);return b(o,`# ${r}
|
|
6
6
|
|
|
7
|
-
${e}`,"utf8"),o}a(K,"saveLocally");const
|
|
7
|
+
${e}`,"utf8"),o}a(K,"saveLocally");const Z=v({name:"feedback",description:"report a crtr harness bug to whoever maintains this crtr install",whenToUse:"a crtr command itself misbehaves \u2014 it errors unexpectedly, hangs, churns, double-spawns, or acts contrary to its documented contract. NOT for your task work or decisions the user should make (that is `crtr human send`); this reports the TOOL, filing a report with the crtr maintainers with your node context auto-attached.",help:{name:"sys feedback",summary:"file a report describing a crtr harness bug, with node context auto-attached",params:[{kind:"positional",name:"message",required:!0,constraint:"What broke, in your own words: the command you ran, what you expected, what happened instead. Be concrete \u2014 this is the only part you write; everything else is auto-collected."},{kind:"flag",name:"title",type:"string",required:!1,constraint:"Issue title. Default: first line of the message, truncated."}],output:[{name:"status",type:"string",required:!0,constraint:"filed | saved-locally."},{name:"url",type:"string",required:!1,constraint:"Where the report landed, when the sink names a location."},{name:"path",type:"string",required:!1,constraint:"Local report path when status is saved-locally."},{name:"error",type:"string",required:!1,constraint:"Why filing fell back to local save."}],outputKind:"object",effects:[`Sends the report where this install delivers harness feedback: the ${l} endpoint when the deployment sets one, otherwise a GitHub issue on ${y} via gh.`,"On delivery failure, writes the report to ~/.crouter/feedback/ instead \u2014 never lost."]},run:a(async r=>{const e=r.message?.trim();if(e===void 0||e==="")throw T("feedback message is required: describe what broke. Run `crtr sys feedback -h`.");const t=await I(),n=P(r.title,e),o=j(e,t),s=process.env[l]?.trim(),c=s!==void 0&&s!==""?await q(s,n,o,e,t):A(n,o);return c.error===void 0?c.url===void 0?{status:"filed"}:{status:"filed",url:c.url}:{status:"saved-locally",path:K(n,o),error:c.error}},"run")});export{Z as sysFeedbackLeaf};
|
|
@@ -9,7 +9,6 @@ export interface Execution {
|
|
|
9
9
|
endedAt: string | null;
|
|
10
10
|
exitReason: string | null;
|
|
11
11
|
runner: 'process' | 'blaxel' | 'machine';
|
|
12
|
-
sandboxName: string | null;
|
|
13
12
|
attempt: number;
|
|
14
13
|
/** The release the wake accepted. */
|
|
15
14
|
release: string | null;
|
|
@@ -31,7 +30,6 @@ export interface BeginExecutionInput {
|
|
|
31
30
|
runner?: Execution['runner'];
|
|
32
31
|
/** Defaults to one above the node's highest attempt. */
|
|
33
32
|
attempt?: number;
|
|
34
|
-
sandboxName?: string | null;
|
|
35
33
|
release?: string | null;
|
|
36
34
|
launchJson?: string | null;
|
|
37
35
|
/** The broker cap. The count of other nodes' live rows and this insert are one step under a database-wide lock,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as R,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class b extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class F extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new b(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,R())!=="dead"));if(s!==void 0)throw new F(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=R(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{F as ExecutionAlreadyLive,b as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
|
|
1
|
+
var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
-- 030-environment-pull-request-write.sql — `environments.allow_pull_request_write`: when true, the git credential a cloud environment's nodes receive also carries pull_requests: write (merging). An added column; it is not part of the recipe, so changing it builds no new image.
|
|
2
|
+
ALTER TABLE environments ADD COLUMN IF NOT EXISTS allow_pull_request_write boolean NOT NULL DEFAULT false;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 30;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=30;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{usage as f}from"./errors.js";import{withCanvasWrite as _}from"./canvas/db.js";async function d(r,e){return await _(n=>u(n,r,e))}s(d,"setEnvironmentRecipe");async function u(r,e,n){const o=new Set;for(const i of n.repositories){if(!/^[A-Za-z0-9._-]+$/.test(i.name)||i.name==="."||i.name==="..")throw new Error(`repository name ${JSON.stringify(i.name)} is not a plain directory name`);if(o.has(i.name))throw new Error(`repository name ${i.name} appears twice in the recipe`);o.add(i.name)}{const i=await r.prepare("SELECT kind, recipe_revision, setup_script, pi_packages FROM environments WHERE object = ? FOR UPDATE").get(e);if(i===void 0)throw new Error(`no environment ${e}`);if(i.kind!=="blaxel")throw new Error(`environment ${e} is a ${i.kind} environment; only a cloud (blaxel) environment has a recipe image`);const p=await r.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(e);if(i.setup_script===n.setup_script&&i.pi_packages===n.pi_packages&&p.length===n.repositories.length&&p.every((a,t)=>a.name===n.repositories[t].name&&a.github_full_name===n.repositories[t].github_full_name&&a.default_branch===n.repositories[t].default_branch))return{revision:Number(i.recipe_revision),changed:!1};await r.prepare("DELETE FROM environment_repos WHERE environment = ?").run(e);const E=r.prepare("INSERT INTO environment_repos (environment, position, name, github_full_name, default_branch) VALUES (?, ?, ?, ?, ?)");for(const[a,t]of n.repositories.entries())await E.run(e,a,t.name,t.github_full_name,t.default_branch);const l=await r.prepare("UPDATE environments SET setup_script = ?, pi_packages = ?, recipe_revision = recipe_revision + 1 WHERE object = ? RETURNING recipe_revision").get(n.setup_script,n.pi_packages,e);return{revision:Number(l.recipe_revision),changed:!0}}}s(u,"writeEnvironmentRecipe");const m=[2048,4096,8192];async function v(r,e){if(e.memory_mb!==void 0&&!m.includes(e.memory_mb))throw f(`memory_mb must be one of ${m.join(", ")}`,{field:"memory_mb"});await _(async n=>{const o=await n.prepare("SELECT setup_script, pi_packages FROM environments WHERE object = ? AND kind = 'blaxel' FOR UPDATE").get(r);if(o===void 0)throw new Error(`no cloud environment ${r}`);if(e.repositories!==void 0||e.setup_script!==void 0||e.pi_packages!==void 0){const i=e.repositories??await n.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(r);await u(n,r,{repositories:i,setup_script:e.setup_script===void 0?o.setup_script:e.setup_script,pi_packages:e.pi_packages===void 0?o.pi_packages:e.pi_packages})}e.memory_mb!==void 0&&await n.prepare("UPDATE environments SET memory_mb = ? WHERE object = ?").run(e.memory_mb,r),e.allow_pull_request_write!==void 0&&await n.prepare("UPDATE environments SET allow_pull_request_write = ? WHERE object = ?").run(String(e.allow_pull_request_write),r)})}s(v,"patchEnvironment");export{m as ENVIRONMENT_MEMORY_MB,v as patchEnvironment,d as setEnvironmentRecipe,u as writeEnvironmentRecipe};
|
|
@@ -2,7 +2,6 @@ export declare const LEDGER_ENV: {
|
|
|
2
2
|
readonly sandboxUsdPerGbHour: "CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR";
|
|
3
3
|
readonly sandboxStandbyS: "CRTR_LEDGER_SANDBOX_STANDBY_S";
|
|
4
4
|
readonly storageUsdPerGbMonth: "CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH";
|
|
5
|
-
readonly sandboxDiskUsdPerGbMonth: "CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH";
|
|
6
5
|
readonly infraFreeUsdPerMonth: "CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH";
|
|
7
6
|
readonly takePct: "CRTR_LEDGER_TAKE_PCT";
|
|
8
7
|
readonly r2Move: "CRTR_LEDGER_R2_MOVE";
|
|
@@ -12,7 +11,6 @@ export declare const DEFAULT_INFRA_FREE_USD = 50;
|
|
|
12
11
|
export declare const sandboxUsdPerGbHour: () => number | null;
|
|
13
12
|
export declare const sandboxStandbyS: () => number;
|
|
14
13
|
export declare const storageUsdPerGbMonth: () => number | null;
|
|
15
|
-
export declare const sandboxDiskUsdPerGbMonth: () => number | null;
|
|
16
14
|
export declare const infraFreeUsdPerMonth: () => number;
|
|
17
15
|
/** Northlight's take on each priced model or tool charge, in percent; 0 (the default) writes no take rows. */
|
|
18
16
|
export declare const takePercent: () => number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{emitEvent as d}from"../events/emit.js";const o={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"},i=30,R=50;function s(r,e=1/0){const n=process.env[r];if(n===void 0||n==="")return null;const _=/^\d+(\.\d+)?$/.test(n)?Number(n):NaN;if(!Number.isFinite(_)||_>e)throw new Error(`${r} must be a number from 0${e===1/0?" up":` to ${e}`}, got ${JSON.stringify(n)}`);return _}t(s,"number");function u(r){const e=process.env[r];if(e===void 0||e==="")return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;throw new Error(`${r} must be true, false, 1 or 0, got ${JSON.stringify(e)}`)}t(u,"flag");const f=t(()=>s(o.sandboxUsdPerGbHour),"sandboxUsdPerGbHour"),c=t(()=>s(o.sandboxStandbyS)??i,"sandboxStandbyS"),b=t(()=>s(o.storageUsdPerGbMonth),"storageUsdPerGbMonth"),S=t(()=>s(o.infraFreeUsdPerMonth)??R,"infraFreeUsdPerMonth"),D=t(()=>s(o.takePct,100)??0,"takePercent"),U=t(()=>u(o.r2Move),"r2MoveEnabled");function p(){f(),c(),b(),S(),D(),U()}t(p,"assertLedgerEnv");const E=new Set;function x(r,...e){const n=`${r}:${e.join(",")}`;E.has(n)||(E.add(n),d({level:"warn",event:"ledger.rate_unset",fields:{lane:r,unset:e}}))}t(x,"warnRateUnset");export{R as DEFAULT_INFRA_FREE_USD,i as DEFAULT_STANDBY_S,o as LEDGER_ENV,p as assertLedgerEnv,S as infraFreeUsdPerMonth,U as r2MoveEnabled,c as sandboxStandbyS,f as sandboxUsdPerGbHour,b as storageUsdPerGbMonth,D as takePercent,x as warnRateUnset};
|
|
@@ -1,3 +1,3 @@
|
|
|
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 he,recordExecutionPid as pe,abortExecution as F,endLiveExecution as de,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 Ee,readGoal as E,readYieldMessage as xe,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 hr(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(hr,"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 dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"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 dr(a)?{}:await hr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(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.isClaimed(e))return await a.has(e)&&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(!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 d=!k&&await a.reserveSlot(e);let o=null;if(d){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(!d||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 de(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 d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(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=d&&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 he)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,h=w?{}:await vr(e,r,x,!u),g=h.resumeSessionPath!==void 0,B=g&&h.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(h.resumeSessionPath)?(await E(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 E(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,{...h,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...h,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),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 ee(e)}else{const n=await Re(r,f);c=y(r,{...h,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}
|
|
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 m,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as me,abortExecution as F,endLiveExecution as de,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 Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,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 hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await m().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await m().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function mr(e){const r=_(e);return r===null?!0:(await m().read(r)).entries.some(i=>i.type==="message")}s(mr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await m().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(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 hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"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 n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.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 n.isClaimed(e))return await n.has(e)&&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(!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 d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.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 n.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{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(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 hr(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:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await N(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 d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(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=d&&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"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,x,!u),g=p.resumeSessionPath!==void 0,B=g&&p.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 mr(p.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await N(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,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await m().header(await m().fork($,e))).path;c=y(r,{resumeSessionPath:le,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...p,prompt:S}),h=C(),await V(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await E(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(c,r)),await ee(e)}else{const a=await Re(r,f);c=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=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)},h!==null&&(c.env[$e]=Ce(h)),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 a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.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}: ${
|
|
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}: ${a.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 me(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.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(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
|
|
@@ -26,6 +26,9 @@ export declare const REPOS_DIR = "repos";
|
|
|
26
26
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
27
27
|
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
28
28
|
export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
|
|
29
|
+
/** `gh` for a sandbox: /usr/local/bin comes before /usr/bin, so this wrapper runs first. It asks git's credential helper (set at sandbox start, so it reaches the control plane's
|
|
30
|
+
* git-credential route) for a fresh installation token, exports it as GH_TOKEN for this one call and runs the real gh. No token is stored on disk. */
|
|
31
|
+
export declare const GH_WRAPPER_PATH = "/usr/local/bin/gh";
|
|
29
32
|
/** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
|
|
30
33
|
* Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
|
|
31
34
|
* the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{constants as P,lstatSync as q,mkdirSync as z,readFileSync as W,readdirSync as J,readlinkSync as X,rmSync as V,writeFileSync as b}from"node:fs";import{join as E,relative as Z}from"node:path";import{crc32 as Q,deflateRawSync as tt}from"node:zlib";import{BlaxelApiError as et}from"./client.js";const rt="public.ecr.aws/docker/library/node:24-alpine",nt="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",D="/var/lib/crtr/recipe-pi-agent",ot="blaxel.toml",st=`[build]
|
|
2
2
|
slim = false
|
|
3
|
-
`,
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines")
|
|
5
|
-
`)}c(
|
|
6
|
-
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,
|
|
3
|
+
`,it="1.1.0",_="recipe-setup.sh",L="repos",B="/work/.crtr/setup.log",G="/work/.crtr/setup-failed",C="/usr/local/bin/gh",at=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],R=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ct=c(t=>(t??"").split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${B} 2>&1 || echo ${R(t)} "exited $?" >> ${G}`,"guarded");function lt(t,r,i=!1){const s=ct(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${rt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${at.map(R).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${nt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${D} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${G} ${B}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${it}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work");for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${R(o)}`));a&&e.push($("setup script",`bash /tmp/${_}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
5
|
+
`)}c(lt,"recipeDockerfile");const pt=c((t,r,i)=>new Promise((s,a)=>{const n=j("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function It(t){const r=t.git??pt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);z(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,ot),st),b(E(t.dir,"Dockerfile"),lt(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
6
|
+
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,_),t.recipe.setup_script.endsWith(`
|
|
7
7
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
8
|
-
`)}c(
|
|
8
|
+
`)}c(It,"prepareBuildDir");function M(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=q(a),e=Z(t,a).split("\\").join("/");n.isDirectory()?M(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:P.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:W(a),mode:P.S_IFREG|n.mode&511})}}c(M,"walk");function dt(t){const r=[];M(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=tt(o.data),I=Q(o.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(o.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(dt,"zipDirectory");async function T(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new et(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(T,"api");async function F(t,r){const{status:i,json:s}=await T(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(F,"getImage");async function bt(t,r){await T(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(bt,"deleteImage");const ut=60*6e4;async function _t(t,r,i,s={}){const a=s.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=s.now??Date.now,e=n(),o=await F(t,r),d=new Set((o?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await T(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(dt(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const N=s.timeoutMs??ut,H=e+N;let O=null;for(;;){const h=await F(t,r),u=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,U)=>m-U);if(u==="BUILT"&&k.length>=2){O??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),U=k[0],S=c(w=>Date.parse(w??"")>=U,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),y=(A.length>0?A:v?m:[]).sort((w,K)=>(K.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(y!==void 0)return{ref:`sandbox/${r}:${y}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>H)throw new Error(`building image ${r} did not finish within ${N} ms (last status ${u??"none"})`);await a(s.pollMs??3e3)}}c(_t,"buildImage");const xt=c(t=>`env-${t}`,"environmentImageName");function Ut(t){V(t,{recursive:!0,force:!0})}c(Ut,"removeBuildDir");export{st as BLAXEL_TOML,ot as BLAXEL_TOML_FILE,ut as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,rt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,nt as SANDBOX_API_IMAGE,G as SETUP_FAILED_FILE,B as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,_t as buildImage,bt as deleteImage,xt as environmentImageName,F as getImage,It as prepareBuildDir,lt as recipeDockerfile,Ut as removeBuildDir,dt as zipDirectory};
|
|
@@ -5,8 +5,6 @@ export interface RunnerExecution {
|
|
|
5
5
|
nodeId: string;
|
|
6
6
|
/** `executions.attempt`. */
|
|
7
7
|
attempt: number;
|
|
8
|
-
/** `executions.sandbox_name`, null for the process runner. */
|
|
9
|
-
sandboxName: string | null;
|
|
10
8
|
}
|
|
11
9
|
/** What `start` needs beyond the execution: the execution row's `launch_json` is the launch recipe. */
|
|
12
10
|
export interface RunnerStartInput extends RunnerExecution {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as p,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await p(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await p(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,sandboxName:null,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await p(d),N=e.creator===void 0||e.creator===null?null:await p(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async h=>h?.isolated===!0||h?.run_id!=null&&(await p(h.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const _=await Qn(e.profile,d,M),W=S?null:await je(_,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:_}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(_)?await He(_,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(_):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const h=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(h.worktree=z),P&&await ve(_e(h),{cwd:j,profileId:_});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:_,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
|
|
1
|
+
var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as p,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await p(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await p(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await p(d),N=e.creator===void 0||e.creator===null?null:await p(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async h=>h?.isolated===!0||h?.run_id!=null&&(await p(h.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const _=await Qn(e.profile,d,M),W=S?null:await je(_,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:_}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(_)?await He(_,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(_):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const h=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(h.worktree=z),P&&await ve(_e(h),{cwd:j,profileId:_});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:_,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
|
|
2
2
|
|
|
3
3
|
`:""}${e.prompt}`;w==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(n);let oe;if(m!==void 0)try{const i=X(m);if(i===null)throw new Error(`invalid fork source ${m}`);const u=await D().fork(i,n.node_id);oe=(await D().header(u)).path}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const g=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(n.node_id)},G){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[tn]=rn(i),await on(g,n)}const E=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){q("birth",performance.now()-t);const O=await nr(n,u,g);if(O==="started"||O==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await V(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await E.reserveSlot(n.node_id),$=ie?await un(n.node_id):null;if($?.verdict==="too_small"){E.releaseReservation(n.node_id);const i=cn($);throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(!ie||$?.verdict==="denied")return $?.verdict==="denied"&&E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:$?.verdict==="denied"?{reason:"app_memory",free_bytes:$.free_bytes,needed_bytes:$.needed_bytes}:{reason:"broker_cap",live_count:await E.occupancy(),hard_cap:Q().automaticReviveCap}}),{node:await p(n.node_id),frozen:!0,window:null,session:null};const be=await kn(n.node_id),{automaticReviveCap:xe}=Q();let F;try{F=await fe(n.node_id,{daemonEpoch:E.epoch(),cap:xe})}catch(i){if(!(i instanceof ue))throw i;return E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await p(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:F};let K;try{K=await qn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await L(F,{reason:"launch_failed"}),i}finally{E.releaseReservation(n.node_id)}if(K.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await L(F,{reason:"launch_failed"}),await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),U(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await sn(F,n.node_id,K.pid)==="shutdown")throw await L(F,{reason:"superseded"}),Z.teardown(n.node_id),U(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(l&&e.readiness==="await"){const i=await pn(n.node_id,K.exited);if(!i.ready){const u=Vn(n.node_id,i);v({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await be.explanation();throw await Jn(n.node_id,new Error(O??u.text)),U(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!s&&d!==null&&Bn("user").auto_open_child_viewers)try{const i=await mn(d);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await wn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:G});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=hn(u.pane))}}catch{}return{node:await p(n.node_id),frozen:!1,window:ae,session:de}}catch(h){throw C!==void 0&&f!==void 0&&await p(f)===null&&(H!==null?await qe(H,C):await Ue(C)),h}}c(ge,"spawnChildPrepared");async function ct(e){return ge(e)}c(ct,"spawnChild");async function rr(e){const r=Hn(e.cwd,e.profile_id).plans.get("node:start")??[];await Kn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await Y(e.node_id),contextDir:await J(e.node_id),jobDir:dn(e.node_id)},runtime:{isBirth:!0,canvasHome:an(),profile:e.profile_id??null}})}c(rr,"invokeBirthLifecycleHooks");const tr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function ut(e,r,o){const t=await p(e);if(t===null)throw k(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await pe(e),s=await J(e);try{await D().header(X(a)),Ce(s,Ee.R_OK)}catch(d){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${d.message}`)}return ge({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async d=>{const w=await J(d);ln(await Y(e),s,await Y(d),w,tr)})}c(ut,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,ut as forkNode,rr as invokeBirthLifecycleHooks,pe as resolveForkSource,Qn as resolveProfileId,Zn as resolveSpawner,ct as spawnChild,ge as spawnChildPrepared};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var t=(r,i)=>c(r,"name",{value:i,configurable:!0});import{openDb as l}from"../../../core/canvas/db.js";import{ApiError as m}from"../../../api/errors.js";import{usage as a}from"../../../core/errors.js";import{personId as w}from"../../../core/canvas/person-state.js";import{patchEnvironment as b}from"../../../core/environment-recipe.js";import{resolveRecipeRepositories as g}from"../../../core/environment-repos.js";import{appOf as v}from"../router.js";import{requireUsableProfile as y}from"./profiles.js";async function u(r){const{profileId:i,manifest:n}=await y(r,r.params.name),e=n.environment_id,o=e===void 0?void 0:await(await l()).prepare("SELECT kind FROM environments WHERE object = ?").get(e);if(e===void 0||o?.kind!=="blaxel")throw new m(400,"invalid_request",`profile ${i} does not run in a cloud environment`);return{profileId:i,environmentId:e}}t(u,"requireBlaxelEnvironment");async function _(r,i){const n=await l(),e=await n.prepare("SELECT setup_script, pi_packages, memory_mb, allow_pull_request_write, recipe_revision, image_revision, image_error FROM environments WHERE object = ?").get(i),o=await n.prepare("SELECT github_full_name AS full FROM environment_repos WHERE environment = ? ORDER BY position").all(i);return{profile_id:r,environment_id:i,repositories:o.map(s=>s.full),setup_script:e.setup_script,pi_packages:e.pi_packages,memory_mb:Number(e.memory_mb),allow_pull_request_write:e.allow_pull_request_write,recipe_revision:Number(e.recipe_revision),image_revision:e.image_revision===null?null:Number(e.image_revision),image_error:e.image_error}}t(_,"readEnvironment");async function E(r){const{profileId:i,environmentId:n}=await u(r);return{status:200,body:await _(i,n)}}t(E,"handleGet");function d(r,i){if(r==null||typeof r=="string")return r;throw a(`${i} must be a string or null`,{field:i})}t(d,"optionalText");async function h(r){if(r.principal.class==="broker"&&v(r.principal)!=="app:terminal")throw new m(403,"permission_error","only the person and terminal-app agents may change a cloud profile recipe");const{profileId:i,environmentId:n}=await u(r),e=r.body??{};if(e.repositories!==void 0&&(!Array.isArray(e.repositories)||e.repositories.some(f=>typeof f!="string")))throw a("repositories must be an array of owner/name strings",{field:"repositories"});if(e.allow_pull_request_write!==void 0&&typeof e.allow_pull_request_write!="boolean")throw a("allow_pull_request_write must be a boolean",{field:"allow_pull_request_write"});const o=d(e.setup_script,"setup_script"),s=d(e.pi_packages,"pi_packages"),p=e.repositories===void 0?void 0:await g(w(),e.repositories);return await b(n,{...p!==void 0?{repositories:p}:{},...o!==void 0?{setup_script:o}:{},...s!==void 0?{pi_packages:s}:{},...e.memory_mb!==void 0?{memory_mb:e.memory_mb}:{},...e.allow_pull_request_write!==void 0?{allow_pull_request_write:e.allow_pull_request_write}:{}}),{status:200,body:await _(i,n)}}t(h,"handleSet");const F=[{method:"GET",pattern:"/v1/profiles/:name/environment",handler:E},{method:"PUT",pattern:"/v1/profiles/:name/environment",handler:h}];export{F as environmentRoutes};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
var h=Object.defineProperty;var d=(o,e)=>h(o,"name",{value:e,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{getNode as m}from"../../../core/canvas/canvas.js";import{environmentOfNode as y}from"../environment-of.js";import{requiredEnv as c}from"./git-credential.js";import{invalidRequest as w,objectBody as _,requiredString as l}from"./validate.js";const k=5e4;async function v(o){const{principal:e}=o;if(e.class!=="broker")throw new r(403,"broker_only","feedback is filed by a node token");const t=[],i=_(o.body,["title","body"],t),f=l(i,"title",t),u=l(i,"body",t);t.length>0&&w("feedback request",t);const s=await m(e.node);if(s===null)throw new r(404,"node_not_found",`no node ${e.node}`);const b=await y(s.profile_id??null),p=`${u.slice(0,k)}
|
|
2
|
+
|
|
3
|
+
### Filed from
|
|
4
|
+
| | |
|
|
5
|
+
|---|---|
|
|
6
|
+
| node | \`${e.node}\` |
|
|
7
|
+
| environment | \`${b}\` |
|
|
8
|
+
| person | \`${e.sub}\` |
|
|
9
|
+
`,n=await fetch(`${c("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/feedback`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${c("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({title:f.slice(0,256),body:p})}),a=await n.json().catch(()=>({}));if(!n.ok||typeof a.url!="string")throw new r(502,"github_service_failed",`the GitHub service answered ${n.status} without an issue url`);return{status:200,body:{url:a.url}}}d(v,"handleFeedback");const T=[{method:"POST",pattern:"/v1/feedback",handler:v}];export{T as feedbackRoutes};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RouteTable } from '../router.js';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
export declare function requiredEnv(name: string): string;
|
|
3
|
+
/** The GitHub app's internal route: a token limited to `repositories` for the person (with pull_requests write too when `allowPullRequestWrite`), and the commit author for their GitHub link (null when unlinked). */
|
|
4
|
+
export declare function mintInstallationToken(sub: string, repositories: string[], allowPullRequestWrite?: boolean): Promise<{
|
|
4
5
|
token: string;
|
|
5
6
|
expires_at: string;
|
|
6
7
|
author: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var d=(o,t)=>_(o,"name",{value:t,configurable:!0});import{ApiError as n}from"../../../api/errors.js";import{openDb as f}from"../../../core/canvas/db.js";import{getNode as w}from"../../../core/canvas/canvas.js";import{environmentOfNode as m,recipeOf as g}from"../environment-of.js";import{invalidRequest as b,objectBody as v,optionalString as y,requiredString as k}from"./validate.js";function p(o){const t=process.env[o];if(t===void 0||t==="")throw new n(500,"github_service_unconfigured",`${o} is not set on this control plane`);return t}d(p,"requiredEnv");async function E(o){const{principal:t}=o;if(t.class!=="broker")throw new n(403,"broker_only","git credentials are issued to a node token");const l=o.params.environment_id??"",r=await w(t.node);if(r===null)throw new n(404,"node_not_found",`no node ${t.node}`);if(await m(r.profile_id??null)!==l)throw new n(403,"not_your_environment",`this node does not run in environment ${l}`);const s=[],e=v(o.body,["host","path"],s),i=k(e,"host",s);if(y(e,"path",s),s.length>0&&b("git credential request",s),i!=="github.com")throw new n(400,"unsupported_git_host",`only github.com credentials are issued, not ${i}`);const a=(await g(l))?.repositories.map(h=>h.github_full_name)??[];if(a.length===0)throw new n(409,"no_recipe_repositories",`environment ${l} has no recipe repositories`);const u=await(await f()).prepare("SELECT allow_pull_request_write FROM environments WHERE object = ?").get(l),c=await x(t.sub,a,u?.allow_pull_request_write===!0);return{status:200,body:{username:"x-access-token",password:c.token,expiry:c.expires_at}}}d(E,"handleGitCredential");async function x(o,t,l=!1){const r=await fetch(`${p("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/installation-token`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${p("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({sub:o,repositories:t,allow_pull_request_write:l})}),s=await r.text(),e=s===""?{}:JSON.parse(s);if(!r.ok){const a=typeof e.error=="object"?e.error?.code:e.code,u=(typeof e.error=="object"?e.error?.message:e.message)??`the GitHub service answered ${r.status}`;throw r.status===409&&(a==="repositories_span_installations"||a==="github_not_connected")?new n(409,a,u,{repositories:t}):new n(502,"github_service_failed",u,{status:r.status,...a===void 0?{}:{code:a}})}if(typeof e.token!="string"||typeof e.expires_at!="string")throw new n(502,"github_service_failed","the GitHub service answered without a token and expiry");const i=e.author;if(i===void 0)throw new n(502,"github_service_failed","the GitHub service answered without an author field");if(i!==null&&(typeof i.name!="string"||typeof i.email!="string"))throw new n(502,"github_service_failed","the GitHub service answered a malformed author");return{token:e.token,expires_at:e.expires_at,author:i===null?null:{name:i.name,email:i.email}}}d(x,"mintInstallationToken");const C=[{method:"POST",pattern:"/v1/environments/:environment_id/git-credential",handler:E}];export{C as gitCredentialRoutes,x as mintInstallationToken,p as requiredEnv};
|