@north-light/cli 0.3.754 → 0.3.756
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 +1 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/health.d.ts +0 -54
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/cli.js +8 -9
- package/dist/clients/attach/viewer.js +481 -481
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/bootstrap.js +1 -1
- package/dist/core/canvas/boot.d.ts +0 -25
- package/dist/core/canvas/boot.js +1 -1
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +5 -5
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +4 -4
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/runs/operations.js +7 -7
- package/dist/core/scoped-state/db.js +2 -2
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/crtrd.js +18 -20
- package/dist/daemon/manage.js +3 -3
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +0 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/dist/build-root.js +0 -9
- package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
- package/packages/crouter-api/dist/commands/sys.js +1 -2
- package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
- package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
- package/packages/crouter-api/dist/core/directory/join.js +18 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
- package/packages/crouter-api/dist/core/grants/sync.js +2 -2
- package/packages/crouter-api/dist/core/io.js +0 -5
- package/packages/crouter-api/dist/core/layout.js +2 -19
- package/packages/crouter-api/dist/core/runs/operations.js +6 -0
- package/packages/crouter-api/dist/daemon/api/map.js +0 -16
- package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
- package/packages/crouter-api/dist/daemon/manage.js +1 -1
- 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/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -1
- package/dist/core/feed/inbox-migrate.d.ts +0 -11
- package/dist/core/feed/inbox-migrate.js +0 -3
- package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
- package/dist/core/graph/bodies-boot-copy.js +0 -1
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -4
- package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
- package/dist/core/layout-migrate/loose-keys.js +0 -1
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -1
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -11
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -3
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -3
- package/dist/daemon/boot-migrations.d.ts +0 -14
- package/dist/daemon/boot-migrations.js +0 -1
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -1
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -3
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -4
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -2
- package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
- package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
- package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
- package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
- package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
- package/packages/crouter-api/dist/core/locked-file.js +0 -121
- package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
- package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
- package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
- package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/packages/crouter-api/dist/migrations/activation.js +0 -46
package/dist/core/io.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;try{if((w(t,{throwIfNoEntry:!1})?.size??0)+Buffer.byteLength(s,"utf8")>
|
|
1
|
+
var x=Object.defineProperty;var i=(e,t)=>x(e,"name",{value:t,configurable:!0});import{appendFileSync as _,statSync as w}from"node:fs";import{CrtrError as u}from"./errors.js";import{ExitCode as a}from"../types.js";import{PREVIEW_RESULT_PATH_ENV as h}from"./preview-result-path.js";import{renderError as A}from"./render.js";import{ApiError as E}from"../api/index.js";let p=!1,f;const v=256*1024;function B(e){const t=process.env[h];f=t===void 0||t===""?void 0:{path:e,jsonl:[]}}i(B,"beginPreview");function y(e){const t=process.env[h];if(t===void 0||t==="")return;const s=`${JSON.stringify({path:f?.path??"",...e})}
|
|
2
|
+
`;try{if((w(t,{throwIfNoEntry:!1})?.size??0)+Buffer.byteLength(s,"utf8")>v)return;_(t,s,"utf8")}catch{}}i(y,"publishPreview");function G(e){f!==void 0&&(e!=null?y({result:e}):(f.jsonl.length>0||f.error!==void 0)&&y({...f.jsonl.length>0?{jsonl:f.jsonl}:{},...f.error===void 0?{}:{error:f.error}}))}i(G,"publishPreviewResult");function g(e){f?.jsonl.push(e)}i(g,"recordPreviewLine");function F(e){try{const t=JSON.parse(e);t!==null&&typeof t=="object"&&!Array.isArray(t)&&g(t)}catch{}}i(F,"recordPreviewJsonLine");function K(e){f!==void 0&&(f.error=e)}i(K,"recordPreviewError");function q(e){p=e}i(q,"setJsonOutput");function z(){return p}i(z,"isJsonOutput");class m extends u{static{i(this,"InputError")}payload;constructor(t,s=a.USAGE){super(t.error,t.message,s,{...t}),this.name="InputError",this.payload=t}}async function D(){if(process.stdin.isTTY)return"";const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}i(D,"readStdinRaw");async function V(e=200){return process.stdin.isTTY?"":await new Promise(t=>{const s=[];let n=!1;const r=i(()=>{n||(n=!0,clearTimeout(c),process.stdin.removeListener("data",o),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d),process.stdin.pause(),t(Buffer.concat(s).toString("utf8")))},"finish"),o=i(b=>s.push(b),"onData"),l=i(()=>r(),"onEnd"),d=i(()=>r(),"onError"),c=setTimeout(r,e);process.stdin.on("data",o),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}i(V,"peekStdinRaw");function Y(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
3
3
|
`)}i(Y,"emit");function H(e){g(e),process.stdout.write(JSON.stringify(e)+`
|
|
4
4
|
`)}i(H,"emitLine");function M(e){return new Promise(t=>{let s=!1;const n=i(o=>{o.code==="EPIPE"&&r(!1)},"onErr"),r=i(o=>{s||(s=!0,process.stdout.off("error",n),t(o))},"finish");process.stdout.on("error",n);try{process.stdout.write(e,o=>r(o==null))}catch{r(!1)}})}i(M,"writeStdout");function X(e){process.stderr.write(e+`
|
|
5
|
-
`)}i(X,"diag");function S(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(S,"isRecord");function
|
|
5
|
+
`)}i(X,"diag");function S(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(S,"isRecord");function T(e){if(e instanceof m)return e.payload;const t=e.details!==void 0?e.details:{},s=t.primaryCompleted===!0&&t.result!==null&&typeof t.result=="object"&&!Array.isArray(t.result)?O(t.result):void 0,n=t.next!==void 0?t.next:"Inspect the error and adjust the call. See -h for the schema.",r={error:e.code,message:e.message,received:t.received,field:t.field,...typeof t.http_status=="number"?{http_status:t.http_status}:{},...typeof t.retry_after_s=="number"?{retry_after_s:t.retry_after_s}:{},...S(t.details)?{details:t.details}:{}};return s===void 0?{...r,next:n}:{...r,primaryCompleted:!0,result:s,next:n}}i(T,"payloadOf");function O(e){const t=new WeakSet;try{const s=JSON.stringify(e,(n,r)=>{if(typeof r=="bigint")return{$crtrType:"bigint",value:r.toString()};if(typeof r=="number"&&!Number.isFinite(r))return{$crtrType:"number",value:String(r)};if(typeof r>"u"||typeof r=="function"||typeof r=="symbol")return{$crtrType:typeof r};if(r!==null&&typeof r=="object"){if(t.has(r))return{$crtrType:"circular"};t.add(r)}return r});if(s!==void 0){const n=JSON.parse(s);if(n!==null&&typeof n=="object"&&!Array.isArray(n))return n}}catch{}return{$crtrType:"unavailable",message:"The completed primary result could not be represented as JSON."}}i(O,"jsonSafeResult");const N={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"};function R(e,t,s={}){if(e.code==="daemon_restarting")return new u("daemon_restarting",e.message,a.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(e.code==="daemon_unavailable")return new u("daemon_unavailable",e.message,a.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(e.code==="northlight_unreachable"){const d=e.details?.next;return new u("northlight_unreachable",e.message,a.NETWORK,{next:typeof d=="string"&&d!==""?d:"Check this computer's internet connection, then retry."})}if(e.code==="model_sign_in_required"){const d=e.details?.url;return new m({error:e.code,message:e.message,next:typeof d=="string"?`Ask the person to sign in at ${d}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof d=="string"?{details:{url:d}}:{}},a.USAGE)}const n=e.details,r=$(e,n,s.providerCall===!0);if(e.status===503||s.providerCall===!0&&e.status===504&&r.code!==void 0){const d=r.code??e.code,c={next:r.next??t??"Retry the command; if it persists, inspect the unavailable service named in the error."};return r.details!==void 0&&(c.details=r.details),r.code!==void 0&&(r.field!==void 0&&(c.field=r.field),r.received!==void 0&&(c.received=r.received),r.retryAfterS!==void 0&&(c.retry_after_s=r.retryAfterS)),new u(d,e.message,a.NETWORK,c)}const o=Array.isArray(n?.violations)?n.violations.map(d=>`${String(d.field)} ${String(d.problem)}${d.received!==void 0?` (received ${JSON.stringify(d.received)})`:""}`):[],l=n&&typeof n.error=="string"&&typeof n.message=="string"&&typeof n.next=="string"?n:{error:r.code??N[e.status]??e.code,...r.field!==void 0?{field:r.field}:{},...r.received!==void 0?{received:r.received}:{},...r.retryAfterS!==void 0?{retry_after_s:r.retryAfterS}:{},...r.details!==void 0?{details:r.details}:{},message:o.length>0?`${e.message}: ${o.join("; ")}`:e.message.trim()!==""?e.message:`request refused (HTTP ${e.status}, ${e.code}) with no message`,next:r.next??(n?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??t??(r.retryAfterS!==void 0?`Wait ${r.retryAfterS}s, then retry; do not retry sooner.`:e.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":e.status===404&&r.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new m(l,j(l.error,e.status))}i(R,"apiErrorToCliError");function $(e,t,s){const n=i(o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o),"snake");if(s&&e.origin!==void 0&&e.origin!=="provider"&&n(e.code)){const o={code:e.code};return(e.status===503||e.status===504)&&(o.next=e.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),S(e.details)&&(o.details=e.details),e.param!==void 0&&(o.field=e.param),typeof e.retryAfterS=="number"&&(o.retryAfterS=e.retryAfterS),o}if(e.origin!=="provider"||t===void 0||t===null||typeof t!="object")return{};const r={};return typeof t.status=="number"&&n(t.code)&&(r.code=t.code),typeof t.next=="string"&&t.next.trim()!==""&&(r.next=t.next),typeof t.field=="string"&&t.field!==""?r.field=t.field:e.param!==void 0&&(r.field=e.param),t.received!==void 0&&t.received!==null&&(r.received=t.received),typeof e.retryAfterS=="number"&&(r.retryAfterS=e.retryAfterS),r}i($,"providerSupplied");function j(e,t){return e==="not_found"||t===404?a.NOT_FOUND:e==="ambiguous"?a.AMBIGUOUS:a.USAGE}i(j,"exitForCliCode");function P(e){if(e instanceof E){P(R(e));return}if(e instanceof u){const n=T(e);f!==void 0&&y({error:n});const r=p?JSON.stringify(n,null,2):A(n);process.stdout.write(r+`
|
|
6
6
|
`),process.exitCode=e.exitCode;return}const t=e,s=t!=null&&typeof t.message=="string"?t.message:String(e);process.stderr.write(JSON.stringify({error:"internal",message:s,next:"This is a crtr bug, not a bad call. Retry; if it persists, report it."},null,2)+`
|
|
7
|
-
`),process.exitCode=a.GENERAL}i(P,"handle");export{m as InputError,
|
|
7
|
+
`),process.exitCode=a.GENERAL}i(P,"handle");export{m as InputError,v as PREVIEW_RESULT_MAX_BYTES,R as apiErrorToCliError,B as beginPreview,X as diag,Y as emit,H as emitLine,P as handle,z as isJsonOutput,V as peekStdinRaw,G as publishPreviewResult,D as readStdinRaw,K as recordPreviewError,F as recordPreviewJsonLine,g as recordPreviewLine,q as setJsonOutput,M as writeStdout};
|
package/dist/core/layout.d.ts
CHANGED
|
@@ -39,6 +39,4 @@ export declare function describeLayoutMarker(bytes: Uint8Array): string;
|
|
|
39
39
|
* never rewritten: an empty or damaged one means the volume lost a write, and
|
|
40
40
|
* stamping the current version over it would assert a layout nobody verified. */
|
|
41
41
|
export declare function assertSupportedLayoutMarker(path: string): void;
|
|
42
|
-
/** A missing version on an occupied volume is never initialized by daemon startup. */
|
|
43
|
-
export declare function layoutNeedsMigration(): boolean;
|
|
44
42
|
export declare function initializeEmptyLayout(): void;
|
package/dist/core/layout.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var $=Object.defineProperty;var
|
|
2
|
-
`,384)}
|
|
1
|
+
var $=Object.defineProperty;var t=(o,r)=>$(o,"name",{value:r,configurable:!0});import{existsSync as m,mkdirSync as d,readFileSync as S,statSync as g}from"node:fs";import{homedir as R,userInfo as A}from"node:os";import{basename as x,dirname as a,isAbsolute as _,join as n,resolve as f}from"node:path";import{envHomeOverride as z}from"../shared/env.js";import{readConfig as C}from"./config.js";import{isCloudRole as O}from"./canvas/person-state.js";import{publishFileExclusive as T,syncDirectory as h}from"./fs-utils.js";const p="1";function i(){const o=f(z()||(process.platform==="linux"?"/":n(R(),".crouter")));if(k()&&o===L())throw new Error(`refusing to use the account's real crouter root ${o} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return o}t(i,"layoutRoot");function k(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}t(k,"runningUnderNodeTest");let s;function L(){if(s===void 0)try{s=f(A().homedir,".crouter")}catch{s=null}return s}t(L,"accountLayoutRoot");function u(){return n(i(),"runtime")}t(u,"runtimeRoot");function v(){return n(i(),"user")}t(v,"userRoot");function w(){return n(i(),"apps")}t(w,"appsRoot");function y(){return n(u(),"secrets")}t(y,"secretsDir");function W(o,r){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(r))throw new Error(`invalid profile id: ${r}`);const e=l(o);return{dir:n(e.profiles,r),env:n(y(),"env",x(e.root),r),home:e.home}}t(W,"profileSpace");function E(){return process.platform==="linux"?"/run/crtr":u()}t(E,"socketDir");function c(){return n(u(),"layout")}t(c,"layoutVersionFile");function F(){const r=(O()?void 0:C("user").paths?.user_files)??(process.platform==="linux"?n(v(),"files"):a(i()));if(!_(r))throw new Error("paths.user_files must be absolute");return f(r)}t(F,"userFilesRoot");function l(o){const r=o.startsWith("app:")?o.slice(4):o;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r)||r==="."||r==="..")throw new Error(`invalid app id: ${o}`);const e=n(w(),r);return{root:e,profiles:n(e,"profiles"),conversations:n(e,"conversations"),nodes:n(e,"nodes"),files:n(e,"files"),home:n(e,"home"),cache:n(e,"cache")}}t(l,"appSpace");function X(o,r){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r))throw new Error(`invalid cron id: ${r}`);return n(l(o).root,"crons",r)}t(X,"cronFolder");function Y(o){const r=l(o);return process.platform==="linux"?r.home:x(r.root)==="terminal"?F():r.home}t(Y,"appProcessHome");function D(o){const r=Array.from(o.subarray(0,32),e=>e===92?"\\\\":e===34?'\\"':e===10?"\\n":e===13?"\\r":e===9?"\\t":e>=32&&e<127?String.fromCharCode(e):`\\x${e.toString(16).padStart(2,"0")}`).join("");return`${o.length} bytes, preview "${r}"${o.length>32?"\u2026":""}`}t(D,"describeLayoutMarker");function H(o){const r=S(o);if(r.toString("utf8").trim()!==p)throw new Error(`unsupported runtime layout version: ${o} holds ${D(r)}; expected "${p}"`)}t(H,"assertSupportedLayoutMarker");function q(){m(c())&&H(c());for(const o of[u(),v(),w(),y()]){const r=d(o,{recursive:!0,mode:448});if(r!==void 0){for(let e=o;h(e),e!==r;e=a(e));h(a(r))}}if(d(E(),{recursive:!0,mode:493}),process.platform==="linux"&&(g(E()).mode&511)!==493)throw new Error("launcher socket directory must be mode 0755");m(c())||T(c(),`${p}
|
|
2
|
+
`,384)}t(q,"initializeEmptyLayout");export{p as LAYOUT_VERSION,Y as appProcessHome,l as appSpace,w as appsRoot,H as assertSupportedLayoutMarker,X as cronFolder,D as describeLayoutMarker,q as initializeEmptyLayout,i as layoutRoot,c as layoutVersionFile,W as profileSpace,u as runtimeRoot,y as secretsDir,E as socketDir,F as userFilesRoot,v as userRoot};
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var Ae=Object.defineProperty;var
|
|
1
|
+
var Ae=Object.defineProperty;var u=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as Z}from"node:crypto";import{ApiError as Te}from"../../api/errors.js";import{CrtrError as Le}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as K,relative as ke,resolve as xe,sep as We,join as Fe}from"node:path";import{SessionManager as qe}from"@earendil-works/pi-coding-agent";import{covers as j}from"@north-light/identity";import{openDb as Y,withCanvasWrite as U}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as ee}from"../canvas/sessions.js";import{getNode as v,nodeFiles as $e,removeNodeFiles as Pe,updateNode as Be}from"../canvas/canvas.js";import{fullName as Je}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{latestExecutionForNode as Ye,liveExecutionForNode as te}from"../canvas/executions.js";import{conversationStore as ne,isConversationNotFound as Ge}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Xe}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as ze}from"../canvas/deliveries.js";import{readNodeRecap as Qe}from"../canvas/node-recap.js";import{enqueueNodeMail as Ve}from"../feed/messages.js";import{recordInitialInput as Ze}from"./initial-input.js";import{newestReportBody as Ke}from"../feed/reports.js";import{ensureAppProfile as ae,loadExactProfileManifest as se}from"../profiles/manifest.js";import{stopNodeSandboxes as re}from"../spaces/stop.js";import{deleteNodeSandboxes as et}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as tt}from"../runtime/broker-request.js";import{interruptLive as nt}from"../runtime/interactive-deliver.js";import{isBrokerLive as ie}from"../runtime/model-swap.js";import{newNodeId as at}from"../runtime/nodes.js";import{reviveNode as G}from"../runtime/revive.js";import{spawnChildPrepared as st}from"../runtime/spawn.js";import{isPortableModelToken as rt}from"../runtime/launch.js";import{parseDurationMs as it}from"../wake.js";import{expandModelCandidates as ot,parseModelSpec as dt}from"../model-routes.js";import{payerOfGrant as X}from"../grants/mirror.js";import{ownsWithoutRow as ct}from"../grants/owner.js";import{environmentPayerOfProfile as ut}from"../ledger/index.js";import{runUsage as mt}from"../ledger/read.js";import{ZERO_RUN_USAGE as lt}from"../../api/dto/run-events.js";import{isolatedBrokerLauncherAvailable as ft}from"../runtime/host.js";import{blaxelEnvironmentOf as pt}from"../runtime/blaxel-environment.js";import{resolveRunKind as _t,resolveRunModel as wt}from"../runtime/launch-target.js";import{transcriptMessages as gt}from"../runtime/session-cycles.js";import{originFor as oe}from"../runtime/stamp/protocol.js";import{readOutputRequest as Et,readOutputResult as de}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as ce}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as yt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as ht}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as Rt}from"../../daemon/runs/observer.js";import{closeNode as ue}from"../runtime/close.js";import{parseScope as St}from"@north-light/identity";import{appendRunEvent as me,lockRunRoot as Nt,subscribeRunEvents as bt}from"./events.js";import{runActivity as vt}from"./activity.js";import{cancelOpenQuestions as le,openNoticeIds as Ot,openQuestionIds as fe}from"./questions.js";import{appSpace as z}from"../layout.js";import{ensureAppSpace as Dt}from"../spaces/space.js";import{assertUploadsUsable as pe,resolveStorageUrls as Mt}from"../storage/attachments.js";import{storageClient as At,storageConfig as It}from"../storage/client.js";import{deleteRunFiles as Tt,deleteUploadRow as Lt,insertUploadUses as _e,releaseRunUploads as Ct,runUsesPath as kt}from"../storage/tables.js";import{abortProviderCalls as we}from"../providers/inflight.js";import{filterAsync as ge,mapAsync as q}from"../async-array.js";import{blobStore as xt}from"../blobs/index.js";import{emitEvent as Wt}from"../events/emit.js";const Ee=u((e,t,a,n,d)=>Mt(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),Ft=3e3;class R extends Error{static{u(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,f,i,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=f,this.scope=i,this.retryable=s}}const S=u((e,t)=>new R(400,"invalid_request",e,t),"invalid"),Q=u(()=>new R(404,"not_found","run not found"),"missing"),I=u(async()=>await Y(),"db");async function $(e,t,a=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw Q();return n}u($,"ownedRun");const ye=["waiting_on_user","idle","settled"];async function k(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await I()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
|
|
2
2
|
(n.last_settled_at IS NULL OR EXISTS (
|
|
3
3
|
SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
|
|
4
4
|
AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
|
|
5
5
|
WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
|
|
6
|
-
)) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await
|
|
6
|
+
)) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await yt(e)?"running":(await fe(e.node_id)).length?"waiting_on_user":await(await I()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
|
|
7
7
|
WHERE n.run_id = ? AND ${ze("d","'armed', 'pending', 'handed_off'")}
|
|
8
|
-
AND (n.status IN ('active', 'idle') OR ${Xe("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}
|
|
8
|
+
AND (n.status IN ('active', 'idle') OR ${Xe("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}u(k,"runStatus");async function na(e){const t=await v(e);return t!==null&&await k(t)==="running"}u(na,"runIsRunning");async function H(e){await ee(e.node_id),e=await v(e.node_id)??e;const t=await k(e),a=t==="settled"?[]:await fe(e.node_id),n=await Ke(e.node_id)||void 0,d=t==="settled"?await ht(e):null,f=d?.kind==="result"?await de(e.node_id):void 0,i=Qe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...i?{recap:i}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await Ot(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:await mt(e.node_id),payer:await X(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await vt(e.node_id,t),worktree:await qt(e.node_id)}}u(H,"runObject");async function qt(e){const t=await Ye(e);if(t===null||t.runner!=="blaxel"||t.launchJson===null)return null;const a=JSON.parse(t.launchJson).worktree;return typeof a?.repository=="string"&&typeof a.branch=="string"?{repository:a.repository,branch:a.branch}:null}u(qt,"runWorktree");const V=864e5,he=255;function aa(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>he)throw S(`Idempotency-Key must be 1-${he} characters`);return e}}u(aa,"idempotencyKeyOf");function x(e){if(Ce()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}u(x,"cloudPersonScope");function W(e,t){const a=x(e);return a===void 0?t:`${a}:${t}`}u(W,"personKey");async function P(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await Y();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=V)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}u(P,"findIdempotent");async function Re(e,t,a,n,d,f,i){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-V).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(f),i)}u(Re,"recordIdempotent");async function sa(e=Date.now()){return Number((await(await Y()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-V).toISOString())).changes)}u(sa,"pruneExpiredIdempotencyKeys");async function Se(e,t,a,n,d,f,i=!1){const s=d.text;let c=0;return{messageId:(await Ve(t,{kind:"message",label:s.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:f?{body:s,...i?{steer:!0}:{}}:{body:s,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:u(async(h,o)=>{d.uses.length&&(await pe(a,x(n),d.uses,h),await _e(d.uses.map(({upload_id:m,path:y,blob_key:r})=>({upload_id:m,path:y,blob_key:r,run_id:t})),h)),c=(await me(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:c}}u(Se,"acceptRunMessage");class Ne extends Error{static{u(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Ht=1440*60*1e3;function be(e){const t=typeof e=="string"?it(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Ht)throw S("deadline must be at most 24h","deadline");return t}u(be,"parseRunDeadlineMs");async function ra(e,t,a,n=Ee){if(t.isolated&&!ft()&&await pt((t.profile===void 0?await ae(e.grantee):se(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&be(t.deadline);const{causedBy:d,...f}=t,i=Z("sha256").update(JSON.stringify(f)).digest("hex");if(a){const o=await P(e.grantee,W(e.sub,a),i);if(o){const m=await $(o.run_id,e.grantee);return!m.pi_pid&&await k(m)==="running"&&(t.output_schema!==void 0&&!m.outcome_at&&await Et(m.node_id)===null&&await de(m.node_id)===void 0&&await ce(m.node_id,"terminal",t.output_schema),await G(m.node_id,{resume:!0,capacity:"freeze"})),o.response}}await Dt(e.grantee);const s=t.profile===void 0?await ae(e.grantee):se(t.profile),c=s.manifest.grantee??"app:terminal";if(await ut(s.profileId)!==null&&!ct(c,e.sub,e.grant))throw new R(403,"app_environment",`an app environment starts runs for ${c} only, not for ${e.sub}`,"profile");if(c!==e.grantee){const o=`crtr:memory:rw:${c}:profile:${s.profileId}`;if(!e.resolved.some(m=>j(m,o))||t.scopes!==null&&!t.scopes.some(m=>j(m,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(rt(o)){if(o.includes("/")&&await X(e.grant)!=="app"){const m=o.lastIndexOf("/"),y=o.slice(0,m),r=o.slice(m+1);if(["ultra","strong","medium","light"].includes(r)&&(await ot({kind:"logical",family:y,strength:r,spec:o},z(e.grantee).files,s.profileId)).every(E=>E.family!==y))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(dt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const _=await at(),h=Fe(z(e.grantee).nodes,_);if(t.isolated&&t.cwd!==void 0){const o=ke(h,xe(t.cwd));if(!K(t.cwd)||o===".."||o.startsWith(`..${We}`)||K(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(_,e.grantee,t.prompt,void 0,x(e.sub)),m=o.text,y=t.message===void 0?void 0:await n(_,e.grantee,t.message,o.uses.map(p=>p.path),x(e.sub)),r=await X(e.grant);let E;try{const p=wt(s,t.model);await st({kind:_t(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:z(e.grantee).files,profile:s.profileId,prompt:m,nodeId:_,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...p===void 0?{}:{model:p},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+be(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:_,event_cursor:1},withinCreate:u(async(g,O)=>{if(a){const N=await P(e.grantee,W(e.sub,a),i,g);if(N)throw new Ne(N)}const A=o.uses;if(A.length&&(await pe(e.grantee,x(e.sub),A,g),await _e(A.map(({upload_id:N,path:F,blob_key:T})=>({upload_id:N,path:F,blob_key:T,run_id:_})),g)),E={run_id:_,node_id:_,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:r,status:"running",created_at:O.created,metadata:t.metadata,sequence_number:0},await me(g,_,_,"run.started",{scopes:t.scopes,payer:r,usage:lt}),y){const N=await Se(g,_,e.grantee,e.sub,y,!1);E.message={run_id:_,message_id:N.messageId,sequence_number:N.sequence}}else await Ze(_,e.grantee,m);a&&await Re(g,e.grantee,W(e.sub,a),i,_,E,O.created)},"withinCreate")},t.output_schema===void 0?void 0:async g=>{await ce(g,"terminal",t.output_schema)})}catch(p){if(p instanceof Ne)return p.winner.response;if(t.model!==void 0&&p instanceof Le&&p.code==="usage")throw S(p.message,"model");if(p instanceof Te&&(p.code==="isolated_run"||p.code==="invalid_request")){const g=p.details&&typeof p.details=="object"&&"param"in p.details&&typeof p.details.param=="string"?p.details.param:void 0;throw new R(p.status,p.code,p.message,g)}throw p}if(!E)throw new Error("run creation did not commit");return E}finally{await Ut(_)}}u(ra,"startRun");async function Ut(e){try{if(await v(e)!==null)return;const t=await xt();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){Wt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}u(Ut,"discardUncommittedAttachments");async function ia(e,t){let a;if(t.after)try{const s=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!s||typeof s!="object"||!("activity"in s)||typeof s.activity!="string"||!("id"in s)||typeof s.id!="string")throw new Error("invalid cursor");a={activity:s.activity,id:s.id}}catch{throw S("invalid list cursor","after")}const n=await(await I()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
|
|
9
9
|
WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}${t.sub===void 0?"":" AND sub = ?"}
|
|
10
|
-
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await ge(await q((await ge(n,async({node_id:
|
|
10
|
+
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await ge(await q((await ge(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:c})=>!a||s<a.activity||s===a.activity&&c<a.id),async s=>({root:await v(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await k(s)===t.status),f=d.slice(0,t.limit),i=f.at(-1);return{runs:await q(f,async({root:s})=>await H(s)),next:d.length>t.limit&&i?Buffer.from(JSON.stringify({activity:i.activity,id:i.root.node_id})).toString("base64url"):null}}u(ia,"listRuns");async function oa(e,t,a){const n=await $(e,t),d=u(async()=>await H(await $(e,t)),"read");return!a||ye.includes(await k(n))?await d():new Promise((f,i)=>{let s=u(()=>{},"unsubscribe");const c=u(()=>{clearTimeout(y),clearInterval(m),s()},"settle"),_=u(async()=>{c();try{f(await d())}catch(r){i(r)}},"finish"),h=u(async()=>{ye.includes(String((await d()).status))&&await _()},"check"),o=u(()=>{h().catch(r=>{c(),i(r)})},"run"),m=setInterval(o,250),y=setTimeout(()=>{_()},a*1e3);bt(e,o).then(r=>{s=r},r=>{c(),i(r)})})}u(oa,"waitRun");const $t=5;async function da(e,t,a=Ee,n=!0,d,f=!0){const i=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",c=Z("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),_=u(async o=>{const m=await v(e.node_id),y=await(await I()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return m&&!i&&n&&!m.pi_pid&&y&&await G(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await P(s,W(e.sub,d),c);if(o)return _(o.response)}if(i)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const m=await a(e.node_id,s,t,void 0,x(e.sub)),y=await U(async r=>{if(d){const g=await P(s,W(e.sub,d),c,r);if(g)return{replayed:g.response}}if(m.uses.length){await Nt(r,e.node_id);for(const g of m.uses)if(await kt(e.node_id,g.path,r))return"path_taken"}await h?.(e.node_id);const E=await Se(r,e.node_id,s,e.sub,m,n,n&&f),p={run_id:e.node_id,message_id:E.messageId,sequence_number:E.sequence};return d&&await Re(r,s,W(e.sub,d),c,e.node_id,p,new Date().toISOString()),{result:p}});if(y==="path_taken"){if(o>=$t)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in y?_(y.replayed):(n&&!e.pi_pid&&await G(e.node_id,{resume:!0,capacity:"freeze"}),y.result)}}u(da,"messageRun");async function Pt(e){const t=u(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await v(e);if(!n)throw Q();if(!ie(n)){if(n.streaming)throw t();return}const d=(await te(e))?.executionId;try{await nt(e)==="turn"&&we({nodes:[e]});return}catch(f){if(!(f instanceof tt))throw f;const i=await v(e);if(!i)throw Q();if(!i.streaming)return;if(a===0&&ie(i)&&(await te(e))?.executionId!==d)continue;throw t()}}throw t()}u(Pt,"interruptNode");async function ca(e,t="stop"){const a=t==="stop"?(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>Pt(n))),await H(await v(e.node_id)??e)}u(ca,"interruptRun");async function ua(e,t={}){const a=(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(i=>i.node_id);we({run:e.node_id});const n=[];if(await k(e)!=="settled")n.push(...(await ue(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const i of a){if(i===e.node_id)continue;const s=await v(i);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...(await ue(i,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await le({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(i=>re(i,"run_canceled")))).some(i=>!i.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await v(e.node_id);return await H(f??e)}u(ua,"cancelRun");const ve=200;async function ma(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>ve)throw S(`name exceeds ${ve} characters`,"name");const n=await Be(e.node_id,{name:a});return n.window&&je(n.window,Je(n)),await H(n)}u(ma,"renameRun");async function la(e,t={config:It,client:At}){await le({run_id:e.node_id},"the run was deleted");const a=await U(async c=>(await c.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await c.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(_=>_.node_id)));if((await Promise.all(a.map(c=>re(c,"run_deleted",{deleting:!0})))).some(c=>!c.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await et(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await q(a,async c=>{const _=await $e(c);if(_.app===null)throw new Error(`run node missing during deletion: ${c}`);return _}),f=await(await I()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:c}of f)try{await ne().delete(c)}catch(_){if(!Ge(_))throw _}const i=await U(async c=>{for(const m of a){const y=await Ue(c,m);y!==null&&y.deleted_at===null&&await He(c,y)}const _=await Ct([e.node_id],c);await Tt([e.node_id],c),await c.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await c.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await c.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await c.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:m}of o)await c.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(m,m);return _});for(const c of d)await Pe(c);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Bt(i,t)}}u(la,"deleteRun");async function Bt(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(i=>a.deleteUpload(i).then(async()=>{await Lt(i),n.add(i)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(i=>{f=setTimeout(i,t.budgetMs??Ft),f.unref?.()})]),clearTimeout(f),e.length-n.size}u(Bt,"deleteReleasedUploads");async function fa(e,t,a){await $(e,t),await ee(e);const n=await U(async r=>{const E=await r.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),p=new Map;for(const b of E)p.set(b.node_id,(await r.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(b.node_id)).map(l=>l.session_id));const O=(await r.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await r.prepare(`SELECT node_id, sequence_number FROM run_events
|
|
11
11
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
|
|
12
|
-
ORDER BY sequence_number`).all(e,O),N=await
|
|
12
|
+
ORDER BY sequence_number`).all(e,O),N=await r.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
|
|
13
13
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
|
|
14
|
-
ORDER BY sequence_number`).all(e,O),F=await
|
|
14
|
+
ORDER BY sequence_number`).all(e,O),F=await r.prepare(`SELECT node_id, sequence_number, ts, body_json FROM run_events
|
|
15
15
|
WHERE run_id = ? AND sequence_number <= ? AND type = 'file.sent'
|
|
16
|
-
ORDER BY sequence_number`).all(e,O),T=new Set((await
|
|
16
|
+
ORDER BY sequence_number`).all(e,O),T=new Set((await r.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=F.flatMap(b=>{const l=JSON.parse(b.body_json);return T.has(l.file_id)?[{file_id:l.file_id,node_id:b.node_id,name:l.name,media_type:l.media_type,size:l.size,sequence_number:Number(b.sequence_number),ts:b.ts}]:[]});return{nodes:E,sessionIds:p,latestSequence:O,completed:A,deltas:N,files:B}}),{nodes:d,sessionIds:f,latestSequence:i,completed:s,deltas:c,files:_}=n,h=await q(d,async r=>({node_id:r.node_id,parent_node_id:r.parent,conversations:await q(f.get(r.node_id)??[],async E=>{const{header:p,entries:g}=await ne().read(E);if(a==="entries")return{conversation_id:E,header:p,entries:g};const O=qe.inMemory(p.cwd,void 0,[p,...g]),A=gt(O.getEntries(),O.getLeafId()),N=new Map(g.map((l,D)=>[l.id,D])),F=g.filter(l=>l.type==="custom"&&l.customType==="crtr-system-prompt").map(l=>({id:l.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in l?l.data:void 0,timestamp:l.timestamp}})),T=g.filter(l=>l.type==="custom_message"&&l.customType==="app_message").map(l=>({id:l.id,message:{role:"custom",customType:"app_message",content:"content"in l?l.content:"",timestamp:l.timestamp}})),B=r.node_id===e?g.find(l=>{if(l.type!=="message"||l.message.role!=="user")return!1;const D=oe(g,l.message.timestamp);return D?.type==="runtime"&&D.kind==="kickoff"})?.id:void 0,b=[...A.filter(({id:l})=>!T.some(D=>D.id===l)),...F,...T].sort((l,D)=>(N.get(l.id)??Number.MAX_SAFE_INTEGER)-(N.get(D.id)??Number.MAX_SAFE_INTEGER)).map(({id:l,message:D})=>{const w=D,L=w.usage,J=w.role==="user"?oe(g,Number(w.timestamp)):null,Oe=J?.type==="human"||l===B,C=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?Oe?"user":"custom":w.role,De=C==="custom"?w.role==="custom"?w.customType:J?.type==="runtime"?J.kind:"unknown":void 0,Me=C==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(M=>M.type==="toolCall"?{type:"tool_call",tool_call_id:M.id,name:M.name,arguments:M.arguments}:M.type==="image"?{type:"image",mime_type:M.mimeType}:M.type==="thinking"?{type:"thinking",text:M.thinking}:M):[];return{entry_id:l,role:C,...C==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...C==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...L?{usage:{input_tokens:L.input??0,output_tokens:L.output??0,cache_read_tokens:L.cacheRead??0,cache_write_tokens:L.cacheWrite??0,cost_usd:L.cost?.total??0}}:{}}:{},...C==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:E,messages:b}})})),o=new Map(await Promise.all(h.map(async r=>[r.node_id,await Rt(r.node_id)])));for(const r of s){const E=o.get(r.node_id);E!=null&&r.sequence_number>=E&&o.set(r.node_id,null)}const m=new Map;for(const r of c){const E=o.get(r.node_id);if(E==null||r.sequence_number<E)continue;const p=JSON.parse(r.body_json),g=m.get(r.node_id)??{thinking:"",text:""};r.type==="node.thinking.delta"?g.thinking+=p.delta:g.text+=p.delta,m.set(r.node_id,g)}const y=h.map(r=>({...r,in_progress_message:o.get(r.node_id)==null?null:m.get(r.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:i,nodes:y,files:_}}u(fa,"traceRun");function pa(e,t,a){if(t===void 0){if(!e.some(n=>j(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{St(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ie(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}u(pa,"requestedScopes");export{V as IDEMPOTENCY_WINDOW_MS,Ht as RUN_DEADLINE_MAX_MS,Ft as RUN_DELETE_STORAGE_BUDGET_MS,ve as RUN_NAME_MAX,R as RunError,ua as cancelRun,x as cloudPersonScope,la as deleteRun,aa as idempotencyKeyOf,ca as interruptRun,ia as listRuns,da as messageRun,$ as ownedRun,be as parseRunDeadlineMs,sa as pruneExpiredIdempotencyKeys,ma as renameRun,pa as requestedScopes,na as runIsRunning,H as runObject,ra as startRun,fa as traceRun,oa as waitRun};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var P=Object.defineProperty;var i=(e,o)=>P(e,"name",{value:o,configurable:!0});import{DatabaseSync as f}from"node:sqlite";import{forgetPrepared as I}from"../sqlite-statements.js";import{chmodSync as m,existsSync as
|
|
2
|
-
ALTER TABLE profile_projects DROP COLUMN memory;`),e.exec(`PRAGMA user_version = ${
|
|
1
|
+
var P=Object.defineProperty;var i=(e,o)=>P(e,"name",{value:o,configurable:!0});import{DatabaseSync as f}from"node:sqlite";import{forgetPrepared as I}from"../sqlite-statements.js";import{chmodSync as m,existsSync as p,mkdirSync as L,readdirSync as C,rmSync as j,statSync as v,writeFileSync as D}from"node:fs";import{join as n}from"node:path";import k from"proper-lockfile";import{CONFIG_FILE as _,PROFILE_DIR as G,STATE_FILE as l}from"../../types.js";import{withExclusiveDirectoryLock as y}from"../exclusive-lock.js";import{syncDirectory as $,syncFile as U}from"../fs-utils.js";import{providerStore as F,projectStore as g,userStore as B}from"./paths.js";import{createScopedSchema as X,ensureProviderModelCooldowns as H,PROFILE_ENVIRONMENT_COLUMN as R,PROFILE_PROJECT_REPO_COLUMN as A,PROVIDER_SCHEMA_VERSION as S,SCOPED_SCHEMA_VERSION as a}from"./schema.js";const u=new Map,K=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;function z(e,o,r){e.prepare("UPDATE scope_owners SET root=? WHERE owner_key=?").run(r,o)}i(z,"writeOwnerRoot");function c(e){return Number(e.prepare("PRAGMA user_version").get().user_version)}i(c,"version");function M(e,o){const r=c(e);if(r===0)throw new Error(`scoped SQL store is uninitialized: ${o.path}; crtr was updated and \`crtr sys daemon restart\` converts local state`);const t=o.kind==="provider"?S:a;if(r>t)throw new Error(`scoped SQL store ${o.path} uses unsupported schema version ${r}`);if(r!==t)throw new Error(`scoped SQL store ${o.path} requires an explicit conversion`)}i(M,"assertVersion");function x(e){return e.prepare("PRAGMA table_info(profiles)").all().some(({name:o})=>o===R)}i(x,"profilesHaveEnvironmentColumn");function w(e,o,r){return e.prepare(`PRAGMA table_info(${o})`).all().some(({name:t})=>t===r)}i(w,"hasColumn");function Q(e){w(e,"profile_projects",A)||e.exec(`ALTER TABLE profile_projects ADD COLUMN ${A} TEXT`),e.exec("CREATE TABLE IF NOT EXISTS profile_project_repos (profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, repo TEXT NOT NULL, position INTEGER NOT NULL, PRIMARY KEY(profile_id,repo))")}i(Q,"addProfileProjectRepos");function O(e,o){if(o.kind==="provider"){c(e)===S&&(e.exec("PRAGMA busy_timeout = 5000"),H(e));return}if(!(c(e)>a)&&(e.exec("PRAGMA busy_timeout = 5000"),!(c(e)===a&&x(e)&&w(e,"profile_projects",A)))){e.exec("BEGIN IMMEDIATE");try{c(e)===1&&(e.prepare("PRAGMA table_info(profiles)").all().some(({name:t})=>t==="grantee")||e.exec("ALTER TABLE profiles ADD COLUMN grantee TEXT"),e.exec("PRAGMA user_version = 2")),c(e)===2&&(e.prepare("PRAGMA table_info(profiles)").all().some(({name:t})=>t==="home")&&e.exec("ALTER TABLE profiles DROP COLUMN home"),e.exec("PRAGMA user_version = 3")),c(e)===3&&(e.exec("ALTER TABLE profiles ADD COLUMN delivery_limits_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(delivery_limits_json))"),e.exec("PRAGMA user_version = 4")),c(e)===4&&(e.exec("CREATE TABLE IF NOT EXISTS legacy_project_caps (profile_id TEXT NOT NULL, path TEXT NOT NULL, memory TEXT NOT NULL CHECK(memory IN ('none','name','preview')), PRIMARY KEY(profile_id,path))"),e.prepare("PRAGMA table_info(profile_projects)").all().some(({name:t})=>t==="memory")&&e.exec(`INSERT INTO legacy_project_caps SELECT profile_id, path, memory FROM profile_projects WHERE memory != 'content';
|
|
2
|
+
ALTER TABLE profile_projects DROP COLUMN memory;`),e.exec(`PRAGMA user_version = ${a}`)),c(e)===a&&!x(e)&&e.exec(`ALTER TABLE profiles ADD COLUMN ${R} TEXT`),c(e)===a&&Q(e),e.exec("COMMIT")}catch(r){throw e.exec("ROLLBACK"),r}}}i(O,"upgradeScopedStore");function fe(e){const o=new f(e.path);try{O(o,e),M(o,e)}finally{o.close()}}i(fe,"assertScopedStoreReady");function V(e){if(!N(e))return;const o=new f(e.path,{readOnly:!0});let r;try{r=c(o)}finally{o.close()}if(r===0)for(const t of[e.path,`${e.path}-wal`,`${e.path}-shm`])j(t,{force:!0})}i(V,"discardIncompleteScopedStore");function W(e,o){return y(n(e,".init.lock"),()=>{const r=n(e,l),t=Date.now()+5e3;let s=10;for(;;){let h;try{h=k.lockSync(r,{realpath:!1,retries:0,stale:3e4,update:1e4})}catch(E){if(E.code!=="ELOCKED")throw E;const T=t-Date.now();if(T<=0)throw new Error(`timed out waiting for project state conversion lock: ${r}`,{cause:E});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.min(s,T)),s=Math.min(s*2,250);continue}try{return o()}finally{h()}}})}i(W,"withProjectStateLock");function d(e){p(e)&&m(e,384);for(const o of["-wal","-shm"])p(`${e}${o}`)&&m(`${e}${o}`,384)}i(d,"secure");function N(e){return p(e.path)}i(N,"scopedStoreExists");function Y(e){if(e.kind==="project")return[n(e.root,l)];if(e.kind==="provider")return[n(e.root,"anthropic-subscriptions.json"),n(e.root,"openai-codex-subscriptions.json"),n(e.root,"provider-rotation.json")];const o=[n(e.root,_),n(e.root,l),n(e.root,"profile-defaults.json")],r=n(e.root,G);if(p(r))for(const t of C(r,{withFileTypes:!0}))t.isDirectory()&&K.test(t.name)&&o.push(n(r,t.name,"profile.json"),n(r,t.name,_),n(r,t.name,l));return o}i(Y,"legacyScopedStorePaths");function q(e){const o=e.kind==="user"?B(e.root):e.kind==="project"?g(e.root):F(e.root);o.kind!=="project"&&L(o.root,{recursive:!0,mode:448});const r=i(()=>{if(o.kind==="project"&&V(o),N(o))return;const t=Y(o).find(p);if(t!==void 0)throw new Error(`legacy scoped state exists at ${t}; crtr was updated and \`crtr sys daemon restart\` converts local state`);Z(o,s=>{X(s,o.kind),o.kind!=="provider"&&z(s,o.kind,o.root)})},"initialize");o.kind==="project"?W(o.root,r):y(n(o.root,".init.lock"),r)}i(q,"initializeFreshScopedStore");function J(e){const o=u.get(e.path);if(o!==void 0)return o;q(e);const r=new f(e.path);try{return r.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"),O(r,e),M(r,e),d(e.path),u.set(e.path,r),r}catch(t){throw r.close(),t}}i(J,"openScopedStore");function Z(e,o){if(p(e.path))throw new Error(`scoped SQL store already exists: ${e.path}`);if(e.kind!=="project"&&L(e.root,{recursive:!0,mode:448}),!v(e.root).isDirectory())throw new Error(`scoped SQL root is not a directory: ${e.root}`);(e.kind!=="project"||process.platform!=="linux")&&m(e.root,448),D(e.path,"",{mode:384});const r=new f(e.path);try{r.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; BEGIN IMMEDIATE;"),o(r),r.exec("COMMIT")}catch(t){try{r.exec("ROLLBACK")}catch{}throw t}finally{d(e.path),r.close()}U(e.path),$(e.root)}i(Z,"createScopedStore");function le(e,o){const r=J(e);if(r.isTransaction)return o(r);r.exec("BEGIN IMMEDIATE");try{const t=o(r);return r.exec("COMMIT"),d(e.path),t}catch(t){try{r.exec("ROLLBACK")}catch{}throw t}}i(le,"withScopedWrite");function ue(){for(const e of u.values())I(e),e.close();u.clear()}i(ue,"closeScopedStores");export{K as PROFILE_ID_SHAPE,fe as assertScopedStoreReady,ue as closeScopedStores,Z as createScopedStore,V as discardIncompleteScopedStore,q as initializeFreshScopedStore,Y as legacyScopedStorePaths,J as openScopedStore,N as scopedStoreExists,W as withProjectStateLock,le as withScopedWrite,z as writeOwnerRoot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var r=Object.defineProperty;var o=(t,e)=>r(t,"name",{value:e,configurable:!0});import{drainState as s,endDrain as i,isDrained as d,settleDrain as m,startDrain as c}from"../../drain.js";import{ApiError as u}from"../../../api/errors.js";import{readMoveRecord as l}from"../../machine-link/config.js";import{boundDaemonControl as a}from"../../control.js";import{ownerOnly as h}from"../router.js";function b(){const t=a();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot hand over"};const{graceMs:e}=t.requestHandover();return{status:202,body:{accepted:!0,predecessor_pid:process.pid,predecessor_epoch:t.epoch,grace_ms:e}}}o(b,"handleRestart");async function p(t){if(t.body!==void 0)throw{status:400,code:"invalid_request",message:"admission request must not include a body"};const e=a();if(e===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot admit normal work"};return{status:200,body:await e.admitStartup()}}o(p,"handleAdmit");async function y(t){const e=t.body??{};if(typeof e!="object"||e===null||Array.isArray(e))throw{status:400,code:"invalid_request",message:"drain request body must be an object"};const n=e.settle_limit_ms;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0))throw{status:400,code:"invalid_request",message:"settle_limit_ms must be a non-negative number"};return await c(),{status:200,body:n===void 0?await s():await m({limitMs:n})}}o(y,"handleDrain");async function f(){if(l()!==void 0)throw new u(409,"conflict","a move to Northlight is unsettled on this computer, so its pause stays: run `crtr sys signin` to settle it");const t=await d();return{status:200,body:{...await i(),was_drained:t}}}o(f,"handleEndDrain");const E=h([{method:"POST",pattern:"/v1/daemon/restart",handler:o(t=>b(),"handler")},{method:"POST",pattern:"/v1/daemon/admit",handler:p},{method:"POST",pattern:"/v1/daemon/drain",handler:y},{method:"DELETE",pattern:"/v1/daemon/drain",handler:f}]);export{E as daemonRoutes};
|