@north-light/cli 0.3.672 → 0.3.674

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 (52) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/execution-start.d.ts +1 -1
  4. package/dist/api/dto/nodes.d.ts +2 -0
  5. package/dist/core/pool-credential-store.d.ts +4 -0
  6. package/dist/core/pool-credential-store.js +1 -1
  7. package/dist/core/runtime/provider-credential-gate.d.ts +2 -2
  8. package/dist/core/runtime/provider-credential-gate.js +2 -2
  9. package/dist/core/runtime/runner/machine/call.d.ts +5 -0
  10. package/dist/core/runtime/runner/machine/call.js +2 -2
  11. package/dist/core/runtime/runner/machine/ops.d.ts +2 -1
  12. package/dist/core/runtime/spawn.d.ts +2 -0
  13. package/dist/core/runtime/spawn.js +2 -2
  14. package/dist/core/subscription-state.d.ts +2 -0
  15. package/dist/core/subscription-state.js +1 -1
  16. package/dist/core/substrate/delivery/deliver.js +3 -3
  17. package/dist/core/substrate/delivery/plan.d.ts +4 -0
  18. package/dist/core/substrate/delivery/plan.js +2 -2
  19. package/dist/daemon/api/handlers/broker-ops.d.ts +12 -1
  20. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  21. package/dist/daemon/api/handlers/execution-start.d.ts +9 -1
  22. package/dist/daemon/api/handlers/execution-start.js +2 -2
  23. package/dist/daemon/api/handlers/nodes.js +1 -1
  24. package/dist/daemon/machine-link/holder.js +4 -4
  25. package/package.json +3 -3
  26. package/packages/crouter-api/dist/api/contract.js +1 -1
  27. package/packages/crouter-api/dist/core/pool-credential-store.js +44 -25
  28. package/packages/crouter-api/dist/core/review/document.js +143 -0
  29. package/packages/crouter-api/dist/core/review/project.js +45 -0
  30. package/packages/crouter-api/dist/core/runtime/launch-recipe.js +45 -0
  31. package/packages/crouter-api/dist/core/runtime/provider-credential-gate.js +4 -4
  32. package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +96 -0
  33. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +170 -0
  34. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +11 -2
  35. package/packages/crouter-api/dist/core/runtime/spawn.js +88 -3
  36. package/packages/crouter-api/dist/core/runtime/stop-signals.js +46 -0
  37. package/packages/crouter-api/dist/core/secrets/blaxel-launch.js +104 -0
  38. package/packages/crouter-api/dist/core/subscription-state.js +18 -2
  39. package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +24 -3
  40. package/packages/crouter-api/dist/core/substrate/delivery/plan.js +2 -0
  41. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +701 -0
  42. package/packages/crouter-api/dist/daemon/api/handlers/execution-start.js +120 -0
  43. package/packages/crouter-api/dist/daemon/api/handlers/node-records.js +113 -0
  44. package/packages/crouter-api/dist/daemon/api/handlers/telemetry-record.js +34 -0
  45. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  46. package/packages/crouter-api/dist/daemon/review/companion.js +29 -0
  47. package/packages/crouter-api/dist/daemon/review/deliver.js +13 -0
  48. package/packages/crouter-api/dist/daemon/review/finish.js +170 -0
  49. package/packages/crouter-api/package.json +1 -1
  50. package/packages/crouter-identity/package.json +1 -1
  51. package/packages/crouter-plugin/package.json +3 -3
  52. package/runtime.lock.json +14 -14
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.59";
2
+ export declare const CONTRACT_LEVEL = "1.60";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.59",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.60",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -60,7 +60,7 @@ export interface StartBundleDTO {
60
60
  plugins: StartBundlePluginDTO[];
61
61
  /** Null when the node has no `import_node_files` row, or its archive was deleted (30 days after the first unpack). Named on every start while the archive exists: a sandbox unpacks it only when it holds no marker of its own. */
62
62
  import_node_files: StartBundleImportFilesDTO | null;
63
- /** Present only for an execution on a machine environment (the Mac, which holds no database): the node's profile metadata (`CRTR_PROFILE_META_*`) and the secrets of its environment (the app's rows, the owning profile's rows, the deployment rows), merged in the process runner's order. Secret values: read with the execution's node token, never carried in a link frame. */
63
+ /** Present only for an execution on a machine environment (the Mac, which holds no database): the node's profile metadata (`CRTR_PROFILE_META_*`) and the secrets of its environment (the app's rows, the owning profile's rows, the deployment rows), merged in the process runner's order. Secret values: a sandbox reads them with the execution's node token; for a machine the control plane carries them in the `start` call's link frame, where they sit in `machine_calls.args_json` only while the call is in flight (erased when the call finishes). */
64
64
  machine_env?: Record<string, string>;
65
65
  /** The start data for a broker that reads it with the bundle instead of asking `cycle-start` (cloud-hosted and local launches carry it this way). */
66
66
  start?: StartDataDTO;
@@ -49,6 +49,8 @@ export interface CreateNodeRequest {
49
49
  /** Sticky isolation; a child cannot turn off an isolated run. */
50
50
  isolated?: boolean;
51
51
  root?: boolean;
52
+ /** Launch the node in the create itself when its profile's environment is a machine reached over a link, instead of leaving it dormant for a first attach to revive. */
53
+ start?: boolean;
52
54
  /** Lifecycle of the new node. Roots default to `resident`; managed children
53
55
  * default to `terminal`. Use `resident` for a child that remains wakeable
54
56
  * without owing a final, or `terminal` for a bounded worker that must
@@ -29,3 +29,7 @@ export declare class PoolCredentialStore implements CredentialStore {
29
29
  modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>): Promise<Credential | undefined>;
30
30
  delete(providerId: string): Promise<void>;
31
31
  }
32
+ /** A read-only view of what `PoolCredentialStore` would serve, built from one read per table (model_api_keys, model_accounts,
33
+ * model_account_cooldowns) instead of one per provider. Same rules as `read`/`list`: a managed provider is its elected pool account,
34
+ * else a stored api_key (never a stored oauth record). */
35
+ export declare function snapshotCredentialStore(): Promise<CredentialStore>;
@@ -1 +1 @@
1
- var l=Object.defineProperty;var s=(i,t)=>l(i,"name",{value:t,configurable:!0});import{CrouterCredentialStore as w}from"./auth-file.js";import{MANAGED_PROVIDER_IDS as m,getProviderLabel as g,isManagedProvider as u,modifyElectedSubscription as x,readSubscriptionPool as f,removeManagedAccount as y}from"./subscription-state.js";import{registerGateCredentialStore as p}from"./runtime/provider-credential-gate.js";async function c(i,t=Date.now()){return h(await f(i),t)}s(c,"electPoolCredential");function h(i,t=Date.now()){return i.find(e=>!e.authFailure&&(!e.rateLimitedUntil||e.rateLimitedUntil<=t))??i[0]}s(h,"electFrom");function d(i){return{type:"oauth",refresh:i.refresh,access:i.access,expires:i.expires,...i.accountId?{accountId:i.accountId}:{},...i.clientId?{clientId:i.clientId}:{}}}s(d,"toCredential");class C{static{s(this,"PoolCredentialStore")}auth=new w;async read(t){if(!u(t))return this.auth.read(t);const e=await c(t);if(e!==void 0)return d(e);const a=await this.auth.read(t);return a?.type==="oauth"?void 0:a}async list(){const t=(await this.auth.list()).filter(e=>!(u(e.providerId)&&e.type==="oauth"));for(const e of m)t.some(a=>a.providerId===e)||(await f(e)).length>0&&t.push({providerId:e,type:"oauth"});return t}async modify(t,e){if(!u(t))return this.auth.modify(t,e);if(await c(t)===void 0){if(await this.read(t)!==void 0)return this.auth.modify(t,e);throw new Error(`${g(t)} has no account to update \u2014 add one with \`crtr sys settings\` or \`/provider-sub ${t} add\`.`)}const a=await x(t,r=>h(r),async r=>{const n=await e(d(r));if(n===void 0||n.type!=="oauth")return;const o=n.clientId;return{refresh:n.refresh,access:n.access,expires:n.expires,...typeof o=="string"&&o?{clientId:o}:{}}});return a===void 0?void 0:d(a)}async delete(t){if(!u(t))return this.auth.delete(t);const e=await c(t);e!==void 0&&await y(t,e.label),await this.auth.read(t)!==void 0&&await this.auth.delete(t)}}p(new C);export{C as PoolCredentialStore,c as electPoolCredential};
1
+ var y=Object.defineProperty;var s=(t,e)=>y(t,"name",{value:e,configurable:!0});import{CrouterCredentialStore as p,readAuthCredentials as g}from"./auth-file.js";import{MANAGED_PROVIDER_IDS as l,getProviderLabel as x,isManagedProvider as o,modifyElectedSubscription as C,readAllSubscriptionPools as P,readSubscriptionPool as h,removeManagedAccount as S}from"./subscription-state.js";import{registerGateCredentialStore as b}from"./runtime/provider-credential-gate.js";async function u(t,e=Date.now()){return d(await h(t),e)}s(u,"electPoolCredential");function d(t,e=Date.now()){return t.find(n=>!n.authFailure&&(!n.rateLimitedUntil||n.rateLimitedUntil<=e))??t[0]}s(d,"electFrom");function f(t){return{type:"oauth",refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}s(f,"toCredential");function w(t,e){return t!==void 0?f(t):e?.type==="oauth"?void 0:e}s(w,"servedManaged");function m(t,e){const n=t.filter(i=>!(o(i.providerId)&&i.type==="oauth"));for(const i of l)!n.some(a=>a.providerId===i)&&e(i)>0&&n.push({providerId:i,type:"oauth"});return n}s(m,"listedCredentials");class F{static{s(this,"PoolCredentialStore")}auth=new p;async read(e){if(!o(e))return this.auth.read(e);const n=await u(e);return w(n,n===void 0?await this.auth.read(e):void 0)}async list(){const e=await this.auth.list(),n=new Map;for(const i of l)e.some(a=>a.providerId===i&&a.type!=="oauth")||n.set(i,(await h(i)).length);return m(e,i=>n.get(i)??0)}async modify(e,n){if(!o(e))return this.auth.modify(e,n);if(await u(e)===void 0){if(await this.read(e)!==void 0)return this.auth.modify(e,n);throw new Error(`${x(e)} has no account to update \u2014 add one with \`crtr sys settings\` or \`/provider-sub ${e} add\`.`)}const i=await C(e,a=>d(a),async a=>{const r=await n(f(a));if(r===void 0||r.type!=="oauth")return;const c=r.clientId;return{refresh:r.refresh,access:r.access,expires:r.expires,...typeof c=="string"&&c?{clientId:c}:{}}});return i===void 0?void 0:f(i)}async delete(e){if(!o(e))return this.auth.delete(e);const n=await u(e);n!==void 0&&await S(e,n.label),await this.auth.read(e)!==void 0&&await this.auth.delete(e)}}async function A(){const[t,e]=await Promise.all([g(),P()]),n=s(a=>o(a)?w(d(e.get(a)??[]),t[a]):t[a],"read"),i=s(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:s(async a=>n(a),"read"),list:s(async()=>m(Object.entries(t).map(([a,r])=>({providerId:a,type:r.type})),a=>e.get(a)?.length??0),"list"),modify:i,delete:i}}s(A,"snapshotCredentialStore"),b(A);export{F as PoolCredentialStore,u as electPoolCredential,A as snapshotCredentialStore};
@@ -1,6 +1,6 @@
1
1
  import type { CredentialStore } from '@earendil-works/pi-ai';
2
- /** The daemon, which owns the rows, registers its row-backed store; every other process asks the daemon over /v1/model-auth. */
3
- export declare function registerGateCredentialStore(store: CredentialStore): void;
2
+ /** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
3
+ export declare function registerGateCredentialStore(snapshot: () => Promise<CredentialStore>): void;
4
4
  export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential; run `crtr sys setup` to log in.";
5
5
  /** Check the setup catalog before a path creates a broker-backed node. `profileEnvNames` are the names stored on the
6
6
  * launching profile (values are never needed: a stored value is never empty). */
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var t=(e,o)=>d(e,"name",{value:o,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as p}from"../model-auth/api-credential-store.js";import{cliClient as f}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as C}from"./spawn-env.js";let a;function D(e){a=e}t(D,"registerGateCredentialStore");function g(e){const o=new Map;let n;const i=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=o.get(r);return s===void 0&&o.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:i,delete:i}}t(g,"readOnceStore");const w="crtr: no provider credential; run `crtr sys setup` to log in.";async function M(e){const o=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(C).some(r=>(o[r]??process.env[r])?.trim()))return!0;const n=E(),i=await l.create({credentials:g(a??new p(()=>f(),!0)),modelsPath:m(n,"models.json")});return await u(i,new c(i))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${w}
2
- `),process.exit(1)}t(_,"exitForMissingProviderCredential");export{w as NO_PROVIDER_CREDENTIAL_MESSAGE,_ as exitForMissingProviderCredential,M as hasConfiguredProviderCredential,D as registerGateCredentialStore};
1
+ var d=Object.defineProperty;var t=(e,o)=>d(e,"name",{value:o,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as p}from"../model-auth/api-credential-store.js";import{cliClient as f}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as w}from"./spawn-env.js";let a;function D(e){a=e}t(D,"registerGateCredentialStore");function g(e){const o=new Map;let n;const i=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=o.get(r);return s===void 0&&o.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:i,delete:i}}t(g,"readOnceStore");const h="crtr: no provider credential; run `crtr sys setup` to log in.";async function M(e){const o=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(w).some(r=>(o[r]??process.env[r])?.trim()))return!0;const n=E(),i=await l.create({credentials:a===void 0?g(new p(()=>f(),!0)):await a(),modelsPath:m(n,"models.json")});return await u(i,new c(i))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${h}
2
+ `),process.exit(1)}t(_,"exitForMissingProviderCredential");export{h as NO_PROVIDER_CREDENTIAL_MESSAGE,_ as exitForMissingProviderCredential,M as hasConfiguredProviderCredential,D as registerGateCredentialStore};
@@ -6,4 +6,9 @@ export interface CallMachineOptions {
6
6
  timeoutMs?: number;
7
7
  rereadMs?: number;
8
8
  }
