@north-light/cli 0.3.657 → 0.3.659

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.
@@ -1052,7 +1052,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
1052
1052
  name TEXT NOT NULL,
1053
1053
  PRIMARY KEY (src, name)
1054
1054
  ) WITHOUT ROWID;
1055
- `),ce];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
1055
+ `),ce,e=>e.exec("ALTER TABLE uploads ADD COLUMN sub TEXT")];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
1056
1056
  CREATE TABLE waits_new (
1057
1057
  wait_id TEXT PRIMARY KEY,
1058
1058
  node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
@@ -1,4 +1,4 @@
1
- var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as N,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new N;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
1
+ var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as N,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new N;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
2
2
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
3
3
  AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
4
4
  AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
@@ -0,0 +1,8 @@
1
+ -- 018-transfer-person.sql — an upload belongs to a person as well as an app. One transaction, additions only: `schema_min_reader` is not
2
+ -- touched, so the previous release (version 17) still opens the result: it never names the column, so its inserts leave it null and its
3
+ -- `SELECT *` reads ignore it.
4
+ --
5
+ -- `uploads.sub` is the calling token's person (`AppPrincipal.sub`) on a cloud role, where one app serves many people. It is null for an
6
+ -- upload made on a Mac (one person, nothing to cut) and for every row written before this step; a null row never matches a run of some
7
+ -- person on a cloud role, so no backfill is attempted (the table keeps no record of whom an older upload was for).
8
+ ALTER TABLE uploads ADD COLUMN sub text;
@@ -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 = 17;
4
+ export declare const CANVAS_SCHEMA_VERSION = 18;
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=17;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
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=18;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,6 +1,6 @@
1
1
  var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as P}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(a=>a.replace(/^user:/,""),"bare"),g=c((a,t)=>`${f(a)}.${f(t)}`,"sq"),N=c(async(a,t,...r)=>await a.prepareUncached(t).all(...r),"all");function I(a,t){return new D("bind","person_mismatch",a,t)}c(I,"mismatch");function te(a,t,r,l){if(a===t||a===r)return r;throw I(`${l} names ${a}, which is neither the bundle's person nor the importing person`,{where:l,value:a})}c(te,"boundSub");async function oe(a,t,r,l){if(!K.test(r))throw I(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===l)return;const d=c(i=>g(t,i),"T"),o=await a.prepareUncached(`SELECT 'identities' AS tbl FROM ${d("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
2
  UNION ALL SELECT 'grants' FROM ${d("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${d("profiles")} WHERE person = ?
3
- UNION ALL SELECT 'nodes' FROM ${d("nodes")} WHERE sub = ? LIMIT 1`).get(r,r,r,r);if(o!==void 0)throw I(`the bundle's person ${r} is already a person in the target (${o.tbl}), not the importing person ${l}`,{where:`${o.tbl}`,value:r})}c(oe,"checkSourcePerson");const Y=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"]],B=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:d}=a,o=c(p=>g(r,p),"S"),i=c((p,u)=>{throw I(`${p} names ${u.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${d}`,{where:p,values:u})},"refuse");for(const[p,u]of Y){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} IS NOT NULL AND ${f(u)} <> '' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}for(const[p,u]of B){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} LIKE 'user:%' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}const h=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,l,d);h.length>0&&i("identities.external_id",h.map(p=>p.v));const _=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
3
+ UNION ALL SELECT 'nodes' FROM ${d("nodes")} WHERE sub = ? LIMIT 1`).get(r,r,r,r);if(o!==void 0)throw I(`the bundle's person ${r} is already a person in the target (${o.tbl}), not the importing person ${l}`,{where:`${o.tbl}`,value:r})}c(oe,"checkSourcePerson");const Y=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"]],B=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:d}=a,o=c(p=>g(r,p),"S"),i=c((p,u)=>{throw I(`${p} names ${u.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${d}`,{where:p,values:u})},"refuse");for(const[p,u]of Y){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} IS NOT NULL AND ${f(u)} <> '' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}for(const[p,u]of B){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} LIKE 'user:%' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}const h=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,l,d);h.length>0&&i("identities.external_id",h.map(p=>p.v));const _=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
4
4
  WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,l,d);_.length>0&&i("daemon_actions principal.sub",_.map(p=>p.v));const m=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(l),C(d));m.length>0&&i("relations acts_for subject",m.map(p=>p.v));const $=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return $>0?{relations:$}:{}}c(ne,"checkStagedPersons");async function z(a,t){return(await N(a,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
5
5
  WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(l=>J(l.inserted_keys).map(d=>d[0]))}c(z,"earlierImportedObjects");async function se(a,t){const{db:r,schema:l,target:d,catalog:o,targetPerson:i}=a,h=c(n=>g(l,n),"S"),_=c(n=>g(d,n),"T"),m=C(i);await r.exec(`CREATE TABLE ${h("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const $=[];for(const[n,E]of P(o))if(!(!o.tables.has(n)||n==="relations"))for(const b of E)!(n==="nodes"&&b==="profile_id")&&!(n==="crons"&&b==="profile")&&$.push([n,b,""]);$.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,E,b]of $)await r.prepareUncached(`INSERT INTO ${h("_refs")} SELECT ?, ?, ${f(E)}::text FROM ${h(n)} ${b===""?"WHERE":`${b} AND`} ${f(E)} IS NOT NULL
6
6
  AND ${f(E)}::text NOT IN (SELECT id FROM ${h("objects")}) AND ${f(E)}::text IN (SELECT id FROM ${_("objects")})`).run(n,E);const p=await z(r,t),u=await N(r,`WITH RECURSIVE chain(start, id) AS (
@@ -3,7 +3,7 @@ import type { AppPrincipal } from '../../daemon/api/principal.js';
3
3
  import { type ResolvedAttachments } from '../storage/attachments.js';
4
4
  import { type StorageClient, type StorageConfig } from '../storage/client.js';
5
5
  /** Fetches the storage URLs of a run's text into the run's `attachments/`. */
6
- export type AttachmentResolver = (runId: string, grantee: string, text: string, taken?: readonly string[]) => Promise<ResolvedAttachments>;
6
+ export type AttachmentResolver = (runId: string, grantee: string, text: string, taken?: readonly string[], person?: string) => Promise<ResolvedAttachments>;
7
7
  /** Storage deletes `run.delete` waits for before it answers. */
8
8
  export declare const RUN_DELETE_STORAGE_BUDGET_MS = 3000;
9
9
  export interface StorageDeps {
@@ -1,14 +1,14 @@
1
- var Me=Object.defineProperty;var c=(e,t)=>Me(e,"name",{value:t,configurable:!0});import{coveredByAny as Ae}from"../../shared/env.js";import{createHash as Q}from"node:crypto";import{ApiError as Ie}from"../../api/errors.js";import{CrtrError as Te}from"../errors.js";import{isCloudRole as Le}from"../canvas/person.js";import{isAbsolute as V,relative as Ce,resolve as ke,sep as xe,join as We}from"node:path";import{SessionManager as Fe}from"@earendil-works/pi-coding-agent";import{covers as P}from"@north-light/identity";import{openDb as B,withCanvasWrite as F}from"../canvas/db.js";import{deleteNodeWithOwned as qe}from"../graph/deletion.js";import{getById as He}from"../graph/objects.js";import{repairRunConversations as Z}from"../canvas/sessions.js";import{getNode as v,nodeFiles as Ue,removeNodeFiles as $e,updateNode as Pe}from"../canvas/canvas.js";import{fullName as Be}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{liveExecutionForNode as K}from"../canvas/executions.js";import{conversationStore as ee,isConversationNotFound as Je}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ye}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Ge}from"../canvas/deliveries.js";import{readNodeRecap as Xe}from"../canvas/node-recap.js";import{enqueueNodeMail as ze}from"../feed/messages.js";import{recordInitialInput as Qe}from"./initial-input.js";import{newestReportBody as Ve}from"../feed/reports.js";import{ensureAppProfile as te,loadExactProfileManifest as ne}from"../profiles/manifest.js";import{stopNodeSandboxes as ae}from"../spaces/stop.js";import{deleteNodeSandboxes as Ze}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as Ke}from"../runtime/broker-request.js";import{interruptLive as et}from"../runtime/interactive-deliver.js";import{isBrokerLive as se}from"../runtime/model-swap.js";import{newNodeId as tt}from"../runtime/nodes.js";import{reviveNode as j}from"../runtime/revive.js";import{spawnChildPrepared as nt}from"../runtime/spawn.js";import{isPortableModelToken as at}from"../runtime/launch.js";import{parseDurationMs as st}from"../wake.js";import{expandModelCandidates as it,parseModelSpec as rt}from"../model-routes.js";import{payerOfGrant as J}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as ot}from"../runtime/host.js";import{blaxelEnvironmentOf as dt}from"../runtime/blaxel-environment.js";import{resolveRunKind as ct,resolveRunModel as ut}from"../runtime/launch-target.js";import{cycleAwareMessages as mt}from"../runtime/session-cycles.js";import{originFor as ie}from"../runtime/stamp/protocol.js";import{readOutputRequest as lt,readOutputResult as re}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as oe}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as ft}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as pt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as _t}from"../../daemon/runs/observer.js";import{closeNode as de}from"../runtime/close.js";import{parseScope as wt}from"@north-light/identity";import{appendRunEvent as ce,lockRunRoot as gt,subscribeRunEvents as Et}from"./events.js";import{runActivity as yt}from"./activity.js";import{cancelOpenQuestions as ue,openNoticeIds as ht,openQuestionIds as me}from"./questions.js";import{appSpace as Y}from"../layout.js";import{ensureAppSpace as Rt}from"../spaces/space.js";import{assertUploadsUsable as le,resolveStorageUrls as St}from"../storage/attachments.js";import{storageClient as Nt,storageConfig as vt}from"../storage/client.js";import{deleteUploadRow as bt,insertUploadUses as fe,releaseRunUploads as Ot,runUsesPath as Dt}from"../storage/tables.js";import{abortProviderCalls as pe}from"../providers/inflight.js";import{filterAsync as _e,mapAsync as x}from"../async-array.js";import{blobStore as Mt}from"../blobs/index.js";import{emitEvent as At}from"../events/emit.js";const we=c((e,t,a,n)=>St(t,e,a,n?{taken:n}:{}),"defaultResolver"),It=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,_,i,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=_,this.scope=i,this.retryable=s}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),G=c(()=>new R(404,"not_found","run not found"),"missing"),X=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),M=c(async()=>await B(),"db");async function q(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 G();return n}c(q,"ownedRun");const ge=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await M()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var Ae=Object.defineProperty;var c=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as V}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 Z,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 B}from"@north-light/identity";import{openDb as j,withCanvasWrite as q}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as K}from"../canvas/sessions.js";import{getNode as b,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{liveExecutionForNode as ee}from"../canvas/executions.js";import{conversationStore as te,isConversationNotFound as Ye}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ge}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Xe}from"../canvas/deliveries.js";import{readNodeRecap as ze}from"../canvas/node-recap.js";import{enqueueNodeMail as Qe}from"../feed/messages.js";import{recordInitialInput as Ve}from"./initial-input.js";import{newestReportBody as Ze}from"../feed/reports.js";import{ensureAppProfile as ne,loadExactProfileManifest as ae}from"../profiles/manifest.js";import{stopNodeSandboxes as se}from"../spaces/stop.js";import{deleteNodeSandboxes as Ke}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as et}from"../runtime/broker-request.js";import{interruptLive as tt}from"../runtime/interactive-deliver.js";import{isBrokerLive as ie}from"../runtime/model-swap.js";import{newNodeId as nt}from"../runtime/nodes.js";import{reviveNode as J}from"../runtime/revive.js";import{spawnChildPrepared as at}from"../runtime/spawn.js";import{isPortableModelToken as st}from"../runtime/launch.js";import{parseDurationMs as it}from"../wake.js";import{expandModelCandidates as rt,parseModelSpec as ot}from"../model-routes.js";import{payerOfGrant as Y}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as dt}from"../runtime/host.js";import{blaxelEnvironmentOf as ct}from"../runtime/blaxel-environment.js";import{resolveRunKind as ut,resolveRunModel as mt}from"../runtime/launch-target.js";import{cycleAwareMessages as lt}from"../runtime/session-cycles.js";import{originFor as re}from"../runtime/stamp/protocol.js";import{readOutputRequest as ft,readOutputResult as oe}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as de}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as pt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as _t}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as wt}from"../../daemon/runs/observer.js";import{closeNode as ce}from"../runtime/close.js";import{parseScope as gt}from"@north-light/identity";import{appendRunEvent as ue,lockRunRoot as Et,subscribeRunEvents as yt}from"./events.js";import{runActivity as ht}from"./activity.js";import{cancelOpenQuestions as me,openNoticeIds as Rt,openQuestionIds as le}from"./questions.js";import{appSpace as G}from"../layout.js";import{ensureAppSpace as St}from"../spaces/space.js";import{assertUploadsUsable as fe,resolveStorageUrls as Nt}from"../storage/attachments.js";import{storageClient as bt,storageConfig as vt}from"../storage/client.js";import{deleteUploadRow as Ot,insertUploadUses as pe,releaseRunUploads as Dt,runUsesPath as Mt}from"../storage/tables.js";import{abortProviderCalls as _e}from"../providers/inflight.js";import{filterAsync as we,mapAsync as W}from"../async-array.js";import{blobStore as At}from"../blobs/index.js";import{emitEvent as It}from"../events/emit.js";const ge=c((e,t,a,n,d)=>Nt(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),Tt=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,f,r,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=f,this.scope=r,this.retryable=s}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),X=c(()=>new R(404,"not_found","run not found"),"missing"),z=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),M=c(async()=>await j(),"db");async function H(e,t,a=!1){const n=await b(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw X();return n}c(H,"ownedRun");const Ee=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await M()).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 ft(e)?"running":(await me(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
- WHERE n.run_id = ? AND ${Ge("d","'armed', 'pending', 'handed_off'")}
8
- AND (n.status IN ('active', 'idle') OR ${Ye("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Jn(e){const t=await v(e);return t!==null&&await C(t)==="running"}c(Jn,"runIsRunning");async function W(e){await Z(e.node_id),e=await v(e.node_id)??e;const t=await C(e),a=t==="settled"?[]:await me(e.node_id),n=await Ve(e.node_id)||void 0,d=t==="settled"?await pt(e):null,_=d?.kind==="result"?await re(e.node_id):void 0,i=Xe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},..._===void 0?{}:{result:_},...n!==void 0?{last_report:n}:{},...i?{recap:i}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await ht(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(X())),payer:await J(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 yt(e.node_id,t)}}c(W,"runObject");const z=864e5,Ee=255;function Yn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>Ee)throw S(`Idempotency-Key must be 1-${Ee} characters`);return e}}c(Yn,"idempotencyKeyOf");function Tt(e){if(Le()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(Tt,"cloudPersonScope");function k(e,t){const a=Tt(e);return a===void 0?t:`${a}:${t}`}c(k,"personKey");async function H(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await B();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)>=z)){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)}}}c(H,"findIdempotent");async function ye(e,t,a,n,d,_,i){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-z).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(_),i)}c(ye,"recordIdempotent");async function Gn(e=Date.now()){return Number((await(await B()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-z).toISOString())).changes)}c(Gn,"pruneExpiredIdempotencyKeys");async function he(e,t,a,n,d,_=!1){const i=n.text;let s=0;return{messageId:(await ze(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:d?{body:i,..._?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:d?"normal":"deferred",wake:d?1:0,withinEnqueue:c(async(l,h)=>{n.uses.length&&(await le(a,n.uses,l),await fe(n.uses.map(({upload_id:o,path:f,blob_key:r})=>({upload_id:o,path:f,blob_key:r,run_id:t})),l)),s=(await ce(l,t,t,"node.message.accepted",{message_id:h,start_turn:d})).sequence_number},"withinEnqueue")})).messageId,sequence:s}}c(he,"acceptRunMessage");class Re extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Lt=1440*60*1e3;function Se(e){const t=typeof e=="string"?st(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>Lt)throw S("deadline must be at most 24h","deadline");return t}c(Se,"parseRunDeadlineMs");async function Xn(e,t,a,n=we){if(t.isolated&&!ot()&&await dt((t.profile===void 0?await te(e.grantee):ne(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Se(t.deadline);const{causedBy:d,..._}=t,i=Q("sha256").update(JSON.stringify(_)).digest("hex");if(a){const o=await H(e.grantee,k(e.sub,a),i);if(o){const f=await q(o.run_id,e.grantee);return!f.pi_pid&&await C(f)==="running"&&(t.output_schema!==void 0&&!f.outcome_at&&await lt(f.node_id)===null&&await re(f.node_id)===void 0&&await oe(f.node_id,"terminal",t.output_schema),await j(f.node_id,{resume:!0,capacity:"freeze"})),o.response}}await Rt(e.grantee);const s=t.profile===void 0?await te(e.grantee):ne(t.profile),m=s.manifest.grantee??"app:terminal";if(m!==e.grantee){const o=`crtr:memory:rw:${m}:profile:${s.profileId}`;if(!e.resolved.some(f=>P(f,o))||t.scopes!==null&&!t.scopes.some(f=>P(f,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(at(o)){if(o.includes("/")&&await J(e.grant)!=="app"){const f=o.lastIndexOf("/"),r=o.slice(0,f),p=o.slice(f+1);if(["ultra","strong","medium","light"].includes(p)&&(await it({kind:"logical",family:r,strength:p,spec:o},Y(e.grantee).files,s.profileId)).every(y=>y.family!==r))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(rt(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 l=await tt(),h=We(Y(e.grantee).nodes,l);if(t.isolated&&t.cwd!==void 0){const o=Ce(h,ke(t.cwd));if(!V(t.cwd)||o===".."||o.startsWith(`..${xe}`)||V(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(l,e.grantee,t.prompt),f=o.text,r=t.message===void 0?void 0:await n(l,e.grantee,t.message,o.uses.map(u=>u.path)),p=await J(e.grant);let y;try{const u=ut(s,t.model);await nt({kind:ct(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:Y(e.grantee).files,profile:s.profileId,prompt:f,nodeId:l,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...u===void 0?{}:{model:u},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Se(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:l,event_cursor:1,usage_json:JSON.stringify(X())},withinCreate:c(async(E,A)=>{if(a){const N=await H(e.grantee,k(e.sub,a),i,E);if(N)throw new Re(N)}const D=o.uses;if(D.length&&(await le(e.grantee,D,E),await fe(D.map(({upload_id:N,path:I,blob_key:U})=>({upload_id:N,path:I,blob_key:U,run_id:l})),E)),y={run_id:l,node_id:l,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:p,status:"running",created_at:A.created,metadata:t.metadata,sequence_number:0},await ce(E,l,l,"run.started",{scopes:t.scopes,payer:p,usage:X()}),r){const N=await he(E,l,e.grantee,r,!1);y.message={run_id:l,message_id:N.messageId,sequence_number:N.sequence}}else await Qe(l,e.grantee,f);a&&await ye(E,e.grantee,k(e.sub,a),i,l,y,A.created)},"withinCreate")},t.output_schema===void 0?void 0:async E=>{await oe(E,"terminal",t.output_schema)})}catch(u){if(u instanceof Re)return u.winner.response;if(t.model!==void 0&&u instanceof Te&&u.code==="usage")throw S(u.message,"model");if(u instanceof Ie&&(u.code==="isolated_run"||u.code==="invalid_request")){const E=u.details&&typeof u.details=="object"&&"param"in u.details&&typeof u.details.param=="string"?u.details.param:void 0;throw new R(u.status,u.code,u.message,E)}throw u}if(!y)throw new Error("run creation did not commit");return y}finally{await Ct(l)}}c(Xn,"startRun");async function Ct(e){try{if(await v(e)!==null)return;const t=await Mt();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){At({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(Ct,"discardUncommittedAttachments");async function zn(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 M()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await pt(e)?"running":(await le(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
+ WHERE n.run_id = ? AND ${Xe("d","'armed', 'pending', 'handed_off'")}
8
+ AND (n.status IN ('active', 'idle') OR ${Ge("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Jn(e){const t=await b(e);return t!==null&&await C(t)==="running"}c(Jn,"runIsRunning");async function F(e){await K(e.node_id),e=await b(e.node_id)??e;const t=await C(e),a=t==="settled"?[]:await le(e.node_id),n=await Ze(e.node_id)||void 0,d=t==="settled"?await _t(e):null,f=d?.kind==="result"?await oe(e.node_id):void 0,r=ze(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}:{},...r?{recap:r}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await Rt(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(z())),payer:await Y(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 ht(e.node_id,t)}}c(F,"runObject");const Q=864e5,ye=255;function Yn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>ye)throw S(`Idempotency-Key must be 1-${ye} characters`);return e}}c(Yn,"idempotencyKeyOf");function k(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}}c(k,"cloudPersonScope");function x(e,t){const a=k(e);return a===void 0?t:`${a}:${t}`}c(x,"personKey");async function U(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await j();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)>=Q)){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)}}}c(U,"findIdempotent");async function he(e,t,a,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-Q).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),r)}c(he,"recordIdempotent");async function Gn(e=Date.now()){return Number((await(await j()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-Q).toISOString())).changes)}c(Gn,"pruneExpiredIdempotencyKeys");async function Re(e,t,a,n,d,f,r=!1){const s=d.text;let u=0;return{messageId:(await Qe(t,{kind:"message",label:s.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:f?{body:s,...r?{steer:!0}:{}}:{body:s,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await fe(a,k(n),d.uses,h),await pe(d.uses.map(({upload_id:_,path:i,blob_key:l})=>({upload_id:_,path:i,blob_key:l,run_id:t})),h)),u=(await ue(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Re,"acceptRunMessage");class Se extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Lt=1440*60*1e3;function Ne(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>Lt)throw S("deadline must be at most 24h","deadline");return t}c(Ne,"parseRunDeadlineMs");async function Xn(e,t,a,n=ge){if(t.isolated&&!dt()&&await ct((t.profile===void 0?await ne(e.grantee):ae(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Ne(t.deadline);const{causedBy:d,...f}=t,r=V("sha256").update(JSON.stringify(f)).digest("hex");if(a){const o=await U(e.grantee,x(e.sub,a),r);if(o){const _=await H(o.run_id,e.grantee);return!_.pi_pid&&await C(_)==="running"&&(t.output_schema!==void 0&&!_.outcome_at&&await ft(_.node_id)===null&&await oe(_.node_id)===void 0&&await de(_.node_id,"terminal",t.output_schema),await J(_.node_id,{resume:!0,capacity:"freeze"})),o.response}}await St(e.grantee);const s=t.profile===void 0?await ne(e.grantee):ae(t.profile),u=s.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${s.profileId}`;if(!e.resolved.some(_=>B(_,o))||t.scopes!==null&&!t.scopes.some(_=>B(_,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(st(o)){if(o.includes("/")&&await Y(e.grant)!=="app"){const _=o.lastIndexOf("/"),i=o.slice(0,_),l=o.slice(_+1);if(["ultra","strong","medium","light"].includes(l)&&(await rt({kind:"logical",family:i,strength:l,spec:o},G(e.grantee).files,s.profileId)).every(y=>y.family!==i))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(ot(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 p=await nt(),h=Fe(G(e.grantee).nodes,p);if(t.isolated&&t.cwd!==void 0){const o=ke(h,xe(t.cwd));if(!Z(t.cwd)||o===".."||o.startsWith(`..${We}`)||Z(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(p,e.grantee,t.prompt,void 0,k(e.sub)),_=o.text,i=t.message===void 0?void 0:await n(p,e.grantee,t.message,o.uses.map(m=>m.path),k(e.sub)),l=await Y(e.grant);let y;try{const m=mt(s,t.model);await at({kind:ut(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:G(e.grantee).files,profile:s.profileId,prompt:_,nodeId:p,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...m===void 0?{}:{model:m},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Ne(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:p,event_cursor:1,usage_json:JSON.stringify(z())},withinCreate:c(async(E,A)=>{if(a){const N=await U(e.grantee,x(e.sub,a),r,E);if(N)throw new Se(N)}const D=o.uses;if(D.length&&(await fe(e.grantee,k(e.sub),D,E),await pe(D.map(({upload_id:N,path:I,blob_key:$})=>({upload_id:N,path:I,blob_key:$,run_id:p})),E)),y={run_id:p,node_id:p,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:l,status:"running",created_at:A.created,metadata:t.metadata,sequence_number:0},await ue(E,p,p,"run.started",{scopes:t.scopes,payer:l,usage:z()}),i){const N=await Re(E,p,e.grantee,e.sub,i,!1);y.message={run_id:p,message_id:N.messageId,sequence_number:N.sequence}}else await Ve(p,e.grantee,_);a&&await he(E,e.grantee,x(e.sub,a),r,p,y,A.created)},"withinCreate")},t.output_schema===void 0?void 0:async E=>{await de(E,"terminal",t.output_schema)})}catch(m){if(m instanceof Se)return m.winner.response;if(t.model!==void 0&&m instanceof Le&&m.code==="usage")throw S(m.message,"model");if(m instanceof Te&&(m.code==="isolated_run"||m.code==="invalid_request")){const E=m.details&&typeof m.details=="object"&&"param"in m.details&&typeof m.details.param=="string"?m.details.param:void 0;throw new R(m.status,m.code,m.message,E)}throw m}if(!y)throw new Error("run creation did not commit");return y}finally{await Ct(p)}}c(Xn,"startRun");async function Ct(e){try{if(await b(e)!==null)return;const t=await At();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){It({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(Ct,"discardUncommittedAttachments");async function zn(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 M()).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 _e(await x((await _e(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:m})=>!a||s<a.activity||s===a.activity&&m<a.id),async s=>({root:await v(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),_=d.slice(0,t.limit),i=_.at(-1);return{runs:await x(_,async({root:s})=>await W(s)),next:d.length>t.limit&&i?Buffer.from(JSON.stringify({activity:i.activity,id:i.root.node_id})).toString("base64url"):null}}c(zn,"listRuns");async function Qn(e,t,a){const n=await q(e,t),d=c(async()=>await W(await q(e,t)),"read");return!a||ge.includes(await C(n))?await d():new Promise((_,i)=>{let s=c(()=>{},"unsubscribe");const m=c(()=>{clearTimeout(r),clearInterval(f),s()},"settle"),l=c(async()=>{m();try{_(await d())}catch(p){i(p)}},"finish"),h=c(async()=>{ge.includes(String((await d()).status))&&await l()},"check"),o=c(()=>{h().catch(p=>{m(),i(p)})},"run"),f=setInterval(o,250),r=setTimeout(()=>{l()},a*1e3);Et(e,o).then(p=>{s=p},p=>{m(),i(p)})})}c(Qn,"waitRun");const kt=5;async function Vn(e,t,a=we,n=!0,d,_=!0){const i=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",m=Q("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!_?["steer:false"]:[]])).digest("hex"),l=c(async o=>{const f=await v(e.node_id),r=await(await M()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return f&&!i&&n&&!f.pi_pid&&r&&await j(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await H(s,k(e.sub,d),m);if(o)return l(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 f=await a(e.node_id,s,t),r=await F(async p=>{if(d){const E=await H(s,k(e.sub,d),m,p);if(E)return{replayed:E.response}}if(f.uses.length){await gt(p,e.node_id);for(const E of f.uses)if(await Dt(e.node_id,E.path,p))return"path_taken"}await h?.(e.node_id);const y=await he(p,e.node_id,s,f,n,n&&_),u={run_id:e.node_id,message_id:y.messageId,sequence_number:y.sequence};return d&&await ye(p,s,k(e.sub,d),m,e.node_id,u,new Date().toISOString()),{result:u}});if(r==="path_taken"){if(o>=kt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in r?l(r.replayed):(n&&!e.pi_pid&&await j(e.node_id,{resume:!0,capacity:"freeze"}),r.result)}}c(Vn,"messageRun");async function xt(e){const t=c(()=>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 G();if(!se(n)){if(n.streaming)throw t();return}const d=(await K(e))?.executionId;try{await et(e)==="turn"&&pe({nodes:[e]});return}catch(_){if(!(_ instanceof Ke))throw _;const i=await v(e);if(!i)throw G();if(!i.streaming)return;if(a===0&&se(i)&&(await K(e))?.executionId!==d)continue;throw t()}}throw t()}c(xt,"interruptNode");async function Zn(e,t="stop"){const a=t==="stop"?(await(await M()).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=>xt(n))),await W(await v(e.node_id)??e)}c(Zn,"interruptRun");async function Kn(e,t={}){const a=(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(i=>i.node_id);pe({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await de(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 de(i,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await ue({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(i=>ae(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 _=await v(e.node_id);return await W(_??e)}c(Kn,"cancelRun");const Ne=200;async function ea(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>Ne)throw S(`name exceeds ${Ne} characters`,"name");const n=await Pe(e.node_id,{name:a});return n.window&&je(n.window,Be(n)),await W(n)}c(ea,"renameRun");async function ta(e,t={config:vt,client:Nt}){await ue({run_id:e.node_id},"the run was deleted");const a=await F(async m=>(await m.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await m.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(l=>l.node_id)));if((await Promise.all(a.map(m=>ae(m,"run_deleted",{deleting:!0})))).some(m=>!m.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await Ze(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 x(a,async m=>{const l=await Ue(m);if(l.app===null)throw new Error(`run node missing during deletion: ${m}`);return l}),_=await(await M()).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:m}of _)try{await ee().delete(m)}catch(l){if(!Je(l))throw l}const i=await F(async m=>{for(const f of a){const r=await He(m,f);r!==null&&r.deleted_at===null&&await qe(m,r)}const l=await Ot([e.node_id],m);await m.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await m.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await m.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 m.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:f}of o)await m.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(f,f);return l});for(const m of d)await $e(m);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Wt(i,t)}}c(ta,"deleteRun");async function Wt(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 bt(i),n.add(i)},()=>{}));let _;return await Promise.race([Promise.all(d),new Promise(i=>{_=setTimeout(i,t.budgetMs??It),_.unref?.()})]),clearTimeout(_),e.length-n.size}c(Wt,"deleteReleasedUploads");async function na(e,t,a){await q(e,t),await Z(e);const n=await F(async r=>{const p=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),y=new Map;for(const N of p)y.set(N.node_id,(await r.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(N.node_id)).map(I=>I.session_id));const E=(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
10
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await we(await W((await we(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:u})=>!a||s<a.activity||s===a.activity&&u<a.id),async s=>({root:await b(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await W(f,async({root:s})=>await F(s)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(zn,"listRuns");async function Qn(e,t,a){const n=await H(e,t),d=c(async()=>await F(await H(e,t)),"read");return!a||Ee.includes(await C(n))?await d():new Promise((f,r)=>{let s=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(i),clearInterval(_),s()},"settle"),p=c(async()=>{u();try{f(await d())}catch(l){r(l)}},"finish"),h=c(async()=>{Ee.includes(String((await d()).status))&&await p()},"check"),o=c(()=>{h().catch(l=>{u(),r(l)})},"run"),_=setInterval(o,250),i=setTimeout(()=>{p()},a*1e3);yt(e,o).then(l=>{s=l},l=>{u(),r(l)})})}c(Qn,"waitRun");const kt=5;async function Vn(e,t,a=ge,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",u=V("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),p=c(async o=>{const _=await b(e.node_id),i=await(await M()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return _&&!r&&n&&!_.pi_pid&&i&&await J(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await U(s,x(e.sub,d),u);if(o)return p(o.response)}if(r)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 _=await a(e.node_id,s,t,void 0,k(e.sub)),i=await q(async l=>{if(d){const E=await U(s,x(e.sub,d),u,l);if(E)return{replayed:E.response}}if(_.uses.length){await Et(l,e.node_id);for(const E of _.uses)if(await Mt(e.node_id,E.path,l))return"path_taken"}await h?.(e.node_id);const y=await Re(l,e.node_id,s,e.sub,_,n,n&&f),m={run_id:e.node_id,message_id:y.messageId,sequence_number:y.sequence};return d&&await he(l,s,x(e.sub,d),u,e.node_id,m,new Date().toISOString()),{result:m}});if(i==="path_taken"){if(o>=kt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in i?p(i.replayed):(n&&!e.pi_pid&&await J(e.node_id,{resume:!0,capacity:"freeze"}),i.result)}}c(Vn,"messageRun");async function xt(e){const t=c(()=>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 b(e);if(!n)throw X();if(!ie(n)){if(n.streaming)throw t();return}const d=(await ee(e))?.executionId;try{await tt(e)==="turn"&&_e({nodes:[e]});return}catch(f){if(!(f instanceof et))throw f;const r=await b(e);if(!r)throw X();if(!r.streaming)return;if(a===0&&ie(r)&&(await ee(e))?.executionId!==d)continue;throw t()}}throw t()}c(xt,"interruptNode");async function Zn(e,t="stop"){const a=t==="stop"?(await(await M()).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=>xt(n))),await F(await b(e.node_id)??e)}c(Zn,"interruptRun");async function Kn(e,t={}){const a=(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);_e({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await ce(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of a){if(r===e.node_id)continue;const s=await b(r);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...(await ce(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await me({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>se(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await b(e.node_id);return await F(f??e)}c(Kn,"cancelRun");const be=200;async function ea(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>be)throw S(`name exceeds ${be} characters`,"name");const n=await Be(e.node_id,{name:a});return n.window&&Je(n.window,je(n)),await F(n)}c(ea,"renameRun");async function ta(e,t={config:vt,client:bt}){await me({run_id:e.node_id},"the run was deleted");const a=await q(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(p=>p.node_id)));if((await Promise.all(a.map(u=>se(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await Ke(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 W(a,async u=>{const p=await $e(u);if(p.app===null)throw new Error(`run node missing during deletion: ${u}`);return p}),f=await(await M()).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:u}of f)try{await te().delete(u)}catch(p){if(!Ye(p))throw p}const r=await q(async u=>{for(const _ of a){const i=await Ue(u,_);i!==null&&i.deleted_at===null&&await He(u,i)}const p=await Dt([e.node_id],u);await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await u.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 u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:_}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(_,_);return p});for(const u of d)await Pe(u);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Wt(r,t)}}c(ta,"deleteRun");async function Wt(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(r=>a.deleteUpload(r).then(async()=>{await Ot(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??Tt),f.unref?.()})]),clearTimeout(f),e.length-n.size}c(Wt,"deleteReleasedUploads");async function na(e,t,a){await H(e,t),await K(e);const n=await q(async i=>{const l=await i.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),y=new Map;for(const N of l)y.set(N.node_id,(await i.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(N.node_id)).map(I=>I.session_id));const E=(await i.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await i.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,E),D=await r.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
12
+ ORDER BY sequence_number`).all(e,E),D=await i.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,E);return{nodes:p,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:_,latestSequence:i,completed:s,deltas:m}=n,l=await x(d,async r=>({node_id:r.node_id,parent_node_id:r.parent,conversations:await x(_.get(r.node_id)??[],async p=>{const{header:y,entries:u}=await ee().read(p);if(a==="entries")return{conversation_id:p,header:y,entries:u};const E=Fe.inMemory(y.cwd,void 0,[y,...u]),A=mt(E)??[],D=new Map(u.map((g,b)=>[g.id,b])),N=u.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=u.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),U=r.node_id===e?u.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const b=ie(u,g.message.timestamp);return b?.type==="runtime"&&b.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(b=>b.id===g)),...N,...I].sort((g,b)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(b.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:b})=>{const w=b,T=w.usage,$=w.role==="user"?ie(u,Number(w.timestamp)):null,be=$?.type==="human"||g===U,L=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"?be?"user":"custom":w.role,Oe=L==="custom"?w.role==="custom"?w.customType:$?.type==="runtime"?$.kind:"unknown":void 0,De=L==="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(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:Oe}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:De,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:p,messages:ve}})})),h=new Map(await Promise.all(l.map(async r=>[r.node_id,await _t(r.node_id)])));for(const r of s){const p=h.get(r.node_id);p!=null&&r.sequence_number>=p&&h.set(r.node_id,null)}const o=new Map;for(const r of m){const p=h.get(r.node_id);if(p==null||r.sequence_number<p)continue;const y=JSON.parse(r.body_json),u=o.get(r.node_id)??{thinking:"",text:""};r.type==="node.thinking.delta"?u.thinking+=y.delta:u.text+=y.delta,o.set(r.node_id,u)}const f=l.map(r=>({...r,in_progress_message:h.get(r.node_id)==null?null:o.get(r.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:i,nodes:f}}c(na,"traceRun");function aa(e,t,a){if(t===void 0){if(!e.some(n=>P(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{wt(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))&&!Ae(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}c(aa,"requestedScopes");export{z as IDEMPOTENCY_WINDOW_MS,Lt as RUN_DEADLINE_MAX_MS,It as RUN_DELETE_STORAGE_BUDGET_MS,Ne as RUN_NAME_MAX,R as RunError,Kn as cancelRun,Tt as cloudPersonScope,ta as deleteRun,Yn as idempotencyKeyOf,Zn as interruptRun,zn as listRuns,Vn as messageRun,q as ownedRun,Se as parseRunDeadlineMs,Gn as pruneExpiredIdempotencyKeys,ea as renameRun,aa as requestedScopes,Jn as runIsRunning,W as runObject,Xn as startRun,na as traceRun,Qn as waitRun};
14
+ ORDER BY sequence_number`).all(e,E);return{nodes:l,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:f,latestSequence:r,completed:s,deltas:u}=n,p=await W(d,async i=>({node_id:i.node_id,parent_node_id:i.parent,conversations:await W(f.get(i.node_id)??[],async l=>{const{header:y,entries:m}=await te().read(l);if(a==="entries")return{conversation_id:l,header:y,entries:m};const E=qe.inMemory(y.cwd,void 0,[y,...m]),A=lt(E)??[],D=new Map(m.map((g,v)=>[g.id,v])),N=m.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=m.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),$=i.node_id===e?m.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const v=re(m,g.message.timestamp);return v?.type==="runtime"&&v.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(v=>v.id===g)),...N,...I].sort((g,v)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(v.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:v})=>{const w=v,T=w.usage,P=w.role==="user"?re(m,Number(w.timestamp)):null,Oe=P?.type==="human"||g===$,L=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=L==="custom"?w.role==="custom"?w.customType:P?.type==="runtime"?P.kind:"unknown":void 0,Me=L==="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(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:l,messages:ve}})})),h=new Map(await Promise.all(p.map(async i=>[i.node_id,await wt(i.node_id)])));for(const i of s){const l=h.get(i.node_id);l!=null&&i.sequence_number>=l&&h.set(i.node_id,null)}const o=new Map;for(const i of u){const l=h.get(i.node_id);if(l==null||i.sequence_number<l)continue;const y=JSON.parse(i.body_json),m=o.get(i.node_id)??{thinking:"",text:""};i.type==="node.thinking.delta"?m.thinking+=y.delta:m.text+=y.delta,o.set(i.node_id,m)}const _=p.map(i=>({...i,in_progress_message:h.get(i.node_id)==null?null:o.get(i.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:_}}c(na,"traceRun");function aa(e,t,a){if(t===void 0){if(!e.some(n=>B(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{gt(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}c(aa,"requestedScopes");export{Q as IDEMPOTENCY_WINDOW_MS,Lt as RUN_DEADLINE_MAX_MS,Tt as RUN_DELETE_STORAGE_BUDGET_MS,be as RUN_NAME_MAX,R as RunError,Kn as cancelRun,k as cloudPersonScope,ta as deleteRun,Yn as idempotencyKeyOf,Zn as interruptRun,zn as listRuns,Vn as messageRun,H as ownedRun,Ne as parseRunDeadlineMs,Gn as pruneExpiredIdempotencyKeys,ea as renameRun,aa as requestedScopes,Jn as runIsRunning,F as runObject,Xn as startRun,na as traceRun,Qn as waitRun};
@@ -1 +1 @@
1
- var p=Object.defineProperty;var o=(n,t)=>p(n,"name",{value:t,configurable:!0});import{ModelRegistry as h}from"@earendil-works/pi-coding-agent";import{boundaryRootedTree as f}from"../session-visibility.js";import{isUnknownModel as M}from"../model-selection.js";import{BUILTIN_SLASH_COMMANDS as b}from"../pi-vendored.js";import{isDeterministicCommandExpansion as y}from"../command-expansion.js";import{registrationChatSurface as k,templateChatSurface as T}from"../command-surface.js";function m(n){return new h(n.modelRuntime)}o(m,"registryOf");const u=o(n=>n===void 0||M(n)?null:{provider:n.provider,id:n.id},"toModelRef"),S=o(n=>`${n.provider}/${n.id}`,"modelKey");function D(n){const t=[];for(const e of b)t.push({name:e.name,description:e.description,source:"builtin",gatewayCapable:!1});try{for(const e of n.extensionRunner.getRegisteredCommands()){const l=e.expansion;t.push({name:e.invocationName,description:e.description??"",source:"command",...y(l)?{expansion:l}:{},...k(e)})}}catch{}try{for(const e of n.promptTemplates)t.push({name:e.name,description:e.description,source:"template",template:e.content,...T(e)})}catch{}return t}o(D,"buildCommandList");function A(n,t,e){return{type:"data",id:n,kind:"list_memory_refs",refs:t,engineLeadingCommandNames:e}}o(A,"buildListMemoryRefsData");function R(n,t){const e=m(t);let l=[];try{l=e.getAvailable().map(S)}catch{}return{type:"data",id:n,kind:"list_models",models:e.getAll(),current:u(t.model),availableIds:l,scopedModels:t.scopedModels.map(a=>({model:a.model,thinkingLevel:a.thinkingLevel})),enabledModelIds:t.settingsManager.getEnabledModels()??null}}o(R,"buildListModelsData");function P(n,t){return{type:"data",id:n,kind:"list_scoped_models",allModels:m(t).getAll(),enabledModelIds:t.settingsManager.getEnabledModels()??null}}o(P,"buildScopedModelsData");function F(n,t,e){const l=t.sessionManager,a=e!==void 0?f(l.getTree(),e):l.getTree(),r=new Set,s=o(d=>{for(const c of d)r.add(c.entry.id),s(c.children)},"collectEntryIds");s(a);const g=t.getUserMessagesForForking().filter(d=>r.has(d.entryId)).map(d=>({id:d.entryId,text:d.text,timestamp:l.getEntry(d.entryId)?.timestamp})),i=l.getLeafId();return{type:"data",id:n,kind:"get_tree",tree:a,currentLeafId:i!==null&&r.has(i)?i:null,forkPoints:g}}o(F,"buildGetTreeData");function _(n,t){const e=t.settingsManager;let l=[];try{l=t.resourceLoader.getThemes().themes.map(i=>i.name??"").filter(i=>i!=="")}catch{}const a=e.getDefaultProvider(),r=e.getDefaultModel();let s=[];try{s=t.modelRuntime.getAvailableSnapshot()}catch{}const g={autoCompact:t.autoCompactionEnabled,defaultModel:a&&r?`${a}/${r}`:"not set",availableDefaultModels:s,showImages:e.getShowImages(),imageWidthCells:e.getImageWidthCells(),autoResizeImages:e.getImageAutoResize(),blockImages:e.getBlockImages(),enableSkillCommands:e.getEnableSkillCommands(),steeringMode:t.steeringMode,followUpMode:t.followUpMode,transport:e.getTransport(),httpIdleTimeoutMs:e.getHttpIdleTimeoutMs(),thinkingLevel:t.thinkingLevel,availableThinkingLevels:t.getAvailableThinkingLevels(),modelThinkingLevels:e.getAllModelThinkingLevels(),currentTheme:e.getTheme()??"",terminalTheme:"dark",availableThemes:l,hideThinkingBlock:e.getHideThinkingBlock(),mermaidRenderingMode:e.getMermaidRenderingMode(),collapseChangelog:e.getCollapseChangelog(),enableInstallTelemetry:e.getEnableInstallTelemetry(),doubleEscapeAction:e.getDoubleEscapeAction(),treeFilterMode:e.getTreeFilterMode(),showHardwareCursor:e.getShowHardwareCursor(),editorPaddingX:e.getEditorPaddingX(),autocompleteMaxVisible:e.getAutocompleteMaxVisible(),quietStartup:e.getQuietStartup(),clearOnShrink:e.getClearOnShrink(),showTerminalProgress:e.getShowTerminalProgress(),tuiMode:e.getTuiMode(),fullscreenExitOutput:e.getFullscreenExitOutput(),fullscreenScrollbar:e.getFullscreenScrollbar(),fullscreenCopyOnSelect:e.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:e.getFullscreenWheelScrollLines(),warnings:e.getWarnings(),defaultProjectTrust:e.getDefaultProjectTrust(),showCacheMissNotices:e.getShowCacheMissNotices(),cacheWarmingMode:e.getCacheWarmingMode(),outputPad:e.getOutputPad(),autoRetry:t.autoRetryEnabled,model:u(t.model)};return{type:"data",id:n,kind:"get_settings",settings:g}}o(_,"buildSettingsData");function O(n,t,e,l){const a=e.sessionManager;return(t==="all"?l.listAll():l.listDir(a.getCwd())).then(r=>({type:"data",id:n,kind:"list_sessions",scope:t,sessions:r,currentSessionFile:e.sessionFile}))}o(O,"buildSessionsData");export{D as buildCommandList,F as buildGetTreeData,A as buildListMemoryRefsData,R as buildListModelsData,P as buildScopedModelsData,O as buildSessionsData,_ as buildSettingsData,S as modelKey};
1
+ var p=Object.defineProperty;var l=(n,t)=>p(n,"name",{value:t,configurable:!0});import{ModelRegistry as h}from"@earendil-works/pi-coding-agent";import{boundaryRootedTree as f}from"../session-visibility.js";import{isUnknownModel as M}from"../model-selection.js";import{BUILTIN_SLASH_COMMANDS as b}from"../pi-vendored.js";import{isDeterministicCommandExpansion as y}from"../command-expansion.js";import{registrationChatSurface as S,templateChatSurface as k}from"../command-surface.js";function m(n){return new h(n.modelRuntime)}l(m,"registryOf");const u=l(n=>n===void 0||M(n)?null:{provider:n.provider,id:n.id},"toModelRef"),T=l(n=>`${n.provider}/${n.id}`,"modelKey");function E(n){const t=[];for(const e of b)t.push({name:e.name,description:e.description,source:"builtin",gatewayCapable:!1});try{for(const e of n.extensionRunner.getRegisteredCommands()){const o=e.expansion;t.push({name:e.invocationName,description:e.description??"",source:"command",...y(o)?{expansion:o}:{},...S(e)})}}catch{}try{for(const e of n.promptTemplates)t.push({name:e.name,description:e.description,source:"template",template:e.content,...k(e)})}catch{}return t}l(E,"buildCommandList");function A(n,t,e){return{type:"data",id:n,kind:"list_memory_refs",refs:t,engineLeadingCommandNames:e}}l(A,"buildListMemoryRefsData");function R(n,t){const e=m(t);let o=[];try{o=e.getAvailable().map(T)}catch{}return{type:"data",id:n,kind:"list_models",models:e.getAll(),current:u(t.model),availableIds:o,scopedModels:t.scopedModels.map(a=>({model:a.model,thinkingLevel:a.thinkingLevel})),enabledModelIds:t.settingsManager.getEnabledModels()??null}}l(R,"buildListModelsData");function P(n,t){return{type:"data",id:n,kind:"list_scoped_models",allModels:m(t).getAll(),enabledModelIds:t.settingsManager.getEnabledModels()??null}}l(P,"buildScopedModelsData");function F(n,t,e){const o=t.sessionManager,a=e!==void 0?f(o.getTree(),e):o.getTree(),r=new Set,s=l(d=>{for(const c of d)r.add(c.entry.id),s(c.children)},"collectEntryIds");s(a);const g=t.getUserMessagesForForking().filter(d=>r.has(d.entryId)).map(d=>({id:d.entryId,text:d.text,timestamp:o.getEntry(d.entryId)?.timestamp})),i=o.getLeafId();return{type:"data",id:n,kind:"get_tree",tree:a,currentLeafId:i!==null&&r.has(i)?i:null,forkPoints:g}}l(F,"buildGetTreeData");function _(n,t){const e=t.settingsManager;let o=[];try{o=t.resourceLoader.getThemes().themes.map(i=>i.name??"").filter(i=>i!=="")}catch{}const a=e.getDefaultProvider(),r=e.getDefaultModel();let s=[];try{s=t.modelRuntime.getAvailableSnapshot()}catch{}const g={autoCompact:t.autoCompactionEnabled,defaultModel:a&&r?`${a}/${r}`:"not set",availableDefaultModels:s,showImages:e.getShowImages(),imageWidthCells:e.getImageWidthCells(),autoResizeImages:e.getImageAutoResize(),blockImages:e.getBlockImages(),enableSkillCommands:e.getEnableSkillCommands(),steeringMode:t.steeringMode,followUpMode:t.followUpMode,transport:e.getTransport(),httpIdleTimeoutMs:e.getHttpIdleTimeoutMs(),thinkingLevel:t.thinkingLevel,availableThinkingLevels:t.getAvailableThinkingLevels(),modelThinkingLevels:e.getAllModelThinkingLevels(),currentTheme:e.getTheme()??"",terminalTheme:"dark",availableThemes:o,hideThinkingBlock:e.getHideThinkingBlock(),mermaidRenderingMode:e.getMermaidRenderingMode(),collapseChangelog:e.getCollapseChangelog(),enableInstallTelemetry:e.getEnableInstallTelemetry(),doubleEscapeAction:e.getDoubleEscapeAction(),treeFilterMode:e.getTreeFilterMode(),showHardwareCursor:e.getShowHardwareCursor(),editorPaddingX:e.getEditorPaddingX(),autocompleteMaxVisible:e.getAutocompleteMaxVisible(),quietStartup:e.getQuietStartup(),clearOnShrink:e.getClearOnShrink(),showTerminalProgress:e.getShowTerminalProgress(),tuiMode:e.getTuiMode(),fullscreenExitOutput:e.getFullscreenExitOutput(),fullscreenScrollbar:e.getFullscreenScrollbar(),fullscreenCopyOnSelect:e.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:e.getFullscreenWheelScrollLines(),warnings:e.getWarnings(),defaultProjectTrust:e.getDefaultProjectTrust(),showCacheMissNotices:e.getShowCacheMissNotices(),cacheWarmingMode:e.getCacheWarmingMode(),outputPad:e.getOutputPad(),sessionShareDestination:e.getSessionShareDestination(),autoRetry:t.autoRetryEnabled,model:u(t.model)};return{type:"data",id:n,kind:"get_settings",settings:g}}l(_,"buildSettingsData");function O(n,t,e,o){const a=e.sessionManager;return(t==="all"?o.listAll():o.listDir(a.getCwd())).then(r=>({type:"data",id:n,kind:"list_sessions",scope:t,sessions:r,currentSessionFile:e.sessionFile}))}l(O,"buildSessionsData");export{E as buildCommandList,F as buildGetTreeData,A as buildListMemoryRefsData,R as buildListModelsData,P as buildScopedModelsData,O as buildSessionsData,_ as buildSettingsData,T as modelKey};
@@ -1,4 +1,4 @@
1
- var l=Object.defineProperty;var r=(e,t)=>l(e,"name",{value:t,configurable:!0});import{Type as i}from"@earendil-works/pi-ai";import{headlessToolCall as m}from"./headless-pi.js";import{defaultProvider as u,modelLadders as c}from"./model-selection.js";import{lightModel as d}from"./naming.js";import{normalizeToolGroupSummary as p}from"../../shared/tool-groups.js";const h=600,f=300,g=400,y=1e3,b=1e4,v=45e3;function n(e,t){const o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}r(n,"capped");function a(e,t){try{return n(typeof e=="string"?e:JSON.stringify(e),t)}catch{return n(String(e),t)}}r(a,"printable");function E(e,t){const o=[`Previous visible message: ${n(e,h)||"(none)"}`,"Between-message activity:"];for(const s of t)s.type==="tool"?o.push(`- tool ${s.name}(${a(s.args,f)})`):s.type==="result"?o.push(`- ${s.isError?"error":"result"} ${s.name}: ${a(s.result,g)}`):o.push(`- context: ${n(s.text,y)}`);return n(o.join(`
1
+ var l=Object.defineProperty;var r=(e,t)=>l(e,"name",{value:t,configurable:!0});import{Type as i}from"typebox";import{headlessToolCall as m}from"./headless-pi.js";import{defaultProvider as u,modelLadders as c}from"./model-selection.js";import{lightModel as d}from"./naming.js";import{normalizeToolGroupSummary as p}from"../../shared/tool-groups.js";const h=600,f=300,g=400,y=1e3,b=1e4,v=45e3;function n(e,t){const o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}r(n,"capped");function a(e,t){try{return n(typeof e=="string"?e:JSON.stringify(e),t)}catch{return n(String(e),t)}}r(a,"printable");function E(e,t){const o=[`Previous visible message: ${n(e,h)||"(none)"}`,"Between-message activity:"];for(const s of t)s.type==="tool"?o.push(`- tool ${s.name}(${a(s.args,f)})`):s.type==="result"?o.push(`- ${s.isError?"error":"result"} ${s.name}: ${a(s.result,g)}`):o.push(`- context: ${n(s.text,y)}`);return n(o.join(`
2
2
  `),b)}r(E,"serializeToolGroup");const w='Create a structured recap of this coding-agent tool activity. Prefer 1\u20133 bullets and use at most 5 only for distinct meaningful outcomes. Each bullet must be an extremely readable plain-English outcome of 3\u201310 words, without markdown markers. Describe what changed or was accomplished, not the tools, commands, or investigation steps; for code work, say what capability was added to a one- or two-phrase plain-English part of the system, such as "Added scheduling controls to the worker service." Never include IDs, hashes, paths, filenames, command names, tool names, raw values, or report text. Omit inbox receipt, delivery, and queueing; node-response and report bookkeeping; help lookups; status checks; and summary-generation activity. A node response may support a substantive outcome, but its arrival or resummarization is never itself an outcome. If no meaningful outcome remains after those omissions, submit the single bullet "No meaningful changes." Count distinct files removed from disk only when the supplied tool arguments or results evidence them; otherwise use zero, even when the corresponding mechanics are omitted from bullets. A deleted file is one that no longer exists after the segment, never a file that was merely edited or overwritten, and a recursive or wildcard removal of an unknown number of files counts as one. Do not invent success when a result shows failure. Call submit_summary exactly once with bullets and filesDeleted, then stop.',S=i.Object({bullets:i.Array(i.String({minLength:1,maxLength:120,description:"A very short, plain-English outcome without bullet markers, identifiers, or operational bookkeeping."}),{minItems:1,maxItems:5}),filesDeleted:i.Integer({minimum:0,description:"Count of distinct files removed from disk during the supplied segment, or zero when none are evidenced."})},{additionalProperties:!1});async function P(e){const t=c(),o=`${u(t)}/light`;return p(await m({systemPrompt:w,userPrompt:`<tool-group>
3
3
  ${e}
4
4
  </tool-group>
@@ -1,4 +1,4 @@
1
- var d=Object.defineProperty;var r=(s,e)=>d(s,"name",{value:e,configurable:!0});import{Type as l}from"@earendil-works/pi-ai";import{headlessToolCall as p}from"./headless-pi.js";import{defaultProvider as h,modelLadders as c}from"./model-selection.js";import{lightModel as g}from"./naming.js";const u=4e3,y=12e3,m=4e4,w=6e4,f="You rewrite a coding agent's several messages to a person into the ONE reply the agent would have sent had it known everything at the end. You receive only the person's message and the agent's messages in the order they were written. Rules: later statements supersede earlier ones \u2014 drop plans that were completed, guesses that were corrected, and status that went stale; keep decisions, results, numbers, document links like [[name]], file paths, commands, errors and open questions verbatim; never add anything the messages did not say; do not mention that this is a rewrite or that there were several messages; write as the agent, speaking to the person, in the agent's own tone and markdown; be as short as the content allows. Call submit_reply exactly once with the reply, then stop.",_=l.Object({text:l.String({minLength:1,description:"The single consolidated reply, in markdown."})},{additionalProperties:!1});function i(s,e){const n=s.trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}r(i,"capped");function P(s){const e=s.map(t=>i(t,y));let n=e.reduce((t,o)=>t+o.length,0);for(let t=1;t<e.length-1&&n>m;t+=1){const o=e[t].length,a=i(e[t],Math.max(200,o-(n-m)));e[t]=a,n-=o-a.length}return e}r(P,"budgetProse");function T(s,e){const n=s.trim()===""?"(the agent was started without a typed message)":i(s,u),t=P(e).map((o,a)=>`<agent-message n="${a+1}">
1
+ var d=Object.defineProperty;var r=(s,e)=>d(s,"name",{value:e,configurable:!0});import{Type as l}from"typebox";import{headlessToolCall as p}from"./headless-pi.js";import{defaultProvider as h,modelLadders as c}from"./model-selection.js";import{lightModel as g}from"./naming.js";const u=4e3,y=12e3,m=4e4,w=6e4,f="You rewrite a coding agent's several messages to a person into the ONE reply the agent would have sent had it known everything at the end. You receive only the person's message and the agent's messages in the order they were written. Rules: later statements supersede earlier ones \u2014 drop plans that were completed, guesses that were corrected, and status that went stale; keep decisions, results, numbers, document links like [[name]], file paths, commands, errors and open questions verbatim; never add anything the messages did not say; do not mention that this is a rewrite or that there were several messages; write as the agent, speaking to the person, in the agent's own tone and markdown; be as short as the content allows. Call submit_reply exactly once with the reply, then stop.",_=l.Object({text:l.String({minLength:1,description:"The single consolidated reply, in markdown."})},{additionalProperties:!1});function i(s,e){const n=s.trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}r(i,"capped");function P(s){const e=s.map(t=>i(t,y));let n=e.reduce((t,o)=>t+o.length,0);for(let t=1;t<e.length-1&&n>m;t+=1){const o=e[t].length,a=i(e[t],Math.max(200,o-(n-m)));e[t]=a,n-=o-a.length}return e}r(P,"budgetProse");function T(s,e){const n=s.trim()===""?"(the agent was started without a typed message)":i(s,u),t=P(e).map((o,a)=>`<agent-message n="${a+1}">
2
2
  ${o}
3
3
  </agent-message>`);return`<person-message>
4
4
  ${n}
@@ -26,11 +26,11 @@ export interface ResolveOptions {
26
26
  taken?: readonly string[];
27
27
  }
28
28
  /** Re-check, inside the accepting write, that every used upload is still this
29
- * grantee's and not pending delete (the due-work tick or an app removal may
29
+ * grantee's (and person's, see `ownsUpload`) and not pending delete (the due-work tick or an app removal may
30
30
  * have released it while its bytes were fetched). */
31
- export declare function assertUploadsUsable(grantee: string, uses: readonly AttachmentUse[], db: CanvasDb): Promise<void>;
31
+ export declare function assertUploadsUsable(grantee: string, person: string | undefined, uses: readonly AttachmentUse[], db: CanvasDb): Promise<void>;
32
32
  /** Fetch every upload a storage URL in `text` names into the blob store at `attachments/<rootId>/<sha256>` and replace
33
33
  * exactly each URL's span with the path the node's broker downloads that file to (`<app space>/nodes/<rootId>/attachments/<name>`).
34
34
  * The control plane writes no file there. Without configured storage the text passes through unchanged. A failure leaves
35
35
  * at most content-keyed blobs, which are harmless and are deleted with the node. */
36
- export declare function resolveStorageUrls(grantee: string, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
36
+ export declare function resolveStorageUrls(grantee: string, person: string | undefined, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
@@ -1 +1 @@
1
- var M=Object.defineProperty;var h=(e,t)=>M(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{extname as H,join as v}from"node:path";import{Writable as B}from"node:stream";import{pipeline as O}from"node:stream/promises";import{blobStore as W}from"../blobs/index.js";import{appSpace as Z}from"../layout.js";import{RunError as A}from"../runs/operations.js";import{storageClient as j,storageConfig as q,StorageRefused as D}from"./client.js";import{getUpload as E,runUsesPath as F}from"./tables.js";const G=11e4,m=h((e,t)=>new A(400,"invalid_request",t,void 0,{url:e}),"refused"),b=h(e=>new A(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function T(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}h(T,"shownUrl");async function N(e,t,o,r,i){const c=`${t}/`,w=[];let f=0;for(let d=e.indexOf(c,f);d!==-1;d=e.indexOf(c,f)){const a=T(e,d),g=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(d+c.length));if(!g)throw m(a,`storage URL ${a} does not name an upload`);if(g[1]!==o)throw m(a,`storage URL ${a} names another runtime`);const l=await E(g[2],i);if(!l||l.grantee!==r)throw m(a,`storage URL ${a} names an unknown upload`);if(l.delete_pending_since)throw m(a,`storage URL ${a} names a deleted upload`);const u=d+c.length+g[0].length,p=encodeURIComponent(l.name);if(!e.startsWith(p,u))throw m(a,`storage URL ${a} does not match the upload's name`);w.push({start:d,end:u+p.length,upload:l}),f=u+p.length}return w}h(N,"matchStorageUrls");async function ae(e,t,o){for(const r of t){const i=await E(r.upload_id,o);if(!i||i.grantee!==e||i.delete_pending_since)throw m(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}h(ae,"assertUploadsUsable");function P(e,t){if(t===1)return e;const o=H(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}h(P,"candidate");async function se(e,t,o,r={}){const i={text:o,uses:[]},c=(r.config??q)();if(!c||!o.includes(`${c.base_url}/`))return i;const w=(r.client??j)(),f=await N(o,c.base_url,w.runtimeId,e);if(!f.length)return i;const d=v(Z(e).nodes,t,"attachments"),a=AbortSignal.timeout(r.budgetMs??G),g=await(r.blobs??W)(),l=new Set(r.taken),u=new Map;for(const{upload:s,start:C}of f){if(u.has(s.upload_id))continue;const _=T(o,C);let y;try{y=await w.fetchUpload(s.upload_id,a)}catch(n){throw n instanceof D?m(_,n.status===409?`storage URL ${_} names an upload that was never finished`:`storage URL ${_} names an unknown upload`):a.aborted?b("attachments could not be fetched within 110 s"):n}const S=[],L=x("sha256");try{await O(y.body,new B({write(n,I,z){L.update(n),S.push(n),z()}}),{signal:a})}catch(n){throw a.aborted?b("attachments could not be fetched within 110 s"):b(`storage stopped sending ${s.name}: ${n instanceof Error?n.message:String(n)}`)}const R=Buffer.concat(S);if(R.length!==s.size)throw b(`storage sent ${R.length} of ${s.size} bytes of ${s.name}`);const k=`attachments/${t}/${L.digest("hex")}`;try{await g.put(k,R)}catch(n){throw b(`the attachment ${s.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let $="";for(let n=1;$=v(d,P(s.name,n)),!(!l.has($)&&!await F(t,$));n++);l.add($),u.set(s.upload_id,{upload_id:s.upload_id,path:$,url:_,blob_key:k})}let p="",U=0;for(const s of f)p+=o.slice(U,s.start)+u.get(s.upload.upload_id).path,U=s.end;return p+=o.slice(U),{text:p,uses:[...u.values()]}}h(se,"resolveStorageUrls");export{G as ATTACHMENT_FETCH_BUDGET_MS,ae as assertUploadsUsable,se as resolveStorageUrls};
1
+ var H=Object.defineProperty;var c=(e,t)=>H(e,"name",{value:t,configurable:!0});import{createHash as B}from"node:crypto";import{extname as O,join as A}from"node:path";import{Writable as W}from"node:stream";import{pipeline as Z}from"node:stream/promises";import{blobStore as j}from"../blobs/index.js";import{appSpace as q}from"../layout.js";import{RunError as E}from"../runs/operations.js";import{storageClient as D,storageConfig as F,StorageRefused as G}from"./client.js";import{getUpload as T,runUsesPath as N}from"./tables.js";const P=11e4,g=c((e,t)=>new E(400,"invalid_request",t,void 0,{url:e}),"refused"),_=c(e=>new E(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function C(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}c(C,"shownUrl");function z(e,t,o){return e.grantee===t&&(o===void 0||e.sub===o)}c(z,"ownsUpload");async function I(e,t,o,i,r,d){const l=`${t}/`,$=[];let p=0;for(let u=e.indexOf(l,p);u!==-1;u=e.indexOf(l,p)){const a=C(e,u),w=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(u+l.length));if(!w)throw g(a,`storage URL ${a} does not name an upload`);if(w[1]!==o)throw g(a,`storage URL ${a} names another runtime`);const f=await T(w[2],d);if(!f||!z(f,i,r))throw g(a,`storage URL ${a} names an unknown upload`);if(f.delete_pending_since)throw g(a,`storage URL ${a} names a deleted upload`);const h=u+l.length+w[0].length,m=encodeURIComponent(f.name);if(!e.startsWith(m,h))throw g(a,`storage URL ${a} does not match the upload's name`);$.push({start:u,end:h+m.length,upload:f}),p=h+m.length}return $}c(I,"matchStorageUrls");async function re(e,t,o,i){for(const r of o){const d=await T(r.upload_id,i);if(!d||!z(d,e,t)||d.delete_pending_since)throw g(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}c(re,"assertUploadsUsable");function J(e,t){if(t===1)return e;const o=O(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}c(J,"candidate");async function ie(e,t,o,i,r={}){const d={text:i,uses:[]},l=(r.config??F)();if(!l||!i.includes(`${l.base_url}/`))return d;const $=(r.client??D)(),p=await I(i,l.base_url,$.runtimeId,e,t);if(!p.length)return d;const u=A(q(e).nodes,o,"attachments"),a=AbortSignal.timeout(r.budgetMs??P),w=await(r.blobs??j)(),f=new Set(r.taken),h=new Map;for(const{upload:s,start:M}of p){if(h.has(s.upload_id))continue;const U=C(i,M);let S;try{S=await $.fetchUpload(s.upload_id,a)}catch(n){throw n instanceof G?g(U,n.status===409?`storage URL ${U} names an upload that was never finished`:`storage URL ${U} names an unknown upload`):a.aborted?_("attachments could not be fetched within 110 s"):n}const L=[],k=B("sha256");try{await Z(S.body,new W({write(n,K,x){k.update(n),L.push(n),x()}}),{signal:a})}catch(n){throw a.aborted?_("attachments could not be fetched within 110 s"):_(`storage stopped sending ${s.name}: ${n instanceof Error?n.message:String(n)}`)}const y=Buffer.concat(L);if(y.length!==s.size)throw _(`storage sent ${y.length} of ${s.size} bytes of ${s.name}`);const v=`attachments/${o}/${k.digest("hex")}`;try{await w.put(v,y)}catch(n){throw _(`the attachment ${s.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let b="";for(let n=1;b=A(u,J(s.name,n)),!(!f.has(b)&&!await N(o,b));n++);f.add(b),h.set(s.upload_id,{upload_id:s.upload_id,path:b,url:U,blob_key:v})}let m="",R=0;for(const s of p)m+=i.slice(R,s.start)+h.get(s.upload.upload_id).path,R=s.end;return m+=i.slice(R),{text:m,uses:[...h.values()]}}c(ie,"resolveStorageUrls");export{P as ATTACHMENT_FETCH_BUDGET_MS,re as assertUploadsUsable,ie as resolveStorageUrls};
@@ -96,7 +96,9 @@ export interface StorageClient {
96
96
  * after it was checked cannot be copied; the caller closes `fd`. */
97
97
  putFileBytes(uploadLink: string, fd: number, size: number, mediaType: string): Promise<void>;
98
98
  }
99
- /** The configured storage, or null when this runtime has none. */
99
+ /** The configured storage, or null when this runtime has none. A cloud role has no person outside a request and its people's settings never
100
+ * hold storage, so it takes the deployment's `CRTR_BOOT_STORAGE_URL` (as `directoryIssuer` takes `CRTR_DIRECTORY_URL`); anything else reads
101
+ * the user config's `runtime.storage`, which the daemon writes at boot from that same variable. */
100
102
  export declare function storageConfig(): StorageConfig | null;
101
103
  /** The storage client for the configured runtime. Refuses with
102
104
  * `storage_unavailable` when no storage is configured. */
@@ -1,3 +1,3 @@
1
- var x=Object.defineProperty;var i=(r,d)=>x(r,"name",{value:d,configurable:!0});import{createReadStream as v,read as S,statSync as $}from"node:fs";import{Readable as _}from"node:stream";import{promisify as T}from"node:util";import{readConfig as E}from"../config.js";import{directoryIssuer as O}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as C,runtimeId as R}from"../grants/sync.js";const G=104857600;class m extends Error{static{i(this,"StorageRefused")}status;code;constructor(d,u,l){super(l),this.status=d,this.code=u}}const j=T(S);async function*U(r,d){let u=0;for(;u<d;){const l=Buffer.allocUnsafe(Math.min(1048576,d-u)),{bytesRead:f}=await j(r,l,0,l.length,u);if(f===0)throw new Error("file shrank while it was being copied");u+=f,yield l.subarray(0,f)}}i(U,"fdChunks");const s=i(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function P(){const r=E("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}i(P,"storageConfig");let w;function F(){const r=P(),d=O();if(!r||!d)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${d}
1
+ var x=Object.defineProperty;var l=(r,s)=>x(r,"name",{value:s,configurable:!0});import{createReadStream as v,read as S,statSync as $}from"node:fs";import{Readable as g}from"node:stream";import{promisify as T}from"node:util";import{isCloudRole as E}from"../canvas/person-state.js";import{readConfig as O}from"../config.js";import{directoryIssuer as R}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as C,runtimeId as U}from"../grants/sync.js";const J=104857600;class m extends Error{static{l(this,"StorageRefused")}status;code;constructor(s,u,d){super(d),this.status=s,this.code=u}}const j=T(S);async function*A(r,s){let u=0;for(;u<s;){const d=Buffer.allocUnsafe(Math.min(1048576,s-u)),{bytesRead:f}=await j(r,d,0,d.length,u);if(f===0)throw new Error("file shrank while it was being copied");u+=f,yield d.subarray(0,f)}}l(A,"fdChunks");const i=l(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function P(){if(E()){const s=process.env.CRTR_BOOT_STORAGE_URL?.replace(/\/$/,"");return s?{service_url:s,base_url:s}:null}const r=O("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}l(P,"storageConfig");let w;function X(){const r=P(),s=R();if(!r||!s)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${s}
2
2
  ${r.service_url}
3
- ${r.base_url}`;return w?.key!==u&&(w={key:u,client:A(r,()=>C(d,r.service_url),R())}),w.client}i(F,"storageClient");function J(){w=void 0}i(J,"resetStorageClient");function A(r,d,u){let l,f;const k=i(async()=>{if(l&&l.expires_at-6e4>Date.now())return l.access_token;f??=d().finally(()=>{f=void 0});try{l=await f}catch(t){throw s(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return l.access_token},"bearer"),c=i(async(t,e,n={})=>{const p=[AbortSignal.timeout(n.timeoutMs??1e4),...n.signal?[n.signal]:[]];let o;try{o=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(p),headers:{Authorization:`Bearer ${await k()}`,...n.body===void 0?{}:{"Content-Type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(a){throw a instanceof b?a:s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(o.status===401&&(l=void 0),o.status===404||o.status===409){const a=await o.json().catch(()=>({})),g=a.error?.code??a.code??(o.status===404?"not_found":"not_uploaded");throw new m(o.status,g,a.error?.message??a.message??`storage answered ${o.status}`)}if(!o.ok)throw await o.body?.cancel().catch(()=>{}),s(`storage answered ${o.status} to ${t} ${e.split("?")[0]}`);return o},"call"),y=i(async t=>{try{return await t.json()}catch{throw s("storage answered with an invalid body")}},"json"),h=i(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await y(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const n=await c("GET",`/v1/uploads/${h(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!n.body)throw s("storage answered with no body");const p=n.headers.get("content-length");return{body:_.fromWeb(n.body),size:p===null?null:Number(p),media_type:n.headers.get("content-type")}},async signDownload(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await y(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw s("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async putShareBytes(t,e,n,p){if($(e).size!==n)throw new Error("shared file changed size while it was being copied");let o;try{o=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:_.toWeb(v(e)),duplex:"half"})}catch(a){throw s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(await o.body?.cancel().catch(()=>{}),!o.ok)throw s(`storage answered ${o.status} to the share upload`)},async deleteShare(t){try{await c("DELETE",`/v1/shares/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await y(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await y(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await y(await c("POST",`/v1/outbound/${h(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,n,p){const o=_.from(U(e,n));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:_.toWeb(o),duplex:"half"})}catch(g){throw s(`storage could not be reached: ${g instanceof Error?g.message:String(g)}`)}finally{o.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw s(`storage answered ${a.status} to the upload`)}}}i(A,"createStorageClient");function X(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}i(X,"invalidStorageName");export{m as StorageRefused,G as UPLOAD_MAX_BYTES,A as createStorageClient,X as invalidStorageName,J as resetStorageClient,F as storageClient,P as storageConfig};
3
+ ${r.base_url}`;return w?.key!==u&&(w={key:u,client:L(r,()=>C(s,r.service_url),U())}),w.client}l(X,"storageClient");function Y(){w=void 0}l(Y,"resetStorageClient");function L(r,s,u){let d,f;const k=l(async()=>{if(d&&d.expires_at-6e4>Date.now())return d.access_token;f??=s().finally(()=>{f=void 0});try{d=await f}catch(t){throw i(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return d.access_token},"bearer"),c=l(async(t,e,n={})=>{const p=[AbortSignal.timeout(n.timeoutMs??1e4),...n.signal?[n.signal]:[]];let o;try{o=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(p),headers:{Authorization:`Bearer ${await k()}`,...n.body===void 0?{}:{"Content-Type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(a){throw a instanceof b?a:i(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(o.status===401&&(d=void 0),o.status===404||o.status===409){const a=await o.json().catch(()=>({})),_=a.error?.code??a.code??(o.status===404?"not_found":"not_uploaded");throw new m(o.status,_,a.error?.message??a.message??`storage answered ${o.status}`)}if(!o.ok)throw await o.body?.cancel().catch(()=>{}),i(`storage answered ${o.status} to ${t} ${e.split("?")[0]}`);return o},"call"),y=l(async t=>{try{return await t.json()}catch{throw i("storage answered with an invalid body")}},"json"),h=l(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await y(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const n=await c("GET",`/v1/uploads/${h(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!n.body)throw i("storage answered with no body");const p=n.headers.get("content-length");return{body:g.fromWeb(n.body),size:p===null?null:Number(p),media_type:n.headers.get("content-type")}},async signDownload(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await y(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw i("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async putShareBytes(t,e,n,p){if($(e).size!==n)throw new Error("shared file changed size while it was being copied");let o;try{o=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:g.toWeb(v(e)),duplex:"half"})}catch(a){throw i(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(await o.body?.cancel().catch(()=>{}),!o.ok)throw i(`storage answered ${o.status} to the share upload`)},async deleteShare(t){try{await c("DELETE",`/v1/shares/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await y(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await y(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await y(await c("POST",`/v1/outbound/${h(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,n,p){const o=g.from(A(e,n));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:g.toWeb(o),duplex:"half"})}catch(_){throw i(`storage could not be reached: ${_ instanceof Error?_.message:String(_)}`)}finally{o.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw i(`storage answered ${a.status} to the upload`)}}}l(L,"createStorageClient");function q(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}l(q,"invalidStorageName");export{m as StorageRefused,J as UPLOAD_MAX_BYTES,L as createStorageClient,q as invalidStorageName,Y as resetStorageClient,X as storageClient,P as storageConfig};
@@ -1,9 +1,11 @@
1
1
  import { type CanvasDb } from '../canvas/db.js';
2
2
  /** Row helpers for the v60 file-transfer tables. Each takes an optional handle
3
3
  * so a caller inside `withCanvasWrite` passes its transaction. */
4
+ /** `sub` is the person a cloud role's upload was made for; null on a Mac and on every row written before the column existed. */
4
5
  export interface UploadRow {
5
6
  upload_id: string;
6
7
  grantee: string;
8
+ sub: string | null;
7
9
  name: string;
8
10
  media_type: string;
9
11
  size: number;
@@ -29,7 +31,9 @@ export interface ShareRow {
29
31
  status: 'on' | 'off';
30
32
  object_deleted_at: string | null;
31
33
  }
32
- export declare function insertUpload(row: Omit<UploadRow, 'delete_pending_since'>, db?: CanvasDb): Promise<void>;
34
+ export declare function insertUpload(row: Omit<UploadRow, 'delete_pending_since' | 'sub'> & {
35
+ sub?: string;
36
+ }, db?: CanvasDb): Promise<void>;
33
37
  export declare function getUpload(uploadId: string, db?: CanvasDb): Promise<UploadRow | null>;
34
38
  export declare function deleteUploadRow(uploadId: string, db?: CanvasDb): Promise<void>;
35
39
  /** Uploads the runtime owes storage a delete for, oldest first. */
@@ -1,3 +1,3 @@
1
- var E=Object.defineProperty;var r=(a,e)=>E(a,"name",{value:e,configurable:!0});import{openDb as l}from"../canvas/db.js";import{filterAsync as _}from"../async-array.js";const n=r(async a=>a??await l(),"handle"),d=r(()=>new Date().toISOString(),"now");async function w(a,e){await(await n(e)).prepare("INSERT INTO uploads (upload_id, grantee, name, media_type, size, created_at, delete_pending_since) VALUES (?, ?, ?, ?, ?, ?, NULL)").run(a.upload_id,a.grantee,a.name,a.media_type,a.size,a.created_at)}r(w,"insertUpload");async function f(a,e){return await(await n(e)).prepare("SELECT * FROM uploads WHERE upload_id = ?").get(a)??null}r(f,"getUpload");async function T(a,e){await(await n(e)).prepare("DELETE FROM uploads WHERE upload_id = ?").run(a)}r(T,"deleteUploadRow");async function L(a){return await(await n(a)).prepare("SELECT * FROM uploads WHERE delete_pending_since IS NOT NULL ORDER BY delete_pending_since, upload_id").all()}r(L,"pendingUploadDeletes");async function u(a,e,t=d()){const i=(await n(e)).prepare("UPDATE uploads SET delete_pending_since = COALESCE(delete_pending_since, ?) WHERE upload_id = ?");for(const s of a)await i.run(t,s)}r(u,"markUploadsDeletePending");async function O(a,e){const t=(await n(e)).prepare("INSERT INTO upload_uses (upload_id, run_id, path, blob_key) VALUES (?, ?, ?, ?)");for(const i of a)await t.run(i.upload_id,i.run_id,i.path,i.blob_key??null)}r(O,"insertUploadUses");async function D(a,e,t){return await(await n(t)).prepare("SELECT 1 AS used FROM upload_uses WHERE run_id = ? AND path = ?").get(a,e)!==void 0}r(D,"runUsesPath");async function y(a,e){await(await n(e)).prepare("DELETE FROM upload_uses WHERE upload_id = ? AND run_id = ? AND path = ?").run(a.upload_id,a.run_id,a.path)}r(y,"deleteUploadUse");async function U(a,e,t){await(await n(t)).prepare("UPDATE uploads SET size = ? WHERE upload_id = ?").run(e,a)}r(U,"setUploadSize");async function x(a,e){return await(await n(e)).prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE path = ? ORDER BY run_id LIMIT 1").get(a)??null}r(x,"uploadUseAt");async function N(a,e){const t=await n(e);if(!a.length)return[];const i=a.map(()=>"?").join(","),s=(await t.prepareUncached(`SELECT DISTINCT upload_id FROM upload_uses WHERE run_id IN (${i})`).all(...a)).map(o=>o.upload_id);await t.prepareUncached(`DELETE FROM upload_uses WHERE run_id IN (${i})`).run(...a);const p=await _(s,async o=>!await t.prepare("SELECT 1 FROM upload_uses WHERE upload_id = ? LIMIT 1").get(o));return await u(p,t),p}r(N,"releaseRunUploads");async function g(a,e){return(await(await n(e)).prepare(`SELECT upload_id FROM uploads u WHERE delete_pending_since IS NULL AND created_at <= ?
1
+ var E=Object.defineProperty;var r=(a,e)=>E(a,"name",{value:e,configurable:!0});import{openDb as l}from"../canvas/db.js";import{filterAsync as _}from"../async-array.js";const n=r(async a=>a??await l(),"handle"),d=r(()=>new Date().toISOString(),"now");async function w(a,e){await(await n(e)).prepare("INSERT INTO uploads (upload_id, grantee, sub, name, media_type, size, created_at, delete_pending_since) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)").run(a.upload_id,a.grantee,a.sub??null,a.name,a.media_type,a.size,a.created_at)}r(w,"insertUpload");async function f(a,e){return await(await n(e)).prepare("SELECT * FROM uploads WHERE upload_id = ?").get(a)??null}r(f,"getUpload");async function T(a,e){await(await n(e)).prepare("DELETE FROM uploads WHERE upload_id = ?").run(a)}r(T,"deleteUploadRow");async function L(a){return await(await n(a)).prepare("SELECT * FROM uploads WHERE delete_pending_since IS NOT NULL ORDER BY delete_pending_since, upload_id").all()}r(L,"pendingUploadDeletes");async function u(a,e,t=d()){const s=(await n(e)).prepare("UPDATE uploads SET delete_pending_since = COALESCE(delete_pending_since, ?) WHERE upload_id = ?");for(const i of a)await s.run(t,i)}r(u,"markUploadsDeletePending");async function O(a,e){const t=(await n(e)).prepare("INSERT INTO upload_uses (upload_id, run_id, path, blob_key) VALUES (?, ?, ?, ?)");for(const s of a)await t.run(s.upload_id,s.run_id,s.path,s.blob_key??null)}r(O,"insertUploadUses");async function D(a,e,t){return await(await n(t)).prepare("SELECT 1 AS used FROM upload_uses WHERE run_id = ? AND path = ?").get(a,e)!==void 0}r(D,"runUsesPath");async function y(a,e){await(await n(e)).prepare("DELETE FROM upload_uses WHERE upload_id = ? AND run_id = ? AND path = ?").run(a.upload_id,a.run_id,a.path)}r(y,"deleteUploadUse");async function U(a,e,t){await(await n(t)).prepare("UPDATE uploads SET size = ? WHERE upload_id = ?").run(e,a)}r(U,"setUploadSize");async function x(a,e){return await(await n(e)).prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE path = ? ORDER BY run_id LIMIT 1").get(a)??null}r(x,"uploadUseAt");async function N(a,e){const t=await n(e);if(!a.length)return[];const s=a.map(()=>"?").join(","),i=(await t.prepareUncached(`SELECT DISTINCT upload_id FROM upload_uses WHERE run_id IN (${s})`).all(...a)).map(o=>o.upload_id);await t.prepareUncached(`DELETE FROM upload_uses WHERE run_id IN (${s})`).run(...a);const p=await _(i,async o=>!await t.prepare("SELECT 1 FROM upload_uses WHERE upload_id = ? LIMIT 1").get(o));return await u(p,t),p}r(N,"releaseRunUploads");async function g(a,e){return(await(await n(e)).prepare(`SELECT upload_id FROM uploads u WHERE delete_pending_since IS NULL AND created_at <= ?
2
2
  AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`).all(a)).map(t=>t.upload_id)}r(g,"staleUnusedUploads");async function A(a,e){await(await n(e)).prepare(`INSERT INTO shares (share_id, source_space, source_path, storage_key, url, created_by, created_at, expires_at, status, object_deleted_at)
3
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(a.share_id,a.source_space,a.source_path,a.storage_key,a.url,a.created_by,a.created_at,a.expires_at)}r(A,"insertShare");async function C(a,e){return await(await n(e)).prepare("SELECT * FROM shares WHERE share_id = ?").get(a)??null}r(C,"getShare");async function H(a,e){return a===null?await(await n(e)).prepare("SELECT * FROM shares ORDER BY created_at DESC, share_id").all():await(await n(e)).prepare("SELECT * FROM shares WHERE created_by = ? ORDER BY created_at DESC, share_id").all(a)}r(H,"listShares");async function c(a,e){await(await n(e)).prepare("UPDATE shares SET status = 'off' WHERE share_id = ?").run(a)}r(c,"turnShareOff");async function W(a,e){const t=await n(e),i=(await t.prepare("SELECT share_id FROM shares WHERE created_by = ? AND status = 'on'").all(a)).map(s=>s.share_id);return await t.prepare("UPDATE shares SET status = 'off' WHERE created_by = ? AND status = 'on'").run(a),i}r(W,"turnSharesOffFor");async function M(a=d(),e){const t=await n(e),i=(await t.prepare("SELECT share_id FROM shares WHERE status = 'on' AND expires_at IS NOT NULL AND expires_at <= ?").all(a)).map(s=>s.share_id);for(const s of i)await c(s,t);return i}r(M,"expireShares");async function m(a){return await(await n(a)).prepare("SELECT * FROM shares WHERE status = 'off' AND object_deleted_at IS NULL ORDER BY created_at, share_id").all()}r(m,"sharesOwingObjectDelete");async function F(a,e,t=d()){await(await n(e)).prepare("UPDATE shares SET object_deleted_at = COALESCE(object_deleted_at, ?) WHERE share_id = ?").run(t,a)}r(F,"markShareObjectDeleted");async function I(a,e,t=d()){const i=await n(e),s=(await i.prepare("SELECT upload_id FROM uploads WHERE grantee = ? AND delete_pending_since IS NULL").all(a)).map(p=>p.upload_id);return await u(s,i,t),s}r(I,"markGranteeUploadsDeletePending");export{T as deleteUploadRow,y as deleteUploadUse,M as expireShares,C as getShare,f as getUpload,A as insertShare,w as insertUpload,O as insertUploadUses,H as listShares,I as markGranteeUploadsDeletePending,F as markShareObjectDeleted,u as markUploadsDeletePending,L as pendingUploadDeletes,N as releaseRunUploads,D as runUsesPath,U as setUploadSize,m as sharesOwingObjectDelete,g as staleUnusedUploads,c as turnShareOff,W as turnSharesOffFor,x as uploadUseAt};
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(a.share_id,a.source_space,a.source_path,a.storage_key,a.url,a.created_by,a.created_at,a.expires_at)}r(A,"insertShare");async function C(a,e){return await(await n(e)).prepare("SELECT * FROM shares WHERE share_id = ?").get(a)??null}r(C,"getShare");async function H(a,e){return a===null?await(await n(e)).prepare("SELECT * FROM shares ORDER BY created_at DESC, share_id").all():await(await n(e)).prepare("SELECT * FROM shares WHERE created_by = ? ORDER BY created_at DESC, share_id").all(a)}r(H,"listShares");async function c(a,e){await(await n(e)).prepare("UPDATE shares SET status = 'off' WHERE share_id = ?").run(a)}r(c,"turnShareOff");async function W(a,e){const t=await n(e),s=(await t.prepare("SELECT share_id FROM shares WHERE created_by = ? AND status = 'on'").all(a)).map(i=>i.share_id);return await t.prepare("UPDATE shares SET status = 'off' WHERE created_by = ? AND status = 'on'").run(a),s}r(W,"turnSharesOffFor");async function M(a=d(),e){const t=await n(e),s=(await t.prepare("SELECT share_id FROM shares WHERE status = 'on' AND expires_at IS NOT NULL AND expires_at <= ?").all(a)).map(i=>i.share_id);for(const i of s)await c(i,t);return s}r(M,"expireShares");async function m(a){return await(await n(a)).prepare("SELECT * FROM shares WHERE status = 'off' AND object_deleted_at IS NULL ORDER BY created_at, share_id").all()}r(m,"sharesOwingObjectDelete");async function F(a,e,t=d()){await(await n(e)).prepare("UPDATE shares SET object_deleted_at = COALESCE(object_deleted_at, ?) WHERE share_id = ?").run(t,a)}r(F,"markShareObjectDeleted");async function I(a,e,t=d()){const s=await n(e),i=(await s.prepare("SELECT upload_id FROM uploads WHERE grantee = ? AND delete_pending_since IS NULL").all(a)).map(p=>p.upload_id);return await u(i,s,t),i}r(I,"markGranteeUploadsDeletePending");export{T as deleteUploadRow,y as deleteUploadUse,M as expireShares,C as getShare,f as getUpload,A as insertShare,w as insertUpload,O as insertUploadUses,H as listShares,I as markGranteeUploadsDeletePending,F as markShareObjectDeleted,u as markUploadsDeletePending,L as pendingUploadDeletes,N as releaseRunUploads,D as runUsesPath,U as setUploadSize,m as sharesOwingObjectDelete,g as staleUnusedUploads,c as turnShareOff,W as turnSharesOffFor,x as uploadUseAt};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var s=(e,a)=>h(e,"name",{value:a,configurable:!0});import{isAbsolute as m,resolve as _}from"node:path";import{isCloudRole as y}from"../../../core/canvas/person-state.js";import{RunError as r}from"../../../core/runs/operations.js";import{invalidStorageName as g,storageClient as p,StorageRefused as b,UPLOAD_MAX_BYTES as q}from"../../../core/storage/client.js";import{serveDownload as v}from"../../../core/storage/download.js";import{createShare as A,deleteOwnShare as S,listOwnShares as k}from"../../../core/storage/shares.js";import{getUpload as O,insertUpload as x,uploadUseAt as z}from"../../../core/storage/tables.js";import{requireRun as R}from"../router.js";const B=new Set(["upload.create","attachment.link","file.download","share.create","share.list","share.delete"]);function f(e){if(!e||typeof e!="object"||Array.isArray(e))throw new r(400,"invalid_request","a JSON object is required");return e}s(f,"object");function c(e){return{app:e.grantee,resolved:e.resolved,launched:null}}s(c,"fileCaller");const T=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(?:\s*;.{0,200})?$/;async function D(e,a){const i=f(a);for(const l of Object.keys(i))if(!["name","media_type","size"].includes(l))throw new r(400,"invalid_request",`unknown field ${l}`,l);const{name:n,media_type:o,size:t}=i;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw new r(400,"invalid_request","size must be a non-negative integer","size");if(t>q)throw new r(400,"invalid_request","size exceeds 100 MiB","size");if(typeof n!="string")throw new r(400,"invalid_request","name is required","name");const d=g(n);if(d)throw new r(400,"invalid_request",d,"name");if(typeof o!="string"||!T.test(o))throw new r(400,"invalid_request","media_type must be a media type","media_type");const u=await p().createUpload({name:n,media_type:o,size:t});return await x({upload_id:u.upload_id,grantee:e.grantee,name:n,media_type:o,size:t,created_at:new Date().toISOString()}),{upload_id:u.upload_id,url:u.url,upload_link:u.upload_link,expires_at:u.expires_at}}s(D,"uploadCreate");async function E(e,a){if(!a)throw new r(400,"invalid_request","path is required","path");if(!m(a))throw new r(400,"invalid_request","path must be absolute","path");const i=await z(_(a)),n=s(()=>new r(404,"not_found","no upload is recorded at that path"),"missing");if(!i)throw n();try{await R(e,i.run_id)}catch(t){throw t instanceof r&&t.code==="not_found"?n():t}const o=await O(i.upload_id);if(!o||o.delete_pending_since)throw n();try{return await p().signDownload(i.upload_id)}catch(t){throw t instanceof b?n():t}}s(E,"attachmentLink");function w(e){if(y())throw new r(403,"permission_error",`${e} is not served by a cloud role: file transfer is not yet scoped to a person`)}s(w,"refuseOnCloudRole");async function L(e,a,i,n,o){switch(e.name!=="attachment.link"&&w(e.name),e.name){case"upload.create":return{status:201,body:await D(a,o)};case"attachment.link":return{status:200,body:await E(a,n.get("path"))};case"share.create":{const t=f(o);for(const d of Object.keys(t))if(!["path","expires_at"].includes(d))throw new r(400,"invalid_request",`unknown field ${d}`,d);return{status:201,body:await A(c(a),{path:t.path,expires_at:t.expires_at})}}case"share.list":return{status:200,body:await k(a.grantee)};case"share.delete":return{status:200,body:await S(a.grantee,i.share_id)};default:throw new r(404,"not_found","unknown operation")}}s(L,"handleTransferOperation");function Y(e,a,i,n){return w("file.download"),v(e,a,c(i),n.get("path"))}s(Y,"handleTransferDownload");export{B as TRANSFER_OPERATIONS,c as fileCaller,Y as handleTransferDownload,L as handleTransferOperation};
1
+ var m=Object.defineProperty;var s=(e,a)=>m(e,"name",{value:a,configurable:!0});import{isAbsolute as _,resolve as y}from"node:path";import{isCloudRole as b}from"../../../core/canvas/person-state.js";import{RunError as n,cloudPersonScope as g}from"../../../core/runs/operations.js";import{invalidStorageName as q,storageClient as f,StorageRefused as v,UPLOAD_MAX_BYTES as S}from"../../../core/storage/client.js";import{serveDownload as A}from"../../../core/storage/download.js";import{createShare as k,deleteOwnShare as O,listOwnShares as x}from"../../../core/storage/shares.js";import{getUpload as z,insertUpload as R,uploadUseAt as T}from"../../../core/storage/tables.js";import{requireRun as D}from"../router.js";const Y=new Set(["upload.create","attachment.link","file.download","share.create","share.list","share.delete"]);function c(e){if(!e||typeof e!="object"||Array.isArray(e))throw new n(400,"invalid_request","a JSON object is required");return e}s(c,"object");function w(e){return{app:e.grantee,resolved:e.resolved,launched:null}}s(w,"fileCaller");const E=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(?:\s*;.{0,200})?$/;async function $(e,a){const i=c(a);for(const p of Object.keys(i))if(!["name","media_type","size"].includes(p))throw new n(400,"invalid_request",`unknown field ${p}`,p);const{name:r,media_type:o,size:t}=i;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw new n(400,"invalid_request","size must be a non-negative integer","size");if(t>S)throw new n(400,"invalid_request","size exceeds 100 MiB","size");if(typeof r!="string")throw new n(400,"invalid_request","name is required","name");const d=q(r);if(d)throw new n(400,"invalid_request",d,"name");if(typeof o!="string"||!E.test(o))throw new n(400,"invalid_request","media_type must be a media type","media_type");const u=await f().createUpload({name:r,media_type:o,size:t}),l=g(e.sub);return await R({upload_id:u.upload_id,grantee:e.grantee,...l===void 0?{}:{sub:l},name:r,media_type:o,size:t,created_at:new Date().toISOString()}),{upload_id:u.upload_id,url:u.url,upload_link:u.upload_link,expires_at:u.expires_at}}s($,"uploadCreate");async function j(e,a){if(!a)throw new n(400,"invalid_request","path is required","path");if(!_(a))throw new n(400,"invalid_request","path must be absolute","path");const i=await T(y(a)),r=s(()=>new n(404,"not_found","no upload is recorded at that path"),"missing");if(!i)throw r();try{await D(e,i.run_id)}catch(t){throw t instanceof n&&t.code==="not_found"?r():t}const o=await z(i.upload_id);if(!o||o.delete_pending_since)throw r();try{return await f().signDownload(i.upload_id)}catch(t){throw t instanceof v?r():t}}s(j,"attachmentLink");function h(e){if(b())throw new n(403,"permission_error",`${e} is not served by a cloud role: file transfer is not yet scoped to a person`)}s(h,"refuseOnCloudRole");async function F(e,a,i,r,o){switch(e.name!=="attachment.link"&&e.name!=="upload.create"&&h(e.name),e.name){case"upload.create":return{status:201,body:await $(a,o)};case"attachment.link":return{status:200,body:await j(a,r.get("path"))};case"share.create":{const t=c(o);for(const d of Object.keys(t))if(!["path","expires_at"].includes(d))throw new n(400,"invalid_request",`unknown field ${d}`,d);return{status:201,body:await k(w(a),{path:t.path,expires_at:t.expires_at})}}case"share.list":return{status:200,body:await x(a.grantee)};case"share.delete":return{status:200,body:await O(a.grantee,i.share_id)};default:throw new n(404,"not_found","unknown operation")}}s(F,"handleTransferOperation");function J(e,a,i,r){return h("file.download"),A(e,a,w(i),r.get("path"))}s(J,"handleTransferDownload");export{Y as TRANSFER_OPERATIONS,w as fileCaller,J as handleTransferDownload,F as handleTransferOperation};