@north-light/cli 0.3.659 → 0.3.660

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.
Files changed (42) hide show
  1. package/dist/api/client.d.ts +3 -0
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/files.d.ts +20 -0
  6. package/dist/api/dto/run-events.d.ts +9 -1
  7. package/dist/api/routes.d.ts +2 -0
  8. package/dist/api/routes.js +1 -1
  9. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +12 -6
  10. package/dist/clients/attach/viewer.js +1 -1
  11. package/dist/commands/push.js +6 -4
  12. package/dist/core/canvas/export-sqlite.js +1 -1
  13. package/dist/core/canvas/migrations.js +1 -1
  14. package/dist/core/canvas/person.js +3 -3
  15. package/dist/core/canvas/schema-pg/019-outbound-files.sql +26 -0
  16. package/dist/core/canvas/schema-version.d.ts +1 -1
  17. package/dist/core/canvas/schema-version.js +1 -1
  18. package/dist/core/grants/remove.js +1 -1
  19. package/dist/core/import/bundle/layout.d.ts +1 -1
  20. package/dist/core/import/bundle/layout.js +3 -3
  21. package/dist/core/import/load/bind.js +8 -8
  22. package/dist/core/providers/files.js +1 -1
  23. package/dist/core/runs/operations.js +4 -4
  24. package/dist/core/storage/download.d.ts +0 -1
  25. package/dist/core/storage/download.js +1 -1
  26. package/dist/core/storage/media-types.d.ts +1 -0
  27. package/dist/core/storage/media-types.js +1 -0
  28. package/dist/core/storage/shares.d.ts +15 -6
  29. package/dist/core/storage/shares.js +1 -1
  30. package/dist/core/storage/tables.d.ts +31 -1
  31. package/dist/core/storage/tables.js +4 -3
  32. package/dist/daemon/api/handlers/node-files.d.ts +2 -0
  33. package/dist/daemon/api/handlers/node-files.js +1 -0
  34. package/dist/daemon/api/handlers/transfer.d.ts +2 -2
  35. package/dist/daemon/api/handlers/transfer.js +1 -1
  36. package/dist/daemon/api/operations.js +1 -1
  37. package/dist/daemon/api/server.js +1 -1
  38. package/dist/daemon/reconcilers/ledger-storage.js +3 -3
  39. package/docs/apps/guides/files-and-documents.md +11 -6
  40. package/package.json +2 -2
  41. package/packages/crouter-identity/package.json +1 -1
  42. package/runtime.lock.json +13 -13
@@ -1 +1 @@
1
- var h=Object.defineProperty;var d=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as L}from"../canvas/worktrees.js";import{withCanvasWrite as E,openDb as f}from"../canvas/db.js";import{cancelCron as W}from"../canvas/crons.js";import{emitEvent as p}from"../events/emit.js";import{appSpace as N,appsRoot as w,secretsDir as H}from"../layout.js";import{notifyRunDeleted as y}from"../runs/events.js";import{cancelOpenQuestions as M}from"../runs/questions.js";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{markGranteeUploadsDeletePending as A,releaseRunUploads as U,turnSharesOffFor as q}from"../storage/tables.js";import{stopNodeSandboxes as I}from"../spaces/stop.js";import{activeAppUser as P,markAppUserRemoved as k}from"../spaces/users.js";import{launcherRequest as j}from"../../launcher/client.js";import{LaunchRefused as B}from"../../launcher/spec.js";import{otherLiveGrantOfApp as b}from"./mirror.js";import{launcherPresent as u,listSandboxes as x,stopSandboxPid as G}from"./sandboxes.js";import{filterAsync as g}from"../async-array.js";async function Ee(r,o){if(r==="app:terminal")throw new Error("app:terminal cannot be removed");const s=o===void 0||!await b(r,o);await R(r,o,s)}d(Ee,"removeApp");async function pe(r,o){await R(r,o,!1,!0)}d(pe,"removePersonData");async function R(r,o,s,_=!1){const l=N(r),i=s?await P(r):null;p({level:"info",event:"daemon.grants.removal_started",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null}});const t=o===void 0?{sql:"grantee = ?",args:[r]}:{sql:"grantee = ? AND sub = ?",args:[r,o]};for(const{node_id:e}of await(await f()).prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args))await M({node_id:e},"the app was removed");const a=await E(async e=>(await e.prepare(`UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id IN (SELECT node_id FROM node_rows WHERE ${t.sql})`).run(new Date().toISOString(),...t.args),(await e.prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args)).map(n=>n.node_id)));for(const{cron_id:e}of await(await f()).prepare(`SELECT cron_id FROM crons WHERE ${t.sql}`).all(...t.args))await W(e);const m=(await Promise.all(a.map(e=>I(e,"app_removed",{deleting:!0})))).filter(e=>!e.confirmed);if(m.length)throw new Error(`sandbox teardown could not be confirmed for ${m.length} node(s) of ${r}`);if(i&&u())for(const e of await x())e.uid===i.uid&&await G(e.pid);const v=await g(a,async e=>(await(await f()).prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(e))?.run_id===e);if(await E(async e=>{if(s&&await q(r,e),await U(a,e),s&&await A(r,e),!a.length)return;const n=a.map(()=>"?").join(","),S=await e.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${n}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${n})`).all(...a,...a);await e.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${n})`).run(...a);for(const{message_id:c}of S)await e.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(c,c)}),_){const e=await g(a,L);if(e.length)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${e.join(", ")}`);for(const n of a)await F(await C(n))}await T(a);for(const e of v)y(e);if(s&&(O(D(H(),"env",l.root.slice(w().length+1)),{recursive:!0,force:!0}),$(w(),l.root)),i&&u())try{await j({operation:"user.delete",uid:i.uid})}catch(e){if(!(e instanceof B&&e.refusal==="invalid_uid"))throw e}i&&await k(i.uid),p({level:"info",event:"daemon.grants.removal_completed",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null,nodes:a.length}})}d(R,"cascade");export{Ee as removeApp,pe as removePersonData};
1
+ var h=Object.defineProperty;var d=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as L}from"../canvas/worktrees.js";import{withCanvasWrite as p,openDb as l}from"../canvas/db.js";import{cancelCron as W}from"../canvas/crons.js";import{emitEvent as w}from"../events/emit.js";import{appSpace as N,appsRoot as u,secretsDir as H}from"../layout.js";import{notifyRunDeleted as y}from"../runs/events.js";import{cancelOpenQuestions as M}from"../runs/questions.js";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{deleteRunFiles as A,markGranteeUploadsDeletePending as U,releaseRunUploads as q,turnSharesOffFor as I}from"../storage/tables.js";import{stopNodeSandboxes as P}from"../spaces/stop.js";import{activeAppUser as k,markAppUserRemoved as j}from"../spaces/users.js";import{launcherRequest as B}from"../../launcher/client.js";import{LaunchRefused as b}from"../../launcher/spec.js";import{otherLiveGrantOfApp as G}from"./mirror.js";import{launcherPresent as g,listSandboxes as Y,stopSandboxPid as x}from"./sandboxes.js";import{filterAsync as R}from"../async-array.js";async function pe(r,o){if(r==="app:terminal")throw new Error("app:terminal cannot be removed");const s=o===void 0||!await G(r,o);await _(r,o,s)}d(pe,"removeApp");async function we(r,o){await _(r,o,!1,!0)}d(we,"removePersonData");async function _(r,o,s,v=!1){const f=N(r),i=s?await k(r):null;w({level:"info",event:"daemon.grants.removal_started",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null}});const t=o===void 0?{sql:"grantee = ?",args:[r]}:{sql:"grantee = ? AND sub = ?",args:[r,o]};for(const{node_id:e}of await(await l()).prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args))await M({node_id:e},"the app was removed");const a=await p(async e=>(await e.prepare(`UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id IN (SELECT node_id FROM node_rows WHERE ${t.sql})`).run(new Date().toISOString(),...t.args),(await e.prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args)).map(n=>n.node_id)));for(const{cron_id:e}of await(await l()).prepare(`SELECT cron_id FROM crons WHERE ${t.sql}`).all(...t.args))await W(e);const m=(await Promise.all(a.map(e=>P(e,"app_removed",{deleting:!0})))).filter(e=>!e.confirmed);if(m.length)throw new Error(`sandbox teardown could not be confirmed for ${m.length} node(s) of ${r}`);if(i&&g())for(const e of await Y())e.uid===i.uid&&await x(e.pid);const c=await R(a,async e=>(await(await l()).prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(e))?.run_id===e);if(await p(async e=>{if(s&&await I(r,e),await q(a,e),await A(c,e),s&&await U(r,e),!a.length)return;const n=a.map(()=>"?").join(","),S=await e.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${n}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${n})`).all(...a,...a);await e.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${n})`).run(...a);for(const{message_id:E}of S)await e.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(E,E)}),v){const e=await R(a,L);if(e.length)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${e.join(", ")}`);for(const n of a)await F(await C(n))}await T(a);for(const e of c)y(e);if(s&&(O(D(H(),"env",f.root.slice(u().length+1)),{recursive:!0,force:!0}),$(u(),f.root)),i&&g())try{await B({operation:"user.delete",uid:i.uid})}catch(e){if(!(e instanceof b&&e.refusal==="invalid_uid"))throw e}i&&await j(i.uid),w({level:"info",event:"daemon.grants.removal_completed",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null,nodes:a.length}})}d(_,"cascade");export{pe as removeApp,we as removePersonData};
@@ -4,7 +4,7 @@ export declare const BODIES_TABLE = "bodies";
4
4
  /** Tables whose rows are dumped, staged and (after rewrites) copied, in no particular order: the lane computes the copy
5
5
  * order from the target's foreign-key catalog. A table's part files, read in order, hold its rows in primary-key order (identity-ordered
6
6
  * tables in source `seq` order). */
