@north-light/cli 0.3.744 → 0.3.746

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 (75) hide show
  1. package/README.md +2 -2
  2. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
  3. package/dist/builtin-memory/crouter-sdk/README.md +1 -1
  4. package/dist/builtin-memory/crouter-sdk/client.md +1 -1
  5. package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
  6. package/dist/clients/attach/viewer.js +1 -1
  7. package/dist/commands/sys/provider-login.js +2 -2
  8. package/dist/commands/sys.js +1 -1
  9. package/dist/core/canvas/daemon-owner.d.ts +1 -1
  10. package/dist/core/canvas/paths.d.ts +1 -1
  11. package/dist/core/canvas/person-state.d.ts +3 -0
  12. package/dist/core/canvas/person-state.js +1 -1
  13. package/dist/core/canvas/person.d.ts +2 -3
  14. package/dist/core/canvas/person.js +7 -7
  15. package/dist/core/environments.d.ts +0 -10
  16. package/dist/core/environments.js +1 -1
  17. package/dist/core/import/load/prepare.d.ts +3 -0
  18. package/dist/core/import/load/prepare.js +14 -14
  19. package/dist/core/import/load/run.js +2 -2
  20. package/dist/core/runtime/blaxel-environment.js +1 -1
  21. package/dist/core/secrets.d.ts +2 -4
  22. package/dist/core/secrets.js +1 -1
  23. package/dist/core/spaces/space.js +2 -2
  24. package/dist/core/user-settings.js +1 -1
  25. package/dist/daemon/api/environment-of.d.ts +1 -1
  26. package/dist/daemon/api/environment-of.js +3 -3
  27. package/dist/daemon/api/handlers/document-access.js +1 -1
  28. package/dist/daemon/api/router.d.ts +1 -1
  29. package/dist/daemon/crtrd-cli.js +1 -1
  30. package/dist/daemon/crtrd.d.ts +4 -2
  31. package/dist/daemon/crtrd.js +20 -20
  32. package/dist/daemon/manage.d.ts +0 -8
  33. package/dist/daemon/manage.js +3 -3
  34. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  35. package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
  36. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  37. package/docs/concepts/scopes-and-trust.md +2 -2
  38. package/docs/public-api.md +1 -7
  39. package/docs/sdk/README.md +1 -1
  40. package/docs/sdk/client.md +1 -1
  41. package/docs/sdk/getting-started.md +3 -38
  42. package/package.json +3 -3
  43. package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
  44. package/packages/crouter-api/dist/commands/sys.js +1 -3
  45. package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
  46. package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
  47. package/packages/crouter-api/dist/core/canvas/person.js +2 -14
  48. package/packages/crouter-api/dist/core/environments.js +2 -38
  49. package/packages/crouter-api/dist/core/import/load/prepare.js +7 -0
  50. package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
  51. package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
  52. package/packages/crouter-api/dist/core/secrets.js +1 -11
  53. package/packages/crouter-api/dist/core/spaces/space.js +2 -2
  54. package/packages/crouter-api/dist/core/user-settings.js +1 -1
  55. package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
  56. package/packages/crouter-api/dist/daemon/manage.js +0 -4
  57. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  58. package/packages/crouter-api/package.json +1 -1
  59. package/packages/crouter-identity/package.json +1 -1
  60. package/packages/crouter-plugin/package.json +3 -3
  61. package/runtime.lock.json +14 -14
  62. package/dist/commands/sys/connect.d.ts +0 -1
  63. package/dist/commands/sys/connect.js +0 -3
  64. package/dist/commands/sys/db.d.ts +0 -1
  65. package/dist/commands/sys/db.js +0 -1
  66. package/dist/core/canvas/export-sqlite.d.ts +0 -14
  67. package/dist/core/canvas/export-sqlite.js +0 -3
  68. package/dist/daemon/api/document-listener.d.ts +0 -7
  69. package/dist/daemon/api/document-listener.js +0 -1
  70. package/dist/daemon/api/document-secret.d.ts +0 -2
  71. package/dist/daemon/api/document-secret.js +0 -1
  72. package/dist/daemon/export-sqlite-run.d.ts +0 -1
  73. package/dist/daemon/export-sqlite-run.js +0 -4
  74. package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
  75. package/packages/crouter-api/dist/commands/sys/db.js +0 -69
