@north-light/cli 0.3.747 → 0.3.749

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 (102) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/objects.d.ts +6 -1
  4. package/dist/api/dto/plugins.d.ts +2 -0
  5. package/dist/clients/attach/chrome/canvas-panels.d.ts +2 -0
  6. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  7. package/dist/clients/attach/chrome/roster.d.ts +2 -0
  8. package/dist/clients/attach/chrome/roster.js +5 -5
  9. package/dist/clients/attach/chrome/run-facts.d.ts +12 -0
  10. package/dist/clients/attach/chrome/run-facts.js +1 -0
  11. package/dist/clients/attach/chrome/widgets.d.ts +3 -1
  12. package/dist/clients/attach/chrome/widgets.js +1 -1
  13. package/dist/clients/attach/viewer.js +487 -487
  14. package/dist/commands/canvas/list.js +2 -2
  15. package/dist/commands/canvas/read.js +4 -4
  16. package/dist/commands/canvas/search.js +1 -1
  17. package/dist/core/canvas/canvas.js +16 -16
  18. package/dist/core/canvas/schema-pg/035-environment-payer.sql +2 -0
  19. package/dist/core/canvas/schema-pg/036-ledger-holder-app-path.sql +13 -0
  20. package/dist/core/canvas/schema-version.d.ts +1 -1
  21. package/dist/core/canvas/schema-version.js +1 -1
  22. package/dist/core/command-manifests/registry.d.ts +2 -1
  23. package/dist/core/command-plugins/compose.js +1 -1
  24. package/dist/core/command.d.ts +11 -0
  25. package/dist/core/command.js +9 -9
  26. package/dist/core/environments.d.ts +2 -1
  27. package/dist/core/environments.js +1 -1
  28. package/dist/core/grants/mirror.d.ts +4 -0
  29. package/dist/core/grants/mirror.js +8 -6
  30. package/dist/core/grants/on-sync.js +1 -1
  31. package/dist/core/graph/reader.js +1 -1
  32. package/dist/core/ledger/environment-payer.d.ts +2 -0
  33. package/dist/core/ledger/environment-payer.js +1 -0
  34. package/dist/core/ledger/index.d.ts +1 -0
  35. package/dist/core/ledger/index.js +1 -1
  36. package/dist/core/ledger/payer.d.ts +4 -1
  37. package/dist/core/ledger/payer.js +1 -1
  38. package/dist/core/llm/run.d.ts +1 -0
  39. package/dist/core/llm/run.js +2 -2
  40. package/dist/core/peer/envelope.js +1 -1
  41. package/dist/core/peer/stubs.js +1 -1
  42. package/dist/core/permissions/ceiling.js +10 -10
  43. package/dist/core/permissions/evaluator.js +2 -2
  44. package/dist/core/providers/call.js +1 -1
  45. package/dist/core/runs/node-sub.d.ts +2 -0
  46. package/dist/core/runs/node-sub.js +1 -0
  47. package/dist/core/runtime/host.js +3 -3
  48. package/dist/core/runtime/recap.js +6 -6
  49. package/dist/core/runtime/spawn.js +2 -2
  50. package/dist/core/runtime/start-check.d.ts +1 -0
  51. package/dist/core/runtime/start-check.js +1 -1
  52. package/dist/core/runtime/warm-pool.js +1 -1
  53. package/dist/core/spaces/process.js +1 -1
  54. package/dist/daemon/api/handlers/bash-jobs.js +2 -2
  55. package/dist/daemon/api/handlers/hook-exec.js +1 -1
  56. package/dist/daemon/api/handlers/llm.js +3 -3
  57. package/dist/daemon/api/handlers/providers.d.ts +2 -0
  58. package/dist/daemon/api/handlers/providers.js +1 -1
  59. package/dist/daemon/peer/authority.d.ts +1 -1
  60. package/dist/daemon/peer/authority.js +1 -1
  61. package/package.json +4 -4
  62. package/packages/crouter-api/dist/api/contract.js +1 -1
  63. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +19 -1
  64. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +1 -0
  65. package/packages/crouter-api/dist/clients/attach/chrome/run-facts.js +76 -0
  66. package/packages/crouter-api/dist/clients/attach/chrome/widgets.js +14 -5
  67. package/packages/crouter-api/dist/clients/attach/viewer.js +7 -1
  68. package/packages/crouter-api/dist/commands/canvas/list.js +3 -1
  69. package/packages/crouter-api/dist/commands/canvas/read.js +4 -2
  70. package/packages/crouter-api/dist/commands/canvas/search.js +3 -1
  71. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -1
  72. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  73. package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -3
  74. package/packages/crouter-api/dist/core/command.js +34 -1
  75. package/packages/crouter-api/dist/core/environments.js +2 -2
  76. package/packages/crouter-api/dist/core/grants/mirror.js +16 -1
  77. package/packages/crouter-api/dist/core/grants/on-sync.js +2 -2
  78. package/packages/crouter-api/dist/core/graph/reader.js +1 -1
  79. package/packages/crouter-api/dist/core/ledger/environment-payer.js +15 -0
  80. package/packages/crouter-api/dist/core/ledger/index.js +1 -0
  81. package/packages/crouter-api/dist/core/ledger/payer.js +4 -0
  82. package/packages/crouter-api/dist/core/llm/run.js +2 -1
  83. package/packages/crouter-api/dist/core/peer/envelope.js +2 -1
  84. package/packages/crouter-api/dist/core/peer/stubs.js +5 -1
  85. package/packages/crouter-api/dist/core/permissions/ceiling.js +4 -0
  86. package/packages/crouter-api/dist/core/permissions/evaluator.js +16 -5
  87. package/packages/crouter-api/dist/core/providers/call.js +2 -2
  88. package/packages/crouter-api/dist/core/runs/node-sub.js +10 -0
  89. package/packages/crouter-api/dist/core/runtime/host.js +2 -2
  90. package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
  91. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  92. package/packages/crouter-api/dist/core/runtime/warm-pool.js +1 -1
  93. package/packages/crouter-api/dist/core/spaces/process.js +5 -4
  94. package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +1 -1
  95. package/packages/crouter-api/dist/daemon/api/handlers/providers.js +5 -1
  96. package/packages/crouter-api/package.json +1 -1
  97. package/packages/crouter-identity/dist/index.d.ts +8 -0
  98. package/packages/crouter-identity/dist/index.js +18 -0
  99. package/packages/crouter-identity/package.json +1 -1
  100. package/packages/crouter-plugin/package.json +3 -3
  101. package/runtime.lock.json +14 -14
  102. package/scripts/lib/install-source.mjs +5 -1