7
- export declare const COPIED_TABLES: readonly ["objects", "documents", "revisions", "revision_parents", "identities", "jobs", "custom_objects", "context_sessions", "environments", "object_kinds", "edges", "watches", "watch_subscriptions", "exposures", "rules", "unresolved_links", "nodes", "sessions", "worktrees", "node_faults", "waits", "structured_requests", "memory_reads", "deleted_isolated_nodes", "node_outcome_deliveries", "run_events", "messages", "message_causes", "deliveries", "crons", "cron_runs", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "audit_rows", "idempotency_keys", "uploads", "upload_uses", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
7
+ export declare const COPIED_TABLES: readonly ["objects", "documents", "revisions", "revision_parents", "identities", "jobs", "custom_objects", "context_sessions", "environments", "object_kinds", "edges", "watches", "watch_subscriptions", "exposures", "rules", "unresolved_links", "nodes", "sessions", "worktrees", "node_faults", "waits", "structured_requests", "memory_reads", "deleted_isolated_nodes", "node_outcome_deliveries", "run_events", "messages", "message_causes", "deliveries", "crons", "cron_runs", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "audit_rows", "idempotency_keys", "uploads", "upload_uses", "files", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
8
8
  /** Dumped and staged so rewrite 2 can map them, never inserted into the target (`grants`: the directory writes them). */
9
9
  export declare const STAGED_ONLY_TABLES: readonly ["grants"];
10
10
  /** Every table the exporter dumps. */
@@ -1,4 +1,4 @@
1
- var c=Object.defineProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});import{once as a}from"node:events";import{createWriteStream as d}from"node:fs";import{pipeline as u}from"node:stream/promises";import{createZstdCompress as f,createZstdDecompress as m,zstdDecompressSync as l}from"node:zlib";const E="bodies",p=["objects","documents","revisions","revision_parents","identities","jobs","custom_objects","context_sessions","environments","object_kinds","edges","watches","watch_subscriptions","exposures","rules","unresolved_links","nodes","sessions","worktrees","node_faults","waits","structured_requests","memory_reads","deleted_isolated_nodes","node_outcome_deliveries","run_events","messages","message_causes","deliveries","crons","cron_runs","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","audit_rows","idempotency_keys","uploads","upload_uses","shares","provider_approvals","relations","charges","limits","conversation_parts","conversation_entries","profiles","bodies"],_=["grants"],S=[...p,..._],b={audit_rows:"id",review_comment_events:"seq"},z=["objects","revisions","watches","watch_subscriptions","sessions","waits","structured_requests","deliveries","run_events"],h={prefix:n(t=>`imports/${t}/`,"prefix"),rowPart:n((t,e,s)=>`imports/${t}/rows/${e}/${s}.jsonl.zst`,"rowPart"),source:n(t=>`imports/${t}/source.json`,"source"),manifest:n(t=>`imports/${t}/manifest.jsonl.zst`,"manifest"),nodeFiles:n((t,e)=>`imports/${t}/node-files/${e}.tar.zst`,"nodeFiles"),request:n((t,e)=>`requests/${t}/${e}`,"request")};function $(t,e,s){return(s.rowParts[e]??[]).map(r=>h.rowPart(t,e,r))}n($,"rowKeys");function L(t,e){let s;for(const r of t)(e===r.from||e.startsWith(r.from.endsWith("/")?r.from:`${r.from}/`))&&(s===void 0||r.from.length>s.from.length)&&(s=r);return s===void 0?e:s.to+e.slice(s.from.length)}n(L,"mapPath");function B(t){const e=l(t).toString("utf8");if(e==="")return[];if(!e.endsWith(`
1
+ var c=Object.defineProperty;var n=(s,e)=>c(s,"name",{value:e,configurable:!0});import{once as a}from"node:events";import{createWriteStream as d}from"node:fs";import{pipeline as u}from"node:stream/promises";import{createZstdCompress as f,createZstdDecompress as m,zstdDecompressSync as l}from"node:zlib";const E="bodies",p=["objects","documents","revisions","revision_parents","identities","jobs","custom_objects","context_sessions","environments","object_kinds","edges","watches","watch_subscriptions","exposures","rules","unresolved_links","nodes","sessions","worktrees","node_faults","waits","structured_requests","memory_reads","deleted_isolated_nodes","node_outcome_deliveries","run_events","messages","message_causes","deliveries","crons","cron_runs","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","audit_rows","idempotency_keys","uploads","upload_uses","files","shares","provider_approvals","relations","charges","limits","conversation_parts","conversation_entries","profiles","bodies"],_=["grants"],S=[...p,..._],b={audit_rows:"id",review_comment_events:"seq"},z=["objects","revisions","watches","watch_subscriptions","sessions","waits","structured_requests","deliveries","run_events"],h={prefix:n(s=>`imports/${s}/`,"prefix"),rowPart:n((s,e,t)=>`imports/${s}/rows/${e}/${t}.jsonl.zst`,"rowPart"),source:n(s=>`imports/${s}/source.json`,"source"),manifest:n(s=>`imports/${s}/manifest.jsonl.zst`,"manifest"),nodeFiles:n((s,e)=>`imports/${s}/node-files/${e}.tar.zst`,"nodeFiles"),request:n((s,e)=>`requests/${s}/${e}`,"request")};function $(s,e,t){return(t.rowParts[e]??[]).map(r=>h.rowPart(s,e,r))}n($,"rowKeys");function L(s,e){let t;for(const r of s)(e===r.from||e.startsWith(r.from.endsWith("/")?r.from:`${r.from}/`))&&(t===void 0||r.from.length>t.from.length)&&(t=r);return t===void 0?e:t.to+e.slice(t.from.length)}n(L,"mapPath");function B(s){const e=l(s).toString("utf8");if(e==="")return[];if(!e.endsWith(`
2
2
  `))throw new Error("row file is truncated: the last line is not newline-terminated");return e.slice(0,-1).split(`
3
- `).map(s=>JSON.parse(s))}n(B,"decodeRows");function P(t){return`${JSON.stringify(t)}
4
- `}n(P,"rowLine");class j{static{n(this,"RowFileWriter")}zst=f();finished;written=0;constructor(e){this.finished=u(this.zst,d(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,s=Buffer.byteLength(e,"utf8")){this.written+=s,this.zst.write(e,"utf8")||await Promise.race([a(this.zst,"drain"),this.finished])}async close(){this.zst.end(),await this.finished}destroy(){this.zst.destroy()}}async function*A(t){const e=m({chunkSize:1048576});e.end(t);let s=[];for await(const r of e){let o=0;for(let i=r.indexOf(10,o);i!==-1;i=r.indexOf(10,o))s.push(r.subarray(o,i)),yield(s.length===1?s[0]:Buffer.concat(s)).toString("utf8"),s=[],o=i+1;o<r.length&&s.push(r.subarray(o))}if(s.length>0)throw new Error("row file is truncated: the last line is not newline-terminated")}n(A,"rowLines");export{E as BODIES_TABLE,p as COPIED_TABLES,S as DUMPED_TABLES,b as KEY_MAPPED_TABLES,j as RowFileWriter,z as SEQ_TABLES,_ as STAGED_ONLY_TABLES,h as bundleKeys,B as decodeRows,L as mapPath,$ as rowKeys,P as rowLine,A as rowLines};
3
+ `).map(t=>JSON.parse(t))}n(B,"decodeRows");function P(s){return`${JSON.stringify(s)}
4
+ `}n(P,"rowLine");class j{static{n(this,"RowFileWriter")}zst=f();finished;written=0;constructor(e){this.finished=u(this.zst,d(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,t=Buffer.byteLength(e,"utf8")){this.written+=t,this.zst.write(e,"utf8")||await Promise.race([a(this.zst,"drain"),this.finished])}async close(){this.zst.end(),await this.finished}destroy(){this.zst.destroy()}}async function*A(s){const e=m({chunkSize:1048576});e.end(s);let t=[];for await(const r of e){let o=0;for(let i=r.indexOf(10,o);i!==-1;i=r.indexOf(10,o))t.push(r.subarray(o,i)),yield(t.length===1?t[0]:Buffer.concat(t)).toString("utf8"),t=[],o=i+1;o<r.length&&t.push(r.subarray(o))}if(t.length>0)throw new Error("row file is truncated: the last line is not newline-terminated")}n(A,"rowLines");export{E as BODIES_TABLE,p as COPIED_TABLES,S as DUMPED_TABLES,b as KEY_MAPPED_TABLES,j as RowFileWriter,z as SEQ_TABLES,_ as STAGED_ONLY_TABLES,h as bundleKeys,B as decodeRows,L as mapPath,$ as rowKeys,P as rowLine,A as rowLines};
@@ -1,9 +1,9 @@
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
- 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"],["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
- 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
- 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
- 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 (
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 u=c(i=>g(t,i),"T"),o=await a.prepareUncached(`SELECT 'identities' AS tbl FROM ${u("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
+ UNION ALL SELECT 'grants' FROM ${u("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${u("profiles")} WHERE person = ?
3
+ UNION ALL SELECT 'nodes' FROM ${u("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"],["files","sub"],["shares","sub"]],B=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:u}=a,o=c(p=>g(r,p),"S"),i=c((p,d)=>{throw I(`${p} names ${d.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${u}`,{where:p,values:d})},"refuse");for(const[p,d]of Y){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,S.map(O=>O.v))}for(const[p,d]of B){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,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,u);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
+ WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,l,u);_.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(u));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
+ 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(u=>u[0]))}c(z,"earlierImportedObjects");async function se(a,t){const{db:r,schema:l,target:u,catalog:o,targetPerson:i}=a,h=c(n=>g(l,n),"S"),_=c(n=>g(u,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,b]of P(o))if(!(!o.tables.has(n)||n==="relations"))for(const E of b)!(n==="nodes"&&E==="profile_id")&&!(n==="crons"&&E==="profile")&&$.push([n,E,""]);$.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,b,E]of $)await r.prepareUncached(`INSERT INTO ${h("_refs")} SELECT ?, ?, ${f(b)}::text FROM ${h(n)} ${E===""?"WHERE":`${E} AND`} ${f(b)} IS NOT NULL
6
+ AND ${f(b)}::text NOT IN (SELECT id FROM ${h("objects")}) AND ${f(b)}::text IN (SELECT id FROM ${_("objects")})`).run(n,b);const p=await z(r,t),d=await N(r,`WITH RECURSIVE chain(start, id) AS (
7
7
  SELECT DISTINCT value, value FROM ${h("_refs")}
8
8
  UNION SELECT c.start, o.owner FROM chain c JOIN ${_("objects")} o ON o.id = c.id JOIN ${_("objects")} up ON up.id = o.owner AND up.type <> 'app'),
9
9
  ok(id) AS (
@@ -13,5 +13,5 @@ var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});i
13
13
  UNION SELECT r.resource_id FROM ${_("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
14
14
  UNION SELECT unnest(?::text[]))
15
15
  SELECT r.tbl, r.col, r.value FROM ${h("_refs")} r
16
- WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(u.length>0)throw I(`the bundle refers to objects that are not ${i}'s: ${u.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:u});const S=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,E]of S){const b=await N(r,`SELECT DISTINCT s.${f(E)} AS v FROM ${h(n)} s JOIN ${_("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,i);if(b.length>0)throw I(`${n}.${E} names profiles that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${n}.${E}`,values:b.map(T=>T.v)})}for(const[n,E]of[["nodes","grant_id"],["crons","grant_id"]]){const b=await N(r,`SELECT DISTINCT s.${f(E)} AS v FROM ${h(n)} s JOIN ${_("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,i);if(b.length>0)throw I(`${n}.${E} names grants that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${n}.${E}`,values:b.map(T=>T.v)})}const O=await N(r,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${h("daemon_actions")} d
17
- JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:d}=a,o=c(e=>g(r,e),"S"),i=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),h=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),_=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),m=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=c(e=>e.split("/")[1]??"","jobOwner"),p=c((e,s,w,L)=>{const F=R(s);if(F===null||F.kind!==w||L!==void 0&&s!==L)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${L===void 0?"":` of the shape ${L}`}`,{where:e,value:s})},"shaped");for(const e of h)if(p("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of _)p("upload_uses.blob_key",e.blob_key,"attachment");for(const e of m)p("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const u=new Set;for(const{blob_key:e}of h){const s=R(e);s!==null&&s.kind==="conversation"&&!i.has(s.owner)&&u.add(s.owner)}for(const{blob_key:e}of _){const s=R(e);s!==null&&s.kind==="attachment"&&!i.has(s.owner)&&u.add(s.owner)}for(const{output_key:e}of m)i.has($(e))||u.add($(e));const S=new Map((u.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(l,"nodes")} WHERE node_id = ANY(?::text[])`,[...u])).map(e=>[e.node_id,e.sub])),O=c(e=>i.has(e)||S.get(e)===d,"held"),n=c(e=>!i.has(e)&&!S.has(e),"gone"),E={},b=c((e,s)=>{s>0&&(E[e]=(E[e]??0)+s)},"count"),T=c(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of h){const w=R(s),L=v.get(e);L!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...L??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(n)).map(([e])=>e);y.length>0&&(b("conversation_parts",await T(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),b("conversation_entries",await T(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=c((e,s)=>{const w=R(s).owner;if(!O(w))throw I(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of h)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=_.filter(e=>{const s=R(e.blob_key);return s!==null&&s.kind==="attachment"&&n(s.owner)&&!i.has(e.run_id)});M.length>0&&b("upload_uses",await T(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of _)U.has(e)||j("upload_uses.blob_key",e.blob_key);const A=m.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&n($(e.output_key)));A.length>0&&b("jobs",await T(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,A.map(e=>e.object)));const x=new Set(A);for(const e of m)x.has(e)||j("jobs.output_key",e.output_key);return E}c(re,"checkStagedBlobKeys");async function ae(a){const{db:t,schema:r}=a;for(const l of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(r,"human_requests")}`))for(const d of["request_dir","presentation_dir","file"]){const o=l[d];if(o===null||!o.startsWith("requests/"))continue;const i=R(o.includes("/",9)?o:`${o}/x`);if(i===null||i.kind!=="request")throw k(`human_requests.${d} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${d}`,value:o});if(i.owner!==l.request_id)throw I(`human_requests.${d} of ${l.request_id} holds ${o}, which belongs to request ${i.owner}`,{where:`human_requests.${d}`,value:o})}}c(ae,"checkStagedRequestKeys");export{te as boundSub,oe as checkSourcePerson,re as checkStagedBlobKeys,ne as checkStagedPersons,se as checkStagedReferences,ae as checkStagedRequestKeys};
16
+ WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(d.length>0)throw I(`the bundle refers to objects that are not ${i}'s: ${d.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:d});const S=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,b]of S){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("profiles")} p ON p.id = s.${f(b)} WHERE p.person <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names profiles that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}for(const[n,b]of[["nodes","grant_id"],["crons","grant_id"]]){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("grants")} g ON g.id = s.${f(b)} WHERE g.sub <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names grants that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}const O=await N(r,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${h("daemon_actions")} d
17
+ JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:u}=a,o=c(e=>g(r,e),"S"),i=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),h=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),_=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),m=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=c(e=>e.split("/")[1]??"","jobOwner"),p=c((e,s,w,L)=>{const F=R(s);if(F===null||F.kind!==w||L!==void 0&&s!==L)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${L===void 0?"":` of the shape ${L}`}`,{where:e,value:s})},"shaped");for(const e of h)if(p("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of _)p("upload_uses.blob_key",e.blob_key,"attachment");for(const e of m)p("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of h){const s=R(e);s!==null&&s.kind==="conversation"&&!i.has(s.owner)&&d.add(s.owner)}for(const{blob_key:e}of _){const s=R(e);s!==null&&s.kind==="attachment"&&!i.has(s.owner)&&d.add(s.owner)}for(const{output_key:e}of m)i.has($(e))||d.add($(e));const S=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(l,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),O=c(e=>i.has(e)||S.get(e)===u,"held"),n=c(e=>!i.has(e)&&!S.has(e),"gone"),b={},E=c((e,s)=>{s>0&&(b[e]=(b[e]??0)+s)},"count"),T=c(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of h){const w=R(s),L=v.get(e);L!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...L??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(n)).map(([e])=>e);y.length>0&&(E("conversation_parts",await T(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),E("conversation_entries",await T(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=c((e,s)=>{const w=R(s).owner;if(!O(w))throw I(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of h)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=_.filter(e=>{const s=R(e.blob_key);return s!==null&&s.kind==="attachment"&&n(s.owner)&&!i.has(e.run_id)});M.length>0&&E("upload_uses",await T(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of _)U.has(e)||j("upload_uses.blob_key",e.blob_key);const A=m.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&n($(e.output_key)));A.length>0&&E("jobs",await T(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,A.map(e=>e.object)));const x=new Set(A);for(const e of m)x.has(e)||j("jobs.output_key",e.output_key);return b}c(re,"checkStagedBlobKeys");async function ae(a){const{db:t,schema:r}=a;for(const l of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(r,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=l[u];if(o===null||!o.startsWith("requests/"))continue;const i=R(o.includes("/",9)?o:`${o}/x`);if(i===null||i.kind!=="request")throw k(`human_requests.${u} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${u}`,value:o});if(i.owner!==l.request_id)throw I(`human_requests.${u} of ${l.request_id} holds ${o}, which belongs to request ${i.owner}`,{where:`human_requests.${u}`,value:o})}}c(ae,"checkStagedRequestKeys");export{te as boundSub,oe as checkSourcePerson,re as checkStagedBlobKeys,ne as checkStagedPersons,se as checkStagedReferences,ae as checkStagedRequestKeys};
@@ -1 +1 @@
1
- var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as oe}from"node:crypto";import{closeSync as D,constants as ne,createWriteStream as ie}from"node:fs";import{basename as re,extname as ae,isAbsolute as se,join as C}from"node:path";import{Transform as de}from"node:stream";import{pipeline as ue}from"node:stream/promises";import{appSpace as M}from"../layout.js";import{RunError as F}from"../runs/operations.js";import{createFileBeneath as le,existsBeneath as q,openBeneath as ce,removeTreeBeneath as I,setModeBeneath as fe,unlinkBeneath as pe,withDirBeneath as he}from"../spaces/open-beneath.js";import{ensureAppSpace as we}from"../spaces/space.js";import{isCloudRole as me}from"../canvas/person-state.js";import{invalidStorageName as N,storageClient as T,StorageRefused as U,UPLOAD_MAX_BYTES as B}from"../storage/client.js";import{contentTypeFor as _e,openCallerFile as ge}from"../storage/download.js";import{withCanvasWrite as ye}from"../canvas/db.js";import{deleteUploadUse as be,getUpload as $e,insertUpload as ve,insertUploadUses as Se,setUploadSize as Ue,uploadUseAt as ze}from"../storage/tables.js";import{ProviderError as d}from"./errors.js";const Ee=11e4,Ae="app:terminal";function H(e){if(e.class==="person")return e.grantee??Ae;if(!e.grantee)throw new d("server_error","provider caller has no grantee");return e.grantee}u(H,"grantee");function Ce(e){if(e.class==="person"&&e.sub)throw new d("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:H(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Ce,"fileCaller");function y(e){return e instanceof d?e:e instanceof U?new d("storage_unavailable",`storage refused: ${e.message}`):e instanceof F&&e.code==="storage_unavailable"&&e.retryable?new d("storage_unavailable",e.message):e}u(y,"storageFailure");const b=u(e=>new d("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!se(n)||n.includes("\0"))throw new d("invalid_request",`${t} must be an absolute runtime path`,{param:t});let r;try{r=ge(Ce(e),n)}catch(i){throw i instanceof F?i.code==="scope_missing"?new d("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new d("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(r.size>B)throw new d("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=re(r.path),o=N(i);if(o)throw new d("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:r,name:i,mediaType:_e(r.path)}}catch(i){throw D(r.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const r=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:r.url}}catch(n){throw y(n)}}u(Te,"copyOutbound");async function P(e,t,n,r){const i=[];try{for(const a of t)n[a]===void 0||n[a]===null||i.push(Fe(e,a,n[a]));if(!i.length)return[];let o;try{o=r()}catch(a){throw y(a)}const c=[];for(const a of i)c.push(await Te(o,a));return c}finally{for(const o of i)D(o.file.fd)}}u(P,"copyArguments");function k(e){const t=N(e);if(t)throw new d("server_error",`file output ${e} cannot name an upload: ${t}`)}u(k,"checkOutputField");async function W(e,t,n){k(t);const r=H(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:B})}catch(c){throw y(c)}return await ve({upload_id:o.upload_id,grantee:r,name:t,media_type:i,size:B,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:r}}u(W,"createResultUpload");function X(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(X,"uploadHeaders");function Y(e,t){const n={...e};for(const r of t)n[r.param]=r.url;return n}u(Y,"withUrls");async function Je(e,t,n,r={}){const i=r.storage??T;if(t.output&&(k(t.output),me()))throw new d("invalid_request","this command returns a file, which cannot be delivered to your computer from here yet, so it is not available from a moved Mac");const o=await P(e,t.params,n,i),c=t.output?await W(e,t.output,i):null;return{arguments:Y(n,o),copies:o,upload:c,headers:X(c)}}u(Je,"prepareFileCall");async function Ke(e,t,n,r,i={}){const o=i.storage??T,c=[];for(const s of r.copies)try{const p=await o().signOutbound(s.object_id);c.push({...s,url:p.url})}catch(p){if(!(p instanceof U))throw y(p);c.push(...await P(e,[s.param],n,o))}let a=r.upload;if(a)try{const s=await o().signUploadLink(a.upload_id);a={...a,upload_link:s.upload_link}}catch(s){if(!(s instanceof U))throw y(s);s.status===404&&(a=await W(e,t.output??a.field,o))}return{arguments:Y(n,c),copies:c,upload:a,headers:X(a)}}u(Ke,"resignForRetry");const Be=/^[0-9a-f]{64}$/i;function Re(e,t){if(t===1)return e;const n=ae(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Re,"candidate");async function Qe(e,t,n,r={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,a=c[o.field];if(a==null)return i;if(typeof a!="object"||Array.isArray(a))throw b(`${o.field} must be {upload_id, size, sha256}`);const s=a;if(typeof s.upload_id!="string"||typeof s.size!="number"||!Number.isSafeInteger(s.size)||s.size<0||typeof s.sha256!="string"||!Be.test(s.sha256))throw b(`${o.field} must be {upload_id, size, sha256}`);if(s.upload_id!==o.upload_id)throw b(`${o.field} names an upload other than Crtr-Upload-Id`);const p=s.size,G=s.sha256.toLowerCase(),z=AbortSignal.timeout(r.budgetMs??Ee),R=r.signal?AbortSignal.any([z,r.signal]):z;let h;try{h=await(r.storage??T)().fetchUpload(o.upload_id,R)}catch(m){throw m instanceof U?b(`${o.field} names an upload with nothing stored`):y(m)}if(h.size===null)throw h.body.destroy(),new d("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(h.size!==p)throw h.body.destroy(),b(`${o.field} claims ${p} bytes; storage holds ${h.size}`);const E=o.grantee,$=e.node_id!==null,J=await we(E),f=$?M(E).nodes:M(E).files,A=$?C(f,e.node_id):f,v=$?C(A,"attachments"):f,K={uid:process.getuid?.()??0,gid:J.gid},O=$&&!q(f,A),Q=$&&!O&&!q(f,v);let w=null,S=null,x=!1;const L=u(async()=>{if(!x){if(x=!0,S)try{await be(S)}catch{}if(w)try{pe(f,w)}catch{}try{O?I(f,A):Q&&I(f,v)}catch{}}},"cleanup");try{he(f,v,()=>{},!0);for(let l=1;;l++){const _=C(v,Re(o.field,l));if(!await ze(_))try{le(f,_,Buffer.alloc(0),432),w=_;break}catch(g){if(g.code!=="EEXIST")throw g}}let m=0;const j=oe("sha256"),V=new de({transform(l,_,g){m+=l.length,j.update(l),g(null,l)}}),Z=ce(f,w,ne.O_WRONLY);try{await ue(h.body,V,ie("",{fd:Z,autoClose:!0}),{signal:R})}catch(l){throw z.aborted?new d("storage_unavailable","the file result could not be fetched within 110 s"):l instanceof F?y(l):new d("storage_unavailable",`storage stopped sending ${o.field}: ${l instanceof Error?l.message:String(l)}`)}if(m!==p)throw new d("storage_unavailable",`storage sent ${m} of ${p} bytes of ${o.field}`);if(j.digest("hex")!==G)throw b(`${o.field}: the stored bytes do not match sha256`);fe(f,w,432,K);const ee=w;await ye(async l=>{const _=await $e(o.upload_id,l);if(!_||_.delete_pending_since)throw new d("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await Ue(o.upload_id,p,l),!e.run_id)return;const g=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!g||g.deleting_at)throw new d("not_found",`run ${e.run_id} was deleted while its file result was fetched`);S={upload_id:o.upload_id,run_id:e.run_id,path:ee},await Se([S],l)})}catch(m){throw h.body.destroy(),await L(),m}return{result:{...c,[o.field]:w},file:{path:w,upload_id:o.upload_id},cleanup:L}}u(Qe,"resolveFileResult");export{Ee as FILE_RESULT_FETCH_BUDGET_MS,Je as prepareFileCall,Ke as resignForRetry,Qe as resolveFileResult};
1
+ var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as oe}from"node:crypto";import{closeSync as D,constants as ne,createWriteStream as ie}from"node:fs";import{basename as re,extname as ae,isAbsolute as se,join as C}from"node:path";import{Transform as de}from"node:stream";import{pipeline as ue}from"node:stream/promises";import{appSpace as M}from"../layout.js";import{RunError as F}from"../runs/operations.js";import{createFileBeneath as le,existsBeneath as q,openBeneath as ce,removeTreeBeneath as I,setModeBeneath as fe,unlinkBeneath as pe,withDirBeneath as he}from"../spaces/open-beneath.js";import{ensureAppSpace as we}from"../spaces/space.js";import{isCloudRole as me}from"../canvas/person-state.js";import{invalidStorageName as N,storageClient as T,StorageRefused as U,UPLOAD_MAX_BYTES as B}from"../storage/client.js";import{openCallerFile as _e}from"../storage/download.js";import{contentTypeFor as ge}from"../storage/media-types.js";import{withCanvasWrite as ye}from"../canvas/db.js";import{deleteUploadUse as be,getUpload as $e,insertUpload as ve,insertUploadUses as Se,setUploadSize as Ue,uploadUseAt as ze}from"../storage/tables.js";import{ProviderError as d}from"./errors.js";const Ee=11e4,Ae="app:terminal";function H(e){if(e.class==="person")return e.grantee??Ae;if(!e.grantee)throw new d("server_error","provider caller has no grantee");return e.grantee}u(H,"grantee");function Ce(e){if(e.class==="person"&&e.sub)throw new d("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:H(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Ce,"fileCaller");function y(e){return e instanceof d?e:e instanceof U?new d("storage_unavailable",`storage refused: ${e.message}`):e instanceof F&&e.code==="storage_unavailable"&&e.retryable?new d("storage_unavailable",e.message):e}u(y,"storageFailure");const b=u(e=>new d("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!se(n)||n.includes("\0"))throw new d("invalid_request",`${t} must be an absolute runtime path`,{param:t});let r;try{r=_e(Ce(e),n)}catch(i){throw i instanceof F?i.code==="scope_missing"?new d("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new d("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(r.size>B)throw new d("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=re(r.path),o=N(i);if(o)throw new d("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:r,name:i,mediaType:ge(r.path)}}catch(i){throw D(r.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const r=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:r.url}}catch(n){throw y(n)}}u(Te,"copyOutbound");async function P(e,t,n,r){const i=[];try{for(const a of t)n[a]===void 0||n[a]===null||i.push(Fe(e,a,n[a]));if(!i.length)return[];let o;try{o=r()}catch(a){throw y(a)}const c=[];for(const a of i)c.push(await Te(o,a));return c}finally{for(const o of i)D(o.file.fd)}}u(P,"copyArguments");function k(e){const t=N(e);if(t)throw new d("server_error",`file output ${e} cannot name an upload: ${t}`)}u(k,"checkOutputField");async function W(e,t,n){k(t);const r=H(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:B})}catch(c){throw y(c)}return await ve({upload_id:o.upload_id,grantee:r,name:t,media_type:i,size:B,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:r}}u(W,"createResultUpload");function X(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(X,"uploadHeaders");function Y(e,t){const n={...e};for(const r of t)n[r.param]=r.url;return n}u(Y,"withUrls");async function Ke(e,t,n,r={}){const i=r.storage??T;if(t.output&&(k(t.output),me()))throw new d("invalid_request","this command returns a file, which cannot be delivered to your computer from here yet, so it is not available from a moved Mac");const o=await P(e,t.params,n,i),c=t.output?await W(e,t.output,i):null;return{arguments:Y(n,o),copies:o,upload:c,headers:X(c)}}u(Ke,"prepareFileCall");async function Qe(e,t,n,r,i={}){const o=i.storage??T,c=[];for(const s of r.copies)try{const p=await o().signOutbound(s.object_id);c.push({...s,url:p.url})}catch(p){if(!(p instanceof U))throw y(p);c.push(...await P(e,[s.param],n,o))}let a=r.upload;if(a)try{const s=await o().signUploadLink(a.upload_id);a={...a,upload_link:s.upload_link}}catch(s){if(!(s instanceof U))throw y(s);s.status===404&&(a=await W(e,t.output??a.field,o))}return{arguments:Y(n,c),copies:c,upload:a,headers:X(a)}}u(Qe,"resignForRetry");const Be=/^[0-9a-f]{64}$/i;function Re(e,t){if(t===1)return e;const n=ae(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Re,"candidate");async function Ve(e,t,n,r={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,a=c[o.field];if(a==null)return i;if(typeof a!="object"||Array.isArray(a))throw b(`${o.field} must be {upload_id, size, sha256}`);const s=a;if(typeof s.upload_id!="string"||typeof s.size!="number"||!Number.isSafeInteger(s.size)||s.size<0||typeof s.sha256!="string"||!Be.test(s.sha256))throw b(`${o.field} must be {upload_id, size, sha256}`);if(s.upload_id!==o.upload_id)throw b(`${o.field} names an upload other than Crtr-Upload-Id`);const p=s.size,G=s.sha256.toLowerCase(),z=AbortSignal.timeout(r.budgetMs??Ee),R=r.signal?AbortSignal.any([z,r.signal]):z;let h;try{h=await(r.storage??T)().fetchUpload(o.upload_id,R)}catch(m){throw m instanceof U?b(`${o.field} names an upload with nothing stored`):y(m)}if(h.size===null)throw h.body.destroy(),new d("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(h.size!==p)throw h.body.destroy(),b(`${o.field} claims ${p} bytes; storage holds ${h.size}`);const E=o.grantee,$=e.node_id!==null,J=await we(E),f=$?M(E).nodes:M(E).files,A=$?C(f,e.node_id):f,v=$?C(A,"attachments"):f,K={uid:process.getuid?.()??0,gid:J.gid},O=$&&!q(f,A),Q=$&&!O&&!q(f,v);let w=null,S=null,x=!1;const L=u(async()=>{if(!x){if(x=!0,S)try{await be(S)}catch{}if(w)try{pe(f,w)}catch{}try{O?I(f,A):Q&&I(f,v)}catch{}}},"cleanup");try{he(f,v,()=>{},!0);for(let l=1;;l++){const _=C(v,Re(o.field,l));if(!await ze(_))try{le(f,_,Buffer.alloc(0),432),w=_;break}catch(g){if(g.code!=="EEXIST")throw g}}let m=0;const j=oe("sha256"),V=new de({transform(l,_,g){m+=l.length,j.update(l),g(null,l)}}),Z=ce(f,w,ne.O_WRONLY);try{await ue(h.body,V,ie("",{fd:Z,autoClose:!0}),{signal:R})}catch(l){throw z.aborted?new d("storage_unavailable","the file result could not be fetched within 110 s"):l instanceof F?y(l):new d("storage_unavailable",`storage stopped sending ${o.field}: ${l instanceof Error?l.message:String(l)}`)}if(m!==p)throw new d("storage_unavailable",`storage sent ${m} of ${p} bytes of ${o.field}`);if(j.digest("hex")!==G)throw b(`${o.field}: the stored bytes do not match sha256`);fe(f,w,432,K);const ee=w;await ye(async l=>{const _=await $e(o.upload_id,l);if(!_||_.delete_pending_since)throw new d("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await Ue(o.upload_id,p,l),!e.run_id)return;const g=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!g||g.deleting_at)throw new d("not_found",`run ${e.run_id} was deleted while its file result was fetched`);S={upload_id:o.upload_id,run_id:e.run_id,path:ee},await Se([S],l)})}catch(m){throw h.body.destroy(),await L(),m}return{result:{...c,[o.field]:w},file:{path:w,upload_id:o.upload_id},cleanup:L}}u(Ve,"resolveFileResult");export{Ee as FILE_RESULT_FETCH_BUDGET_MS,Ke as prepareFileCall,Qe as resignForRetry,Ve as resolveFileResult};
@@ -1,14 +1,14 @@
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
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{deleteRunFiles as Ot,deleteUploadRow as Dt,insertUploadUses as pe,releaseRunUploads as Mt,runUsesPath as At}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 It}from"../blobs/index.js";import{emitEvent as Tt}from"../events/emit.js";const ge=c((e,t,a,n,d)=>Nt(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),Lt=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
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
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
8
+ AND (n.status IN ('active', 'idle') OR ${Ge("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Yn(e){const t=await b(e);return t!==null&&await C(t)==="running"}c(Yn,"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 Gn(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(Gn,"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 Xn(e=Date.now()){return Number((await(await j()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-Q).toISOString())).changes)}c(Xn,"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 Ct=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>Ct)throw S("deadline must be at most 24h","deadline");return t}c(Ne,"parseRunDeadlineMs");async function zn(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 kt(p)}}c(zn,"startRun");async function kt(e){try{if(await b(e)!==null)return;const t=await It();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){Tt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(kt,"discardUncommittedAttachments");async function Qn(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 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
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(Qn,"listRuns");async function Vn(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(Vn,"waitRun");const xt=5;async function Zn(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 At(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>=xt)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(Zn,"messageRun");async function Wt(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(Wt,"interruptNode");async function Kn(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=>Wt(n))),await F(await b(e.node_id)??e)}c(Kn,"interruptRun");async function ea(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(ea,"cancelRun");const be=200;async function ta(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(ta,"renameRun");async function na(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 Mt([e.node_id],u);await Ot([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 Ft(r,t)}}c(na,"deleteRun");async function Ft(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 Dt(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??Lt),f.unref?.()})]),clearTimeout(f),e.length-n.size}c(Ft,"deleteReleasedUploads");async function aa(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
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: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};
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(aa,"traceRun");function sa(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(sa,"requestedScopes");export{Q as IDEMPOTENCY_WINDOW_MS,Ct as RUN_DEADLINE_MAX_MS,Lt as RUN_DELETE_STORAGE_BUDGET_MS,be as RUN_NAME_MAX,R as RunError,ea as cancelRun,k as cloudPersonScope,na as deleteRun,Gn as idempotencyKeyOf,Kn as interruptRun,Qn as listRuns,Zn as messageRun,H as ownedRun,Ne as parseRunDeadlineMs,Xn as pruneExpiredIdempotencyKeys,ta as renameRun,sa as requestedScopes,Yn as runIsRunning,F as runObject,zn as startRun,aa as traceRun,Vn as waitRun};
@@ -1,6 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type FileCaller } from '../spaces/permissions.js';
3
- export declare function contentTypeFor(path: string): string;
4
3
  /** An open regular file the caller may read. The caller closes `fd`. */
5
4
  export interface CallerFile {
6
5
  fd: number;
@@ -1 +1 @@
1
- var y=Object.defineProperty;var c=(i,e)=>y(i,"name",{value:e,configurable:!0});import{closeSync as m,constants as h,createReadStream as v,fstatSync as b,realpathSync as g}from"node:fs";import{extname as C,isAbsolute as N,join as w,relative as l,resolve as R,sep as d}from"node:path";import{pipeline as S}from"node:stream/promises";import{appsRoot as E,runtimeRoot as _,userRoot as $}from"../layout.js";import{RunError as f}from"../runs/operations.js";import{isBeneathRefusal as O,openBeneath as I}from"../spaces/open-beneath.js";import{fileRoot as T}from"../spaces/permissions.js";const j={".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".tsv":"text/tab-separated-values; charset=utf-8",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".bmp":"image/bmp",".tif":"image/tiff",".tiff":"image/tiff",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav",".ogg":"audio/ogg",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},L=new Set(["text/html","image/svg+xml","application/xhtml+xml"]);function A(i){const e=j[C(i).toLowerCase()]??"application/octet-stream";return L.has(e.split(";")[0].trim().toLowerCase())?"application/octet-stream":e}c(A,"contentTypeFor");function u(i,e){const o=l(i,e);return o===""||o!==".."&&!o.startsWith(`..${d}`)&&!o.startsWith(d)}c(u,"contains");function D(i){const e=c(n=>process.platform==="darwin"?n.toLowerCase():n,"fold"),o=e(i),r=e(E());if(u(e(_()),o)||u(e(w($(),"memory")),o))return!0;if(!u(r,o))return!1;const t=l(r,o).split(d)[1];return t==="memory"||t==="profiles"||t==="conversations"}c(D,"withheld");function z(i,e){if(typeof e!="string"||!e)throw new f(400,"invalid_request","path is required","path");if(!N(e)||e.includes("\0"))throw new f(400,"invalid_request","path must be absolute","path");const o=R(e),r=c(()=>new f(404,"not_found",`no such file: ${o}`),"notFound");if(D(o))throw r();const t=T(i,o,"read");if("hidden"in t)throw r();if(!("root"in t))throw new f(403,"scope_missing",t.missing?`missing scope ${t.missing}`:`no permission names ${o}`,void 0,void 0,t.missing??void 0);const n=c(()=>new f(400,"invalid_request",`${o} meets a symlink, leaves its permitted root, or is not a regular file`,"path"),"symlink");let p;try{p=I(t.root,o,h.O_RDONLY|h.O_NONBLOCK)}catch(a){if(O(a))throw n();const s=a.code;throw s==="ENOENT"||s==="ENOTDIR"||s==="EISDIR"||s==="ENXIO"||s==="EACCES"||s==="EPERM"?r():a}try{if(process.platform!=="linux"){let s;try{s=g(o)}catch{throw r()}if(s!==w(g(t.root),l(t.root,o)))throw n()}const a=b(p);if(!a.isFile())throw r();return{fd:p,path:o,size:a.size}}catch(a){throw m(p),a}}c(z,"openCallerFile");function M(i,e){if(i===void 0)return null;const o=c(()=>new f(416,"range_not_satisfiable","range not satisfiable","range",{size:e}),"refuse"),r=/^bytes=(.+)$/i.exec(i.trim());if(!r)throw o();if(r[1].includes(","))return null;const t=/^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(r[1]);if(!t||t[1]===""&&t[2]==="")throw o();let n,p;if(t[1]===""){const a=Number(t[2]);if(!Number.isSafeInteger(a)||a===0||e===0)throw o();n=Math.max(0,e-a),p=e-1}else if(n=Number(t[1]),p=t[2]===""?e-1:Math.min(Number(t[2]),e-1),!Number.isSafeInteger(n)||!Number.isSafeInteger(p)||n>=e||t[2]!==""&&Number(t[2])<n)throw o();return{start:n,end:p}}c(M,"parseRange");async function X(i,e,o,r){const t=z(o,r);let n;try{const s=i.headers.range;try{n=M(Array.isArray(s)?s[0]:s,t.size)}catch(x){throw e.setHeader("Content-Range",`bytes */${t.size}`),x}}catch(s){throw m(t.fd),s}const p={"Content-Type":A(t.path),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox; default-src 'none'","Accept-Ranges":"bytes","Cache-Control":"no-store"};if(i.destroyed||e.destroyed){m(t.fd);return}if(n?e.writeHead(206,{...p,"Content-Length":String(n.end-n.start+1),"Content-Range":`bytes ${n.start}-${n.end}/${t.size}`}):e.writeHead(200,{...p,"Content-Length":String(t.size)}),t.size===0||n&&n.end<n.start){m(t.fd),e.end();return}const a=v("",{fd:t.fd,autoClose:!0,...n?{start:n.start,end:n.end}:{start:0}});try{await S(a,e)}catch{a.destroy(),e.destroy()}}c(X,"serveDownload");export{A as contentTypeFor,z as openCallerFile,M as parseRange,X as serveDownload};
1
+ var b=Object.defineProperty;var c=(a,e)=>b(a,"name",{value:e,configurable:!0});import{closeSync as u,constants as p,createReadStream as C,fstatSync as R,realpathSync as y}from"node:fs";import{isAbsolute as N,join as w,relative as l,resolve as S,sep as h}from"node:path";import{pipeline as $}from"node:stream/promises";import{appsRoot as E,runtimeRoot as x,userRoot as O}from"../layout.js";import{RunError as d}from"../runs/operations.js";import{isBeneathRefusal as _,openBeneath as v}from"../spaces/open-beneath.js";import{fileRoot as I}from"../spaces/permissions.js";import{contentTypeFor as A}from"./media-types.js";function m(a,e){const r=l(a,e);return r===""||r!==".."&&!r.startsWith(`..${h}`)&&!r.startsWith(h)}c(m,"contains");function L(a){const e=c(n=>process.platform==="darwin"?n.toLowerCase():n,"fold"),r=e(a),o=e(E());if(m(e(x()),r)||m(e(w(O(),"memory")),r))return!0;if(!m(o,r))return!1;const t=l(o,r).split(h)[1];return t==="memory"||t==="profiles"||t==="conversations"}c(L,"withheld");function T(a,e){if(typeof e!="string"||!e)throw new d(400,"invalid_request","path is required","path");if(!N(e)||e.includes("\0"))throw new d(400,"invalid_request","path must be absolute","path");const r=S(e),o=c(()=>new d(404,"not_found",`no such file: ${r}`),"notFound");if(L(r))throw o();const t=I(a,r,"read");if("hidden"in t)throw o();if(!("root"in t))throw new d(403,"scope_missing",t.missing?`missing scope ${t.missing}`:`no permission names ${r}`,void 0,void 0,t.missing??void 0);const n=c(()=>new d(400,"invalid_request",`${r} meets a symlink, leaves its permitted root, or is not a regular file`,"path"),"symlink");let f;try{f=v(t.root,r,p.O_RDONLY|p.O_NONBLOCK)}catch(s){if(_(s))throw n();const i=s.code;throw i==="ENOENT"||i==="ENOTDIR"||i==="EISDIR"||i==="ENXIO"||i==="EACCES"||i==="EPERM"?o():s}try{if(process.platform!=="linux"){let i;try{i=y(r)}catch{throw o()}if(i!==w(y(t.root),l(t.root,r)))throw n()}const s=R(f);if(!s.isFile())throw o();return{fd:f,path:r,size:s.size}}catch(s){throw u(f),s}}c(T,"openCallerFile");function D(a,e){if(a===void 0)return null;const r=c(()=>new d(416,"range_not_satisfiable","range not satisfiable","range",{size:e}),"refuse"),o=/^bytes=(.+)$/i.exec(a.trim());if(!o)throw r();if(o[1].includes(","))return null;const t=/^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(o[1]);if(!t||t[1]===""&&t[2]==="")throw r();let n,f;if(t[1]===""){const s=Number(t[2]);if(!Number.isSafeInteger(s)||s===0||e===0)throw r();n=Math.max(0,e-s),f=e-1}else if(n=Number(t[1]),f=t[2]===""?e-1:Math.min(Number(t[2]),e-1),!Number.isSafeInteger(n)||!Number.isSafeInteger(f)||n>=e||t[2]!==""&&Number(t[2])<n)throw r();return{start:n,end:f}}c(D,"parseRange");async function j(a,e,r,o){const t=T(r,o);let n;try{const i=a.headers.range;try{n=D(Array.isArray(i)?i[0]:i,t.size)}catch(g){throw e.setHeader("Content-Range",`bytes */${t.size}`),g}}catch(i){throw u(t.fd),i}const f={"Content-Type":A(t.path),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox; default-src 'none'","Accept-Ranges":"bytes","Cache-Control":"no-store"};if(a.destroyed||e.destroyed){u(t.fd);return}if(n?e.writeHead(206,{...f,"Content-Length":String(n.end-n.start+1),"Content-Range":`bytes ${n.start}-${n.end}/${t.size}`}):e.writeHead(200,{...f,"Content-Length":String(t.size)}),t.size===0||n&&n.end<n.start){u(t.fd),e.end();return}const s=C("",{fd:t.fd,autoClose:!0,...n?{start:n.start,end:n.end}:{start:0}});try{await $(s,e)}catch{s.destroy(),e.destroy()}}c(j,"serveDownload");export{T as openCallerFile,D as parseRange,j as serveDownload};
@@ -0,0 +1 @@
1
+ export declare function contentTypeFor(path: string): string;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var i=(e,t)=>a(e,"name",{value:t,configurable:!0});import{extname as p}from"node:path";const o={".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".tsv":"text/tab-separated-values; charset=utf-8",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".bmp":"image/bmp",".tif":"image/tiff",".tiff":"image/tiff",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav",".ogg":"audio/ogg",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},m=new Set(["text/html","image/svg+xml","application/xhtml+xml"]);function s(e){const t=o[p(e).toLowerCase()]??"application/octet-stream";return m.has(t.split(";")[0].trim().toLowerCase())?"application/octet-stream":t}i(s,"contentTypeFor");export{s as contentTypeFor};
@@ -1,4 +1,5 @@
1
1
  import type { FileCaller } from '../spaces/permissions.js';
2
+ import { type FileRow } from './tables.js';
2
3
  export declare const SHARE_SCOPE = "crtr:files:share";
3
4
  export interface ShareView {
4
5
  share_id: string;
@@ -9,9 +10,8 @@ export interface ShareView {
9
10
  expires_at: string | null;
10
11
  status: 'on' | 'off';
11
12
  }
12
- /** `share.create`: freeze a copy of a file the caller may read at a public URL.
13
- * Without `crtr:files:share` only the caller's own app space may be shared. The
14
- * row is inserted only once storage holds the bytes. */
13
+ /** `share.create {path}`: freeze a copy of a file the caller may read at a public URL. Without `crtr:files:share` only the caller's own app
14
+ * space may be shared. The row is inserted only once storage holds the bytes. */
15
15
  export declare function createShare(caller: FileCaller, input: {
16
16
  path: unknown;
17
17
  expires_at?: unknown;
@@ -20,13 +20,22 @@ export declare function createShare(caller: FileCaller, input: {
20
20
  url: string;
21
21
  expires_at: string | null;
22
22
  }>;
23
- /** `share.list`: the shares `createdBy` created. */
24
- export declare function listOwnShares(createdBy: string): Promise<{
23
+ /** `share.create {file_id}` for a handed-over file: copy the stored object into a new share object, streaming it through this server without touching
24
+ * its disk. The caller has already checked the file is its own and complete. The row is inserted only once storage holds the bytes. */
25
+ export declare function createShareFromFile(file: FileRow, person: string | undefined, input: {
26
+ expires_at?: unknown;
27
+ }): Promise<{
28
+ share_id: string;
29
+ url: string;
30
+ expires_at: string | null;
31
+ }>;
32
+ /** `share.list`: the shares `createdBy` created; on a cloud role only those of `person`. */
33
+ export declare function listOwnShares(createdBy: string, person?: string): Promise<{
25
34
  shares: ShareView[];
26
35
  }>;
27
36
  /** `share.delete`: turn the share off, then delete its stored copy. A storage
28
37
  * failure leaves `object_deleted_at` unset for the due-work tick to retry. */
29
- export declare function deleteOwnShare(createdBy: string, shareId: string): Promise<{
38
+ export declare function deleteOwnShare(createdBy: string, shareId: string, person?: string): Promise<{
30
39
  share_id: string;
31
40
  status: 'off';
32
41
  }>;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var n=(e,t)=>g(e,"name",{value:t,configurable:!0});import{closeSync as x,read as v}from"node:fs";import{promisify as O}from"node:util";import{basename as $,relative as u,sep as d}from"node:path";import{Readable as _}from"node:stream";import{appsRoot as m,appSpace as A}from"../layout.js";import{RunError as s}from"../runs/operations.js";import{scopeAllowed as k}from"../scopes.js";import{invalidStorageName as q,storageClient as w,UPLOAD_MAX_BYTES as D}from"./client.js";import{contentTypeFor as E,openCallerFile as C}from"./download.js";import{getShare as R,insertShare as T,listShares as B,markShareObjectDeleted as N,turnShareOff as F}from"./tables.js";const f="crtr:files:share";function y(e,t){const a=u(e,t);return a===""||a!==".."&&!a.startsWith(`..${d}`)&&!a.startsWith(d)}n(y,"contains");function M(e){if(y(m(),e)){const t=u(m(),e).split(d)[0];if(t)return`app:${t}`}return"user"}n(M,"spaceOf");const b=n(e=>new s(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable"),P=O(v);async function*U(e,t){let a=0;for(;a<t;){const r=Buffer.allocUnsafe(Math.min(1048576,t-a)),{bytesRead:i}=await P(e,r,0,r.length,a);if(i===0)throw new Error("shared file shrank while it was being copied");a+=i,yield r.subarray(0,i)}}n(U,"chunks");async function W(e,t,a,r){const i=_.from(U(t,a));let c;try{c=await fetch(e,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":r,"Content-Length":String(a)},body:_.toWeb(i),duplex:"half"})}catch(p){throw b(`storage could not be reached: ${p instanceof Error?p.message:String(p)}`)}finally{i.destroy()}if(await c.body?.cancel().catch(()=>{}),!c.ok)throw b(`storage answered ${c.status} to the share upload`)}n(W,"putBytes");async function Z(e,t){if(typeof t.path!="string"||!t.path)throw new s(400,"invalid_request","path is required","path");let a;if(t.expires_at!==void 0&&t.expires_at!==null){const i=typeof t.expires_at=="string"?Date.parse(t.expires_at):NaN;if(!Number.isFinite(i))throw new s(400,"invalid_request","expires_at must be an ISO 8601 time","expires_at");if(i<=Date.now())throw new s(400,"invalid_request","expires_at must be in the future","expires_at");a=new Date(i).toISOString()}const r=C(e,t.path);try{if(!k(e.resolved,f)&&!y(A(e.app).root,r.path))throw new s(403,"scope_missing",`missing scope ${f}: without it only files in the app's own space can be shared`,void 0,void 0,f);if(r.size>D)throw new s(400,"invalid_request","file exceeds 100 MiB","path");const i=$(r.path),c=q(i);if(c)throw new s(400,"invalid_request",`file name cannot be shared: ${c}`,"path");const p=E(r.path),h=w(),o=await h.createShare({name:i,media_type:p,size:r.size,...a?{expires_at:a}:{}});try{await W(o.upload_link,r.fd,r.size,p)}catch(S){throw await h.deleteShare(o.share_id).catch(()=>{}),S}const l=o.expires_at??a??null;return await T({share_id:o.share_id,source_space:M(r.path),source_path:r.path,storage_key:`${h.runtimeId}/shares/${o.share_id}/${i}`,url:o.url,created_by:e.app,created_at:new Date().toISOString(),expires_at:l}),{share_id:o.share_id,url:o.url,expires_at:l}}finally{x(r.fd)}}n(Z,"createShare");function j(e){return{share_id:e.share_id,url:e.url,source_path:e.source_path,created_by:e.created_by,created_at:e.created_at,expires_at:e.expires_at,status:e.status}}n(j,"view");async function ee(e){return{shares:(await B(e)).map(j)}}n(ee,"listOwnShares");async function te(e,t){const a=await R(t);if(!a||a.created_by!==e)throw new s(404,"not_found","share not found");if(await F(t),!a.object_deleted_at)try{await w().deleteShare(t),await N(t)}catch(r){if(!(r instanceof s&&r.code==="storage_unavailable"))throw r}return{share_id:t,status:"off"}}n(te,"deleteOwnShare");export{f as SHARE_SCOPE,Z as createShare,te as deleteOwnShare,ee as listOwnShares};
1
+ var O=Object.defineProperty;var s=(e,t)=>O(e,"name",{value:t,configurable:!0});import{closeSync as v,read as A}from"node:fs";import{promisify as k}from"node:util";import{basename as z,relative as l,sep as h}from"node:path";import{Readable as m}from"node:stream";import{appsRoot as w,appSpace as D}from"../layout.js";import{RunError as o}from"../runs/operations.js";import{scopeAllowed as E}from"../scopes.js";import{invalidStorageName as q,storageClient as u,StorageRefused as R,UPLOAD_MAX_BYTES as C}from"./client.js";import{contentTypeFor as F}from"./media-types.js";import{openCallerFile as T}from"./download.js";import{getShare as N,insertShare as y,listShares as U,markShareObjectDeleted as B,turnShareOff as M}from"./tables.js";const f="crtr:files:share";function S(e,t){const r=l(e,t);return r===""||r!==".."&&!r.startsWith(`..${h}`)&&!r.startsWith(h)}s(S,"contains");function P(e){if(S(w(),e)){const t=l(w(),e).split(h)[0];if(t)return`app:${t}`}return"user"}s(P,"spaceOf");const b=s(e=>new o(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable"),W=k(A);async function*j(e,t){let r=0;for(;r<t;){const a=Buffer.allocUnsafe(Math.min(1048576,t-r)),{bytesRead:i}=await W(e,a,0,a.length,r);if(i===0)throw new Error("shared file shrank while it was being copied");r+=i,yield a.subarray(0,i)}}s(j,"chunks");async function g(e,t,r,a){let i;try{i=await fetch(e,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":a,"Content-Length":String(r)},body:m.toWeb(t),duplex:"half"})}catch(n){throw b(`storage could not be reached: ${n instanceof Error?n.message:String(n)}`)}finally{t.destroy()}if(await i.body?.cancel().catch(()=>{}),!i.ok)throw b(`storage answered ${i.status} to the share upload`)}s(g,"putStream");const x=s(e=>{if(e==null)return;const t=typeof e=="string"?Date.parse(e):NaN;if(!Number.isFinite(t))throw new o(400,"invalid_request","expires_at must be an ISO 8601 time","expires_at");if(t<=Date.now())throw new o(400,"invalid_request","expires_at must be in the future","expires_at");return new Date(t).toISOString()},"parseExpiry");async function ae(e,t){if(typeof t.path!="string"||!t.path)throw new o(400,"invalid_request","path is required","path");const r=x(t.expires_at),a=T(e,t.path);try{if(!E(e.resolved,f)&&!S(D(e.app).root,a.path))throw new o(403,"scope_missing",`missing scope ${f}: without it only files in the app's own space can be shared`,void 0,void 0,f);if(a.size>C)throw new o(400,"invalid_request","file exceeds 100 MiB","path");const i=z(a.path),n=q(i);if(n)throw new o(400,"invalid_request",`file name cannot be shared: ${n}`,"path");const p=F(a.path),c=u(),d=await c.createShare({name:i,media_type:p,size:a.size,...r?{expires_at:r}:{}});try{await g(d.upload_link,m.from(j(a.fd,a.size)),a.size,p)}catch($){throw await c.deleteShare(d.share_id).catch(()=>{}),$}const _=d.expires_at??r??null;return await y({share_id:d.share_id,source_space:P(a.path),source_path:a.path,storage_key:`${c.runtimeId}/shares/${d.share_id}/${i}`,url:d.url,created_by:e.app,created_at:new Date().toISOString(),expires_at:_}),{share_id:d.share_id,url:d.url,expires_at:_}}finally{v(a.fd)}}s(ae,"createShare");async function re(e,t,r){const a=x(r.expires_at),i=u(),n=await i.createShare({name:e.name,media_type:e.media_type,size:e.size,...a?{expires_at:a}:{}});try{const c=await i.fetchUpload(e.file_id,AbortSignal.timeout(11e4));await g(n.upload_link,c.body,e.size,e.media_type)}catch(c){throw await i.deleteShare(n.share_id).catch(()=>{}),c instanceof R?new o(404,"not_found","file not found"):c}const p=n.expires_at??a??null;return await y({share_id:n.share_id,source_space:`file:${e.file_id}`,source_path:e.name,storage_key:`${i.runtimeId}/shares/${n.share_id}/${e.name}`,url:n.url,created_by:e.grantee,...t===void 0?{}:{sub:t},created_at:new Date().toISOString(),expires_at:p}),{share_id:n.share_id,url:n.url,expires_at:p}}s(re,"createShareFromFile");function I(e){return{share_id:e.share_id,url:e.url,source_path:e.source_path,created_by:e.created_by,created_at:e.created_at,expires_at:e.expires_at,status:e.status}}s(I,"view");async function ie(e,t){return{shares:(await U(e)).filter(r=>t===void 0||r.sub===t).map(I)}}s(ie,"listOwnShares");async function ne(e,t,r){const a=await N(t);if(!a||a.created_by!==e||r!==void 0&&a.sub!==r)throw new o(404,"not_found","share not found");if(await M(t),!a.object_deleted_at)try{await u().deleteShare(t),await B(t)}catch(i){if(!(i instanceof o&&i.code==="storage_unavailable"))throw i}return{share_id:t,status:"off"}}s(ne,"deleteOwnShare");export{f as SHARE_SCOPE,ae as createShare,re as createShareFromFile,ne as deleteOwnShare,ie as listOwnShares};
@@ -19,6 +19,7 @@ export interface UploadUseRow {
19
19
  path: string;
20
20
  blob_key?: string | null;
21
21
  }
22
+ /** `sub` is the person a cloud role's share was made for; null on a Mac and on every row written before the column existed. */
22
23
  export interface ShareRow {
23
24
  share_id: string;
24
25
  source_space: string;
@@ -26,11 +27,30 @@ export interface ShareRow {
26
27
  storage_key: string;
27
28
  url: string;
28
29
  created_by: string;
30
+ sub: string | null;
29
31
  created_at: string;
30
32
  expires_at: string | null;
31
33
  status: 'on' | 'off';
32
34
  object_deleted_at: string | null;
33
35
  }
36
+ /** A file an agent handed to the person. Its bytes are the storage upload with the same id as `file_id`; `completed_at` is set once the API
37
+ * has read them back and found the declared size and sha256. `sub` is the person of a cloud role's run, null on a Mac. */
38
+ export interface FileRow {
39
+ file_id: string;
40
+ run_id: string;
41
+ node_id: string;
42
+ grantee: string;
43
+ sub: string | null;
44
+ name: string;
45
+ media_type: string;
46
+ size: number;
47
+ sha256: string;
48
+ created_at: string;
49
+ completed_at: string | null;
50
+ }
51
+ /** The `upload_uses.path` a handed-over file is recorded under: it ties the file's upload to its run, so deleting the run or removing the
52
+ * app releases the upload and the 24 h unused-upload sweep leaves it alone. It is not absolute, so `attachment.link` never resolves it. */
53
+ export declare const fileUsePath: (fileId: string) => string;
34
54
  export declare function insertUpload(row: Omit<UploadRow, 'delete_pending_since' | 'sub'> & {
35
55
  sub?: string;
36
56
  }, db?: CanvasDb): Promise<void>;
@@ -54,7 +74,17 @@ export declare function uploadUseAt(path: string, db?: CanvasDb): Promise<Upload
54
74
  export declare function releaseRunUploads(runIds: readonly string[], db?: CanvasDb): Promise<string[]>;
55
75
  /** Uploads never used 24 h after creation (the tick marks them for deletion). */
56
76
  export declare function staleUnusedUploads(before: string, db?: CanvasDb): Promise<string[]>;
57
- export declare function insertShare(row: Omit<ShareRow, 'status' | 'object_deleted_at'>, db?: CanvasDb): Promise<void>;
77
+ export declare function insertShare(row: Omit<ShareRow, 'status' | 'object_deleted_at' | 'sub'> & {
78
+ sub?: string;
79
+ }, db?: CanvasDb): Promise<void>;
80
+ export declare function insertFile(row: Omit<FileRow, 'sub' | 'completed_at'> & {
81
+ sub?: string;
82
+ }, db?: CanvasDb): Promise<void>;
83
+ export declare function getFile(fileId: string, db?: CanvasDb): Promise<FileRow | null>;
84
+ /** Mark a file complete; false when it already was (a repeated completion). */
85
+ export declare function completeFile(fileId: string, at?: string, db?: CanvasDb): Promise<boolean>;
86
+ /** Drop the file rows of the given runs (their uploads are released by `releaseRunUploads`). */
87
+ export declare function deleteRunFiles(runIds: readonly string[], db?: CanvasDb): Promise<void>;
58
88
  export declare function getShare(shareId: string, db?: CanvasDb): Promise<ShareRow | null>;
59
89
  /** Shares `created_by` owns; `null` (the person) lists every share. */
60
90
  export declare function listShares(createdBy: string | null, db?: CanvasDb): Promise<ShareRow[]>;