@@ -1,9 +1,9 @@
1
- var g=Object.defineProperty;var o=(e,r)=>g(e,"name",{value:r,configurable:!0});import{execFile as h}from"node:child_process";import{createInterface as w}from"node:readline/promises";import{join as y}from"node:path";import{ModelRuntime as $}from"@earendil-works/pi-coding-agent";import{cliClient as s}from"../api-client.js";import{InputError as l}from"../../core/io.js";import{ApiCredentialStore as b}from"../../core/model-auth/api-credential-store.js";import{isManagedProvider as _}from"../../core/managed-providers.js";import{daemonManagedLogin as x}from"../../core/model-auth/daemon-login.js";import{piAgentDir as k}from"../../core/runtime/package-health.js";async function E(){const e=k();return $.create({credentials:new b(()=>s()),modelsPath:y(e,"models.json")})}o(E,"openProviderLoginRuntime");async function U(e,r,n,t={}){if(_(r))return await x(s(),r,n,t.label?{label:t.label}:{}),!0;const a=e.getProvider(r)?.auth.oauth;if(a===void 0)throw new l({error:"provider_login_unavailable",message:`provider ${r} has no OAuth login flow`,next:"Configure an API key through `crtr sys setup`, then run `crtr sys connect` again."});const f=await a.login(n);if(t.beforeInstall?.()===!1)return!1;const{type:A,access:d,refresh:p,expires:m,...c}=f;return await s().installCredential(r,{kind:"oauth",access_token:d,refresh_token:p,expires_at:new Date(m).toISOString(),...Object.keys(c).length>0?{extra:c}:{}}),!0}o(U,"loginProvider");function u(e){const r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];h(r,n,{timeout:5e3},()=>{})}o(u,"openBrowser");function C(e){switch(e.type){case"auth_url":process.stderr.write(`${e.instructions}
1
+ var g=Object.defineProperty;var o=(e,r)=>g(e,"name",{value:r,configurable:!0});import{execFile as h}from"node:child_process";import{createInterface as w}from"node:readline/promises";import{join as y}from"node:path";import{ModelRuntime as $}from"@earendil-works/pi-coding-agent";import{cliClient as s}from"../api-client.js";import{InputError as l}from"../../core/io.js";import{ApiCredentialStore as b}from"../../core/model-auth/api-credential-store.js";import{isManagedProvider as _}from"../../core/managed-providers.js";import{daemonManagedLogin as x}from"../../core/model-auth/daemon-login.js";import{piAgentDir as k}from"../../core/runtime/package-health.js";async function E(){const e=k();return $.create({credentials:new b(()=>s()),modelsPath:y(e,"models.json")})}o(E,"openProviderLoginRuntime");async function U(e,r,n,t={}){if(_(r))return await x(s(),r,n,t.label?{label:t.label}:{}),!0;const a=e.getProvider(r)?.auth.oauth;if(a===void 0)throw new l({error:"provider_login_unavailable",message:`provider ${r} has no OAuth login flow`,next:"Configure an API key through `crtr sys setup`, then try again."});const f=await a.login(n);if(t.beforeInstall?.()===!1)return!1;const{type:A,access:d,refresh:p,expires:m,...c}=f;return await s().installCredential(r,{kind:"oauth",access_token:d,refresh_token:p,expires_at:new Date(m).toISOString(),...Object.keys(c).length>0?{extra:c}:{}}),!0}o(U,"loginProvider");function u(e){const r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];h(r,n,{timeout:5e3},()=>{})}o(u,"openBrowser");function C(e){switch(e.type){case"auth_url":process.stderr.write(`${e.instructions}
2
2
  ${e.url}
3
3
  `),u(e.url);break;case"device_code":process.stderr.write(`${e.verificationUri}
4
4
  Code: ${e.userCode}
5
5
  `),u(e.verificationUri);break;case"info":case"progress":process.stderr.write(`${e.message}
6
- `);break}}o(C,"notify");async function v(e){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new l({error:"interactive_login_required",message:"provider login requires an interactive terminal",next:"Run `crtr sys connect` from an interactive terminal, or configure the provider credential through `crtr sys setup` first."});const r=e.type==="select"?`${e.message}
6
+ `);break}}o(C,"notify");async function v(e){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new l({error:"interactive_login_required",message:"provider login requires an interactive terminal",next:"Run this from an interactive terminal, or configure the provider credential through `crtr sys setup` first."});const r=e.type==="select"?`${e.message}
7
7
  ${e.options.map((t,i)=>`${i+1}. ${t.label}`).join(`
8
8
  `)}
9
9
  Select: `:`${e.message}${e.placeholder?` (${e.placeholder})`:""}: `,n=w({input:process.stdin,output:process.stderr});try{const t=await n.question(r,{signal:e.signal});if(e.type!=="select")return t;const i=e.options[Number.parseInt(t,10)-1]?.id;if(i===void 0)throw new Error("Login cancelled");return i}finally{n.close()}}o(v,"promptTerminal");function Y(){return{signal:new AbortController().signal,notify:C,prompt:v}}o(Y,"terminalAuthInteraction");export{U as loginProvider,E as openProviderLoginRuntime,Y as terminalAuthInteraction};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as a}from"./sys/doctor.js";import{sysFeedbackLeaf as p}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysConnectLeaf as g}from"./sys/connect.js";import{sysSetupLeaf as u}from"./sys/setup.js";import{tutorialBranch as d}from"./sys/tutorial/branch.js";import{supportBranch as D}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as b}from"./sys/sync.js";import{sysMigrateLeaf as l}from"./sys/migrate.js";import{sysJoinLeaf as v}from"./sys/join.js";import{sysDbBranch as x}from"./sys/db.js";import{sysImportBranch as M}from"./sys/import/start.js";import{sysMachineBranch as C}from"./sys/machine/rotate.js";import{sysDesktopBranch as E}from"./sys/desktop.js";import{sysSigninLeaf as F,sysSignoutLeaf as I}from"./sys/signin.js";import{sysUpdateLeaf as J,sysVersionLeaf as R}from"./sys/update.js";function er(){return t([S,f,i,g,u,d,a,k,p,n,c,y,L,h,B,D,J,R,l,v,b,x,M,C,F,I,E,e])}r(er,"registerSys");export{er as registerSys};
1
+ var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as a}from"./sys/doctor.js";import{sysFeedbackLeaf as p}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{sysMigrateLeaf as l}from"./sys/migrate.js";import{sysJoinLeaf as v}from"./sys/join.js";import{sysImportBranch as x}from"./sys/import/start.js";import{sysMachineBranch as M}from"./sys/machine/rotate.js";import{sysDesktopBranch as b}from"./sys/desktop.js";import{sysSigninLeaf as E,sysSignoutLeaf as F}from"./sys/signin.js";import{sysUpdateLeaf as I,sysVersionLeaf as J}from"./sys/update.js";function sr(){return t([S,f,i,g,u,a,k,p,n,c,y,L,h,B,d,I,J,l,v,D,x,M,E,F,b,e])}r(sr,"registerSys");export{sr as registerSys};
@@ -15,7 +15,7 @@ export interface DaemonOwnerClaim {
15
15
  * process running both roles); the cloud's `--role api` and `--role reconcile` processes are several per database by design, so
16
16
  * they never claim, never release, and never read the row. The caller (`crtrd.ts`) checks this before
17
17
  * `claimDaemonOwnership` / `releaseDaemonOwnership` / `daemonOwnershipClaimed`. */
18
- export declare function daemonOwnershipApplies(role: 'api' | 'reconcile' | 'machine' | undefined): boolean;
18
+ export declare function daemonOwnershipApplies(role: 'api' | 'reconcile' | 'machine' | 'all' | undefined): boolean;
19
19
  /** Every terminal, non-retriable way `claimDaemonOwnership` can lose. A loss
20
20
  * never deletes or otherwise mutates the incumbent row — only a positively
21
21
  * DEAD incumbent is ever CAS-replaced. */
@@ -1,6 +1,6 @@
1
1
  /** Runtime-owned records; never a bind source for an app sandbox. */
2
2
  export declare function crtrHome(): string;
3
- /** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres and by `crtr sys db export-sqlite`. */
3
+ /** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres. */
4
4
  export declare function canvasDbPath(): string;
5
5
  export declare function onDiskMigrationLockPath(): string;
6
6
  export declare function onDiskMigrationMarkerPath(): string;
@@ -15,6 +15,9 @@ export declare function setPersonId(id: string): void;
15
15
  export declare function markCloudRole(): void;
16
16
  /** Whether this process is a cloud role (`markCloudRole` ran at boot). */
17
17
  export declare function isCloudRole(): boolean;
18
+ /** `crtrd --role all` (tests and crouter development) runs every node's engine on its own host: no Blaxel sandbox, no remote machine. */
19
+ export declare function markEnginesInProcess(): void;
20
+ export declare function areEnginesInProcess(): boolean;
18
21
  /** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
19
22
  export declare function runAsPerson<T>(person: string, fn: () => T): T;
20
23
  /** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
@@ -1 +1 @@
1
- var u=Object.defineProperty;var r=(e,n)=>u(e,"name",{value:n,configurable:!0});import{AsyncLocalStorage as d}from"node:async_hooks";class i extends Error{static{r(this,"PersonUnresolvedError")}code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}}class c extends Error{static{r(this,"PersonOutsideRequestError")}code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}}let o,t=!1;const s=new d;function f(e){o=e}r(f,"setPersonId");function a(){t=!0}r(a,"markCloudRole");function x(){return t}r(x,"isCloudRole");function P(e,n){return s.run(e,n)}r(P,"runAsPerson");function m(){const e=s.getStore();if(e!==void 0)return e;if(t)throw new c;if(o===void 0)throw new i;return o}r(m,"personId");function q(){return o}r(q,"bootPersonId");function h(){return s.getStore()}r(h,"requestPersonId");export{c as PersonOutsideRequestError,i as PersonUnresolvedError,q as bootPersonId,x as isCloudRole,a as markCloudRole,m as personId,h as requestPersonId,P as runAsPerson,f as setPersonId};
1
+ var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{AsyncLocalStorage as d}from"node:async_hooks";class c extends Error{static{e(this,"PersonUnresolvedError")}code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}}class l extends Error{static{e(this,"PersonOutsideRequestError")}code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}}let o,t=!1;const s=new d;function a(r){o=r}e(a,"setPersonId");function x(){t=!0}e(x,"markCloudRole");function P(){return t}e(P,"isCloudRole");let u=!1;function m(){u=!0}e(m,"markEnginesInProcess");function E(){return u}e(E,"areEnginesInProcess");function I(r,n){return s.run(r,n)}e(I,"runAsPerson");function q(){const r=s.getStore();if(r!==void 0)return r;if(t)throw new l;if(o===void 0)throw new c;return o}e(q,"personId");function g(){return o}e(g,"bootPersonId");function h(){return s.getStore()}e(h,"requestPersonId");export{l as PersonOutsideRequestError,c as PersonUnresolvedError,E as areEnginesInProcess,g as bootPersonId,P as isCloudRole,x as markCloudRole,m as markEnginesInProcess,q as personId,h as requestPersonId,I as runAsPerson,a as setPersonId};
@@ -2,13 +2,12 @@ import { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markClou
2
2
  import { type CanvasDb } from './db.js';
3
3
  import { LEGACY_LOCAL_PERSON } from './legacy-person.js';
4
4
  export { LEGACY_LOCAL_PERSON };
5
- export type PersonSource = 'stored' | 'joined' | 'grants' | 'minted';
5
+ export type PersonSource = 'stored' | 'joined' | 'grants';
6
6
  export { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId };
7
7
  /** As `personId()`, but a process that is not the daemon gets a lazy get-or-create keyed by the active canvas database. */
8
8
  export declare function personIdAsync(): Promise<string>;
9
9
  /** Get-or-create the person and say where it came from. Order: stored, the join file's owner, the single `sub` of the
10
- * mirrored grants (a runtime with an issuer and no join file), else a minted id on a runtime without an issuer.
11
- * Null when an issuer runtime has no mirrored grants yet; nothing is stored then. */
10
+ * mirrored grants (a runtime with an issuer and no join file), else null (nothing is stored): no person is ever minted. */
12
11
  export declare function resolvePerson(): Promise<{
13
12
  id: string;
14
13
  source: PersonSource;
@@ -1,11 +1,11 @@
1
- var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as f,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new f;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["files","sub"],["files","grantee"],["shares","sub"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
1
+ var U=Object.defineProperty;var c=(n,e)=>U(n,"name",{value:e,configurable:!0});import{CrtrError as N}from"../errors.js";import{PersonUnresolvedError as R,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as H,isCloudRole as D,runAsPerson as W,personId as v,bootPersonId as b,requestPersonId as $}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as k,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as C}from"../grants/local.js";import{dropLocalGrantMirror as M}from"../grants/mirror.js";import{ownerForGrantee as F,ensureOwner as x}from"../graph/objects.js";import{canvasDatabaseUrl as G,CanvasConstraintError as J,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as q}from"../ledger/totals.js";const d="person_id",O="local_person_retired",z=/^user:[A-Za-z0-9._-]+$/,I=new Map;async function de(){const n=$();if(n!==void 0)return n;if(D())throw new A;const e=b();if(e!==void 0)return e;const r=await G(),t=I.get(r);if(t!==void 0)return t;const s=await K();if(s===null)throw new R;return I.set(r,s),s}c(de,"personIdAsync");async function T(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(T,"readMeta");async function g(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(g,"writeMeta");async function B(){return await j(async n=>{const e=await T(n,d);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await g(n,d,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const t=await n.prepare("SELECT DISTINCT sub FROM grants").all();return t.length!==1?null:(await g(n,d,t[0].sub),{id:t[0].sub,source:"grants"})}return null})}c(B,"resolvePerson");async function K(){return(await B())?.id??null}c(K,"resolvePersonId");const a=c(n=>Number(n.changes),"changes"),X=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["files","sub"],["files","grantee"],["shares","sub"],["provider_approvals","grantee"]],V=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],Z=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function L(n,e){if(!z.test(e))throw new N("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(L,"assertPerson");async function Q(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(Q,"namesPerson");async function P(n,e,r){if(L("from",e),L("to",r),e===r)throw new N("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=a(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=a(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof J?new N("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=a(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
2
2
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
3
- AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
3
+ AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of X)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+a(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const s=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=a(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
4
4
  AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
5
- AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+s(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,a)),t["relations.written_by"]=s(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=s(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of ne)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of ee){const d=s(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+s(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));d!==0&&(t[`${o}.person`]=d)}const u=s(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await re(n,e))&&(await z(n,e,r),t["charge_totals.rebuilt"]=1),t}c(U,"substitutePerson");async function te(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
6
- WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?s(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await G(n,"app:terminal")).id)):0)+s(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+s(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(te,"rewriteLegacyGrantees");async function ae(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),a=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=s(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t)),p["node_tokens.grant"]=s(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${a})`).run(r,...t)),p["crons.grant_id"]=s(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=s(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
5
+ AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(s,p))+a(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,s)),t["relations.written_by"]=a(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=a(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of Z)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of V){const l=a(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+a(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));l!==0&&(t[`${o}.person`]=l)}const u=a(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await Q(n,e))&&(await q(n,e,r),t["charge_totals.rebuilt"]=1),t}c(P,"substitutePerson");async function ee(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
6
+ WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?a(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await F(n,"app:terminal")).id)):0)+a(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+a(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(ee,"rewriteLegacyGrantees");async function ne(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),s=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=a(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t)),p["node_tokens.grant"]=a(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${s})`).run(r,...t)),p["crons.grant_id"]=a(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=a(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
7
7
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
8
- AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[N,R]of Object.entries(w))R!==0&&(r[T+N]=(r[T+N]??0)+R)},"add");let a=await m(e,l);if(a===null)throw new f;let p=null;const u=h();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
9
- WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${w} LIMIT 1`).get()!==void 0){const T=await J(e,"person","user",a,"user");t({repaired_stubs:s(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${w})`).run(T.id))})}t({"nodes.sub_null_terminal":s(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
8
+ AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${s})`).run(...r===null?[]:[r],...t)),p}c(ne,"repointGrantReferences");async function _e(){const n=await j(async e=>{const r={},t=c((_,w="")=>{for(const[m,f]of Object.entries(_))f!==0&&(r[w+m]=(r[w+m]??0)+f)},"add");let s=await T(e,d);if(s===null)throw new R;let p=null;const u=h();u!==null&&u!==s&&(t(await P(e,s,u),"join."),await g(e,d,u),p=s,s=u);const o=k()??S("user").runtime?.issuer,i=await T(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const l=await T(e,O)!==s;if(l){t({legacy_grantees:await ee(e)}),t(await P(e,E,s));const _=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
9
+ WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${_} LIMIT 1`).get()!==void 0){const w=await x(e,"person","user",s,"user");t({repaired_stubs:a(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${_})`).run(w.id))})}t({"nodes.sub_null_terminal":a(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
10
10
  SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
11
- WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,f as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
11
+ WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(s))}),t(await ne(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await M(e)}),await g(e,O,s)}return o||await C(i,s),{person:s,joinedFrom:p,retired:l,columns:r}});return y(n.person),n}c(_e,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,R as PersonUnresolvedError,D as isCloudRole,H as markCloudRole,v as personId,de as personIdAsync,B as resolvePerson,K as resolvePersonId,_e as retireLocalPerson,W as runAsPerson,y as setPersonId,P as substitutePerson};
@@ -1,11 +1,5 @@
1
1
  import type { CanvasDb } from './canvas/db.js';
