@north-light/cli 0.3.749 → 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.
Files changed (53) hide show
  1. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  2. package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
  3. package/dist/core/canvas/schema-version.d.ts +1 -1
  4. package/dist/core/canvas/schema-version.js +1 -1
  5. package/dist/core/grants/local.js +1 -1
  6. package/dist/core/grants/mirror.d.ts +11 -3
  7. package/dist/core/grants/mirror.js +12 -12
  8. package/dist/core/grants/owner.d.ts +7 -0
  9. package/dist/core/grants/owner.js +1 -0
  10. package/dist/core/grants/shadow.js +1 -1
  11. package/dist/core/grants/sync.js +1 -1
  12. package/dist/core/graph/reader.js +3 -3
  13. package/dist/core/import/load/bind.d.ts +1 -1
  14. package/dist/core/import/load/bind.js +11 -8
  15. package/dist/core/ledger/payer.d.ts +4 -4
  16. package/dist/core/ledger/payer.js +1 -1
  17. package/dist/core/llm/app-rungs.js +1 -1
  18. package/dist/core/llm/run.d.ts +2 -2
  19. package/dist/core/llm/run.js +2 -2
  20. package/dist/core/runtime/start-check.js +1 -1
  21. package/dist/core/spaces/permissions.js +1 -1
  22. package/dist/core/spaces/process.js +1 -1
  23. package/dist/daemon/api/app-listener.js +12 -12
  24. package/dist/daemon/api/handlers/git-credential.js +1 -1
  25. package/dist/daemon/api/handlers/runs.js +1 -1
  26. package/dist/daemon/api/principal.d.ts +11 -5
  27. package/dist/daemon/api/principal.js +1 -1
  28. package/docs/ci-runner.md +1 -1
  29. package/docs/sdk/release-notes.md +10 -0
  30. package/package.json +3 -3
  31. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  32. package/packages/crouter-api/dist/core/grants/local.js +1 -1
  33. package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
  34. package/packages/crouter-api/dist/core/grants/owner.js +15 -0
  35. package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
  36. package/packages/crouter-api/dist/core/grants/sync.js +5 -4
  37. package/packages/crouter-api/dist/core/graph/reader.js +8 -5
  38. package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
  39. package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
  40. package/packages/crouter-api/dist/core/llm/run.js +3 -2
  41. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  42. package/packages/crouter-api/dist/core/spaces/permissions.js +10 -4
  43. package/packages/crouter-api/dist/core/spaces/process.js +5 -3
  44. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
  45. package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
  46. package/packages/crouter-api/package.json +1 -1
  47. package/packages/crouter-identity/dist/index.d.ts +4 -2
  48. package/packages/crouter-identity/dist/index.js +31 -12
  49. package/packages/crouter-identity/package.json +1 -1
  50. package/packages/crouter-plugin/dist/serve.js +4 -1
  51. package/packages/crouter-plugin/dist/verify.js +36 -8
  52. package/packages/crouter-plugin/package.json +3 -3
  53. package/runtime.lock.json +14 -14
@@ -1,7 +1,7 @@
1
1
  import { type ThinkingLevel } from '@earendil-works/pi-ai/compat';
2
2
  import { openModelRegistry } from '../runtime/model-registry.js';
3
3
  import { type ManagedProviderId, type SubscriptionCredential } from '../managed-providers.js';