9
+ /** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
10
+ * so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
11
+ export declare function enqueueMachineCall<O extends MachineOp>(environmentId: string, op: O, args: MachineOpTable[O]['args']): Promise<string>;
9
12
  export declare function callMachine<O extends MachineOp>(environmentId: string, op: O, args: MachineOpTable[O]['args'], options?: CallMachineOptions): Promise<MachineOpTable[O]['result']>;
13
+ /** Wait for the holder's answer to a queued call. */
14
+ export declare function awaitMachineCall<O extends MachineOp>(environmentId: string, op: O, callId: string, options?: CallMachineOptions): Promise<MachineOpTable[O]['result']>;
@@ -1,3 +1,3 @@
1
- var S=Object.defineProperty;var s=(e,n)=>S(e,"name",{value:n,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as E,withCanvasWrite as N}from"../../../canvas/db.js";import{brokerSignalBus as k}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as O,MachineLostError as _,MachineOfflineError as d}from"./ops.js";const D={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"job.stop":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60,"repo.identify":15},M=1e3;async function b(e,n,t,l={}){const o=g(),c=new Date().toISOString();if(!await N(async r=>await r.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,c)===void 0?!1:(await r.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(o,e,n,JSON.stringify(t),c),await r.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new d(e,"no live link");const i=Date.now()+(l.timeoutMs??D[n]*1e3);let u,f=!1;const h=await k.subscribe(r=>{r===o&&(f=!0,u?.())},{kinds:["machine_call"]});try{return await T(e,n,o,i,l.rereadMs??M,r=>new Promise(w=>{if(f){f=!1,w();return}const p=setTimeout(()=>{u=void 0,w()},r);u=s(()=>{clearTimeout(p),u=void 0,f=!1,w()},"wake")}))}finally{h()}}s(b,"callMachine");async function T(e,n,t,l,o,c){for(;;){const a=await(await E()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(t);if(a===void 0)throw new _(e,t);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const i=a.result_json===null?{}:JSON.parse(a.result_json);throw i.code==="machine_offline"?new d(e,i.message,i.sent===!0):i.code==="machine_lost"?new _(e,t):new O(e,n,i.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await m(t,"lease expired")===void 0)continue;throw new _(e,t)}if(Date.now()>=l){const i=await m(t,"timed out");if(i===void 0)continue;throw i===null?new d(e,"no holder claimed the call"):new _(e,t)}await c(Math.min(o,Math.max(0,l-Date.now())))}}s(T,"waitForCall");async function m(e,n){const t=await(await E()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
1
+ var p=Object.defineProperty;var s=(e,n)=>p(e,"name",{value:n,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as _,withCanvasWrite as m}from"../../../canvas/db.js";import{brokerSignalBus as g}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as S,MachineLostError as c,MachineOfflineError as w}from"./ops.js";const N={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"job.stop":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60,"repo.identify":15},k=1e3;async function M(e,n,t){const r=E(),l=new Date().toISOString();if(!await m(async a=>await a.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,l)===void 0?!1:(await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(r,e,n,JSON.stringify(t),l),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new w(e,"no live link");return r}s(M,"enqueueMachineCall");async function R(e,n,t,r={}){return await O(e,n,await M(e,n,t),r)}s(R,"callMachine");async function O(e,n,t,r={}){const l=Date.now()+(r.timeoutMs??N[n]*1e3);let o,a=!1;const i=await g.subscribe(u=>{u===t&&(a=!0,o?.())},{kinds:["machine_call"]});try{return await y(e,n,t,l,r.rereadMs??k,u=>new Promise(f=>{if(a){a=!1,f();return}const h=setTimeout(()=>{o=void 0,f()},u);o=s(()=>{clearTimeout(h),o=void 0,a=!1,f()},"wake")}))}finally{i()}}s(O,"awaitMachineCall");async function y(e,n,t,r,l,o){for(;;){const a=await(await _()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(t);if(a===void 0)throw new c(e,t);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const i=a.result_json===null?{}:JSON.parse(a.result_json);throw i.code==="machine_offline"?new w(e,i.message,i.sent===!0):i.code==="machine_lost"?new c(e,t):new S(e,n,i.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await d(t,"lease expired")===void 0)continue;throw new c(e,t)}if(Date.now()>=r){const i=await d(t,"timed out");if(i===void 0)continue;throw i===null?new w(e,"no holder claimed the call"):new c(e,t)}await o(Math.min(l,Math.max(0,r-Date.now())))}}s(y,"waitForCall");async function d(e,n){const t=await(await _()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
2
2
  result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
3
- WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return t===void 0?void 0:t.claimed_generation===null?null:Number(t.claimed_generation)}s(m,"failOpenCall");export{D as MACHINE_CALL_TIMEOUT_S,b as callMachine};
3
+ WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return t===void 0?void 0:t.claimed_generation===null?null:Number(t.claimed_generation)}s(d,"failOpenCall");export{N as MACHINE_CALL_TIMEOUT_S,O as awaitMachineCall,R as callMachine,M as enqueueMachineCall};
@@ -8,7 +8,8 @@ import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions
8
8
  export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "status.all", "delete", "viewer", "cron.run", "cron.cancel", "job.stop", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize", "repo.identify"];
9
9
  export type MachineOp = (typeof MACHINE_OPS)[number];
10
10
  /** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
11
- * The token sits in `machine_calls.args_json` until the row is deleted a day after it finishes; the execution's token row holds its hash. */
11
+ * The bundle includes `machine_env`, the environment's secrets. The token and the bundle sit in `machine_calls.args_json` only while the call is in flight:
12
+ * the UPDATE that finishes any call (answered, failed, lost or offline) sets `args_json` to '{}', and a requeue from `sent` to `pending` keeps it. A row nothing finishes (its awaiter died and no link ever claims it) keeps its arguments: no code deletes `machine_calls` rows. */
12
13
  export type MachineStartArgs = RunnerStartInput & {
13
14
  nodeToken: string;
14
15
  /** The start bundle, when the control plane carries it: the Mac then does not fetch it. */
@@ -27,6 +27,8 @@ export interface SpawnChildOpts {
27
27
  * bounded worker that must finalize. For roots, terminal keeps the
28
28
  * unattended no-viewer behavior. */
29
29
  rootLifecycle?: Lifecycle;
30
+ /** Start the node on its remote machine in the create itself (a machine environment on a cloud role) instead of leaving it dormant. */
31
+ start?: boolean;
30
32
  /** Direct root creation waits until the broker accepts viewers before it
31
33
  * returns. Cron-launched births use `launch`: the daemon must never wait in
32
34
  * its supervision loop. */
@@ -1,3 +1,3 @@
1
- var ke=Object.defineProperty;var d=(e,r)=>ke(e,"name",{value:r,configurable:!0});import{accessSync as _e,constants as ve}from"node:fs";import{isAbsolute as ge,resolve as ye,join as be}from"node:path";import{appSpace as xe}from"../layout.js";import{ApiError as oe}from"../../api/errors.js";import{spawnNode as Ce,forkSourceNode as $e,currentNodeContext as Se,rootOfSpine as Ee,newNodeId as te,preflightNodeId as Oe}from"./nodes.js";import{resolveProfileOperand as Re}from"../profiles/manifest.js";import{selectProfileForCwd as Ie,selectProfileForCwdReadOnly as Fe}from"../profiles/select.js";import{buildLaunchSpecAsync as ie,buildPiArgv as Me}from"./launch.js";import{devEnvironmentCwd as Be,runsOnBlaxel as Pe,sandboxWorktreeRequest as De}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ne,rollbackManagedWorktreeAsync as Le}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Te,rollbackManagedWorktreeOnMachine as Ae,worktreeMachineOf as We}from"../worktree-machine.js";import{usage as h,brokerLaunchFailed as L}from"../errors.js";import{writeGoal as je}from"./kickoff.js";import{appendSituationalContext as ze,formatSituationalProse as He}from"./situational-context.js";import{ensureRoadmap as Ke}from"./roadmap.js";import{buildWakeBearings as Ge}from"./bearings.js";import{encodeKickoffOrigin as Ue,KICKOFF_ORIGIN_ENV as Ve}from"./stamp/protocol.js";import{carryInitialInput as Xe}from"../runs/initial-input.js";import{ExecutionCapReached as qe,beginExecution as Ye,crtrHome as Je,getNode as u,fullName as ae,jobDir as Qe,recordExecutionPid as Ze,abortExecution as H,setFrozen as K}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as U}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as en}from"../spaces/open-beneath.js";import{conversationIdFromPath as T,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as nn,boundFleet as rn,brokerThresholdsForDaemon as de}from"./fleet.js";import{admitBrokerMemory as on}from"./memory-admission.js";import{emitEvent as A}from"../events/emit.js";import{remoteEnvironmentOf as tn}from"./blaxel-environment.js";import{openViewerWindow as an,focusOf as dn,windowOfPane as sn}from"./placement.js";import{awaitBrokerViewSocket as ln}from"./view-socket.js";import{readLogSnapshot as cn}from"../events/read.js";import{transition as g}from"./lifecycle.js";import{beginBootFaultAttempt as un}from"../canvas/recovery.js";import{headlessBrokerHost as V}from"./host.js";import{ensureDaemon as fn}from"../../daemon/manage.js";import{readConfig as wn}from"../config.js";import{modelRequestFromConfig as mn,unregisteredConcreteModel as hn,unroutableConcreteModel as pn}from"../model-routes.js";import{openModelRegistry as kn}from"./model-registry.js";import{MODEL_SPEC_NEXT as _n}from"./model-selection.js";import{forkNodeLedger as vn}from"./ledger.js";import{appRungForGrant as gn}from"../llm/app-rungs.js";import{APP_FAMILY as X}from"../model-routes.js";import{discoverLifecycleHookRegistry as yn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as bn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as xn}from"../async-array.js";import{checkStart as Cn}from"./start-check.js";function y(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(y,"launchFailureOutcome");async function $n(e,r,a){try{return await V.launch(e,r,a)}catch(o){try{await g(e,"crash",{reason:"launch_failed",outcome:y(o)})}catch{}const t=o.message;throw L(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d($n,"launchBrokerOrCrash");function Sn(e){return cn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(Sn,"lastStartupStep");function En(e,r){const a=Sn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:s}=r.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}d(En,"notReadyDescription");async function On(e,r){try{await g(e,"crash",{reason:"launch_failed",outcome:y(r)})}catch{}try{V.teardown(e)}catch{}}d(On,"crashAndTearDown");async function Rn(e){const r=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw h(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw h(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}d(Rn,"resolveSessionUuid");async function se(e){const r=e.trim();if(r==="")throw h("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=T(ge(r)?r:ye(process.cwd(),r));if(o===null)throw h(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(o)).path}const a=await u(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw h(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=T(o);if(t===null)throw h(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await Rn(r)}d(se,"resolveForkSource");async function In(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?Re(e).profileId:r!==null?(await u(r))?.profile_id??null:o.readOnlySelection===!0?Fe(a):Ie(a)}d(In,"resolveProfileId");function le(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return mn(e.model,r,e.modelExact===!0)}d(le,"requestFromLaunch");async function ce(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await gn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:X,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${X}/${t.strength}`}}}d(ce,"appPaidLaunch");async function ue(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==X)return;const o=await hn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await kn(),r);if(o!==void 0)throw h(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:_n});const t=await pn(e,r);if(t!==void 0)throw h(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(ue,"assertLaunchModelRegistered");function Fn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}d(Fn,"resolveSpawner");async function fe(e,r,a){try{fn()}catch{}const o=Se(),t=e.root===!0,s=Fn(e.parent,o.nodeId??null,t),l=e.mode??"base",b=e.rootLifecycle??(t?"resident":"terminal"),we=t&&b==="resident",I=s===null?null:await u(s),q=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Oe(e.nodeId);const x=e.forkFrom!==void 0?await se(e.forkFrom):void 0,W=x===void 0?null:await $e(x),j=await xn([I,q,W],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(j&&e.isolated===!1)throw new oe(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const E=j||e.isolated===!0;if(E&&e.worktree===!0)throw new oe(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let w=E||e.worktree===!0?e.nodeId??await te():e.nodeId,C=E?e.run!==void 0&&t&&!j?e.cwd:be(xe(e.run?.grantee??I?.grantee??"app:terminal").nodes,w):e.cwd;const m=await In(e.profile,s,C),F=E?null:await Be(m,e.worktreeCwd??C);F!==null&&(C=F,w??=await te());const O=e.worktree===!0||F!==null,Y=e.run?.grant_id??I?.grant_id??null,R=e.run??q??I??W,J=await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:C,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model);await ue(le(J),{cwd:C,profileId:m}),await Cn({grantee:R?.grantee??"app:terminal",sub:R?.sub,grant_id:R?.grant_id});const Q=W?.node_id??null;let p,M=C;const B=O&&await Pe(m)?await De(m,F??e.worktreeCwd??e.cwd,w,e.worktreeBase):void 0,P=O&&B===void 0?await We(m):null;try{O&&B===void 0&&(p=P!==null?await Te(P,e.worktreeCwd??e.cwd,w,e.worktreeBase):await Ne(e.worktreeCwd??e.cwd,w,e.worktreeBase),M=p.path);const f=O?await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model):J;B!==void 0&&(f.worktree=B),O&&await ue(le(f),{cwd:M,profileId:m});const n=await Ce({kind:e.kind,mode:l,lifecycle:b,cwd:M,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Q,spawnedBy:t?s??void 0:void 0,profile_id:m,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:E,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:x,modelOverride:e.model===void 0?void 0:f.model,...p!==void 0?{managedWorktree:p}:{},...w!==void 0?{nodeId:w}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await vn(n.node_id,Q??null)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(await je(n.node_id,e.prompt),e.situationalContext!==void 0&&await ze(n.node_id,He(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const z=e.prompt!=="",me=`${z&&e.wakeOrigin!==void 0?`${Ge(e.wakeOrigin)}
1
+ var ye=Object.defineProperty;var l=(e,r)=>ye(e,"name",{value:r,configurable:!0});import{accessSync as be,constants as xe}from"node:fs";import{isAbsolute as Ce,resolve as Se,join as Ee}from"node:path";import{appSpace as Oe}from"../layout.js";import{ApiError as ie}from"../../api/errors.js";import{spawnNode as Ie,forkSourceNode as $e,currentNodeContext as Re,rootOfSpine as Me,newNodeId as ae,preflightNodeId as Fe}from"./nodes.js";import{resolveProfileOperand as De}from"../profiles/manifest.js";import{selectProfileForCwd as Ne,selectProfileForCwdReadOnly as Be}from"../profiles/select.js";import{buildLaunchSpecAsync as de,buildPiArgv as Pe}from"./launch.js";import{devEnvironmentCwd as Le,runsOnBlaxel as Te,sandboxWorktreeRequest as Ae}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as We,rollbackManagedWorktreeAsync as je}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as ze,rollbackManagedWorktreeOnMachine as He,worktreeMachineOf as Ke}from"../worktree-machine.js";import{usage as p,brokerLaunchFailed as H}from"../errors.js";import{writeGoal as Ue}from"./kickoff.js";import{appendSituationalContext as Xe,formatSituationalProse as Ge}from"./situational-context.js";import{ensureRoadmap as Ve}from"./roadmap.js";import{buildWakeBearings as qe}from"./bearings.js";import{encodeKickoffOrigin as Je,KICKOFF_ORIGIN_ENV as Ye}from"./stamp/protocol.js";import{carryInitialInput as Qe}from"../runs/initial-input.js";import{ExecutionCapReached as se,beginExecution as le,crtrHome as Ze,getNode as w,fullName as ce,jobDir as en,recordExecutionPid as nn,abortExecution as B,setFrozen as X}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as V}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as rn}from"../spaces/open-beneath.js";import{conversationIdFromPath as K,conversationStore as $}from"../conversation-store/index.js";import{appMemoryTooSmall as on,boundFleet as ue,brokerThresholdsForDaemon as q}from"./fleet.js";import{admitBrokerMemory as tn}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as an}from"./blaxel-environment.js";import{openViewerWindow as dn,focusOf as sn,windowOfPane as ln}from"./placement.js";import{awaitBrokerViewSocket as cn}from"./view-socket.js";import{readLogSnapshot as un}from"../events/read.js";import{transition as C}from"./lifecycle.js";import{beginBootFaultAttempt as fn}from"../canvas/recovery.js";import{headlessBrokerHost as J,brokerLaunchJson as wn}from"./host.js";import{openDb as mn,withCanvasWrite as hn}from"../canvas/db.js";import{warmNodeRepos as pn}from"../graph/reader.js";import{mintNodeToken as _n}from"../canvas/node-tokens.js";import{personIdAsync as kn}from"../canvas/person.js";import{recordLaunch as vn}from"../canvas/canvas.js";import{setExecutionLaunchJson as gn}from"../canvas/executions.js";import{acceptedRelease as fe,remoteMachineEnvironmentOf as yn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as bn,awaitMachineCall as xn}from"./runner/machine/call.js";import{MachineLostError as Cn,MachineOfflineError as Sn}from"./runner/machine/ops.js";import{isDrained as En}from"../../daemon/drain.js";import{ensureDaemon as On}from"../../daemon/manage.js";import{readConfig as In}from"../config.js";import{modelRequestFromConfig as $n,unregisteredConcreteModel as Rn,unroutableConcreteModel as Mn}from"../model-routes.js";import{openModelRegistry as Fn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Dn}from"./model-selection.js";import{forkNodeLedger as Nn}from"./ledger.js";import{appRungForGrant as Bn}from"../llm/app-rungs.js";import{APP_FAMILY as Y}from"../model-routes.js";import{discoverLifecycleHookRegistry as Pn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Ln}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Tn}from"../async-array.js";import{checkStart as An}from"./start-check.js";function S(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(S,"launchFailureOutcome");async function Wn(e,r,a){try{return await J.launch(e,r,a)}catch(o){try{await C(e,"crash",{reason:"launch_failed",outcome:S(o)})}catch{}const t=o.message;throw H(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}l(Wn,"launchBrokerOrCrash");function jn(e){return un({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}l(jn,"lastStartupStep");function zn(e,r){const a=jn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:d}=r.status;return{text:`exited (code ${t??"null"}, signal ${d??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:d,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}l(zn,"notReadyDescription");async function Hn(e,r){try{await C(e,"crash",{reason:"launch_failed",outcome:S(r)})}catch{}try{J.teardown(e)}catch{}}l(Hn,"crashAndTearDown");async function Kn(e){const r=(await $().list()).map(({conversation_id:t,path:d})=>({id:t,path:d})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw p(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw p(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}l(Kn,"resolveSessionUuid");async function we(e){const r=e.trim();if(r==="")throw p("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=K(Ce(r)?r:Se(process.cwd(),r));if(o===null)throw p(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await $().header(o)).path}const a=await w(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw p(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=K(o);if(t===null)throw p(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await $().header(t)).path}return await Kn(r)}l(we,"resolveForkSource");async function Un(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?De(e).profileId:r!==null?(await w(r))?.profile_id??null:o.readOnlySelection===!0?Be(a):Ne(a)}l(Un,"resolveProfileId");function me(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return $n(e.model,r,e.modelExact===!0)}l(me,"requestFromLaunch");async function he(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await Bn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:d,...c}=e.env??{};return{...e,model:t.model,modelIntent:{family:Y,strength:t.strength},modelExact:void 0,env:{...c,CRTR_MODEL_INTENT:`${Y}/${t.strength}`}}}l(he,"appPaidLaunch");async function pe(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==Y)return;const o=await Rn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await Fn(),r);if(o!==void 0)throw p(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:Dn});const t=await Mn(e,r);if(t!==void 0)throw p(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(pe,"assertLaunchModelRegistered");function Xn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}l(Xn,"resolveSpawner");async function Gn(e,r,a){const{buildStartBundle:o}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:t}=await import("../../daemon/api/handlers/broker-ops.js");if(await En())return"full";let d;try{d=await le(e.node_id,{daemonEpoch:ue().epoch(),cap:q().automaticReviveCap,runner:"machine",release:fe()})}catch(s){return s instanceof se?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),"failed")}let c;try{a.env={...a.env,CRTR_EXECUTION_ID:d};const s=await wn(e.node_id,a,e.cwd);await gn(d,s);const P=d;await pn(await mn(),e.node_id);const E=e.sub??await kn(),L=await o({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:E,launchJson:s,runner:"machine"});c=await hn(async _=>{const R=await t(e.node_id),M=await _n(_,P,e.node_id,new Date().toISOString());return await bn(r,"start",{executionId:P,nodeId:e.node_id,attempt:1,sandboxName:null,release:fe(),launchJson:s,cwd:e.cwd,resuming:!1,nodeToken:M,bundle:L,start:R})})}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),await B(d,{reason:"launch_failed"}),"failed"}try{await xn(r,"start",c)}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof Cn||s instanceof Sn&&s.sent?"uncertain":(await B(d,{reason:"launch_failed"}),"failed")}try{await vn(e.node_id,new Date().toISOString())}catch(s){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:s})}return"started"}l(Gn,"startOnMachine");async function _e(e,r,a){try{On()}catch{}const o=Re(),t=e.root===!0,d=Xn(e.parent,o.nodeId??null,t),c=e.mode??"base",s=e.rootLifecycle??(t?"resident":"terminal"),P=t&&s==="resident",E=d===null?null:await w(d),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Fe(e.nodeId);const _=e.forkFrom!==void 0?await we(e.forkFrom):void 0,R=_===void 0?null:await $e(_),M=await Tn([E,L,R],async f=>f?.isolated===!0||f?.run_id!=null&&(await w(f.run_id))?.isolated===!0);if(M&&e.isolated===!1)throw new ie(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const F=M||e.isolated===!0;if(F&&e.worktree===!0)throw new ie(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let m=F||e.worktree===!0?e.nodeId??await ae():e.nodeId,O=F?e.run!==void 0&&t&&!M?e.cwd:Ee(Oe(e.run?.grantee??E?.grantee??"app:terminal").nodes,m):e.cwd;const h=await Un(e.profile,d,O),T=F?null:await Le(h,e.worktreeCwd??O);T!==null&&(O=T,m??=await ae());const D=e.worktree===!0||T!==null,Q=e.run?.grant_id??E?.grant_id??null,N=e.run??L??E??R,Z=await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model);await pe(me(Z),{cwd:O,profileId:h}),await An({grantee:N?.grantee??"app:terminal",sub:N?.sub,grant_id:N?.grant_id});const ee=R?.node_id??null;let g,A=O;const W=D&&await Te(h)?await Ae(h,T??e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0,j=D&&W===void 0?await Ke(h):null;try{D&&W===void 0&&(g=j!==null?await ze(j,e.worktreeCwd??e.cwd,m,e.worktreeBase):await We(e.worktreeCwd??e.cwd,m,e.worktreeBase),A=g.path);const f=D?await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:A,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model):Z;W!==void 0&&(f.worktree=W),D&&await pe(me(f),{cwd:A,profileId:h});const n=await Ie({kind:e.kind,mode:c,lifecycle:s,cwd:A,name:e.name??e.kind,description:e.description,parent:t?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:ee,spawnedBy:t?d??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:F,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:_,modelOverride:e.model===void 0?void 0:f.model,...g!==void 0?{managedWorktree:g}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await Nn(n.node_id,ee??null)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}if(await Ue(n.node_id,e.prompt),e.situationalContext!==void 0&&await Xe(n.node_id,Ge(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}const U=e.prompt!=="",ke=`${U&&e.wakeOrigin!==void 0?`${qe(e.wakeOrigin)}
2
2
 
3
- `:""}${e.prompt}`;l==="orchestrator"&&await Ke(n.node_id,{goal:e.prompt.trim()}),await Mn(n);let Z;if(x!==void 0)try{const i=T(x);if(i===null)throw new Error(`invalid fork source ${x}`);const c=await S().fork(i,n.node_id);Z=(await S().header(c)).path}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const k=Me(n,{prompt:me,resumeSessionPath:Z});if(k.env={...k.env,CRTR_SUBTREE:await Ee(n.node_id)},z){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};k.env[Ve]=Ue(i),await Xe(k,n)}const _=rn();if(await tn(n.profile_id??null)!==null)return await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const ee=await _.reserveSlot(n.node_id),v=ee?await on(n.node_id):null;if(v?.verdict==="too_small"){_.releaseReservation(n.node_id);const i=nn(v);throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(!ee||v?.verdict==="denied")return v?.verdict==="denied"&&_.releaseReservation(n.node_id),await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:v?.verdict==="denied"?{reason:"app_memory",free_bytes:v.free_bytes,needed_bytes:v.needed_bytes}:{reason:"broker_cap",live_count:await _.occupancy(),hard_cap:de().automaticReviveCap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const he=await un(n.node_id),{automaticReviveCap:pe}=de();let $;try{$=await Ye(n.node_id,{daemonEpoch:_.epoch(),cap:pe})}catch(i){if(!(i instanceof qe))throw i;return _.releaseReservation(n.node_id),await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null}}k.env={...k.env,CRTR_EXECUTION_ID:$};let D;try{D=await $n(n.node_id,k,{cwd:n.cwd,name:ae(n),resuming:!1})}catch(i){throw await H($,{reason:"launch_failed"}),i}finally{_.releaseReservation(n.node_id)}if(D.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await H($,{reason:"launch_failed"}),await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),L(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await Ze($,n.node_id,D.pid)==="shutdown")throw await H($,{reason:"superseded"}),V.teardown(n.node_id),L(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(we&&e.readiness==="await"){const i=await ln(n.node_id,D.exited);if(!i.ready){const c=En(n.node_id,i);A({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:c.fields});const N=await he.explanation();throw await On(n.node_id,new Error(N??c.text)),L(N!==null?`the root broker ${n.node_id} could not start \u2014 ${N}`:`the root broker ${n.node_id} ${c.text} \u2014 it was not started.`,N!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ne=null,re=null;if(!t&&s!==null&&wn("user").auto_open_child_viewers)try{const i=await dn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const c=await an(n.node_id,i.session??"",{name:ae(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:z});c!==null&&c.pane!==null&&c.pane!==""&&(re=c.session,ne=sn(c.pane))}}catch{}return{node:await u(n.node_id),frozen:!1,window:ne,session:re}}catch(f){throw p!==void 0&&w!==void 0&&await u(w)===null&&(P!==null?await Ae(P,p):await Le(p)),f}}d(fe,"spawnChildPrepared");async function Er(e){return fe(e)}d(Er,"spawnChild");async function Mn(e){const r=yn(e.cwd,e.profile_id).plans.get("node:start")??[];await bn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await U(e.node_id),contextDir:await G(e.node_id),jobDir:Qe(e.node_id)},runtime:{isBirth:!0,canvasHome:Je(),profile:e.profile_id??null}})}d(Mn,"invokeBirthLifecycleHooks");const Bn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function Or(e,r,a){const o=await u(e);if(o===null)throw h(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await se(e),s=await G(e);try{await S().header(T(t)),_e(s,ve.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return fe({kind:o.kind,mode:"base",cwd:o.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:o.profile_id,model:o.model_override??void 0,...r===void 0?{}:{scopes:r}},async l=>{const b=await G(l);en(await U(e),s,await U(l),b,Bn)})}d(Or,"forkNode");export{ce as appPaidLaunch,ue as assertLaunchModelRegistered,Or as forkNode,Mn as invokeBirthLifecycleHooks,se as resolveForkSource,In as resolveProfileId,Fn as resolveSpawner,Er as spawnChild,fe as spawnChildPrepared};
3
+ `:""}${e.prompt}`;c==="orchestrator"&&await Ve(n.node_id,{goal:e.prompt.trim()}),await Vn(n);let ne;if(_!==void 0)try{const i=K(_);if(i===null)throw new Error(`invalid fork source ${_}`);const u=await $().fork(i,n.node_id);ne=(await $().header(u)).path}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}const k=Pe(n,{prompt:ke,resumeSessionPath:ne});if(k.env={...k.env,CRTR_SUBTREE:await Me(n.node_id)},U){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};k.env[Ye]=Je(i),await Qe(k,n)}const y=ue();if(await an(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await yn(n.profile_id??null):null;if(u!==null){const x=await Gn(n,u,k);if(x==="started"||x==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await X(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}const re=await y.reserveSlot(n.node_id),b=re?await tn(n.node_id):null;if(b?.verdict==="too_small"){y.releaseReservation(n.node_id);const i=on(b);throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}if(!re||b?.verdict==="denied")return b?.verdict==="denied"&&y.releaseReservation(n.node_id),await X(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:b?.verdict==="denied"?{reason:"app_memory",free_bytes:b.free_bytes,needed_bytes:b.needed_bytes}:{reason:"broker_cap",live_count:await y.occupancy(),hard_cap:q().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const ve=await fn(n.node_id),{automaticReviveCap:ge}=q();let I;try{I=await le(n.node_id,{daemonEpoch:y.epoch(),cap:ge})}catch(i){if(!(i instanceof se))throw i;return y.releaseReservation(n.node_id),await X(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}k.env={...k.env,CRTR_EXECUTION_ID:I};let z;try{z=await Wn(n.node_id,k,{cwd:n.cwd,name:ce(n),resuming:!1})}catch(i){throw await B(I,{reason:"launch_failed"}),i}finally{y.releaseReservation(n.node_id)}if(z.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await B(I,{reason:"launch_failed"}),await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),H(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await nn(I,n.node_id,z.pid)==="shutdown")throw await B(I,{reason:"superseded"}),J.teardown(n.node_id),H(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(P&&e.readiness==="await"){const i=await cn(n.node_id,z.exited);if(!i.ready){const u=zn(n.node_id,i);v({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const x=await ve.explanation();throw await Hn(n.node_id,new Error(x??u.text)),H(x!==null?`the root broker ${n.node_id} could not start \u2014 ${x}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,x!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let oe=null,te=null;if(!t&&d!==null&&In("user").auto_open_child_viewers)try{const i=await sn(d);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await dn(n.node_id,i.session??"",{name:ce(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:U});u!==null&&u.pane!==null&&u.pane!==""&&(te=u.session,oe=ln(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:oe,session:te}}catch(f){throw g!==void 0&&m!==void 0&&await w(m)===null&&(j!==null?await He(j,g):await je(g)),f}}l(_e,"spawnChildPrepared");async function Zr(e){return _e(e)}l(Zr,"spawnChild");async function Vn(e){const r=Pn(e.cwd,e.profile_id).plans.get("node:start")??[];await Ln(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await V(e.node_id),contextDir:await G(e.node_id),jobDir:en(e.node_id)},runtime:{isBirth:!0,canvasHome:Ze(),profile:e.profile_id??null}})}l(Vn,"invokeBirthLifecycleHooks");const qn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function eo(e,r,a){const o=await w(e);if(o===null)throw p(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await we(e),d=await G(e);try{await $().header(K(t)),be(d,xe.R_OK)}catch(c){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${c.message}`)}return _e({kind:o.kind,mode:"base",cwd:o.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:o.profile_id,model:o.model_override??void 0,...r===void 0?{}:{scopes:r}},async c=>{const s=await G(c);rn(await V(e),d,await V(c),s,qn)})}l(eo,"forkNode");export{he as appPaidLaunch,pe as assertLaunchModelRegistered,eo as forkNode,Vn as invokeBirthLifecycleHooks,we as resolveForkSource,Un as resolveProfileId,Xn as resolveSpawner,Zr as spawnChild,_e as spawnChildPrepared};
@@ -39,6 +39,8 @@ export declare class RefreshTimeoutError extends Error {
39
39
  constructor(provider: ManagedProviderId);
40
40
  }
41
41
  export declare const aadOf: (person: string, provider: string, id: string, part: "refresh" | "access") => string;
42
+ /** Every managed provider's pool for the person in two statements (accounts, cooldowns), tokens opened. A provider with no account is absent. */
43
+ export declare function readAllSubscriptionPools(): Promise<Map<ManagedProviderId, SubscriptionCredential[]>>;
42
44
  export declare function insertAccount(db: CanvasDb, person: string, provider: ManagedProviderId, row: ProviderRow, entry: StoredCredential): Promise<void>;
43
45
  export declare function upsertModelCooldown(db: CanvasDb, person: string, provider: string, accountId: string, family: string, until: number, rateLimitedAt: number): Promise<void>;
44
46
  export declare function readSubscriptionPool(provider: ManagedProviderId): Promise<SubscriptionCredential[]>;
@@ -1 +1 @@
1
- var _t=Object.defineProperty;var l=(t,a)=>_t(t,"name",{value:a,configurable:!0});import{createHash as pt,randomUUID as I}from"node:crypto";import{brokerConfigSnapshot as ht}from"./config.js";import{openDb as K,withCanvasWrite as F}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as B,open as Y,seal as $}from"./secrets/index.js";import{classifyRateLimit as wt,modelCooldownFamily as At}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as bt,REFRESH_TIMEOUT_PHRASE as yt}from"./provider-error-recognition.js";import{registerRotationReader as Et}from"./model-routes.js";import{coolingUntilFor as Lt,retryAfterMsFromHeaders as Rt,getProviderLabel as p,isInvalidRefreshTokenError as J,DuplicateSubscriptionError as O,ANTHROPIC_PROVIDER_ID as gt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as xt}from"./managed-providers.js";export*from"./managed-providers.js";const Q="strong";function Z(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(Z,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function It(t){const a=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",n=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!a||!e||!n||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:a,refresh:e,access:n,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...v(t.modelCooldowns)?{modelCooldowns:v(t.modelCooldowns)}:{}}}l(It,"credential");function v(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=Object.entries(t).filter(([e,n])=>e.trim()!==""&&Number.isFinite(Number(n))).map(([e,n])=>[e,Number(n)]);return a.length?Object.fromEntries(a):void 0}l(v,"modelCooldowns");function N(t,a){if(!a.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=It(a);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${a.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(N,"assertCredential");function tt(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(tt,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${pt("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function et(t,a){const e=V(a);return e?{...t,clientId:e}:t}l(et,"withClientId");function at(t,a,e){const n=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!n||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${a}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:n,access:i,expires:r}}l(at,"assertTokens");const nt=1e4,Ft="15s",Nt="55P03";class it extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${p(a)} subscription "${e}" ${bt}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class St extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${p(a)} ${yt} ${nt} ms`),this.name="RefreshTimeoutError"}}const rt="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",x=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Tt(t,a){return{providerId:t,id:a.id,label:a.label,labelKey:a.label_key,position:a.position,lastAttemptAt:a.last_attempt_at,lastRateLimitedAt:a.last_rate_limited_at,rateLimitedUntil:a.rate_limited_until,...a.auth_failure?{authFailure:a.auth_failure}:{}}}l(Tt,"rowOf");function st(t,a,e,n=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${a} account ${e.id} has no credential record`);const i=B(),r=Y(e.refresh_sealed,e.key_id,i,x(t,a,e.id,"refresh")),s=Y(e.access_sealed,e.key_id,i,x(t,a,e.id,"access")),o=Tt(a,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+j):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(st,"toPublic");async function S(t,a,e){const n=new Map,i=await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(a,e);for(const r of i){const s=n.get(r.account_id)??[];s.push({family:r.family,rateLimitedUntil:r.rate_limited_until,lastRateLimitedAt:r.last_rate_limited_at}),n.set(r.account_id,s)}return n}l(S,"loadCooldowns");async function k(t,a,e,n=!1){const i=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${n?" FOR UPDATE":""}`).all(a,e),r=await S(t,a,e);return i.map(s=>st(a,e,s,r.get(s.id)))}l(k,"loadPool");async function ot(t,a,e,n){const i=n.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(a,e,s?r-1:i);if(o)return st(a,e,o,(await S(t,a,e)).get(o.id))}l(ot,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${Ft}'`)}l(T,"setLockTimeout");async function L(t,a){const e=await y();return F(async n=>(await T(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await k(n,e,t,!0)})))}l(L,"locked");async function C(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n.id,"refresh")),o=$(i.access,r,x(a,e,n.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a,e,n.id,n.label,n.labelKey,n.position,n.lastAttemptAt,n.lastRateLimitedAt,n.rateLimitedUntil,n.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(C,"insertAccount");async function M(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n,"refresh")),o=$(i.access,r,x(a,e,n,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,a,e,n)}l(M,"setCredential");async function b(t,a,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,a,e.providerId,e.id)}l(b,"updateHealth");async function lt(t,a,e,n,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(a,e,n,i,r,s)}l(lt,"upsertModelCooldown");async function U(t,a,e,n){n===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(a,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(a,e,n)}l(U,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await k(t,a,e)).map(({entry:n})=>n),"publicPool"),ct=l(t=>t?.code===Nt,"lockWaitExpired");function ut(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new St(t)),nt)})]).finally(()=>clearTimeout(e))}l(ut,"withExchangeTimeout");async function G(t){return(await Ut(t)).map(({entry:a})=>a)}l(G,"readSubscriptionPool");async function Ut(t){const a=await y();return(await k(await K(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(Ut,"readSubscriptionPoolRows");async function Yt(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(d=>N(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??I()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await U(n,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await C(n,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await lt(n,i,t,m,f,A,c.get(m)?.find(D=>D.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(Yt,"writeSubscriptionPool");function H(t,a){const e=a.trim().toLowerCase(),n=Number.parseInt(e,10);return Number.isFinite(n)&&String(n)===e&&n>=1&&n<=t.length?n-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(H,"resolve");const P=l((t,a)=>new O(`This ${p(t)} account is already added as \u201C${a}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Dt(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new O(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),c=s.find(({entry:d})=>h(d)===o);if(o&&c)throw P(t,c.entry.label);return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),R(n,t)})}l(Dt,"addSubscription");async function Jt(t,a){const e=N(t,a);return(await G(t)).find(i=>_(i.label)===_(e.label))?$t(t,e):Dt(t,e)}l(Jt,"upsertSubscription");async function $t(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&h(f)===h(e));if(h(e)&&d)throw P(t,d.entry.label);if(!c)return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),R(n,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await M(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),tt(c.entry,e)&&await U(i,r,t,u.id),R(n,t)})}l($t,"upsertSubscriptionWithUniqueAccount");async function Qt(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=H(s,a);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new O(`${p(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),R(n,t)})}l(Qt,"renameSubscription");async function z(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=a(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await U(i,r,t,c.id),R(n,t)})}l(z,"remove");async function Ot(t,a){return z(t,e=>H(e,a),a)}l(Ot,"removeManagedAccount");async function Zt(t,a){return z(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(Zt,"removeManagedAccountById");async function vt(t,a){return z(t,e=>H(e,a),a)}l(vt,"removeSubscription");async function kt(t){return L(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await U(a,e,t),n.length))}l(kt,"removeAllManagedAccounts");async function te(t,a){return a===void 0?(await kt(t),[]):Ot(t,a)}l(te,"removeManagedProvider");async function ee(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=H(r,a);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(n,i,{...d.row,position:c});return R(e,t)})}l(ee,"promoteSubscription");async function W(t,a,e){const n=await y();return await F(async i=>{await T(i);const r=await ot(i,n,t,a);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${a}`);await e(i,n,r.row)}),G(t)}l(W,"healthWrite");async function ae(t,a,e=Date.now()){return W(t,a,(n,i,r)=>b(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(ae,"markSubscriptionAttempt");async function ne(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),W(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const d=(await S(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await lt(s,o,t,c.id,r.family,i+e,i)})}l(ne,"markSubscriptionRateLimited");async function ie(t,a,e=Date.now(),n){const i=At(n);return W(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await S(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(ie,"markSubscriptionSuccess");async function q(t,a,e){const n=Date.now();await b(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+xt)})}l(q,"recordInvalidGrant");function re(t,a,e,n=15e3,i=Date.now()){const r=Rt(t),s=wt(t,a,i),o=e??r??n;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(re,"vendorRateLimit");async function se(t,a){return W(t,a,(e,n,i)=>q(e,n,i))}l(se,"markSubscriptionAuthFailure");async function oe(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await ot(r,n,t,a);if(!s)throw new Error(`${p(t)} subscription "${a}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${p(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await ut(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!J(d))throw d;return await q(r,n,s.row),{refused:d}}const c=et(at(t,s.entry.label,o),o.clientId??s.entry.clientId);return await M(r,n,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw ct(r)?new it(t,a):r}if("refused"in i)throw i.refused;return i.entry}l(oe,"refreshSubscriptionCredential");async function le(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await k(r,n,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=a(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await ut(t,e(u.entry));if(!m)return{entry:u.entry};const f=et(at(t,u.entry.label,m),m.clientId??u.entry.clientId);return await M(r,n,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!J(m))throw m;c=m,await q(r,n,u.row)}}return c?{refused:c}:{}})}catch(r){throw ct(r)?new it(t,a([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(le,"modifyElectedSubscription");async function Ct(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==gt)return{...e?{accountId:e}:{},...n?{email:n}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${a.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Ct,"enrichManagedLoginIdentity");async function ce(t,a,e){const n=await Ct(t,e);return L(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),d=h({refresh:e.refresh,accountId:n.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>h(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:ft})=>_(ft.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${p(t)} subscription label cannot be empty`);const f=N(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...n.accountId?{accountId:n.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new O(`${p(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>h(g)===h(f));if(h(f)&&w)throw P(t,w.entry.label);return await C(r,s,t,{providerId:t,id:I(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),R(i,t)}const A=u.row,D=o.find(({entry:w})=>w.label!==u.entry.label&&h(w)===h(f));if(h(f)&&D)throw P(t,D.entry.label);const X=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await M(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:X?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:X?0:A.rateLimitedUntil}),tt(u.entry,f)&&await U(r,s,t,A.id),R(i,t)})}l(ce,"commitManagedLogin");const dt=new Map;function mt(t){return{defaultFallbackStrength:Z(t?.default_fallback_strength)??Q,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(mt,"rotationFromRow");async function Mt(){const t=await y(),a=mt(await(await K()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return dt.set(t,a),a}l(Mt,"loadRotationConfig"),Et(()=>Ht());async function Ht(){const t=ht();return t?t.rotation:Mt()}l(Ht,"readRotationConfig");async function ue(t){const a=await y(),e=await F(async n=>{await T(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=mt(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:Z(t.defaultFallbackStrength)??i.defaultFallbackStrength??Q,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await n.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,a),r});return dt.set(a,e),e}l(ue,"writeRotationConfig");async function de(){const t=await y();return(await(await K()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,I())).openai_device_id}l(de,"openAIDeviceId");async function me(t,a=Date.now(),e){const n=await G(t),i=n.filter(s=>s.authFailure===void 0&&Lt(s,e)<=a),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(me,"formatStatusLine");export{nt as REFRESH_EXCHANGE_TIMEOUT_MS,it as RefreshBusyError,St as RefreshTimeoutError,x as aadOf,Dt as addSubscription,ce as commitManagedLogin,Ct as enrichManagedLoginIdentity,me as formatStatusLine,C as insertAccount,Mt as loadRotationConfig,ae as markSubscriptionAttempt,se as markSubscriptionAuthFailure,ne as markSubscriptionRateLimited,ie as markSubscriptionSuccess,le as modifyElectedSubscription,de as openAIDeviceId,ee as promoteSubscription,Ht as readRotationConfig,G as readSubscriptionPool,Ut as readSubscriptionPoolRows,oe as refreshSubscriptionCredential,kt as removeAllManagedAccounts,Ot as removeManagedAccount,Zt as removeManagedAccountById,te as removeManagedProvider,vt as removeSubscription,Qt as renameSubscription,lt as upsertModelCooldown,Jt as upsertSubscription,$t as upsertSubscriptionWithUniqueAccount,re as vendorRateLimit,ue as writeRotationConfig,Yt as writeSubscriptionPool};
1
+ var pt=Object.defineProperty;var l=(t,n)=>pt(t,"name",{value:n,configurable:!0});import{createHash as ht,randomUUID as I}from"node:crypto";import{brokerConfigSnapshot as wt}from"./config.js";import{openDb as O,withCanvasWrite as F}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as B,open as Q,seal as $}from"./secrets/index.js";import{classifyRateLimit as At,modelCooldownFamily as yt}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as bt,REFRESH_TIMEOUT_PHRASE as Et}from"./provider-error-recognition.js";import{registerRotationReader as Rt}from"./model-routes.js";import{coolingUntilFor as Lt,retryAfterMsFromHeaders as gt,getProviderLabel as p,isInvalidRefreshTokenError as Z,DuplicateSubscriptionError as C,ANTHROPIC_PROVIDER_ID as xt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as It}from"./managed-providers.js";export*from"./managed-providers.js";const v="strong";function tt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(tt,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function Ft(t){const n=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",a=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!n||!e||!a||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:n,refresh:e,access:a,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...et(t.modelCooldowns)?{modelCooldowns:et(t.modelCooldowns)}:{}}}l(Ft,"credential");function et(t){if(!t||typeof t!="object"||Array.isArray(t))return;const n=Object.entries(t).filter(([e,a])=>e.trim()!==""&&Number.isFinite(Number(a))).map(([e,a])=>[e,Number(a)]);return n.length?Object.fromEntries(n):void 0}l(et,"modelCooldowns");function S(t,n){if(!n.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=Ft(n);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${n.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(S,"assertCredential");function nt(t,n){const e=t.accountId?.trim(),a=n.accountId?.trim();return!!(e&&a&&e!==a)}l(nt,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${ht("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function at(t,n){const e=V(n);return e?{...t,clientId:e}:t}l(at,"withClientId");function it(t,n,e){const a=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!a||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${n}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:a,access:i,expires:r}}l(it,"assertTokens");const rt=1e4,St="15s",Nt="55P03";class st extends Error{static{l(this,"RefreshBusyError")}constructor(n,e){super(`${p(n)} subscription "${e}" ${bt}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Tt extends Error{static{l(this,"RefreshTimeoutError")}constructor(n){super(`${p(n)} ${Et} ${rt} ms`),this.name="RefreshTimeoutError"}}const G="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",x=l((t,n,e,a)=>`model_accounts|${t}|${n}|${e}|${a}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Dt(t,n){return{providerId:t,id:n.id,label:n.label,labelKey:n.label_key,position:n.position,lastAttemptAt:n.last_attempt_at,lastRateLimitedAt:n.last_rate_limited_at,rateLimitedUntil:n.rate_limited_until,...n.auth_failure?{authFailure:n.auth_failure}:{}}}l(Dt,"rowOf");function Y(t,n,e,a=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${n} account ${e.id} has no credential record`);const i=B(),r=Q(e.refresh_sealed,e.key_id,i,x(t,n,e.id,"refresh")),s=Q(e.access_sealed,e.key_id,i,x(t,n,e.id,"access")),o=Dt(n,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...a.length?{modelCooldowns:Object.fromEntries(a.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+j):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(Y,"toPublic");function ot(t){const n=new Map;for(const e of t){const a=n.get(e.account_id)??[];a.push({family:e.family,rateLimitedUntil:e.rate_limited_until,lastRateLimitedAt:e.last_rate_limited_at}),n.set(e.account_id,a)}return n}l(ot,"groupCooldowns");async function N(t,n,e){return ot(await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(n,e))}l(N,"loadCooldowns");async function k(t,n,e,a=!1){const i=await t.prepare(`SELECT ${G} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${a?" FOR UPDATE":""}`).all(n,e),r=await N(t,n,e);return i.map(s=>Y(n,e,s,r.get(s.id)))}l(k,"loadPool");async function Jt(){const t=await y(),n=await O(),e=await n.prepare(`SELECT provider_id,${G} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(t),a=ot(await n.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? ORDER BY family").all(t)),i=new Map;for(const r of e){const s=i.get(r.provider_id)??[];s.push(Y(t,r.provider_id,r,a.get(r.id)).entry),i.set(r.provider_id,s)}return i}l(Jt,"readAllSubscriptionPools");async function lt(t,n,e,a){const i=a.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${G} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(n,e,s?r-1:i);if(o)return Y(n,e,o,(await N(t,n,e)).get(o.id))}l(lt,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${St}'`)}l(T,"setLockTimeout");async function R(t,n){const e=await y();return F(async a=>(await T(a),await a.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),n({db:a,person:e,rows:await k(a,e,t,!0)})))}l(R,"locked");async function M(t,n,e,a,i){const r=B(),s=$(i.refresh,r,x(n,e,a.id,"refresh")),o=$(i.access,r,x(n,e,a.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(n,e,a.id,a.label,a.labelKey,a.position,a.lastAttemptAt,a.lastRateLimitedAt,a.rateLimitedUntil,a.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(M,"insertAccount");async function H(t,n,e,a,i){const r=B(),s=$(i.refresh,r,x(n,e,a,"refresh")),o=$(i.access,r,x(n,e,a,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,n,e,a)}l(H,"setCredential");async function b(t,n,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,n,e.providerId,e.id)}l(b,"updateHealth");async function ct(t,n,e,a,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(n,e,a,i,r,s)}l(ct,"upsertModelCooldown");async function D(t,n,e,a){a===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(n,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(n,e,a)}l(D,"deleteModelCooldowns");const L=l(async({db:t,person:n},e)=>(await k(t,n,e)).map(({entry:a})=>a),"publicPool"),ut=l(t=>t?.code===Nt,"lockWaitExpired");function dt(t,n){let e;return Promise.race([n,new Promise((a,i)=>{e=setTimeout(()=>i(new Tt(t)),rt)})]).finally(()=>clearTimeout(e))}l(dt,"withExchangeTimeout");async function z(t){return(await Ut(t)).map(({entry:n})=>n)}l(z,"readSubscriptionPool");async function Ut(t){const n=await y();return(await k(await O(),n,t)).map(({row:e,entry:a})=>({id:e.id,entry:a}))}l(Ut,"readSubscriptionPoolRows");async function Qt(t,n){return R(t,async e=>{const{db:a,person:i,rows:r}=e,s=n.map(d=>S(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??I()})),c=await N(a,i,t);await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await D(a,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await M(a,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await ct(a,i,t,m,f,A,c.get(m)?.find(U=>U.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(Qt,"writeSubscriptionPool");function W(t,n){const e=n.trim().toLowerCase(),a=Number.parseInt(e,10);return Number.isFinite(a)&&String(a)===e&&a>=1&&a<=t.length?a-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(W,"resolve");const P=l((t,n)=>new C(`This ${p(t)} account is already added as \u201C${n}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Ot(t,n){const e=S(t,n);return R(t,async a=>{const{db:i,person:r,rows:s}=a;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new C(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),c=s.find(({entry:d})=>h(d)===o);if(o&&c)throw P(t,c.entry.label);return await M(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),L(a,t)})}l(Ot,"addSubscription");async function Zt(t,n){const e=S(t,n);return(await z(t)).find(i=>_(i.label)===_(e.label))?$t(t,e):Ot(t,e)}l(Zt,"upsertSubscription");async function $t(t,n){const e=S(t,n);return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&h(f)===h(e));if(h(e)&&d)throw P(t,d.entry.label);if(!c)return await M(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),L(a,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await H(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),nt(c.entry,e)&&await D(i,r,t,u.id),L(a,t)})}l($t,"upsertSubscriptionWithUniqueAccount");async function vt(t,n,e){return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=W(s,n);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new C(`${p(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),L(a,t)})}l(vt,"renameSubscription");async function q(t,n,e){return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=n(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await D(i,r,t,c.id),L(a,t)})}l(q,"remove");async function Ct(t,n){return q(t,e=>W(e,n),n)}l(Ct,"removeManagedAccount");async function te(t,n){return q(t,e=>e.findIndex(({row:a})=>a.id===n),n)}l(te,"removeManagedAccountById");async function ee(t,n){return q(t,e=>W(e,n),n)}l(ee,"removeSubscription");async function kt(t){return R(t,async({db:n,person:e,rows:a})=>(await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await D(n,e,t),a.length))}l(kt,"removeAllManagedAccounts");async function ne(t,n){return n===void 0?(await kt(t),[]):Ct(t,n)}l(ne,"removeManagedProvider");async function ae(t,n){return R(t,async e=>{const{db:a,person:i,rows:r}=e,s=W(r,n);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(a,i,{...d.row,position:c});return L(e,t)})}l(ae,"promoteSubscription");async function K(t,n,e){const a=await y();return await F(async i=>{await T(i);const r=await lt(i,a,t,n);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${n}`);await e(i,a,r.row)}),z(t)}l(K,"healthWrite");async function ie(t,n,e=Date.now()){return K(t,n,(a,i,r)=>b(a,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(ie,"markSubscriptionAttempt");async function re(t,n,e,a=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),K(t,n,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,a),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,a)});const d=(await N(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await ct(s,o,t,c.id,r.family,i+e,i)})}l(re,"markSubscriptionRateLimited");async function se(t,n,e=Date.now(),a){const i=yt(a);return K(t,n,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await N(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(se,"markSubscriptionSuccess");async function X(t,n,e){const a=Date.now();await b(t,n,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,a),rateLimitedUntil:Math.max(e.rateLimitedUntil,a+It)})}l(X,"recordInvalidGrant");function oe(t,n,e,a=15e3,i=Date.now()){const r=gt(t),s=At(t,n,i),o=e??r??a;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(oe,"vendorRateLimit");async function le(t,n){return K(t,n,(e,a,i)=>X(e,a,i))}l(le,"markSubscriptionAuthFailure");async function ce(t,n,e){const a=await y();let i;try{i=await F(async r=>{await T(r);const s=await lt(r,a,t,n);if(!s)throw new Error(`${p(t)} subscription "${n}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${p(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await dt(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!Z(d))throw d;return await X(r,a,s.row),{refused:d}}const c=at(it(t,s.entry.label,o),o.clientId??s.entry.clientId);return await H(r,a,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw ut(r)?new st(t,n):r}if("refused"in i)throw i.refused;return i.entry}l(ce,"refreshSubscriptionCredential");async function ue(t,n,e){const a=await y();let i;try{i=await F(async r=>{await T(r);const s=await k(r,a,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=n(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await dt(t,e(u.entry));if(!m)return{entry:u.entry};const f=at(it(t,u.entry.label,m),m.clientId??u.entry.clientId);return await H(r,a,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!Z(m))throw m;c=m,await X(r,a,u.row)}}return c?{refused:c}:{}})}catch(r){throw ut(r)?new st(t,n([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(ue,"modifyElectedSubscription");async function Mt(t,n){const e=n.accountId?.trim(),a=n.email?.trim();if(t!==xt)return{...e?{accountId:e}:{},...a?{email:a}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${n.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Mt,"enrichManagedLoginIdentity");async function de(t,n,e){const a=await Mt(t,e);return R(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:n?.trim(),d=h({refresh:e.refresh,accountId:a.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>h(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=a.email||n?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:_t})=>_(_t.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${p(t)} subscription label cannot be empty`);const f=S(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...a.accountId?{accountId:a.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new C(`${p(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>h(g)===h(f));if(h(f)&&w)throw P(t,w.entry.label);return await M(r,s,t,{providerId:t,id:I(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),L(i,t)}const A=u.row,U=o.find(({entry:w})=>w.label!==u.entry.label&&h(w)===h(f));if(h(f)&&U)throw P(t,U.entry.label);const J=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await H(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:J?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:J?0:A.rateLimitedUntil}),nt(u.entry,f)&&await D(r,s,t,A.id),L(i,t)})}l(de,"commitManagedLogin");const mt=new Map;function ft(t){return{defaultFallbackStrength:tt(t?.default_fallback_strength)??v,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(ft,"rotationFromRow");async function Ht(){const t=await y(),n=ft(await(await O()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return mt.set(t,n),n}l(Ht,"loadRotationConfig"),Rt(()=>Wt());async function Wt(){const t=wt();return t?t.rotation:Ht()}l(Wt,"readRotationConfig");async function me(t){const n=await y(),e=await F(async a=>{await T(a),await a.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(n);const i=ft(await a.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(n)),r={defaultFallbackStrength:tt(t.defaultFallbackStrength)??i.defaultFallbackStrength??v,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await a.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,n),r});return mt.set(n,e),e}l(me,"writeRotationConfig");async function fe(){const t=await y();return(await(await O()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,I())).openai_device_id}l(fe,"openAIDeviceId");async function _e(t,n=Date.now(),e){const a=await z(t),i=a.filter(s=>s.authFailure===void 0&&Lt(s,e)<=n),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${a.length} ready)`}l(_e,"formatStatusLine");export{rt as REFRESH_EXCHANGE_TIMEOUT_MS,st as RefreshBusyError,Tt as RefreshTimeoutError,x as aadOf,Ot as addSubscription,de as commitManagedLogin,Mt as enrichManagedLoginIdentity,_e as formatStatusLine,M as insertAccount,Ht as loadRotationConfig,ie as markSubscriptionAttempt,le as markSubscriptionAuthFailure,re as markSubscriptionRateLimited,se as markSubscriptionSuccess,ue as modifyElectedSubscription,fe as openAIDeviceId,ae as promoteSubscription,Jt as readAllSubscriptionPools,Wt as readRotationConfig,z as readSubscriptionPool,Ut as readSubscriptionPoolRows,ce as refreshSubscriptionCredential,kt as removeAllManagedAccounts,Ct as removeManagedAccount,te as removeManagedAccountById,ne as removeManagedProvider,ee as removeSubscription,vt as renameSubscription,ct as upsertModelCooldown,Zt as upsertSubscription,$t as upsertSubscriptionWithUniqueAccount,oe as vendorRateLimit,me as writeRotationConfig,Qt as writeSubscriptionPool};
@@ -1,6 +1,6 @@
1
- var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{dirname as F}from"node:path";import{clearLedger as $,demoteTranscript as M,freezePreferences as g,loadLedger as P,saveLedger as T}from"../../graph/exposures.js";import{recordWatches as H}from"../../graph/watches.js";import{publishMany as x}from"../../graph/events.js";import{checkoutsForCwd as y}from"../../graph/repo-sync/repos.js";import{liveLookups as W,profileObject as Y,viewRepos as B}from"../../graph/reader.js";import{ownerForGrantee as U}from"../../graph/objects.js";import{resolveName as J}from"../../graph/names.js";import{SCOPE_VOCABULARY as K}from"../../scopes.js";import{getNode as V}from"../../canvas/index.js";import{recordMemoryReadsIn as G}from"../../canvas/memory-reads.js";import{lookupProfile as X}from"../../profiles/manifest.js";import{getDefaultProfileId as z}from"../../profiles/default-binding.js";import{effectiveScopes as Q,profileNameFor as Z,scopeForCwd as q}from"../subject-fields.js";import{spineDepth as ee}from"../subject.js";import{appForNode as te}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as ne}from"../../canvas/paths.js";import{readableProjectForScopes as oe}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as re}from"../../runtime/bearings.js";import{deliveryDocOf as b,listingCorpora as ae,loadCorpus as w,nodeSubject as j,primeBodies as ie,viewOwners as se}from"./corpus.js";import{listingPrefixes as ce}from"./listings.js";import{planDelivery as de}from"./plan.js";import{renderEvent as N,renderExplicitRead as k}from"./render-event.js";import{renderConfigDelta as le,renderKnowledge as pe,renderPreferences as O,renderWorkspaceOpen as _}from"./render-boot.js";import{mapAsync as S}from"../../async-array.js";function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const R="hypothetical";function v(t){return t.node.id===R}l(v,"isHypothetical");async function E(t,e){if(!v(e))return await te(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(E,"granteeOf");async function ue(t,e,n,o=async(a,d)=>await y(t,a,d)){const a=f(e).node,d=new Set,r=new Date().toISOString(),s=[],i=[];for(const{doc:c,level:p}of n)p!=="content"||d.has(c.object.id)||(d.add(c.object.id),i.push({watcher:a,object:c.object,start:"deliver",opts:{readHeadsKey:c.headsKey}}),s.push({name:c.name,scope:c.ownerHandle,at:r,type:"loaded"}));await H(t,i),await x(t,i.map(c=>({event:"read",object:c.object,actor:a,attrs:{}})),o),v(f(e))||await G(t,a.id,s)}l(ue,"recordContentDelivery");async function D(t,e,n){const o=(await y(t,F(n))).filter(a=>!e.repos.some(d=>d.id===a.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(a=>a.repo)],checkouts:[...e.checkouts,...o]}}l(D,"fileReadReader");async function me(t,e,n){const o=await E(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||oe(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(me,"assertReadableFile");async function fe(t){const e=f(t.reader),n=e.node,o=await E(t.db,e),a=await w(t.db,t.reader,["slash-command"]);await ie(t.db,a);const d=await S(a,async r=>{const s=await r.body();return{name:r.displayName,command_name:r.displayName,description:r.preview,canonical_body:s,execution_body:ne(s,n.id,o)}});return{docs:a,commands:d}}l(fe,"slashCommands");function we(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(we,"scopeOf");async function ye(t,e){const n=[],o=new Set,a=await se(t,e),d=await ae(t,e,a);for(const r of a){const s=d.get(r.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:we(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const c=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of ce(s,i.name))o.add(`${c}${p}`)}}return{refs:n,names:[...o]}}l(ye,"composerNames");async function C(t,e){const n=f(t.reader),{db:o,ledger:a}=t,d=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[i,c]of a.objects)if(c.transcript===void 0)a.objects.delete(i);else{const{system:p,...u}=c;a.objects.set(i,u)}for(const[i,c]of a.listed)c.transcript===void 0?a.listed.delete(i):a.listed.set(i,{transcript:c.transcript});return a.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const r=v(n)?await ve(t):await re(n.node.id,t),s=await O({...t,channel:"system"});return g(a,s.content),{result:{content:r.content},delivered:[...r.delivered,...s.delivered]}}case"system-prompt":{if(a.preferenceSnapshot!==null)return{result:{content:a.preferenceSnapshot},delivered:[]};const r=await O({...t,channel:"system"});return{result:{content:g(a,r.content)},delivered:r.delivered}}case"compact":{for(const r of await w(o,n,["pre-command"]))M(a,r.object.id);return{result:{content:""},delivered:[]}}case"persona":{const r=await le(t);return{result:{content:r.content},delivered:r.delivered}}case"file-read":{const r=d();await me(o,n,r);const s=await D(o,n,r),i={...t,reader:s},c=await N(i,"file-read",{absoluteFile:r},await w(o,s,["file-read"]));return{result:{content:c.content},delivered:c.delivered}}case"command":case"pre-command":{const r=await N(t,e.activity,{command:d()});return{result:{content:r.content},delivered:r.delivered}}case"slash-command":{const{docs:r,commands:s}=await fe(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=r.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(i<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const c=r[i],p=await k(t,c,!0);return{result:{content:"",execution_body:s[i].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:c,level:"content"},...p.delivered]}}case"workspace-open":{const r=await _(t);return{result:{content:r.content},delivered:r.delivered}}case"document-read":{const r=await I(o,n,d()),s=await k(t,await b(o,n,r),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await ye(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(C,"render");async function ve(t){const e=await pe(t),n=await _(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
- `),delivered:[...e.delivered,...n.delivered]}}l(ve,"hypotheticalBearings");async function I(t,e,n){const o=await J(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(I,"readDocument");const he=["workspace-open","document-read"];async function Ge(t,e,n){if(he.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const o=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await $(t,o.id);const a=await P(t,o.id),d={db:t,reader:e,subject:await j(t,e),ledger:a,channel:"transcript"},{result:r,delivered:s}=await C(d,n);return await ue(t,e,s),await T(t,a),r}l(Ge,"deliver");const ge={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function Xe(t,e){const n=await V(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await ee(t)}}l(Xe,"hypotheticalFrom");function be(t,e){if(t===null)return null;if(t===void 0||t==="")return z(e);const n=X(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(be,"resolveProfileId");async function ze(t,e){const n=await U(t,e.grantee??"app:terminal"),o=be(e.profile,e.cwd),a=await B(t,e.cwd,o,async(p,u)=>await y(t,p,u),W(t)),{repos:d}=a,r=e.mode??"base",i={class:"node",node:{id:R,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...K],cwd:e.cwd,...a,profile:o===null?null:await Y(t,o,n)},c={kind:e.kind??"general",mode:r,lifecycle:e.lifecycle??(r==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:q(e.cwd),orchestration:{depth:e.depth??0},profile:Z(o),app:e.grantee??"app:terminal",scopes:Q(null),repo:[...d,...a.projectRepos].map(p=>p.name)};return{reader:i,subject:c}}l(ze,"hypotheticalReader");async function Qe(t,e,n,o,a){const r={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...a??await j(t,e),...o},i={db:t,reader:e,subject:s,ledger:r,channel:"transcript"},{result:c}=await C(i,n),p=ge[n.activity];let u=null;if(p!==void 0){const A=n.activity==="file-read"?{absoluteFile:n.subject}:n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await b(t,e,await I(t,e,n.subject))}:{},h=n.activity==="file-read"&&n.subject!==void 0?await D(t,f(e),n.subject):e;u=await de(t,s,h,await w(t,h,[p]),p,A)}return{result:c,plan:u}}l(Qe,"inspect");async function Ze(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
1
+ var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});import{dirname as P}from"node:path";import{isCloudRole as T}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as H}from"../../runtime/runner/machine/environment.js";import{clearLedger as W,demoteTranscript as x,freezePreferences as j,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as y}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as ae}from"../subject-fields.js";import{spineDepth as re}from"../subject.js";import{appForNode as ie}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as k}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce}from"../../runtime/bearings.js";import{deliveryDocOf as N,listingCorpora as de,loadCorpus as w,nodeSubject as O,primeBodies as le,viewOwners as pe}from"./corpus.js";import{listingPrefixes as ue}from"./listings.js";import{planDelivery as me}from"./plan.js";import{renderEvent as R,renderExplicitRead as _}from"./render-event.js";import{renderConfigDelta as fe,renderKnowledge as we,renderPreferences as S,renderWorkspaceOpen as E}from"./render-boot.js";import{mapAsync as D}from"../../async-array.js";function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const C="hypothetical";function h(t){return t.node.id===C}l(h,"isHypothetical");async function v(t,e){if(!h(e))return await ie(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(v,"granteeOf");async function ye(t,e,n,o=async(a,d)=>await y(t,a,d)){const a=f(e).node,d=new Set,r=new Date().toISOString(),s=[],i=[];for(const{doc:c,level:p}of n)p!=="content"||d.has(c.object.id)||(d.add(c.object.id),i.push({watcher:a,object:c.object,start:"deliver",opts:{readHeadsKey:c.headsKey}}),s.push({name:c.name,scope:c.ownerHandle,at:r,type:"loaded"}));await U(t,i),await J(t,i.map(c=>({event:"read",object:c.object,actor:a,attrs:{}})),o),h(f(e))||await q(t,a.id,s)}l(ye,"recordContentDelivery");async function I(t,e,n){if(await g(t,e,n))return e;const o=(await y(t,P(n))).filter(a=>!e.repos.some(d=>d.id===a.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(a=>a.repo)],checkouts:[...e.checkouts,...o]}}l(I,"fileReadReader");async function g(t,e,n){const o=await v(t,e);return o==="app:terminal"&&T()&&e.profile!=null&&await H(e.profile.id)!==null&&!k(n,o,e.scopes??[],null)}l(g,"isMacEnforcedRead");async function A(t,e,n){if(!await g(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:a,repo:d}of e.checkouts)n.startsWith(a.endsWith("/")?a:`${a}/`)&&!o.has(d.id)&&o.set(d.id,a);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(A,"fileReadPayload");async function he(t,e,n){const o=await v(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await g(t,e,n)||k(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(he,"assertReadableFile");async function ve(t){const e=f(t.reader),n=e.node,o=await v(t.db,e),a=await w(t.db,t.reader,["slash-command"]);await le(t.db,a);const d=await D(a,async r=>{const s=await r.body();return{name:r.displayName,command_name:r.displayName,description:r.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:a,commands:d}}l(ve,"slashCommands");function ge(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(ge,"scopeOf");async function be(t,e){const n=[],o=new Set,a=await pe(t,e),d=await de(t,e,a);for(const r of a){const s=d.get(r.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:ge(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const c=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of ue(s,i.name))o.add(`${c}${p}`)}}return{refs:n,names:[...o]}}l(be,"composerNames");async function F(t,e){const n=f(t.reader),{db:o,ledger:a}=t,d=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[i,c]of a.objects)if(c.transcript===void 0)a.objects.delete(i);else{const{system:p,...u}=c;a.objects.set(i,u)}for(const[i,c]of a.listed)c.transcript===void 0?a.listed.delete(i):a.listed.set(i,{transcript:c.transcript});return a.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const r=h(n)?await je(t):await ce(n.node.id,t),s=await S({...t,channel:"system"});return j(a,s.content),{result:{content:r.content},delivered:[...r.delivered,...s.delivered]}}case"system-prompt":{if(a.preferenceSnapshot!==null)return{result:{content:a.preferenceSnapshot},delivered:[]};const r=await S({...t,channel:"system"});return{result:{content:j(a,r.content)},delivered:r.delivered}}case"compact":{for(const r of await w(o,n,["pre-command"]))x(a,r.object.id);return{result:{content:""},delivered:[]}}case"persona":{const r=await fe(t);return{result:{content:r.content},delivered:r.delivered}}case"file-read":{const r=d();await he(o,n,r);const s=await I(o,n,r),i={...t,reader:s},c=await R(i,"file-read",await A(o,n,r),await w(o,s,["file-read"]));return{result:{content:c.content},delivered:c.delivered}}case"command":case"pre-command":{const r=await R(t,e.activity,{command:d()});return{result:{content:r.content},delivered:r.delivered}}case"slash-command":{const{docs:r,commands:s}=await ve(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=r.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(i<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const c=r[i],p=await _(t,c,!0);return{result:{content:"",execution_body:s[i].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:c,level:"content"},...p.delivered]}}case"workspace-open":{const r=await E(t);return{result:{content:r.content},delivered:r.delivered}}case"document-read":{const r=await L(o,n,d()),s=await _(t,await N(o,n,r),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await be(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(F,"render");async function je(t){const e=await we(t),n=await E(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
+ `),delivered:[...e.delivered,...n.delivered]}}l(je,"hypotheticalBearings");async function L(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(L,"readDocument");const ke=["workspace-open","document-read"];async function et(t,e,n){if(ke.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const o=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await W(t,o.id);const a=await Y(t,o.id),d={db:t,reader:e,subject:await O(t,e),ledger:a,channel:"transcript"},{result:r,delivered:s}=await F(d,n);return await ye(t,e,s),await B(t,a),r}l(et,"deliver");const Ne={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function tt(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await re(t)}}l(tt,"hypotheticalFrom");function Oe(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Oe,"resolveProfileId");async function nt(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Oe(e.profile,e.cwd),a=await G(t,e.cwd,o,async(p,u)=>await y(t,p,u),K(t)),{repos:d}=a,r=e.mode??"base",i={class:"node",node:{id:C,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...a,profile:o===null?null:await V(t,o,n)},c={kind:e.kind??"general",mode:r,lifecycle:e.lifecycle??(r==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:ae(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...d,...a.projectRepos].map(p=>p.name)};return{reader:i,subject:c}}l(nt,"hypotheticalReader");async function ot(t,e,n,o,a){const r={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...a??await O(t,e),...o},i={db:t,reader:e,subject:s,ledger:r,channel:"transcript"},{result:c}=await F(i,n),p=Ne[n.activity];let u=null;if(p!==void 0){const M=n.activity==="file-read"?await A(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await N(t,e,await L(t,e,n.subject))}:{},b=n.activity==="file-read"&&n.subject!==void 0?await I(t,f(e),n.subject):e;u=await me(t,s,b,await w(t,b,[p]),p,M)}return{result:c,plan:u}}l(ot,"inspect");async function at(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
3
3
  FROM watches w JOIN objects o ON o.id = w.object AND o.type = 'document' AND o.deleted_at IS NULL
4
4
  JOIN revisions r ON r.document = o.id LEFT JOIN objects a ON a.id = r.author
5
5
  WHERE w.watcher = ? AND r.created_at > ? AND (r.author IS NULL OR r.author != ?)
6
- GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await S(o,async({to_seq:a,authors:d,...r})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(r.id,n);return{doc:r,from:s.seq,to:a,authors:d===null?[]:d.split(",")}})}l(Ze,"changedWhileDone");export{he as DRY_RUN_ONLY,Ze as changedWhileDone,Ge as deliver,Xe as hypotheticalFrom,ze as hypotheticalReader,Qe as inspect,ue as recordContentDelivery};
6
+ GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await D(o,async({to_seq:a,authors:d,...r})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(r.id,n);return{doc:r,from:s.seq,to:a,authors:d===null?[]:d.split(",")}})}l(at,"changedWhileDone");export{ke as DRY_RUN_ONLY,at as changedWhileDone,et as deliver,tt as hypotheticalFrom,nt as hypotheticalReader,ot as inspect,ye as recordContentDelivery};
@@ -12,6 +12,10 @@ export interface DeliveryPayload {
12
12
  absoluteFile?: string;
13
13
  /** `file-read`: the read file's frontmatter; parsed from the file when omitted. */
14
14
  readFrontmatter?: Record<string, unknown>;
15
+ /** `file-read`: checkout root of each repo (by id) enclosing the file; computed from the file's disk when omitted. */
16
+ repoRoots?: ReadonlyMap<string, string>;
17
+ /** `file-read`: the file lives on another machine, so the planner must not realpath it or look at it on this disk. */
18
+ remotePath?: boolean;
15
19
  /** `document-read`: the document delivered or read; it never delivers to itself. */
16
20
  doc?: DeliveryDoc;
17
21
  /** `command` / `pre-command`: the command string. */
@@ -1,2 +1,2 @@
1
- var p=Object.defineProperty;var u=(e,r)=>p(e,"name",{value:r,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChainOf as b}from"../../checkout-identities.js";import{readableRepos as k}from"../../graph/repo-sync/repos.js";import{minRung as O,rungAtLeast as F,rungRank as m}from"../schema.js";import{ruleConstraintsFit as v,ruleGate as y}from"./match.js";import{personIdAsync as N}from"../../canvas/person.js";function x(e){return e.doc.ownNode?"knowledge":e.doc.kind}u(x,"bootPartitionOf");async function H(e,r,n,i,t,a={}){const o=await A(e,t,a),d=(t==="document-read"&&a.doc!==void 0?i.filter(l=>l.object.id!==a.doc.object.id):i).map(l=>W(l,r,t,o));return j(t,d),{on:t,subject:r,reader:n,docs:d}}u(H,"planDelivery");async function A(e,r,n){if(r!=="file-read"||n.absoluteFile===void 0)return n;const i=R(n.absoluteFile);return{...n,absoluteFile:i,readFrontmatter:n.readFrontmatter??E(i),repoRoots:await S(e,i)}}u(A,"resolvePayload");function E(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}u(E,"readFileFrontmatter");async function S(e,r){const n=new Map;let i;const t=u(async()=>i??=await N(),"personOf");for(const o of await b(e,h(r),t)){if(!o.ok)break;for(const s of(await k(e,await t(),o.scheme,o.externalId)).readable)n.has(s.id)||n.set(s.id,o.root)}const a=await e.prepare(`SELECT o.id, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:o,path:s,person:d}of a)!n.has(o)&&r.startsWith(s.endsWith("/")?s:`${s}/`)&&d===await t()&&n.set(o,s);return n}u(S,"repoRootsOf");function W(e,r,n,i){const t=e.rules.filter(c=>c.on===n).map(c=>{const f=y(c,r);return{rule:c,gate:f,matched:f.pass&&v(c,e,n,i)}});let a=null;for(const{rule:c,matched:f}of t)f&&(a===null||m(c.deliver)>m(a.deliver))&&(a=c);const o=a?.deliver??"none",s=(n==="boot"||n==="workspace-open")&&!e.ownNode?e.limit:null,d=s===null?o:O(o,s),l=n==="boot"&&e.ownNode&&t.length===0?"name":d;return{doc:e,authoredRules:t,matchedRule:a,authoredRung:o,limit:s,cappedRung:d,ruleGate:t.length===0?null:a!==null?{pass:!0}:t.find(c=>!c.gate.pass)?.gate??{pass:!0},finalRung:l,winner:!1,shadowedBy:null}}u(W,"decide");function $(e,r){if(r==="boot"){const n=e.authoredRules.length>0&&e.authoredRules.every(i=>!i.gate.pass);return e.limit!=="none"&&!n}return F(e.finalRung,"name")}u($,"holdsName");function j(e,r){const n=e==="boot"||e==="workspace-open",i=new Map;for(const t of r){if(!$(t,e))continue;if(!n){t.winner=!0;continue}const a=e==="boot"?`${x(t)}:${t.doc.name}`:t.doc.name,o=i.get(a);o===void 0?(i.set(a,t),t.winner=!0):t.shadowedBy=o.doc}}u(j,"resolveWinners");export{x as bootPartitionOf,H as planDelivery};
1
+ var p=Object.defineProperty;var u=(e,r)=>p(e,"name",{value:r,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChainOf as b}from"../../checkout-identities.js";import{readableRepos as k}from"../../graph/repo-sync/repos.js";import{minRung as O,rungAtLeast as F,rungRank as m}from"../schema.js";import{ruleConstraintsFit as v,ruleGate as N}from"./match.js";import{personIdAsync as x}from"../../canvas/person.js";function y(e){return e.doc.ownNode?"knowledge":e.doc.kind}u(y,"bootPartitionOf");async function H(e,r,t,i,n,a={}){const o=await A(e,n,a),d=(n==="document-read"&&a.doc!==void 0?i.filter(l=>l.object.id!==a.doc.object.id):i).map(l=>W(l,r,n,o));return j(n,d),{on:n,subject:r,reader:t,docs:d}}u(H,"planDelivery");async function A(e,r,t){if(r!=="file-read"||t.absoluteFile===void 0||t.remotePath)return t;const i=R(t.absoluteFile);return{...t,absoluteFile:i,readFrontmatter:t.readFrontmatter??E(i),repoRoots:await S(e,i)}}u(A,"resolvePayload");function E(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}u(E,"readFileFrontmatter");async function S(e,r){const t=new Map;let i;const n=u(async()=>i??=await x(),"personOf");for(const o of await b(e,h(r),n)){if(!o.ok)break;for(const s of(await k(e,await n(),o.scheme,o.externalId)).readable)t.has(s.id)||t.set(s.id,o.root)}const a=await e.prepare(`SELECT o.id, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:o,path:s,person:d}of a)!t.has(o)&&r.startsWith(s.endsWith("/")?s:`${s}/`)&&d===await n()&&t.set(o,s);return t}u(S,"repoRootsOf");function W(e,r,t,i){const n=e.rules.filter(c=>c.on===t).map(c=>{const f=N(c,r);return{rule:c,gate:f,matched:f.pass&&v(c,e,t,i)}});let a=null;for(const{rule:c,matched:f}of n)f&&(a===null||m(c.deliver)>m(a.deliver))&&(a=c);const o=a?.deliver??"none",s=(t==="boot"||t==="workspace-open")&&!e.ownNode?e.limit:null,d=s===null?o:O(o,s),l=t==="boot"&&e.ownNode&&n.length===0?"name":d;return{doc:e,authoredRules:n,matchedRule:a,authoredRung:o,limit:s,cappedRung:d,ruleGate:n.length===0?null:a!==null?{pass:!0}:n.find(c=>!c.gate.pass)?.gate??{pass:!0},finalRung:l,winner:!1,shadowedBy:null}}u(W,"decide");function $(e,r){if(r==="boot"){const t=e.authoredRules.length>0&&e.authoredRules.every(i=>!i.gate.pass);return e.limit!=="none"&&!t}return F(e.finalRung,"name")}u($,"holdsName");function j(e,r){const t=e==="boot"||e==="workspace-open",i=new Map;for(const n of r){if(!$(n,e))continue;if(!t){n.winner=!0;continue}const a=e==="boot"?`${y(n)}:${n.doc.name}`:n.doc.name,o=i.get(a);o===void 0?(i.set(a,n),n.winner=!0):n.shadowedBy=o.doc}}u(j,"resolveWinners");export{y as bootPartitionOf,H as planDelivery};
@@ -1,7 +1,18 @@
1
- import type { BrokerExtensionNodeDTO } from '../../../api/dto/broker-ops.js';
1
+ import type { BrokerCycleStartRequest, BrokerCycleStartResultDTO, BrokerExtensionNodeDTO, BrokerExtensionStateDTO } from '../../../api/dto/broker-ops.js';
2
2
  import { getNode } from '../../../core/canvas/canvas.js';
3
3
  import { type RouteTable } from '../router.js';
4
+ import type { StartDataDTO } from '../../../api/dto/execution-start.js';
4
5
  export declare function extensionNode(node: NonNullable<Awaited<ReturnType<typeof getNode>>>): Promise<BrokerExtensionNodeDTO>;
6
+ /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
7
+ * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
8
+ * or system prompt until the bind commits. */
9
+ export declare function renderStartData(nodeId: string, bearings: BrokerCycleStartRequest['bearings'], namesOnly: boolean, warmed?: boolean): Promise<{
10
+ state: BrokerExtensionStateDTO;
11
+ delivery: Pick<BrokerCycleStartResultDTO, 'names' | 'boot' | 'system_prompt'>;
12
+ }>;
13
+ /** The start data a broker launched with a carried bundle opens its first cycle with: what `cycle-start` answers a fresh, unbound-nothing launch.
14
+ * The caller has already warmed the node's checkout identities, because that may ask the Mac and must not run inside its open transaction. */
15
+ export declare function renderCarriedStart(nodeId: string): Promise<StartDataDTO>;
5
16
  /** crtrd sets this once at boot from its role: only a process that runs the reconciler lanes starts run observers (an api
6
17
  * process leaves them to `pollRunObservers` in the reconcile process). */
7
18
  export declare function setRequestsStartRunObservers(enabled: boolean): void;