@@ -1,10 +1,10 @@
1
- var G=Object.defineProperty;var c=(e,i)=>G(e,"name",{value:i,configurable:!0});import{renderRoot as V,renderBranch as B,renderLeafArgv as W,withAsyncHelpState as K,collapseWideChildren as L,rootPromotedChildren as J}from"./help.js";import{beginPreview as D,publishPreviewResult as Q,readStdinRaw as M,peekStdinRaw as X,emit as Y,handle as Z,setJsonOutput as ee,isJsonOutput as ne}from"./io.js";import{renderResult as te}from"./render.js";import{CrtrError as R}from"./errors.js";import{validateValue as ie}from"../api/command-manifest/result.js";import{isManifestStaleError as re}from"./manifest-stale.js";import{operationIdContext as ae}from"./events/operation-id.js";import{ExitCode as _}from"../types.js";import{envNodeId as oe,providerProjectionOverBrokerRelay as se}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as le}from"node:child_process";import{constants as fe}from"node:os";import{resolve as ce}from"node:path";function F(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const i of Object.values(e))F(i);return Object.freeze(e)}c(F,"freezeCommandMetadata");function Ve(e){const i=F(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:i,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>K(i,r,n)),slash:e.slash===void 0?void 0:F(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}c(Ve,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}c(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(i=>i.tier!=="hidden").length}c(I,"visibleSubCount");function Be(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(i=>{const r=I(i);return{name:i.name,description:i.description??"",whenToUse:i.whenToUse??"",tier:O(i),kind:i.kind,...i.plugin!==void 0?{plugin:i.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}c(Be,"defineBranch");function Je(e){const i=[],r=c(n=>{if(n.slash!==void 0&&i.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return i}c(Je,"collectSlashSpecs");function Me(e){const i=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(s=>s.tier!=="hidden"),l=J(a).map(s=>({path:`${n.name} ${s.name}`,desc:s.tier==="important"?s.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:l.length>0?l:void 0,otherSubcommandCount:a.length-l.length}});return{kind:"root",help:{tagline:e.tagline,commands:i,globals:e.globals},subtrees:e.subtrees}}c(Me,"defineRoot");function ue(e){if(e.kind==="root")return e.subtrees.filter(i=>O(i)!=="hidden").map(i=>i.name);if(e.kind==="branch"){const{listed:i,unlisted:r}=L(e.children.filter(n=>O(n)!=="hidden"));return[...i.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}c(ue,"childNames");function he(e,i){let r=e;const n=[];let a=0;for(;a<i.length;){const l=i[a];if(l==="-h"||l==="--help")break;if(r.kind==="root"){const s=r.subtrees.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else if(r.kind==="branch"){const s=r.children.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else break}return{node:r,path:n,remaining:i.slice(a)}}c(he,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):W(e.help)}c(me,"renderNode");async function z(e,i,r){if(r!==void 0&&e.kind==="leaf")return W(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?W(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(i.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:l},{SUBTREE_NAMES:s,coreCommandPathsCovering:o,extensibleCoreBranches:y}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),v=await l(i.join(" "),{reservedCoreNames:new Set(s),coreCommandPaths:o,extensibleCoreBranches:y});return n+v.map(P=>`
1
+ var G=Object.defineProperty;var f=(e,t)=>G(e,"name",{value:t,configurable:!0});import{parsePrincipal as K}from"@north-light/identity";import{renderRoot as V,renderBranch as B,renderLeafArgv as T,withAsyncHelpState as L,collapseWideChildren as D,rootPromotedChildren as J}from"./help.js";import{beginPreview as Q,publishPreviewResult as X,readStdinRaw as M,peekStdinRaw as Y,emit as Z,handle as ee,setJsonOutput as ne,isJsonOutput as te}from"./io.js";import{renderResult as ie}from"./render.js";import{CrtrError as H}from"./errors.js";import{validateValue as re}from"../api/command-manifest/result.js";import{isManifestStaleError as ae}from"./manifest-stale.js";import{operationIdContext as oe}from"./events/operation-id.js";import{ExitCode as j}from"../types.js";import{envNodeId as se,providerProjectionOverBrokerRelay as le}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as fe}from"node:child_process";import{constants as ce}from"node:os";import{resolve as ue}from"node:path";function q(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const t of Object.values(e))q(t);return Object.freeze(e)}f(q,"freezeCommandMetadata");function Me(e){const t=q(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:t,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>L(t,r,n)),slash:e.slash===void 0?void 0:q(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,actingAs:e.actingAs,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}f(Me,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}f(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(t=>t.tier!=="hidden").length}f(I,"visibleSubCount");function Ie(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(t=>{const r=I(t);return{name:t.name,description:t.description??"",whenToUse:t.whenToUse??"",tier:O(t),kind:t.kind,...t.plugin!==void 0?{plugin:t.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}f(Ie,"defineBranch");function ze(e){const t=[],r=f(n=>{if(n.slash!==void 0&&t.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return t}f(ze,"collectSlashSpecs");function Ge(e){const t=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(o=>o.tier!=="hidden"),d=J(a).map(o=>({path:`${n.name} ${o.name}`,desc:o.tier==="important"?o.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:d.length>0?d:void 0,otherSubcommandCount:a.length-d.length}});return{kind:"root",help:{tagline:e.tagline,commands:t,globals:e.globals},subtrees:e.subtrees}}f(Ge,"defineRoot");function he(e){if(e.kind==="root")return e.subtrees.filter(t=>O(t)!=="hidden").map(t=>t.name);if(e.kind==="branch"){const{listed:t,unlisted:r}=D(e.children.filter(n=>O(n)!=="hidden"));return[...t.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}f(he,"childNames");function pe(e,t){let r=e;const n=[];let a=0;for(;a<t.length;){const d=t[a];if(d==="-h"||d==="--help")break;if(r.kind==="root"){const o=r.subtrees.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else if(r.kind==="branch"){const o=r.children.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else break}return{node:r,path:n,remaining:t.slice(a)}}f(pe,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):T(e.help)}f(me,"renderNode");async function z(e,t,r){if(r!==void 0&&e.kind==="leaf")return T(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?T(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(t.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:d},{SUBTREE_NAMES:o,coreCommandPathsCovering:s,extensibleCoreBranches:x}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),k=await d(t.join(" "),{reservedCoreNames:new Set(o),coreCommandPaths:s,extensibleCoreBranches:x});return n+k.map(E=>`
2
2
 
3
- <plugin-help plugin="${P.plugin}">
4
- ${P.text}
5
- </plugin-help>`).join("")}c(z,"renderNodeWithAddenda");function pe(e){return e.some(i=>i==="-h"||i==="--help")}c(pe,"helpRequested");function ge(e,i){if(e.kind!=="leaf"||i.length!==2)return;const[r,n]=i;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(s=>s.kind==="flag"&&s.name===a)?.focusedHelp!==void 0?a:void 0}c(ge,"focusedHelpFlag");function we(e,i){let r=0;for(let n=0;n<e.length;n++){if(r===i.length)return e.slice(n);e[n]!=="--json"&&e[n]===i[r]&&r++}return[]}c(we,"rawArgsAfterPath");function ve(e,i){const r=le(e.bin,i,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new R("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,_.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=fe.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}c(ve,"runPassthrough");function be(e,i,r){const n=ue(e),a=n.length>0?n.join(", "):"(none)",l=i.length>0?`crtr ${i.join(" ")} -h`:"crtr -h",s=n.some(o=>o.startsWith("(and "));return new R("unknown_path",`unknown subcommand: ${r}`,_.USAGE,{received:r,next:s?`Valid children include: ${a}. Run \`${l}\` for how to find the rest.`:`Valid children: ${a}. Run \`${l}\` for the full list.`})}c(be,"unknownPathError");function xe(e){const i="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new R("not_joined",`\`crtr ${e}\` isn't a command here. ${i}`,_.USAGE,{received:e,next:i})}c(xe,"notJoinedError");async function ke(){if(se())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:i}=await import("../daemon/machine-link/config.js");return i()===void 0&&!e("user").runtime?.issuer}catch{return!1}}c(ke,"runtimeUnjoined");function m(e,i,r,n,a){return new R(e,i,_.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}c(m,"parseArgvError");function $(e){return e.replace(/-([a-z])/g,(i,r)=>r.toUpperCase())}c($,"flagNameToKey");async function $e(e,i,r){const n={},a=new Set,l=new Map,s=e.filter(t=>t.kind==="positional"),o=e.find(t=>t.kind==="stdin"),y=e.find(t=>t.kind==="context-file"),v=e.filter(t=>t.kind==="flag"),P=new Map(v.map(t=>[t.name,t])),C=v.some(t=>t.sensitive===!0);for(const t of v)t.type==="bool"?n[$(t.name)]=t.default!==void 0?t.default:!1:t.default!==void 0&&(n[$(t.name)]=t.default);const w=[];let b=0,U=!1,u=0;for(;u<i.length;){const t=i[u];if(t==="--"&&!U){U=!0,u++;continue}if(!U&&t.startsWith("--")){const h=t.indexOf("=");let d,E;if(h!==-1?(d=t.slice(2,h),E=t.slice(h+1)):d=t.slice(2),d==="context-file"){if(y===void 0)throw m("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const f=E!==void 0?E:i[++u];if(f===void 0)throw m("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let k;try{k=de(f,"utf8")}catch{throw m("invalid_type",`--context-file: cannot read file: ${f}`,f,"context-file","Provide a readable file path.")}let q;try{q=JSON.parse(k)}catch{throw m("invalid_type",`--context-file: file is not valid JSON: ${f}`,f,"context-file","Ensure the file contains a valid JSON object.")}const T=$(y.name);n[T]=q,l.set(T,ce(f)),a.add(T),u++;continue}const A=P.has(d)||!d.startsWith("no-")?void 0:P.get(d.slice(3));if(A!==void 0&&A.type==="bool"){if(E!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${E}`,A.name,`Use --${d} (presence = false) with no value.`);const f=$(A.name);a.add(f),n[f]=!1,u++;continue}const x=P.get(d);if(x===void 0)throw m("unknown_flag",`unknown flag: --${d}`,`--${d}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const j=$(d);if(a.has(j)&&x.type!=="bool"&&x.repeatable!==!0)throw m("bad_invocation",`--${d} given twice; it takes one value`,`--${d}`,d,`Pass --${d} once.`);if(a.add(j),x.type==="bool"){if(E!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${E}`,d,`Use --${d} (presence = true) or --no-${d} (false), with no value.`);n[j]=!0,u++;continue}const S=E!==void 0?E:i[++u];if(S===void 0||E===void 0&&S.startsWith("--")){const f=x.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${d} -h\` and read the focused value contract before retrying.`:void 0;throw m("missing_parameter",`--${d} requires a value`,`--${d}`,d,f)}let N;if(x.type==="int"){const f=Number(S);if(!Number.isInteger(f))throw m("invalid_type",`--${d} must be an integer`,S,d,`Provide an integer value for --${d}.`);N=f}else if(x.type==="enum"){const f=x.choices;if(f!==void 0&&!f.includes(S))throw m("invalid_type",`--${d} must be one of: ${f.join(", ")}`,S,d,`Retry with one of: ${f.join(", ")}.`);N=S}else if(x.type==="json"){let f;try{f=JSON.parse(S)}catch{throw m("invalid_type",`--${d} is not valid JSON`,S,d,`Pass one JSON value for --${d}; run -h for its shape.`)}const k=x.shape===void 0?null:ie(x.shape,f,`--${d}`);if(k!==null)throw m("invalid_type",`${k.path} must be ${k.expected}, got ${k.receivedType}`,S,k.path,`Fix ${k.path}; run -h for the shape of --${d}.`);N=f}else N=S;if(x.repeatable===!0){const f=n[j],k=Array.isArray(f)?f:[];k.push(N),n[j]=k}else n[j]=N;u++;continue}const p=s[b];if(p!==void 0){const h=$(p.name);if(p.repeatable===!0){const d=n[h]??[];d.push(t),n[h]=d}else n[h]=t,b++;w.push(t),a.add(h),u++;continue}if(w.length>0){if(o!==void 0&&s.length===0){w.push(t),u++;continue}throw o!==void 0?m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):m("bad_invocation",C?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${t}`,C?void 0:i.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(s.length===0&&(o===void 0||o.allowPositional===!1))throw m("bad_invocation",C?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${t}`,C?void 0:t,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(t),u++}let g=!1;if(o!==void 0){if(w.length>1&&s.length===0){const t=o.positionalStdinConflict?.(n);throw t!==void 0?m("bad_invocation",t.message,void 0,t.field,t.next):m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&s.length===0&&o.allowPositional!==!1){const t=w[0];if(t==="-"){const p=await M();(p.trim()!==""||!o.required)&&(n[$(o.name)]=p),g=!0}else{if((await X()).trim()!==""){const h=o.positionalStdinConflict?.(n);throw m("bad_invocation",h?.message??`both a positional argument ("${t}") and piped stdin were provided for ${o.name}`,t,h?.field??o.name,h?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[$(o.name)]=t,g=!0}}else{const t=await M();t!==""&&(t.trim()!==""||!o.required)&&(n[$(o.name)]=t,g=!0)}}g&&o!==void 0&&a.add($(o.name));for(const t of e){if(t.kind!=="flag"&&t.kind!=="positional"||t.defaultFromEnv===void 0)continue;const p=$(t.name);if(a.has(p))continue;const h=process.env[t.defaultFromEnv];h===void 0||h===""||(n[p]=t.kind==="positional"&&t.repeatable===!0?[h]:h,a.add(p))}const H=[];for(const t of e){const p=$(t.name),h=t.kind==="flag"&&t.type==="bool"&&!a.has(p);if(t.required&&(h||n[p]===void 0||n[p]===null)){const d=t.kind==="positional"?`positional ${t.name.toUpperCase()}`:t.kind==="flag"?`--${t.name}`:t.kind==="context-file"?"--context-file":"stdin";H.push({display:d,name:t.name})}}if(H.length>0){const t=H.map(d=>d.display).join(", "),p=r?.leafPath,h=p!==void 0&&p.length>0?`\`crtr ${p.join(" ")} -h\``:"this command with -h";throw m("missing_parameter",H.length===1?`required parameter is missing: ${t}`:`required parameters are missing: ${t}`,void 0,H.map(d=>d.name).join(", "),`Run ${h} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(l),n}c($e,"parseArgv");function ye(e){const i=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){i.push(...e.slice(n));break}const l=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&l===void 0){i.push(a);continue}const s=l??e[n+1];if(s===void 0||s===""||l===void 0&&s.startsWith("-"))throw m("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");l===void 0&&n++,r=s}return r===void 0?{rest:i}:{rest:i,machine:r}}c(ye,"takeMachineSelector");const Se=new Set(["--json","--no-autostart"]);async function Ie(e,i){const r=i.slice(2);r.includes("--json")&&ee(!0);const n=r.filter(o=>!Se.has(o));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const o=oe()?{...e.help,commands:await Promise.all(e.help.commands.map(async y=>{const v=e.subtrees.find(b=>b.name===y.name);if(v?.effectiveHelp===void 0)return y;const C=((await v.effectiveHelp()).listing??[]).filter(b=>b.tier!=="hidden"),w=J(C).map(b=>({path:`${v.name} ${b.name}`,desc:b.tier==="important"?b.description:void 0}));return{...y,subcommands:w.length?w:void 0,otherSubcommandCount:C.length-w.length}}))}:e.help;process.stdout.write(V(o)+`
6
- `),process.exitCode=_.SUCCESS;return}if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){const{readPackageVersion:o}=await import("../commands/sys/shared.js");process.stdout.write(o()+`
7
- `),process.exitCode=_.SUCCESS;return}let{node:a,path:l,remaining:s}=he(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&ve(a.passthrough,we(r,l)),a.kind==="branch"&&a.refusal!==void 0&&s[0]!=="-h"&&s[0]!=="--help")throw new R(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&s.length>0&&s[0]!=="-h"&&s[0]!=="--help")throw a.kind==="root"&&!s[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!s[0].startsWith("-")&&await ke()?xe(s[0]):be(a,l,s[0]);if(pe(s)){process.stdout.write(await z(a,l,ge(a,s))+`
8
- `),process.exitCode=_.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await z(a,l)+`
9
- `),process.exitCode=_.SUCCESS;return}const o=a;D(l.join(" "));const y=o.help.params!==void 0?o.help.params:[];let v=new Set,P=new Map,C=s,w;if(o.machineSelector===!0&&!y.some(g=>g.kind==="flag"&&g.name==="machine")){const g=ye(s);C=g.rest,w=g.machine}const b=await $e(y,C,{leafPath:l,onProvidedParams:c(g=>{v=g},"onProvidedParams"),onContextFilePaths:c(g=>{P=g},"onContextFilePaths")}),U={providedParams:v,contextFilePaths:P,...w===void 0?{}:{machine:w}},u=await ae.fresh(()=>o.run(b,U));if(Q(u==null?u:o.preview?.(u)??u),u!=null)if(ne())Y(u);else{const g=o.render!==void 0?o.render(u):te(u,o.help);process.stdout.write(g+(o.stdoutExact?.(u)?"":`
10
- `))}}catch(o){if(re(o))throw o;Z(o)}}c(Ie,"runCli");export{Se as GLOBAL_TOKENS,Je as collectSlashSpecs,Be as defineBranch,Ve as defineLeaf,Me as defineRoot,xe as notJoinedError,$e as parseArgv,me as renderNode,Ie as runCli,ye as takeMachineSelector,be as unknownPathError,he as walk};
3
+ <plugin-help plugin="${E.plugin}">
4
+ ${E.text}
5
+ </plugin-help>`).join("")}f(z,"renderNodeWithAddenda");function ge(e){return e.some(t=>t==="-h"||t==="--help")}f(ge,"helpRequested");function we(e,t){if(e.kind!=="leaf"||t.length!==2)return;const[r,n]=t;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(o=>o.kind==="flag"&&o.name===a)?.focusedHelp!==void 0?a:void 0}f(we,"focusedHelpFlag");function ve(e,t){let r=0;for(let n=0;n<e.length;n++){if(r===t.length)return e.slice(n);e[n]!=="--json"&&e[n]===t[r]&&r++}return[]}f(ve,"rawArgsAfterPath");function be(e,t){const r=fe(e.bin,t,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new H("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,j.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=ce.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}f(be,"runPassthrough");function xe(e,t,r){const n=he(e),a=n.length>0?n.join(", "):"(none)",d=t.length>0?`crtr ${t.join(" ")} -h`:"crtr -h",o=n.some(s=>s.startsWith("(and "));return new H("unknown_path",`unknown subcommand: ${r}`,j.USAGE,{received:r,next:o?`Valid children include: ${a}. Run \`${d}\` for how to find the rest.`:`Valid children: ${a}. Run \`${d}\` for the full list.`})}f(xe,"unknownPathError");function ke(e){const t="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new H("not_joined",`\`crtr ${e}\` isn't a command here. ${t}`,j.USAGE,{received:e,next:t})}f(ke,"notJoinedError");async function $e(){if(le())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:t}=await import("../daemon/machine-link/config.js");return t()===void 0&&!e("user").runtime?.issuer}catch{return!1}}f($e,"runtimeUnjoined");function h(e,t,r,n,a){return new H(e,t,j.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}f(h,"parseArgvError");function P(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}f(P,"flagNameToKey");async function ye(e,t,r){const n={},a=new Set,d=new Map,o=e.filter(i=>i.kind==="positional"),s=e.find(i=>i.kind==="stdin"),x=e.find(i=>i.kind==="context-file"),k=e.filter(i=>i.kind==="flag"),E=new Map(k.map(i=>[i.name,i])),$=k.some(i=>i.sensitive===!0);for(const i of k)i.type==="bool"?n[P(i.name)]=i.default!==void 0?i.default:!1:i.default!==void 0&&(n[P(i.name)]=i.default);const w=[];let v=0,A=!1,b=0;for(;b<t.length;){const i=t[b];if(i==="--"&&!A){A=!0,b++;continue}if(!A&&i.startsWith("--")){const p=i.indexOf("=");let l,_;if(p!==-1?(l=i.slice(2,p),_=i.slice(p+1)):l=i.slice(2),l==="context-file"){if(x===void 0)throw h("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const c=_!==void 0?_:t[++b];if(c===void 0)throw h("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let S;try{S=de(c,"utf8")}catch{throw h("invalid_type",`--context-file: cannot read file: ${c}`,c,"context-file","Provide a readable file path.")}let F;try{F=JSON.parse(S)}catch{throw h("invalid_type",`--context-file: file is not valid JSON: ${c}`,c,"context-file","Ensure the file contains a valid JSON object.")}const W=P(x.name);n[W]=F,d.set(W,ue(c)),a.add(W),b++;continue}const R=E.has(l)||!l.startsWith("no-")?void 0:E.get(l.slice(3));if(R!==void 0&&R.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,R.name,`Use --${l} (presence = false) with no value.`);const c=P(R.name);a.add(c),n[c]=!1,b++;continue}const y=E.get(l);if(y===void 0)throw h("unknown_flag",`unknown flag: --${l}`,`--${l}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const N=P(l);if(a.has(N)&&y.type!=="bool"&&y.repeatable!==!0)throw h("bad_invocation",`--${l} given twice; it takes one value`,`--${l}`,l,`Pass --${l} once.`);if(a.add(N),y.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,l,`Use --${l} (presence = true) or --no-${l} (false), with no value.`);n[N]=!0,b++;continue}const C=_!==void 0?_:t[++b];if(C===void 0||_===void 0&&C.startsWith("--")){const c=y.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${l} -h\` and read the focused value contract before retrying.`:void 0;throw h("missing_parameter",`--${l} requires a value`,`--${l}`,l,c)}let U;if(y.type==="int"){const c=Number(C);if(!Number.isInteger(c))throw h("invalid_type",`--${l} must be an integer`,C,l,`Provide an integer value for --${l}.`);U=c}else if(y.type==="enum"){const c=y.choices;if(c!==void 0&&!c.includes(C))throw h("invalid_type",`--${l} must be one of: ${c.join(", ")}`,C,l,`Retry with one of: ${c.join(", ")}.`);U=C}else if(y.type==="json"){let c;try{c=JSON.parse(C)}catch{throw h("invalid_type",`--${l} is not valid JSON`,C,l,`Pass one JSON value for --${l}; run -h for its shape.`)}const S=y.shape===void 0?null:re(y.shape,c,`--${l}`);if(S!==null)throw h("invalid_type",`${S.path} must be ${S.expected}, got ${S.receivedType}`,C,S.path,`Fix ${S.path}; run -h for the shape of --${l}.`);U=c}else U=C;if(y.repeatable===!0){const c=n[N],S=Array.isArray(c)?c:[];S.push(U),n[N]=S}else n[N]=U;b++;continue}const m=o[v];if(m!==void 0){const p=P(m.name);if(m.repeatable===!0){const l=n[p]??[];l.push(i),n[p]=l}else n[p]=i,v++;w.push(i),a.add(p),b++;continue}if(w.length>0){if(s!==void 0&&o.length===0){w.push(i),b++;continue}throw s!==void 0?h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):h("bad_invocation",$?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${i}`,$?void 0:t.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(o.length===0&&(s===void 0||s.allowPositional===!1))throw h("bad_invocation",$?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${i}`,$?void 0:i,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(i),b++}let g=!1;if(s!==void 0){if(w.length>1&&o.length===0){const i=s.positionalStdinConflict?.(n);throw i!==void 0?h("bad_invocation",i.message,void 0,i.field,i.next):h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&o.length===0&&s.allowPositional!==!1){const i=w[0];if(i==="-"){const m=await M();(m.trim()!==""||!s.required)&&(n[P(s.name)]=m),g=!0}else{if((await Y()).trim()!==""){const p=s.positionalStdinConflict?.(n);throw h("bad_invocation",p?.message??`both a positional argument ("${i}") and piped stdin were provided for ${s.name}`,i,p?.field??s.name,p?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[P(s.name)]=i,g=!0}}else{const i=await M();i!==""&&(i.trim()!==""||!s.required)&&(n[P(s.name)]=i,g=!0)}}g&&s!==void 0&&a.add(P(s.name));for(const i of e){if(i.kind!=="flag"&&i.kind!=="positional"||i.defaultFromEnv===void 0)continue;const m=P(i.name);if(a.has(m))continue;const p=process.env[i.defaultFromEnv];p===void 0||p===""||(n[m]=i.kind==="positional"&&i.repeatable===!0?[p]:p,a.add(m))}const u=[];for(const i of e){const m=P(i.name),p=i.kind==="flag"&&i.type==="bool"&&!a.has(m);if(i.required&&(p||n[m]===void 0||n[m]===null)){const l=i.kind==="positional"?`positional ${i.name.toUpperCase()}`:i.kind==="flag"?`--${i.name}`:i.kind==="context-file"?"--context-file":"stdin";u.push({display:l,name:i.name})}}if(u.length>0){const i=u.map(l=>l.display).join(", "),m=r?.leafPath,p=m!==void 0&&m.length>0?`\`crtr ${m.join(" ")} -h\``:"this command with -h";throw h("missing_parameter",u.length===1?`required parameter is missing: ${i}`:`required parameters are missing: ${i}`,void 0,u.map(l=>l.name).join(", "),`Run ${p} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(d),n}f(ye,"parseArgv");function Se(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||o===""||d===void 0&&o.startsWith("-"))throw h("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,machine:r}}f(Se,"takeMachineSelector");function Pe(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--as=")?a.slice(5):void 0;if(a!=="--as"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||K(o)===null)throw h("missing_parameter","--as requires a principal like user:<id> or app:<id>/<path>","--as","as","Name the principal this call acts for, for example `--as user:alice`.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,as:r}}f(Pe,"takeActingAs");const Ce=new Set(["--json","--no-autostart"]);async function Ke(e,t){const r=t.slice(2);r.includes("--json")&&ne(!0);const n=r.filter(s=>!Ce.has(s));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const s=se()?{...e.help,commands:await Promise.all(e.help.commands.map(async x=>{const k=e.subtrees.find(v=>v.name===x.name);if(k?.effectiveHelp===void 0)return x;const $=((await k.effectiveHelp()).listing??[]).filter(v=>v.tier!=="hidden"),w=J($).map(v=>({path:`${k.name} ${v.name}`,desc:v.tier==="important"?v.description:void 0}));return{...x,subcommands:w.length?w:void 0,otherSubcommandCount:$.length-w.length}}))}:e.help;process.stdout.write(V(s)+`
6
+ `),process.exitCode=j.SUCCESS;return}if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){const{readPackageVersion:s}=await import("../commands/sys/shared.js");process.stdout.write(s()+`
7
+ `),process.exitCode=j.SUCCESS;return}let{node:a,path:d,remaining:o}=pe(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&be(a.passthrough,ve(r,d)),a.kind==="branch"&&a.refusal!==void 0&&o[0]!=="-h"&&o[0]!=="--help")throw new H(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&o.length>0&&o[0]!=="-h"&&o[0]!=="--help")throw a.kind==="root"&&!o[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!o[0].startsWith("-")&&await $e()?ke(o[0]):xe(a,d,o[0]);if(ge(o)){process.stdout.write(await z(a,d,we(a,o))+`
8
+ `),process.exitCode=j.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await z(a,d)+`
9
+ `),process.exitCode=j.SUCCESS;return}const s=a;Q(d.join(" "));const x=s.help.params!==void 0?s.help.params:[];let k=new Set,E=new Map,$=o,w;if(s.machineSelector===!0&&!x.some(u=>u.kind==="flag"&&u.name==="machine")){const u=Se(o);$=u.rest,w=u.machine}let v;if(s.actingAs===!0&&!x.some(u=>u.kind==="flag"&&u.name==="as")){const u=Pe($);$=u.rest,v=u.as}const A=await ye(x,$,{leafPath:d,onProvidedParams:f(u=>{k=u},"onProvidedParams"),onContextFilePaths:f(u=>{E=u},"onContextFilePaths")}),b={providedParams:k,contextFilePaths:E,...w===void 0?{}:{machine:w},...v===void 0?{}:{as:v}},g=await oe.fresh(()=>s.run(A,b));if(X(g==null?g:s.preview?.(g)??g),g!=null)if(te())Z(g);else{const u=s.render!==void 0?s.render(g):ie(g,s.help);process.stdout.write(u+(s.stdoutExact?.(g)?"":`
10
+ `))}}catch(s){if(ae(s))throw s;ee(s)}}f(Ke,"runCli");export{Ce as GLOBAL_TOKENS,ze as collectSlashSpecs,Ie as defineBranch,Me as defineLeaf,Ge as defineRoot,ke as notJoinedError,ye as parseArgv,me as renderNode,Ke as runCli,Pe as takeActingAs,Se as takeMachineSelector,xe as unknownPathError,pe as walk};
@@ -1,7 +1,7 @@
1
1
  import type { CanvasDb } from './canvas/db.js';
2
2
  import { type EnvironmentRecipeInput } from './environment-recipe.js';
3
3
  /** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
4
- * its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
4
+ * its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. `payer` (null by default: the run's `sub` pays) names who pays; an app environment passes `person` and `grantee` as `app:<id>` and `payer` the same. Runs in the
5
5
  * caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
6
6
  * here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
7
7
  * across them, while the handle is unique per object type. Returns the environment's object id. */
@@ -9,6 +9,7 @@ export declare function createProfileBlaxelEnvironment(db: CanvasDb, spec: {
9
9
  profileId: string;
10
10
  grantee: string;
11
11
  person: string;
12
+ payer?: string;
12
13
  memoryMb?: number;
13
14
  recipe?: EnvironmentRecipeInput;
14
15
  }): Promise<string>;
@@ -1 +1 @@
1
- var n=Object.defineProperty;var o=(r,e)=>n(r,"name",{value:e,configurable:!0});import{withCanvasWrite as l}from"./canvas/db.js";import{createObject as m,ensureOwner as p,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as f}from"./permissions/facts.js";import{writeEnvironmentRecipe as c}from"./environment-recipe.js";import{setCloudProfileWriter as d}from"./profiles/manifest.js";async function u(r,e){const t=await w(r,e.grantee),a=await p(r,"profile","profile",e.profileId,e.profileId,t),i=await m(r,{type:"environment",kind:"blaxel",owner:a.id,privacy:"private",name:e.profileId,preview:"blaxel"});return await f(r,i.id,e.person),await r.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)").run(i.id,e.memoryMb??2048,new Date().toISOString()),e.recipe!==void 0&&await c(r,i.id,e.recipe),i.id}o(u,"createProfileBlaxelEnvironment"),d((r,e)=>l(async t=>{await e(await u(t,r))}));export{u as createProfileBlaxelEnvironment};
1
+ var o=Object.defineProperty;var a=(r,e)=>o(r,"name",{value:e,configurable:!0});import{withCanvasWrite as l}from"./canvas/db.js";import{createObject as m,ensureOwner as p,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as f}from"./permissions/facts.js";import{writeEnvironmentRecipe as u}from"./environment-recipe.js";import{setCloudProfileWriter as c}from"./profiles/manifest.js";async function d(r,e){const t=await w(r,e.grantee),n=await p(r,"profile","profile",e.profileId,e.profileId,t),i=await m(r,{type:"environment",kind:"blaxel",owner:n.id,privacy:"private",name:e.profileId,preview:"blaxel"});return await f(r,i.id,e.person),await r.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)").run(i.id,e.memoryMb??2048,e.payer??null,new Date().toISOString()),e.recipe!==void 0&&await u(r,i.id,e.recipe),i.id}a(d,"createProfileBlaxelEnvironment"),c((r,e)=>l(async t=>{await e(await d(t,r))}));export{d as createProfileBlaxelEnvironment};
@@ -189,6 +189,10 @@ export declare function teamsOf(value: unknown): TeamRecord[];
189
189
  /** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
190
190
  * ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
191
191
  export declare function replaceGrants(grants: readonly GrantRecord[], syncedAt: string, source: string, teams?: readonly TeamRecord[]): Promise<void>;
192
+ export declare const APP_ADMIN_WRITER = "app-admin";
193
+ /** Make `editor`, `messenger` and `user_of` on each app object exactly its app's `admin` tuples (a `user` or a `crtr/group#member` team),
194
+ * so a removed admin loses them. Runs in the caller's transaction; the admin tuples are the directory's, the facts it writes are `written_by = 'app-admin'`. */
195
+ export declare function reconcileAppAdminFacts(db: CanvasDb): Promise<void>;
192
196
  /** Bumped by every `replaceGrants`. A launch compiled against one generation
193
197
  * and started under another may hold mounts the new mirror no longer grants. */
194
198
  export declare function grantsGeneration(): Promise<number>;
@@ -1,11 +1,11 @@
1
- var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";import{shadowCheck as $}from"./shadow.js";const F=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(v,"runtimeScope");async function i(e,r,t=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function U(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(U,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!U(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!F.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(G,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=G(s);o&&(r[t]=o)}return r}n(O,"dependenciesOf");function H(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of k){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(H,"inferenceEndpointOf");function A(e,r,t,s){return r===e&&t&&s}n(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?H(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{const r=B(f(e));return r!==null&&$(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}n(_,"mirrorOnly");async function se(){return(await V()).filter(e=>!_(e))}n(se,"localGrants");async function ae(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(ae,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",W=new RegExp(`^(${y}):(${y})$`);function P(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=W.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(P,"providerIdsFromGrants");async function oe(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var I=Object.defineProperty;var n=(e,t)=>I(e,"name",{value:t,configurable:!0});import{createHash as L}from"node:crypto";import{parseScope as C}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as M}from"../permissions/facts.js";import{GROUP_TYPE as _,OBJECT_TYPE as F}from"../permissions/builtin.js";import{shadowCheck as $}from"./shadow.js";const k=["not_started","pending","ready","failed","unavailable"],U=["ultra","strong","medium","light"];function m(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(m,"runtimeScope");async function i(e,t,r=[]){const s=m();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${t})${s.sql}`).all(...r,...s.args)}n(i,"grantRows");async function u(e,t,r=[]){return(await i(e,t,r))[0]}n(u,"grantRow");function G(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(G,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(t=>{if(!t||typeof t!="object"||typeof t.scope!="string"||!G(t.scope)||!["always","ask"].includes(t.mode))throw new TypeError("invalid grant scope entry");return{scope:t.scope,mode:t.mode}})}n(l,"entries");function H(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:t,message:r,next:s,step:o}=e;return typeof t!="string"||!k.includes(t)||r!==void 0&&typeof r!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:t,...r===void 0?{}:{message:r},next:s,...o===void 0?{}:{step:o}}}n(H,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e)){const o=H(s);o&&(t[r]=o)}return t}n(O,"dependenciesOf");function W(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:t,rungs:r}=e;if(typeof t!="string"||!t||!r||typeof r!="object"||Array.isArray(r))return null;const s={};for(const o of U){const a=r[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:t.replace(/\/+$/,""),rungs:s}:null}n(W,"inferenceEndpointOf");function b(e,t,r,s){return t===e&&r&&s}n(b,"computedFor");function f(e){if(!b(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?W(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{const t=X(f(e));return t!==null&&$(t),t}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(d,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function ie(){return(await q()).filter(e=>!y(e))}n(ie,"localGrants");async function ue(e,t){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,t])!==void 0}n(ue,"otherLiveGrantOfApp");const E="[A-Za-z0-9_-]{1,64}",P=new RegExp(`^(${E}):(${E})$`);function J(e){const t=new Set;for(const r of e)if(r.status==="active")for(const{scope:s}of r.resolved_scopes){const o=P.exec(s);o&&o[1]!=="crtr"&&t.add(o[1])}return[...t].sort()}n(J,"providerIdsFromGrants");async function pe(){const e=m();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
- SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
3
+ SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${x}${S()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
- CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
6
- WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(oe,"activeProviderIds");async function ce(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(ce,"anyActiveGrant");async function ie(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
5
+ CROSS JOIN LATERAL regexp_match(s.scope, '^(${E}):${E}$') m
6
+ WHERE m[1] <> 'crtr'`).all(...e.args)).map(r=>r.id).sort()}n(pe,"activeProviderIds");async function de(){const e=m();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${x}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(de,"anyActiveGrant");async function le(e,t){return await u("1",`sub = ? AND ${x}${S()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ie,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",J="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}n(x,"localOnly");async function ue(){return(await i("DISTINCT sub",J)).map(e=>e.sub)}n(ue,"grantSubs");async function pe(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(pe,"activeGrants");async function de(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(P(r.flatMap(t=>{try{return[f(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(de,"grantedProviderIds");function le(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(le,"isProviderBundleRow");async function fe(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=d(t);return s===null?[]:[s]})}n(fe,"activeGrantsOfPerson");async function V(){return j(await i("*","true"))}n(V,"allGrants");async function _e(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!A(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(_e,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(j,"records");function q(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(q,"grantExpired");function B(e){if(e.status!=="active"||q(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>L(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(B,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function ye(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}n(ye,"grantVersion");async function Ee(e){return!!await u("1","id = ?",[e])}n(Ee,"hasGrant");async function ge(e){return await u("rev, status","id = ?",[e])??null}n(ge,"grantSyncState");async function ve(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(ve,"grantSyncStateFor");async function X(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(X,"grantRecord");async function me(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=d(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(me,"grantStanding");async function xe(e){return(await i("id",e)).map(r=>r.id)}n(xe,"grantIdsWhere");async function Se(e){return(e?(await X(e))?.payer:null)??"user"}n(Se,"payerOfGrant");async function z(e){return d(await u("*","id = ?",[e]))}n(z,"activeGrant");async function Te(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}n(Te,"grantFor");async function Ne(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}n(Ne,"activeGrantForApp");async function Oe(e){const r=await z(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(Oe,"runNoticeTarget");async function Ae(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}n(Ae,"terminalGrant");async function je(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(je,"grantsSource");async function we(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(we,"hasSyncedGrants");async function be(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(be,"dropLocalGrantMirror");async function he(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(he,"backfillComputedRev");function Re(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Re,"teamsOf");async function De(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${t}:`])!==void 0}n(le,"activeGrantNamesApp");const x="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",V="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function _e(){return(await i("DISTINCT sub",V)).map(e=>e.sub)}n(_e,"grantSubs");async function fe(e){return w(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(fe,"activeGrants");async function ye(e){const t=await i("*","sub = ? AND status = 'active'",[e]);return new Set(J(t.flatMap(r=>{try{return[f(r)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ye,"grantedProviderIds");function Ee(e,t){return e.source_marketplace===null&&e.source_path===null&&t.has(e.name)}n(Ee,"isProviderBundleRow");async function ge(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(r=>{const s=d(r);return s===null?[]:[s]})}n(ge,"activeGrantsOfPerson");async function q(){return w(await i("*","true"))}n(q,"allGrants");async function ve(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(r=>{if(!b(r.rev,r.computed_rev,r.has_scopes,r.resolved_scopes_json!==null))return[];try{return[{sub:r.sub,status:r.status,resolved_scopes:l(JSON.parse(r.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(ve,"grantsOfPerson");function w(e){return e.flatMap(t=>{try{return[f(t)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}n(w,"records");function B(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(B,"grantExpired");function X(e){if(e.status!=="active"||B(e))return null;try{const t=e.resolved_scopes.map(({scope:r})=>C(r));return{...e,resolved:e.resolved_scopes.flatMap(({mode:r},s)=>r==="always"?[t[s]]:[])}}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(X,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(t=>e[t]!==void 0).map(t=>`${JSON.stringify(t)}:${N(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function me(e){const t={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return L("sha256").update(N(t)).digest("base64url").slice(0,22)}n(me,"grantVersion");async function xe(e){return!!await u("1","id = ?",[e])}n(xe,"hasGrant");async function Se(e){return await u("rev, status","id = ?",[e])??null}n(Se,"grantSyncState");async function Ne(e,t){return await u("rev, status","grantee = ? AND sub = ?",[e,t])??null}n(Ne,"grantSyncStateFor");async function Y(e){const t=await u("*","id = ?",[e]);if(!t)return null;try{return f(t)}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Y,"grantRecord");async function Te(e){const t=await u("*","id = ?",[e]);if(!t)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const r={rev:t.rev,sub:t.sub,grantee:t.grantee,status:t.status,removal_done_at:t.removal_done_at??null};if(t.status!=="active")return{...r,standing:"inactive",record:null};if(t.computed_rev!==t.rev)return{...r,standing:"lagging",record:null};const s=d(t);return s===null?{...r,standing:"inactive",record:null}:{...r,standing:"active",record:s}}n(Te,"grantStanding");async function Ae(e){return(await i("id",e)).map(t=>t.id)}n(Ae,"grantIdsWhere");async function je(e){return(e?(await Y(e))?.payer:null)??"user"}n(je,"payerOfGrant");async function z(e){return d(await u("*","id = ?",[e]))}n(z,"activeGrant");async function Oe(e,t){return d(await u("*","grantee = ? AND sub = ?",[e,t]))}n(Oe,"grantFor");async function be(e){if(y({grantee:e}))return null;const t=await i("*","grantee = ? AND status = 'active'",[e]);if(t.length>1)throw new Error(`multiple active grants for ${e}`);return d(t[0])}n(be,"activeGrantForApp");async function we(e){const t=await z(e);return t&&t.run_notice_url&&!y(t)?{url:t.run_notice_url,sub:t.sub,grantee:t.grantee}:null}n(we,"runNoticeTarget");async function Re(e){const t=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(t.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(t[0])}n(Re,"terminalGrant");async function he(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(he,"grantsSource");async function De(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(De,"hasSyncedGrants");async function Ie(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Ie,"dropLocalGrantMirror");async function Le(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(Le,"backfillComputedRev");function Ce(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const t=[];for(const r of e){const{team:s,members:o}=r??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");t.push({team:s,members:o})}}return t}n(Ce,"teamsOf");async function Me(e,t,r,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let g=0;const v=[...o];g+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,4 +19,6 @@ var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(De,"replaceGrants");async function Le(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Le,"grantsGeneration");export{z as activeGrant,Ne as activeGrantForApp,ie as activeGrantNamesApp,pe as activeGrants,fe as activeGrantsOfPerson,oe as activeProviderIds,B as activeRecord,V as allGrants,ce as anyActiveGrant,he as backfillComputedRev,S as canonicalJson,O as dependenciesOf,be as dropLocalGrantMirror,q as grantExpired,Te as grantFor,xe as grantIdsWhere,X as grantRecord,me as grantStanding,ue as grantSubs,ge as grantSyncState,ve as grantSyncStateFor,ye as grantVersion,de as grantedProviderIds,Le as grantsGeneration,_e as grantsOfPerson,je as grantsSource,Ee as hasGrant,we as hasSyncedGrants,H as inferenceEndpointOf,le as isProviderBundleRow,se as localGrants,_ as mirrorOnly,ae as otherLiveGrantOfApp,Se as payerOfGrant,P as providerIdsFromGrants,De as replaceGrants,Oe as runNoticeTarget,v as runtimeScope,Re as teamsOf,Ae as terminalGrant};
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)g+=Number((await R.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await j(a,"directory",_,"member",s.flatMap(({team:c,members:h})=>h.map(D=>({resourceId:c,subject:M(D)})))),await Q(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r),g>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(Me,"replaceGrants");const Z=["editor","messenger","user_of"],K="app-admin";async function Q(e){const r=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
23
+ JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
24
+ WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(_)).map(s=>({resourceId:s.object,subject:s.subject_type===_?{type:_,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of Z)await j(e,K,F,s,r)}n(Q,"reconcileAppAdminFacts");async function Fe(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Fe,"grantsGeneration");export{K as APP_ADMIN_WRITER,z as activeGrant,be as activeGrantForApp,le as activeGrantNamesApp,fe as activeGrants,ge as activeGrantsOfPerson,pe as activeProviderIds,X as activeRecord,q as allGrants,de as anyActiveGrant,Le as backfillComputedRev,N as canonicalJson,O as dependenciesOf,Ie as dropLocalGrantMirror,B as grantExpired,Oe as grantFor,Ae as grantIdsWhere,Y as grantRecord,Te as grantStanding,_e as grantSubs,Se as grantSyncState,Ne as grantSyncStateFor,me as grantVersion,ye as grantedProviderIds,Fe as grantsGeneration,ve as grantsOfPerson,he as grantsSource,xe as hasGrant,De as hasSyncedGrants,W as inferenceEndpointOf,Ee as isProviderBundleRow,ie as localGrants,y as mirrorOnly,ue as otherLiveGrantOfApp,je as payerOfGrant,J as providerIdsFromGrants,Q as reconcileAppAdminFacts,Me as replaceGrants,we as runNoticeTarget,m as runtimeScope,Ce as teamsOf,Re as terminalGrant};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var d=(t,e)=>b(t,"name",{value:e,configurable:!0});import{relative as x,sep as _}from"node:path";import{runningJobs as y}from"../graph/jobs.js";import{appSpace as h}from"../layout.js";import{getNode as l,recordSettledTurn as S}from"../canvas/index.js";import{transition as E}from"../runtime/lifecycle.js";import{openDb as m}from"../canvas/db.js";import{emitEvent as w}from"../events/emit.js";import{grantedMounts as R,isGrantedSource as k,mountAllowed as I}from"../spaces/mounts.js";import{permissionsForRun as g}from"../spaces/permissions.js";import{stopNodeSandboxes as P}from"../spaces/stop.js";import{activeGrantForApp as A}from"./mirror.js";import{launcherPresent as C,listSandboxes as F,stopSandboxPid as M}from"./sandboxes.js";import{checkCronFire as N}from"../../daemon/cron/authority.js";import{cronExecutionFor as O}from"../../daemon/cron/live-runs.js";import{cronExecutionsReady as T}from"../../daemon/cron/run-socket.js";import{flatMapAsync as W}from"../async-array.js";import{personId as D}from"../canvas/person.js";async function v(){return new Map((await(await m()).prepare("SELECT uid, app, status FROM app_users").all()).map(t=>[t.uid,{app:t.app,status:t.status}]))}d(v,"appUserOwners");async function G(t,e){e??=await v();const n=e.get(t.uid),p=t.nodeId.startsWith("cron-"),a=p?O(t.nodeId.slice(5)):void 0;if(p&&(a===void 0||!n))return"permission_revoked";let o=null;if(a!==void 0&&n.status==="active"){const i=await N({grantee:a.grantee,sub:a.sub,grant_id:a.grantId,scopes:a.scopes});if(!i.allowed)return a.refusal??={reason:i.reason,message:i.message},"permission_revoked";o=i.scopes}if(!n||n.app==="app:terminal")return null;if(n.status!=="active")return"app_removed";const s=await l(t.nodeId);try{let i;if(a!==void 0)i=await g(a.grantee,a.sub,a.grantId,o);else if(s&&s.grantee===n.app)i=await g(n.app,s.sub??D(),s.grant_id??null,s.scopes??null);else{const r=await A(n.app);if(!r)return"permission_revoked";i=await g(n.app,r.sub,r.id,null)}const c=R(i),u=h(n.app).root;return t.mounts.every(r=>{const f=x(u,r.source);return f===""||f!==".."&&!f.startsWith(`..${_}`)&&!f.startsWith(_)||!k(n.app,r.source)||I(r,c)})?null:"permission_revoked"}catch{return"permission_revoked"}}d(G,"exceeds");async function L(t){const e=await l(t);if(!e)return;(e.status==="active"||e.status==="idle")&&await E(t,"release");const n=new Date().toISOString();await S(t,n),e.run_id&&e.run_id!==t&&await(await m()).prepare("UPDATE nodes SET last_settled_at = COALESCE(last_settled_at, ?) WHERE node_id = ?").run(n,e.run_id)}d(L,"afterRevocationStop");async function U(t){const e=new Set,n=await l(t);n?.pi_pid!=null&&e.add(n.pi_pid);for(const p of await y(await m(),t))p.pgid!==null&&e.add(p.pgid);return e}d(U,"nodePids");async function $(){if(!C())return{completion:Promise.resolve()};await T();const t=await F(),e=await v(),n=await W(t,async o=>{const s=await G(o,e);return s?[{sandbox:o,reason:s}]:[]}),p=[],a=new Map;for(const o of n){w({level:"info",event:"daemon.grants.sandbox_stop",fields:{sandbox_node:o.sandbox.nodeId,pid:o.sandbox.pid,grantee:e.get(o.sandbox.uid).app,reason:o.reason}});const s=a.get(o.sandbox.nodeId)??[];s.push(o),a.set(o.sandbox.nodeId,s)}for(const[o,s]of a){const i=await l(o),c=i?await U(o):new Set,u=i!==null&&s.some(({sandbox:r})=>c.has(r.pid));p.push((async()=>{if(u){const r=await P(o,"permission_revoked",{holdRecovery:!0,after:d(()=>L(o),"after")});if(!r.confirmed)throw r.error??new Error(`stop of ${o} was not confirmed`)}for(const{sandbox:r}of s)(!u||!c.has(r.pid))&&await M(r.pid)})().catch(r=>{w({level:"error",event:"daemon.grants.sandbox_stop_failed",...i?{node_id:o}:{fields:{sandbox_node:o}},error:r})}))}return{completion:Promise.all(p).then(()=>{})}}d($,"sweepSandboxes");async function ie(t=e=>{}){try{const{completion:e}=await $();t(e)}catch(e){w({level:"error",event:"daemon.grants.sweep_failed",error:e})}}d(ie,"onGrantSync");export{L as afterRevocationStop,G as exceeds,ie as onGrantSync,$ as sweepSandboxes};
1
+ var b=Object.defineProperty;var d=(t,e)=>b(t,"name",{value:e,configurable:!0});import{relative as x,sep as g}from"node:path";import{runningJobs as h}from"../graph/jobs.js";import{appSpace as y}from"../layout.js";import{getNode as l,recordSettledTurn as S}from"../canvas/index.js";import{transition as E}from"../runtime/lifecycle.js";import{openDb as m}from"../canvas/db.js";import{emitEvent as w}from"../events/emit.js";import{grantedMounts as R,isGrantedSource as k,mountAllowed as I}from"../spaces/mounts.js";import{permissionsForRun as _}from"../spaces/permissions.js";import{stopNodeSandboxes as P}from"../spaces/stop.js";import{activeGrantForApp as A}from"./mirror.js";import{launcherPresent as C,listSandboxes as F,stopSandboxPid as M}from"./sandboxes.js";import{checkCronFire as N}from"../../daemon/cron/authority.js";import{cronExecutionFor as O}from"../../daemon/cron/live-runs.js";import{cronExecutionsReady as T}from"../../daemon/cron/run-socket.js";import{flatMapAsync as W}from"../async-array.js";import{launchSub as D}from"../runs/node-sub.js";async function v(){return new Map((await(await m()).prepare("SELECT uid, app, status FROM app_users").all()).map(t=>[t.uid,{app:t.app,status:t.status}]))}d(v,"appUserOwners");async function G(t,e){e??=await v();const n=e.get(t.uid),p=t.nodeId.startsWith("cron-"),a=p?O(t.nodeId.slice(5)):void 0;if(p&&(a===void 0||!n))return"permission_revoked";let o=null;if(a!==void 0&&n.status==="active"){const i=await N({grantee:a.grantee,sub:a.sub,grant_id:a.grantId,scopes:a.scopes});if(!i.allowed)return a.refusal??={reason:i.reason,message:i.message},"permission_revoked";o=i.scopes}if(!n||n.app==="app:terminal")return null;if(n.status!=="active")return"app_removed";const s=await l(t.nodeId);try{let i;if(a!==void 0)i=await _(a.grantee,a.sub,a.grantId,o);else if(s&&s.grantee===n.app)i=await _(n.app,D(s.sub,s.node_id),s.grant_id??null,s.scopes??null);else{const r=await A(n.app);if(!r)return"permission_revoked";i=await _(n.app,r.sub,r.id,null)}const c=R(i),u=y(n.app).root;return t.mounts.every(r=>{const f=x(u,r.source);return f===""||f!==".."&&!f.startsWith(`..${g}`)&&!f.startsWith(g)||!k(n.app,r.source)||I(r,c)})?null:"permission_revoked"}catch{return"permission_revoked"}}d(G,"exceeds");async function L(t){const e=await l(t);if(!e)return;(e.status==="active"||e.status==="idle")&&await E(t,"release");const n=new Date().toISOString();await S(t,n),e.run_id&&e.run_id!==t&&await(await m()).prepare("UPDATE nodes SET last_settled_at = COALESCE(last_settled_at, ?) WHERE node_id = ?").run(n,e.run_id)}d(L,"afterRevocationStop");async function U(t){const e=new Set,n=await l(t);n?.pi_pid!=null&&e.add(n.pi_pid);for(const p of await h(await m(),t))p.pgid!==null&&e.add(p.pgid);return e}d(U,"nodePids");async function $(){if(!C())return{completion:Promise.resolve()};await T();const t=await F(),e=await v(),n=await W(t,async o=>{const s=await G(o,e);return s?[{sandbox:o,reason:s}]:[]}),p=[],a=new Map;for(const o of n){w({level:"info",event:"daemon.grants.sandbox_stop",fields:{sandbox_node:o.sandbox.nodeId,pid:o.sandbox.pid,grantee:e.get(o.sandbox.uid).app,reason:o.reason}});const s=a.get(o.sandbox.nodeId)??[];s.push(o),a.set(o.sandbox.nodeId,s)}for(const[o,s]of a){const i=await l(o),c=i?await U(o):new Set,u=i!==null&&s.some(({sandbox:r})=>c.has(r.pid));p.push((async()=>{if(u){const r=await P(o,"permission_revoked",{holdRecovery:!0,after:d(()=>L(o),"after")});if(!r.confirmed)throw r.error??new Error(`stop of ${o} was not confirmed`)}for(const{sandbox:r}of s)(!u||!c.has(r.pid))&&await M(r.pid)})().catch(r=>{w({level:"error",event:"daemon.grants.sandbox_stop_failed",...i?{node_id:o}:{fields:{sandbox_node:o}},error:r})}))}return{completion:Promise.all(p).then(()=>{})}}d($,"sweepSandboxes");async function ie(t=e=>{}){try{const{completion:e}=await $();t(e)}catch(e){w({level:"error",event:"daemon.grants.sweep_failed",error:e})}}d(ie,"onGrantSync");export{L as afterRevocationStop,G as exceeds,ie as onGrantSync,$ as sweepSandboxes};
@@ -1,3 +1,3 @@
1
- var W=Object.defineProperty;var s=(o,e)=>W(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as D}from"../../api/dto/profiles.js";import{existsSync as N}from"node:fs";import{CrtrError as B}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as C}from"@north-light/identity";import{activeGrant as x,grantFor as A,runtimeScope as J}from"../grants/mirror.js";import{withCanvasWrite as P}from"../canvas/db.js";import{ApiError as k}from"../../api/errors.js";import{pluginAppToken as G}from"../secrets.js";import{loadExactProfileManifest as q}from"../profiles/manifest.js";import{ensureOwner as L,getById as U,nodeObject as Y,ownerForGrantee as z,profileHandle as K}from"./objects.js";import{personId as Q,personIdAsync as V}from"../canvas/person.js";import{OBJECT_TYPE as X}from"../permissions/builtin.js";import{warmCheckoutDirs as M}from"../checkout-identities.js";import{fillProfileProjectRepo as Z}from"../profiles/manifest.js";import{emitEvent as I}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ee,readableAmong as oe,prefetchRepoReads as te,reposForCwd as ne,warmCheckoutIdentities as b}from"./repo-sync/repos.js";async function T(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await V(),c=p===void 0?void 0:await ee(o,p);c!==void 0&&p!==void 0&&await te(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||N(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await oe(o,p,d,c),g=await r(e,a,c),w=new Set(g.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!N(i.path))continue;let y;try{y=await r(i.path,a,c)}catch(u){if(u instanceof B&&u.code==="git-lookup-failed")continue;throw u}for(const u of y)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:E,projectCheckouts:m}}s(T,"viewRepos");async function Ce(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?D(j(o).projects(t.profile_id)):[];if(R()){await re(t.profile_id,[t.cwd,...r]);return}await b(t.cwd);for(const n of r)N(n)&&await b(n)}s(Ce,"warmNodeRepos");async function re(o,e){if(await M(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await P(async n=>await ne(n,t.path)))[0];r!==void 0&&await Z(o,t.path,r.id)}catch(r){I({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(re,"warmCloudNodeCheckouts");async function xe(o,e,t){if(!R()){for(const n of t)await b(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await M(r?.profile_id,t)}s(xe,"warmNodeDirs");async function Ae(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await F(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await F(o)};const p=await A(e.actor.app,e.sub);if(!p)throw new k(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(d=>_(p.resolved,d))}}if(e.class==="cron"){const p=e.grant?(await x(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await Y(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await H(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await T(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ae,"readerFor");async function ae(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
1
+ var W=Object.defineProperty;var s=(o,e)=>W(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as D}from"../../api/dto/profiles.js";import{existsSync as b}from"node:fs";import{CrtrError as B}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as C}from"@north-light/identity";import{activeGrant as x,grantFor as A,runtimeScope as J}from"../grants/mirror.js";import{withCanvasWrite as P}from"../canvas/db.js";import{ApiError as k}from"../../api/errors.js";import{pluginAppToken as G}from"../secrets.js";import{loadExactProfileManifest as q}from"../profiles/manifest.js";import{ensureOwner as L,getById as U,nodeObject as Y,ownerForGrantee as z,profileHandle as K}from"./objects.js";import{personId as Q,personIdAsync as V}from"../canvas/person.js";import{OBJECT_TYPE as X}from"../permissions/builtin.js";import{warmCheckoutDirs as M}from"../checkout-identities.js";import{fillProfileProjectRepo as Z}from"../profiles/manifest.js";import{emitEvent as I}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ee,readableAmong as oe,prefetchRepoReads as te,reposForCwd as ne,warmCheckoutIdentities as N}from"./repo-sync/repos.js";async function T(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await V(),c=p===void 0?void 0:await ee(o,p);c!==void 0&&p!==void 0&&await te(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||b(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await oe(o,p,d,c),g=await r(e,a,c),w=new Set(g.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!b(i.path))continue;let y;try{y=await r(i.path,a,c)}catch(u){if(u instanceof B&&u.code==="git-lookup-failed")continue;throw u}for(const u of y)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:E,projectCheckouts:m}}s(T,"viewRepos");async function Ce(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?D(j(o).projects(t.profile_id)):[];if(R()){await re(t.profile_id,[t.cwd,...r]);return}await N(t.cwd);for(const n of r)b(n)&&await N(n)}s(Ce,"warmNodeRepos");async function re(o,e){if(await M(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await P(async n=>await ne(n,t.path)))[0];r!==void 0&&await Z(o,t.path,r.id)}catch(r){I({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(re,"warmCloudNodeCheckouts");async function xe(o,e,t){if(!R()){for(const n of t)await N(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await M(r?.profile_id,t)}s(xe,"warmNodeDirs");async function Ae(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await F(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await F(o)};const p=await A(e.actor.app,e.sub);if(!p)throw new k(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),sub:e.sub,place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(d=>_(p.resolved,d))}}if(e.class==="cron"){const p=e.grant?(await x(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await Y(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await H(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await T(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ae,"readerFor");async function ae(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
2
  sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.length>1&&(a.type==="app"||a.type==="repo")?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(X,a.type==="repo"?a.id:e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
3
  WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await L(o,"profile","profile",e,K(e,q(e).manifest.name),t)}s(ce,"profileObject");export{se as NoOwningAppError,Me as appScopesNow,j as liveLookups,ce as profileObject,Te as publishLookups,Ae as readerFor,ae as readerForNode,Le as readerForObject,T as viewRepos,re as warmCloudNodeCheckouts,xe as warmNodeDirs,Ce as warmNodeRepos};
@@ -0,0 +1,2 @@
1
+ export declare function environmentPayerOfProfile(profileId: string | null | undefined): Promise<string | null>;
2
+ export declare function environmentPayerOfNode(nodeId: string | null | undefined): Promise<string | null>;
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var r=(e,n)=>t(e,"name",{value:n,configurable:!0});import{openDb as o}from"../canvas/db.js";async function a(e){return e?(await(await o()).prepare("SELECT e.payer AS payer FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(e))?.payer??null:null}r(a,"environmentPayerOfProfile");async function l(e){return e?(await(await o()).prepare("SELECT e.payer AS payer FROM nodes n JOIN profiles p ON p.id = n.profile_id JOIN environments e ON e.object = p.environment_id WHERE n.node_id = ?").get(e))?.payer??null:null}r(l,"environmentPayerOfNode");export{l as environmentPayerOfNode,a as environmentPayerOfProfile};
@@ -1,5 +1,6 @@
1
1
  export * from './types.js';
2
2
  export * from './months.js';
3
+ export { environmentPayerOfNode, environmentPayerOfProfile } from './environment-payer.js';
3
4
  export { payerOf, type Payer, type PayerCall } from './payer.js';
4
5
  export { writeCharge, receiptChargeId, chargeOf, type WriteResult } from './charges.js';
5
6
  export { check, findRefusal, refusalError, refusedMark, userActionOf, type Candidate, type CallCandidate, type StartCandidate, type Refusal } from './check.js';
@@ -1 +1 @@
1
- export*from"./types.js";export*from"./months.js";import{payerOf as f}from"./payer.js";import{writeCharge as a,receiptChargeId as p,chargeOf as i}from"./charges.js";import{check as l,findRefusal as x,refusalError as u,refusedMark as L,userActionOf as c}from"./check.js";import{upsertLimit as g,deleteLimit as h,listLimits as n}from"./limits.js";import{usageFor as T,runUsage as A,listCharges as C,monthTotals as R,assertReference as k}from"./read.js";import{REBUILD_ALL_TOTALS as B,rebuildTotalsFor as E}from"./totals.js";import{appsHeldBy as I}from"./account.js";export{B as REBUILD_ALL_TOTALS,I as appsHeldBy,k as assertReference,i as chargeOf,l as check,h as deleteLimit,x as findRefusal,C as listCharges,n as listLimits,R as monthTotals,f as payerOf,E as rebuildTotalsFor,p as receiptChargeId,u as refusalError,L as refusedMark,A as runUsage,g as upsertLimit,T as usageFor,c as userActionOf,a as writeCharge};
1
+ export*from"./types.js";export*from"./months.js";import{environmentPayerOfNode as f,environmentPayerOfProfile as a}from"./environment-payer.js";import{payerOf as m}from"./payer.js";import{writeCharge as p,receiptChargeId as n,chargeOf as l}from"./charges.js";import{check as u,findRefusal as d,refusalError as L,refusedMark as c,userActionOf as g}from"./check.js";import{upsertLimit as O,deleteLimit as y,listLimits as T}from"./limits.js";import{usageFor as C,runUsage as P,listCharges as R,monthTotals as k,assertReference as v}from"./read.js";import{REBUILD_ALL_TOTALS as E,rebuildTotalsFor as F}from"./totals.js";import{appsHeldBy as U}from"./account.js";export{E as REBUILD_ALL_TOTALS,U as appsHeldBy,v as assertReference,l as chargeOf,u as check,y as deleteLimit,f as environmentPayerOfNode,a as environmentPayerOfProfile,d as findRefusal,R as listCharges,T as listLimits,k as monthTotals,m as payerOf,F as rebuildTotalsFor,n as receiptChargeId,L as refusalError,c as refusedMark,P as runUsage,O as upsertLimit,C as usageFor,g as userActionOf,p as writeCharge};
@@ -3,7 +3,8 @@ export interface Payer {
3
3
  payer: string;
4
4
  funding: Funding;
5
5
  }
6
- export type PayerCall =
6
+ /** `environmentPayer`: the payer stored on the environment the calling node runs in (`environments.payer`). When set it is the payer of every call; funding is unchanged. */
7
+ export type PayerCall = (
7
8
  /** A model call on an app-paid grant: the app's inference endpoint pays. `grantee` is the app principal (`app:<id>`). */
8
9
  {
9
10
  call: 'model';
@@ -29,6 +30,8 @@ export type PayerCall =
29
30
  grantPayer: 'user' | 'app' | null | undefined;
30
31
  sub: string;
31
32
  grantee: string;
33
+ }) & {
34
+ environmentPayer?: string | null;
32
35
  };
33
36
  /** Who pays, and with what funding. A device call is not priced and never asks. */
34
37
  export declare function payerOf(call: PayerCall): Payer;
@@ -1 +1 @@
1
- var t=Object.defineProperty;var n=(e,r)=>t(e,"name",{value:r,configurable:!0});function p(e){switch(e.call){case"model":return e.route==="endpoint"?{payer:e.grantee,funding:"endpoint"}:{payer:e.sub,funding:e.route};case"tool":return e.tokenPayer.startsWith("app:")?{payer:e.tokenPayer,funding:"bill"}:{payer:e.sub,funding:"bill"};case"start":return e.grantPayer==="app"?{payer:e.grantee,funding:"endpoint"}:{payer:e.sub,funding:"bill"}}}n(p,"payerOf");export{p as payerOf};
1
+ var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});function p(n){const e=i(n);return n.environmentPayer?{payer:n.environmentPayer,funding:e.funding}:e}r(p,"payerOf");function i(n){switch(n.call){case"model":return n.route==="endpoint"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:n.route};case"tool":return n.tokenPayer.startsWith("app:")?{payer:n.tokenPayer,funding:"bill"}:{payer:n.sub,funding:"bill"};case"start":return n.grantPayer==="app"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:"bill"}}}r(i,"fundedBy");export{p as payerOf};
@@ -86,6 +86,7 @@ export interface LlmSpend {
86
86
  node?: string | null;
87
87
  run?: string | null;
88
88
  request?: string;
89
+ environmentPayer?: string | null;
89
90
  spend_cap?: number | null;
90
91
  }
91
92
  /** `spend`: who the call is attributed to. With it, the ledger check runs for each candidate route before its vendor request
@@ -1,3 +1,3 @@
1
- var Be=Object.defineProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{randomUUID as Je}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as ye,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,modelCooldownFamily as st,rateLimitHeaders as dt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ge}from"../provider-error-recognition.js";import{isSafetyRefusal as lt}from"./refusal.js";import{findRefusal as ut,payerOf as Ee,refusalError as ct,refusedMark as ft,writeCharge as we}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as mt,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as pt}from"../provider-failure.js";import{personIdAsync as ht}from"../canvas/person.js";import{getNode as De}from"../canvas/canvas.js";import{outboundToken as Ne}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as _t}from"../providers/errors.js";import{appCandidates as yt}from"./app-rungs.js";import{hostedRoute as gt,matchesFeatures as wt,ownerCandidates as bt}from"./owner-candidates.js";function vt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(vt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function kt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=ge({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(kt,"refreshFailure");async function xt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const S=e.getProvider(t)?.auth.oauth;if(!S)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await nt(t,o.label,async(r,_)=>{const w=await S.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(R=>{throw kt(R,s)}),x=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(xt,"freshSubscriptionAccess");function nn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&vt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&Rt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(nn,"parseLlmRequest");function Rt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(Rt,"isJsonObject");function qt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),S=d.join(`
1
+ var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as He}from"node:crypto";import{streamSimple as ze}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Xe,probeRouteAvailability as Ge}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as Me,parseModelSpec as Ve}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{getProviderLabel as Ze,isInvalidRefreshTokenError as Qe}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Se,coolingUntilFor as $e,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ce,retryAfterMsFromHeaders as ge,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,vendorRateLimit as it,RefreshBusyError as at,RefreshTimeoutError as st}from"../subscription-state.js";import{describeRateLimitScope as Ee,modelCooldownFamily as dt,rateLimitHeaders as lt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as we}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Ie,refusalError as ft,refusedMark as mt,writeCharge as be}from"../ledger/index.js";import{storedApiKey as Oe}from"../auth-file.js";import{eligibleHostedEndpoint as pt,readHostedEndpoint as De}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ht}from"../provider-failure.js";import{personIdAsync as _t}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as Fe}from"../providers/mint.js";import{discardFile as Le}from"../providers/token-cache.js";import{ProviderError as yt}from"../providers/errors.js";import{appCandidates as gt}from"./app-rungs.js";import{hostedRoute as wt,matchesFeatures as bt,ownerCandidates as vt}from"./owner-candidates.js";function kt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(kt,"validContent");function Pe(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Pe,"imageContent");function xt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=we({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(xt,"refreshFailure");async function Rt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const S=e.getProvider(t)?.auth.oauth;if(!S)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await ot(t,o.label,async(r,_)=>{const w=await S.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(R=>{throw xt(R,s)}),x=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof at||r instanceof st?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(Rt,"freshSubscriptionAccess");function on(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&kt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&qt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(on,"parseLlmRequest");function qt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(qt,"isJsonObject");function At(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Pe(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Pe(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),S=d.join(`
2
2
 
3
- `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(qt,"contextOf");function At(e){return pt(e?.payment)}l(At,"paymentOf");function jt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(jt,"hostedModel");function Mt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&s===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}l(Mt,"usdEquivalent");function St(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(St,"allowedFallback");function on(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(on,"llmCallerOf");function Te(e){return e instanceof _t?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const $t=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Ct(e,t,o){if(!(e!=="openai-codex"||t===void 0||!$t.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Ct,"codexAccountModelRejection");function Et(e){return e.get("request-id")??e.get("x-request-id")}l(Et,"vendorRequestId");async function rn(e,t,o,s,d,S,J){const r=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await ht(),x=await Ve();let R;_?(R=yt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ge(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),R=R.filter(y=>wt(x,e,y))):R=await bt(x,e,s);const ie=!_&&d!==void 0&&w!==null?await mt():null,ae=ie===null?void 0:gt(e,R,ie),Pe=ae?ie:null;ae&&(R=[...R,ae]);const Ue=_?new Set:ze(),be=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await be();const H=`chatcmpl-${Je()}`;let F=1/0,L=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await De(d.node))?.caused_by??null:null)??(d?.run?(await De(d.run))?.caused_by??null:null),"causeOf");for(const y of R){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Xe(y,x)).authenticated){if(y.credentialSource!==je&&N(y.providerId)){const k=await $e(y.providerId);k.length>0&&k.every(q=>q.authFailure)&&G.add(y.providerId)}continue}const $=b?jt(x,y.modelId):x.find(y.providerId,y.modelId);if(!$)continue;const z=b?Pe.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===je&&N(h),ce=!r&&!b&&!V&&N(h)?await $e(h):[],T=ce.filter(k=>!k.authFailure),ve=T.filter(k=>Se(k,u.id)<=Date.now()),P=V?await Ie(h):Ue.has(h)?void 0:ce.length?await Ie(h):void 0;if(V&&P===void 0)continue;if(ce.length>0&&T.length===0&&P===void 0){N(h)&&G.add(h);continue}if(T.length&&!ve.length&&P===void 0){const k=Math.min(...T.map(c=>Se(c,u.id)));k<F&&(F=k,de=`${u.provider}/${u.id}`);const q=st(u.id);for(const c of T){const C=q!==void 0&&(c.modelCooldowns?.[q]??0)>Date.now()?c.vendorLimits?.[q]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(L=Math.min(L,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const ke=r||b?[void 0,void 0]:V?["key"]:T.length||P!==void 0?[...ve,...P!==void 0?["key"]:[]]:[void 0];let xe=!1;for(const[k,q]of ke.entries()){if(xe&&q!=="key")continue;const c=q==="key"?void 0:q,C=q==="key",Y=Date.now();let Re=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{Re=await xt(x,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Ze(n))throw n;se??=n;continue}const Ke=qt(e),U=c||r||b||C?void 0:await x.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,A=b?w===null?null:{payer:w,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):w===null?null:Ee({call:"model",route:c?"subscription":"key",sub:w});if(d!==void 0&&A!==null){const n=await ut({scope:"call",payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await we({request:d.request??H,kind:"model",what:f,usd:null,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:ft(n)}),le??=n,q!=="key"&&ke.includes("key")){xe=!0;continue}break}}let O;if(r&&_)try{O=await Ne({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Ne({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,qe=!1,g,X,Z,E=!1,j,Q=null,M=3e4,B;const fe=[],me=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{fe.push(n),o?.(n)},"emit"),We=He(u,Ke,{apiKey:O?.access_token??Re??(C?P:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(j=p.status,Q=Et(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw qe=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=At(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,M=ye(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,M=ye(n.headers)??15e3)},"onResponse")});try{for await(const n of We)n.type==="text_delta"&&(me.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=tt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(dt(n.headers)).length&&(B=n.headers);const p=ge({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw fe.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,M=m??M}}if(b){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(j===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||j!==void 0&&j>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${j??"with an error"}`;throw j===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ye(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||j!==void 0&&j>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&ge({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,M=15e3),E){const n=rt(B,u.id,M),{observation:m,vendorReset:p}=n;if(M=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ce(m.scope)} retry_after_ms=${M} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await Qe(h,c.label,M,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(L=Math.min(L,p)),Date.now()+Math.min(M,Me)<F&&(F=Date.now()+Math.min(M,Me),de=f),me.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=lt(a);if(j===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Ct(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&ot(c,u.id)&&await et(h,c.label,Y,u.id);const pe=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),he=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",_e=a.responseModel?St(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:_e?`${u.provider}/${_e.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:Mt(_e??u,a.usage.cost.total),served_model:I};b?d!==void 0&&A!==null&&await we({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&A!==null&&await we({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const Ae={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:me.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...pe.length?{tool_calls:pe}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:he}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of pe.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},he),model:I,served_model:I,substituted:Ae.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:he,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:Ae,chunks:fe}}}throw le!==void 0?ct(le):F!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:L===1/0?null:new Date(L).toISOString()},retry_after_s:Math.max(1,Math.ceil((F-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await be()}l(rn,"runLlm");export{xt as freshSubscriptionAccess,on as llmCallerOf,nn as parseLlmRequest,rn as runLlm,Mt as usdEquivalent};
3
+ `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(At,"contextOf");function jt(e){return ht(e?.payment)}l(jt,"paymentOf");function Mt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(Mt,"hostedModel");function St(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&s===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}l(St,"usdEquivalent");function $t(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l($t,"allowedFallback");function rn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(rn,"llmCallerOf");function Te(e){return e instanceof yt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const Ct=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Et(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Ct.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Et,"codexAccountModelRejection");function It(e){return e.get("request-id")??e.get("x-request-id")}l(It,"vendorRequestId");async function an(e,t,o,s,d,S,J){const r=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await _t(),x=await Ye();let R;_?(R=gt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ve(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),R=R.filter(y=>bt(x,e,y))):R=await vt(x,e,s);const ie=!_&&d!==void 0&&w!==null?await pt():null,ae=ie===null?void 0:wt(e,R,ie),Ue=ae?ie:null;ae&&(R=[...R,ae]);const Ke=_?new Set:Xe(),ve=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await De())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await ve();const H=`chatcmpl-${He()}`;let F=1/0,L=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const y of R){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,x)).authenticated){if(y.credentialSource!==Me&&N(y.providerId)){const k=await Ce(y.providerId);k.length>0&&k.every(q=>q.authFailure)&&G.add(y.providerId)}continue}const $=b?Mt(x,y.modelId):x.find(y.providerId,y.modelId);if(!$)continue;const z=b?Ue.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===Me&&N(h),ce=!r&&!b&&!V&&N(h)?await Ce(h):[],P=ce.filter(k=>!k.authFailure),ke=P.filter(k=>$e(k,u.id)<=Date.now()),T=V?await Oe(h):Ke.has(h)?void 0:ce.length?await Oe(h):void 0;if(V&&T===void 0)continue;if(ce.length>0&&P.length===0&&T===void 0){N(h)&&G.add(h);continue}if(P.length&&!ke.length&&T===void 0){const k=Math.min(...P.map(c=>$e(c,u.id)));k<F&&(F=k,de=`${u.provider}/${u.id}`);const q=dt(u.id);for(const c of P){const C=q!==void 0&&(c.modelCooldowns?.[q]??0)>Date.now()?c.vendorLimits?.[q]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(L=Math.min(L,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const xe=r||b?[void 0,void 0]:V?["key"]:P.length||T!==void 0?[...ke,...T!==void 0?["key"]:[]]:[void 0];let Re=!1;for(const[k,q]of xe.entries()){if(Re&&q!=="key")continue;const c=q==="key"?void 0:q,C=q==="key",Y=Date.now();let qe=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{qe=await Rt(x,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;se??=n;continue}const We=At(e),U=c||r||b||C?void 0:await x.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,fe=d?.environmentPayer,A=b?w===null?null:{payer:fe??w,funding:"endpoint"}:r?Ie({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:fe}):w===null?null:Ie({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:fe});if(d!==void 0&&A!==null){const n=await ct({scope:"call",payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await be({request:d.request??H,kind:"model",what:f,usd:null,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:mt(n)}),le??=n,q!=="key"&&xe.includes("key")){Re=!0;continue}break}}let O;if(r&&_)try{O=await Fe({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Fe({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,Ae=!1,g,X,Z,E=!1,j,Q=null,M=3e4,B;const me=[],pe=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{me.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??qe??(C?T:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(j=p.status,Q=It(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw Ae=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=jt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,M=ge(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,M=ge(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(pe.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=nt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&(B=n.headers);const p=we({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw me.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,M=m??M}}if(b){if(Ae)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(j===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(j===401){if(O&&Le(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||j!==void 0&&j>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${j??"with an error"}`;throw j===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(j===401){if(O&&Le(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ge(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||j!==void 0&&j>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&we({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,M=15e3),E){const n=it(B,u.id,M),{observation:m,vendorReset:p}=n;if(M=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ee(m.scope)} retry_after_ms=${M} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,M,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(L=Math.min(L,p)),Date.now()+Math.min(M,Se)<F&&(F=Date.now()+Math.min(M,Se),de=f),pe.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=ut(a);if(j===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Et(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&rt(c,u.id)&&await tt(h,c.label,Y,u.id);const he=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),_e=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ye=a.responseModel?$t(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:ye?`${u.provider}/${ye.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:St(ye??u,a.usage.cost.total),served_model:I};b?d!==void 0&&A!==null&&await be({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&A!==null&&await be({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const je={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:pe.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...he.length?{tool_calls:he}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:_e}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of he.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},_e),model:I,served_model:I,substituted:je.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:_e,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:je,chunks:me}}}throw le!==void 0?ft(le):F!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await De())?.payment_setup_url??null,reset_at:L===1/0?null:new Date(L).toISOString()},retry_after_s:Math.max(1,Math.ceil((F-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ee(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ze).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await ve()}l(an,"runLlm");export{Rt as freshSubscriptionAccess,rn as llmCallerOf,on as parseLlmRequest,an as runLlm,St as usdEquivalent};
@@ -1 +1 @@
1
- var w=Object.defineProperty;var a=(e,o)=>w(e,"name",{value:o,configurable:!0});import{joinedOwner as m}from"../directory/join.js";import{nodePlace as d}from"../permissions/ceiling.js";import{openDb as f}from"../canvas/db.js";import{ownMachineId as p}from"./directory.js";const N="Crtr-Envelope",E=16*1024,h=12*1024;class r extends Error{static{a(this,"EnvelopeError")}constructor(o){super(o),this.name="EnvelopeError"}}async function x(e,o={}){return b(await v(e,o))}a(x,"envelopeFor");async function v(e,o){const n=o.via??p(),t=e.class==="person"?"":e.sub,s=o.owner??(t.startsWith("user:")?t:m());if(s==null)throw new r("this machine has no account owner to make a peer call for");if(e.class==="person")return{sub:s,act:{sub:n}};if(e.class==="broker"){const c=await(o.placeOf??(async u=>await d(await f(),u)))(e.node);return{sub:s,act:{sub:n,act:{sub:e.app,node:e.node,node_scopes:e.scopes===null?null:[...e.scopes],place:c}}}}return{sub:s,act:{sub:n,act:{sub:e.app,node:e.anchor,node_scopes:e.scopes===null?null:[...e.scopes],place:{run:e.origin_run??"",isolated:e.isolated}}}}}a(v,"buildEnvelope");function b(e){const o=y(e).length;if(o>h){const n=e.act.act?.node_scopes?.length;throw new r(`the call's identity is ${o} bytes, over the ${h}-byte limit for a call to another machine${n===void 0?"":` (the node holds ${n} scopes)`}; narrow the node's scopes`)}return e}a(b,"fits");function y(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}a(y,"encodeEnvelope");const i=a(e=>typeof e=="string"&&e!=="","isString"),l=a(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord");function P(e){if(e.length>E)throw new r("the envelope is too large");if(!/^[A-Za-z0-9_-]+$/.test(e))throw new r("the envelope is not base64url");let o;try{o=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new r("the envelope is not JSON")}if(!l(o)||!i(o.sub)||!o.sub.startsWith("user:"))throw new r("the envelope names no user");const n=o.act;if(!l(n)||!i(n.sub)||!n.sub.startsWith("runtime:"))throw new r("the envelope names no calling machine");const t=n.act;if(t===void 0)return{sub:o.sub,act:{sub:n.sub}};if(!l(t)||!i(t.sub)||!t.sub.startsWith("app:"))throw new r("the envelope names no calling app");const{node:s,node_scopes:c,place:u}=t;if(s!==null&&!i(s))throw new r("the envelope node is not a node id");if(c!==null&&!(Array.isArray(c)&&c.every(i)))throw new r("the envelope node_scopes is not a list of scopes");if(u!==null&&!(l(u)&&typeof u.run=="string"&&typeof u.isolated=="boolean"))throw new r("the envelope place is malformed");return{sub:o.sub,act:{sub:n.sub,act:{sub:t.sub,node:s,node_scopes:c,place:u===null?null:{run:u.run,isolated:u.isolated}}}}}a(P,"decodeEnvelope");async function $(e,o,n={}){const t=n.via??p();if(e.class==="person"||e.grantee===null)return{sub:o,act:{sub:t}};const s=e.node_id===null?null:await(n.placeOf??(async c=>await d(await f(),c)))(e.node_id);return b({sub:o,act:{sub:t,act:{sub:e.grantee,node:e.node_id,node_scopes:e.nodeScopes===null?null:[...e.nodeScopes],place:s}}})}a($,"envelopeForProviderCaller");export{N as ENVELOPE_HEADER,r as EnvelopeError,E as MAX_ENVELOPE_BYTES,h as MAX_SENT_ENVELOPE_BYTES,P as decodeEnvelope,y as encodeEnvelope,x as envelopeFor,$ as envelopeForProviderCaller};
1
+ var w=Object.defineProperty;var a=(e,o)=>w(e,"name",{value:o,configurable:!0});import{parsePrincipal as m}from"@north-light/identity";import{joinedOwner as E}from"../directory/join.js";import{nodePlace as d}from"../permissions/ceiling.js";import{openDb as f}from"../canvas/db.js";import{ownMachineId as p}from"./directory.js";const P="Crtr-Envelope",v=16*1024,h=12*1024;class r extends Error{static{a(this,"EnvelopeError")}constructor(o){super(o),this.name="EnvelopeError"}}async function $(e,o={}){return b(await y(e,o))}a($,"envelopeFor");async function y(e,o){const n=o.via??p(),t=e.class==="person"?"":e.sub,s=o.owner??(t.startsWith("user:")?t:E());if(s==null)throw new r("this machine has no account owner to make a peer call for");if(e.class==="person")return{sub:s,act:{sub:n}};if(e.class==="broker"){const c=await(o.placeOf??(async u=>await d(await f(),u)))(e.node);return{sub:s,act:{sub:n,act:{sub:e.app,node:e.node,node_scopes:e.scopes===null?null:[...e.scopes],place:c}}}}return{sub:s,act:{sub:n,act:{sub:e.app,node:e.anchor,node_scopes:e.scopes===null?null:[...e.scopes],place:{run:e.origin_run??"",isolated:e.isolated}}}}}a(y,"buildEnvelope");function b(e){const o=_(e).length;if(o>h){const n=e.act.act?.node_scopes?.length;throw new r(`the call's identity is ${o} bytes, over the ${h}-byte limit for a call to another machine${n===void 0?"":` (the node holds ${n} scopes)`}; narrow the node's scopes`)}return e}a(b,"fits");function _(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}a(_,"encodeEnvelope");const i=a(e=>typeof e=="string"&&e!=="","isString"),l=a(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord");function B(e){if(e.length>v)throw new r("the envelope is too large");if(!/^[A-Za-z0-9_-]+$/.test(e))throw new r("the envelope is not base64url");let o;try{o=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new r("the envelope is not JSON")}if(!l(o)||!i(o.sub)||!o.sub.startsWith("user:"))throw new r("the envelope names no user");const n=o.act;if(!l(n)||!i(n.sub)||!n.sub.startsWith("runtime:"))throw new r("the envelope names no calling machine");const t=n.act;if(t===void 0)return{sub:o.sub,act:{sub:n.sub}};if(!l(t)||!i(t.sub)||m(t.sub)?.kind!=="app")throw new r("the envelope names no calling app");const{node:s,node_scopes:c,place:u}=t;if(s!==null&&!i(s))throw new r("the envelope node is not a node id");if(c!==null&&!(Array.isArray(c)&&c.every(i)))throw new r("the envelope node_scopes is not a list of scopes");if(u!==null&&!(l(u)&&typeof u.run=="string"&&typeof u.isolated=="boolean"))throw new r("the envelope place is malformed");return{sub:o.sub,act:{sub:n.sub,act:{sub:t.sub,node:s,node_scopes:c,place:u===null?null:{run:u.run,isolated:u.isolated}}}}}a(B,"decodeEnvelope");async function k(e,o,n={}){const t=n.via??p();if(e.class==="person"||e.grantee===null)return{sub:o,act:{sub:t}};const s=e.node_id===null?null:await(n.placeOf??(async c=>await d(await f(),c)))(e.node_id);return b({sub:o,act:{sub:t,act:{sub:e.grantee,node:e.node_id,node_scopes:e.nodeScopes===null?null:[...e.nodeScopes],place:s}}})}a(k,"envelopeForProviderCaller");export{P as ENVELOPE_HEADER,r as EnvelopeError,v as MAX_ENVELOPE_BYTES,h as MAX_SENT_ENVELOPE_BYTES,B as decodeEnvelope,_ as encodeEnvelope,$ as envelopeFor,k as envelopeForProviderCaller};