@north-light/cli 0.3.712 → 0.3.714

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 (113) hide show
  1. package/dist/clients/attach/input/controller.d.ts +8 -0
  2. package/dist/clients/attach/input/controller.js +3 -3
  3. package/dist/clients/attach/input/local-files.d.ts +18 -0
  4. package/dist/clients/attach/input/local-files.js +11 -0
  5. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/editor-frame.d.ts +2 -2
  8. package/dist/clients/attach/session/editor-frame.js +1 -1
  9. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  10. package/dist/clients/attach/session/input-wiring.js +1 -1
  11. package/dist/clients/attach/viewer.js +526 -517
  12. package/dist/commands/node/bash.js +1 -1
  13. package/dist/commands/node/inspect.js +5 -5
  14. package/dist/core/bash-guard.d.ts +10 -0
  15. package/dist/core/bash-guard.js +4 -4
  16. package/dist/core/broker-client/client.d.ts +2 -2
  17. package/dist/core/broker-client/client.js +1 -1
  18. package/dist/core/canvas/canvas.js +1 -1
  19. package/dist/core/canvas/deliveries.js +10 -10
  20. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  21. package/dist/core/canvas/schema-version.d.ts +1 -1
  22. package/dist/core/canvas/schema-version.js +1 -1
  23. package/dist/core/canvas/types.d.ts +1 -0
  24. package/dist/core/checkout-identities.js +1 -1
  25. package/dist/core/conversation-store/row-store.js +1 -1
  26. package/dist/core/graph/documents.d.ts +5 -5
  27. package/dist/core/graph/documents.js +9 -9
  28. package/dist/core/graph/kinds/custom.js +2 -2
  29. package/dist/core/graph/kinds/document.js +4 -4
  30. package/dist/core/graph/kinds/environment.js +2 -2
  31. package/dist/core/graph/kinds/job.js +2 -2
  32. package/dist/core/graph/kinds/kind.d.ts +9 -1
  33. package/dist/core/graph/kinds/live-read.d.ts +4 -2
  34. package/dist/core/graph/kinds/live-read.js +1 -1
  35. package/dist/core/graph/kinds/node.js +5 -5
  36. package/dist/core/graph/kinds/owner.js +2 -2
  37. package/dist/core/import/load/bind.d.ts +8 -0
  38. package/dist/core/import/load/bind.js +15 -15
  39. package/dist/core/import/load/prepare.d.ts +8 -1
  40. package/dist/core/import/load/prepare.js +9 -7
  41. package/dist/core/import/load/run.js +2 -2
  42. package/dist/core/llm/run.d.ts +1 -1
  43. package/dist/core/pool-credential-store.d.ts +5 -5
  44. package/dist/core/runtime/bearings-render.d.ts +3 -0
  45. package/dist/core/runtime/bearings-render.js +7 -7
  46. package/dist/core/runtime/bearings.js +5 -5
  47. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  48. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  49. package/dist/core/runtime/broker/frame-read.d.ts +5 -1
  50. package/dist/core/runtime/broker/frame-read.js +1 -1
  51. package/dist/core/runtime/broker-protocol.d.ts +37 -2
  52. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  53. package/dist/core/runtime/broker-wedge.js +2 -2
  54. package/dist/core/subscription-state.d.ts +3 -3
  55. package/dist/core/subscription-state.js +1 -1
  56. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  57. package/dist/daemon/api/handlers/llm.js +3 -3
  58. package/dist/daemon/api/handlers/objects.js +3 -3
  59. package/dist/daemon/api/handlers/reviews.js +1 -1
  60. package/dist/daemon/api/map.d.ts +6 -0
  61. package/dist/daemon/api/map.js +1 -1
  62. package/dist/daemon/fleet.d.ts +1 -12
  63. package/dist/daemon/fleet.js +2 -2
  64. package/dist/daemon/machine-daemon.js +1 -1
  65. package/dist/daemon/machine-link/holder.js +1 -1
  66. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  67. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  68. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  69. package/docs/ci-runner.md +4 -4
  70. package/package.json +3 -3
  71. package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
  72. package/packages/crouter-api/dist/clients/attach/input/local-files.js +113 -0
  73. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  74. package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
  75. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  76. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  77. package/packages/crouter-api/dist/commands/node/bash.js +2 -2
  78. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  79. package/packages/crouter-api/dist/core/bash-guard.js +1 -1
  80. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  81. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  82. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  83. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  84. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  85. package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
  86. package/packages/crouter-api/dist/core/graph/documents.js +12 -24
  87. package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
  88. package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
  89. package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
  90. package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
  91. package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
  92. package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
  93. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  94. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  95. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  96. package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
  97. package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
  98. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  99. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  100. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -6
  101. package/packages/crouter-api/dist/daemon/api/map.js +1 -1
  102. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  103. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  104. package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
  105. package/packages/crouter-api/package.json +1 -1
  106. package/packages/crouter-identity/package.json +1 -1
  107. package/packages/crouter-plugin/package.json +3 -3
  108. package/runtime.lock.json +14 -14
  109. package/scripts/install-runtime.mjs +3 -2
  110. package/scripts/self-update.mjs +5 -1
  111. package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
  112. /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
  113. /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var m=(e,i)=>X(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,checkSourcePerson as _e,checkStagedBlobKeys as we,checkStagedPersons as ge,checkStagedReferences as be,checkStagedRequestKeys as he}from"./bind.js";import{deleteBlobs as ye,deleteRunBlobs as Ee,deleteRunPrefix as Se,moveRunBlobs as ve}from"./blobs.js";import{dropStubRows as Re,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Ie,renameClashingRepos as Te,rewriteIds as je,rewritePerson as ke,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Ae,stagingSchema as Ce,targetSchema as Me}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as Le,writeNodeFiles as Be}from"./path-map.js";import{allStoreKeys as We,readPluginsStore as He,recordImportedActivations as Ke,writeStores as Ue}from"./stores.js";import{publishImportedPlugins as Fe}from"./publish-plugins.js";import{COPIED_TABLES as Je}from"../bundle/layout.js";import{emitEvent as qe}from"../../events/emit.js";import{ClaimLostError as $e}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,Ge=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,i)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Ye(e,i){const t=await e.get(N.source(i));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Ye,"readSource");async function ze(e,i,t,a,n,p){const r=[];for(const c of L(t.run_id,"grants",a)){const f=await e.get(c);if(f===null)throw new g("stage","bundle_invalid",`row file ${c} is missing`);r.push(...ne(f))}const o=[];for(const c of r){const f=me(c.sub,a.person,t.person,"grants.sub");await Oe(i,n,p,f,c.grantee)===void 0&&o.push(c.grantee)}if(o.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Pe(o);return!1}m(ze,"grantsReady");async function Et(e,i,t={}){const a=t.blobs??await x(),n=await v(),p=Ce(e.run_id);let r="start";const o=m(async s=>{r=s,await i.assertOwned(),await O(e.run_id,s),await t.atStep?.(s)},"at");let c=e.state==="committed";const f=[];try{const s=await Ye(a,e.run_id);if(e.source_kind==="machine"&&s.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${s.installId}, the run is for ${e.source_install_id}`);s.installId=e.source_install_id;const l=await Me(n),P=[...Je],b=await se(n,l,[...P,"grants"]);if(!c){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await _e(n,l,s.person,e.person),!await ze(a,n,e,s,l,k)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await o("publish-plugins");const F=await He(a,e.run_id),y=await ee(e.person,()=>Fe(F));if(y.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...y.refused),await o("stage");const J=await Ae(n,e.run_id,s.counts,d=>L(e.run_id,d,s),d=>a.get(d));for(const[d,u]of Object.entries(J))_[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:l,catalog:b,sourcePerson:s.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:s.shippedBodies??{}};await o("bind-staged");for(const[d,u]of Object.entries(await ge(w)))E(_,d,u);for(const[d,u]of Object.entries(await we(w)))E(_,d,u);await o("rewrite-person"),await ke(w),await De(w),await o("prune");const q=await oe(n,p,b,s),S=s.kind==="hosted"?Le(s.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(n,p,S),await ue(n,p,S,a,e.run_id),await le(n,p),await he(w);const $=await Ie(w);await pe(n,p,l,s.installId,e.person),await o("rewrite-ids");const D=await je(w,$);await o("drop");const G=await fe(n,p,l),Y=await Re(w);for(const[d,u]of Object.entries({...q}))E(_,d,u);for(const[d,u]of Object.entries(Y))E(_,d,u);await be(w,{installId:s.installId,person:e.person,runId:e.run_id}),await Te(w),await o("pre-check");const z=new Map([["messages",["seq"]],...ie.map(d=>[d,["seq"]])]);await de(n,p,l,b,P,new Set,z),await o("blobs"),await ve(n,p,l,e.person,a,e.run_id,f),await o("copy"),await M(async d=>{await i.assertOwned({extendLeaseMs:Ge});const u=await re({db:d,runId:e.run_id,schema:p,target:l,catalog:b,source:s,person:e.person,idMap:D,pathMap:S}),A=await Xe(d,e.run_id,G);A>0&&(u.inserted.revisions=(u.inserted.revisions??0)+A),await Be(d,p,e.run_id,s);const C=await Ue({db:d,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(C.inserted))u.inserted[Q]=V.length;return T.push(...C.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ve(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),c=!0,await t.atStep?.("committed")}await o("verify");const h=await Ne(n,e.run_id,p,l,b,s.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(h),e.run_id),!h.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:h.differences,invariants:h.invariants});await o("manifest");const I=N.manifest(e.run_id);await a.put(I,await Ze(e.run_id)),await H(n,e.run_id);for(const _ of We(e.run_id))await a.delete(_);await Ee(a,e.run_id),await M(async _=>{await Ke(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(I,R(),e.run_id)})}catch(s){if(s instanceof $e)throw s;const l=Qe(s,r);qe({level:"error",event:"import.run.failed",error:s,fields:{run_id:e.run_id,step:l.step,code:l.code}}),await H(n,e.run_id).catch(()=>{}),c||await ye(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(l),R(),e.run_id),await Se(a,e.run_id,{keepNodeFiles:c,bestEffort:!0})}}m(Et,"processRun");function Qe(e,i){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:i,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Qe,"failureOf");function E(e,i,t){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(E,"addDropped");function Ve(e,i){for(const[t,a]of Object.entries(i.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(i.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ve,"withInserted");async function Xe(e,i,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(r=>r.rev_id)))).map(r=>r.rev_id)),n=t.filter(r=>!a.has(r.rev_id)),p=new Map;for(const r of t)p.set(r.document,[...p.get(r.document)??[],r]);for(const[r,o]of p){const c=await ae(e,r);c!==null&&await te(e,c,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,i,"revisions",n.map(r=>[r.rev_id])),await U(e,i,"revision_parents",n.flatMap(r=>r.parents.map(o=>[r.rev_id,o]))),n.length}m(Xe,"arrive");async function U(e,i,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),i,t)}m(U,"appendManifest");async function Ze(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
1
+ var X=Object.defineProperty;var m=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ue,rewriteConversationHeaders as ce,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Ee}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Pe,grantMissing as Te,mapProfileIds as je,renameClashingRepos as ke,rewriteIds as De,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Me,stagingSchema as Ne,targetSchema as Le}from"./stage.js";import{verifyRun as Be}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ge}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,ze=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Qe(e,s){const t=await e.get(N.source(s));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Qe,"readSource");async function Ve(e,s,t,a,n,p){const o=[];for(const l of L(t.run_id,"grants",a)){const f=await e.get(l);if(f===null)throw new g("stage","bundle_invalid",`row file ${l} is missing`);o.push(...ne(f))}const d=[];for(const l of o){const f=_e(l.sub,a.person,t.person,"grants.sub");await Pe(s,n,p,f,l.grantee)===void 0&&d.push(l.grantee)}if(d.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Te(d);return!1}m(Ve,"grantsReady");async function vt(e,s,t={}){const a=t.blobs??await x(),n=await v(),p=Ne(e.run_id);let o="start";const d=m(async i=>{o=i,await s.assertOwned(),await O(e.run_id,i),await t.atStep?.(i)},"at");let l=e.state==="committed";const f=[];try{const i=await Qe(a,e.run_id);if(e.source_kind==="machine"&&i.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${i.installId}, the run is for ${e.source_install_id}`);i.installId=e.source_install_id;const c=await Le(n),I=[...$e],b=await se(n,c,[...I,"grants"]);if(!l){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ge(n,c,i.person,e.person),!await Ve(a,n,e,i,c,k)){await s.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await d("publish-plugins");const F=await Ue(a,e.run_id),E=await ee(e.person,()=>qe(F));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...E.refused),await d("stage");const J=await Me(n,e.run_id,i.counts,r=>L(e.run_id,r,i),r=>a.get(r));for(const[r,u]of Object.entries(J))_[r]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:c,catalog:b,sourcePerson:i.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:i.shippedBodies??{}};await d("bind-staged");for(const[r,u]of Object.entries(await he(w)))h(_,r,u);for(const[r,u]of Object.entries(await be(w)))h(_,r,u);await d("rewrite-person"),await Ce(w),await Ae(w),await d("prune");const q=await oe(n,p,b,i),S=i.kind==="hosted"?We(i.pathPrefixes??[]):[];await d("rewrite-paths"),await le(n,p,S),await ce(n,p,S,a,e.run_id),await fe(n,p),await Ee(w);const $=await je(w);await ue(n,p,c,i.installId,e.person),await d("rewrite-ids");const D=await De(w,$);await d("drop");const G=await me(n,p,c),Y=await Ie(w);for(const[r,u]of Object.entries({...q}))h(_,r,u);for(const[r,u]of Object.entries(Y))h(_,r,u);for(const[r,u]of Object.entries(await we(w,{installId:i.installId,person:e.person,runId:e.run_id})))h(_,r,u);await ye(w,{installId:i.installId,person:e.person,runId:e.run_id}),await ke(w),await pe(n,p,c,i.installId),await d("pre-check");const z=new Map([["messages",["seq"]],...ie.map(r=>[r,["seq"]])]);await de(n,p,c,b,I,new Set,z),await d("blobs"),await Oe(n,p,c,e.person,a,e.run_id,f),await d("copy"),await M(async r=>{await s.assertOwned({extendLeaseMs:ze});const u=await re({db:r,runId:e.run_id,schema:p,target:c,catalog:b,source:i,person:e.person,idMap:D,pathMap:S}),C=await xe(r,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,i);const A=await Je({db:r,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.length;return T.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ze(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),l=!0,await t.atStep?.("committed")}await d("verify");const y=await Be(n,e.run_id,p,c,b,i.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const P=N.manifest(e.run_id);await a.put(P,await et(e.run_id)),await H(n,e.run_id);for(const _ of Ke(e.run_id))await a.delete(_);await ve(a,e.run_id),await M(async _=>{await Fe(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,R(),e.run_id)})}catch(i){if(i instanceof Ye)throw i;const c=Xe(i,o);Ge({level:"error",event:"import.run.failed",error:i,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(n,e.run_id).catch(()=>{}),l||await Se(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}m(vt,"processRun");function Xe(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:s,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Xe,"failureOf");function h(e,s,t){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(h,"addDropped");function Ze(e,s){for(const[t,a]of Object.entries(s.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(s.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ze,"withInserted");async function xe(e,s,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(o=>o.rev_id)))).map(o=>o.rev_id)),n=t.filter(o=>!a.has(o.rev_id)),p=new Map;for(const o of t)p.set(o.document,[...p.get(o.document)??[],o]);for(const[o,d]of p){const l=await ae(e,o);l!==null&&await te(e,l,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,s,"revisions",n.map(o=>[o.rev_id])),await U(e,s,"revision_parents",n.flatMap(o=>o.parents.map(d=>[o.rev_id,d]))),n.length}m(xe,"arrive");async function U(e,s,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),s,t)}m(U,"appendManifest");async function et(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(Ze,"manifestFile");export{Ge as COPY_LEASE_MS,K as GRANT_WAIT_MS,Et as processRun};
3
+ `))}m(et,"manifestFile");export{ze as COPY_LEASE_MS,K as GRANT_WAIT_MS,vt as processRun};
@@ -51,7 +51,7 @@ export interface LlmRequest {
51
51
  stop?: string | string[];
52
52
  seed?: number;
53
53
  }
54
- /** The account's access token, refreshed under the pool's row lock when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
54
+ /** The account's access token, refreshed under the account's refresh claim (no connection held during the vendor call) when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
55
55
  export declare function freshSubscriptionAccess(registry: Awaited<ReturnType<typeof openModelRegistry>>, provider: ManagedProviderId, account: SubscriptionCredential, served: string, signal?: AbortSignal): Promise<string>;
56
56
  export declare function parseLlmRequest(raw: unknown): LlmRequest;
57
57
  export interface LlmResult {
@@ -17,11 +17,11 @@ export declare class PoolCredentialStore implements CredentialStore {
17
17
  read(providerId: string): Promise<Credential | undefined>;
18
18
  list(): Promise<readonly CredentialInfo[]>;
19
19
  /**
20
- * pi's locked read-modify-write, chiefly its OAuth refresh. The whole transaction — electing
21
- * the account, running pi's `fn`, committing the result — happens under the account row locks, because a refresh token is single-use: two brokers electing the same
22
- * expired account outside a lock would both spend it and the loser would get a genuine
23
- * `invalid_grant`. Electing under the lock is also what guarantees the refreshed token lands
24
- * back on exactly the account whose token was spent.
20
+ * pi's read-modify-write, chiefly its OAuth refresh. Running pi's `fn` and committing the result
21
+ * happen under the account's refresh claim, because a refresh token is single-use: two brokers
22
+ * refreshing the same expired account without it would both spend it and the loser would get a
23
+ * genuine `invalid_grant`. The commit is conditional on the spent token, so the refreshed token
24
+ * lands back on exactly the account whose token was spent.
25
25
  *
26
26
  * A managed provider with no pool account is NOT created here — pi must not be able to mint a
27
27
  * managed account behind crouter's login surfaces, which own the account-identity gate.
@@ -14,6 +14,9 @@ export declare function buildProjectContextBlock(cwd: string): string;
14
14
  * every node, rendered as the `## Your documents and context directory`
15
15
  * subsection of <crtr-bearings>. */
16
16
  export declare function contextDirNote(nodeId: string, grantee?: string): string;
17
+ /** Where the node's engine and shell run, by the runner of its latest execution. A cloud sandbox is not the person's
18
+ * computer, so a path from their Mac (a pasted screenshot's temp file, a `/Users/...` path) does not exist there. */
19
+ export declare function whereYouRunNote(runner: 'process' | 'blaxel' | 'machine' | undefined): string;
17
20
  /** The profile-purview note — rendered ONLY when the profile resolves to a
18
21
  * manifest that names at least one project dir. Phrased as PURVIEW, not a cwd
19
22
  * replacement: the node's cwd is still its one working dir (bash/edits run
@@ -1,18 +1,18 @@
1
- var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function T(){const e=x();return`Host: ${[`${process.platform} ${process.arch}`,C(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(T,"runtimeLine");function A(e){try{const n=_("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(A,"directoryListingLines");function f(e,t,n,r){const o=k(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(f,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function d(e,t){const n=f(e,"git",t,$());return n.ok?n.stdout:""}s(d,"runGit");function G(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(G,"parseWorktrees");function O(e){const t=f(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
1
+ var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function A(){const e=x();return`Host: ${[`${process.platform} ${process.arch}`,C(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function T(e){try{const n=_("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(T,"directoryListingLines");function f(e,t,n,r){const o=k(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(f,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function d(e,t){const n=f(e,"git",t,$());return n.ok?n.stdout:""}s(d,"runGit");function G(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(G,"parseWorktrees");function O(e){const t=f(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
2
2
  `).filter(c=>c!=="").length,i=d(e,["worktree","list","--porcelain"]).split(`
3
- `),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function W(e){const t=A(e),n=O(e);let r=`<project_context>
3
+ `),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function P(e){const t=T(e),n=O(e);let r=`<project_context>
4
4
 
5
5
  `;return r+=`<environment cwd="${N(e)}">
6
- `,r+=`${T()}
6
+ `,r+=`${A()}
7
7
  `,r+=`Directory:
8
8
  ${t.map(o=>` ${o}`).join(`
9
9
  `)}
10
10
  `,r+=`${n.map(o=>`${o}`).join(`
11
11
  `)}
12
12
  `,r+=`</environment>
13
- </project_context>`,r}s(W,"buildProjectContextBlock");function M(e,t){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`${m(e,t)}\` (also \`$CRTR_CONTEXT_DIR\`) holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(M,"contextDirNote");function F(e,t){if(t==null||t==="")return"";let n;try{n=D(t)}catch{return""}const r=w(n.manifest.projects);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(F,"profileNote");function X(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(X,"orchestratorContextNote");function z(e,t,n){return`Context directory: \`${m(e,t)}\` (\`$CRTR_CONTEXT_DIR\`), for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${n}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(z,"forkContextNote");function y(e){const t=v(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(y,"relativeLabel");const j=5;function K(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${y(c)}`)});const u=r.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const h=o.slice(0,j),l=o.length-h.length;return h.forEach((c,p)=>{const g=p===h.length-1&&l===0;a.push(`${i(u+1)}${g?"\u2514 ":"\u251C "}${y(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
- `)}s(K,"renderGraphMap");function q(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
- `)}s(q,"buildIdentityAssertion");function U(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
13
+ </project_context>`,r}s(P,"buildProjectContextBlock");function W(e,t){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`${m(e,t)}\` (also \`$CRTR_CONTEXT_DIR\`) holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(W,"contextDirNote");function F(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(F,"whereYouRunNote");function X(e,t){if(t==null||t==="")return"";let n;try{n=D(t)}catch{return""}const r=w(n.manifest.projects);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(X,"profileNote");function z(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(z,"orchestratorContextNote");function K(e,t,n){return`Context directory: \`${m(e,t)}\` (\`$CRTR_CONTEXT_DIR\`), for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${n}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(K,"forkContextNote");function y(e){const t=v(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(y,"relativeLabel");const j=5;function U(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${y(c)}`)});const u=r.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const h=o.slice(0,j),l=o.length-h.length;return h.forEach((c,p)=>{const g=p===h.length-1&&l===0;a.push(`${i(u+1)}${g?"\u2514 ":"\u251C "}${y(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
+ `)}s(U,"renderGraphMap");function q(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
+ `)}s(q,"buildIdentityAssertion");function J(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
16
16
  Worktree: \`${e.path}\`
17
17
  Base: \`${e.base_ref}\` @ \`${e.base_sha}\`
18
- Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(U,"worktreeNote");export{q as buildIdentityAssertion,W as buildProjectContextBlock,M as contextDirNote,N as escapeAttribute,z as forkContextNote,X as orchestratorContextNote,F as profileNote,y as relativeLabel,K as renderGraphMap,U as worktreeNote};
18
+ Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(J,"worktreeNote");export{q as buildIdentityAssertion,P as buildProjectContextBlock,W as contextDirNote,N as escapeAttribute,K as forkContextNote,z as orchestratorContextNote,X as profileNote,y as relativeLabel,U as renderGraphMap,F as whereYouRunNote,J as worktreeNote};
@@ -1,7 +1,7 @@
1
- var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as k,fullName as d,isSafeNodeId as g,subscriptionsOf as N}from"../canvas/index.js";import{cadenceDisplay as v}from"../wake.js";import{renderKnowledge as x,renderWorkspaceOpen as _}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as $}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as w,orchestratorContextNote as p,profileNote as C,renderGraphMap as S,buildIdentityAssertion as E,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as Z}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":C(n.cwd,n.profile_id)}a(A,"profileNote");async function j(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(j,"ancestorTrunk");const K=5;async function B(e){return(await Y(await N(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(B,"childNodes");async function R(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await j(e,n),o=await B(e);return S(e,n.kind,n.mode,t,o)}a(R,"buildGraphMap");async function T(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&g(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return E(e,r?.kind??"general",r?.mode??"base",n,o)}a(T,"buildIdentityAssertion");function D(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(D,"armerPhrase");async function q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(q,"cronWakeOrigin");function z(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?v(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
1
+ var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as N,fullName as w,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as f}from"../canvas/node-order.js";import{buildProjectContextBlock as p,contextDirNote as h,orchestratorContextNote as m,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as re}from"../../shared/generated-context.js";async function B(e,r){const n=r!==void 0?r:await s(e);return n===null?"":E(n.cwd,n.profile_id)}i(B,"profileNote");async function T(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const a=await s(o);if(a===null)break;n.unshift(a),o=a.parent??null}return n}i(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>f(r.status)-f(n.status))}i(W,"childNodes");async function D(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await T(e,n),o=await W(e);return O(e,n.kind,n.mode,t,o)}i(D,"buildGraphMap");async function H(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&v(n)?await s(n):null,o=t!==null?`${n} ("${w(t)}")`:n??"";return R(e,r?.kind??"general",r?.mode??"base",n,o)}i(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}i(L,"armerPhrase");async function Q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:w(n)}:{},armedAt:e.created,recur:e.recur}}i(Q,"cronWakeOrigin");function V(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
2
  ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const t=D(e);return`<crtr-wake>
3
+ </crtr-wake>`;const t=L(e);return`<crtr-wake>
4
4
  ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(z,"buildWakeBearings");function W(e){return O(e?.managed_worktree)}a(W,"managedWorktreeNote");async function H(e,r,n){const t=await s(e),o=["<crtr-bearings>",await T(e,t)],i=await R(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=W(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await $(e)??"",m=t?.cwd!==void 0&&(await k(e))?.runner==="process"?f(t.cwd):"";return[o.join(`
6
- `),r,n,h,m].filter(y=>y!=="").join(`
7
- `)}a(H,"bearingsShell");async function J(e,r){const n=await x(r),t=await _(r);return{content:await H(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(J,"buildContextBearings");export{Z as CONTEXT_INTRO_CUSTOM_TYPE,J as buildContextBearings,R as buildGraphMap,f as buildProjectContextBlock,z as buildWakeBearings,w as contextDirNote,q as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
5
+ </crtr-wake>`}i(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}i(M,"managedWorktreeNote");async function P(e,r,n){const t=await s(e),o=await N(e),a=["<crtr-bearings>",await H(e,t)],u=S(o?.runner);u!==""&&a.push("","## Where you run",u);const c=await D(e,t);c!==""&&a.push("","## Your place in the canvas",c),a.push("","## Your documents and context directory",h(e,t?.grantee));const d=await B(e,t);d!==""&&a.push("",d);const l=M(t);l!==""&&a.push("","## Your managed worktree",l),t?.mode==="orchestrator"&&a.push("",m()),a.push("</crtr-bearings>");const y=await C(e)??"",b=t?.cwd!==void 0&&o?.runner==="process"?p(t.cwd):"";return[a.join(`
6
+ `),r,n,y,b].filter(k=>k!=="").join(`
7
+ `)}i(P,"bearingsShell");async function Z(e,r){const n=await Y(r),t=await $(r);return{content:await P(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}i(Z,"buildContextBearings");export{re as CONTEXT_INTRO_CUSTOM_TYPE,Z as buildContextBearings,D as buildGraphMap,p as buildProjectContextBlock,V as buildWakeBearings,h as contextDirNote,Q as cronWakeOrigin,m as orchestratorContextNote,B as profileNote};
@@ -59,6 +59,8 @@ export declare function createFrameDispatchContext(deps: FrameDispatchDeps): {
59
59
  notifyTurnAccepted: () => void;
60
60
  pendingPromptDispatches: () => number;
61
61
  resetForSession: () => void;
62
+ /** A correlated request of a type this broker does not know (a newer client's): reject it at once instead of letting it time out. */
63
+ refuseUnknown: (client: BrokerClient, type: string, id: string) => void;
62
64
  /** A new cycle's memory names: the response's, or a fresh read when the cycle-start request gave none. */
63
65
  refreshMemoryNames: (names: import("./frame-memory-refs.js").ComposerNames | undefined) => Promise<void>;
64
66
  };
@@ -1 +1 @@
1
- var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as x}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as U,createPromptDispatchTracker as V,createTurnAcceptanceGate as X}from"./turn-ignition.js";import{prependRunDeferredMail as y}from"./run-deferred-mail.js";function ce(n){const{nodeId:e,registry:s,toolGroups:v,projection:k,rebind:l,boundaryReviewId:m,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:M,broadcastModelChanged:F,registryOf:E,formatModelSpec:R,formatExactModelSpec:S,turnAdmission:u,runNode:h,memoryInventory:H,onKickoffAdmitted:P}=n,t=o(()=>l.session(),"currentSession"),T=o(()=>l.services(),"currentServices"),a=j(s),{notWritable:G}=a,c=B(t,e,H),p=V(t),_=X(),f=U({session:t,dispatches:p,turnAdmission:u,prependDeferred:h?r=>y(e,r):void 0,onAdmitted:P}),g=q({nodeId:e,registry:s,replies:a,session:t,dispatches:p,memoryRefs:c,rebind:l,projection:k,toolGroups:v,turnAdmission:u,prependDeferred:h?r=>y(e,r):void 0}),I=o((r,i)=>{G(r,"drive the engine")||((i.type==="prompt"||i.type==="steer"||i.type==="follow_up")&&x(i.text,{type:"human",channel:{type:"viewer"}}),g(r,i))},"handleDriveFrame"),d=z({registry:s,replies:a,session:t,driveEngine:g,turnAcceptance:_,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,disposeAndExit:C}),W=J({registry:s,replies:a,session:t,services:T,registryOf:E,persistModelChoice:M,broadcastModelChanged:o(async(...r)=>{await F(...r),f.drivePending()},"broadcastModelChanged"),formatModelSpec:R}),K=L({registry:s,replies:a,session:t,boundaryReviewId:m,memoryRefs:c,formatExactModelSpec:S}),N=Q({registry:s,replies:a,rebind:l,session:t,boundaryReviewId:m,memoryRefs:c,reWelcomeAll:A});return{handlers:{hello:d.hello,drive:I,deliver:d.deliver,dialog:d.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{a.ackTo(r,"reload_auth")},"authentication"),bye:d.bye,shutdown:d.shutdown},kickoff:o((r,i)=>f.kickoff(r,i),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:p.pending,resetForSession:o(()=>{},"resetForSession"),refreshMemoryNames:o(r=>r===void 0?c.invalidate():(c.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(ce,"createFrameDispatchContext");function de(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return}}o(de,"handleFrame");export{ce as createFrameDispatchContext,de as handleFrame};
1
+ var U=Object.defineProperty;var o=(n,e)=>U(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as $}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as V,createPromptDispatchTracker as X,createTurnAcceptanceGate as Y}from"./turn-ignition.js";import{prependRunDeferredMail as v}from"./run-deferred-mail.js";function de(n){const{nodeId:e,registry:s,toolGroups:c,projection:k,rebind:p,boundaryReviewId:m,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:F,broadcastModelChanged:M,registryOf:S,formatModelSpec:E,formatExactModelSpec:R,turnAdmission:h,runNode:f,memoryInventory:H,onKickoffAdmitted:P}=n,a=o(()=>p.session(),"currentSession"),T=o(()=>p.services(),"currentServices"),i=j(s),{notWritable:G}=i,d=B(a,e,H),u=X(a),_=Y(),g=V({session:a,dispatches:u,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0,onAdmitted:P}),y=q({nodeId:e,registry:s,replies:i,session:a,dispatches:u,memoryRefs:d,rebind:p,projection:k,toolGroups:c,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0}),I=o((r,t)=>{G(r,"drive the engine")||((t.type==="prompt"||t.type==="steer"||t.type==="follow_up")&&$(t.text,{type:"human",channel:{type:"viewer"}}),y(r,t))},"handleDriveFrame"),l=z({registry:s,replies:i,session:a,driveEngine:y,turnAcceptance:_,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,disposeAndExit:C}),W=J({registry:s,replies:i,session:a,services:T,registryOf:S,persistModelChoice:F,broadcastModelChanged:o(async(...r)=>{await M(...r),g.drivePending()},"broadcastModelChanged"),formatModelSpec:E}),K=L({nodeId:e,registry:s,replies:i,session:a,boundaryReviewId:m,memoryRefs:d,formatExactModelSpec:R}),N=Q({registry:s,replies:i,rebind:p,session:a,boundaryReviewId:m,memoryRefs:d,reWelcomeAll:A});return{handlers:{hello:l.hello,drive:I,deliver:l.deliver,dialog:l.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{i.ackTo(r,"reload_auth")},"authentication"),bye:l.bye,shutdown:l.shutdown},kickoff:o((r,t)=>g.kickoff(r,t),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:u.pending,resetForSession:o(()=>{},"resetForSession"),refuseUnknown:o((r,t,O)=>s.sendFrame(r,{type:"error",code:"unknown_frame",id:O,message:`this broker does not handle '${t}' frames`}),"refuseUnknown"),refreshMemoryNames:o(r=>r===void 0?d.invalidate():(d.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(de,"createFrameDispatchContext");function le(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return;default:{const c=s;typeof c.id=="string"&&n.refuseUnknown(e,String(c.type),c.id)}}}o(le,"handleFrame");export{de as createFrameDispatchContext,le as handleFrame};
@@ -8,9 +8,13 @@ import { type BrokerSession } from './read-ops.js';
8
8
  * `list_sessions` is the exception: it lists conversations beyond this node, so
9
9
  * only a controller (one that may message the node) gets it. */
10
10
  export type ReadFrame = Extract<ClientToBroker, {
11
- type: 'get_commands' | 'list_models' | 'list_scoped_models' | 'list_memory_refs' | 'get_tree' | 'get_settings' | 'list_sessions' | 'get_human_fork_coordinates';
11
+ type: 'get_commands' | 'list_models' | 'list_scoped_models' | 'list_memory_refs' | 'get_tree' | 'get_settings' | 'list_sessions' | 'get_human_fork_coordinates' | 'get_git_status' | 'upload_file';
12
12
  }>;
13
+ /** Write viewer-sent bytes into the node's attachments folder under a name no
14
+ * earlier file holds (`photo.png`, `photo-2.png`, …); returns the path. */
15
+ export declare function writeViewerUpload(dir: string, name: string, bytes: Buffer): string;
13
16
  export declare function createReadHandler(deps: {
17
+ nodeId: string;
14
18
  registry: BrokerClientRegistry;
15
19
  replies: FrameReplies;
16
20
  session: () => BrokerSession;
@@ -1 +1 @@
1
- var h=Object.defineProperty;var c=(t,d)=>h(t,"name",{value:d,configurable:!0});import{SessionListCache as k}from"../session-list-cache.js";import{sessionListCachePath as y}from"../../canvas/paths.js";import{engineLeadingCommandTokens as _}from"./engine-routing.js";import{buildCommandList as p,buildGetTreeData as l,buildListMemoryRefsData as T,buildListModelsData as E,buildScopedModelsData as S,buildSessionsData as F,buildSettingsData as L}from"./read-ops.js";function R(t){const{registry:d,replies:o,session:i,boundaryReviewId:g,memoryRefs:b,formatExactModelSpec:m}=t,u=new k(y());return(s,r)=>{switch(r.type){case"get_commands":{try{o.ackTo(s,"get_commands",!0,JSON.stringify(p(i())))}catch(e){o.engineErrorTo(s)(e)}break}case"list_models":{try{d.sendFrame(s,E(r.id,i()))}catch(e){o.engineErrorTo(s,r.id)(e)}break}case"list_scoped_models":{try{d.sendFrame(s,S(r.id,i()))}catch(e){o.engineErrorTo(s,r.id)(e)}break}case"list_memory_refs":{try{d.sendFrame(s,T(r.id,b.refs(),_(i())))}catch(e){o.engineErrorTo(s,r.id)(e)}break}case"get_tree":{try{d.sendFrame(s,l(r.id,i(),g))}catch(e){o.engineErrorTo(s,r.id)(e)}break}case"get_settings":{try{d.sendFrame(s,L(r.id,i()))}catch(e){o.engineErrorTo(s,r.id)(e)}break}case"list_sessions":{if(o.notWritable(s,"list sessions",r.id))break;F(r.id,r.scope??"cwd",i(),u).then(e=>d.sendFrame(s,e)).catch(o.engineErrorTo(s,r.id));break}case"get_human_fork_coordinates":{try{const e=i().sessionManager,n=e.getSessionFile(),a=e.getLeafId();if(n===void 0||n===""||a===null){o.engineErrorTo(s,r.id)(new Error("no persisted source session leaf"));break}d.sendFrame(s,{type:"data",id:r.id,kind:"human_fork_coordinates",sourceFile:n,sourceSessionId:e.getSessionId(),leafId:a,modelSpec:m(i().model,i().thinkingLevel)})}catch(e){o.engineErrorTo(s,r.id)(e)}break}}}}c(R,"createReadHandler");export{R as createReadHandler};
1
+ var k=Object.defineProperty;var g=(n,a)=>k(n,"name",{value:a,configurable:!0});import{mkdirSync as f,writeFileSync as S,openSync as b,closeSync as m,constants as h,readFileSync as E,fstatSync as F}from"node:fs";import{basename as T,extname as L,join as _}from"node:path";import{nodeAgentDir as w}from"../../canvas/paths.js";import{fetchGitInfo as O}from"../../../shared/git-status.js";import{SessionListCache as C}from"../session-list-cache.js";import{sessionListCachePath as D}from"../../canvas/paths.js";import{engineLeadingCommandTokens as I}from"./engine-routing.js";import{buildCommandList as R,buildGetTreeData as M,buildListMemoryRefsData as x,buildListModelsData as N,buildScopedModelsData as v,buildSessionsData as A,buildSettingsData as W}from"./read-ops.js";function $(n,a,o){const t=T(a).replace(/[\u0000-\u001f]/g,"")||"file";f(n,{recursive:!0});const i=L(t),p=i&&i!==t?t.slice(0,-i.length):t;for(let d=1;;d++){const l=_(n,d===1?t:`${p}-${d}${i}`);let c;try{c=b(l,h.O_WRONLY|h.O_CREAT|h.O_EXCL,432)}catch(s){if(s.code==="EEXIST")continue;throw s}try{S(c,o)}finally{m(c)}return l}}g($,"writeViewerUpload");function B(n,a){if(a.length===0)return!1;let o;try{o=b(n,h.O_RDONLY|h.O_NONBLOCK)}catch{return!1}try{const t=F(o);return t.isFile()&&t.size===a.length&&E(o).equals(a)}catch{return!1}finally{m(o)}}g(B,"sameFileAt");function P(n){const{nodeId:a,registry:o,replies:t,session:i,boundaryReviewId:p,memoryRefs:d,formatExactModelSpec:l}=n,c=new C(D());return(s,r)=>{switch(r.type){case"get_commands":{try{t.ackTo(s,"get_commands",!0,JSON.stringify(R(i())))}catch(e){t.engineErrorTo(s)(e)}break}case"list_models":{try{o.sendFrame(s,N(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_scoped_models":{try{o.sendFrame(s,v(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_memory_refs":{try{o.sendFrame(s,x(r.id,d.refs(),I(i())))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_tree":{try{o.sendFrame(s,M(r.id,i(),p))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_settings":{try{o.sendFrame(s,W(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_sessions":{if(t.notWritable(s,"list sessions",r.id))break;A(r.id,r.scope??"cwd",i(),c).then(e=>o.sendFrame(s,e)).catch(t.engineErrorTo(s,r.id));break}case"get_git_status":{O(i().sessionManager.getCwd(),e=>{o.sendFrame(s,{type:"data",id:r.id,kind:"git_status",...e.branch===void 0?{}:{branch:e.branch},dirty:e.dirty,ahead:e.ahead,behind:e.behind})});break}case"upload_file":{if(t.notWritable(s,"upload a file",r.id))break;try{const e=Buffer.from(r.data,"base64"),u=B(r.source_path,e)?r.source_path:$(_(w(a),"attachments"),r.source_path,e);o.sendFrame(s,{type:"data",id:r.id,kind:"upload_file",path:u})}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_human_fork_coordinates":{try{const e=i().sessionManager,u=e.getSessionFile(),y=e.getLeafId();if(u===void 0||u===""||y===null){t.engineErrorTo(s,r.id)(new Error("no persisted source session leaf"));break}o.sendFrame(s,{type:"data",id:r.id,kind:"human_fork_coordinates",sourceFile:u,sourceSessionId:e.getSessionId(),leafId:y,modelSpec:l(i().model,i().thinkingLevel)})}catch(e){t.engineErrorTo(s,r.id)(e)}break}}}}g(P,"createReadHandler");export{P as createReadHandler,$ as writeViewerUpload};
@@ -385,7 +385,24 @@ export interface GetHumanForkCoordinatesFrame {
385
385
  type: 'get_human_fork_coordinates';
386
386
  id: string;
387
387
  }
388
- export type ClientToBroker = HelloFrame | PromptFrame | SteerFrame | FollowUpFrame | AbortFrame | DeliverFrame | BashFrame | ByeFrame | ShutdownFrame | SetModelFrame | DeliverCustomMessageFrame | CycleModelFrame | CycleLadderFrame | CycleThinkingFrame | SetThinkingLevelFrame | DequeueFrame | SetAutoRetryFrame | SetAutoCompactionFrame | CompactFrame | NewSessionFrame | SwitchSessionFrame | ForkFrame | SetSessionNameFrame | GetCommandsFrame | NavigateTreeFrame | ReloadFrame | ExportFrame | ListModelsFrame | ListSessionsFrame | GetTreeFrame | GetSettingsFrame | ListScopedModelsFrame | ListMemoryRefsFrame | ExtensionUIResponseFrame | CloneFrame | ShareFrame | ReloadAuthFrame | GetHumanForkCoordinatesFrame;
388
+ /** Read the git branch and status of the node's own working directory, where the
389
+ * broker runs (a viewer on another machine cannot read it). Observer-safe. */
390
+ export interface GetGitStatusFrame {
391
+ type: 'get_git_status';
392
+ id: string;
393
+ }
394
+ /** Write one file from the viewer's machine into this node's attachments folder,
395
+ * so a path the person typed or pasted can be read by the node. Controller only.
396
+ * `data` is the file's bytes in base64; the reply names the written path. */
397
+ export interface UploadFileFrame {
398
+ type: 'upload_file';
399
+ id: string;
400
+ /** The path on the viewer's machine. When the broker reads the same bytes at
401
+ * this path (viewer and node share a disk) it answers with it and writes nothing. */
402
+ source_path: string;
403
+ data: string;
404
+ }
405
+ export type ClientToBroker = HelloFrame | GetGitStatusFrame | UploadFileFrame | PromptFrame | SteerFrame | FollowUpFrame | AbortFrame | DeliverFrame | BashFrame | ByeFrame | ShutdownFrame | SetModelFrame | DeliverCustomMessageFrame | CycleModelFrame | CycleLadderFrame | CycleThinkingFrame | SetThinkingLevelFrame | DequeueFrame | SetAutoRetryFrame | SetAutoCompactionFrame | CompactFrame | NewSessionFrame | SwitchSessionFrame | ForkFrame | SetSessionNameFrame | GetCommandsFrame | NavigateTreeFrame | ReloadFrame | ExportFrame | ListModelsFrame | ListSessionsFrame | GetTreeFrame | GetSettingsFrame | ListScopedModelsFrame | ListMemoryRefsFrame | ExtensionUIResponseFrame | CloneFrame | ShareFrame | ReloadAuthFrame | GetHumanForkCoordinatesFrame;
389
406
  export interface WelcomeFrame {
390
407
  type: 'welcome';
391
408
  snapshot: BrokerSnapshot;
@@ -622,8 +639,26 @@ export interface HumanForkCoordinatesData {
622
639
  leafId: string;
623
640
  modelSpec: string | null;
624
641
  }
642
+ /** The `get_git_status` result: git context of the node's working directory. */
643
+ export interface GitStatusData {
644
+ type: 'data';
645
+ id: string;
646
+ kind: 'git_status';
647
+ /** Undefined outside a repository. */
648
+ branch?: string;
649
+ dirty: boolean;
650
+ ahead: number;
651
+ behind: number;
652
+ }
653
+ /** The `upload_file` result: where the node can read the file. */
654
+ export interface UploadFileData {
655
+ type: 'data';
656
+ id: string;
657
+ kind: 'upload_file';
658
+ path: string;
659
+ }
625
660
  /** All correlated data replies (read-ops + dequeue). Discriminate on `kind`. */
626
- export type BrokerDataFrame = ListModelsData | ListSessionsData | GetTreeData | GetSettingsData | ListScopedModelsData | ListMemoryRefsData | DequeueData | HumanForkCoordinatesData;
661
+ export type BrokerDataFrame = GitStatusData | UploadFileData | ListModelsData | ListSessionsData | GetTreeData | GetSettingsData | ListScopedModelsData | ListMemoryRefsData | DequeueData | HumanForkCoordinatesData;
627
662
  /** An extension UI call routed to viewers — pi's public RPC request type. */
628
663
  export type ExtensionUIRequestFrame = RpcExtensionUIRequest;
629
664
  /** Broker → client: dismiss a previously-forwarded blocking dialog by request id,
@@ -1,10 +1,9 @@
1
- import type { NodeRow } from '../canvas/index.js';
2
1
  export declare const YIELD_STALL_GRACE_MS: number;
3
2
  export declare const KILL_ESCALATE_MS = 20000;
4
3
  export declare const WEDGE_QUIET_MS: number;
5
4
  export declare const WEDGE_CPU_MAX_PERCENT = 2;
6
5
  export type WedgeVerdict = 'leave' | 'pending' | 'wedged';
7
- export declare function yieldStallVerdict(piPidAlive: boolean | null, intent: NodeRow['intent'], busy: boolean, stalledFor: number | null): 'leave' | 'pending' | 'kill';
6
+ export declare function yieldStallVerdict(piPidAlive: boolean | null, busy: boolean, stalledFor: number | null): 'leave' | 'pending' | 'kill';
8
7
  export declare function wedgeVerdict(input: {
9
8
  busy: boolean;
10
9
  quietForMs: number | null;
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var c=(e,n)=>d(e,"name",{value:n,configurable:!0});import{execFile as a}from"node:child_process";import{promisify as m}from"node:util";const h=m(a),g=3*6e4,N=2e4,_=20*6e4,x=2;function P(e,n,t,r){return e!==!0||n!=="refresh"||t?"leave":r===null||r<g?"pending":"kill"}c(P,"yieldStallVerdict");function S(e){return!e.busy||e.quietForMs===null||e.quietForMs<_?"leave":e.cpuPercent===null||e.hasDescendants!==!1&&e.cpuPercent>x?"pending":"wedged"}c(S,"wedgeVerdict");function p(e){const n=new Map,t=new Map;for(const r of e.split(`
2
- `)){const o=r.trim();if(o==="")continue;const i=o.split(/\s+/);if(i.length<3)continue;const u=Number(i[0]),s=Number(i[1]),l=Number(i[2]);if(!Number.isFinite(u)||!Number.isFinite(s)||!Number.isFinite(l))continue;n.set(u,l);const f=t.get(s);f===void 0?t.set(s,[u]):f.push(u)}return{byPid:n,childrenOf:t}}c(p,"parsePsTree");function b(e,n){const{byPid:t,childrenOf:r}=p(e);if(!t.has(n))return null;let o=0;const i=[n],u=new Set;for(;i.length>0;){const s=i.pop();if(u.has(s))continue;u.add(s),o+=t.get(s)??0;const l=r.get(s);l!==void 0&&i.push(...l)}return o}c(b,"sumTreeCpu");function E(e,n){const{byPid:t,childrenOf:r}=p(e);return t.has(n)?(r.get(n)??[]).length>0:null}c(E,"treeHasDescendants");async function T(e){try{const{stdout:n}=await h("ps",["-ax","-o","pid=,ppid=,pcpu="],{encoding:"utf8",timeout:2e3});if(typeof n!="string")return null;const t=b(n,e),r=E(n,e);return t===null||r===null?null:{cpuPercent:t,hasDescendants:r}}catch{return null}}c(T,"sampleBrokerTree");export{N as KILL_ESCALATE_MS,x as WEDGE_CPU_MAX_PERCENT,_ as WEDGE_QUIET_MS,g as YIELD_STALL_GRACE_MS,T as sampleBrokerTree,b as sumTreeCpu,E as treeHasDescendants,S as wedgeVerdict,P as yieldStallVerdict};
1
+ var d=Object.defineProperty;var u=(e,n)=>d(e,"name",{value:n,configurable:!0});import{execFile as a}from"node:child_process";import{promisify as m}from"node:util";const g=m(a),h=3*6e4,N=2e4,_=20*6e4,x=2;function P(e,n,t){return e!==!0||n?"leave":t===null||t<h?"pending":"kill"}u(P,"yieldStallVerdict");function S(e){return!e.busy||e.quietForMs===null||e.quietForMs<_?"leave":e.cpuPercent===null||e.hasDescendants!==!1&&e.cpuPercent>x?"pending":"wedged"}u(S,"wedgeVerdict");function f(e){const n=new Map,t=new Map;for(const r of e.split(`
2
+ `)){const o=r.trim();if(o==="")continue;const i=o.split(/\s+/);if(i.length<3)continue;const c=Number(i[0]),s=Number(i[1]),l=Number(i[2]);if(!Number.isFinite(c)||!Number.isFinite(s)||!Number.isFinite(l))continue;n.set(c,l);const p=t.get(s);p===void 0?t.set(s,[c]):p.push(c)}return{byPid:n,childrenOf:t}}u(f,"parsePsTree");function b(e,n){const{byPid:t,childrenOf:r}=f(e);if(!t.has(n))return null;let o=0;const i=[n],c=new Set;for(;i.length>0;){const s=i.pop();if(c.has(s))continue;c.add(s),o+=t.get(s)??0;const l=r.get(s);l!==void 0&&i.push(...l)}return o}u(b,"sumTreeCpu");function E(e,n){const{byPid:t,childrenOf:r}=f(e);return t.has(n)?(r.get(n)??[]).length>0:null}u(E,"treeHasDescendants");async function T(e){try{const{stdout:n}=await g("ps",["-ax","-o","pid=,ppid=,pcpu="],{encoding:"utf8",timeout:2e3});if(typeof n!="string")return null;const t=b(n,e),r=E(n,e);return t===null||r===null?null:{cpuPercent:t,hasDescendants:r}}catch{return null}}u(T,"sampleBrokerTree");export{N as KILL_ESCALATE_MS,x as WEDGE_CPU_MAX_PERCENT,_ as WEDGE_QUIET_MS,h as YIELD_STALL_GRACE_MS,T as sampleBrokerTree,b as sumTreeCpu,E as treeHasDescendants,S as wedgeVerdict,P as yieldStallVerdict};
@@ -28,9 +28,9 @@ export type RefreshedTokens = {
28
28
  expires: number;
29
29
  clientId?: string;
30
30
  };
31
- /** Longest a refresh exchange may hold the account's row lock. */
31
+ /** Longest a refresh exchange may take. */
32
32
  export declare const REFRESH_EXCHANGE_TIMEOUT_MS = 10000;
33
- /** Another process held this account's row lock for the whole lock timeout (a slow refresh exchange): the account is cooling for this call, not failed. */
33
+ /** Another process claimed this account's refresh and wrote no fresh tokens within `REFRESH_CLAIM_MS`: the account is cooling for this call, not failed. */
34
34
  export declare class RefreshBusyError extends Error {
35
35
  constructor(provider: ManagedProviderId, label: string);
36
36
  }
@@ -74,8 +74,8 @@ export declare function vendorRateLimit(headers: Headers | Record<string, string
74
74
  };
75
75
  /** The vendor refused this account's access token on a request (401): flag the row as a refused refresh does, so every pool reader skips it until a sign-in replaces it. */
76
76
  export declare function markSubscriptionAuthFailure(provider: ManagedProviderId, ref: string): Promise<SubscriptionCredential[]>;
77
- /** Refresh one account's tokens under its row lock. A process that waited on the lock finds the tokens already fresh (or the account already flagged) and does not call the vendor again. */
78
77
  export declare function refreshSubscriptionCredential(provider: ManagedProviderId, label: string, exchange: (refreshToken: string, clientId?: string) => Promise<RefreshedTokens>): Promise<SubscriptionCredential>;
78
+ /** Elect an account and refresh it with `apply`; an account whose refresh token the vendor refuses is flagged and the next elected account is tried. */
79
79
  export declare function modifyElectedSubscription(provider: ManagedProviderId, elect: (pool: SubscriptionCredential[]) => SubscriptionCredential | undefined, apply: (current: SubscriptionCredential) => Promise<RefreshedTokens | undefined>): Promise<SubscriptionCredential | undefined>;
80
80
  export type ManagedLoginIdentity = {
81
81
  accountId?: string;
@@ -1 +1 @@
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
+ var ut=Object.defineProperty;var l=(t,a)=>ut(t,"name",{value:a,configurable:!0});import{createHash as mt,randomUUID as x}from"node:crypto";import{setTimeout as ft}from"node:timers/promises";import{brokerConfigSnapshot as _t}from"./config.js";import{openDb as N,withCanvasWrite as B}from"./canvas/db.js";import{personIdAsync as b}from"./canvas/person.js";import{loadSecretsKey as G,open as J,seal as U}from"./secrets/index.js";import{classifyRateLimit as pt,modelCooldownFamily as ht}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as At,REFRESH_TIMEOUT_PHRASE as wt}from"./provider-error-recognition.js";import{registerRotationReader as Et}from"./model-routes.js";import{coolingUntilFor as bt,retryAfterMsFromHeaders as yt,getProviderLabel as p,isInvalidRefreshTokenError as Q,DuplicateSubscriptionError as $,ANTHROPIC_PROVIDER_ID as Rt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as Z}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 f(t){return t.toLowerCase()}l(f,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function Lt(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}:{},...et(t.modelCooldowns)?{modelCooldowns:et(t.modelCooldowns)}:{}}}l(Lt,"credential");function et(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(et,"modelCooldowns");function D(t,a){if(!a.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=Lt(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(D,"assertCredential");function at(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(at,"differentAccount");function A(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${mt("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(A,"identity");function gt(t,a){const e=V(a);return e?{...t,clientId:e}:t}l(gt,"withClientId");function It(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(It,"assertTokens");const nt=1e4,it=15e3,xt="15s";class Nt extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${p(a)} subscription "${e}" ${At}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Dt extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${p(a)} ${wt} ${nt} ms`),this.name="RefreshTimeoutError"}}const O="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",I=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function L(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(L,"stored");function St(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(St,"rowOf");function C(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=G(),r=J(e.refresh_sealed,e.key_id,i,I(t,a,e.id,"refresh")),s=J(e.access_sealed,e.key_id,i,I(t,a,e.id,"access")),o=St(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(u=>[u.family,u.lastRateLimitedAt?Math.min(u.rateLimitedUntil,u.lastRateLimitedAt+j):u.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(C,"toPublic");function rt(t){const a=new Map;for(const e of t){const n=a.get(e.account_id)??[];n.push({family:e.family,rateLimitedUntil:e.rate_limited_until,lastRateLimitedAt:e.last_rate_limited_at}),a.set(e.account_id,n)}return a}l(rt,"groupCooldowns");async function S(t,a,e){return rt(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))}l(S,"loadCooldowns");async function M(t,a,e,n=!1){const i=await t.prepare(`SELECT ${O} 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=>C(a,e,s,r.get(s.id)))}l(M,"loadPool");async function Zt(){const t=await b(),a=await N(),e=await a.prepare(`SELECT provider_id,${O} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(t),n=rt(await a.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(C(t,r.provider_id,r,n.get(r.id)).entry),i.set(r.provider_id,s)}return i}l(Zt,"readAllSubscriptionPools");async function Y(t){await t.exec(`SET LOCAL lock_timeout = '${xt}'`)}l(Y,"setLockTimeout");async function Tt(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 ${O} 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 C(a,e,o,(await S(t,a,e)).get(o.id))}l(Tt,"lockedAccount");async function y(t,a){const e=await b();return B(async n=>(await Y(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await M(n,e,t,!0)})))}l(y,"locked");async function k(t,a,e,n,i){const r=G(),s=U(i.refresh,r,I(a,e,n.id,"refresh")),o=U(i.access,r,I(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(k,"insertAccount");async function X(t,a,e,n,i,r){const s=G(),o=U(i.refresh,s,I(a,e,n,"refresh")),c=U(i.access,s,I(a,e,n,"access"));return(await t.prepare(`UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=?,refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?${r?" AND refresh_sealed=?":""}`).run(o.sealed,c.sealed,i.expires,i.accountId??null,i.clientId??null,o.keyId,a,e,n,...r?[r]:[])).changes===1}l(X,"setCredential");async function E(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(E,"updateHealth");async function st(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(st,"upsertModelCooldown");async function T(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(T,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await M(t,a,e)).map(({entry:n})=>n),"publicPool");function Ft(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new Dt(t)),nt)})]).finally(()=>clearTimeout(e))}l(Ft,"withExchangeTimeout");async function H(t){return(await Ut(t)).map(({entry:a})=>a)}l(H,"readSubscriptionPool");async function Ut(t){const a=await b();return(await M(await N(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(Ut,"readSubscriptionPoolRows");async function vt(t,a){return y(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(u=>D(t,u)),o=s.map((u,d)=>({entry:u,id:r[d]?.row.id??x()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await T(n,i,t);for(const[u,{entry:d,id:_}]of o.entries()){await k(n,i,t,{providerId:t,id:_,label:d.label,labelKey:f(d.label),position:u,lastAttemptAt:d.lastAttemptAt,lastRateLimitedAt:d.lastRateLimitedAt,rateLimitedUntil:d.rateLimitedUntil,...d.authFailure?{authFailure:d.authFailure}:{}},L(d));for(const[m,h]of Object.entries(d.modelCooldowns??{}))await st(n,i,t,_,m,h,c.get(_)?.find(F=>F.family===m)?.lastRateLimitedAt??d.lastRateLimitedAt)}return s})}l(vt,"writeSubscriptionPool");function W(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})=>f(i.label)===e)}l(W,"resolve");const P=l((t,a)=>new $(`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 $t(t,a){const e=D(t,a);return y(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:u})=>f(u.label)===f(e.label)))throw new $(`${p(t)} subscription already exists: ${e.label}`);const o=A(e),c=s.find(({entry:u})=>A(u)===o);if(o&&c)throw P(t,c.entry.label);return await k(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},L(e)),R(n,t)})}l($t,"addSubscription");async function te(t,a){const e=D(t,a);return(await H(t)).find(i=>f(i.label)===f(e.label))?Ot(t,e):$t(t,e)}l(te,"upsertSubscription");async function Ot(t,a){const e=D(t,a);return y(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:m})=>f(m.label)===f(e.label)),c=s[o],u=s.find(({entry:m},h)=>h!==o&&A(m)===A(e));if(A(e)&&u)throw P(t,u.entry.label);if(!c)return await k(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},L(e)),R(n,t);const d=c.row,_=e.lastRateLimitedAt>=d.lastRateLimitedAt;return await X(i,r,t,d.id,L(e)),await E(i,r,{...d,authFailure:void 0,label:e.label,labelKey:f(e.label),lastAttemptAt:Math.max(d.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:_?e.lastRateLimitedAt:d.lastRateLimitedAt,rateLimitedUntil:_?e.rateLimitedUntil:d.rateLimitedUntil}),at(c.entry,e)&&await T(i,r,t,d.id),R(n,t)})}l(Ot,"upsertSubscriptionWithUniqueAccount");async function ee(t,a,e){return y(t,async n=>{const{db:i,person:r,rows:s}=n,o=W(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((u,d)=>d!==o&&f(u.entry.label)===f(c)))throw new $(`${p(t)} subscription already exists: ${c}`);return await E(i,r,{...s[o].row,label:c,labelKey:f(c)}),R(n,t)})}l(ee,"renameSubscription");async function q(t,a,e){return y(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 T(i,r,t,c.id),R(n,t)})}l(q,"remove");async function Ct(t,a){return q(t,e=>W(e,a),a)}l(Ct,"removeManagedAccount");async function ae(t,a){return q(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(ae,"removeManagedAccountById");async function ne(t,a){return q(t,e=>W(e,a),a)}l(ne,"removeSubscription");async function Mt(t){return y(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await T(a,e,t),n.length))}l(Mt,"removeAllManagedAccounts");async function ie(t,a){return a===void 0?(await Mt(t),[]):Ct(t,a)}l(ie,"removeManagedProvider");async function re(t,a){return y(t,async e=>{const{db:n,person:i,rows:r}=e,s=W(r,a);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,u)=>u!==s)];for(const[c,u]of o.entries())await E(n,i,{...u.row,position:c});return R(e,t)})}l(re,"promoteSubscription");async function K(t,a,e){const n=await b();return await B(async i=>{await Y(i);const r=await Tt(i,n,t,a);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${a}`);await e(i,n,r.row)}),H(t)}l(K,"healthWrite");async function se(t,a,e=Date.now()){return K(t,a,(n,i,r)=>E(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(se,"markSubscriptionAttempt");async function oe(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),K(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await E(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await E(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const u=(await S(s,o,t)).get(c.id)?.find(d=>d.family===r.family);u&&i<u.lastRateLimitedAt||await st(s,o,t,c.id,r.family,i+e,i)})}l(oe,"markSubscriptionRateLimited");async function le(t,a,e=Date.now(),n){const i=ht(n);return K(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await E(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(u=>u.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(le,"markSubscriptionSuccess");async function kt(t,a,e){const n=Date.now();await E(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+Z)})}l(kt,"recordInvalidGrant");function ce(t,a,e,n=15e3,i=Date.now()){const r=yt(t),s=pt(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(ce,"vendorRateLimit");async function de(t,a){return K(t,a,(e,n,i)=>kt(e,n,i))}l(de,"markSubscriptionAuthFailure");async function ot(t,a,e,n){const i=await b(),r=await N(),s=Date.now()+it;for(;;){const o=Date.now(),c=await r.prepare(`UPDATE model_accounts SET refresh_claimed_until=? WHERE person=? AND provider_id=? AND label_key=? AND expires<=? AND auth_failure IS NULL AND refresh_claimed_until<=? RETURNING ${O}`).get(o+it,i,t,f(a),e?o:Number.MAX_SAFE_INTEGER,o);if(c)try{const d=C(i,t,c);let _;try{_=await Ft(t,n(d.entry))}catch(h){throw Q(h)&&await r.prepare("UPDATE model_accounts SET auth_failure=?,last_attempt_at=GREATEST(last_attempt_at,?),rate_limited_until=GREATEST(rate_limited_until,?) WHERE person=? AND provider_id=? AND id=? AND refresh_sealed=?").run("invalid_grant",Date.now(),Date.now()+Z,i,t,c.id,c.refresh_sealed),h}if(!_)return d.entry;const m=gt(It(t,d.entry.label,_),_.clientId??d.entry.clientId);if(await X(r,i,t,c.id,L({...d.entry,...m}),c.refresh_sealed))return{...d.entry,...m};continue}finally{await r.prepare("UPDATE model_accounts SET refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?").run(i,t,c.id).catch(()=>{})}const u=(await M(r,i,t)).find(({entry:d})=>f(d.label)===f(a));if(!u)throw new Error(`${p(t)} subscription "${a}" no longer exists`);if(u.row.authFailure)throw new Error(`${p(t)} subscription "${u.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);if(e&&u.entry.expires>o)return u.entry;if(Date.now()>=s)throw new Nt(t,u.entry.label);await ft(500)}}l(ot,"refreshAccount");async function ue(t,a,e){return ot(t,a,!0,n=>e(n.refresh,n.clientId))}l(ue,"refreshSubscriptionCredential");async function me(t,a,e){const n=new Set;let i;for(;;){const r=a((await H(t)).filter(({label:s})=>!n.has(s)));if(!r){if(i)throw i;return}n.add(r.label);try{return await ot(t,r.label,!1,e)}catch(s){if(!Q(s))throw s;i=s}}}l(me,"modifyElectedSubscription");async function Ht(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==Rt)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(Ht,"enrichManagedLoginIdentity");async function fe(t,a,e){const n=await Ht(t,e);return y(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),u=A({refresh:e.refresh,accountId:n.accountId}),d=(c?o.find(({entry:w})=>f(w.label)===f(c)):void 0)??o.find(({entry:w})=>A(w)===u);let _=d?.entry.label??c;if(!_&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;_=w;for(let g=2;o.some(({entry:dt})=>f(dt.label)===f(_));g++)_=`${w} (${g})`}if(!_)throw new Error(`${p(t)} subscription label cannot be empty`);const m=D(t,{label:_,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(!d){if(o.some(({entry:g})=>f(g.label)===f(m.label)))throw new $(`${p(t)} subscription already exists: ${m.label}`);const w=o.find(({entry:g})=>A(g)===A(m));if(A(m)&&w)throw P(t,w.entry.label);return await k(r,s,t,{providerId:t,id:x(),label:m.label,labelKey:f(m.label),position:o.length,lastAttemptAt:m.lastAttemptAt,lastRateLimitedAt:m.lastRateLimitedAt,rateLimitedUntil:m.rateLimitedUntil},L(m)),R(i,t)}const h=d.row,F=o.find(({entry:w})=>w.label!==d.entry.label&&A(w)===A(m));if(A(m)&&F)throw P(t,F.entry.label);const z=m.lastRateLimitedAt>=h.lastRateLimitedAt;return await X(r,s,t,h.id,L(m)),await E(r,s,{...h,authFailure:void 0,lastAttemptAt:Math.max(h.lastAttemptAt,m.lastAttemptAt),lastRateLimitedAt:z?m.lastRateLimitedAt:h.lastRateLimitedAt,rateLimitedUntil:z?0:h.rateLimitedUntil}),at(d.entry,m)&&await T(r,s,t,h.id),R(i,t)})}l(fe,"commitManagedLogin");const lt=new Map;function ct(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(ct,"rotationFromRow");async function Wt(){const t=await b(),a=ct(await(await N()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return lt.set(t,a),a}l(Wt,"loadRotationConfig"),Et(()=>Pt());async function Pt(){const t=_t();return t?t.rotation:Wt()}l(Pt,"readRotationConfig");async function _e(t){const a=await b(),e=await B(async n=>{await Y(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=ct(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:tt(t.defaultFallbackStrength)??i.defaultFallbackStrength??v,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 lt.set(a,e),e}l(_e,"writeRotationConfig");async function pe(){const t=await b();return(await(await N()).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,x())).openai_device_id}l(pe,"openAIDeviceId");async function he(t,a=Date.now(),e){const n=await H(t),i=n.filter(s=>s.authFailure===void 0&&bt(s,e)<=a),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(he,"formatStatusLine");export{nt as REFRESH_EXCHANGE_TIMEOUT_MS,Nt as RefreshBusyError,Dt as RefreshTimeoutError,I as aadOf,$t as addSubscription,fe as commitManagedLogin,Ht as enrichManagedLoginIdentity,he as formatStatusLine,k as insertAccount,Wt as loadRotationConfig,se as markSubscriptionAttempt,de as markSubscriptionAuthFailure,oe as markSubscriptionRateLimited,le as markSubscriptionSuccess,me as modifyElectedSubscription,pe as openAIDeviceId,re as promoteSubscription,Zt as readAllSubscriptionPools,Pt as readRotationConfig,H as readSubscriptionPool,Ut as readSubscriptionPoolRows,ue as refreshSubscriptionCredential,Mt as removeAllManagedAccounts,Ct as removeManagedAccount,ae as removeManagedAccountById,ie as removeManagedProvider,ne as removeSubscription,ee as renameSubscription,st as upsertModelCooldown,te as upsertSubscription,Ot as upsertSubscriptionWithUniqueAccount,ce as vendorRateLimit,_e as writeRotationConfig,vt as writeSubscriptionPool};