@north-light/cli 0.3.750 → 0.3.751
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.
- package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/local.js +1 -1
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +12 -12
- package/dist/core/grants/shadow.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/ledger/payer.d.ts +4 -4
- package/dist/core/ledger/payer.js +1 -1
- package/dist/core/llm/app-rungs.js +1 -1
- package/dist/core/llm/run.d.ts +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/git-credential.js +1 -1
- package/dist/daemon/api/handlers/runs.js +1 -1
- package/dist/daemon/api/principal.d.ts +11 -5
- package/dist/daemon/api/principal.js +1 -1
- package/docs/ci-runner.md +1 -1
- package/docs/sdk/release-notes.md +10 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/grants/local.js +1 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
- package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
- package/packages/crouter-api/dist/core/grants/sync.js +5 -4
- package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
- package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
- package/packages/crouter-api/dist/core/llm/run.js +3 -2
- package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
- package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
- package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/dist/index.d.ts +4 -2
- package/packages/crouter-identity/dist/index.js +31 -12
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +4 -1
- package/packages/crouter-plugin/dist/verify.js +36 -8
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ee=Object.defineProperty;var i=(e,n)=>ee(e,"name",{value:n,configurable:!0});import{AsyncResource as te}from"node:async_hooks";import{randomUUID as ne}from"node:crypto";import{createServer as re}from"node:http";import{Router as z,causedByOf as ae}from"./router.js";import{toErrorBody as oe}from"./map.js";import{objectRoutes as ie}from"./handlers/objects.js";import{customObjectRoutes as se}from"./handlers/custom-objects.js";import{checkRoutes as ue}from"./handlers/check.js";import{chargeRoutes as de}from"./handlers/charges.js";import{docRoutes as ce}from"./handlers/docs.js";import{relationRoutes as le}from"./handlers/relations.js";import{schemaRoutes as fe}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as pe}from"../readiness.js";import{errorCodes as G}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as he,RUNTIME_VERSION_HEADER as we,minimumRuntimeRefusal as ye}from"../../api/runtime-version.js";import{CONTRACT_HEADER as _e,CONTRACT_LEVEL as Y,REQUIRED_CONTRACT_HEADER as ge,contractRefusal as ve}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as Re,parseTraceparent as Oe}from"../../shared/traceparent.js";import{AppPrincipalResolver as be,grantIdOf as L}from"./principal.js";import{isDaemonRoute as Ee,runtimeOwner as Ae,servePeer as F}from"../peer/ingress.js";import{applySyncNotice as Se}from"./sync-notice.js";import{ownMachineId as Te}from"../../core/peer/directory.js";import{handleRunOperation as Ne,integer as Ce}from"./handlers/runs.js";import{runAnthropicMessages as Ie}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Pe,parseLlmRequest as ke,runLlm as Me}from"../../core/llm/run.js";import{parseUsageMonth as He,usageFor as De}from"../../core/ledger/index.js";import{capFields as Be}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as Q,MODEL_CONTEXT_BODY_MAX_BYTES as W}from"../../core/llm/body-limits.js";import{RunError as f,cloudPersonScope as xe,runIsRunning as je}from"../../core/runs/operations.js";import{requireRun as U}from"./router.js";import{deferHead as Je}from"./deferred-head.js";import{readRunEvents as q,registerGrantStream as Le,subscribeRunEvents as Ue}from"../../core/runs/events.js";import{activeGrant as K,payerOfGrant as Xe}from"../../core/grants/mirror.js";async function $e(e){if(await Xe(e)==="app")throw new f(401,"grant_revoked","this app-paid grant is no longer active");return null}i($e,"appPaidGone");import{releaseGrantWaiters as Ve}from"../../core/grants/watch.js";import{emitEvent as ze}from"../../core/events/emit.js";import{runNotices as Ge}from"../run-notices.js";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Fe}from"./key-signin.js";import{listAppProfiles as Qe}from"./handlers/app-profiles.js";import{handleTransferOperation as We,TRANSFER_OPERATIONS as qe}from"./handlers/transfer.js";import{handleQuestionOperation as Ke,QUESTION_OPERATIONS as Ze}from"./handlers/questions.js";import{removeVendorAccount as et,vendorStatus as tt}from"./handlers/vendor-status.js";import{handleMemoryOperation as nt,MEMORY_OPERATIONS as rt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as at,handleExec as ot}from"./handlers/exec.js";import{abortOnClose as X,callerFromApp as it,handleProviderOperation as st,PROVIDER_OPERATIONS as ut,providerFailure as dt}from"./handlers/providers.js";function ct(e){return Object.prototype.hasOwnProperty.call(G,e)?G[e]:void 0}i(ct,"fixedRow");function lt(e){const n=ct(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(lt,"errorType");function ft(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(ft,"appDetails");function x(e,n,o){const c=ft(e.details);return{error:{code:e.code,message:e.message,...c===void 0?{}:{details:c},type:lt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...Be(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,c,d){const y=n instanceof f?n:new f(500,"server_failure","runtime request failed");if(n instanceof f||console.error("[app-listener]",`trace_id=${c}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
|
|
2
2
|
data: ${JSON.stringify(x(y,o,d))}
|
|
3
3
|
|
|
4
|
-
`);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(mt,"fail");function
|
|
4
|
+
`);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(mt,"fail");function $(e){return Array.isArray(e)?e[0]:e}i($,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function Z(e,n=Q){const o=[];let c=0;for await(const d of e){if(c+=d.length,c>n)throw new f(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(Z,"rawBodyOf");async function I(e,n=Q){const o=await Z(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new f(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function pt(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new f(400,"invalid_request","invalid cursor","after");return Ce(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(pt,"cursor");function ht(e){return`id: ${e.sequence_number}
|
|
5
5
|
event: ${e.type}
|
|
6
6
|
data: ${JSON.stringify(e)}
|
|
7
7
|
|
|
8
|
-
`}i(
|
|
8
|
+
`}i(ht,"frame");const wt=6e4;async function yt(e,n,o,c,d,y,S,O={},r){await U(c,o);let t=await q(o,d);if(d>t.latest_sequence)throw new f(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new f(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":S==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),S==="sse"?n.write(`: connected
|
|
9
9
|
|
|
10
|
-
`):n.flushHeaders();let p=d;const _=await
|
|
11
|
-
data: ${JSON.stringify(x(
|
|
10
|
+
`):n.flushHeaders();let p=d;const _=await Ge().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(m=>{b=m}),R=i(()=>{v||(v=!0,_(p).catch(m=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],m)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),b())},"end"),a=i(()=>{N=!1,E()},"onDrain"),H=i(m=>{v||n.write(S==="sse"?`event: error
|
|
11
|
+
data: ${JSON.stringify(x(m,y,o))}
|
|
12
12
|
|
|
13
|
-
`:`${JSON.stringify({type:"error",...x(
|
|
14
|
-
`),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await
|
|
15
|
-
`),p=
|
|
13
|
+
`:`${JSON.stringify({type:"error",...x(m,y,o)})}
|
|
14
|
+
`),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await U(c,o),t=await q(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new f(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const m of t.events){if(N)break;N=!n.write(S==="sse"?ht(m):`${JSON.stringify(m)}
|
|
15
|
+
`),p=m.sequence_number}}catch(m){H(m instanceof f?m:new f(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new f(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in c||c.grant===null||await K(c.grant)!==null,"grantActive"),C=await Ue(o,te.bind(E)),u="class"in c||c.grant===null?()=>{}:Le(c.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
|
|
16
16
|
|
|
17
|
-
`)},15e3),s=O.idleMs??
|
|
17
|
+
`)},15e3),s=O.idleMs??wt,w=O.isRunning??je;let l=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const m=Date.now();let V=!0;try{V=await w(o)}catch{}if(!v){if(V||p!==A){l=m,A=p;return}m-l<s||N||(n.write(`event: idle
|
|
18
18
|
data: {}
|
|
19
19
|
|
|
20
|
-
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(
|
|
20
|
+
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(m=>ze({level:"error",event:"api.run_stream.idle_check_failed",error:m}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(yt,"streamRunEvents");function _t(e,n,o,c={}){const d=new z,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const S=new z().registerAll(ie).registerAll(se).registerAll(ce).registerAll(fe).registerAll(le).registerAll(ue).registerAll(de);return i((r,t,p)=>(async()=>{Je(r,t,c.deferHead);const _=ne();t.setHeader("Request-Id",_);const v=Oe($(r.headers.traceparent))??Re();t.setHeader(we,J()),t.setHeader(_e,Y);let T;try{const N=$(r.headers[he.toLowerCase()]),b=ye(N,J())??ve($(r.headers[ge.toLowerCase()]),Y,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new f(400,b.code,b.message,b.param):new f(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Fe(h.pathname)){await Ye(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let E,P;if(p!==void 0)E=p;else if(!H&&r.headers.authorization!==void 0)try{E=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ae,self:Te,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await F(r,t,D,E);return}if(E===void 0&&a===void 0&&await Ee(r.method??"GET",h.pathname)){await F(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await pe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new f(503,"runtime_starting","runtime_starting");if(!R||!a)throw new f(404,"not_found","unknown operation");T=R.params.run_id;const C=ae(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Se(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await tt());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await et(await I(r)));return}if(E===void 0)throw P??new f(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await U(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=S.match(a.method,h.pathname);if(!s)throw new f(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let l;try{l=await s.handler(w)}catch(A){const{status:k,body:M}=oe(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new f(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(l.rawBody!==void 0||l.status===204||l.body===void 0){t.writeHead(l.status,l.headers??{}),t.end(l.rawBody);return}t.writeHead(l.status,{"Content-Type":"application/json; charset=utf-8",...l.headers??{}}),t.end(JSON.stringify(l.body));return}if(a.stream){await yt(r,t,T,u,pt(r,h.searchParams),_,"sse",c.stream,v);return}if(a.name==="llm"){const s=ke(await I(r,W)),w=new AbortController,l=i(()=>w.abort(),"abort");t.on("close",l);try{const A=await Me(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
|
|
21
21
|
|
|
22
|
-
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},
|
|
22
|
+
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},Pe(await K(L(u))??await $e(L(u))),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
|
|
23
23
|
|
|
24
|
-
`)):g(t,200,A.completion)}finally{t.off("close",
|
|
24
|
+
`)):g(t,200,A.completion)}finally{t.off("close",l)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=X(t);try{await Ie(await Z(r,W),r.headers,s,{grant:L(u),sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=X(t);try{g(t,200,await ot(u,await I(r,at),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await De(u.grantee,He(h.searchParams.get("month")),xe(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Qe(u));return}if(Ze.has(a.name)){const s=await Ke(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(ut.has(a.name)){const{signal:s,release:w}=X(t);try{const l=await st(a.name,it(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,l.status,l.body)}catch(l){const A=dt(l,_,!0);t.writeHead(A.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...A.headers}),t.end(JSON.stringify(A.body))}finally{w()}return}if(rt.has(a.name)){const s=await nt(a.name,{class:"app",app:u.grantee,sub:u.sub,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(qe.has(a.name)){const s=await We(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Ne(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){mt(t,N,_,v,T)}})(),"handle")}i(_t,"createAppRequestHandler");async function fn(e,n,o,c={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<0||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new be(e.issuer,e.audience,o,e.jwksUrl),S=_t(y,n,o,c),O=re((t,p)=>{S(t,p)});return{ready:new Promise((t,p)=>{O.once("error",p),O.listen(d.port,d.address,()=>{O.off("error",p),t()})}),port:i(()=>O.address().port,"port"),close:i(async()=>{y.close(),Ve(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(fn,"createAppListener");export{wt as RUN_STREAM_IDLE_MS,fn as createAppListener,_t as createAppRequestHandler,pt as cursor,yt as streamRunEvents};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var p=(o,t)=>f(o,"name",{value:t,configurable:!0});import{ApiError as n}from"../../../api/errors.js";import{openDb as _}from"../../../core/canvas/db.js";import{getNode as w}from"../../../core/canvas/canvas.js";import{environmentOfNode as m,recipeOf as g}from"../environment-of.js";import{invalidRequest as b,objectBody as v,optionalString as y,requiredString as k}from"./validate.js";function h(o){const t=process.env[o];if(t===void 0||t==="")throw new n(500,"github_service_unconfigured",`${o} is not set on this control plane`);return t}p(h,"requiredEnv");async function x(o){const{principal:t}=o;if(t.class!=="broker")throw new n(403,"broker_only","git credentials are issued to a node token");const l=o.params.environment_id??"",s=await w(t.node);if(s===null)throw new n(404,"node_not_found",`no node ${t.node}`);if(await m(s.profile_id??null)!==l)throw new n(403,"not_your_environment",`this node does not run in environment ${l}`);const a=[],e=v(o.body,["host","path"],a),r=k(e,"host",a);if(y(e,"path",a),a.length>0&&b("git credential request",a),r!=="github.com")throw new n(400,"unsupported_git_host",`only github.com credentials are issued, not ${r}`);const i=(await g(l))?.repositories.map(c=>c.github_full_name)??[];if(i.length===0)throw new n(409,"no_recipe_repositories",`environment ${l} has no recipe repositories`);const d=await(await _()).prepare("SELECT allow_pull_request_write FROM environments WHERE object = ?").get(l),u=await E(t.sub,i,d?.allow_pull_request_write===!0);return{status:200,body:{username:"x-access-token",password:u.token,expiry:u.expires_at}}}p(x,"handleGitCredential");async function E(o,t,l=!1){const s=await fetch(`${h("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/installation-token`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${h("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({sub:o,repositories:t,allow_pull_request_write:l})}),a=await s.text(),e=a===""?{}:JSON.parse(a);if(!s.ok){const i=typeof e.error=="object"?e.error?.code:e.code,d=(typeof e.error=="object"?e.error?.message:e.message)??`the GitHub service answered ${s.status}`,u=typeof e.error=="object"?e.error?.next:e.next;if(s.status===409&&(i==="repositories_span_installations"||i==="github_not_connected")){const c=typeof u=="string"&&u!==""?u:void 0;throw new n(409,i,d,{repositories:t,...c===void 0?{}:{error:i,message:d,next:i==="github_not_connected"?`Ask the person to open ${c}, link GitHub and install the Northlight GitHub App on the account that owns these repositories (choose "All repositories"), then retry.`:`List repositories from one GitHub account only; manage installations at ${c}.`,url:c}})}throw new n(502,"github_service_failed",d,{status:s.status,...i===void 0?{}:{code:i}})}if(typeof e.token!="string"||typeof e.expires_at!="string")throw new n(502,"github_service_failed","the GitHub service answered without a token and expiry");const r=e.author;if(r===void 0)throw new n(502,"github_service_failed","the GitHub service answered without an author field");if(r!==null&&(typeof r.name!="string"||typeof r.email!="string"))throw new n(502,"github_service_failed","the GitHub service answered a malformed author");return{token:e.token,expires_at:e.expires_at,author:r===null?null:{name:r.name,email:r.email}}}p(E,"mintInstallationToken");const q=[{method:"POST",pattern:"/v1/environments/:environment_id/git-credential",handler:x}];export{q as gitCredentialRoutes,E as mintInstallationToken,h as requiredEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var c=(a,t)=>O(a,"name",{value:t,configurable:!0});import{callerGrant as b,grantIdOf as _}from"../principal.js";import{grantVersion as v,payerOfGrant as $}from"../../../core/grants/mirror.js";import{holdGrant as N}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as y,cancelRun as A,cloudPersonScope as j,deleteRun as x,interruptRun as B,listRuns as J,messageRun as z,renameRun as D,requestedScopes as E,startRun as G,traceRun as K,waitRun as M}from"../../../core/runs/operations.js";import{canReadRun as q,requireRun as w,runCallerApp as P}from"../router.js";import{waitSeconds as k}from"../long-poll-wait.js";import{outputSchemaProblem as T}from"../../../core/runtime/structured-output.js";function m(a){if(!a||typeof a!="object"||Array.isArray(a))throw new n(400,"invalid_request","a JSON object is required");return a}c(m,"object");function R(a,t,i,u,l){if(a===null)return l;if(!/^(0|[1-9]\d*)$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<i||Number(a)>u)throw new n(400,"invalid_request",`invalid ${t}`,t);return Number(a)}c(R,"integer");const C=256*1024;async function Z(a,t,i,u,l,h,p){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=k("grant.get",u),s=u.get("since");if(s!==null&&!/^[A-Za-z0-9_-]{1,64}$/.test(s))throw new n(400,"invalid_request","invalid since","since");const d=e&&s!==null?N(_(t)):void 0;let o;try{if(o=await b(t),d){const f=Date.now()+e*1e3;for(;v(o)===s&&Date.now()<f;)await d.changed(Math.max(0,(f-Date.now())/1e3)),o=await b(t)}}finally{d?.release()}return{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:_(t),rev:o.rev,resolved_scopes:o.resolved_scopes,spend_cap:o.spend_cap,exp:t.exp,payer:await $(_(t)),dependencies:o.dependencies??{},version:v(o)}}}case"run.start":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=m(l),s=["mode","parent","fork_from","node_id","env","tools","system_prompt"];for(const r of s)if(e[r]!==void 0)throw new n(403,"owner_only",`${r} is owner-only`,r);const d=["payer","model_policy","kind"];for(const r of d)if(e[r]!==void 0)throw new n(400,"invalid_request",`${r} is not available`,r);for(const r of Object.keys(e))if(!["prompt","scopes","metadata","profile","isolated","cwd","worktree","output_schema","message","model","deadline"].includes(r))throw new n(400,"invalid_request",`unknown field ${r}`,r);if(e.model!==void 0&&(typeof e.model!="string"||!e.model.trim()))throw new n(400,"invalid_request","model must be a non-empty string","model");if(e.deadline!==void 0&&(typeof e.deadline!="string"||!e.deadline.trim()))throw new n(400,"invalid_request","deadline must be a duration string such as 10m","deadline");if(e.profile!==void 0&&(typeof e.profile!="string"||!e.profile))throw new n(400,"invalid_request","profile must be a profile id","profile");if(e.isolated!==void 0&&typeof e.isolated!="boolean")throw new n(400,"invalid_request","isolated must be a boolean","isolated");if(e.cwd!==void 0&&(e.isolated!==!0||typeof e.cwd!="string"||!e.cwd))throw new n(400,"invalid_request","cwd is available only for an isolated run and must be an absolute path inside its root folder","cwd");if(e.worktree!==void 0&&e.isolated!==!0)throw new n(400,"invalid_request","worktree is not available","worktree");if(e.isolated===!0&&e.worktree!==void 0)throw new n(400,"invalid_request","worktree is unavailable for an isolated run","worktree");if(typeof e.prompt!="string"||!e.prompt.trim())throw new n(400,"invalid_request","prompt is required","prompt");if(e.message!==void 0&&(typeof e.message!="string"||!e.message.trim()))throw new n(400,"invalid_request","message must be a non-empty string","message");const o=e.metadata===void 0?{}:m(e.metadata);if(Buffer.byteLength(JSON.stringify(o))>4096)throw new n(400,"invalid_request","metadata exceeds 4 KB","metadata");let f;if(e.output_schema!==void 0){const r=e.output_schema;if(!r||typeof r!="object"||Array.isArray(r))throw new n(400,"invalid_request","output_schema must be a JSON Schema object","output_schema");if(Buffer.byteLength(JSON.stringify(r))>C)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");const g=await T(r);if(g!==null)throw new n(400,"invalid_request",`output_schema is not usable: ${g}`,"output_schema");f=r}const S=E(t.resolved,e.scopes,t.grantee);return{status:201,body:await G(t,{prompt:e.prompt,scopes:S,metadata:o,profile:e.profile,isolated:e.isolated,cwd:e.cwd,...e.model===void 0?{}:{model:e.model},...e.deadline===void 0?{}:{deadline:e.deadline},...f===void 0?{}:{output_schema:f},...e.message===void 0?{}:{message:e.message},...p===void 0?{}:{causedBy:p}},y(h))}}case"run.list":{const e=u.get("status")??void 0;if(e&&!["running","waiting_on_user","idle","settled"].includes(e))throw new n(400,"invalid_request","invalid status","status");const s=u.get("app");if(s!==null&&!/^(?:app:)?[a-z0-9][a-z0-9-]*$/.test(s))throw new n(400,"invalid_request","invalid app","app");const d=s===null?P(t):s.startsWith("app:")?s:`app:${s}`;if(d!==null&&!await q(t,d))throw new n(404,"not_found","run not found");const o=j("sub"in t?t.sub:void 0);return{status:200,body:await J(d,{status:e,...o===void 0?{}:{sub:o},after:u.get("after")??void 0,limit:R(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&d!==null?{visible:c(async f=>await q(t,d,f),"visible")}:{}})}}case"run.get":{const e=k("run.get",u),s=await w(t,i),d=await M(i,s.grantee,e);return await w(t,i),{status:200,body:d}}case"run.message":{const e=m(l);if(typeof e.message!="string"||!e.message.trim())throw new n(400,"invalid_request","message is required","message");if(e.start_turn!==void 0&&typeof e.start_turn!="boolean")throw new n(400,"invalid_request","start_turn must be a boolean","start_turn");if(e.steer!==void 0&&typeof e.steer!="boolean")throw new n(400,"invalid_request","steer must be a boolean","steer");if(e.start_turn===!1&&e.steer===!0)throw new n(400,"invalid_request","steer requires start_turn","steer");return{status:202,body:await z(await w(t,i,!0),e.message,void 0,e.start_turn,y(h),e.steer)}}case"run.interrupt":{const e=m(l===void 0?{}:l);if(e.children!==void 0&&e.children!=="stop"&&e.children!=="continue")throw new n(400,"invalid_request","invalid children","children");return{status:200,body:await B(await w(t,i,!0),e.children)}}case"run.cancel":{const e=m(l===void 0?{}:l);if(e.keep_schedules!==void 0&&typeof e.keep_schedules!="boolean")throw new n(400,"invalid_request","invalid keep_schedules","keep_schedules");return{status:200,body:await A(await w(t,i,!0),{keepSchedules:e.keep_schedules})}}case"run.rename":{const e=m(l);for(const s of Object.keys(e))if(s!=="name")throw new n(400,"invalid_request",`unknown field ${s}`,s);return{status:200,body:await D(await w(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await x(await w(t,i,!0,!0));return{status:200,body:{run_id:i,uploads_pending:e}}}case"trace.get":{const e=u.get("format")??void 0;if(e&&e!=="entries")throw new n(400,"invalid_request","unknown trace format","format");const s=await w(t,i);return{status:200,body:await K(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}c(Z,"handleRunOperation");export{Z as handleRunOperation,R as integer};
|
|
@@ -5,9 +5,12 @@ import { type NoticeTicket } from './sync-notice.js';
|
|
|
5
5
|
export interface AppPrincipal {
|
|
6
6
|
sub: string;
|
|
7
7
|
grantee: string;
|
|
8
|
+
/** The caller: the token's presenting link (an app, an app owning `sub`'s namespace, or a person acting through an exchanged token). */
|
|
9
|
+
actor: string;
|
|
8
10
|
client_id: string;
|
|
9
|
-
grant
|
|
10
|
-
|
|
11
|
+
/** Null for an owner principal, which holds its namespace without a grant row. */
|
|
12
|
+
grant: string | null;
|
|
13
|
+
rev: number | null;
|
|
11
14
|
resolved: Scope[];
|
|
12
15
|
resolved_scopes: GrantScope[];
|
|
13
16
|
spend_cap: number | null;
|
|
@@ -58,9 +61,10 @@ export declare class AppPrincipalResolver {
|
|
|
58
61
|
* 503 before the mirror loads; every other failure is 401. */
|
|
59
62
|
verifyCall(authorization: string | undefined): Promise<CallToken>;
|
|
60
63
|
resolve(authorization: string | undefined, scope?: string): Promise<AppPrincipal>;
|
|
61
|
-
/** The caller an already-verified
|
|
62
|
-
* (
|
|
63
|
-
*
|
|
64
|
+
/** The caller an already-verified token names, from `chain[0]` (which must be the whole chain): (a) an app link holding a
|
|
65
|
+
* grant, (b) an owner link (a grantless app link whose app owns `sub`'s namespace: no grant row, the app's declared
|
|
66
|
+
* scopes), or (c) a person's grant-bearing link on an exchanged token. A grant is covered by the mirror and read now
|
|
67
|
+
* (`coverGrant`). Any other presenter is refused 401. */
|
|
64
68
|
resolveVerified(token: CallToken, scope?: string): Promise<AppPrincipal>;
|
|
65
69
|
}
|
|
66
70
|
/** The mirrored grant a caller's token names, read now, when it is still the
|
|
@@ -68,3 +72,5 @@ export declare class AppPrincipalResolver {
|
|
|
68
72
|
* Otherwise 401 `grant_revoked`. `resolve()` and every later re-read during a
|
|
69
73
|
* request (a `grant.get` long-poll waking) apply this one check. */
|
|
70
74
|
export declare function callerGrant(caller: Pick<AppPrincipal, 'grant' | 'sub' | 'grantee'>): Promise<ActiveGrant>;
|
|
75
|
+
/** The grant id of a caller that must hold a grant row; an owner principal (CR-9 (b)) holds none, so the operation is 403. */
|
|
76
|
+
export declare function grantIdOf(caller: Pick<AppPrincipal, 'grant'>): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var u=(s,r)=>m(s,"name",{value:r,configurable:!0});import{covers as w,JwksCache as v,parsePrincipal as _,MissingRevClaimError as b,verifyCallToken as k}from"@north-light/identity";import{createLocalJWKSet as p,decodeProtectedHeader as l,jwtVerify as g}from"jose";import{callerGrantOf as x,coverGrant as E}from"../../core/grants/cover.js";import{ownerScopes as S}from"../../core/grants/owner.js";import{RunError as n}from"../../core/runs/operations.js";import{NoticeLedger as C}from"./sync-notice.js";function G(s){return new n(401,"unauthorized",s==="vendor_sign_in"?"invalid vendor sign-in handoff":"invalid key handoff")}u(G,"unauthorizedHandoff");class L{static{u(this,"AppPrincipalResolver")}issuer;audience;syncGrants;cache;ready=!1;timer;constructor(r,i,e,t){this.issuer=r,this.audience=i,this.syncGrants=e,this.cache=new v(r,fetch,t),this.load(),this.timer=setInterval(()=>{this.ready||this.load()},5e3),this.timer.unref()}async load(){try{await this.cache.load(),this.ready=!0}catch{}}isReady(){return this.ready}get jwks(){return this.cache}close(){this.timer&&clearInterval(this.timer)}ledger=new C;async verifySyncNotice(r){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");return this.ledger.accept(r,this.cache,this.issuer,this.audience)}async verifyHandoff(r,i){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");const e=u(()=>G(i),"refuse");if(!r)throw e();let t;try{const f=l(r);if(f.alg!=="ES256")throw e();const y=await this.cache.forKid(f.kid);({payload:t}=await g(r,p(y),{issuer:this.issuer,audience:this.audience,algorithms:["ES256"],requiredClaims:["exp","jti","sub"]}))}catch{throw e()}const{sub:o,jti:d,exp:a,purpose:c,aud:h}=t;if(c!==i||h!==this.audience||typeof o!="string"||typeof d!="string"||d===""||typeof a!="number")throw e();return{sub:o,jti:d,exp:a}}async verifyDirectoryRead(r,i){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");const e=u(()=>new n(401,"unauthorized","invalid directory token"),"refuse");if(!r?.startsWith("Bearer ")||r.length<=7)throw e();const t=r.slice(7);let o;try{const d=l(t);if(d.alg!=="ES256")throw e();const a=await this.cache.forKid(d.kid);({payload:o}=await g(t,p(a),{issuer:this.issuer,audience:this.audience,algorithms:["ES256"],requiredClaims:["exp"]}))}catch{throw e()}if(o.purpose!==i||o.aud!==this.audience)throw e()}async verifyCall(r){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");if(!r?.startsWith("Bearer ")||r.length<=7)throw new n(401,"unauthorized","a directory access token is required");const i=r.slice(7);try{if(l(i).alg!=="ES256")throw new Error("Invalid call token header");return await k({token:i,jwks:this.cache,issuer:this.issuer,audience:this.audience})}catch(e){throw e instanceof b?new n(401,"unauthorized",e.message):new n(401,"unauthorized","invalid directory access token")}}async resolve(r,i){return this.resolveVerified(await this.verifyCall(r),i)}async resolveVerified(r,i){const e=r.chain[0],t=r.claims,o=e!==void 0&&e.grant!==void 0&&e.rev!==void 0,d=e!==void 0&&_(e.sub)?.kind==="user";if(r.chain.length!==1||!e||!/^[A-Za-z0-9_-]{1,64}$/.test(t.client_id)||!(e.owner===!0||o&&(e.sub.startsWith("app:")||d))||t.grantee!==void 0&&t.grantee!==e.sub||t.rev!==void 0&&t.rev!==e.rev)throw new n(401,"unauthorized","invalid directory access token");if(e.owner===!0){const c=S(e.sub);if(i&&!c.some(h=>w(h,i)))throw new n(403,"scope_missing",`missing scope ${i}`,void 0,void 0,i);return{sub:r.sub,grantee:e.sub,actor:e.sub,client_id:t.client_id,grant:null,rev:null,resolved:c,resolved_scopes:c.map(h=>({scope:h,mode:"always"})),spend_cap:null,dependencies:{},exp:t.exp}}const a=await E(e.grant,e.rev,r.sub,e.sub,this.syncGrants);if(i&&!a.resolved.some(c=>w(c,i)))throw new n(403,"scope_missing",`missing scope ${i}`,void 0,void 0,i);return{sub:r.sub,grantee:e.sub,actor:e.sub,client_id:t.client_id,grant:e.grant,rev:a.rev,resolved:a.resolved,resolved_scopes:a.resolved_scopes,spend_cap:a.spend_cap,dependencies:a.dependencies??{},exp:t.exp}}}async function P(s){return await x(j(s),s.sub,s.grantee)}u(P,"callerGrant");function j(s){if(s.grant===null)throw new n(403,"permission_error","this operation needs a grant; an owner token holds none");return s.grant}u(j,"grantIdOf");export{L as AppPrincipalResolver,P as callerGrant,j as grantIdOf,G as unauthorizedHandoff};
|
package/docs/ci-runner.md
CHANGED
|
@@ -85,7 +85,7 @@ Installing and upgrading: get a registration token (`gh api -X POST repos/Northl
|
|
|
85
85
|
|
|
86
86
|
`publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `build`, `checks` and every `linux` shard pass and every `macos` job (including `macos build-output`) passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
|
|
87
87
|
|
|
88
|
-
-
|
|
88
|
+
- Squash-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
|
|
89
89
|
- A direct push to `main`, or a merge after `main` moved (a different tree from the one the PR run tested) → no artifact → the full suite runs exactly as before. A release commit (`chore: release …`, pushed by Publish itself) changes the tree, so a PR not updated since before the latest release runs the suite once on merge; update the branch to avoid it.
|
|
90
90
|
- The gate can only skip; if the lookup errors it runs the suite. `publish` runs only when `tests` passed, or was skipped *because* the gate found a record. A failed or cancelled suite never publishes.
|
|
91
91
|
- Branch protection is not enabled on `main` and the gate does not depend on it: the proof is the tree, not a required check. Artifacts are kept 30 days; older trees are simply re-tested.
|
|
@@ -7,6 +7,16 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.751
|
|
11
|
+
|
|
12
|
+
### Call tokens may name any principal
|
|
13
|
+
|
|
14
|
+
The identity verifier accepts an `app:<id>` or `app:<id>/<path>` subject, and an app link with no grant when that app owns the subject's namespace (`chain[i].owner`). Strings that are not `user:`, `app:` or an app path are refused.
|
|
15
|
+
|
|
16
|
+
### The daemon resolves owner tokens and exchanged person tokens
|
|
17
|
+
|
|
18
|
+
A token whose only link is an owner link now resolves to a caller holding the app's declared scopes and no grant (`grant` and `rev` are null). Operations that read or stream a grant (`grant.get`, `llm.*`) answer 403 `permission_error` to it. A grant-bearing `user:` link on an exchanged token resolves like an app link, with the person as the caller.
|
|
19
|
+
|
|
10
20
|
## 0.3.721
|
|
11
21
|
|
|
12
22
|
### `inferenceEndpoint` serves an app that pays for its own model calls (`billing: 'app'`)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.751",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.751",
|
|
162
|
+
"@north-light/plugin": "0.3.751",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 37;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -22,5 +22,5 @@ export async function installLocalTerminalGrant(installId, person) {
|
|
|
22
22
|
await replaceGrants([{ id, runtime: installId, sub: person,
|
|
23
23
|
grantee: 'app:terminal', rev: 1, scopes: TERMINAL_SCOPES,
|
|
24
24
|
resolved_scopes: TERMINAL_SCOPES, spend_cap: null, expires_at: null,
|
|
25
|
-
status: 'active', revoked_at: null, approved_at: now, payer:
|
|
25
|
+
status: 'active', revoked_at: null, approved_at: now, payer: person, dependencies: {}, synced_at: now }], now, 'local');
|
|
26
26
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { parseScope } from '@north-light/identity';
|
|
2
|
+
import { parsePrincipal, parseScope } from '@north-light/identity';
|
|
3
3
|
import { openDb, withCanvasWrite } from '../canvas/db.js';
|
|
4
4
|
import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
|
|
5
5
|
import { replaceWrittenBy, userSubject } from '../permissions/facts.js';
|
|
@@ -7,6 +7,21 @@ import { GROUP_TYPE, OBJECT_TYPE } from '../permissions/builtin.js';
|
|
|
7
7
|
import { shadowCheck } from './shadow.js';
|
|
8
8
|
const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
|
|
9
9
|
const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
|
|
10
|
+
/** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
|
|
11
|
+
export function principalPayer(payer, sub, grantee) {
|
|
12
|
+
if (payer === undefined || payer === null || payer === 'user')
|
|
13
|
+
return sub;
|
|
14
|
+
if (payer === 'app')
|
|
15
|
+
return grantee;
|
|
16
|
+
if (typeof payer !== 'string' || parsePrincipal(payer) === null)
|
|
17
|
+
throw new TypeError('invalid grant payer');
|
|
18
|
+
return payer;
|
|
19
|
+
}
|
|
20
|
+
/** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
|
|
21
|
+
export function endpointPays(grant) {
|
|
22
|
+
const payer = grant.payer === null ? null : parsePrincipal(grant.payer);
|
|
23
|
+
return payer !== null && payer.kind === 'app' && payer.path.length === 0;
|
|
24
|
+
}
|
|
10
25
|
/** The fleet's runtime principal (`CRTR_RUNTIME`): a cloud role reads only its own runtime's grants, so a person's VM or laptop grants are never used. A Mac sets none. */
|
|
11
26
|
export function runtimeScope() {
|
|
12
27
|
const runtime = process.env['CRTR_RUNTIME'];
|
|
@@ -93,7 +108,7 @@ function record(row) {
|
|
|
93
108
|
// A row whose computed columns lag its revision (a consent written but not yet computed) reads as no grant, never as the previous scopes.
|
|
94
109
|
if (!computedFor(row.rev, row.computed_rev, row.scopes_json !== null, row.resolved_scopes_json !== null))
|
|
95
110
|
throw new TypeError('grant columns are not computed for this revision');
|
|
96
|
-
return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee,
|
|
111
|
+
return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee, grantee_prefix: row.grantee_prefix ?? null,
|
|
97
112
|
rev: row.rev, scopes: entries(JSON.parse(row.scopes_json)),
|
|
98
113
|
resolved_scopes: entries(JSON.parse(row.resolved_scopes_json)),
|
|
99
114
|
spend_cap: row.spend_cap, expires_at: row.expires_at, status: row.status,
|
|
@@ -342,15 +357,22 @@ export async function grantStanding(grantId) {
|
|
|
342
357
|
export async function grantIdsWhere(where) {
|
|
343
358
|
return (await grantRows('id', where)).map((row) => row.id);
|
|
344
359
|
}
|
|
345
|
-
/** Who a grant's model calls are charged to: `app` only
|
|
360
|
+
/** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
|
|
346
361
|
export async function payerOfGrant(grantId) {
|
|
347
|
-
|
|
362
|
+
const grant = grantId ? await grantRecord(grantId) : null;
|
|
363
|
+
return grant !== null && endpointPays(grant) ? 'app' : 'user';
|
|
348
364
|
}
|
|
349
365
|
export async function activeGrant(grantId) {
|
|
350
366
|
return active(await grantRow('*', 'id = ?', [grantId]));
|
|
351
367
|
}
|
|
368
|
+
/** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
|
|
352
369
|
export async function grantFor(grantee, sub) {
|
|
353
|
-
|
|
370
|
+
const exact = await grantRow('*', 'grantee = ? AND grantee_prefix IS NULL AND sub = ?', [grantee, sub]);
|
|
371
|
+
if (exact)
|
|
372
|
+
return active(exact);
|
|
373
|
+
const rows = await grantRows('*', 'sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)', [sub, grantee]);
|
|
374
|
+
rows.sort((a, b) => b.grantee_prefix.length - a.grantee_prefix.length);
|
|
375
|
+
return active(rows[0]);
|
|
354
376
|
}
|
|
355
377
|
/** The app's own active grant on this machine. Null for a mirror-only grant: an
|
|
356
378
|
* unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
|
|
@@ -430,6 +452,8 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
|
|
|
430
452
|
!Number.isInteger(grant.rev) || !['active', 'revoked', 'removed'].includes(grant.status)) {
|
|
431
453
|
throw new TypeError('invalid grant sync response');
|
|
432
454
|
}
|
|
455
|
+
if ((grant.grantee === '*') !== (grant.grantee_prefix != null))
|
|
456
|
+
throw new TypeError('invalid grant sync response');
|
|
433
457
|
ids.add(grant.id);
|
|
434
458
|
entries(grant.scopes);
|
|
435
459
|
entries(grant.resolved_scopes);
|
|
@@ -443,22 +467,22 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
|
|
|
443
467
|
? db.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${kept.map(() => '?').join(',')})`).run(...kept)
|
|
444
468
|
: db.prepareUncached('DELETE FROM grants').run())).changes);
|
|
445
469
|
const upsert = db.prepare(`INSERT INTO grants
|
|
446
|
-
(id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
470
|
+
(id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
447
471
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
448
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
449
|
-
ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
|
|
472
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
473
|
+
ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, grantee_prefix = excluded.grantee_prefix, rev = excluded.rev,
|
|
450
474
|
scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
|
|
451
475
|
expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
|
|
452
476
|
payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
|
|
453
477
|
inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
|
|
454
|
-
WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
|
|
478
|
+
WHERE (grants.runtime, grants.sub, grants.grantee, grants.grantee_prefix, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
|
|
455
479
|
grants.expires_at, grants.status, grants.revoked_at, grants.approved_at, grants.payer, grants.dependencies_json,
|
|
456
480
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
457
|
-
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
481
|
+
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
458
482
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
459
483
|
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);
|
|
460
484
|
for (const grant of grants) {
|
|
461
|
-
changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, grant.payer, JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
|
|
485
|
+
changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.grantee_prefix ?? null, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, principalPayer(grant.payer, grant.sub, grant.grantee), JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
|
|
462
486
|
}
|
|
463
487
|
await replaceWrittenBy(db, 'directory', GROUP_TYPE, 'member', teams.flatMap(({ team, members }) => members.map((member) => ({ resourceId: team, subject: userSubject(member) }))));
|
|
464
488
|
await reconcileAppAdminFacts(db);
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { directoryIssuer } from '../directory/issuer.js';
|
|
4
4
|
import { outboundFetch } from '../events/outbound.js';
|
|
5
5
|
import { warn } from '../output.js';
|
|
6
|
-
import { canonicalJson } from './mirror.js';
|
|
6
|
+
import { canonicalJson, principalPayer } from './mirror.js';
|
|
7
7
|
let ttlMs = 5_000;
|
|
8
8
|
/** Test hook: how long a cached answer is used before its epochs are re-checked. */
|
|
9
9
|
export function setShadowTtl(ms) { ttlMs = ms; }
|
|
@@ -67,7 +67,9 @@ async function compare(stored) {
|
|
|
67
67
|
shadowCounts.lagging++;
|
|
68
68
|
return;
|
|
69
69
|
}
|
|
70
|
-
|
|
70
|
+
// The directory may still send the older `'user'`/`'app'` payer; the mirror stores it as a principal.
|
|
71
|
+
const liveSide = { ...live, payer: principalPayer(live['payer'], stored.sub, stored.grantee) };
|
|
72
|
+
const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(stored[key] ?? null));
|
|
71
73
|
if (fields.length === 0) {
|
|
72
74
|
shadowCounts.agree++;
|
|
73
75
|
return;
|
|
@@ -7,7 +7,7 @@ import { reconcilePackages } from '../graph/package-reconcile.js';
|
|
|
7
7
|
import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
|
|
8
8
|
import { emitEvent } from '../events/emit.js';
|
|
9
9
|
import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
|
|
10
|
-
import { dependenciesOf, inferenceEndpointOf, replaceGrants, teamsOf } from './mirror.js';
|
|
10
|
+
import { dependenciesOf, endpointPays, inferenceEndpointOf, principalPayer, replaceGrants, teamsOf } from './mirror.js';
|
|
11
11
|
import { onGrantSync } from './on-sync.js';
|
|
12
12
|
import { hostedEndpointOf, paymentSetupUrlOf, storeHostedEndpoint } from './hosted-endpoint.js';
|
|
13
13
|
import { adoptInstallPerson } from '../scoped-state/migrate.js';
|
|
@@ -108,11 +108,12 @@ function responseGrant(value, client) {
|
|
|
108
108
|
const approvedAt = revisions?.find((revision) => revision.rev === grant.rev)?.approved_at;
|
|
109
109
|
if (typeof approvedAt !== 'string')
|
|
110
110
|
throw new TypeError('grant revision has no approval time');
|
|
111
|
-
//
|
|
112
|
-
const payer = grant.payer
|
|
111
|
+
// The payer is a principal; an older directory's `'user'`/`'app'` (or none) maps to the grant's `sub`/`grantee`. The endpoint rides only a grant the app's endpoint pays for.
|
|
112
|
+
const payer = principalPayer(grant.payer, grant.sub, grant.grantee);
|
|
113
113
|
return { ...grant, spend_cap: grant.spend_cap ?? null, expires_at: grant.expires_at ?? null,
|
|
114
|
+
grantee_prefix: typeof grant.grantee_prefix === 'string' ? grant.grantee_prefix : null,
|
|
114
115
|
revoked_at: grant.revoked_at ?? null, approved_at: approvedAt, payer, dependencies: dependenciesOf(grant.dependencies),
|
|
115
|
-
inference_endpoint: payer
|
|
116
|
+
inference_endpoint: endpointPays({ payer }) ? inferenceEndpointOf(grant.inference_endpoint) : null,
|
|
116
117
|
run_notice_url: typeof grant.run_notice_url === 'string' && grant.run_notice_url !== '' ? grant.run_notice_url : null };
|
|
117
118
|
}
|
|
118
119
|
/** The person this pull serves: the bound one, else (a hosted first boot has none until its first snapshot commits) the one
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Payer resolution (design-ledger, "Payer resolution"): one function. It reads the grant's payer and the credential route,
|
|
2
2
|
// never a request header, so a caller cannot name its payer.
|
|
3
|
+
import { endpointPays } from '../grants/mirror.js';
|
|
4
|
+
import { isNamespaceOwner } from '../grants/owner.js';
|
|
3
5
|
/** Who pays, and with what funding. A device call is not priced and never asks. */
|
|
4
6
|
export function payerOf(call) {
|
|
5
7
|
const paid = fundedBy(call);
|
|
@@ -10,9 +12,12 @@ function fundedBy(call) {
|
|
|
10
12
|
case 'model':
|
|
11
13
|
return call.route === 'endpoint' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: call.route };
|
|
12
14
|
case 'tool':
|
|
13
|
-
return
|
|
14
|
-
case 'start':
|
|
15
|
+
return { payer: call.tokenPayer || call.sub, funding: 'bill' };
|
|
16
|
+
case 'start': {
|
|
15
17
|
// Funding is chosen per candidate later; a start check ignores it.
|
|
16
|
-
|
|
18
|
+
if (call.grantPayer)
|
|
19
|
+
return { payer: call.grantPayer, funding: endpointPays({ payer: call.grantPayer }) ? 'endpoint' : 'bill' };
|
|
20
|
+
return { payer: isNamespaceOwner(call.grantee, call.sub) ? call.grantee : call.sub, funding: 'bill' };
|
|
21
|
+
}
|
|
17
22
|
}
|
|
18
23
|
}
|
|
@@ -5,7 +5,7 @@ import { defaultModelLaddersConfig } from '../../types.js';
|
|
|
5
5
|
import { MODEL_STRENGTHS, stripThinkingSuffix } from '../runtime/model-selection.js';
|
|
6
6
|
import { modelTokenStrength } from '../runtime/launch.js';
|
|
7
7
|
import { RunError } from '../runs/operations.js';
|
|
8
|
-
import { grantRecord } from '../grants/mirror.js';
|
|
8
|
+
import { endpointPays, grantRecord } from '../grants/mirror.js';
|
|
9
9
|
const STRENGTHS = MODEL_STRENGTHS;
|
|
10
10
|
/** The endpoint's declared rungs, nearest to `strength` first (the stronger on a tie). */
|
|
11
11
|
function rungsByDistance(endpoint, strength) {
|
|
@@ -55,7 +55,7 @@ export function appCandidates(endpoint, requested, exact = false) {
|
|
|
55
55
|
* each rung's own level. */
|
|
56
56
|
export async function appRungForGrant(grantId, requested, exact = false) {
|
|
57
57
|
const grant = grantId ? await grantRecord(grantId) : null;
|
|
58
|
-
if (grant
|
|
58
|
+
if (!grant || !endpointPays(grant))
|
|
59
59
|
return null;
|
|
60
60
|
if (!grant.inference_endpoint)
|
|
61
61
|
throw new RunError(404, 'model_unavailable', `${grant.grantee} is app-paid but its grant carries no inference endpoint`);
|
|
@@ -15,6 +15,7 @@ import { eligibleHostedEndpoint, readHostedEndpoint } from '../grants/hosted-end
|
|
|
15
15
|
import { parseProviderPayment } from '../provider-failure.js';
|
|
16
16
|
import { personIdAsync } from '../canvas/person.js';
|
|
17
17
|
import { getNode } from '../canvas/canvas.js';
|
|
18
|
+
import { endpointPays } from '../grants/mirror.js';
|
|
18
19
|
import { outboundToken } from '../providers/mint.js';
|
|
19
20
|
import { discardFile } from '../providers/token-cache.js';
|
|
20
21
|
import { ProviderError } from '../providers/errors.js';
|
|
@@ -154,7 +155,7 @@ function allowedFallback(model, responseModel) {
|
|
|
154
155
|
return fallbacks?.find((fallback) => fallback.provider === model.provider && fallback.model === responseModel);
|
|
155
156
|
}
|
|
156
157
|
export function llmCallerOf(grant) {
|
|
157
|
-
return grant ? { payer: grant.payer
|
|
158
|
+
return grant ? { payer: grant.payer, sub: grant.sub, grantee: grant.grantee, inference_endpoint: grant.inference_endpoint ?? null } : undefined;
|
|
158
159
|
}
|
|
159
160
|
/** A directory-token failure as the `llm` refusal it is (RT-RTE-26): the directory unreachable or failing is
|
|
160
161
|
* transient, a refused mint is a configuration fault. */
|
|
@@ -184,7 +185,7 @@ function vendorRequestId(headers) {
|
|
|
184
185
|
* and a completed call writes one `charges` row. Omitted, the call is neither checked nor recorded.
|
|
185
186
|
* `causedBy`: the request's `Crtr-Caused-By` value (`message:<id>`, `request:<id>`, `cron_run:<id>`), when it carried one; stored on the row. */
|
|
186
187
|
export async function runLlm(input, signal, onChunk, target, spend, caller, causedBy) {
|
|
187
|
-
const app = caller
|
|
188
|
+
const app = caller && endpointPays(caller) ? caller : undefined;
|
|
188
189
|
if (input.payer === 'app' && !app)
|
|
189
190
|
throw new RunError(403, 'payer_not_app', 'this grant is not app-paid');
|
|
190
191
|
if (input.payer === 'user' && app)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// starts or a dormant node revives. The candidate's payer is whoever pays the node's model calls.
|
|
3
3
|
import { check, environmentPayerOfProfile, findRefusal, payerOf } from '../ledger/index.js';
|
|
4
4
|
import { RunError } from '../runs/operations.js';
|
|
5
|
-
import {
|
|
5
|
+
import { grantRecord, grantStanding } from '../grants/mirror.js';
|
|
6
6
|
import { callerTerminalGrant } from '../grants/terminal.js';
|
|
7
7
|
/** The start candidate for an identity, or null when no person is known yet (a terminal node before its first grant snapshot). */
|
|
8
8
|
export async function startCandidateOf(who) {
|
|
@@ -10,7 +10,7 @@ export async function startCandidateOf(who) {
|
|
|
10
10
|
const sub = who.sub ?? (grantee === 'app:terminal' ? (await callerTerminalGrant())?.sub : undefined) ?? null;
|
|
11
11
|
if (sub === null)
|
|
12
12
|
return null;
|
|
13
|
-
const paid = await
|
|
13
|
+
const paid = who.grant_id ? (await grantRecord(who.grant_id))?.payer : null;
|
|
14
14
|
const payer = payerOf({ call: 'start', grantPayer: paid, sub, grantee, environmentPayer: await environmentPayerOfProfile(who.profile_id) });
|
|
15
15
|
return { scope: 'start', payer: payer.payer, sub, grantee };
|
|
16
16
|
}
|