@north-light/cli 0.3.658 → 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 (48) 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/018-transfer-person.sql +8 -0
  16. package/dist/core/canvas/schema-pg/019-outbound-files.sql +26 -0
  17. package/dist/core/canvas/schema-version.d.ts +1 -1
  18. package/dist/core/canvas/schema-version.js +1 -1
  19. package/dist/core/grants/remove.js +1 -1
  20. package/dist/core/import/bundle/layout.d.ts +1 -1
  21. package/dist/core/import/bundle/layout.js +3 -3
  22. package/dist/core/import/load/bind.js +8 -8
  23. package/dist/core/providers/files.js +1 -1
  24. package/dist/core/runs/operations.d.ts +1 -1
  25. package/dist/core/runs/operations.js +7 -7
  26. package/dist/core/storage/attachments.d.ts +3 -3
  27. package/dist/core/storage/attachments.js +1 -1
  28. package/dist/core/storage/client.d.ts +3 -1
  29. package/dist/core/storage/client.js +2 -2
  30. package/dist/core/storage/download.d.ts +0 -1
  31. package/dist/core/storage/download.js +1 -1
  32. package/dist/core/storage/media-types.d.ts +1 -0
  33. package/dist/core/storage/media-types.js +1 -0
  34. package/dist/core/storage/shares.d.ts +15 -6
  35. package/dist/core/storage/shares.js +1 -1
  36. package/dist/core/storage/tables.d.ts +36 -2
  37. package/dist/core/storage/tables.js +4 -3
  38. package/dist/daemon/api/handlers/node-files.d.ts +2 -0
  39. package/dist/daemon/api/handlers/node-files.js +1 -0
  40. package/dist/daemon/api/handlers/transfer.d.ts +2 -2
  41. package/dist/daemon/api/handlers/transfer.js +1 -1
  42. package/dist/daemon/api/operations.js +1 -1
  43. package/dist/daemon/api/server.js +1 -1
  44. package/dist/daemon/reconcilers/ledger-storage.js +3 -3
  45. package/docs/apps/guides/files-and-documents.md +11 -6
  46. package/package.json +2 -2
  47. package/packages/crouter-identity/package.json +1 -1
  48. 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"]],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};
@@ -3,7 +3,7 @@ import type { AppPrincipal } from '../../daemon/api/principal.js';
3
3
  import { type ResolvedAttachments } from '../storage/attachments.js';
4
4
  import { type StorageClient, type StorageConfig } from '../storage/client.js';
5
5
  /** Fetches the storage URLs of a run's text into the run's `attachments/`. */
6
- export type AttachmentResolver = (runId: string, grantee: string, text: string, taken?: readonly string[]) => Promise<ResolvedAttachments>;
6
+ export type AttachmentResolver = (runId: string, grantee: string, text: string, taken?: readonly string[], person?: string) => Promise<ResolvedAttachments>;
7
7
  /** Storage deletes `run.delete` waits for before it answers. */
8
8
  export declare const RUN_DELETE_STORAGE_BUDGET_MS = 3000;