2
2
  import { type EnvironmentRecipeInput } from './environment-recipe.js';
3
- /** Find the `environments` row for `installId`, or create its object and row; either way set `last_seen_at`, and cache
4
- * the environment id and install id for {@link machineEnvironmentId} and {@link touchMachineEnvironment}. */
5
- export declare function registerMachineEnvironment(installId: string): Promise<{
6
- environmentId: string;
7
- created: boolean;
8
- }>;
9
3
  /** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
10
4
  * its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
11
5
  * caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
@@ -18,7 +12,3 @@ export declare function createProfileBlaxelEnvironment(db: CanvasDb, spec: {
18
12
  memoryMb?: number;
19
13
  recipe?: EnvironmentRecipeInput;
20
14
  }): Promise<string>;
21
- /** Stamp `last_seen_at` on the machine environment: one statement, no read. A no-op before {@link registerMachineEnvironment}. */
22
- export declare function touchMachineEnvironment(now: string): Promise<void>;
23
- /** The machine environment's object id; throws before {@link registerMachineEnvironment} has run. */
24
- export declare function machineEnvironmentId(): string;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var a=(e,n)=>u(e,"name",{value:n,configurable:!0});import{openDb as d,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as f,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as _}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async r=>{const i=await r.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(i!==void 0)return await r.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:i.object,created:!1};const l=await w(r,"app:terminal"),m=await p(r,{type:"environment",kind:"machine",owner:l.id,privacy:"public",name:e,preview:"machine"});return v()||await s(r,m.id,await E()),await r.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function I(e,n){const t=await w(e,n.grantee),r=await f(e,"profile","profile",n.profileId,n.profileId,t),i=await p(e,{type:"environment",kind:"blaxel",owner:r.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,i.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)").run(i.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,i.id,n.recipe),i.id}a(I,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await d()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),_((e,n)=>c(async t=>{await n(await I(t,e))}));export{I as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
1
+ var n=Object.defineProperty;var o=(r,e)=>n(r,"name",{value:e,configurable:!0});import{withCanvasWrite as l}from"./canvas/db.js";import{createObject as m,ensureOwner as p,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as f}from"./permissions/facts.js";import{writeEnvironmentRecipe as c}from"./environment-recipe.js";import{setCloudProfileWriter as d}from"./profiles/manifest.js";async function u(r,e){const t=await w(r,e.grantee),a=await p(r,"profile","profile",e.profileId,e.profileId,t),i=await m(r,{type:"environment",kind:"blaxel",owner:a.id,privacy:"private",name:e.profileId,preview:"blaxel"});return await f(r,i.id,e.person),await r.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)").run(i.id,e.memoryMb??2048,new Date().toISOString()),e.recipe!==void 0&&await c(r,i.id,e.recipe),i.id}o(u,"createProfileBlaxelEnvironment"),d((r,e)=>l(async t=>{await e(await u(t,r))}));export{u as createProfileBlaxelEnvironment};
@@ -39,6 +39,9 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
39
39
  /** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
40
40
  * row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
41
41
  export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
42
+ /** A staged idempotency key at least `IDEMPOTENCY_WINDOW_MS` old is already expired (`findIdempotent` ignores it and the daemon's sweep deletes it within a minute), so it is dropped before
43
+ * the copy: otherwise the sweep removes it between copy and verify and verify reports a difference. Returns the dropped rows. Runs before the pre-check. */
44
+ export declare function dropExpiredIdempotencyKeys(db: CanvasDb, schema: string): Promise<number>;
42
45
  /** The rows `fillEnvironments` created, as manifest keys per table, so rollback removes them and verify (which has no staged row for them) skips them. */
43
46
  export interface FilledRow {
44
47
  table: string;
@@ -1,14 +1,14 @@
1
- var D=Object.defineProperty;var E=(t,s)=>D(t,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((t,s)=>`${l(t)}.${l(s)}`,"sq");async function K(t,s,o){if(o.length===0)return 0;const e=E(c=>d(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const p=E(async(c,r,n,$=!1)=>{const R=await t.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of R){const T=$?g(f,o):S(o,f);T!==f&&(await t.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,f),a+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(t,s,o,e,i){if(o.length===0)return 0;const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
- AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=M(i,n),R=await e.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=H(R,r,T=>S(o,T));f!==null&&(await e.put($,f),c+=1),await t.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??R).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(t,s){const o=d(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
3
- WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
- WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
5
- ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await t.prepareUncached(`UPDATE ${o} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
6
- request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function g(t,s){const o=E(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(o):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,o(a)])):e,"walk");try{return JSON.stringify(o(JSON.parse(t)))}catch{return S(s,t)}}E(g,"rewriteJsonPaths");async function Y(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await t.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
- WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=n===void 0?void 0:await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&R===void 0)continue;const f=`${r.name}-${e}`;await t.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),n!==void 0&&await t.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,n.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(t,s,o,e){const i=await t.prepareUncached(`UPDATE ${d(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
8
- WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(t,s,o){const e=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await t.prepareUncached(`DELETE FROM ${d(s,"watch_subscriptions")} u USING ${d(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await t.prepareUncached(`DELETE FROM ${d(s,"watches")} s WHERE EXISTS (SELECT 1 ${e})`).run();return{watches:Number(a.changes),watch_subscriptions:Number(i.changes)}}E(G,"dropExistingWatches");async function z(t,s,o){const e=await t.prepareUncached(`DELETE FROM ${d(s,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(e.changes)}E(z,"dropExistingIdempotencyKeys");async function Q(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=[],c=await t.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"){const $=await t.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(t,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const R of await t.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await t.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(Q,"fillEnvironments");async function V(t,s,o,e){const i=E(c=>d(s,c),"S"),a={},p=E(async(c,r,...n)=>{const $=Number((await t.prepareUncached(r).run(...n)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await t.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await t.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(v))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await t.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}E(V,"pruneStaged");async function Z(t,s,o){const e=E(p=>d(s,p),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await t.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
9
- CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await t.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
- COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
11
- FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await t.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await t.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(p=>({...p}))}E(Z,"takeRepoSyncedDocuments");const C={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function ee(t,s,o,e,i,a,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...C[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=e.tables.get(n);if($===void 0||a.has(n)||$.primaryKey.length===0)continue;const R=$.primaryKey,f=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),y=f?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===n&&!h.columns.every(_=>I.has(_)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,_=u.columns.map(m=>`s.${l(m)} = t.${l(m)}`).join(" AND "),O=await t.prepareUncached(`SELECT ${u.columns.map(m=>`s.${l(m)}::text`).join(" || ',' || ")} AS value
12
- FROM (SELECT * FROM ${d(s,n)}${h}) s JOIN (SELECT * FROM ${d(o,n)}${h}) t ON ${_} AND (${y}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(m=>m.value)});const A=f?"TRUE":R.map(m=>`a.${l(m)} IS DISTINCT FROM b.${l(m)}`).join(" OR "),L=await t.prepareUncached(`SELECT DISTINCT ${u.columns.map(m=>`a.${l(m)}::text`).join(" || ',' || ")} AS value
13
- FROM (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) b ON ${u.columns.map(m=>`a.${l(m)} = b.${l(m)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:n,key:u.name,values:L.map(m=>m.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),h=await t.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
14
- FROM ${d(s,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:n,key:"primary key payload",values:h.map(_=>_.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(ee,"precheck");export{z as dropExistingIdempotencyKeys,G as dropExistingWatches,Q as fillEnvironments,ee as precheck,V as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Z as takeRepoSyncedDocuments};
1
+ var A=Object.defineProperty;var E=(e,a)=>A(e,"name",{value:a,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as M,mapPath as S}from"../bundle/layout.js";import{IDEMPOTENCY_WINDOW_MS as g}from"../../runs/operations.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as v}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((e,a)=>`${l(e)}.${l(a)}`,"sq");async function J(e,a,o){if(o.length===0)return 0;const t=E(c=>d(a,c),"S"),i=`(SELECT node_id FROM ${t("nodes")} WHERE status IN ('active', 'idle'))`;let s=0;const p=E(async(c,r,n,$=!1)=>{const m=await e.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${t(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:_}of m){const T=$?C(_,o):S(o,_);T!==_&&(await e.prepareUncached(`UPDATE ${t(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,_),s+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),s}E(J,"rewritePaths");async function Y(e,a,o,t,i){if(o.length===0)return 0;const s=E(r=>d(a,r),"S"),p=await e.prepareUncached(`SELECT conversation_id, blob_key FROM ${s("conversation_parts")} WHERE seq = 0
2
+ AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=v(i,n),m=await t.get($);if(m===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const _=H(m,r,T=>S(o,T));_!==null&&(await t.put($,_),c+=1),await e.prepareUncached(`UPDATE ${s("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((_??m).length,r)}return c}E(Y,"rewriteConversationHeaders");async function X(e,a){const o=d(a,"human_requests"),t=E(s=>`CASE WHEN ${s} IS NULL OR ${s} NOT LIKE '/%' THEN ${s}
3
+ WHEN rtrim(${s}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
+ WHEN ${s} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${s}, length(rtrim(request_dir, '/')) + 2)
5
+ ELSE 'requests/' || request_id || '/source/' || regexp_replace(${s}, '^.*/', '') END`,"moved"),i=await e.prepareUncached(`UPDATE ${o} SET file = ${t("file")}, presentation_dir = ${t("presentation_dir")},
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(X,"rewriteRequestPaths");function C(e,a){const o=E(t=>typeof t=="string"?S(a,t):Array.isArray(t)?t.map(o):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([i,s])=>[i,o(s)])):t,"walk");try{return JSON.stringify(o(JSON.parse(e)))}catch{return S(a,e)}}E(C,"rewriteJsonPaths");async function G(e,a,o,t,i){const s=E(r=>d(a,r),"S"),p=await e.prepareUncached(`SELECT id, name FROM ${s("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await e.prepareUncached(`SELECT o.id FROM ${s("objects")} o JOIN ${s("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
+ WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),m=n===void 0?void 0:await e.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&m===void 0)continue;const _=`${r.name}-${t}`;await e.prepareUncached(`UPDATE ${s("profiles")} SET name = ? WHERE id = ?`).run(_,r.id),n!==void 0&&await e.prepareUncached(`UPDATE ${s("objects")} SET name = ? WHERE id = ?`).run(_,n.id),c+=1}return c}E(G,"renameClashingProfiles");async function z(e,a,o,t){const i=await e.prepareUncached(`UPDATE ${d(a,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
8
+ WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(t);return Number(i.changes)}E(z,"renameClashingLegacyCharges");async function Q(e,a,o){const t=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await e.prepareUncached(`DELETE FROM ${d(a,"watch_subscriptions")} u USING ${d(a,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${t})`).run(),s=await e.prepareUncached(`DELETE FROM ${d(a,"watches")} s WHERE EXISTS (SELECT 1 ${t})`).run();return{watches:Number(s.changes),watch_subscriptions:Number(i.changes)}}E(Q,"dropExistingWatches");async function V(e,a,o){const t=await e.prepareUncached(`DELETE FROM ${d(a,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(t.changes)}E(V,"dropExistingIdempotencyKeys");async function Z(e,a){const o=await e.prepareUncached(`DELETE FROM ${d(a,"idempotency_keys")} WHERE created_at <= ?`).run(new Date(Date.now()-g).toISOString());return Number(o.changes)}E(Z,"dropExpiredIdempotencyKeys");async function ee(e,a,o,t,i){const s=E(r=>d(a,r),"S"),p=[],c=await e.prepareUncached(`SELECT id, grantee FROM ${s("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=t.kind==="machine"?t.environmentObject??null:null;if(t.kind==="hosted"){const $=await e.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(e,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const m of await e.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[m.resource_type,m.resource_id,m.relation,m.subject_type,m.subject_id,m.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await e.prepareUncached(`UPDATE ${s("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(ee,"fillEnvironments");async function te(e,a,o,t){const i=E(c=>d(a,c),"S"),s={},p=E(async(c,r,...n)=>{const $=Number((await e.prepareUncached(r).run(...n)).changes);$>0&&(s[c]=(s[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),t.kind==="hosted"&&(await e.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await e.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(M))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,t.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await e.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return s}E(te,"pruneStaged");async function ne(e,a,o){const t=E(p=>d(a,p),"S"),i=`(SELECT d.object FROM ${t("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await e.exec(`CREATE TABLE ${t("_arr_revisions")} AS SELECT r.* FROM ${t("revisions")} r WHERE r.document IN ${i};
9
+ CREATE TABLE ${t("_arr_parents")} AS SELECT p.* FROM ${t("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${i})`);const s=await e.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
+ COALESCE((SELECT array_agg(p.parent) FROM ${t("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
11
+ FROM ${t("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await e.prepareUncached(`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${i})`).run(),await e.prepareUncached(`DELETE FROM ${t("revisions")} WHERE document IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${t("objects")} WHERE id IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${t("documents")} WHERE object IN ${i}`).run(),s.map(p=>({...p}))}E(ne,"takeRepoSyncedDocuments");const W={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function re(e,a,o,t,i,s,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...W[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=t.tables.get(n);if($===void 0||s.has(n)||$.primaryKey.length===0)continue;const m=$.primaryKey,_=m.some(u=>$.identity.includes(u)),T=m.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),L=_?"TRUE":m.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of t.uniqueKeys.filter(f=>f.table===n&&!f.columns.every(h=>I.has(h)))){const f=u.predicate===null?"":` WHERE ${u.predicate}`,h=u.columns.map(R=>`s.${l(R)} = t.${l(R)}`).join(" AND "),O=await e.prepareUncached(`SELECT ${u.columns.map(R=>`s.${l(R)}::text`).join(" || ',' || ")} AS value
12
+ FROM (SELECT * FROM ${d(a,n)}${f}) s JOIN (SELECT * FROM ${d(o,n)}${f}) t ON ${h} AND (${L}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(R=>R.value)});const D=_?"TRUE":m.map(R=>`a.${l(R)} IS DISTINCT FROM b.${l(R)}`).join(" OR "),y=await e.prepareUncached(`SELECT DISTINCT ${u.columns.map(R=>`a.${l(R)}::text`).join(" || ',' || ")} AS value
13
+ FROM (SELECT ctid AS row_id, * FROM ${d(a,n)}${f}) a JOIN (SELECT ctid AS row_id, * FROM ${d(a,n)}${f}) b ON ${u.columns.map(R=>`a.${l(R)} = b.${l(R)}`).join(" AND ")} AND a.row_id < b.row_id AND (${D}) LIMIT 10`).all();y.length>0&&r.push({table:n,key:u.name,values:y.map(R=>R.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!_){const u=w.map(h=>`s.${l(h)} IS DISTINCT FROM t.${l(h)}`).join(" OR "),f=await e.prepareUncached(`SELECT ${m.map(h=>`s.${l(h)}::text`).join(" || ',' || ")} AS value
14
+ FROM ${d(a,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();f.length>0&&r.push({table:n,key:"primary key payload",values:f.map(h=>h.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(re,"precheck");export{V as dropExistingIdempotencyKeys,Q as dropExistingWatches,Z as dropExpiredIdempotencyKeys,ee as fillEnvironments,re as precheck,te as pruneStaged,z as renameClashingLegacyCharges,G as renameClashingProfiles,Y as rewriteConversationHeaders,J as rewritePaths,X as rewriteRequestPaths,ne as takeRepoSyncedDocuments};
@@ -1,3 +1,3 @@
1
- var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as Z}from"../../graph/documents.js";import{getById as x}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExistingWatches as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ce,rewriteConversationHeaders as ue,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Se}from"./bind.js";import{deleteBlobs as ve,deleteRunBlobs as Ee,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as ke,renameClashingRepos as Te,rewriteIds as Ce,rewritePerson as Me,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as Ae,stagingSchema as Be,targetSchema as Le}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as Ke}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{openImportGrants as Ge}from"./open-grants.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ye}from"../../events/emit.js";import{ClaimLostError as ze}from"../../../daemon/reconcilers/row-claim.js";const Qe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),K=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(i.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Xe,"readSource");async function Ze(e,r,i,a,n,d,p){const o=[];for(const t of L(i.run_id,"grants",a)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ee(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,a.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await Pe(r,n,d,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw je(f)}m(Ze,"ensureGrants");async function Ot(e,r,i={}){const a=i.blobs??await X(),n=await E(),d=Be(e.run_id);let p="start";const o=m(async t=>{p=t,await r.assertOwned(),await K(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(a,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Le(n),I=[...$e],h=await ae(n,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(n,c,t.person,e.person),await o("open-grants"),await Ze(a,n,e,t,c,k,i.openGrants??Ge),await o("publish-plugins");const H=await Ue(a,e.run_id),S=await A(e.person,()=>qe(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Qe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await o("stage");const U=await Ae(n,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>a.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:n,schema:d,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[s,u]of Object.entries(await he(_)))b(l,s,u);for(const[s,u]of Object.entries(await be(_)))b(l,s,u);await o("rewrite-person"),await Me(_),await De(_),await o("prune");const F=await se(n,d,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(n,d,v),await ue(n,d,v,a,e.run_id),await fe(n,d),await Se(_);const J=await ke(_);await ce(n,d,c,t.installId,e.person),await o("rewrite-ids");const T=await Ce(_,J);await o("drop");const G=await me(n,d,c),q=await Oe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await ye(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Te(_),await pe(n,d,c,t.installId);for(const[s,u]of Object.entries(await de(n,d,c)))b(l,s,u);b(l,"idempotency_keys",await oe(n,d,c)),await o("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(n,d,c,h,I,new Set,$),await o("blobs"),await Ie(n,d,c,e.person,a,e.run_id,f),await o("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:d,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await tt(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ke(s,d,e.run_id,t);const M=await Je({db:s,blobs:a,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...et(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await o("verify");const y=await Ne(n,e.run_id,d,c,h,t.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=B.manifest(e.run_id);await a.put(O,await at(e.run_id)),await W(n,e.run_id);for(const l of He(e.run_id))await a.delete(l);await Ee(a,e.run_id),await D(async l=>{await Fe(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof ze)throw t;const c=xe(t,p);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await W(n,e.run_id).catch(()=>{}),w||await ve(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Ot,"processRun");function xe(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(xe,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function et(e,r){for(const[i,a]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[i,a]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(et,"withInserted");async function tt(e,r,i){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),n=i.filter(p=>!a.has(p.rev_id)),d=new Map;for(const p of i)d.set(p.document,[...d.get(p.document)??[],p]);for(const[p,o]of d){const w=await x(e,p);w!==null&&await Z(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",n.map(p=>[p.rev_id])),await N(e,r,"revision_parents",n.flatMap(p=>p.parents.map(o=>[p.rev_id,o]))),n.length}m(tt,"arrive");async function at(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(i.map(a=>JSON.stringify({table:a.table_name,keys:ie(a.inserted_keys)})).join(`
1
+ var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as x}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExpiredIdempotencyKeys as de,dropExistingWatches as pe,renameClashingLegacyCharges as ce,renameClashingProfiles as ue,rewriteConversationHeaders as le,rewritePaths as fe,rewriteRequestPaths as me,takeRepoSyncedDocuments as _e}from"./prepare.js";import{boundSub as we,dropRefusedMessages as ge,checkSourcePerson as be,checkStagedBlobKeys as he,checkStagedPersons as ye,checkStagedReferences as Se,checkStagedRequestKeys as ve}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Re,deleteRunPrefix as Ie,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Pe,findFleetGrant as je,grantMissing as ke,mapProfileIds as Te,renameClashingRepos as Ce,rewriteIds as Me,rewritePerson as De,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Be,stagingSchema as Le,targetSchema as Ne}from"./stage.js";import{verifyRun as Ke}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ue,readPluginsStore as Fe,recordImportedActivations as Je,writeStores as Ge}from"./stores.js";import{openImportGrants as qe}from"./open-grants.js";import{publishImportedPlugins as $e}from"./publish-plugins.js";import{COPIED_TABLES as Ye}from"../bundle/layout.js";import{emitEvent as ze}from"../../events/emit.js";import{ClaimLostError as Qe}from"../../../daemon/reconcilers/row-claim.js";const xe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),W=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(i.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(Xe,"readSource");async function Ze(e,r,i,n,a,o,p){const d=[];for(const t of L(i.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);d.push(...ee(c))}if(d.length===0)return;const w=d.map(t=>({sub:we(t.sub,n.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await je(r,a,o,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw ke(f)}m(Ze,"ensureGrants");async function Pt(e,r,i={}){const n=i.blobs??await V(),a=await E(),o=Le(e.run_id);let p="start";const d=m(async t=>{p=t,await r.assertOwned(),await W(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ne(a),I=[...Ye],h=await ae(a,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await be(a,c,t.person,e.person),await d("open-grants"),await Ze(n,a,e,t,c,k,i.openGrants??qe),await d("publish-plugins");const H=await Fe(n,e.run_id),S=await A(e.person,()=>$e(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=xe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await W(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await d("stage");const U=await Be(a,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>n.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:a,schema:o,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await d("bind-staged");for(const[s,u]of Object.entries(await ye(_)))b(l,s,u);for(const[s,u]of Object.entries(await he(_)))b(l,s,u);await d("rewrite-person"),await De(_),await Ae(_),await d("prune");const F=await se(a,o,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await d("rewrite-paths"),await fe(a,o,v),await le(a,o,v,n,e.run_id),await me(a,o),await ve(_);const J=await Te(_);await ue(a,o,c,t.installId,e.person),await d("rewrite-ids");const T=await Me(_,J);await d("drop");const G=await _e(a,o,c),q=await Pe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await ge(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await Se(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Ce(_),await ce(a,o,c,t.installId);for(const[s,u]of Object.entries(await pe(a,o,c)))b(l,s,u);b(l,"idempotency_keys",await oe(a,o,c)),b(l,"idempotency_keys",await de(a,o)),await d("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(a,o,c,h,I,new Set,$),await d("blobs"),await Oe(a,o,c,e.person,n,e.run_id,f),await d("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:o,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await at(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(s,o,e.run_id,t);const M=await Ge({db:s,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...tt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await d("verify");const y=await Ke(a,e.run_id,o,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const O=B.manifest(e.run_id);await n.put(O,await nt(e.run_id)),await K(a,e.run_id);for(const l of Ue(e.run_id))await n.delete(l);await Re(n,e.run_id),await D(async l=>{await Je(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Qe)throw t;const c=et(t,p);ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Ie(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Pt,"processRun");function et(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(et,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function tt(e,r){for(const[i,n]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[i,n]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(tt,"withInserted");async function at(e,r,i){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),a=i.filter(p=>!n.has(p.rev_id)),o=new Map;for(const p of i)o.set(p.document,[...o.get(p.document)??[],p]);for(const[p,d]of o){const w=await Z(e,p);w!==null&&await X(e,w,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",a.map(p=>[p.rev_id])),await N(e,r,"revision_parents",a.flatMap(p=>p.parents.map(d=>[p.rev_id,d]))),a.length}m(at,"arrive");async function nt(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return x(Buffer.from(i.map(n=>JSON.stringify({table:n.table_name,keys:ie(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(at,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
3
+ `))}m(nt,"manifestFile");export{Ve as COPY_LEASE_MS,xe as GRANT_WAIT_MS,Pt as processRun};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var e=(n,t)=>o(n,"name",{value:t,configurable:!0});import{openDb as r}from"../canvas/db.js";import{isCloudRole as i}from"../canvas/person-state.js";import{machineEnvironmentOfProfile as l}from"./runner/machine/environment.js";async function a(n){return n===null?null:(await(await r()).prepare("SELECT e.object AS object FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ? AND e.kind = 'blaxel'").get(n))?.object??null}e(a,"blaxelEnvironmentOf");async function p(n){return n===null?null:await a(n)??(i()?await l(n):null)}e(p,"remoteEnvironmentOf");export{a as blaxelEnvironmentOf,p as remoteEnvironmentOf};
1
+ var o=Object.defineProperty;var e=(n,r)=>o(n,"name",{value:r,configurable:!0});import{openDb as i}from"../canvas/db.js";import{areEnginesInProcess as t,isCloudRole as l}from"../canvas/person-state.js";import{machineEnvironmentOfProfile as a}from"./runner/machine/environment.js";async function m(n){return n===null||t()?null:(await(await i()).prepare("SELECT e.object AS object FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ? AND e.kind = 'blaxel'").get(n))?.object??null}e(m,"blaxelEnvironmentOf");async function s(n){return n===null?null:await m(n)??(l()&&!t()?await a(n):null)}e(s,"remoteEnvironmentOf");export{m as blaxelEnvironmentOf,s as remoteEnvironmentOf};
@@ -11,7 +11,7 @@ export interface SecretsStore {
11
11
  apiToken?: string;
12
12
  scopedApiTokens?: ScopedApiToken[];
13
13
  }
14
- /** A bearer token minted by `crtr sys connect --scopes` whose `scopes` list is
14
+ /** A bearer token minted for an app whose `scopes` list is
15
15
  * the ceiling for every scope-gated daemon operation the holder performs. The
16
16
  * owner token (`apiToken`) has no ceiling. */
17
17
  export interface ScopedApiToken {
@@ -29,15 +29,13 @@ export declare function getRelayToken(ref: string, scope: Scope): string | undef
29
29
  export declare function setRelayToken(ref: string, token: string, scope: Scope): void;
30
30
  export declare function deleteRelayToken(ref: string, scope: Scope): void;
31
31
  export declare function getApiToken(scope: Scope): string | undefined;
32
- export declare function setApiToken(token: string, scope: Scope): void;
33
32
  export declare function listScopedApiTokens(scope: Scope): ScopedApiToken[];
34
- export declare function addScopedApiToken(entry: ScopedApiToken, scope: Scope): void;
35
33
  /** The `crtr_app_` token minted for an installed plugin, if it holds one. */
36
34
  export declare function pluginAppToken(plugin: string): ScopedApiToken | undefined;
37
35
  /** Mint the plugin's `crtr_app_` token when absent; rewrite its `scopes` in place (same token) when they
38
36
  * differ; otherwise write nothing. */
39
37
  export declare function ensurePluginAppToken(plugin: string, scopes: readonly string[]): ScopedApiToken;
40
- /** Remove the plugin's `crtr_app_` tokens. Entries minted by `crtr sys connect` are never touched. */
38
+ /** Remove the plugin's `crtr_app_` tokens. Other entries are never touched. */
41
39
  export declare function revokePluginAppTokens(plugin: string): boolean;
42
40
  /** Look a raw scoped bearer up in the user store. Cached; the cache is dropped by every in-process
43
41
  * `writeSecrets` and re-read when the file's (inode, size, mtime) changes, so a revocation by any
@@ -1 +1 @@
1
- var h=Object.defineProperty;var o=(e,n)=>h(e,"name",{value:n,configurable:!0});import{createHash as E,randomBytes as R}from"node:crypto";import{existsSync as $,readFileSync as _,statSync as b}from"node:fs";import{join as w}from"node:path";import{scopeRoot as y,requireScopeRoot as P,userScopeRoot as g}from"./scope.js";import{secretsDir as A}from"./layout.js";import{atomicWriteJson as z,ensureDir as F}from"./fs-utils.js";const N="secrets.json";function T(e){return w(e===g()?A():e,N)}o(T,"secretsPathFor");function p(e){const n=y(e);if(!n)return{relayTokens:{}};const t=T(n);if(!$(t))return{relayTokens:{}};try{const r=JSON.parse(_(t,"utf8")),i=Array.isArray(r.scopedApiTokens)?r.scopedApiTokens.filter(s=>typeof s?.token=="string"&&s.token!==""&&typeof s.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(s.grantee)&&Array.isArray(s.scopes)&&typeof s.created=="string"):[];return{relayTokens:r.relayTokens??{},...typeof r.apiToken=="string"&&r.apiToken!==""?{apiToken:r.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}o(p,"readSecrets");function a(e,n){const t=P(e),r=T(t);F(t===g()?A():t),z(r,n,{mode:384,durable:!0}),u=void 0}o(a,"writeSecrets");function L(e,n){return p(n).relayTokens[e]}o(L,"getRelayToken");function W(e,n,t){const r=p(t);r.relayTokens[e]=n,a(t,r)}o(W,"setRelayToken");function q(e,n){const t=p(n);delete t.relayTokens[e],a(n,t)}o(q,"deleteRelayToken");function B(e){return p(e).apiToken}o(B,"getApiToken");function C(e,n){const t=p(n);t.apiToken=e,a(n,t)}o(C,"setApiToken");function m(e){return p(e).scopedApiTokens??[]}o(m,"listScopedApiTokens");function H(e,n){const t=p(n);t.scopedApiTokens=[...t.scopedApiTokens??[],e],a(n,t)}o(H,"addScopedApiToken");const O=/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/,x="crtr_app_";function l(e){const n=`app:${e}`;if(!O.test(n))throw new Error(`invalid plugin name for an app token: ${JSON.stringify(e)}`);return n}o(l,"appGrantee");const d=o(e=>e.token.startsWith(x),"isAppEntry");function M(e){const n=l(e);return m("user").find(t=>t.grantee===n&&d(t))}o(M,"pluginAppToken");function X(e,n){const t=l(e),r=p("user"),i=r.scopedApiTokens??[],s=i.find(c=>c.grantee===t&&d(c)),k=[...n];if(s&&s.scopes.length===k.length&&s.scopes.every((c,S)=>c===k[S]))return s;const f=s?{...s,scopes:k}:{token:`${x}${R(32).toString("base64url")}`,grantee:t,scopes:k,created:new Date().toISOString()};return r.scopedApiTokens=s?i.map(c=>c===s?f:c):[...i,f],a("user",r),f}o(X,"ensurePluginAppToken");function Q(e){const n=l(e),t=p("user"),r=t.scopedApiTokens??[],i=r.filter(s=>!(s.grantee===n&&d(s)));return i.length===r.length?!1:(i.length>0?t.scopedApiTokens=i:delete t.scopedApiTokens,a("user",t),!0)}o(Q,"revokePluginAppTokens");let u;function Z(){const e=y("user");if(!e)return"none";try{const n=b(T(e),{bigint:!0});return`${n.ino}:${n.size}:${n.mtimeNs}`}catch{return"absent"}}o(Z,"secretsFileKey");function U(e){const n=Z();return(!u||u.key!==n)&&(u={key:n,byToken:new Map(m("user").map(t=>[t.token,t]))}),u.byToken.get(e)}o(U,"findScopedApiToken");function V(e){return E("sha256").update(e).digest("hex").slice(0,12)}o(V,"fingerprint");export{H as addScopedApiToken,q as deleteRelayToken,X as ensurePluginAppToken,U as findScopedApiToken,V as fingerprint,B as getApiToken,L as getRelayToken,m as listScopedApiTokens,M as pluginAppToken,p as readSecrets,Q as revokePluginAppTokens,C as setApiToken,W as setRelayToken,a as writeSecrets};
1
+ var h=Object.defineProperty;var s=(e,n)=>h(e,"name",{value:n,configurable:!0});import{createHash as E,randomBytes as R}from"node:crypto";import{existsSync as $,readFileSync as _,statSync as b}from"node:fs";import{join as w}from"node:path";import{scopeRoot as d,requireScopeRoot as P,userScopeRoot as g}from"./scope.js";import{secretsDir as A}from"./layout.js";import{atomicWriteJson as z,ensureDir as F}from"./fs-utils.js";const N="secrets.json";function l(e){return w(e===g()?A():e,N)}s(l,"secretsPathFor");function c(e){const n=d(e);if(!n)return{relayTokens:{}};const t=l(n);if(!$(t))return{relayTokens:{}};try{const o=JSON.parse(_(t,"utf8")),i=Array.isArray(o.scopedApiTokens)?o.scopedApiTokens.filter(r=>typeof r?.token=="string"&&r.token!==""&&typeof r.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r.grantee)&&Array.isArray(r.scopes)&&typeof r.created=="string"):[];return{relayTokens:o.relayTokens??{},...typeof o.apiToken=="string"&&o.apiToken!==""?{apiToken:o.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}s(c,"readSecrets");function f(e,n){const t=P(e),o=l(t);F(t===g()?A():t),z(o,n,{mode:384,durable:!0}),a=void 0}s(f,"writeSecrets");function L(e,n){return c(n).relayTokens[e]}s(L,"getRelayToken");function W(e,n,t){const o=c(t);o.relayTokens[e]=n,f(t,o)}s(W,"setRelayToken");function q(e,n){const t=c(n);delete t.relayTokens[e],f(n,t)}s(q,"deleteRelayToken");function B(e){return c(e).apiToken}s(B,"getApiToken");function m(e){return c(e).scopedApiTokens??[]}s(m,"listScopedApiTokens");const O=/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/,x="crtr_app_";function T(e){const n=`app:${e}`;if(!O.test(n))throw new Error(`invalid plugin name for an app token: ${JSON.stringify(e)}`);return n}s(T,"appGrantee");const y=s(e=>e.token.startsWith(x),"isAppEntry");function C(e){const n=T(e);return m("user").find(t=>t.grantee===n&&y(t))}s(C,"pluginAppToken");function H(e,n){const t=T(e),o=c("user"),i=o.scopedApiTokens??[],r=i.find(p=>p.grantee===t&&y(p)),u=[...n];if(r&&r.scopes.length===u.length&&r.scopes.every((p,S)=>p===u[S]))return r;const k=r?{...r,scopes:u}:{token:`${x}${R(32).toString("base64url")}`,grantee:t,scopes:u,created:new Date().toISOString()};return o.scopedApiTokens=r?i.map(p=>p===r?k:p):[...i,k],f("user",o),k}s(H,"ensurePluginAppToken");function M(e){const n=T(e),t=c("user"),o=t.scopedApiTokens??[],i=o.filter(r=>!(r.grantee===n&&y(r)));return i.length===o.length?!1:(i.length>0?t.scopedApiTokens=i:delete t.scopedApiTokens,f("user",t),!0)}s(M,"revokePluginAppTokens");let a;function Z(){const e=d("user");if(!e)return"none";try{const n=b(l(e),{bigint:!0});return`${n.ino}:${n.size}:${n.mtimeNs}`}catch{return"absent"}}s(Z,"secretsFileKey");function X(e){const n=Z();return(!a||a.key!==n)&&(a={key:n,byToken:new Map(m("user").map(t=>[t.token,t]))}),a.byToken.get(e)}s(X,"findScopedApiToken");function Q(e){return E("sha256").update(e).digest("hex").slice(0,12)}s(Q,"fingerprint");export{q as deleteRelayToken,H as ensurePluginAppToken,X as findScopedApiToken,Q as fingerprint,B as getApiToken,L as getRelayToken,m as listScopedApiTokens,C as pluginAppToken,c as readSecrets,M as revokePluginAppTokens,W as setRelayToken,f as writeSecrets};
@@ -1,2 +1,2 @@
1
- var f=Object.defineProperty;var s=(o,r)=>f(o,"name",{value:r,configurable:!0});import{chownSync as a,chmodSync as d,existsSync as l,mkdirSync as c,readFileSync as m,statSync as h}from"node:fs";import{appSpace as g,appsRoot as w,userFilesRoot as y}from"../layout.js";import{launcherRequest as S}from"../../launcher/client.js";import{LAUNCHER_SOCKET as x}from"../../launcher/spec.js";import{allocateAppUser as E,uidForApp as v}from"./users.js";import{isCloudRole as $}from"../canvas/person-state.js";function p(){const o=m("/etc/group","utf8").split(`
2
- `).find(e=>e.startsWith("crtr-data:"));if(!o)throw new Error("crtr-data group is required on sandboxed Linux");const r=Number(o.split(":")[2]);if(!Number.isInteger(r))throw new Error("invalid crtr-data group id");return r}s(p,"dataGroup");function N(){const o=y(),r=p();c(o,{recursive:!0,mode:1528});const e=h(o),t=e.mode&4095;if(!e.isDirectory()||e.gid!==r||t!==1528){if(!e.isDirectory()||e.uid!==process.getuid())throw new Error(`${o} has owner ${e.uid}, group ${e.gid}, mode ${t.toString(8).padStart(4,"0")}; requires an crtr-data (${r}) directory with mode 2770; only its owner can repair it`);e.gid!==r&&a(o,e.uid,r),t!==1528&&d(o,1528)}}s(N,"ensureUserFiles");async function U(o){const r=g(o);if($())return{uid:process.getuid(),gid:process.getgid(),root:r.root};if(!(process.platform==="linux"&&l(x))){if(process.platform==="linux")throw new Error("app space requires the root launcher on Linux");for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0});return{uid:await v(o),gid:process.getgid(),root:r.root}}const t=p(),n=await E(o),u=await S({operation:"user.create",app:r.root.slice(w().length+1),uid:n.uid});if(!("uid"in u)||u.uid!==n.uid)throw new Error(`launcher did not create OS user for ${o}`);for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0,mode:1528}),a(i,process.getuid(),t),d(i,1528);return{uid:n.uid,gid:t,root:r.root}}s(U,"ensureAppSpace");export{U as ensureAppSpace,N as ensureUserFiles};
1
+ var f=Object.defineProperty;var s=(o,r)=>f(o,"name",{value:r,configurable:!0});import{chownSync as a,chmodSync as d,existsSync as l,mkdirSync as c,readFileSync as m,statSync as g}from"node:fs";import{appSpace as h,appsRoot as w,userFilesRoot as y}from"../layout.js";import{launcherRequest as S}from"../../launcher/client.js";import{LAUNCHER_SOCKET as x}from"../../launcher/spec.js";import{allocateAppUser as E,uidForApp as v}from"./users.js";import{areEnginesInProcess as $,isCloudRole as R}from"../canvas/person-state.js";function p(){const o=m("/etc/group","utf8").split(`
2
+ `).find(e=>e.startsWith("crtr-data:"));if(!o)throw new Error("crtr-data group is required on sandboxed Linux");const r=Number(o.split(":")[2]);if(!Number.isInteger(r))throw new Error("invalid crtr-data group id");return r}s(p,"dataGroup");function U(){const o=y(),r=p();c(o,{recursive:!0,mode:1528});const e=g(o),t=e.mode&4095;if(!e.isDirectory()||e.gid!==r||t!==1528){if(!e.isDirectory()||e.uid!==process.getuid())throw new Error(`${o} has owner ${e.uid}, group ${e.gid}, mode ${t.toString(8).padStart(4,"0")}; requires an crtr-data (${r}) directory with mode 2770; only its owner can repair it`);e.gid!==r&&a(o,e.uid,r),t!==1528&&d(o,1528)}}s(U,"ensureUserFiles");async function D(o){const r=h(o);if(R()&&!$())return{uid:process.getuid(),gid:process.getgid(),root:r.root};if(!(process.platform==="linux"&&l(x))){if(process.platform==="linux")throw new Error("app space requires the root launcher on Linux");for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0});return{uid:await v(o),gid:process.getgid(),root:r.root}}const t=p(),n=await E(o),u=await S({operation:"user.create",app:r.root.slice(w().length+1),uid:n.uid});if(!("uid"in u)||u.uid!==n.uid)throw new Error(`launcher did not create OS user for ${o}`);for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0,mode:1528}),a(i,process.getuid(),t),d(i,1528);return{uid:n.uid,gid:t,root:r.root}}s(D,"ensureAppSpace");export{D as ensureAppSpace,U as ensureUserFiles};
@@ -1 +1 @@
1
- var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});import{MOUSE_MODE_DEFAULTS as u,VERBOSITY_LEVELS as a,WHIP_MESSAGE_MODES as p}from"../types.js";const w={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};function v(e){const t=a.indexOf(e);return`less ${a.map((n,s)=>s===t?"\u25CF":"\u25CB").map((n,s)=>s===0?n:`${s<=t?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${n}`).join("")} more ${w[e]}`}r(v,"verbositySpectrum");function d(e,t,o){const n=e.indexOf(t),s=n>=0?n:0;return e[(s+o+e.length)%e.length]}r(d,"cycleChoice");function c(e,t,o){const n=e.indexOf(t);return n>=0?e[(n+o+e.length)%e.length]:o>=0?e.find(s=>s>t)??e[0]:[...e].reverse().find(s=>s<t)??e[e.length-1]}r(c,"cycleNumber");function i(e,t){return e==="true"?!0:e==="false"?!1:`${t} must be true or false`}r(i,"booleanFromString");function f(e,t){if(!/^\d+$/.test(e))return`${t} must be an integer >= 0`;const o=Number(e);return Number.isSafeInteger(o)?o:`${t} must be an integer >= 0`}r(f,"nonNegativeIntegerFromString");function b(e,t){const o=f(e,t);return typeof o=="string"||o<1?`${t} must be an integer >= 1`:o}r(b,"positiveIntegerFromString");const m=[!1,"notify","apply"],x=[0,1,6,12,24,48,72,168],S=[1,2,3,4,5,6,8,10,12],l="openai-codex";function _(e,t){const o=e.providerOptions[t];if(o!==void 0)return o;const n={};return e.providerOptions[t]=n,n}r(_,"providerOptionsFor");const g={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:r(e=>e.auto_update.crtr===!1?"off":e.auto_update.crtr,"format"),cycle:r((e,t)=>{e.auto_update.crtr=d(m,e.auto_update.crtr,t)},"cycle"),setFromString:r((e,t)=>{const o=t==="true"?"notify":t;return o!=="notify"&&o!=="apply"&&o!=="false"?"auto_update.crtr must be notify, apply, or false":(e.auto_update.crtr=o==="false"?!1:o,null)},"setFromString")},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:r(e=>e.auto_update.content===!1?"off":e.auto_update.content,"format"),cycle:r((e,t)=>{e.auto_update.content=d(m,e.auto_update.content,t)},"cycle"),setFromString:r((e,t)=>t!=="notify"&&t!=="apply"&&t!=="false"?"auto_update.content must be notify, apply, or false":(e.auto_update.content=t==="false"?!1:t,null),"setFromString")},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:r(e=>`${e.auto_update.interval_hours}h`,"format"),cycle:r((e,t)=>{e.auto_update.interval_hours=c(x,e.auto_update.interval_hours,t)},"cycle"),setFromString:r((e,t)=>{const o=f(t,"auto_update.interval_hours");return typeof o=="string"?o:(e.auto_update.interval_hours=o,null)},"setFromString")}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:r(e=>String(e.max_panes_per_window),"format"),cycle:r((e,t)=>{e.max_panes_per_window=c(S,e.max_panes_per_window,t)},"cycle"),setFromString:r((e,t)=>{const o=b(t,"max_panes_per_window");return typeof o=="string"?o:(e.max_panes_per_window=o,null)},"setFromString")}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:r(e=>e.auto_open_child_viewers?"on":"off","format"),cycle:r(e=>{e.auto_open_child_viewers=!e.auto_open_child_viewers},"cycle"),setFromString:r((e,t)=>{const o=i(t,"auto_open_child_viewers");return typeof o=="string"?o:(e.auto_open_child_viewers=o,null)},"setFromString")}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:r(e=>e.completion_bell?"on":"off","format"),cycle:r(e=>{e.completion_bell=!e.completion_bell},"cycle"),setFromString:r((e,t)=>{const o=i(t,"completion_bell");return typeof o=="string"?o:(e.completion_bell=o,null)},"setFromString")}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:r(e=>e.whip_mode?"on":"off","format"),cycle:r(e=>{e.whip_mode=!e.whip_mode},"cycle"),setFromString:r((e,t)=>{const o=i(t,"whip_mode");return typeof o=="string"?o:(e.whip_mode=o,null)},"setFromString")}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:r(e=>e.page_surface?"on":"off","format"),cycle:r(e=>{e.page_surface=!e.page_surface},"cycle"),setFromString:r((e,t)=>{const o=i(t,"page_surface");return typeof o=="string"?o:(e.page_surface=o,null)},"setFromString")}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:p.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:r(e=>e.whip_message_mode==="go-faster"?"go faster":"random","format"),cycle:r((e,t)=>{e.whip_message_mode=d(p,e.whip_message_mode,t)},"cycle"),setFromString:r((e,t)=>p.includes(t)?(e.whip_message_mode=t,null):`whip_message_mode must be one of: ${p.join("|")}`,"setFromString")}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:u.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:r(e=>e.mouse_mode_default==="tmux"?"follow tmux":e.mouse_mode_default,"format"),cycle:r((e,t)=>{e.mouse_mode_default=d(u,e.mouse_mode_default,t)},"cycle"),setFromString:r((e,t)=>u.includes(t)?(e.mouse_mode_default=t,null):`mouse_mode_default must be one of: ${u.join("|")}`,"setFromString")}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:r(e=>e.bash_tool_purpose?"on":"off","format"),cycle:r(e=>{e.bash_tool_purpose=!e.bash_tool_purpose},"cycle"),setFromString:r((e,t)=>{const o=i(t,"bash_tool_purpose");return typeof o=="string"?o:(e.bash_tool_purpose=o,null)},"setFromString")}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:a.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:r(e=>e.verbosity,"format"),display:r(e=>v(e.verbosity),"display"),cycle:r((e,t)=>{const o=a.indexOf(e.verbosity)+t;e.verbosity=a[Math.max(0,Math.min(a.length-1,o))]},"cycle"),setFromString:r((e,t)=>a.includes(t)?(e.verbosity=t,null):`verbosity must be one of: ${a.join("|")}`,"setFromString")}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:r(e=>String(e.document_port),"format"),cycle:r((e,t)=>{e.document_port=Math.max(1,Math.min(65535,e.document_port+t))},"cycle"),setFromString:r((e,t)=>{const o=Number(t);return!/^\d+$/.test(t)||!Number.isInteger(o)||o<1||o>65535?"document_port must be an integer from 1 to 65535":(e.document_port=o,null)},"setFromString")}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:r(e=>e.detailed_tool_recaps?"on":"off","format"),cycle:r(e=>{e.detailed_tool_recaps=!e.detailed_tool_recaps},"cycle"),setFromString:r((e,t)=>{const o=i(t,"detailed_tool_recaps");return typeof o=="string"?o:(e.detailed_tool_recaps=o,null)},"setFromString")}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${l}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:r(e=>e.providerOptions[l]?.fastMode?"on":"off","format"),cycle:r(e=>{const t=_(e,l);t.fastMode=!t.fastMode},"cycle"),setFromString:r((e,t)=>{const o=i(t,`providerOptions.${l}.fastMode`);return typeof o=="string"?o:(_(e,l).fastMode=o,null)},"setFromString")}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},C=Object.keys(g);function k(){const e=[];for(const t of Object.values(g))t.surface==="settings"&&("setting"in t?e.push(t.setting):e.push(...Object.values(t.settings)));return e.sort((t,o)=>t.order-o.order)}r(k,"collectUserSettings");const h=k();function E(e){return h.find(t=>t.key===e)}r(E,"findUserSetting");function M(e){return h.filter(t=>t.group===e)}r(M,"userSettingsInGroup");export{g as CONFIG_SETTINGS_COVERAGE,C as SCOPE_CONFIG_KEYS,h as USER_SETTINGS,w as VERBOSITY_LABELS,E as findUserSetting,M as userSettingsInGroup,v as verbositySpectrum};
1
+ var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});import{MOUSE_MODE_DEFAULTS as u,VERBOSITY_LEVELS as a,WHIP_MESSAGE_MODES as p}from"../types.js";const w={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};function v(e){const t=a.indexOf(e);return`less ${a.map((n,s)=>s===t?"\u25CF":"\u25CB").map((n,s)=>s===0?n:`${s<=t?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${n}`).join("")} more ${w[e]}`}r(v,"verbositySpectrum");function d(e,t,o){const n=e.indexOf(t),s=n>=0?n:0;return e[(s+o+e.length)%e.length]}r(d,"cycleChoice");function c(e,t,o){const n=e.indexOf(t);return n>=0?e[(n+o+e.length)%e.length]:o>=0?e.find(s=>s>t)??e[0]:[...e].reverse().find(s=>s<t)??e[e.length-1]}r(c,"cycleNumber");function i(e,t){return e==="true"?!0:e==="false"?!1:`${t} must be true or false`}r(i,"booleanFromString");function f(e,t){if(!/^\d+$/.test(e))return`${t} must be an integer >= 0`;const o=Number(e);return Number.isSafeInteger(o)?o:`${t} must be an integer >= 0`}r(f,"nonNegativeIntegerFromString");function b(e,t){const o=f(e,t);return typeof o=="string"||o<1?`${t} must be an integer >= 1`:o}r(b,"positiveIntegerFromString");const m=[!1,"notify","apply"],x=[0,1,6,12,24,48,72,168],S=[1,2,3,4,5,6,8,10,12],l="openai-codex";function _(e,t){const o=e.providerOptions[t];if(o!==void 0)return o;const n={};return e.providerOptions[t]=n,n}r(_,"providerOptionsFor");const g={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:r(e=>e.auto_update.crtr===!1?"off":e.auto_update.crtr,"format"),cycle:r((e,t)=>{e.auto_update.crtr=d(m,e.auto_update.crtr,t)},"cycle"),setFromString:r((e,t)=>{const o=t==="true"?"notify":t;return o!=="notify"&&o!=="apply"&&o!=="false"?"auto_update.crtr must be notify, apply, or false":(e.auto_update.crtr=o==="false"?!1:o,null)},"setFromString")},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:r(e=>e.auto_update.content===!1?"off":e.auto_update.content,"format"),cycle:r((e,t)=>{e.auto_update.content=d(m,e.auto_update.content,t)},"cycle"),setFromString:r((e,t)=>t!=="notify"&&t!=="apply"&&t!=="false"?"auto_update.content must be notify, apply, or false":(e.auto_update.content=t==="false"?!1:t,null),"setFromString")},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:r(e=>`${e.auto_update.interval_hours}h`,"format"),cycle:r((e,t)=>{e.auto_update.interval_hours=c(x,e.auto_update.interval_hours,t)},"cycle"),setFromString:r((e,t)=>{const o=f(t,"auto_update.interval_hours");return typeof o=="string"?o:(e.auto_update.interval_hours=o,null)},"setFromString")}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:r(e=>String(e.max_panes_per_window),"format"),cycle:r((e,t)=>{e.max_panes_per_window=c(S,e.max_panes_per_window,t)},"cycle"),setFromString:r((e,t)=>{const o=b(t,"max_panes_per_window");return typeof o=="string"?o:(e.max_panes_per_window=o,null)},"setFromString")}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:r(e=>e.auto_open_child_viewers?"on":"off","format"),cycle:r(e=>{e.auto_open_child_viewers=!e.auto_open_child_viewers},"cycle"),setFromString:r((e,t)=>{const o=i(t,"auto_open_child_viewers");return typeof o=="string"?o:(e.auto_open_child_viewers=o,null)},"setFromString")}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:r(e=>e.completion_bell?"on":"off","format"),cycle:r(e=>{e.completion_bell=!e.completion_bell},"cycle"),setFromString:r((e,t)=>{const o=i(t,"completion_bell");return typeof o=="string"?o:(e.completion_bell=o,null)},"setFromString")}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:r(e=>e.whip_mode?"on":"off","format"),cycle:r(e=>{e.whip_mode=!e.whip_mode},"cycle"),setFromString:r((e,t)=>{const o=i(t,"whip_mode");return typeof o=="string"?o:(e.whip_mode=o,null)},"setFromString")}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:r(e=>e.page_surface?"on":"off","format"),cycle:r(e=>{e.page_surface=!e.page_surface},"cycle"),setFromString:r((e,t)=>{const o=i(t,"page_surface");return typeof o=="string"?o:(e.page_surface=o,null)},"setFromString")}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:p.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:r(e=>e.whip_message_mode==="go-faster"?"go faster":"random","format"),cycle:r((e,t)=>{e.whip_message_mode=d(p,e.whip_message_mode,t)},"cycle"),setFromString:r((e,t)=>p.includes(t)?(e.whip_message_mode=t,null):`whip_message_mode must be one of: ${p.join("|")}`,"setFromString")}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:u.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:r(e=>e.mouse_mode_default==="tmux"?"follow tmux":e.mouse_mode_default,"format"),cycle:r((e,t)=>{e.mouse_mode_default=d(u,e.mouse_mode_default,t)},"cycle"),setFromString:r((e,t)=>u.includes(t)?(e.mouse_mode_default=t,null):`mouse_mode_default must be one of: ${u.join("|")}`,"setFromString")}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:r(e=>e.bash_tool_purpose?"on":"off","format"),cycle:r(e=>{e.bash_tool_purpose=!e.bash_tool_purpose},"cycle"),setFromString:r((e,t)=>{const o=i(t,"bash_tool_purpose");return typeof o=="string"?o:(e.bash_tool_purpose=o,null)},"setFromString")}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:a.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:r(e=>e.verbosity,"format"),display:r(e=>v(e.verbosity),"display"),cycle:r((e,t)=>{const o=a.indexOf(e.verbosity)+t;e.verbosity=a[Math.max(0,Math.min(a.length-1,o))]},"cycle"),setFromString:r((e,t)=>a.includes(t)?(e.verbosity=t,null):`verbosity must be one of: ${a.join("|")}`,"setFromString")}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:r(e=>String(e.document_port),"format"),cycle:r((e,t)=>{e.document_port=Math.max(1,Math.min(65535,e.document_port+t))},"cycle"),setFromString:r((e,t)=>{const o=Number(t);return!/^\d+$/.test(t)||!Number.isInteger(o)||o<1||o>65535?"document_port must be an integer from 1 to 65535":(e.document_port=o,null)},"setFromString")}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:r(e=>e.detailed_tool_recaps?"on":"off","format"),cycle:r(e=>{e.detailed_tool_recaps=!e.detailed_tool_recaps},"cycle"),setFromString:r((e,t)=>{const o=i(t,"detailed_tool_recaps");return typeof o=="string"?o:(e.detailed_tool_recaps=o,null)},"setFromString")}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${l}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:r(e=>e.providerOptions[l]?.fastMode?"on":"off","format"),cycle:r(e=>{const t=_(e,l);t.fastMode=!t.fastMode},"cycle"),setFromString:r((e,t)=>{const o=i(t,`providerOptions.${l}.fastMode`);return typeof o=="string"?o:(_(e,l).fastMode=o,null)},"setFromString")}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"daemon API listener"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},C=Object.keys(g);function k(){const e=[];for(const t of Object.values(g))t.surface==="settings"&&("setting"in t?e.push(t.setting):e.push(...Object.values(t.settings)));return e.sort((t,o)=>t.order-o.order)}r(k,"collectUserSettings");const h=k();function E(e){return h.find(t=>t.key===e)}r(E,"findUserSetting");function M(e){return h.filter(t=>t.group===e)}r(M,"userSettingsInGroup");export{g as CONFIG_SETTINGS_COVERAGE,C as SCOPE_CONFIG_KEYS,h as USER_SETTINGS,w as VERBOSITY_LABELS,E as findUserSetting,M as userSettingsInGroup,v as verbositySpectrum};
@@ -1,5 +1,5 @@
1
1
  import type { StartBundleRecipeDTO } from '../../api/index.js';
2
- /** The environment object id a node runs in: its profile's `environment_id`, or the machine environment when it has none. */
2
+ /** The environment object id a node runs in: its profile's `environment_id`. A node whose profile names none is a defect: the environment is set when the profile is made. */
3
3
  export declare function environmentOfNode(profileId: string | null): Promise<string>;
4
4
  /** SQL predicate over `environments`: the recipe has content (a repository, a setup script or pi packages). A recipe cleared back to nothing
5
5
  * has none, whatever its `recipe_revision` counter says: the counter only orders edits, it does not say whether a recipe exists. */
@@ -1,5 +1,5 @@
1
- var m=Object.defineProperty;var o=(n,e)=>m(n,"name",{value:e,configurable:!0});import{ApiError as l}from"../../api/errors.js";import{openDb as i}from"../../core/canvas/db.js";import{machineEnvironmentId as u}from"../../core/environments.js";async function c(n){return n===null?u():(await(await i()).prepare("SELECT environment_id FROM profiles WHERE id = ?").get(n))?.environment_id??u()}o(c,"environmentOfNode");const _=`(btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''
2
- OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object))`,f="northlight-systems/";async function O(n){const e=process.env.CRTR_PACKAGES_TOKEN;if(e===void 0||e==="")return null;const r=await(await i()).prepare("SELECT github_full_name FROM environment_repos WHERE environment = ?").all(n);return r.length>0&&r.every(t=>t.github_full_name.toLowerCase().startsWith(f))?e:null}o(O,"packagesTokenFor");async function E(n){const e=await(await i()).prepare(`SELECT recipe_revision, setup_script, pi_packages, ${_} AS has_content,
1
+ var E=Object.defineProperty;var o=(n,e)=>E(n,"name",{value:e,configurable:!0});import{ApiError as l}from"../../api/errors.js";import{openDb as i}from"../../core/canvas/db.js";async function u(n){if(n===null)throw new Error("a node with no profile has no environment");const e=await(await i()).prepare("SELECT environment_id FROM profiles WHERE id = ?").get(n);if(e?.environment_id==null)throw new Error(`profile ${n} has no environment`);return e.environment_id}o(u,"environmentOfNode");const m=`(btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''
2
+ OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object))`,_="northlight-systems/";async function b(n){const e=process.env.CRTR_PACKAGES_TOKEN;if(e===void 0||e==="")return null;const r=await(await i()).prepare("SELECT github_full_name FROM environment_repos WHERE environment = ?").all(n);return r.length>0&&r.every(t=>t.github_full_name.toLowerCase().startsWith(_))?e:null}o(b,"packagesTokenFor");async function c(n){const e=await(await i()).prepare(`SELECT recipe_revision, setup_script, pi_packages, ${m} AS has_content,
3
3
  (SELECT COALESCE(json_agg(json_build_object('name', r.name, 'github_full_name', r.github_full_name, 'default_branch', r.default_branch) ORDER BY r.position), '[]'::json)
4
4
  FROM environment_repos r WHERE r.environment = environments.object) AS repositories
5
- FROM environments WHERE object = ?`).get(n);return e===void 0||!e.has_content?null:{revision:Number(e.recipe_revision),repositories:JSON.parse(e.repositories),setup_script:e.setup_script,pi_packages:e.pi_packages}}o(E,"recipeOf");async function R(n){return(await(await i()).prepare("SELECT kind FROM environments WHERE object = ?").get(await c(n)))?.kind==="blaxel"}o(R,"runsOnBlaxel");async function h(n,e,r,t){const a=((await E(await c(n)))?.repositories??[]).find(p=>e===`/work/${p.name}`||e.startsWith(`/work/${p.name}/`));if(a===void 0)throw new l(400,"invalid_request",`--worktree needs a cwd inside one of the environment's repositories under /work, not ${e}`,{param:"worktree"});return{repository:a.name,branch:`crtr/${r}`,base:t??a.default_branch}}o(h,"sandboxWorktreeRequest");async function k(n,e){if(n===null)return null;const r=await(await i()).prepare("SELECT e.object, e.kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(n);if(r?.kind!=="blaxel")return null;const t=(await E(r.object))?.repositories??[];return t.length===0?null:t.some(s=>e===`/work/${s.name}`||e.startsWith(`/work/${s.name}/`))?e:`/work/${t[0].name}`}o(k,"devEnvironmentCwd");export{_ as RECIPE_HAS_CONTENT_SQL,k as devEnvironmentCwd,c as environmentOfNode,O as packagesTokenFor,E as recipeOf,R as runsOnBlaxel,h as sandboxWorktreeRequest};
5
+ FROM environments WHERE object = ?`).get(n);return e===void 0||!e.has_content?null:{revision:Number(e.recipe_revision),repositories:JSON.parse(e.repositories),setup_script:e.setup_script,pi_packages:e.pi_packages}}o(c,"recipeOf");async function h(n){return n===null?!1:(await(await i()).prepare("SELECT kind FROM environments WHERE object = ?").get(await u(n)))?.kind==="blaxel"}o(h,"runsOnBlaxel");async function d(n,e,r,t){const a=((await c(await u(n)))?.repositories??[]).find(p=>e===`/work/${p.name}`||e.startsWith(`/work/${p.name}/`));if(a===void 0)throw new l(400,"invalid_request",`--worktree needs a cwd inside one of the environment's repositories under /work, not ${e}`,{param:"worktree"});return{repository:a.name,branch:`crtr/${r}`,base:t??a.default_branch}}o(d,"sandboxWorktreeRequest");async function O(n,e){if(n===null)return null;const r=await(await i()).prepare("SELECT e.object, e.kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(n);if(r?.kind!=="blaxel")return null;const t=(await c(r.object))?.repositories??[];return t.length===0?null:t.some(s=>e===`/work/${s.name}`||e.startsWith(`/work/${s.name}/`))?e:`/work/${t[0].name}`}o(O,"devEnvironmentCwd");export{m as RECIPE_HAS_CONTENT_SQL,O as devEnvironmentCwd,u as environmentOfNode,b as packagesTokenFor,c as recipeOf,h as runsOnBlaxel,d as sandboxWorktreeRequest};
@@ -1 +1 @@
1
- var n=Object.defineProperty;var o=(e,t)=>n(e,"name",{value:t,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{isCloudRole as s}from"../../../core/canvas/person.js";import{canvasOrigin as i}from"../canvas-host.js";import{documentListenerUnavailable as a}from"../document-listener.js";import{documentSecret as u}from"../document-secret.js";const v=[{method:"GET",pattern:"/v1/documents/browser-access",handler:o(()=>{if(s()){const t=i();if(t===void 0)throw new r(503,"document_listener_unavailable","this API serves no document page (CRTR_CANVAS_URL is unset)");return{status:200,body:{canvas_url:t}}}const e=a();if(e!==void 0)throw new r(503,"document_listener_unavailable",e);return{status:200,body:{secret:u()}}},"handler")}];export{v as documentAccessRoutes};
1
+ var t=Object.defineProperty;var n=(e,r)=>t(e,"name",{value:r,configurable:!0});import{ApiError as o}from"../../../api/errors.js";import{canvasOrigin as s}from"../canvas-host.js";const u=[{method:"GET",pattern:"/v1/documents/browser-access",handler:n(()=>{const e=s();if(e===void 0)throw new o(503,"document_listener_unavailable","this API serves no document page (CRTR_CANVAS_URL is unset)");return{status:200,body:{canvas_url:e}}},"handler")}];export{u as documentAccessRoutes};