4
- import type { GrantRecord, InferenceEndpoint } from '../grants/mirror.js';
4
+ import { type GrantRecord, type InferenceEndpoint } from '../grants/mirror.js';
5
5
  type WireContent = string | null | Array<{
6
6
  type: 'text';
7
7
  text: string;
@@ -70,7 +70,7 @@ export declare function usdEquivalent(model: {
70
70
  }, total: number): number | null;
71
71
  /** Who the call is made for: the caller's grant decides the payer (RT-RTE-12). A caller with no grant (the person) is user-paid. */
72
72
  export interface LlmCaller {
73
- payer: 'user' | 'app';
73
+ payer: string | null;
74
74
  sub: string;
75
75
  grantee: string;
76
76
  inference_endpoint: InferenceEndpoint | null;
@@ -1,3 +1,3 @@
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(`
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{endpointPays as yt}from"../grants/mirror.js";import{outboundToken as Pe}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as gt}from"../providers/errors.js";import{appCandidates as wt}from"./app-rungs.js";import{hostedRoute as bt,matchesFeatures as vt,ownerCandidates as kt}from"./owner-candidates.js";function xt(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(xt,"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 Rt(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(Rt,"refreshFailure");async function qt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const x=e.getProvider(t)?.auth.oauth;if(!x)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 x.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(q=>{throw Rt(q,s)}),R=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof R=="string"&&R?{clientId:R}:{}}}).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(qt,"freshSubscriptionAccess");function an(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)&&xt(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"&&At(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(an,"parseLlmRequest");function At(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(At,"isJsonObject");function jt(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),x=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(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};
3
+ `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...x?{systemPrompt:x}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(jt,"contextOf");function Mt(e){return ht(e?.payment)}l(Mt,"paymentOf");function St(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(St,"hostedModel");function $t(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:x}=e.cost;return o===0&&s===0&&d===0&&x===0?null:Number.isFinite(t)&&t>=0?t:null}l($t,"usdEquivalent");function Ct(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Ct,"allowedFallback");function sn(e){return e?{payer:e.payer,sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(sn,"llmCallerOf");function Te(e){return e instanceof gt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const Et=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function It(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Et.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(It,"codexAccountModelRejection");function Ot(e){return e.get("request-id")??e.get("x-request-id")}l(Ot,"vendorRequestId");async function dn(e,t,o,s,d,x,J){const r=x&&yt(x)?x: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(),R=await Ye();let q;_?(q=wt(_,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}]:[]}),q=q.filter(y=>vt(R,e,y))):q=await kt(R,e,s);const ie=!_&&d!==void 0&&w!==null?await pt():null,ae=ie===null?void 0:bt(e,q,ie),Ue=ae?ie:null;ae&&(q=[...q,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(q.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 P=1/0,F=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 q){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,R)).authenticated){if(y.credentialSource!==Me&&N(y.providerId)){const k=await Ce(y.providerId);k.length>0&&k.every(A=>A.authFailure)&&G.add(y.providerId)}continue}const $=b?St(R,y.modelId):R.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):[],L=ce.filter(k=>!k.authFailure),ke=L.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&&L.length===0&&T===void 0){N(h)&&G.add(h);continue}if(L.length&&!ke.length&&T===void 0){const k=Math.min(...L.map(c=>$e(c,u.id)));k<P&&(P=k,de=`${u.provider}/${u.id}`);const A=dt(u.id);for(const c of L){const C=A!==void 0&&(c.modelCooldowns?.[A]??0)>Date.now()?c.vendorLimits?.[A]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(F=Math.min(F,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"]:L.length||T!==void 0?[...ke,...T!==void 0?["key"]:[]]:[void 0];let Re=!1;for(const[k,A]of xe.entries()){if(Re&&A!=="key")continue;const c=A==="key"?void 0:A,C=A==="key",Y=Date.now();let qe=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{qe=await qt(R,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;se??=n;continue}const We=jt(e),U=c||r||b||C?void 0:await R.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,fe=d?.environmentPayer,j=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&&j!==null){const n=await ct({scope:"call",payer:j.payer,funding:j.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:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:mt(n)}),le??=n,A!=="key"&&xe.includes("key")){Re=!0;continue}break}}let O;if(r&&_)try{O=await Pe({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 Pe({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,M,Q=null,S=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(M=p.status,Q=Ot(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=Mt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,S=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,S=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,S=m??S}}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(M===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(M===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||M!==void 0&&M>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${M??"with an error"}`;throw M===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(M===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&&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||M!==void 0&&M>=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,S=15e3),E){const n=it(B,u.id,S),{observation:m,vendorReset:p}=n;if(S=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=${S} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,S,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(F=Math.min(F,p)),Date.now()+Math.min(S,Se)<P&&(P=Date.now()+Math.min(S,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(M===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=It(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?Ct(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:$t(ye??u,a.usage.cost.total),served_model:I};b?d!==void 0&&j!==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:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&j!==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:j.payer,funding:j.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):P!==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:F===1/0?null:new Date(F).toISOString()},retry_after_s:Math.max(1,Math.ceil((P-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(dn,"runLlm");export{qt as freshSubscriptionAccess,sn as llmCallerOf,an as parseLlmRequest,dn as runLlm,$t as usdEquivalent};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as p,payerOf as u}from"../ledger/index.js";import{RunError as r}from"../runs/operations.js";import{grantStanding as f,payerOfGrant as d}from"../grants/mirror.js";import{callerTerminalGrant as m}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",e=t.sub??(a==="app:terminal"?(await m())?.sub:void 0)??null;if(e===null)return null;const c=await d(t.grant_id);return{scope:"start",payer:u({call:"start",grantPayer:c,sub:e,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:e,grantee:a}}n(i,"startCandidateOf");async function w(t){const a=await i(t);a!==null&&await s(a)}n(w,"checkStart");async function O(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new r(401,"grant_revoked","the node's grant is not active")}n(O,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await p(a)}n(P,"startRefusal");function R(t){return t instanceof r&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(R,"isStartRefusal");export{O as checkGrantActive,w as checkStart,R as isStartRefusal,i as startCandidateOf,P as startRefusal};
1
+ var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as u,payerOf as p}from"../ledger/index.js";import{RunError as e}from"../runs/operations.js";import{grantRecord as d,grantStanding as f}from"../grants/mirror.js";import{callerTerminalGrant as g}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",r=t.sub??(a==="app:terminal"?(await g())?.sub:void 0)??null;if(r===null)return null;const c=t.grant_id?(await d(t.grant_id))?.payer:null;return{scope:"start",payer:p({call:"start",grantPayer:c,sub:r,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:r,grantee:a}}n(i,"startCandidateOf");async function R(t){const a=await i(t);a!==null&&await s(a)}n(R,"checkStart");async function w(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new e(401,"grant_revoked","the node's grant is not active")}n(w,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await u(a)}n(P,"startRefusal");function b(t){return t instanceof e&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(b,"isStartRefusal");export{w as checkGrantActive,R as checkStart,b as isStartRefusal,i as startCandidateOf,P as startRefusal};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var f=(r,i)=>v(r,"name",{value:i,configurable:!0});import{parseScope as A}from"@north-light/identity";import{coveredByAny as u}from"../../shared/env.js";import{activeGrant as F,grantFor as S}from"../grants/mirror.js";import{appSpace as w,userFilesRoot as j}from"../layout.js";import{contains as h}from"./file-root.js";import{join as E,resolve as l}from"node:path";import{lstatSync as z,realpathSync as y}from"node:fs";async function g(r,i,o,e){return R(r,i,o?await F(o):await S(r,i),e)}f(g,"permissionsForRun");function R(r,i,o,e){if(!o||o.grantee!==r||o.sub!==i)throw new Error(`no active grant for ${r}`);if(e!==null&&!Array.isArray(e))throw new Error("invalid launched scopes");const t=[],n=[];let c=e===null;const d=e??o.resolved;for(const s of d){if(typeof s!="string")throw new Error("invalid launched scope");A(s);const $=s===`crtr:memory:read:${r}`||s===`crtr:memory:rw:${r}`||s.startsWith(`crtr:memory:read:${r}:`)||s.startsWith(`crtr:memory:rw:${r}:`);if(e!==null&&!$&&!u(o.resolved,s))throw new Error(`launched scope not in grant: ${s}`);const m=/^crtr:files:(read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(s);if(m){const[,x,p,b]=m;if(p===r)throw new Error(`own-app files cannot narrow a run: ${s}`);t.push({holder:p,path:b,writable:x==="rw"})}const a=/^crtr:objects:read:(app:[A-Za-z0-9_-]{1,64})$/.exec(s);a&&a[1]!==r&&n.push(a[1])}return{app:r,ownNodes:c,otherFiles:t,otherNodes:n}}f(R,"permissionsForGrant");function Z(r,i){const o=l(r);for(const e of i){const t=l(e);if(h(t,o))try{if(y(o)!==o||y(t)!==t)continue;let n=o;for(;h(t,n)&&!z(n).isSymbolicLink();){if(n===t)return!0;n=l(n,"..")}}catch{}}return!1}f(Z,"readableProject");function q(r,i,o,e){const t=[w(i).files];for(const n of e??o){if(e!==null&&!u(o,n))continue;const c=/^crtr:files:(?:read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(n);c&&t.push(E(c[1]==="user"?j():w(c[1]).files,c[2]==="."?"":c[2]))}return Z(r,t)}f(q,"readableProjectForScopes");import{fileRoot as H}from"./file-root.js";export{H as fileRoot,R as permissionsForGrant,g as permissionsForRun,Z as readableProject,q as readableProjectForScopes};
1
+ var b=Object.defineProperty;var f=(r,n)=>b(r,"name",{value:n,configurable:!0});import{parseScope as A}from"@north-light/identity";import{coveredByAny as p}from"../../shared/env.js";import{activeGrant as E,grantFor as F}from"../grants/mirror.js";import{isNamespaceOwner as j,ownerScopes as z}from"../grants/owner.js";import{appSpace as h,userFilesRoot as N}from"../layout.js";import{contains as y}from"./file-root.js";import{join as R,resolve as l}from"node:path";import{lstatSync as Z,realpathSync as d}from"node:fs";async function D(r,n,o,t){const e=o?await E(o):await F(r,n);if(o&&!e)throw new Error(`no active grant for ${r}`);return _(r,n,e,t)}f(D,"permissionsForRun");function _(r,n,o,t){if(o?o.grantee!==r||o.sub!==n:!j(r,n))throw new Error(`no active grant for ${r}`);if(t!==null&&!Array.isArray(t))throw new Error("invalid launched scopes");const e=[],s=[];let c=t===null;const m=o?o.resolved:z(r),$=t??m;for(const i of $){if(typeof i!="string")throw new Error("invalid launched scope");A(i);const v=i===`crtr:memory:read:${r}`||i===`crtr:memory:rw:${r}`||i.startsWith(`crtr:memory:read:${r}:`)||i.startsWith(`crtr:memory:rw:${r}:`);if(t!==null&&!v&&!p(m,i))throw new Error(`launched scope not in grant: ${i}`);const w=/^crtr:files:(read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(i);if(w){const[,x,u,S]=w;if(u===r)throw new Error(`own-app files cannot narrow a run: ${i}`);e.push({holder:u,path:S,writable:x==="rw"})}const a=/^crtr:objects:read:(app:[A-Za-z0-9_-]{1,64})$/.exec(i);a&&a[1]!==r&&s.push(a[1])}return{app:r,ownNodes:c,otherFiles:e,otherNodes:s}}f(_,"permissionsForGrant");function k(r,n){const o=l(r);for(const t of n){const e=l(t);if(y(e,o))try{if(d(o)!==o||d(e)!==e)continue;let s=o;for(;y(e,s)&&!Z(s).isSymbolicLink();){if(s===e)return!0;s=l(s,"..")}}catch{}}return!1}f(k,"readableProject");function H(r,n,o,t){const e=[h(n).files];for(const s of t??o){if(t!==null&&!p(o,s))continue;const c=/^crtr:files:(?:read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(s);c&&e.push(R(c[1]==="user"?N():h(c[1]).files,c[2]==="."?"":c[2]))}return k(r,e)}f(H,"readableProjectForScopes");import{fileRoot as M}from"./file-root.js";export{M as fileRoot,_ as permissionsForGrant,D as permissionsForRun,k as readableProject,H as readableProjectForScopes};
@@ -1 +1 @@
1
- var $=Object.defineProperty;var u=(e,r)=>$(e,"name",{value:r,configurable:!0});import{existsSync as _}from"node:fs";import{assertGranteeRunsHere as N}from"../runtime/unsandboxed.js";import{randomUUID as O}from"node:crypto";import{join as h}from"node:path";import{getNode as R}from"../canvas/canvas.js";import{nodeAgentDir as k,nodeHome as H,nodeRunDir as K}from"../canvas/paths.js";import{appSpace as B}from"../layout.js";import{activeGrant as g,activeGrantForApp as S,grantFor as I,grantsGeneration as y}from"../grants/mirror.js";import{emitEvent as G}from"../events/emit.js";import{ensureAppSpace as F}from"./space.js";import{compileLaunch as A,launchStillGranted as M}from"./mounts.js";import{pinSandboxRuntimeHome as j}from"./runtime-home.js";import{sandboxCacheEnv as q}from"./cache-env.js";import{launcherRequest as b}from"../../launcher/client.js";import{LAUNCHER_SOCKET as D}from"../../launcher/spec.js";import{isCloudRole as U}from"../canvas/person.js";import{launchSub as E}from"../runs/node-sub.js";function W(e){return`cron-${e}`}u(W,"cronLaunchId");function le(){if(process.platform!=="linux")return!1;if(_(D))return!0;throw new Error("root launcher socket is unavailable; refusing an unsandboxed app process")}u(le,"appProcessSandboxed");function me(){return L??(process.platform==="linux"&&_(D))}u(me,"appProcessesSandboxed");let L;function pe(e){L=e}u(pe,"__setAppProcessesSandboxedForTest");async function we(e,r,n,a=!1,o,d){const t=n===void 0?null:await R(n),s=d!==void 0?d.grantId?await g(d.grantId):await I(e,d.sub):t?null:await S(e);if((d!==void 0||!t)&&!s)throw new Error(`no active grant for ${e}`);return(await A({nodeId:n??"proc-cwd-check",app:e,...d!==void 0?{sub:d.sub,grantId:s?.id??null,scopes:d.scopes}:{sub:t?E(t.sub,t.node_id):s.sub,grantId:t?t.grant_id??null:s.id,scopes:t?.scopes??null},command:["true"],env:{},...n===void 0?{withoutNode:!0}:{},...o===void 0?{}:{folder:o},isolated:t?.isolated===!0||a,auditMissing:u(()=>{},"auditMissing")})).mounts.some(({source:c})=>r===c||r.startsWith(c==="/"?"/":`${c}/`))}u(we,"cwdIsMounted");async function P(e,r="SIGKILL",n){if(!("ok"in await b({operation:"stop",pid:e,signal:r,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}u(P,"stopAppProcess");function z(e,r,n,a,o){return a?o??k(e,r):n}u(z,"appProcessCwd");async function he(e){if(U())throw new Error("a cloud role launches no app process; the node runs in its sandbox");if(e.cron!==void 0&&(e.nodeId!==void 0||e.principal===void 0))throw new Error("a cron launch has a stored principal and no node");const r=e.nodeId===void 0?null:await R(e.nodeId);if(e.nodeId!==void 0&&!r)throw new Error(`missing node ${e.nodeId}`);const n=r?.grantee??e.app??"app:terminal";if(N(n),e.app!==void 0&&e.app!==n)throw new Error("app does not match node");const a=e.principal;let o=null;if(a!==void 0){if(o=a.grantId?await g(a.grantId):await I(n,a.sub),!o||o.grantee!==n||o.sub!==a.sub)throw new Error(`no active grant for ${n}`)}else if(r){if(n!=="app:terminal"&&!(r.grant_id?await g(r.grant_id):await I(n,E(r.sub,r.node_id))))throw new Error(`no active grant for ${n}`)}else if(o=await S(n),!o)throw new Error(`no active grant for ${n}`);await F(n);const d=e.cron===void 0?e.nodeId??`proc-${O()}`:W(e.cron.executionId),t=r?.isolated===!0||e.isolated===!0;if(t&&!r&&e.folder===void 0)throw new Error("isolated process requires a live node");const s=B(n),m=z(d,n,e.cwd,t,e.folder),c=r?H(d,n,t):t&&e.folder!==void 0?h(e.folder,"home"):s.home,C=j(Object.fromEntries(Object.entries({...e.env,...process.platform==="linux"?q(n):{},HOME:c,PI_CODING_AGENT_DIR:h(c,".pi","agent"),PWD:m,...e.nodeId===void 0&&e.cron===void 0?{}:{CRTR_API_SOCKET:h(K(d),"cli.sock")}}).filter(i=>i[1]!==void 0))),x=a!==void 0?{nodeId:d,app:n,sub:a.sub,grantId:o?.id??null,scopes:a.scopes}:{nodeId:d,app:n,sub:r?E(r.sub,r.node_id):o.sub,grantId:r?r.grant_id??null:o.id,scopes:r?.scopes??null},T=u(async()=>{const i=await A({...x,command:e.command,env:C,...e.nodeId===void 0?{withoutNode:!0}:{},isolated:t,cwd:m,...e.folder===void 0?{}:{folder:e.folder},...e.cron===void 0?{}:{cron:e.cron.anchorDir===void 0?{}:{anchorDir:e.cron.anchorDir}},...e.pluginRoot===void 0?{}:{pluginRoot:e.pluginRoot},auditMissing:u(w=>G({level:"warn",event:"process.mount.missing",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{source:w}}),"auditMissing")});if(e.pluginRoot!==void 0&&(i.pluginRoot=e.pluginRoot),e.capture===!1){if(e.nodeId===void 0||e.stdin!==void 0)throw new Error("uncaptured process requires a node and no stdin")}else i.capture={stdoutBytes:e.stdoutBytes??256*1024,stderrBytes:e.stderrBytes??256*1024,...e.stderrTail?{stderrTail:!0}:{},...e.stdin===void 0?{}:{stdin:e.stdin}};return i},"compile");let f;for(let i=0;i<2&&f===void 0;i++){const w=await y(),v=await T(),l=await b({operation:"launch",spec:v});if(!("pid"in l))throw new Error("launcher did not return a process id");if(await y()===w||await M(x,v)){f=l.pid;break}G({level:"info",event:"process.launch.regranted",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{pid:l.pid}}),await P(l.pid,"SIGKILL").catch(()=>{})}if(f===void 0)throw new Error("grant changed during every launch attempt");const p=f;return{pid:p,get completion(){return b({operation:"wait",pid:p}).then(i=>{if(!("result"in i))throw new Error("launcher did not return process completion");return i.result})},stop:u((i="SIGKILL")=>P(p,i,e.cron===void 0?e.nodeId:d),"stop")}}u(he,"launchAppProcess");export{pe as __setAppProcessesSandboxedForTest,z as appProcessCwd,le as appProcessSandboxed,me as appProcessesSandboxed,W as cronLaunchId,we as cwdIsMounted,he as launchAppProcess,P as stopAppProcess};
1
+ var N=Object.defineProperty;var u=(e,r)=>N(e,"name",{value:r,configurable:!0});import{existsSync as R}from"node:fs";import{assertGranteeRunsHere as O}from"../runtime/unsandboxed.js";import{randomUUID as k}from"node:crypto";import{join as h}from"node:path";import{getNode as S}from"../canvas/canvas.js";import{nodeAgentDir as H,nodeHome as K,nodeRunDir as B}from"../canvas/paths.js";import{appSpace as F}from"../layout.js";import{activeGrant as g,activeGrantForApp as y,grantFor as I,grantsGeneration as G}from"../grants/mirror.js";import{ownsWithoutRow as b}from"../grants/owner.js";import{emitEvent as A}from"../events/emit.js";import{ensureAppSpace as M}from"./space.js";import{compileLaunch as D,launchStillGranted as j}from"./mounts.js";import{pinSandboxRuntimeHome as q}from"./runtime-home.js";import{sandboxCacheEnv as U}from"./cache-env.js";import{launcherRequest as E}from"../../launcher/client.js";import{LAUNCHER_SOCKET as L}from"../../launcher/spec.js";import{isCloudRole as W}from"../canvas/person.js";import{launchSub as x}from"../runs/node-sub.js";function z(e){return`cron-${e}`}u(z,"cronLaunchId");function we(){if(process.platform!=="linux")return!1;if(R(L))return!0;throw new Error("root launcher socket is unavailable; refusing an unsandboxed app process")}u(we,"appProcessSandboxed");function pe(){return P??(process.platform==="linux"&&R(L))}u(pe,"appProcessesSandboxed");let P;function he(e){P=e}u(he,"__setAppProcessesSandboxedForTest");async function ge(e,r,n,o=!1,i,d){const a=n===void 0?null:await S(n),s=d!==void 0?d.grantId?await g(d.grantId):await I(e,d.sub):a?null:await y(e);if(d!==void 0?!s&&!b(e,d.sub,d.grantId):!a&&!s)throw new Error(`no active grant for ${e}`);return(await D({nodeId:n??"proc-cwd-check",app:e,...d!==void 0?{sub:d.sub,grantId:s?.id??null,scopes:d.scopes}:{sub:a?x(a.sub,a.node_id):s.sub,grantId:a?a.grant_id??null:s.id,scopes:a?.scopes??null},command:["true"],env:{},...n===void 0?{withoutNode:!0}:{},...i===void 0?{}:{folder:i},isolated:a?.isolated===!0||o,auditMissing:u(()=>{},"auditMissing")})).mounts.some(({source:c})=>r===c||r.startsWith(c==="/"?"/":`${c}/`))}u(ge,"cwdIsMounted");async function C(e,r="SIGKILL",n){if(!("ok"in await E({operation:"stop",pid:e,signal:r,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}u(C,"stopAppProcess");function J(e,r,n,o,i){return o?i??H(e,r):n}u(J,"appProcessCwd");async function Ie(e){if(W())throw new Error("a cloud role launches no app process; the node runs in its sandbox");if(e.cron!==void 0&&(e.nodeId!==void 0||e.principal===void 0))throw new Error("a cron launch has a stored principal and no node");const r=e.nodeId===void 0?null:await S(e.nodeId);if(e.nodeId!==void 0&&!r)throw new Error(`missing node ${e.nodeId}`);const n=r?.grantee??e.app??"app:terminal";if(O(n),e.app!==void 0&&e.app!==n)throw new Error("app does not match node");const o=e.principal;let i=null;if(o!==void 0){if(i=o.grantId?await g(o.grantId):await I(n,o.sub),i?i.grantee!==n||i.sub!==o.sub:!b(n,o.sub,o.grantId))throw new Error(`no active grant for ${n}`)}else if(r){const t=x(r.sub,r.node_id);if(n!=="app:terminal"&&!b(n,t,r.grant_id)&&!(r.grant_id?await g(r.grant_id):await I(n,t)))throw new Error(`no active grant for ${n}`)}else if(i=await y(n),!i)throw new Error(`no active grant for ${n}`);await M(n);const d=e.cron===void 0?e.nodeId??`proc-${k()}`:z(e.cron.executionId),a=r?.isolated===!0||e.isolated===!0;if(a&&!r&&e.folder===void 0)throw new Error("isolated process requires a live node");const s=F(n),m=J(d,n,e.cwd,a,e.folder),c=r?K(d,n,a):a&&e.folder!==void 0?h(e.folder,"home"):s.home,T=q(Object.fromEntries(Object.entries({...e.env,...process.platform==="linux"?U(n):{},HOME:c,PI_CODING_AGENT_DIR:h(c,".pi","agent"),PWD:m,...e.nodeId===void 0&&e.cron===void 0?{}:{CRTR_API_SOCKET:h(B(d),"cli.sock")}}).filter(t=>t[1]!==void 0))),v=o!==void 0?{nodeId:d,app:n,sub:o.sub,grantId:i?.id??null,scopes:o.scopes}:{nodeId:d,app:n,sub:r?x(r.sub,r.node_id):i.sub,grantId:r?r.grant_id??null:i.id,scopes:r?.scopes??null},$=u(async()=>{const t=await D({...v,command:e.command,env:T,...e.nodeId===void 0?{withoutNode:!0}:{},isolated:a,cwd:m,...e.folder===void 0?{}:{folder:e.folder},...e.cron===void 0?{}:{cron:e.cron.anchorDir===void 0?{}:{anchorDir:e.cron.anchorDir}},...e.pluginRoot===void 0?{}:{pluginRoot:e.pluginRoot},auditMissing:u(p=>A({level:"warn",event:"process.mount.missing",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{source:p}}),"auditMissing")});if(e.pluginRoot!==void 0&&(t.pluginRoot=e.pluginRoot),e.capture===!1){if(e.nodeId===void 0||e.stdin!==void 0)throw new Error("uncaptured process requires a node and no stdin")}else t.capture={stdoutBytes:e.stdoutBytes??256*1024,stderrBytes:e.stderrBytes??256*1024,...e.stderrTail?{stderrTail:!0}:{},...e.stdin===void 0?{}:{stdin:e.stdin}};return t},"compile");let f;for(let t=0;t<2&&f===void 0;t++){const p=await G(),_=await $(),l=await E({operation:"launch",spec:_});if(!("pid"in l))throw new Error("launcher did not return a process id");if(await G()===p||await j(v,_)){f=l.pid;break}A({level:"info",event:"process.launch.regranted",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{pid:l.pid}}),await C(l.pid,"SIGKILL").catch(()=>{})}if(f===void 0)throw new Error("grant changed during every launch attempt");const w=f;return{pid:w,get completion(){return E({operation:"wait",pid:w}).then(t=>{if(!("result"in t))throw new Error("launcher did not return process completion");return t.result})},stop:u((t="SIGKILL")=>C(w,t,e.cron===void 0?e.nodeId:d),"stop")}}u(Ie,"launchAppProcess");export{he as __setAppProcessesSandboxedForTest,J as appProcessCwd,we as appProcessSandboxed,pe as appProcessesSandboxed,z as cronLaunchId,ge as cwdIsMounted,Ie as launchAppProcess,C as stopAppProcess};
@@ -1,24 +1,24 @@
1
- var Z=Object.defineProperty;var i=(e,n)=>Z(e,"name",{value:n,configurable:!0});import{AsyncResource as ee}from"node:async_hooks";import{randomUUID as te}from"node:crypto";import{createServer as ne}from"node:http";import{Router as V,causedByOf as re}from"./router.js";import{toErrorBody as ae}from"./map.js";import{objectRoutes as oe}from"./handlers/objects.js";import{customObjectRoutes as ie}from"./handlers/custom-objects.js";import{checkRoutes as se}from"./handlers/check.js";import{chargeRoutes as ue}from"./handlers/charges.js";import{docRoutes as de}from"./handlers/docs.js";import{relationRoutes as ce}from"./handlers/relations.js";import{schemaRoutes as le}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as fe}from"../readiness.js";import{errorCodes as z}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as pe,RUNTIME_VERSION_HEADER as he,minimumRuntimeRefusal as we}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ye,CONTRACT_LEVEL as G,REQUIRED_CONTRACT_HEADER as _e,contractRefusal as ge}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ve,parseTraceparent as Re}from"../../shared/traceparent.js";import{AppPrincipalResolver as Oe}from"./principal.js";import{isDaemonRoute as be,runtimeOwner as Ee,servePeer as Y}from"../peer/ingress.js";import{applySyncNotice as Ae}from"./sync-notice.js";import{ownMachineId as Se}from"../../core/peer/directory.js";import{handleRunOperation as Te,integer as Ne}from"./handlers/runs.js";import{runAnthropicMessages as Ce}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Ie,parseLlmRequest as Pe,runLlm as ke}from"../../core/llm/run.js";import{parseUsageMonth as Me,usageFor as He}from"../../core/ledger/index.js";import{capFields as De}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as F,MODEL_CONTEXT_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{RunError as l,cloudPersonScope as Be,runIsRunning as xe}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as je}from"./deferred-head.js";import{readRunEvents as W,registerGrantStream as Je,subscribeRunEvents as Le}from"../../core/runs/events.js";import{activeGrant as q,payerOfGrant as Ue}from"../../core/grants/mirror.js";async function Xe(e){if(await Ue(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Xe,"appPaidGone");import{releaseGrantWaiters as $e}from"../../core/grants/watch.js";import{emitEvent as Ve}from"../../core/events/emit.js";import{runNotices as ze}from"../run-notices.js";import{handleRuntimeSignIn as Ge,isRuntimeSignInPath as Ye}from"./key-signin.js";import{listAppProfiles as Fe}from"./handlers/app-profiles.js";import{handleTransferOperation as Qe,TRANSFER_OPERATIONS as We}from"./handlers/transfer.js";import{handleQuestionOperation as qe,QUESTION_OPERATIONS as Ke}from"./handlers/questions.js";import{removeVendorAccount as Ze,vendorStatus as et}from"./handlers/vendor-status.js";import{handleMemoryOperation as tt,MEMORY_OPERATIONS as nt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as rt,handleExec as at}from"./handlers/exec.js";import{abortOnClose as U,callerFromApp as ot,handleProviderOperation as it,PROVIDER_OPERATIONS as st,providerFailure as ut}from"./handlers/providers.js";function dt(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(dt,"fixedRow");function ct(e){const n=dt(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(ct,"errorType");function lt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(lt,"appDetails");function x(e,n,o){const m=lt(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:ct(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"}:{},...De(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,m,d){const y=n instanceof l?n:new l(500,"server_failure","runtime request failed");if(n instanceof l||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
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 X(e){return Array.isArray(e)?e[0]:e}i(X,"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 K(e,n=F){const o=[];let m=0;for await(const d of e){if(m+=d.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(K,"rawBodyOf");async function I(e,n=F){const o=await K(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ft(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return Ne(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ft,"cursor");function pt(e){return`id: ${e.sequence_number}
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(pt,"frame");const ht=6e4;async function wt(e,n,o,m,d,y,S,O={},r){await L(m,o);let t=await W(o,d);if(d>t.latest_sequence)throw new l(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 l(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
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 ze().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(f=>{b=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),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(f=>{v||n.write(S==="sse"?`event: error
11
- data: ${JSON.stringify(x(f,y,o))}
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(f,y,o)})}
14
- `),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await W(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(S==="sse"?pt(f):`${JSON.stringify(f)}
15
- `),p=f.sequence_number}}catch(f){H(f instanceof l?f:new l(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new l(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await q(m.grant)!==null,"grantActive"),C=await Le(o,ee.bind(E)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
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??ht,w=O.isRunning??xe;let c=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==A){c=f,A=p;return}f-c<s||N||(n.write(`event: idle
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(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(wt,"streamRunEvents");function yt(e,n,o,m={}){const d=new V,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 V().registerAll(oe).registerAll(ie).registerAll(de).registerAll(le).registerAll(ce).registerAll(se).registerAll(ue);return i((r,t,p)=>(async()=>{je(r,t,m.deferHead);const _=te();t.setHeader("Request-Id",_);const v=Re(X(r.headers.traceparent))??ve();t.setHeader(he,J()),t.setHeader(ye,G);let T;try{const N=X(r.headers[pe.toLowerCase()]),b=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new l(400,b.code,b.message,b.param):new l(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(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:Ee,self:Se,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,E);return}if(E===void 0&&a===void 0&&await be(r.method??"GET",h.pathname)){await Y(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 fe({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 l(503,"runtime_starting","runtime_starting");if(!R||!a)throw new l(404,"not_found","unknown operation");T=R.params.run_id;const C=re(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Ae(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 et());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await Ze(await I(r)));return}if(E===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await L(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 l(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 c;try{c=await s.handler(w)}catch(A){const{status:k,body:M}=ae(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream){await wt(r,t,T,u,ft(r,h.searchParams),_,"sse",m.stream,v);return}if(a.name==="llm"){const s=Pe(await I(r,Q)),w=new AbortController,c=i(()=>w.abort(),"abort");t.on("close",c);try{const A=await ke(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)}
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:_},Ie(await q(u.grant)??await Xe(u.grant)),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]
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",c)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=U(t);try{await Ce(await K(r,Q),r.headers,s,{grant:u.grant,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}=U(t);try{g(t,200,await at(u,await I(r,rt),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await He(u.grantee,Me(h.searchParams.get("month")),Be(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Fe(u));return}if(Ke.has(a.name)){const s=await qe(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(st.has(a.name)){const{signal:s,release:w}=U(t);try{const c=await it(a.name,ot(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,c.status,c.body)}catch(c){const A=ut(c,_,!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(nt.has(a.name)){const s=await tt(a.name,{class:"app",app:u.grantee,sub:u.sub,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(We.has(a.name)){const s=await Qe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Te(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(yt,"createAppRequestHandler");async function ln(e,n,o,m={}){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 Oe(e.issuer,e.audience,o,e.jwksUrl),S=yt(y,n,o,m),O=ne((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(),$e(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(ln,"createAppListener");export{ht as RUN_STREAM_IDLE_MS,ln as createAppListener,yt as createAppRequestHandler,ft as cursor,wt as streamRunEvents};
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 _=Object.defineProperty;var d=(o,t)=>_(o,"name",{value:t,configurable:!0});import{ApiError as n}from"../../../api/errors.js";import{openDb as f}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 p(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}d(p,"requiredEnv");async function E(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??"",r=await w(t.node);if(r===null)throw new n(404,"node_not_found",`no node ${t.node}`);if(await m(r.profile_id??null)!==l)throw new n(403,"not_your_environment",`this node does not run in environment ${l}`);const s=[],e=v(o.body,["host","path"],s),i=k(e,"host",s);if(y(e,"path",s),s.length>0&&b("git credential request",s),i!=="github.com")throw new n(400,"unsupported_git_host",`only github.com credentials are issued, not ${i}`);const a=(await g(l))?.repositories.map(h=>h.github_full_name)??[];if(a.length===0)throw new n(409,"no_recipe_repositories",`environment ${l} has no recipe repositories`);const u=await(await f()).prepare("SELECT allow_pull_request_write FROM environments WHERE object = ?").get(l),c=await x(t.sub,a,u?.allow_pull_request_write===!0);return{status:200,body:{username:"x-access-token",password:c.token,expiry:c.expires_at}}}d(E,"handleGitCredential");async function x(o,t,l=!1){const r=await fetch(`${p("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/installation-token`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${p("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({sub:o,repositories:t,allow_pull_request_write:l})}),s=await r.text(),e=s===""?{}:JSON.parse(s);if(!r.ok){const a=typeof e.error=="object"?e.error?.code:e.code,u=(typeof e.error=="object"?e.error?.message:e.message)??`the GitHub service answered ${r.status}`;throw r.status===409&&(a==="repositories_span_installations"||a==="github_not_connected")?new n(409,a,u,{repositories:t}):new n(502,"github_service_failed",u,{status:r.status,...a===void 0?{}:{code:a}})}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 i=e.author;if(i===void 0)throw new n(502,"github_service_failed","the GitHub service answered without an author field");if(i!==null&&(typeof i.name!="string"||typeof i.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:i===null?null:{name:i.name,email:i.email}}}d(x,"mintInstallationToken");const C=[{method:"POST",pattern:"/v1/environments/:environment_id/git-credential",handler:E}];export{C as gitCredentialRoutes,x as mintInstallationToken,p as requiredEnv};
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 S=Object.defineProperty;var c=(a,t)=>S(a,"name",{value:t,configurable:!0});import{callerGrant as g}from"../principal.js";import{grantVersion as b,payerOfGrant as O}from"../../../core/grants/mirror.js";import{holdGrant as $}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as v,cancelRun as N,cloudPersonScope as A,deleteRun as j,interruptRun as x,listRuns as B,messageRun as J,renameRun as z,requestedScopes as D,startRun as E,traceRun as G,waitRun as K}from"../../../core/runs/operations.js";import{canReadRun as y,requireRun as w,runCallerApp as M}from"../router.js";import{waitSeconds as q}from"../long-poll-wait.js";import{outputSchemaProblem as P}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 k(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(k,"integer");const T=256*1024;async function Y(a,t,i,u,l,_,h){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=q("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?$(t.grant):void 0;let o;try{if(o=await g(t),d){const f=Date.now()+e*1e3;for(;b(o)===s&&Date.now()<f;)await d.changed(Math.max(0,(f-Date.now())/1e3)),o=await g(t)}}finally{d?.release()}return{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:t.grant,rev:o.rev,resolved_scopes:o.resolved_scopes,spend_cap:o.spend_cap,exp:t.exp,payer:await O(t.grant),dependencies:o.dependencies??{},version:b(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))>T)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");const p=await P(r);if(p!==null)throw new n(400,"invalid_request",`output_schema is not usable: ${p}`,"output_schema");f=r}const R=D(t.resolved,e.scopes,t.grantee);return{status:201,body:await E(t,{prompt:e.prompt,scopes:R,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},...h===void 0?{}:{causedBy:h}},v(_))}}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?M(t):s.startsWith("app:")?s:`app:${s}`;if(d!==null&&!await y(t,d))throw new n(404,"not_found","run not found");const o=A("sub"in t?t.sub:void 0);return{status:200,body:await B(d,{status:e,...o===void 0?{}:{sub:o},after:u.get("after")??void 0,limit:k(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&d!==null?{visible:c(async f=>await y(t,d,f),"visible")}:{}})}}case"run.get":{const e=q("run.get",u),s=await w(t,i),d=await K(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 J(await w(t,i,!0),e.message,void 0,e.start_turn,v(_),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 x(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 N(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 z(await w(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await j(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 G(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}c(Y,"handleRunOperation");export{Y as handleRunOperation,k as integer};
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: string;
10
- rev: number;
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 app token names. Grantee, grant and rev come from the token's app link
62
- * (`chain[0]`, which must be the whole chain); the mirror is made to cover the link's `rev` and the grant
63
- * is read now (`coverGrant`). A token whose presenter is not an app link holding a grant is refused 401. */
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 v=Object.defineProperty;var o=(a,e)=>v(a,"name",{value:e,configurable:!0});import{covers as m,JwksCache as p,MissingRevClaimError as _,verifyCallToken as b}from"@north-light/identity";import{createLocalJWKSet as l,decodeProtectedHeader as h,jwtVerify as f}from"jose";import{callerGrantOf as k,coverGrant as x}from"../../core/grants/cover.js";import{RunError as n}from"../../core/runs/operations.js";import{NoticeLedger as E}from"./sync-notice.js";function C(a){return new n(401,"unauthorized",a==="vendor_sign_in"?"invalid vendor sign-in handoff":"invalid key handoff")}o(C,"unauthorizedHandoff");class q{static{o(this,"AppPrincipalResolver")}issuer;audience;syncGrants;cache;ready=!1;timer;constructor(e,t,r,i){this.issuer=e,this.audience=t,this.syncGrants=r,this.cache=new p(e,fetch,i),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 E;async verifySyncNotice(e){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");return this.ledger.accept(e,this.cache,this.issuer,this.audience)}async verifyHandoff(e,t){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");const r=o(()=>C(t),"refuse");if(!e)throw r();let i;try{const u=h(e);if(u.alg!=="ES256")throw r();const g=await this.cache.forKid(u.kid);({payload:i}=await f(e,l(g),{issuer:this.issuer,audience:this.audience,algorithms:["ES256"],requiredClaims:["exp","jti","sub"]}))}catch{throw r()}const{sub:s,jti:c,exp:d,purpose:w,aud:y}=i;if(w!==t||y!==this.audience||typeof s!="string"||typeof c!="string"||c===""||typeof d!="number")throw r();return{sub:s,jti:c,exp:d}}async verifyDirectoryRead(e,t){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");const r=o(()=>new n(401,"unauthorized","invalid directory token"),"refuse");if(!e?.startsWith("Bearer ")||e.length<=7)throw r();const i=e.slice(7);let s;try{const c=h(i);if(c.alg!=="ES256")throw r();const d=await this.cache.forKid(c.kid);({payload:s}=await f(i,l(d),{issuer:this.issuer,audience:this.audience,algorithms:["ES256"],requiredClaims:["exp"]}))}catch{throw r()}if(s.purpose!==t||s.aud!==this.audience)throw r()}async verifyCall(e){if(!this.ready)throw new n(503,"runtime_starting","runtime_starting");if(!e?.startsWith("Bearer ")||e.length<=7)throw new n(401,"unauthorized","a directory access token is required");const t=e.slice(7);try{if(h(t).alg!=="ES256")throw new Error("Invalid call token header");return await b({token:t,jwks:this.cache,issuer:this.issuer,audience:this.audience})}catch(r){throw r instanceof _?new n(401,"unauthorized",r.message):new n(401,"unauthorized","invalid directory access token")}}async resolve(e,t){return this.resolveVerified(await this.verifyCall(e),t)}async resolveVerified(e,t){const r=e.chain[0],i=e.claims;if(e.chain.length!==1||!r||!r.sub.startsWith("app:")||r.grant===void 0||r.rev===void 0||!/^[A-Za-z0-9_-]{1,64}$/.test(i.client_id)||i.grantee!==void 0&&i.grantee!==r.sub||i.rev!==void 0&&i.rev!==r.rev)throw new n(401,"unauthorized","invalid directory access token");const s=await x(r.grant,r.rev,e.sub,r.sub,this.syncGrants);if(t&&!s.resolved.some(c=>m(c,t)))throw new n(403,"scope_missing",`missing scope ${t}`,void 0,void 0,t);return{sub:e.sub,grantee:r.sub,client_id:i.client_id,grant:r.grant,rev:s.rev,resolved:s.resolved,resolved_scopes:s.resolved_scopes,spend_cap:s.spend_cap,dependencies:s.dependencies??{},exp:i.exp}}}async function H(a){return await k(a.grant,a.sub,a.grantee)}o(H,"callerGrant");export{q as AppPrincipalResolver,H as callerGrant,C as unauthorizedHandoff};
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
- - Rebase-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
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.749",
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.749",
162
- "@north-light/plugin": "0.3.749",
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 = 36;
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: 'user', dependencies: {}, synced_at: now }], now, 'local');
25
+ status: 'active', revoked_at: null, approved_at: now, payer: person, dependencies: {}, synced_at: now }], now, 'local');
26
26
  }