9
9
  export interface StorageDeps {
@@ -1,14 +1,14 @@
1
- var Me=Object.defineProperty;var c=(e,t)=>Me(e,"name",{value:t,configurable:!0});import{coveredByAny as Ae}from"../../shared/env.js";import{createHash as Q}from"node:crypto";import{ApiError as Ie}from"../../api/errors.js";import{CrtrError as Te}from"../errors.js";import{isCloudRole as Le}from"../canvas/person.js";import{isAbsolute as V,relative as Ce,resolve as ke,sep as xe,join as We}from"node:path";import{SessionManager as Fe}from"@earendil-works/pi-coding-agent";import{covers as P}from"@north-light/identity";import{openDb as B,withCanvasWrite as F}from"../canvas/db.js";import{deleteNodeWithOwned as qe}from"../graph/deletion.js";import{getById as He}from"../graph/objects.js";import{repairRunConversations as Z}from"../canvas/sessions.js";import{getNode as v,nodeFiles as Ue,removeNodeFiles as $e,updateNode as Pe}from"../canvas/canvas.js";import{fullName as Be}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{liveExecutionForNode as K}from"../canvas/executions.js";import{conversationStore as ee,isConversationNotFound as Je}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ye}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Ge}from"../canvas/deliveries.js";import{readNodeRecap as Xe}from"../canvas/node-recap.js";import{enqueueNodeMail as ze}from"../feed/messages.js";import{recordInitialInput as Qe}from"./initial-input.js";import{newestReportBody as Ve}from"../feed/reports.js";import{ensureAppProfile as te,loadExactProfileManifest as ne}from"../profiles/manifest.js";import{stopNodeSandboxes as ae}from"../spaces/stop.js";import{deleteNodeSandboxes as Ze}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as Ke}from"../runtime/broker-request.js";import{interruptLive as et}from"../runtime/interactive-deliver.js";import{isBrokerLive as se}from"../runtime/model-swap.js";import{newNodeId as tt}from"../runtime/nodes.js";import{reviveNode as j}from"../runtime/revive.js";import{spawnChildPrepared as nt}from"../runtime/spawn.js";import{isPortableModelToken as at}from"../runtime/launch.js";import{parseDurationMs as st}from"../wake.js";import{expandModelCandidates as it,parseModelSpec as rt}from"../model-routes.js";import{payerOfGrant as J}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as ot}from"../runtime/host.js";import{blaxelEnvironmentOf as dt}from"../runtime/blaxel-environment.js";import{resolveRunKind as ct,resolveRunModel as ut}from"../runtime/launch-target.js";import{cycleAwareMessages as mt}from"../runtime/session-cycles.js";import{originFor as ie}from"../runtime/stamp/protocol.js";import{readOutputRequest as lt,readOutputResult as re}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as oe}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as ft}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as pt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as _t}from"../../daemon/runs/observer.js";import{closeNode as de}from"../runtime/close.js";import{parseScope as wt}from"@north-light/identity";import{appendRunEvent as ce,lockRunRoot as gt,subscribeRunEvents as Et}from"./events.js";import{runActivity as yt}from"./activity.js";import{cancelOpenQuestions as ue,openNoticeIds as ht,openQuestionIds as me}from"./questions.js";import{appSpace as Y}from"../layout.js";import{ensureAppSpace as Rt}from"../spaces/space.js";import{assertUploadsUsable as le,resolveStorageUrls as St}from"../storage/attachments.js";import{storageClient as Nt,storageConfig as vt}from"../storage/client.js";import{deleteUploadRow as bt,insertUploadUses as fe,releaseRunUploads as Ot,runUsesPath as Dt}from"../storage/tables.js";import{abortProviderCalls as pe}from"../providers/inflight.js";import{filterAsync as _e,mapAsync as x}from"../async-array.js";import{blobStore as Mt}from"../blobs/index.js";import{emitEvent as At}from"../events/emit.js";const we=c((e,t,a,n)=>St(t,e,a,n?{taken:n}:{}),"defaultResolver"),It=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,_,i,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=_,this.scope=i,this.retryable=s}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),G=c(()=>new R(404,"not_found","run not found"),"missing"),X=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),M=c(async()=>await B(),"db");async function q(e,t,a=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw G();return n}c(q,"ownedRun");const ge=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await M()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var Ae=Object.defineProperty;var c=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as V}from"node:crypto";import{ApiError as Te}from"../../api/errors.js";import{CrtrError as Le}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as Z,relative as ke,resolve as xe,sep as We,join as Fe}from"node:path";import{SessionManager as qe}from"@earendil-works/pi-coding-agent";import{covers as B}from"@north-light/identity";import{openDb as j,withCanvasWrite as q}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as K}from"../canvas/sessions.js";import{getNode as b,nodeFiles as $e,removeNodeFiles as Pe,updateNode as Be}from"../canvas/canvas.js";import{fullName as je}from"../canvas/labels.js";import{renameWindow as Je}from"../runtime/placement.js";import{liveExecutionForNode as ee}from"../canvas/executions.js";import{conversationStore as te,isConversationNotFound as Ye}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ge}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Xe}from"../canvas/deliveries.js";import{readNodeRecap as ze}from"../canvas/node-recap.js";import{enqueueNodeMail as Qe}from"../feed/messages.js";import{recordInitialInput as Ve}from"./initial-input.js";import{newestReportBody as Ze}from"../feed/reports.js";import{ensureAppProfile as ne,loadExactProfileManifest as ae}from"../profiles/manifest.js";import{stopNodeSandboxes as se}from"../spaces/stop.js";import{deleteNodeSandboxes as Ke}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as et}from"../runtime/broker-request.js";import{interruptLive as tt}from"../runtime/interactive-deliver.js";import{isBrokerLive as ie}from"../runtime/model-swap.js";import{newNodeId as nt}from"../runtime/nodes.js";import{reviveNode as J}from"../runtime/revive.js";import{spawnChildPrepared as at}from"../runtime/spawn.js";import{isPortableModelToken as st}from"../runtime/launch.js";import{parseDurationMs as it}from"../wake.js";import{expandModelCandidates as rt,parseModelSpec as ot}from"../model-routes.js";import{payerOfGrant as Y}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as dt}from"../runtime/host.js";import{blaxelEnvironmentOf as ct}from"../runtime/blaxel-environment.js";import{resolveRunKind as ut,resolveRunModel as mt}from"../runtime/launch-target.js";import{cycleAwareMessages as lt}from"../runtime/session-cycles.js";import{originFor as re}from"../runtime/stamp/protocol.js";import{readOutputRequest as ft,readOutputResult as oe}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as de}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as pt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as _t}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as wt}from"../../daemon/runs/observer.js";import{closeNode as ce}from"../runtime/close.js";import{parseScope as gt}from"@north-light/identity";import{appendRunEvent as ue,lockRunRoot as Et,subscribeRunEvents as yt}from"./events.js";import{runActivity as ht}from"./activity.js";import{cancelOpenQuestions as me,openNoticeIds as Rt,openQuestionIds as le}from"./questions.js";import{appSpace as G}from"../layout.js";import{ensureAppSpace as St}from"../spaces/space.js";import{assertUploadsUsable as fe,resolveStorageUrls as Nt}from"../storage/attachments.js";import{storageClient as bt,storageConfig as vt}from"../storage/client.js";import{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
- )) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await ft(e)?"running":(await me(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
- WHERE n.run_id = ? AND ${Ge("d","'armed', 'pending', 'handed_off'")}
8
- AND (n.status IN ('active', 'idle') OR ${Ye("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Jn(e){const t=await v(e);return t!==null&&await C(t)==="running"}c(Jn,"runIsRunning");async function W(e){await Z(e.node_id),e=await v(e.node_id)??e;const t=await C(e),a=t==="settled"?[]:await me(e.node_id),n=await Ve(e.node_id)||void 0,d=t==="settled"?await pt(e):null,_=d?.kind==="result"?await re(e.node_id):void 0,i=Xe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},..._===void 0?{}:{result:_},...n!==void 0?{last_report:n}:{},...i?{recap:i}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await ht(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(X())),payer:await J(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await yt(e.node_id,t)}}c(W,"runObject");const z=864e5,Ee=255;function Yn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>Ee)throw S(`Idempotency-Key must be 1-${Ee} characters`);return e}}c(Yn,"idempotencyKeyOf");function Tt(e){if(Le()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(Tt,"cloudPersonScope");function k(e,t){const a=Tt(e);return a===void 0?t:`${a}:${t}`}c(k,"personKey");async function H(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await B();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=z)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(H,"findIdempotent");async function ye(e,t,a,n,d,_,i){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-z).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(_),i)}c(ye,"recordIdempotent");async function Gn(e=Date.now()){return Number((await(await B()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-z).toISOString())).changes)}c(Gn,"pruneExpiredIdempotencyKeys");async function he(e,t,a,n,d,_=!1){const i=n.text;let s=0;return{messageId:(await ze(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:d?{body:i,..._?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:d?"normal":"deferred",wake:d?1:0,withinEnqueue:c(async(l,h)=>{n.uses.length&&(await le(a,n.uses,l),await fe(n.uses.map(({upload_id:o,path:f,blob_key:r})=>({upload_id:o,path:f,blob_key:r,run_id:t})),l)),s=(await ce(l,t,t,"node.message.accepted",{message_id:h,start_turn:d})).sequence_number},"withinEnqueue")})).messageId,sequence:s}}c(he,"acceptRunMessage");class Re extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Lt=1440*60*1e3;function Se(e){const t=typeof e=="string"?st(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Lt)throw S("deadline must be at most 24h","deadline");return t}c(Se,"parseRunDeadlineMs");async function Xn(e,t,a,n=we){if(t.isolated&&!ot()&&await dt((t.profile===void 0?await te(e.grantee):ne(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Se(t.deadline);const{causedBy:d,..._}=t,i=Q("sha256").update(JSON.stringify(_)).digest("hex");if(a){const o=await H(e.grantee,k(e.sub,a),i);if(o){const f=await q(o.run_id,e.grantee);return!f.pi_pid&&await C(f)==="running"&&(t.output_schema!==void 0&&!f.outcome_at&&await lt(f.node_id)===null&&await re(f.node_id)===void 0&&await oe(f.node_id,"terminal",t.output_schema),await j(f.node_id,{resume:!0,capacity:"freeze"})),o.response}}await Rt(e.grantee);const s=t.profile===void 0?await te(e.grantee):ne(t.profile),m=s.manifest.grantee??"app:terminal";if(m!==e.grantee){const o=`crtr:memory:rw:${m}:profile:${s.profileId}`;if(!e.resolved.some(f=>P(f,o))||t.scopes!==null&&!t.scopes.some(f=>P(f,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(at(o)){if(o.includes("/")&&await J(e.grant)!=="app"){const f=o.lastIndexOf("/"),r=o.slice(0,f),p=o.slice(f+1);if(["ultra","strong","medium","light"].includes(p)&&(await it({kind:"logical",family:r,strength:p,spec:o},Y(e.grantee).files,s.profileId)).every(y=>y.family!==r))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(rt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const l=await tt(),h=We(Y(e.grantee).nodes,l);if(t.isolated&&t.cwd!==void 0){const o=Ce(h,ke(t.cwd));if(!V(t.cwd)||o===".."||o.startsWith(`..${xe}`)||V(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(l,e.grantee,t.prompt),f=o.text,r=t.message===void 0?void 0:await n(l,e.grantee,t.message,o.uses.map(u=>u.path)),p=await J(e.grant);let y;try{const u=ut(s,t.model);await nt({kind:ct(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:Y(e.grantee).files,profile:s.profileId,prompt:f,nodeId:l,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...u===void 0?{}:{model:u},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Se(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:l,event_cursor:1,usage_json:JSON.stringify(X())},withinCreate:c(async(E,A)=>{if(a){const N=await H(e.grantee,k(e.sub,a),i,E);if(N)throw new Re(N)}const D=o.uses;if(D.length&&(await le(e.grantee,D,E),await fe(D.map(({upload_id:N,path:I,blob_key:U})=>({upload_id:N,path:I,blob_key:U,run_id:l})),E)),y={run_id:l,node_id:l,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:p,status:"running",created_at:A.created,metadata:t.metadata,sequence_number:0},await ce(E,l,l,"run.started",{scopes:t.scopes,payer:p,usage:X()}),r){const N=await he(E,l,e.grantee,r,!1);y.message={run_id:l,message_id:N.messageId,sequence_number:N.sequence}}else await Qe(l,e.grantee,f);a&&await ye(E,e.grantee,k(e.sub,a),i,l,y,A.created)},"withinCreate")},t.output_schema===void 0?void 0:async E=>{await oe(E,"terminal",t.output_schema)})}catch(u){if(u instanceof Re)return u.winner.response;if(t.model!==void 0&&u instanceof Te&&u.code==="usage")throw S(u.message,"model");if(u instanceof Ie&&(u.code==="isolated_run"||u.code==="invalid_request")){const E=u.details&&typeof u.details=="object"&&"param"in u.details&&typeof u.details.param=="string"?u.details.param:void 0;throw new R(u.status,u.code,u.message,E)}throw u}if(!y)throw new Error("run creation did not commit");return y}finally{await Ct(l)}}c(Xn,"startRun");async function Ct(e){try{if(await v(e)!==null)return;const t=await Mt();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){At({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(Ct,"discardUncommittedAttachments");async function zn(e,t){let a;if(t.after)try{const s=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!s||typeof s!="object"||!("activity"in s)||typeof s.activity!="string"||!("id"in s)||typeof s.id!="string")throw new Error("invalid cursor");a={activity:s.activity,id:s.id}}catch{throw S("invalid list cursor","after")}const n=await(await M()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await pt(e)?"running":(await le(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
+ WHERE n.run_id = ? AND ${Xe("d","'armed', 'pending', 'handed_off'")}
8
+ AND (n.status IN ('active', 'idle') OR ${Ge("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function 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 _e(await x((await _e(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:m})=>!a||s<a.activity||s===a.activity&&m<a.id),async s=>({root:await v(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),_=d.slice(0,t.limit),i=_.at(-1);return{runs:await x(_,async({root:s})=>await W(s)),next:d.length>t.limit&&i?Buffer.from(JSON.stringify({activity:i.activity,id:i.root.node_id})).toString("base64url"):null}}c(zn,"listRuns");async function Qn(e,t,a){const n=await q(e,t),d=c(async()=>await W(await q(e,t)),"read");return!a||ge.includes(await C(n))?await d():new Promise((_,i)=>{let s=c(()=>{},"unsubscribe");const m=c(()=>{clearTimeout(r),clearInterval(f),s()},"settle"),l=c(async()=>{m();try{_(await d())}catch(p){i(p)}},"finish"),h=c(async()=>{ge.includes(String((await d()).status))&&await l()},"check"),o=c(()=>{h().catch(p=>{m(),i(p)})},"run"),f=setInterval(o,250),r=setTimeout(()=>{l()},a*1e3);Et(e,o).then(p=>{s=p},p=>{m(),i(p)})})}c(Qn,"waitRun");const kt=5;async function Vn(e,t,a=we,n=!0,d,_=!0){const i=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",m=Q("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!_?["steer:false"]:[]])).digest("hex"),l=c(async o=>{const f=await v(e.node_id),r=await(await M()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return f&&!i&&n&&!f.pi_pid&&r&&await j(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await H(s,k(e.sub,d),m);if(o)return l(o.response)}if(i)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const f=await a(e.node_id,s,t),r=await F(async p=>{if(d){const E=await H(s,k(e.sub,d),m,p);if(E)return{replayed:E.response}}if(f.uses.length){await gt(p,e.node_id);for(const E of f.uses)if(await Dt(e.node_id,E.path,p))return"path_taken"}await h?.(e.node_id);const y=await he(p,e.node_id,s,f,n,n&&_),u={run_id:e.node_id,message_id:y.messageId,sequence_number:y.sequence};return d&&await ye(p,s,k(e.sub,d),m,e.node_id,u,new Date().toISOString()),{result:u}});if(r==="path_taken"){if(o>=kt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in r?l(r.replayed):(n&&!e.pi_pid&&await j(e.node_id,{resume:!0,capacity:"freeze"}),r.result)}}c(Vn,"messageRun");async function xt(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await v(e);if(!n)throw G();if(!se(n)){if(n.streaming)throw t();return}const d=(await K(e))?.executionId;try{await et(e)==="turn"&&pe({nodes:[e]});return}catch(_){if(!(_ instanceof Ke))throw _;const i=await v(e);if(!i)throw G();if(!i.streaming)return;if(a===0&&se(i)&&(await K(e))?.executionId!==d)continue;throw t()}}throw t()}c(xt,"interruptNode");async function Zn(e,t="stop"){const a=t==="stop"?(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>xt(n))),await W(await v(e.node_id)??e)}c(Zn,"interruptRun");async function Kn(e,t={}){const a=(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(i=>i.node_id);pe({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await de(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const i of a){if(i===e.node_id)continue;const s=await v(i);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...(await de(i,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await ue({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(i=>ae(i,"run_canceled")))).some(i=>!i.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const _=await v(e.node_id);return await W(_??e)}c(Kn,"cancelRun");const Ne=200;async function ea(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>Ne)throw S(`name exceeds ${Ne} characters`,"name");const n=await Pe(e.node_id,{name:a});return n.window&&je(n.window,Be(n)),await W(n)}c(ea,"renameRun");async function ta(e,t={config:vt,client:Nt}){await ue({run_id:e.node_id},"the run was deleted");const a=await F(async m=>(await m.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await m.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(l=>l.node_id)));if((await Promise.all(a.map(m=>ae(m,"run_deleted",{deleting:!0})))).some(m=>!m.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await Ze(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await x(a,async m=>{const l=await Ue(m);if(l.app===null)throw new Error(`run node missing during deletion: ${m}`);return l}),_=await(await M()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:m}of _)try{await ee().delete(m)}catch(l){if(!Je(l))throw l}const i=await F(async m=>{for(const f of a){const r=await He(m,f);r!==null&&r.deleted_at===null&&await qe(m,r)}const l=await Ot([e.node_id],m);await m.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await m.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await m.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await m.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:f}of o)await m.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(f,f);return l});for(const m of d)await $e(m);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Wt(i,t)}}c(ta,"deleteRun");async function Wt(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(i=>a.deleteUpload(i).then(async()=>{await bt(i),n.add(i)},()=>{}));let _;return await Promise.race([Promise.all(d),new Promise(i=>{_=setTimeout(i,t.budgetMs??It),_.unref?.()})]),clearTimeout(_),e.length-n.size}c(Wt,"deleteReleasedUploads");async function na(e,t,a){await q(e,t),await Z(e);const n=await F(async r=>{const p=await r.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),y=new Map;for(const N of p)y.set(N.node_id,(await r.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(N.node_id)).map(I=>I.session_id));const E=(await r.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await r.prepare(`SELECT node_id, sequence_number FROM run_events
10
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await we(await W((await we(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:u})=>!a||s<a.activity||s===a.activity&&u<a.id),async s=>({root:await b(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await W(f,async({root:s})=>await F(s)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(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
- ORDER BY sequence_number`).all(e,E),D=await r.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
12
+ ORDER BY sequence_number`).all(e,E),D=await i.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
13
13
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
14
- ORDER BY sequence_number`).all(e,E);return{nodes:p,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:_,latestSequence:i,completed:s,deltas:m}=n,l=await x(d,async r=>({node_id:r.node_id,parent_node_id:r.parent,conversations:await x(_.get(r.node_id)??[],async p=>{const{header:y,entries:u}=await ee().read(p);if(a==="entries")return{conversation_id:p,header:y,entries:u};const E=Fe.inMemory(y.cwd,void 0,[y,...u]),A=mt(E)??[],D=new Map(u.map((g,b)=>[g.id,b])),N=u.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=u.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),U=r.node_id===e?u.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const b=ie(u,g.message.timestamp);return b?.type==="runtime"&&b.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(b=>b.id===g)),...N,...I].sort((g,b)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(b.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:b})=>{const w=b,T=w.usage,$=w.role==="user"?ie(u,Number(w.timestamp)):null,be=$?.type==="human"||g===U,L=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?be?"user":"custom":w.role,Oe=L==="custom"?w.role==="custom"?w.customType:$?.type==="runtime"?$.kind:"unknown":void 0,De=L==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:Oe}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:De,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:p,messages:ve}})})),h=new Map(await Promise.all(l.map(async r=>[r.node_id,await _t(r.node_id)])));for(const r of s){const p=h.get(r.node_id);p!=null&&r.sequence_number>=p&&h.set(r.node_id,null)}const o=new Map;for(const r of m){const p=h.get(r.node_id);if(p==null||r.sequence_number<p)continue;const y=JSON.parse(r.body_json),u=o.get(r.node_id)??{thinking:"",text:""};r.type==="node.thinking.delta"?u.thinking+=y.delta:u.text+=y.delta,o.set(r.node_id,u)}const f=l.map(r=>({...r,in_progress_message:h.get(r.node_id)==null?null:o.get(r.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:i,nodes:f}}c(na,"traceRun");function aa(e,t,a){if(t===void 0){if(!e.some(n=>P(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{wt(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ae(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(aa,"requestedScopes");export{z as IDEMPOTENCY_WINDOW_MS,Lt as RUN_DEADLINE_MAX_MS,It as RUN_DELETE_STORAGE_BUDGET_MS,Ne as RUN_NAME_MAX,R as RunError,Kn as cancelRun,Tt as cloudPersonScope,ta as deleteRun,Yn as idempotencyKeyOf,Zn as interruptRun,zn as listRuns,Vn as messageRun,q as ownedRun,Se as parseRunDeadlineMs,Gn as pruneExpiredIdempotencyKeys,ea as renameRun,aa as requestedScopes,Jn as runIsRunning,W as runObject,Xn as startRun,na as traceRun,Qn as waitRun};
14
+ ORDER BY sequence_number`).all(e,E);return{nodes:l,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:f,latestSequence:r,completed:s,deltas:u}=n,p=await W(d,async i=>({node_id:i.node_id,parent_node_id:i.parent,conversations:await W(f.get(i.node_id)??[],async l=>{const{header:y,entries:m}=await te().read(l);if(a==="entries")return{conversation_id:l,header:y,entries:m};const E=qe.inMemory(y.cwd,void 0,[y,...m]),A=lt(E)??[],D=new Map(m.map((g,v)=>[g.id,v])),N=m.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=m.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),$=i.node_id===e?m.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const v=re(m,g.message.timestamp);return v?.type==="runtime"&&v.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(v=>v.id===g)),...N,...I].sort((g,v)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(v.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:v})=>{const w=v,T=w.usage,P=w.role==="user"?re(m,Number(w.timestamp)):null,Oe=P?.type==="human"||g===$,L=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?Oe?"user":"custom":w.role,De=L==="custom"?w.role==="custom"?w.customType:P?.type==="runtime"?P.kind:"unknown":void 0,Me=L==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:l,messages:ve}})})),h=new Map(await Promise.all(p.map(async i=>[i.node_id,await wt(i.node_id)])));for(const i of s){const l=h.get(i.node_id);l!=null&&i.sequence_number>=l&&h.set(i.node_id,null)}const o=new Map;for(const i of u){const l=h.get(i.node_id);if(l==null||i.sequence_number<l)continue;const y=JSON.parse(i.body_json),m=o.get(i.node_id)??{thinking:"",text:""};i.type==="node.thinking.delta"?m.thinking+=y.delta:m.text+=y.delta,o.set(i.node_id,m)}const _=p.map(i=>({...i,in_progress_message:h.get(i.node_id)==null?null:o.get(i.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:_}}c(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};
@@ -26,11 +26,11 @@ export interface ResolveOptions {
26
26
  taken?: readonly string[];
27
27
  }
28
28
  /** Re-check, inside the accepting write, that every used upload is still this
29
- * grantee's and not pending delete (the due-work tick or an app removal may
29
+ * grantee's (and person's, see `ownsUpload`) and not pending delete (the due-work tick or an app removal may
30
30
  * have released it while its bytes were fetched). */
31
- export declare function assertUploadsUsable(grantee: string, uses: readonly AttachmentUse[], db: CanvasDb): Promise<void>;
31
+ export declare function assertUploadsUsable(grantee: string, person: string | undefined, uses: readonly AttachmentUse[], db: CanvasDb): Promise<void>;
32
32
  /** Fetch every upload a storage URL in `text` names into the blob store at `attachments/<rootId>/<sha256>` and replace
33
33
  * exactly each URL's span with the path the node's broker downloads that file to (`<app space>/nodes/<rootId>/attachments/<name>`).
34
34
  * The control plane writes no file there. Without configured storage the text passes through unchanged. A failure leaves
35
35
  * at most content-keyed blobs, which are harmless and are deleted with the node. */
36
- export declare function resolveStorageUrls(grantee: string, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
36
+ export declare function resolveStorageUrls(grantee: string, person: string | undefined, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
@@ -1 +1 @@
1
- var M=Object.defineProperty;var h=(e,t)=>M(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{extname as H,join as v}from"node:path";import{Writable as B}from"node:stream";import{pipeline as O}from"node:stream/promises";import{blobStore as W}from"../blobs/index.js";import{appSpace as Z}from"../layout.js";import{RunError as A}from"../runs/operations.js";import{storageClient as j,storageConfig as q,StorageRefused as D}from"./client.js";import{getUpload as E,runUsesPath as F}from"./tables.js";const G=11e4,m=h((e,t)=>new A(400,"invalid_request",t,void 0,{url:e}),"refused"),b=h(e=>new A(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function T(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}h(T,"shownUrl");async function N(e,t,o,r,i){const c=`${t}/`,w=[];let f=0;for(let d=e.indexOf(c,f);d!==-1;d=e.indexOf(c,f)){const a=T(e,d),g=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(d+c.length));if(!g)throw m(a,`storage URL ${a} does not name an upload`);if(g[1]!==o)throw m(a,`storage URL ${a} names another runtime`);const l=await E(g[2],i);if(!l||l.grantee!==r)throw m(a,`storage URL ${a} names an unknown upload`);if(l.delete_pending_since)throw m(a,`storage URL ${a} names a deleted upload`);const u=d+c.length+g[0].length,p=encodeURIComponent(l.name);if(!e.startsWith(p,u))throw m(a,`storage URL ${a} does not match the upload's name`);w.push({start:d,end:u+p.length,upload:l}),f=u+p.length}return w}h(N,"matchStorageUrls");async function ae(e,t,o){for(const r of t){const i=await E(r.upload_id,o);if(!i||i.grantee!==e||i.delete_pending_since)throw m(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}h(ae,"assertUploadsUsable");function P(e,t){if(t===1)return e;const o=H(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}h(P,"candidate");async function se(e,t,o,r={}){const i={text:o,uses:[]},c=(r.config??q)();if(!c||!o.includes(`${c.base_url}/`))return i;const w=(r.client??j)(),f=await N(o,c.base_url,w.runtimeId,e);if(!f.length)return i;const d=v(Z(e).nodes,t,"attachments"),a=AbortSignal.timeout(r.budgetMs??G),g=await(r.blobs??W)(),l=new Set(r.taken),u=new Map;for(const{upload:s,start:C}of f){if(u.has(s.upload_id))continue;const _=T(o,C);let y;try{y=await w.fetchUpload(s.upload_id,a)}catch(n){throw n instanceof D?m(_,n.status===409?`storage URL ${_} names an upload that was never finished`:`storage URL ${_} names an unknown upload`):a.aborted?b("attachments could not be fetched within 110 s"):n}const S=[],L=x("sha256");try{await O(y.body,new B({write(n,I,z){L.update(n),S.push(n),z()}}),{signal:a})}catch(n){throw a.aborted?b("attachments could not be fetched within 110 s"):b(`storage stopped sending ${s.name}: ${n instanceof Error?n.message:String(n)}`)}const R=Buffer.concat(S);if(R.length!==s.size)throw b(`storage sent ${R.length} of ${s.size} bytes of ${s.name}`);const k=`attachments/${t}/${L.digest("hex")}`;try{await g.put(k,R)}catch(n){throw b(`the attachment ${s.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let $="";for(let n=1;$=v(d,P(s.name,n)),!(!l.has($)&&!await F(t,$));n++);l.add($),u.set(s.upload_id,{upload_id:s.upload_id,path:$,url:_,blob_key:k})}let p="",U=0;for(const s of f)p+=o.slice(U,s.start)+u.get(s.upload.upload_id).path,U=s.end;return p+=o.slice(U),{text:p,uses:[...u.values()]}}h(se,"resolveStorageUrls");export{G as ATTACHMENT_FETCH_BUDGET_MS,ae as assertUploadsUsable,se as resolveStorageUrls};
1
+ var H=Object.defineProperty;var c=(e,t)=>H(e,"name",{value:t,configurable:!0});import{createHash as B}from"node:crypto";import{extname as O,join as A}from"node:path";import{Writable as W}from"node:stream";import{pipeline as Z}from"node:stream/promises";import{blobStore as j}from"../blobs/index.js";import{appSpace as q}from"../layout.js";import{RunError as E}from"../runs/operations.js";import{storageClient as D,storageConfig as F,StorageRefused as G}from"./client.js";import{getUpload as T,runUsesPath as N}from"./tables.js";const P=11e4,g=c((e,t)=>new E(400,"invalid_request",t,void 0,{url:e}),"refused"),_=c(e=>new E(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function C(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}c(C,"shownUrl");function z(e,t,o){return e.grantee===t&&(o===void 0||e.sub===o)}c(z,"ownsUpload");async function I(e,t,o,i,r,d){const l=`${t}/`,$=[];let p=0;for(let u=e.indexOf(l,p);u!==-1;u=e.indexOf(l,p)){const a=C(e,u),w=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(u+l.length));if(!w)throw g(a,`storage URL ${a} does not name an upload`);if(w[1]!==o)throw g(a,`storage URL ${a} names another runtime`);const f=await T(w[2],d);if(!f||!z(f,i,r))throw g(a,`storage URL ${a} names an unknown upload`);if(f.delete_pending_since)throw g(a,`storage URL ${a} names a deleted upload`);const h=u+l.length+w[0].length,m=encodeURIComponent(f.name);if(!e.startsWith(m,h))throw g(a,`storage URL ${a} does not match the upload's name`);$.push({start:u,end:h+m.length,upload:f}),p=h+m.length}return $}c(I,"matchStorageUrls");async function re(e,t,o,i){for(const r of o){const d=await T(r.upload_id,i);if(!d||!z(d,e,t)||d.delete_pending_since)throw g(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}c(re,"assertUploadsUsable");function J(e,t){if(t===1)return e;const o=O(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}c(J,"candidate");async function ie(e,t,o,i,r={}){const d={text:i,uses:[]},l=(r.config??F)();if(!l||!i.includes(`${l.base_url}/`))return d;const $=(r.client??D)(),p=await I(i,l.base_url,$.runtimeId,e,t);if(!p.length)return d;const u=A(q(e).nodes,o,"attachments"),a=AbortSignal.timeout(r.budgetMs??P),w=await(r.blobs??j)(),f=new Set(r.taken),h=new Map;for(const{upload:s,start:M}of p){if(h.has(s.upload_id))continue;const U=C(i,M);let S;try{S=await $.fetchUpload(s.upload_id,a)}catch(n){throw n instanceof G?g(U,n.status===409?`storage URL ${U} names an upload that was never finished`:`storage URL ${U} names an unknown upload`):a.aborted?_("attachments could not be fetched within 110 s"):n}const L=[],k=B("sha256");try{await Z(S.body,new W({write(n,K,x){k.update(n),L.push(n),x()}}),{signal:a})}catch(n){throw a.aborted?_("attachments could not be fetched within 110 s"):_(`storage stopped sending ${s.name}: ${n instanceof Error?n.message:String(n)}`)}const y=Buffer.concat(L);if(y.length!==s.size)throw _(`storage sent ${y.length} of ${s.size} bytes of ${s.name}`);const v=`attachments/${o}/${k.digest("hex")}`;try{await w.put(v,y)}catch(n){throw _(`the attachment ${s.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let b="";for(let n=1;b=A(u,J(s.name,n)),!(!f.has(b)&&!await N(o,b));n++);f.add(b),h.set(s.upload_id,{upload_id:s.upload_id,path:b,url:U,blob_key:v})}let m="",R=0;for(const s of p)m+=i.slice(R,s.start)+h.get(s.upload.upload_id).path,R=s.end;return m+=i.slice(R),{text:m,uses:[...h.values()]}}c(ie,"resolveStorageUrls");export{P as ATTACHMENT_FETCH_BUDGET_MS,re as assertUploadsUsable,ie as resolveStorageUrls};
@@ -96,7 +96,9 @@ export interface StorageClient {
96
96
  * after it was checked cannot be copied; the caller closes `fd`. */
97
97
  putFileBytes(uploadLink: string, fd: number, size: number, mediaType: string): Promise<void>;
98
98
  }
99
- /** The configured storage, or null when this runtime has none. */
99
+ /** The configured storage, or null when this runtime has none. A cloud role has no person outside a request and its people's settings never
100
+ * hold storage, so it takes the deployment's `CRTR_BOOT_STORAGE_URL` (as `directoryIssuer` takes `CRTR_DIRECTORY_URL`); anything else reads
101
+ * the user config's `runtime.storage`, which the daemon writes at boot from that same variable. */
100
102
  export declare function storageConfig(): StorageConfig | null;
101
103
  /** The storage client for the configured runtime. Refuses with
102
104
  * `storage_unavailable` when no storage is configured. */
@@ -1,3 +1,3 @@
1
- var x=Object.defineProperty;var i=(r,d)=>x(r,"name",{value:d,configurable:!0});import{createReadStream as v,read as S,statSync as $}from"node:fs";import{Readable as _}from"node:stream";import{promisify as T}from"node:util";import{readConfig as E}from"../config.js";import{directoryIssuer as O}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as C,runtimeId as R}from"../grants/sync.js";const G=104857600;class m extends Error{static{i(this,"StorageRefused")}status;code;constructor(d,u,l){super(l),this.status=d,this.code=u}}const j=T(S);async function*U(r,d){let u=0;for(;u<d;){const l=Buffer.allocUnsafe(Math.min(1048576,d-u)),{bytesRead:f}=await j(r,l,0,l.length,u);if(f===0)throw new Error("file shrank while it was being copied");u+=f,yield l.subarray(0,f)}}i(U,"fdChunks");const s=i(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function P(){const r=E("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}i(P,"storageConfig");let w;function F(){const r=P(),d=O();if(!r||!d)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${d}
1
+ var x=Object.defineProperty;var l=(r,s)=>x(r,"name",{value:s,configurable:!0});import{createReadStream as v,read as S,statSync as $}from"node:fs";import{Readable as g}from"node:stream";import{promisify as T}from"node:util";import{isCloudRole as E}from"../canvas/person-state.js";import{readConfig as O}from"../config.js";import{directoryIssuer as R}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as C,runtimeId as U}from"../grants/sync.js";const J=104857600;class m extends Error{static{l(this,"StorageRefused")}status;code;constructor(s,u,d){super(d),this.status=s,this.code=u}}const j=T(S);async function*A(r,s){let u=0;for(;u<s;){const d=Buffer.allocUnsafe(Math.min(1048576,s-u)),{bytesRead:f}=await j(r,d,0,d.length,u);if(f===0)throw new Error("file shrank while it was being copied");u+=f,yield d.subarray(0,f)}}l(A,"fdChunks");const i=l(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function P(){if(E()){const s=process.env.CRTR_BOOT_STORAGE_URL?.replace(/\/$/,"");return s?{service_url:s,base_url:s}:null}const r=O("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}l(P,"storageConfig");let w;function X(){const r=P(),s=R();if(!r||!s)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${s}
2
2
  ${r.service_url}
3
- ${r.base_url}`;return w?.key!==u&&(w={key:u,client:A(r,()=>C(d,r.service_url),R())}),w.client}i(F,"storageClient");function J(){w=void 0}i(J,"resetStorageClient");function A(r,d,u){let l,f;const k=i(async()=>{if(l&&l.expires_at-6e4>Date.now())return l.access_token;f??=d().finally(()=>{f=void 0});try{l=await f}catch(t){throw s(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return l.access_token},"bearer"),c=i(async(t,e,n={})=>{const p=[AbortSignal.timeout(n.timeoutMs??1e4),...n.signal?[n.signal]:[]];let o;try{o=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(p),headers:{Authorization:`Bearer ${await k()}`,...n.body===void 0?{}:{"Content-Type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(a){throw a instanceof b?a:s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(o.status===401&&(l=void 0),o.status===404||o.status===409){const a=await o.json().catch(()=>({})),g=a.error?.code??a.code??(o.status===404?"not_found":"not_uploaded");throw new m(o.status,g,a.error?.message??a.message??`storage answered ${o.status}`)}if(!o.ok)throw await o.body?.cancel().catch(()=>{}),s(`storage answered ${o.status} to ${t} ${e.split("?")[0]}`);return o},"call"),y=i(async t=>{try{return await t.json()}catch{throw s("storage answered with an invalid body")}},"json"),h=i(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await y(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const n=await c("GET",`/v1/uploads/${h(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!n.body)throw s("storage answered with no body");const p=n.headers.get("content-length");return{body:_.fromWeb(n.body),size:p===null?null:Number(p),media_type:n.headers.get("content-type")}},async signDownload(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await y(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw s("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async putShareBytes(t,e,n,p){if($(e).size!==n)throw new Error("shared file changed size while it was being copied");let o;try{o=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:_.toWeb(v(e)),duplex:"half"})}catch(a){throw s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(await o.body?.cancel().catch(()=>{}),!o.ok)throw s(`storage answered ${o.status} to the share upload`)},async deleteShare(t){try{await c("DELETE",`/v1/shares/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await y(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await y(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await y(await c("POST",`/v1/outbound/${h(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,n,p){const o=_.from(U(e,n));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:_.toWeb(o),duplex:"half"})}catch(g){throw s(`storage could not be reached: ${g instanceof Error?g.message:String(g)}`)}finally{o.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw s(`storage answered ${a.status} to the upload`)}}}i(A,"createStorageClient");function X(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}i(X,"invalidStorageName");export{m as StorageRefused,G as UPLOAD_MAX_BYTES,A as createStorageClient,X as invalidStorageName,J as resetStorageClient,F as storageClient,P as storageConfig};
3
+ ${r.base_url}`;return w?.key!==u&&(w={key:u,client:L(r,()=>C(s,r.service_url),U())}),w.client}l(X,"storageClient");function Y(){w=void 0}l(Y,"resetStorageClient");function L(r,s,u){let d,f;const k=l(async()=>{if(d&&d.expires_at-6e4>Date.now())return d.access_token;f??=s().finally(()=>{f=void 0});try{d=await f}catch(t){throw i(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return d.access_token},"bearer"),c=l(async(t,e,n={})=>{const p=[AbortSignal.timeout(n.timeoutMs??1e4),...n.signal?[n.signal]:[]];let o;try{o=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(p),headers:{Authorization:`Bearer ${await k()}`,...n.body===void 0?{}:{"Content-Type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(a){throw a instanceof b?a:i(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(o.status===401&&(d=void 0),o.status===404||o.status===409){const a=await o.json().catch(()=>({})),_=a.error?.code??a.code??(o.status===404?"not_found":"not_uploaded");throw new m(o.status,_,a.error?.message??a.message??`storage answered ${o.status}`)}if(!o.ok)throw await o.body?.cancel().catch(()=>{}),i(`storage answered ${o.status} to ${t} ${e.split("?")[0]}`);return o},"call"),y=l(async t=>{try{return await t.json()}catch{throw i("storage answered with an invalid body")}},"json"),h=l(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await y(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const n=await c("GET",`/v1/uploads/${h(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!n.body)throw i("storage answered with no body");const p=n.headers.get("content-length");return{body:g.fromWeb(n.body),size:p===null?null:Number(p),media_type:n.headers.get("content-type")}},async signDownload(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await y(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw i("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async putShareBytes(t,e,n,p){if($(e).size!==n)throw new Error("shared file changed size while it was being copied");let o;try{o=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:g.toWeb(v(e)),duplex:"half"})}catch(a){throw i(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(await o.body?.cancel().catch(()=>{}),!o.ok)throw i(`storage answered ${o.status} to the share upload`)},async deleteShare(t){try{await c("DELETE",`/v1/shares/${h(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await y(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await y(await c("POST",`/v1/uploads/${h(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await y(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await y(await c("POST",`/v1/outbound/${h(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw i("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,n,p){const o=g.from(A(e,n));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":p,"Content-Length":String(n)},body:g.toWeb(o),duplex:"half"})}catch(_){throw i(`storage could not be reached: ${_ instanceof Error?_.message:String(_)}`)}finally{o.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw i(`storage answered ${a.status} to the upload`)}}}l(L,"createStorageClient");function q(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}l(q,"invalidStorageName");export{m as StorageRefused,J as UPLOAD_MAX_BYTES,L as createStorageClient,q as invalidStorageName,Y as resetStorageClient,X as storageClient,P as storageConfig};
@@ -1,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};